Advertisement
Python253

heap_sort_demo

Jun 24th, 2024
454
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.89 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Filename: heap_sort_demo.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9.    This script demonstrates the Heap Sort algorithm by sorting an array of integers.
  10.  
  11. Requirements:
  12.    - Python 3.x
  13.  
  14. Functions:
  15.    - heap_sort(arr):
  16.        Perform heap sort on the given list `arr`.
  17.  
  18. Usage:
  19.    - Run the script to see the Heap Sort algorithm in action.
  20.  
  21. Example:
  22.  
  23.                :: HEAP SORTING DEMO ::
  24.  
  25.        Original array: [12, 11, 13,  5,  6,  7]
  26.        Sorted array:   [ 5,  6,  7, 11, 12, 13]
  27.  
  28.        Heap Sorting Complete!
  29.  
  30.            Exiting Program...   GoodBye!
  31.  
  32. Additional Notes:
  33.    - Heap Sort is an efficient sorting algorithm with a time complexity of O(n log n).
  34. """
  35.  
  36. def heap_sort(arr):
  37.     """
  38.    Perform heap sort on the given list `arr`.
  39.  
  40.    Args:
  41.        arr (list): List of integers to be sorted in place.
  42.  
  43.    Returns:
  44.        None. The list `arr` is sorted in place using heap sort.
  45.    """
  46.     def heapify(arr, n, i):
  47.         largest = i
  48.         l = 2 * i + 1
  49.         r = 2 * i + 2
  50.  
  51.         if l < n and arr[largest] < arr[l]:
  52.             largest = l
  53.  
  54.         if r < n and arr[largest] < arr[r]:
  55.             largest = r
  56.  
  57.         if largest != i:
  58.             arr[i], arr[largest] = arr[largest], arr[i]
  59.             heapify(arr, n, largest)
  60.  
  61.     n = len(arr)
  62.  
  63.     # Build a max heap
  64.     for i in range(n // 2 - 1, -1, -1):
  65.         heapify(arr, n, i)
  66.  
  67.     # Extract elements from the heap one by one
  68.     for i in range(n - 1, 0, -1):
  69.         arr[i], arr[0] = arr[0], arr[i]
  70.         heapify(arr, i, 0)
  71.  
  72. def main():
  73.     """
  74.    Main function to demonstrate heap sort.
  75.  
  76.    It initializes an example array, sorts it using heap_sort function,
  77.    and prints the original and sorted arrays.
  78.    """
  79.     print("\n\t\t:: HEAP SORTING DEMO ::\n")
  80.    
  81.     # Example array to sort
  82.     arr = [12, 11, 13, 5, 6, 7]
  83.  
  84.     # Print the original array
  85.     original_arr_str = "["
  86.     for index, num in enumerate(arr):
  87.         if index == 0:
  88.             original_arr_str += f"{num:2}"  # Add one space for single-digit numbers
  89.         else:
  90.             original_arr_str += f", {num:2}"  # Add one space for single-digit numbers
  91.     original_arr_str += "]"
  92.     print("Original array:", original_arr_str)
  93.  
  94.     # Sort the array using heap sort
  95.     heap_sort(arr)
  96.  
  97.     # Print the sorted array
  98.     sorted_arr_str = "["
  99.     for index, num in enumerate(arr):
  100.         if index == 0:
  101.             sorted_arr_str += f"{num:2}"  # Add one space for single-digit numbers
  102.         else:
  103.             sorted_arr_str += f", {num:2}"  # Add one space for single-digit numbers
  104.     sorted_arr_str += "]"
  105.     print("Sorted array:  ", sorted_arr_str)
  106.    
  107.     # Print completion message
  108.     print("\nHeap Sorting Complete!\n\n\tExiting Program...   GoodBye!")
  109.  
  110. if __name__ == "__main__":
  111.     main()
  112.  
  113.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement