Skip to content

Commit 682b3d3

Browse files
authored
Merge pull request #867 from neha030/dev23
Heap Sort added
2 parents ec71cc2 + 7146cdf commit 682b3d3

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

Sorting Algorithms/heap_sort.py

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
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 total number of elements :"))
49+
print("Enter elements to be sorted ")
50+
51+
for i in range(n):
52+
data.append(int(input()))
53+
54+
# Sending element to get sorted
55+
heap_sort(data)
56+
57+
# Priting Elements after Getting Sorted
58+
for d in data:
59+
print(d, end = " ")
60+
61+
62+
'''
63+
INPUT
64+
Enter total number of elements :5
65+
Enter elements to be sorted
66+
30
67+
50
68+
10
69+
20
70+
40
71+
72+
OUTPUT
73+
10 20 30 40 50
74+
75+
Time Complexity:
76+
Best Case: O (nlogn)
77+
Average Case: O (nlogn)
78+
Worst Case: O (nlogn)
79+
Space Complexity: O (1)
80+
'''
81+

0 commit comments

Comments
 (0)