Selection Sort

Selection Sort is a simple $$O(n^2)$$ algorithm using $$O(1)$$ memory. it works by repeatedly "selecting" the minimum element and putting it in its right position.

Selection sort is not adaptive, meaning it dosen't take less time on almost-sorted arrays than random ones. it is also unstable, meaning it does not preserve the relative order of equal elements. It can be made stable by inserting the element instead of swapping it with the item in the position.

=Explanation= First, the sort does a linear scan of the input to find the minimum. Then it swaps it with the beginning of the array. Now the sort does another linear scan to determine the second-smallest item, and swaps it with the second element, and so on until all elements are swapped out in order.

= Example = consider: 6 5 7 1 5 3 4 2

find the minimum: 1

swap it to the front.

1|5 7 6 3 4 2

find the minimum and swap.

1 2|7 6 3 4 5

find the minimum and swap.

1 2 3|6 7 4 5

find the minimum and swap.

1 2 3 4|5 7 6

find the minimum and swap.

1 2 3 4 5|7 6

find the minimum and swap.

1 2 3 4 5 6 7

Sorted!

=Pseudocode= procedure selection_sort(array arr) do for index = 0 to length(arr)-1 do int min = index; int i = index; for j = index to length(arr)-1 do if arr[min] > arr[j] min = j            end if end for swap arr[min] and arr[i] end for end

=Analysis= Each "find the minimum" operation takes $$n$$ time, and it is done $$n$$ times, but on decreasing amounts of elements. So, $$n + (n - 1) + (n - 2)... + 1 = O(n^2)$$.