输入一个数组,返回一个排好序的数组。需要使用插入排序算法
样例输入:
[8, 5, 2, 9, 5, 6, 3]
整个过程类似于在头部开始建立一个不断增加的子数组,如果组数组后边的元素比子数组末尾的元素小,就把这个元素向前进行交换,直到这个元素比子数组中所有的元素都要小为止。
样例输出:
[2, 3, 5, 5, 6, 8, 9]
test_array = [8, 5, 2, 9, 5, 6, 3]
def insertionSort(array):
# Write your code here.
for i in range(1,len(array)):
#second index j
j = i
while j>0 and array[j]<array[j-1]:
array = swap(j,j-1,array)
j -= 1
return array
def swap(a,b,array_toswap):
array_toswap[a],array_toswap[b] = array_toswap[b],array_toswap[a]
return array_toswap
# print(sorted(test_array))
print(insertionSort(array = test_array))
#Space: O(1)
#Time: O(n^2)
中间过程:
[5, 8, 2, 9, 5, 6, 3]
[5, 2, 8, 9, 5, 6, 3]
[2, 5, 8, 9, 5, 6, 3]
[2, 5, 8, 5, 9, 6, 3]
[2, 5, 5, 8, 9, 6, 3]
[2, 5, 5, 8, 6, 9, 3]
[2, 5, 5, 6, 8, 9, 3]
[2, 5, 5, 6, 8, 3, 9]
[2, 5, 5, 6, 3, 8, 9]
[2, 5, 5, 3, 6, 8, 9]
[2, 5, 3, 5, 6, 8, 9]
[2, 3, 5, 5, 6, 8, 9]
[2, 3, 5, 5, 6, 8, 9]
#Time: O(n^2)