I implemented in-place quickSort that use the middle of the array as 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.
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.
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).
I don't want to post too much, but if I am correct, then
your code used 195 comparisons and 29 swaps, and
the instructor's code used 142 comparisons and 87 swaps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.