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. It is one of the few algorithms that uses $$O(n)$$ element moves, making it useful for Block Merge Sorts and other complex algorithms.

=Algorithm= 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 = Selection Sort the list [7 8 4 1 5 2 6 3]. Select the minimum and swap: [1 8 4 7 5 2 6 3] └─────┘ Select and swap again: [1 2 4 7 5 8 6 3]   └───────┘ Continue: [1 2 3 7 5 8 6 4]     └─────────┘ [1 2 3 4 5 8 6 7]        └───────┘ 5 is already in it's position, so don't swap. [1 2 3 4 5 6 8 7]           └─┘ [1 2 3 4 5 6 7 8]              └─┘ =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

=Variants=

Bingo Sort
Bingo Sort is a variant of Selection Sort that swaps equal elements into their correct place. it does so by finding the minimum, and then scanning through the array again to swap any elements that are equal to it to the front. it is adaptive on few unique distributions, with a higher constant factor on distinct inputs.