从 Python 上的快速排序调用插入排序函数



我想知道是否有人可以帮助我?我有一个简单的 2/3 行代码通过 Python 调用另一个函数,但似乎无法弄清楚。原始的quicksort2有效,插入排序有效,但对该函数的调用不起作用(它们在同一个目录中(-有人知道该怎么做吗?谢谢。我将在下面发布这两个代码。

该赋值特别指出:当 n ≤ 16 时,Quicksort2 不会对列表进行分区,而是调用插入排序。这意味着我需要在我的快速排序 2 函数中一个简单的 if-elif 语句,但不知道该怎么做。

# insertion sort function for an array 
def insertion_sort(array_values):
for i in range(1, len(array_values)):
# condition for previous index greater than current index
while i > 0 and array_values[i - 1] > array_values[i]:
# setting our previous index as current index, and current index as previous index
array_values[i - 1], array_values[i] = array_values[i], array_values[i - 1]
# decrementing index at i for index pointer
i -= 1
# testing our insertion sort with a given array of values
array_values = [38,89,27,77,16,86,29,20,1,7]
insertion_sort(array_values)
print(array_values)
# ******************************************
def quicksort2(array, low, high): 
# THIS PART NEEDS TO CALL MY INSERTION SORT
#if len(array) <= 16:
#insertion_sort(array)   
# THIS PART NEEDS TO CALL MY INSERTION SORT              
if high > low:
index = partition(array, low, high)    
quicksort2(array, low, index - 1)      
quicksort2(array, index + 1, high)     
def partition(array, low, high):                
firstitem = array[low]
j = low
for i in range(low+1, high+1):            
if array[i] < firstitem:
j+=1
array[j], array[i] = array[i], array[j]
index = j
array[low], array[index] = array[index], array[low]     
return index                               
array = [10, 3, 4, 8, 1, 7, 0, 13]
quicksort2(array, 0, len(array)-1)             
for j in range(len(array)):                    
print ("%d" %array[j])

该赋值具有误导性,"n <= 16"。 当子列表包含 <= 16 个元素时,quiksort2 应使用插入排序,当高低<16 时。需要修改插入排序以将低和高作为参数。

最新更新