Skip to content

Commit 4c9446f

Browse files
committed
HeapSort implementation: 1st commit
1 parent 100543a commit 4c9446f

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

heap/HeapSort.java

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/*******************************************************
2+
* @author SAGAR PAUL (paulsagar1a)
3+
* @category heap
4+
*******************************************************/
5+
6+
//Heap sort algorithm
7+
8+
package heap;
9+
10+
public class HeapSort {
11+
12+
public static void main(String[] args) {
13+
// TODO Auto-generated method stub
14+
int[] arr = {1, 11, 8, 5, 7, 10};
15+
HeapSort obj = new HeapSort();
16+
obj.sort(arr);
17+
obj.printSortedArray(arr);
18+
}
19+
20+
private void printSortedArray(int[] arr) {
21+
// TODO Auto-generated method stub
22+
int n = arr.length;
23+
for (int i=0; i < n; ++i)
24+
System.out.print(arr[i]+" ");
25+
System.out.println();
26+
}
27+
28+
private void sort(int[] arr) {
29+
// TODO Auto-generated method stub
30+
int n = arr.length;
31+
32+
//build max heap
33+
for(int i=n/2-1; i>=0; i--) {
34+
heapify(arr, n, i);
35+
}
36+
37+
// Heap sort
38+
for (int i=n-1; i>=0; i--)
39+
{
40+
int temp = arr[0];
41+
arr[0] = arr[i];
42+
arr[i] = temp;
43+
44+
// Heapify root element
45+
heapify(arr, i, 0);
46+
}
47+
}
48+
49+
private void heapify(int[] arr, int n, int i) {
50+
// TODO Auto-generated method stub
51+
//find largest among root, left child and right child
52+
int largest = i;
53+
int l = 2*i + 1;
54+
int r = 2*i + 2;
55+
56+
if (l < n && arr[l] > arr[largest])
57+
largest = l;
58+
59+
if (r < n && arr[r] > arr[largest])
60+
largest = r;
61+
62+
// Swap and continue heapifying if root is not largest
63+
if (largest != i)
64+
{
65+
int swap = arr[i];
66+
arr[i] = arr[largest];
67+
arr[largest] = swap;
68+
69+
heapify(arr, n, largest);
70+
}
71+
}
72+
73+
}

0 commit comments

Comments
 (0)