我试图通过阅读模糊的描述来实现插入排序,所以我可能会以错误的方式进行操作。但是,根据我的看法,这应该有效:
import random
arr = []
c_num = 0
for i in range(0, 10):
arr.append(random.randint(0, 10))
def InsertionSort(unsorted_array, current_num):
smallest_num = unsorted_array[current_num]
smallest_num_index = 0
isSorted = True
for i in range(current_num, len(unsorted_array) - 1):
if unsorted_array[i] < smallest_num:
smallest_num = unsorted_array[i]
smallest_num_index = i
isSorted = False
if isSorted:
return unsorted_array
else:
temp = unsorted_array[current_num]
unsorted_array[current_num] = smallest_num
unsorted_array[smallest_num_index] = temp
current_num += 1
return InsertionSort(unsorted_array, current_num)
print(InsertionSort(arr, c_num))
它将对前几个元素进行排序,然后打印出现在稍微排序的数组,但是我无法看到我所缺少的内容,以便对整个事物进行排序。
样品:
输入= [9,8,5,4,5,8,2,10,7,5]
输出= [2,4,5,8,5,8,9,10,7,5]