Updated April 10, 2023
For such kinds of Sorting techniques, we have Algorithms or a Flowchart.
Algorithm for Selection sort:
Step 1: Consider an array of elements, out of which we set the first element as a minimum.
Step 2: Compare the minimum value with the second. And if the second element is less than the minimum element, the second element is assigned as a minimum element.
Step 3: So Step 2 gets repeated by comparing the minimum element with the third element. If the third element in less than the minimum element, the third element will be assigned as the minimum element else nothing. And the likewise process will repeat till the last element.
Step 4: After each change, the minimum element is placed at the start of the unsorted element.
Step 5: For each iteration, the index starts with 0 i.e. first unsorted element. So all the above steps are repeated until the elements are placed at their correct positions i.e. in Ascending order.
How does Selection Sort work?
We shall see How Selection Sort works with few examples,
It is a comparison-based algorithm, which divides into two parts. One is the sorted part and the other being the unsorted part. Initially, sorted part is empty. The first element from the unsorted part is compared and swapped with the before element which actually adds to the sorted list, and the process goes on.
So here we see the input array and the sorted array, which is sorted with the Selection sort Algorithm. Let us explain this in a simpler manner as to How this above input array has been sorted.
inputArr = [2, 7, 9, 1, 8];
1. As per the Algorithm, the minimum element will be 2 i.e. first element.
2. Compare ‘2’ with ‘7’. Since 2 < 7, no swapping
3. Compare ‘2’ with ‘9’, no swapping
4. Compare ‘2’ with ‘1’, which will be swapped. inputArr = [1, 7, 9, 2, 8]
5. Now, the index of minimum element changes to 1 i.e. 7.
6. So, as the left part is sorted part, 7 is now compared with 9. No swapping
7. ‘7’ is now compared with ‘2’, swaps. indexArr = [1, 2, 9, 7, 8].
8. Now, index of the minimum element changes to 2 i.e. 9.
9. Compare ‘9’ with ‘7’, swaps. indexArr = [1, 2, 7, 9, 8].
10. Index of minimum element changes to 3 i.e. 9.
11. Compare ‘9’ with ‘8’, swaps. indexArr = [1, 2, 7, 8, 9].
12. Array is sorted.
Selection Sort ( maintaining a copy of the array elements since objects are passed by reference)
So this is how we have used a different way of writing the logic for Selection sort and have got a sorted array.