So let's go ahead and look some pseudo-code for Selection Sort.
selectionSort(array x){
for i <-- x.length-1 to 0, i <-- i-1
max <-- i
for j <-- 0 to i-1, j <-- j+1
if(x[j] > x[max])
max <-- j
end if
end for
swap(x[max], x[i])
end for
}
Some things we see here are nested for loops, the first linear on the array, and the inner loop linear on the outer loop. So when we some k from 1 to n-1 for (n-k), we get an O(n^2). In addition, in this pseudo-code, we are placing the largest elements at the end for an ascending order sort. Consider how we would place the array in descending order. It would be as easy as placing the smallest elements at the end instead of the largest.







MultiQuote


|