forked from SamirPaulb/DSAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
1f0a2a3
commit a1af534
Showing
1 changed file
with
46 additions
and
33 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,33 +1,46 @@ | ||
def heapify(arr, n, i): | ||
largest = i | ||
l = 2 * i + 1 | ||
r = 2 * i + 2 | ||
|
||
if l < n and arr[i] < arr[l]: | ||
largest = l | ||
|
||
if r < n and arr[largest] < arr[r]: | ||
largest = r | ||
|
||
if largest != i: | ||
(arr[i], arr[largest]) = (arr[largest], arr[i]) # swap | ||
|
||
heapify(arr, n, largest) | ||
|
||
def heapSort(arr): | ||
n = len(arr) | ||
|
||
for i in range(n // 2 - 1, -1, -1): | ||
heapify(arr, n, i) | ||
|
||
for i in range(n - 1, 0, -1): | ||
(arr[i], arr[0]) = (arr[0], arr[i]) # swap | ||
heapify(arr, i, 0) | ||
|
||
arr = [12, 11, 13, 5, 6, 7, ] | ||
heapSort(arr) | ||
n = len(arr) | ||
print('Sorted array is') | ||
for i in range(n): | ||
print(arr[i]) | ||
|
||
# https://practice.geeksforgeeks.org/problems/heap-sort/1 | ||
|
||
|
||
class Solution: | ||
|
||
#Heapify function to maintain heap property. | ||
def heapify(self,arr, n, i): | ||
largest = i | ||
l = 2 * i + 1 | ||
r = 2 * i + 2 | ||
|
||
#if left or right child is greater than current element, | ||
#we store its position. | ||
if l < n and arr[i] < arr[l]: | ||
largest = l | ||
if r < n and arr[largest] < arr[r]: | ||
largest = r | ||
|
||
#if largest is not equal to i, we swap the values at their position. | ||
if largest != i: | ||
arr[i], arr[largest] = arr[largest], arr[i] | ||
#calling function recursively for the largest variable. | ||
self.heapify(arr, n, largest) | ||
|
||
|
||
#Function to build a Heap from array. | ||
def buildHeap(self,arr,n): | ||
|
||
#calling heapify function for values from half to first index. | ||
for i in range(n, -1, -1): | ||
self.heapify(arr, n, i) | ||
|
||
#Function to sort an array using Heap Sort. | ||
def HeapSort(self,arr,n): | ||
|
||
#calling function to build heap with array. | ||
self.buildHeap(arr,n) | ||
|
||
for i in range(n - 1, 0, -1): | ||
|
||
#swapping values at current and first index. | ||
arr[i], arr[0] = arr[0], arr[i] | ||
#calling heapify function for first index. | ||
self.heapify(arr, i, 0) | ||
|
||
|