我实施了QuickSort(简单和就地)策略。我了解到In Place排序技术必须比Simple QuickSort更快,但我尝试了3次随机数组,阵列大小为2,000,000,Simple QuickSort更快。
我的In Place实施是否错误?
简单的QuickSort代码:
def quick(arr):
if (len(arr) > 1):
less = []
equal = []
greater = []
pivot = arr[0]
for i in arr:
if (i < pivot):
less.append(i)
elif (i == pivot):
equal.append(i)
else:
greater.append(i)
return quick(less) + equal + quick(greater)
else:
return arr
就地QS代码:
def quickSort(arr, leftIndex = 0, rightIndex = None):
if (rightIndex is None):
rightIndex = len(arr) - 1
def _partition(arr, leftIndex, rightIndex):
pivot = arr[int((leftIndex + rightIndex)/2)]
while(leftIndex <= rightIndex):
while (arr[leftIndex] < pivot):
leftIndex += 1
while (arr[rightIndex] > pivot):
rightIndex -= 1
if (leftIndex <= rightIndex):
temp = arr[leftIndex]
arr[leftIndex] = arr[rightIndex]
arr[rightIndex] = temp
leftIndex += 1
rightIndex -= 1
return leftIndex
def _quickSort(arr, leftIndex, rightIndex):
index = _partition(arr, leftIndex, rightIndex)
if (leftIndex < index - 1):
_quickSort(arr, leftIndex, index - 1)
if (index < rightIndex):
_quickSort(arr, index, rightIndex)
_quickSort(arr, leftIndex, rightIndex)
主
randomArr = numpy.random.randint(low=-999999, high=9999999, size=2000000)
start = time.time()
quickArr = quick(randomArr)
print("----Quick (Simple): %.2f seconds----" % float(time.time() - start))
start = time.time()
quickSort(randomArr)
print("----Quick (In Place): %.2f seconds----" % float(time.time() - start))
输出:
Trial 1:
----Quick (Simple): 13.08 seconds----
----Quick (In Place): 17.24 seconds----
Trial 2:
----Quick (Simple): 14.25 seconds----
----Quick (In Place): 18.50 seconds----
Trial 3:
----Quick (Simple): 12.94 seconds----
----Quick (In Place): 17.32 seconds----