Skip to content

Commit b46ceff

Browse files
authored
Create HeapSort.java
1 parent 1ff1c3c commit b46ceff

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

Sorting Algorithms/HeapSort.java

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
// Java program for implementation of Heap Sort
2+
public class HeapSort
3+
{
4+
public void sort(int arr[])
5+
{
6+
int n = arr.length;
7+
8+
// Build heap (rearrange array)
9+
for (int i = n / 2 - 1; i >= 0; i--)
10+
heapify(arr, n, i);
11+
12+
// One by one extract an element from heap
13+
for (int i=n-1; i>=0; i--)
14+
{
15+
// Move current root to end
16+
int temp = arr[0];
17+
arr[0] = arr[i];
18+
arr[i] = temp;
19+
20+
// call max heapify on the reduced heap
21+
heapify(arr, i, 0);
22+
}
23+
}
24+
25+
// To heapify a subtree rooted with node i which is
26+
// an index in arr[]. n is size of heap
27+
void heapify(int arr[], int n, int i)
28+
{
29+
int largest = i; // Initialize largest as root
30+
int l = 2*i + 1; // left = 2*i + 1
31+
int r = 2*i + 2; // right = 2*i + 2
32+
33+
// If left child is larger than root
34+
if (l < n && arr[l] > arr[largest])
35+
largest = l;
36+
37+
// If right child is larger than largest so far
38+
if (r < n && arr[r] > arr[largest])
39+
largest = r;
40+
41+
// If largest is not root
42+
if (largest != i)
43+
{
44+
int swap = arr[i];
45+
arr[i] = arr[largest];
46+
arr[largest] = swap;
47+
48+
// Recursively heapify the affected sub-tree
49+
heapify(arr, n, largest);
50+
}
51+
}
52+
53+
/* A utility function to print array of size n */
54+
static void printArray(int arr[])
55+
{
56+
int n = arr.length;
57+
for (int i=0; i<n; ++i)
58+
System.out.print(arr[i]+" ");
59+
System.out.println();
60+
}
61+
62+
// Driver program
63+
public static void main(String args[])
64+
{
65+
int arr[] = {12, 11, 13, 5, 6, 7};
66+
int n = arr.length;
67+
68+
HeapSort ob = new HeapSort();
69+
ob.sort(arr);
70+
71+
System.out.println("Sorted array is");
72+
printArray(arr);
73+
}
74+
}

0 commit comments

Comments
 (0)