Answered step by step
Verified Expert Solution
Question
1 Approved Answer
I need help fixing my code. Basically I'm counting the number of comparisons and swaps in a quicksort. The way its set up right now,
I need help fixing my code. Basically I'm counting the number of comparisons and swaps in a quicksort. The way its set up right now, it is printing the number of comparisons and swaps one by one because the print statement is in the partition function. How do i fix it so that the print can be in the quick_sort function and will print the total number of comparisons and swaps? def quick_sort(array): quick_sort2(array, 0, len(array) - 1) #print(" QUICK SORT - Comparisons: ", comparisons, "Swaps: ", swaps) #Where I want to print. def quick_sort2(array, first, last): if first < last: midpoint = partition(array, first, last) quick_sort2(array, first, midpoint - 1) quick_sort2(array, midpoint + 1, last) def partition(array, first, last): comparisons = 0 swaps = 0 pivot = array[first] left = first+1 right = last done = False while not done: comparisons = comparisons + 1 while left <= right and array[left] <= pivot: left = left + 1 while array[right] >= pivot and right >= left: right = right - 1 if right < left: done = True else: temp = array[left] array[left] = array[right] array[right] = temp swaps = swaps + 1 temp = array[first] array[first] = array[right] array[right] = temp print(" QUICK SORT - Comparisons: ", comparisons, "Swaps: ", swaps) return right def display(array): for words in array: print(words) file = open("words25.txt", "r") array = [] i = 1 for words in file.read().lower().split(" "): if i <= 5000: array.append(words) i += 1 display(array) quick_sort(array) display(array)
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started