|
| 1 | +''' |
| 2 | +HEAP SORT |
| 3 | +It is a sorting technique based on the heap data structure. |
| 4 | +Heap is a complete binary tree, in which every level except the last, is filled |
| 5 | +completely with its nodes, and nodes are far left. |
| 6 | +We implement this sorting in an array using Max Heap, in which the parent node |
| 7 | +value is greater than it child node values. |
| 8 | +''' |
| 9 | +def heapify(arr, length, index): |
| 10 | + # base case |
| 11 | + # we will call this function until the largest number is the index... |
| 12 | + largest_num_index = index |
| 13 | + left_index = (index * 2) + 1 |
| 14 | + right_index = (index * 2) + 2 |
| 15 | + |
| 16 | + if(left_index < length and arr[index] < arr[left_index]): |
| 17 | + largest_num_index = left_index |
| 18 | + |
| 19 | + if(right_index < length and arr[largest_num_index] < arr[right_index]): |
| 20 | + largest_num_index = right_index |
| 21 | + |
| 22 | + # if index is not the largest, make it the largest! |
| 23 | + # and run it again! |
| 24 | + if(largest_num_index != index): |
| 25 | + arr[index], arr[largest_num_index] = arr[largest_num_index], arr[index] |
| 26 | + heapify(arr, length, largest_num_index) |
| 27 | + |
| 28 | + |
| 29 | +def heap_sort(arr): |
| 30 | + # need array length to create indices |
| 31 | + length = len(arr) |
| 32 | + |
| 33 | + for index in range(length, -1, -1): |
| 34 | + # ask about functions modifying arrays without return value |
| 35 | + # build max heap |
| 36 | + heapify(arr, length, index) |
| 37 | + |
| 38 | + # for each sorted heap, swap the root and the last number |
| 39 | + for index in range(length - 1, 0, -1): |
| 40 | + arr[index], arr[0] = arr[0], arr[index] |
| 41 | + # then call heapify again with the new array |
| 42 | + heapify(arr, index, 0) |
| 43 | + |
| 44 | + |
| 45 | +# Taking Elements to be Sorted |
| 46 | + |
| 47 | +data = [] |
| 48 | +n = int(input("Enter elements to be sorted :")) |
| 49 | + |
| 50 | +for i in range(n): |
| 51 | + data.append(int(input())) |
| 52 | + |
| 53 | +# Sending element to get sorted |
| 54 | +heap_sort(data) |
| 55 | + |
| 56 | +# Priting Elements after Getting Sorted |
| 57 | +for d in data: |
| 58 | + print(d, end = " ") |
| 59 | + |
| 60 | + |
| 61 | +''' |
| 62 | +INPUT |
| 63 | +Enter elements to be sorted : 5 |
| 64 | +30 |
| 65 | +50 |
| 66 | +10 |
| 67 | +20 |
| 68 | +40 |
| 69 | +
|
| 70 | +OUTPUT |
| 71 | +10 20 30 40 50 |
| 72 | +
|
| 73 | +Time Complexity: |
| 74 | +Best Case: O (nlogn) |
| 75 | +Average Case: O (nlogn) |
| 76 | +Worst Case: O (nlogn) |
| 77 | +Space Complexity: O (1) |
| 78 | +''' |
| 79 | + |
0 commit comments