选择排序
复杂度:O(n2)
WIKI
In computer science, selection sort is a sorting algorithm, specifically an in-place comparison sort.
工作原理
在一个长度为N的无序数组中,在第一趟遍历N个数据,找出其中最小的数值与第一个元素交换,第二趟遍历剩下的N-1个数据,找出其中最小的数值与第二个元素交换......第N-1趟遍历剩下的2个数据,找出其中最小的数值与第N-1个元素交换,至此选择排序完成。
Python代码
def select_sort(alist):
n = len(alist)
for i in range(0, n - 1):
# Store the smallest number's index
index_min = i
# Compared with the remaining numbers
for j in range(i + 1, n):
if alist[index_min] > alist[j]:
index_min = j
alist[index_min], alist[i] = alist[i], alist[index_min]
if __name__ == "__main__":
alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
select_sort(alist)
print alist
>>>[17, 20, 26, 31, 44, 54, 55, 77, 93]