Heap Sort Algorithm Explanation.
Heap Sort Algorithm Steps:
- Convert the unsorted array into a Max Heap or Min Heap.
- Perform heapify operations to maintain the heap property after each element removal.
- Sequentially remove elements from the heap, starting from the root node. After each removal, reorganize the heap to maintain the heap property.
- Store the removed elements in an array to obtain the sorted order.
Python Program for Heap Sort Algorithm.
# Python Code implementatin for Heap Sort Algorithm def heapify(arr, n, i): largest = i # Initialize largest as root left = 2 * i + 1 # Left child right = 2 * i + 2 # Right child # Check if left child exists and is greater than root if left < n and arr[left] > arr[largest]: largest = left # Check if right child exists and is greater than root if right < n and arr[right] > arr[largest]: largest = right # Change root if needed if largest != i: arr[i], arr[largest] = arr[largest], arr[i] # Swap heapify(arr, n, largest) def heap_sort(arr): n = len(arr) # Build a max heap for i in range(n // 2 - 1, -1, -1): heapify(arr, n, i) # Extract elements one by one for i in range(n - 1, 0, -1): arr[i], arr[0] = arr[0], arr[i] # Swap root with last element heapify(arr, i, 0) # Heapify root element # Example usage: arr = [12, 11, 13, 5, 6, 7] heap_sort(arr) print("Sorted array:", arr)
Sorted array: [5, 6, 7, 11, 12, 13]
Heap Sort Using Python Built-in Function.
- heapify(iterable): Converts a given iterable (such as a list) into a heap in place. The function rearranges the elements so that they satisfy the heap property.
- heappush(heap, item): Adds an element item to the heap while maintaining the heap property.
- heappop(heap): Removes and returns the smallest element (root) from the heap while maintaining the heap property.
# Heap Sort Algorithm using heapq module import heapq def heap_sort(arr): # Convert the input list into a min-heap heapq.heapify(arr) sorted_list = [] while arr: # Extract elements one by one sorted_list.append(heapq.heappop(arr)) return sorted_list # Example usage: arr = [12, 11, 13, 5, 6, 7] sorted_array = heap_sort(arr) print("Sorted array:", sorted_array)
Sorted array: [5, 6, 7, 11, 12, 13]







Trends is an amazing magazine Blogger theme that is easy to customize and change to fit your needs.