Understanding selection sort

Selection sort is another comparison-based sorting algorithm, which looks similar to bubble sort. The biggest difference is that it takes fewer swapping than bubble sort. In selection sort, we first find the minimum/maximum item of the array and place it in the first place. If we are sorting in descending order, then we will take the maximum value from the array. For ascending order, we will take the minimum value. In the second iteration, we will find the second-most maximum or minimum value of the array and place it in second place. This goes on until we place each number into a correctly sorted position. This is known as selection sort. The pseudocode for selection sort looks like this:

procedure selectionSort( A : list of sortable items )
n = length(A)
for i = 1 to n inclusive do
min = i
for j = i+1 to n inclusive do
if A[j] < A[min] then
min = j
end if
end for

if min != i
swap(a[i],a[min])
end if

end for
end procedure

If we look at the preceding algorithm, we can see that, after iteration one in the outer loop, the first minimum item is stored in position one. During the first iteration, we selected the first item and then found the minimum value from the remaining items (from 2 to n). We assumed that the first item is the minimum value. If we find another minimum value, we would mark its position until we have scanned the remaining list and found a new minimum value. If no minimum value is found, then our assumption is correct, and that is indeed the minimum value. Here is a picture illustrating our 20, 45, 93, 67, 10, 97, 52, 88, 33, 92 arrays during the first two steps in selection sort:

As we can see in the preceding image, we started with the first item in the list, which is 20. Then, we found the minimum value from the rest of the array, which is 10. At the end of the first iteration, we just swapped the values from two places (marked by arrows). As a result, at the end of the first iteration, we have the minimum value from the array stored in the first place. Then, we pointed to the next item, which is 45, and started finding the next smallest items compared to 45 from the right side of its position. We found 20 from the remaining items (as shown by two arrows). At the end of the second iteration, we are just swapping the second position number to the newly found smallest one from the remainder of the list. This continues until the last element, and, at the end of the process, we have a sorted list of arrays. Let's now convert the pseudocode into a PHP code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset