defSelection_sort (alist): N=Len (alist)#requires a n-1 selection operation forIinchRange (n-1): #Record minimum positionMin_index =I#Select the minimum data from the i+1 position to the end forJinchRange (i+1, N):ifALIST[J] <Alist[min_index]: Min_index=J#If the selected data is not in the correct location, swap ifMin_index! =I:alist[i], Alist[min_index]=Alist[min_index], alist[i]alist= [54,226,93,17,77,31,44,55,20]selection_sort (alist)Print(alist)
- Optimal time complexity: O (n2)
- Worst time complexity: O (n2)
- Stability: Unstable (consider ascending each time to select the maximum case)
It works as follows. First find the smallest (large) element in the unordered sequence, place it at the beginning of the sort sequence, and then continue looking for the smallest (large) element from the remaining unsorted elements, and place it at the end of the sorted sequence. And so on until all elements are sorted.
The main advantages of selecting a sort are related to data movement. If an element is in the correct final position, it will not be moved. Select sort every time a pair of elements is exchanged, at least one of them will be moved to its final position, so the table of n elements is sorted for a total of up to n-1 times. In all of the sorting methods that rely entirely on swapping to move elements, choosing a sort is a very good one.
Python Select sort