Selection Sort Algorithm
Line by Line Selection Sort Algorithm Explained in C++
The Selection sort algorithm is based on the idea of finding the minimum or maximum element in an unsorted array and then putting it in its correct position in a sorted array.
Assume that the array A=[7,5,4,2] needs to be sorted in ascending order.
The minimum element in the array i.e. 2 is searched for and then swapped with the element that is currently located at the first position, i.e. 7. Now the minimum element in the remaining unsorted array is searched for and put in the second position, and so on.
Line 21 :- Here is main function starts while program execute Then declaring an array named as myarr of size “5" . Then we are asking user to enter elements of array using for loop and printed using for loop , our loop which is unsorted , because we don’t performed sorting till now .
Line 35 :- Here we are calling the sorting function
Line 4 :- Starting our loop from 0th index and making it till before the last , we are taking 1 less the size of array because the algorithm for this sort puts sorted elements one by one , so last element will sort automatically when previous elements get sorted .
Line 6 :- we are considering minimum element as ith element , because suppose at first iteration the minimum element will be first element then only you can compare with all further elements .
Line 8 :- To compare with all further elements after ith element , we are taking j loop . starting from i+1 elements and goes till the end of array .
Line 9 :- Now we are checking wether the jth element is less then the min element or not . if it is then assign min value as jth element .
Line 13 :- Here we are checking weather the min elements remains the same or change , cause if previous if condition got true then min value will change and if got false then will not change , and we want swapping only when if the previous if condition got true , so in this condition we are swapping the elements .