The basic idea of selection sort :
select the smallest (or largest) number from the sequence to be sorted, exchange it with the number in the first position, and then select the smallest (or largest) number from the remaining sequence to be sorted, and the second Swap the number of positions until the n-1th (second to last) element is compared with the nth (last) element
Operation method:
9 5 6 2 1 8 --------------------- First trip: 1 5 6 2 9 8 Second trip: 1 2 6 5 9 8 Third trip: 1 2 5 6 9 8 Fourth trip 1 2 5 6 9 8 fifth trip 1 2 5 6 8 9
Time complexity:
The first comparison is n-1 times, the second comparison is n-2 times... The last comparison is 1 time, the arithmetic sequence summation n^2/2
rounds off the highest term coefficient, O(n^2)
Stability:
The relative position changes of the same elements are all unstable sorting: as follows
5(first), 8, 5(second), 1 Selection sort: 1 8 5 (second) 5 (first)
python code example: select_sort.py
def select_min_key(l, i): key = i for j in range(i+1, len(l)): if l[key] > l[j]: key = j return key def select_sort(l): for i in range(0, len(l)): key = select_min_key(l, i) if l[i] != l[key]: tmp = l[i] l[i] = l[key] l[key] = tmp if __name__ == '__main__': l = [72,32,16,52,49,84,17,9,7,29] select_sort(l) print('result:'+str(l))
Lua code example: select_sort.lua
function selectMinKey(t, i) key = i len = table.getn(t) for j = i + 1, len do if t[key] > t[j] then key = j end end return key end function select_sort(t) len = table.getn(t) for i = 1, len do key = selectMinKey(t, i) if t[i] ~= t[key] then tmp = t[i] t[i] = t[key] t[key] = tmp end end end t = {71,26,53,52,47,9,58,49,2,77} select_sort(t) for _,v in ipairs(t) do print(v) end