The selection sort enhances the bubble sort by making only a single swap for each pass through the rundown. Indorder to do this, a selection sort searches for the biggest value as it makes a pass and, after finishing the pass, places it in the best possible area. Similarly as with a bubble sort, after the first pass, the biggest item is in the right place. After the second pass, the following biggest is set up. This procedure proceeds and requires n-1 goes to sort n item, since the last item must be set up after the (n-1) st pass.
ALGORITHM: SELECTION SORT (A) 1. k ← length [A] 2. for j ←1 to n-1 3. smallest ← j 4. for I ← j + 1 to k 5. if A [i] < A [ smallest] 6. then smallest ← i 7. exchange (A [j], A [smallest])
In pass 1: n-1 comparisons are required In pass 2: n-2 comparisons are required In pass 3: n-3 comparisons are required ............................................................................ ............................................................................... In pass n-1: 1 comparison is required Total comparisons: T (n) = (n-1) + (n-2) + (n-3) +........+ 1 =
= o (n
2) Therefore complexity is of order n2
Sort the following array using selection sort: A [] = (7, 4, 3, 6, 5).
A [] =
74365
Swap 7 and 3
34765
No Swap
34765
Swap 7 and 5
34567
No Swap
34567
Finally, the sorted list is:
34567