📜  门| GATE-CS-2002 |问题 4(1)

📅  最后修改于: 2023-12-03 14:58:25.135000             🧑  作者: Mango

GATE-CS-2002 Question 4

The GATE-CS-2002 question 4 is a programming question aimed at testing the candidate's proficiency in data structures and algorithms. The objective of the question is to implement a heap data structure and use it to sort a given array.

Problem Statement

You are given an array arr of n integers. Your task is to implement a heap data structure and use it to sort the given array. You must implement the following functions:

  • build_heap(arr, n): A function that builds the heap from the given array.
  • heapify(arr, n, i): A function that restores the heap property at the given index.
  • heap_sort(arr, n): A function that uses build_heap() and heapify() functions to sort the array.

The output of your program should be the sorted array.

Solution

We can start by implementing the heapify() function. This function takes an array arr, its length n, and an index i. It restores the heap property at the given index i.

def heapify(arr, n, i):
    largest = i
    left = 2 * i + 1 # left child index
    right = 2 * i + 2 # right child index

    # check if the left child is larger than the root
    if left < n and arr[largest] < arr[left]:
        largest = left

    # check if the right child is larger than the root or the left child
    if right < n and arr[largest] < arr[right]:
        largest = right

    # swap the root with the largest child if necessary
    if largest != i:
        arr[i], arr[largest] = arr[largest], arr[i]
        heapify(arr, n, largest) # recurse on the largest child index

Next, we can implement the build_heap() function. This function builds a heap from the given array. We can start at the last non-leaf node (i.e., n/2 - 1) and use heapify() to restore the heap property starting from each node.

def build_heap(arr, n):
    # start from the last non-leaf node and heapify down
    for i in range(n // 2 - 1, -1, -1):
        heapify(arr, n, i)

Finally, we can implement the heap_sort() function. This function uses build_heap() to build a heap from the given array, and then repeatedly swaps the root element with the last element, reduces the heap size by 1, and restores the heap property using heapify().

def heap_sort(arr, n):
    # build the max heap
    build_heap(arr, n)

    # repeatedly extract the maximum element and restore the heap property
    for i in range(n - 1, 0, -1):
        arr[0], arr[i] = arr[i], arr[0]
        heapify(arr, i, 0)

    return arr
Conclusion

The implementation of the heap data structure and heap sort algorithm provided here should successfully sort a given array. It demonstrates the use of recursion to traverse the heap structure efficiently and effectively.