选择排序:
遍历列表,找出最小的那个数, 和初始位置调换顺序
时间复杂度:O(n^2)
迭代实现:
def select_sort_iteration(datas):
length = len(datas)
for i in range(0, length - 1):
min_index = i
for j in range(i+1, length):
if datas[j] < datas[min_index]:
min_index = j
if i != min_index:
temp = datas[i]
datas[i] = datas[min_index]
datas[min_index] = temp
return datas
递归实现:
def select_sort_recursion(datas):
def _select(start_index):
if start_index == length - 1:
return
min_index = start_index
for j in range(start_index+1, length):
if datas[j] < datas[min_index]:
min_index = j
if min_index != start_index:
temp = datas[start_index]
datas[start_index] = datas[min_index]
datas[min_index] = temp
_select(start_index + 1)
length = len(datas)
_select(0)
return datas