In: Computer Science
Hi, so for my homework assignment, we are meant to change this function so that instead of making a list from the array going up in an ascending order, making it be listed in descending order, meaning going from largest number to smallest number, the code I have now works for the ascending order, but how would I change this for it to go descending? Any help would be amazing, and please with a tutorial, thanks so much.
def heapify(arr, n, i): | |
largest = i # Initialize largest as root | |
l = 2 * i + 1 # left = 2*i + 1 | |
r = 2 * i + 2 # right = 2*i + 2 | |
# See if left child of root exists and is | |
# greater than root | |
if l < n and arr[i] < arr[l]: | |
largest = l | |
# See if right child of root exists and is | |
# greater than root | |
if r < n and arr[largest] < arr[r]: | |
largest = r | |
# Change root, if needed | |
if largest != i: | |
arr[i], arr[largest] = arr[largest], arr[i] # swap | |
# Heapify the root. | |
heapify(arr, n, largest) |
def heapify(arr, n, i): smallest = i # Initialize smallest as root l = 2 * i + 1 # left = 2*i + 1 r = 2 * i + 2 # right = 2*i + 2 # See if left child of root exists and is # less than root if l < n and arr[i] >= arr[l]: smallest = l # See if right child of root exists and is # less than root if r < n and arr[smallest] >= arr[r]: smallest = r if smallest != i: arr[i], arr[smallest] = arr[smallest], arr[i] # swap # Heapify the root. heapify(arr, n, smallest) # The main function to sort an array of given size def heapSort(arr): n = len(arr) # Build a maxheap. for i in range(n, -1, -1): heapify(arr, n, i) # One by one extract elements for i in range(n - 1, 0, -1): arr[i], arr[0] = arr[0], arr[i] # swap heapify(arr, i, 0) # Driver code to test above arr = [12, 11, 13, 5, 6, 7] heapSort(arr) n = len(arr) print("Sorted array is") for i in range(n): print("%d" % arr[i]),
Sorted array is 13 12 12 11 7 6