Skip to content

Commit 50e1268

Browse files
authored
Merge pull request bhrigukansra#171 from computerwala/master
updated
2 parents f3bdfa1 + a021abb commit 50e1268

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Python program for implementation of heap Sort
2+
3+
# To heapify subtree rooted at index i.
4+
# n is size of heap
5+
def heapify(arr, n, i):
6+
largest = i # Initialize largest as root
7+
l = 2 * i + 1 # left = 2*i + 1
8+
r = 2 * i + 2 # right = 2*i + 2
9+
10+
# See if left child of root exists and is
11+
# greater than root
12+
if l < n and arr[i] < arr[l]:
13+
largest = l
14+
15+
# See if right child of root exists and is
16+
# greater than root
17+
if r < n and arr[largest] < arr[r]:
18+
largest = r
19+
20+
# Change root, if needed
21+
if largest != i:
22+
arr[i],arr[largest] = arr[largest],arr[i] # swap
23+
24+
# Heapify the root.
25+
heapify(arr, n, largest)
26+
27+
# The main function to sort an array of given size
28+
def heapSort(arr):
29+
n = len(arr)
30+
31+
# Build a maxheap.
32+
for i in range(n, -1, -1):
33+
heapify(arr, n, i)
34+
35+
# One by one extract elements
36+
for i in range(n-1, 0, -1):
37+
arr[i], arr[0] = arr[0], arr[i] # swap
38+
heapify(arr, i, 0)
39+
40+
# Driver code to test above
41+
arr = [ 12, 11, 13, 5, 6, 7]
42+
heapSort(arr)
43+
n = len(arr)
44+
print ("Sorted array is")
45+
for i in range(n):
46+
print ("%d" %arr[i]),
47+
# This code is contributed by Aman Soni(computerwala)

contributors.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,4 +45,5 @@
4545
43. [Seemant Aggarwal](https://github.com/seemantaggarwal)
4646
44. [Vibhav Tiwari](https://github.com/VibhavTiwari)
4747
45. [Anh Hoai Ung](https://github.com/hoaianhkhang)
48-
46. [Your Name](https://github.com/yourusername)
48+
46. [Aman Soni](https://github.com/computerwala)
49+
47. [Your Name](https://github.com/yourusername)

0 commit comments

Comments
 (0)