[英]Too many array comparisons - In-place quicksort
I implemented in-place quickSort that use the middle of the array as pivot.我实现了使用数组中间作为 pivot 的就地快速排序。 I have some test cases I need to fulfill, however my code seems to run to many comparisons.我有一些需要完成的测试用例,但是我的代码似乎可以进行很多比较。 For the array-list:对于数组列表:
[10, 4, 33, 44, 17, 20, 3, 2, 9, 82, 38, 67, 55, 11, 32, 23, 19, 7, 6, 14, 29, 10, 10]
I should get 142 comparisons, however I get 196.我应该得到 142 个比较,但我得到了 196 个。
This is my code:这是我的代码:
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
You have implemented a different partition scheme than your instructor, which will change the actual number of comparisons on a specific data set.您实施的分区方案与您的讲师不同,这将改变特定数据集的实际比较次数。
Your instructor seems to have implemented the basic "pivot on the last item" partition scheme -- slightly modified by swapping the middle item to the last item, with no comparison.您的讲师似乎已经实施了基本的“以最后一项为中心”分区方案——通过将中间项交换到最后一项进行了轻微修改,没有比较。 I get 142 on that data set with that algorithm.我使用该算法在该数据集上得到 142。
Using the terminology at https://en.wikipedia.org/wiki/Quicksort you implemented Hoare partition scheme, but you were expected to use Lomuto (which was probably covered in class).使用https://en.wikipedia.org/wiki/Quicksort中的术语,您实现了 Hoare 分区方案,但您应该使用 Lomuto(可能在课堂上介绍过)。
I don't want to post too much, but if I am correct, then我不想发太多,但如果我是对的,那么
your code used 195 comparisons and 29 swaps, and您的代码使用了 195 次比较和 29 次交换,并且
the instructor's code used 142 comparisons and 87 swaps.讲师的代码使用了 142 次比较和 87 次交换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.