Selection Sort
Code
python.py
java-script.js
type-script.ts
def selection_sort(arr):
# save array's length
N = len(arr)
for i in range(N - 1):
# assume first index item is the min
minIdx = i
for j in range(i + 1, N):
# check if next item is < current min
if arr[j] < arr[minIdx]:
# save new min index
minIdx = j
# check if there was a change of min index
if minIdx != i:
# swap first index item of outer loop with min index item
arr[i], arr[minIdx] = arr[minIdx], arr[i]
Pseudocode
pseudocode
selectionSort(array of numbers)
for i = 0 to i = length(array) - 2
minIdx = i
for j = i + 1 to j = length(array) - 1
if array[j] < array[minIdx]:
minIdx = j
if minIdx is not i
swap array[i] and array[minIdx]