i. Selection sorting algorithm is an in-place comparison based algorithm in which the list is divided into two sub parts, the sorted part at the left end and the unsorted part at the right end.
ii. Initially, the sorted part is empty and the unsorted part is the entire list.
iii. The smallest element is selected from the unsorted array and swapped with the leftmost element, and that element becomes a part of the sorted array. This process continues moving unsorted array boundary by one element to the right.
This algorithm is not suitable for large data sets as its average and worst case complexities are of Ο (n2), where n is the number of items.
Consider the following array as an example.
19 24 17 42 25 47 28 44
Step 1: For finding the first position in the list, the whole list is scanned sequentially. After scanning the entire list we find that 17 is the lowest value and it is swapped with the first position value 19.
17 24 19 42 25 47 28 44
Step 2: For the second position, where 24 is residing, we start scanning the unsorted list in a linear manner. 19 is the lower most value present in the unsorted list and we will swap with 24.
17 19 24 42 25 47 28 44
Step 3: For the third position, where 24 is residing. 24 is the lower most value present in the unsorted list and there is no need to swap.
17 19 24 42 25 47 28 44
Step 4: For the fourth position, where 42 is residing. 24 is the lower most value present in the unsorted list and there is swap operation will be performed.
17 19 24 25 42 47 28 44
Step 5: by continuing these methods we can get a sorted list of values.
17 19 24 25 28 42 44 47
The above array is the final answer of the example.
Step 1 − Set MIN to location 0
Step 2 − Search the minimum element in the list
Step 3 − Swap with value at location MIN
Step 4 − Increment MIN to point to next element
Step 5 − Repeat until list is sorted
To find the minimum element from the array of N elements, N−1 comparisons are required. After putting the minimum element in its proper position, the size of an unsorted array reduces to N−1 and then N−2comparisons are required to find the minimum in the unsorted array.
Therefore (N−1) + (N−2) + ....... + 1 = (N⋅(N−1))/2 comparisons and N swaps result in the overall complexity of O(N2).
Selection sort algorithm is easy to use but, there are other sorting algorithm which perform better than selection sort. Specially, selection sort shouldn't be used to sort large number of elements if the performance matters in that program.
Program in C:
printf("Enter the number of elements to be sorted: ");
printf("%d. Enter element: ",i+1);
/* To sort in descending order, change > to <. */
printf("In ascending order: ");
Enter the number of elements to be sorted: 5
1. Enter element: 12
2. Enter element: 1
3. Enter element: 23
4. Enter element: 2
5. Enter element: 0
In ascending order: 0 1 2 12 23