Page 303 - Cs_withBlue_J_C11_Flipbook
P. 303
Let us take the following example.
The array is to be sorted in ascending order:
Index 0 1 2 3 4
Ar 27 16 12 10 21
Step 1: Find the smallest element.
Index 0 1 2 3 4
Ar 27 16 12 10 21
The smallest element is in position ar[3]: 10. Interchange this number with the first element.
After swapping ar[0] and ar[3], the array becomes:
Index 0 1 2 3 4
Ar 10 16 12 27 21
After the first step, the smallest element is stored in the first position of the array.
Step 2: Find the next smallest number.
Index 0 1 2 3 4
Ar 10 16 12 27 21
The second smallest element is in position ar[2]: 12. Interchange this number with the second element.
After swapping ar[1] and ar[2], the array becomes:
Index 0 1 2 3 4
Ar 10 12 16 27 21
After the second step, the second smallest element is stored in the second position of the array.
Step 3: Find the next smallest number.
Index 0 1 2 3 4
Ar 10 12 16 27 21
The third smallest element is in position ar[2]: 16. Interchange this number with the third element.
After the third step, the third smallest element is already stored in the third position of the array.
Step 4: Find the next smallest number.
Index 0 1 2 3 4
Ar 10 12 16 27 21
The fourth smallest element is in position ar[4]: 21. Interchange this number with the fourth element.
After swapping ar[3] and ar[4], the array becomes:
Index 0 1 2 3 4
Ar 16 12 16 21 27
After the fourth step, the array has been sorted in ascending order.
We can clearly see that the selection sort technique performs a smaller number of swaps as compared to the bubble
sort technique. Thus, it performs faster and more efficiently than the bubble sort.
301
Arrays 301

