我正在尝试在Python上执行快速排序,在其中它提取一个随机整数而不是第一个元素,并比较左侧和右侧的值,并以此进行排序。我的partition和quicksort方法已经可以工作(我已经测试过并且对其进行了排序),但是我不知道首先采取随机int的方法。
到目前为止,我已经导入了我的随机包,并尝试了一个名为“ random.choice()”的东西。问题在于这仅需要第一个要素,而不是全部要素。之后,我需要调用分区(在quicksort上实现。最后一部分,我需要使用以下伪代码:
if (numItemsInSubArray > 16) then swap a[low] and a[random index between high and low];
我将在下面发布我的代码,任何想法都会有所帮助,谢谢。
def quicksort3(array, low, high):
if high > low:
index = partition(array, low, high)
quicksort3(array, low, index - 1)
quicksort3(array, index + 1, high)
# attempt to return first element in array, followed by quicksorted array
random.choice(array)
if (len(subarray) > 16):
# swap a[low] and a[random index (such as high?) between high and low];
array[low], array[high] = array[high], array[low]
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]
quicksort3(array, 0, len(array)-1)
for j in range(len(array)):
print ("%d" %array[j])
您误解了您的代码和random.choice
。此函数返回参数的随机选择的元素。您的代码调用了该函数,但忽略了返回值:
# attempt to return first element in array, followed by quicksorted array
random.choice(array)
您需要将返回值分配给变量,并use作为排序的枢纽。