[英]Too many array comparisons - In-place quicksort
我实现了使用数组中间作为 pivot 的就地快速排序。 我有一些需要完成的测试用例,但是我的代码似乎可以进行很多比较。 对于数组列表:
[10, 4, 33, 44, 17, 20, 3, 2, 9, 82, 38, 67, 55, 11, 32, 23, 19, 7, 6, 14, 29, 10, 10]
我应该得到 142 个比较,但我得到了 196 个。
这是我的代码:
comparisons = 0
def addComparison() -> bool:
global comparisons
comparisons += 1
return True
def quicksort(arr_list: list, lower_bound: int, upper_bound: int) -> list:
if upper_bound > lower_bound:
index = split_arr(arr_list, lower_bound, upper_bound)
quicksort(arr_list, lower_bound, index)
quicksort(arr_list, index+1, upper_bound)
addComparison()
def split_arr(arr_list: list, lower_bound: int, upper_bound: int) -> int:
global comparisons
pivot_index = (lower_bound + upper_bound) // 2
pivot_elem = arr_list[pivot_index]
while lower_bound <= upper_bound:
left = lower_bound
while addComparison() and arr_list[left] < pivot_elem:
left += 1
right = upper_bound
while addComparison() and arr_list[right] > pivot_elem:
right -= 1
if left < right:
arr_list[left], arr_list[right] = arr_list[right], arr_list[left]
lower_bound = left + 1
upper_bound = right - 1
else:
return right
return upper_bound
unsorted_list = [10, 4, 33, 44, 17, 20, 3, 2, 9, 82, 38, 67, 55, 11, 32, 23, 19, 7, 6, 14, 29, 10, 10]
quicksort(unsorted_list, 0, len(unsorted_list) - 1)
assert comparisons == 142
您实施的分区方案与您的讲师不同,这将改变特定数据集的实际比较次数。
您的讲师似乎已经实施了基本的“以最后一项为中心”分区方案——通过将中间项交换到最后一项进行了轻微修改,没有比较。 我使用该算法在该数据集上得到 142。
使用https://en.wikipedia.org/wiki/Quicksort中的术语,您实现了 Hoare 分区方案,但您应该使用 Lomuto(可能在课堂上介绍过)。
我不想发太多,但如果我是对的,那么
您的代码使用了 195 次比较和 29 次交换,并且
讲师的代码使用了 142 次比较和 87 次交换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.