27 Aug Selection Sort in C
Let us see how to implement Selection Sort in C Language.
What is Selection Sort?
The selection sort is a sorting method that yields a sorted array. It does so by repeatedly finding the smallest element in the array and interchanging it with the element at the starting of the unsorted part.
Given example explains the steps required in Selection Sort.
The array before sorting starts is:
1 2 3 |
3 9 5 1 2 |
Now, the smallest element in this array is 1 which is at position 3. This element is interchanged with 3 at position 0. So the array obtained is:
1 2 3 |
1 9 5 3 2 |
After the above step, first element of the array is sorted. Out of the remaining 4 elements, the smallest element is 2, at position 4. This is exchanged with 9 which is at position 1. The array obtained is:
1 2 3 |
1 2 5 3 9 |
The first 2 elements of the array are sorted. Out of the remaining elements, smallest is 3 at position 3. This is replaced with 5 at position 2. The array obtained is:
1 2 3 |
1 2 3 5 9 |
Finally the sorted array is obtained. This is given as:
1 2 3 |
1 2 3 5 9 |
Source Code
The source code for Selection Sort is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
#include < stdio.h > void selectionSort(int arr[], int n) { int i, j, minpos, temp; for (i = 0; i < n - 1; i++) { minpos = i; for (j = i + 1; j < n; j++) if (arr[j] < arr[minpos]) minpos = j; temp = arr[i]; arr[i] = arr[minpos]; arr[minpos] = temp; } } int main() { int arr[] = { 3, 9, 1, 5, 2 }; int n = 5, i; printf("Given array is: \n"); for (i = 0; i < n; i++) printf("%d ", arr[i]); printf("\n"); selectionSort(arr, n); printf("\nSorted array is: \n"); for (i = 0; i < n; i++) printf("%d ", arr[i]); return 0; } |
Output
The output obtained for the above code is:
No Comments