-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathHeapSort.java
More file actions
76 lines (58 loc) · 1.61 KB
/
HeapSort.java
File metadata and controls
76 lines (58 loc) · 1.61 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package sortingAlgorithms;
import java.util.*;
//Java program for implementation of Heap Sort
public class HeapSort {
public void sort(int A[]) {
int n = A.length;
for(int i=n/2;i>=0;i--)
heapify(A,n,i);
for(int i = n-1;i>0;i--) {
int temp = A[0];
A[0] = A[i];
A[i] = temp;
heapify(A,i,0);
}
}
void heapify(int A[], int n, int i) {
int largest = i; // Initialize largest as root
int l = 2*i + 1; // left = 2*i + 1
int r = 2*i + 2; // right = 2*i + 2
// If left child is larger than root
if (l < n && A[l] > A[largest])
largest = l;
// If right child is larger than largest so far
if (r < n && A[r] > A[largest])
largest = r;
// If largest is not root
if (largest != i)
{
int swap = A[i];
A[i] = A[largest];
A[largest] = swap;
// Recursively heapify the affected sub-tree
heapify(A, n, largest);
}
}
/* A utility function to print arrays.array of size n */
static void printArray(int A[])
{
int n = A.length;
for (int i=0; i<n; ++i)
System.out.print(A[i]+" ");
System.out.println();
}
// Driver program
public static void main(String args[])
{
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int A[] = new int[n];
for(int i=0;i<n;i++)
A[i] = sc.nextInt();
HeapSort ob = new HeapSort();
ob.sort(A);
System.out.println("Sorted arrays.array is");
printArray(A);
}
}