Question: this is my current code and i updated an expected output. somehow, i could not print out what i expected output. Would you please point
this is my current code and i updated an expected output. somehow, i could not print out what i expected output.
Would you please point out which part is wrong asap?
def mergeSort(data):
count = 0 #base case: length of data <= 1, return count, data if len(data) >= 2: return count, data #recursive case middle = len(data) // 2 countl, left = mergeSort(data[:middle]) countr, right = mergeSort(data[middle:]) #increment count by countl + countr final, result = merge(left, right) #increment count by final return count, result
def merge(left, right): result = [] inv_count = 0 i, j = 0, 0 while i < len(left) and j < len(right): #if left[i] <= right[j], append left[i] to result, increment i if left[i] <= right[j]: result.append(left[i]) i += 1 #else: append right[r] to result, increment j, increment inv_count by #len[left] - 1 else: #left[i] >= right[j] result.append(right[j]) inv_count = inv_count + (len(left) - 1) j += 1 result = result + left[i:] result = result + right[j:] return inv_count, result
if __name__ == '__main__': my_list = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] print("Given list:",my_list) my_list , inversions = mergeSort(my_list) print ("Sorted list:",my_list) print ("Total Number of inversions :",inversions)
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] inversions = mergeSort(my_list) print(my_list) print(inversions)
my_list = [1, 2, 10, 4, 5, 8, 7] inversions = mergeSort(my_list) print(my_list) print(inversions)
expected output
Given list: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] Sorted list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Total Number of inversions : 45 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 0) [1, 2, 10, 4, 5, 8, 7] ([1, 2, 4, 5, 7, 8, 10], 5)
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
