-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeap Sort.java
More file actions
46 lines (40 loc) · 1.04 KB
/
Heap Sort.java
File metadata and controls
46 lines (40 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
//https://practice.geeksforgeeks.org/problems/heap-sort/1
class Solution
{
//Function to build a Heap from array.
void buildHeap(int arr[], int n)
{
// Your code here
for(int i=n/2-1; i>=0; i--){
heapify(arr,n,i);
}
}
//Heapify function to maintain heap property.
void heapify(int arr[], int n, int i)
{
// Your code here
int max=i;
int l= 2*i+1;
int r= 2*i+2;
if(l<n && arr[l]>arr[max]) max = l;
if(r<n && arr[r]>arr[max]) max = r;
if(max!=i){
int temp = arr[max];
arr[max] = arr[i];
arr[i] = temp;
heapify(arr, n , max);
}
}
//Function to sort an array using Heap Sort.
public void heapSort(int arr[], int n)
{
//code here
buildHeap(arr,n);
for(int i=n-1; i>0; i--){
int temp = arr[i];
arr[i]= arr[0];
arr[0]= temp;
heapify(arr,i,0);
}
}
}