MCPcopy Create free account
hub / github.com/PrajaktaSathe/Java / HeapSort

Class HeapSort

Programs/HeapSort.java:1–68  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

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

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected