How to do a selection sort?
Which I want to sort in descending order this data
1 50
2 90
3 40
agreed with niek_e he has given you the good resource for selection sort.
let me discuss what I know about selection sort.
selection sort is simple it just select the element and put the selected element in correct position.
in your case the data is 50, 90, 40.
if you want to sort in descending order.
i) loop on i through the array from 2nd element to end ( make sure your array size is greater than 1).
ii) pick the ith element in key (i.e. 90 in this case its the selected element).
iii) loop on j from (i-1)st element down to zero.
iv) check if key > jth element.
v) yes ! then move jth element to j+1st position. (i.e. making room for 90 in your case).
vi) no! break.
vii). set the key at (j+1)st position.
lets run on your data.
Pass 1.
key = 90.
we start looping on j=1.
checking 90 > 50
yes! moving 50 to 2nd position
j=0, breaks the above loop.
setting key at 1st position.
now array = 90, 50, 40
Pass 2.
key = 40.
we start looping on j = 2.
check 40 > 50.
no ! break.
setting key at 3rd position. (which already was 40).
Pass three, the parent loop breaks. as i == size of array.
so the sorted array is 90, 50, 40.
Hope this helps.
check whether its stable sort or not ?. what about inplace ?
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.