SELECTION SORT
Selection sort is a simple comparison-based sorting algorithm that works by repeatedly finding the smallest (or largest) element from the unsorted portion of an array and placing it in its correct position. For each element at index i, the algorithm compares it with every element after it to determine the minimum, meaning the inner loop goes all the way to the end of the array—there is no n-1-i restriction. This makes selection sort predictable in the number of comparisons it performs, but it does not take advantage of partially sorted arrays. While easy to implement, selection sort is inefficient for large datasets and is rarely used in practical applications, though it is useful for teaching fundamental sorting concepts.
Selection sort and bubble sort are both elementary sorting algorithms, but they operate differently. In selection sort, for each position in the array, the algorithm searches through all remaining elements to find the smallest one and swaps it into place. This means the inner loop goes all the way to the end of the array—there’s no n-1-i limitation—because each position is directly compared with all elements after it. Bubble sort, on the other hand, repeatedly compares adjacent elements and swaps them if they are out of order, causing the largest elements to “bubble” to the end of the array. Because each pass guarantees that the largest unsorted element is at its correct position, the inner loop runs only up to n-1-i to avoid unnecessary comparisons with already sorted elements. In practice, both algorithms are inefficient for large datasets, but bubble sort can be slightly better with nearly sorted data due to its early-exit optimization, while selection sort performs a predictable number of comparisons. For real-world applications, however, more advanced algorithms like quick sort or merge sort are preferred.
#include <stdio.h>
int main(int argc, char *argv[])
{
int numbers[5] = {0};
int swapped = 0;
//populate the array with numbers
for(int i = 0; i < 5; i++){
printf("Enter value #%d: ", i + 1);
scanf("%d", &numbers[i]);
}
//perform bubble sort
for(int i = 0; i < 5; i++){
for(int j = i + 1; j < 5; j++){
if(numbers[i] > numbers[j]){
swapped++;
int temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
}
}
//display
printf("Sorted Array: ");
for(int i = 0; i < 5; i++){
printf("%d ", numbers[i]);
}
printf("\nNumber of swapped: %d", swapped);
return 0;
}Last updated