What is selection sort?How does it work?
Selection sort is an intuitive sort algorithm. The idea is that At first time,we select the smallest data element(or the biggest one),then put it in the starting position.Then we select the smallest one in the rest of unsorted elements,then put it behind the ordered sequence of elements. And so on,until the number of the unsorted element equals zero.Selection sort is an unstable sort method.
We can select out the proper one in each round.Now we have the following sequence:
6,5,6,2,7
There are six elements totally waiting to sort.
Round 1:We need to find out the smallest elements in [6,5,6,2,7],then we get the smallest one 2.we exchange the element of the first position with 2.Then we get the sequence:
2,[5,6,6,7]
Round 2:We select out the smallest one in the rest elements [5,6,6,7],and we get 5.Now the State of the sequence is that:
2,5,[6,6,7]
Round 3:We select out the smallest one in the rest elements [6,6,7],and we get 6.Now the sequence is that:
2,5,6,[6,7]
Round 4:We select out the smallest one int the rest elements [6,7],and we get 6,Now the sequence is that:
2,5,6,6,[7]
In round 4,we finished the sorting.Because the rest just has only one.That is no need to sort any more.
As you can see,the element 6,their Relative fore and aft position has exchanged.That is why selection sort is unstable.Stable sorting means that the relative position of the same elements will never change. n elements need to do n-1 rounds sorting in n elements.