selection sort
#include <stdio.h>
void selectionSort(int arr[], int n) {
int i, j, minIndex, temp;
for (i = 0; i < n-1; i++) {
minIndex = i;
for (j = i+1; j < n; j++) {
if (arr[j] < arr[minIndex])
minIndex = j;
}
temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: \n");
for (int i=0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
Explanation:
The selection sort algorithm works by repeatedly finding the minimum element from the unsorted portion of the array and placing it at the beginning. This process is repeated until the entire array is sorted.
The selectionSort
function takes an array arr
and its size n
as input. It uses two nested loops to iterate through the array. The outer loop selects the current minimum element, while the inner loop finds the minimum element from the remaining unsorted portion of the array.
In each iteration of the outer loop, the minIndex
variable is initially set to the current element index. The inner loop compares the current element with the elements following it. If a smaller element is found, the minIndex
is updated to the index of that element.
After finding the minimum element, it is swapped with the current element of the outer loop using a temporary variable temp
. This ensures that the minimum element is placed at the correct position in the sorted portion of the array.
The main
function demonstrates the usage of the selectionSort
function. It initializes an array arr
with some values, calculates its size n
, and calls selectionSort
to sort the array. Finally, it prints the sorted array using the printf
function.