Select Sort:
First, the language description: From a list of numbers in turn select the smallest place, the second bit small, and so on to complete the sorting
- First traversal, find the smallest number, put it in the first position
- Second traversal, find the second largest number, put it in the second position
- ...... and so on, complete the sorting
Fixed position, find element
- for An array of n elements, start at the first position, find the smallest, and place it in the first position
- From the second position, the rest of the array, find the smallest, put in the second position
- ....
- Starting from the n-1 position, in the remaining array, find the smallest and place it in the n-1 position
Code implementation:
# Encoding=utf-8
def selectsort (LISTX):
Xlen = Len (LISTX)
For I in Xrange (Xlen):
Min = i
For j in Xrange (I+1,xlen):
If listx[min] > Listx[j]:
Min = J
Listx[i],listx[min] = Listx[min],listx[i]
Return LISTX
if __name__ = = ' __main__ ':
Print Selectsort ([32,34,55,66,5])
Exercise one: Change to descending order
#enconding = Utf-8
def select_sort (lista):
For i in Xrange (Len (lista)):
Min = i
For j in Xrange (I+1,len (lista)):
if (Lista[min] < lista[j]):
Min = J
Lista[min],lista[i] = Lista[i],lista[min]
return lista
if __name__ = = ' __main__ ':
Print Select_sort ([32,14,67,8,21])
Exercise 2: Does the code have an unnecessary comparison, can you subtract it, say why
# Encoding=utf-8
def selectsort (LISTX):
Xlen = Len (LISTX)
For I in Xrange (xLen-1):
Min = i
For j in Xrange (I+1,xlen):
If listx[min] > Listx[j]:
Min = J
Listx[i],listx[min] = Listx[min],listx[i]
Return LISTX
if __name__ = = ' __main__ ':
Print Selectsort ([32,34,55,66,5])
Second, the calculation of time complexity
32,34,55,66,5
First round:5,32,34,55,66 n-1 times
Second round:5,32,34,55,66 n-2 times
...
Fifth round:5,32,34,55,66 1 times
1+2+3+ +n-2+ n-1 = N (n-1)/2
The complexity of time is O (n^2)
Python algorithm-Select sort