MCPcopy Create free account
hub / github.com/Vishruth-S/CompetitiveCode / HeapSort

Class HeapSort

Misc/Heap_Sort/solution.java:42–114  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

40
41// Java program for implementation of Heap Sort
42public class HeapSort
43{
44 public void sort(int arr[])
45 {
46 int n = arr.length;
47
48 // Build heap (rearrange array)
49 for (int i = n / 2 - 1; i >= 0; i--)
50 heapify(arr, n, i);
51
52 // One by one extract an element from heap
53 for (int i=n-1; i>0; i--)
54 {
55 // Move current root to end
56 int temp = arr[0];
57 arr[0] = arr[i];
58 arr[i] = temp;
59
60 // call max heapify on the reduced heap
61 heapify(arr, i, 0);
62 }
63 }
64
65 // To heapify a subtree rooted with node i which is
66 // an index in arr[]. n is size of heap
67 void heapify(int arr[], int n, int i)
68 {
69 int largest = i; // Initialize largest as root
70 int l = 2*i + 1; // left = 2*i + 1
71 int r = 2*i + 2; // right = 2*i + 2
72
73 // If left child is larger than root
74 if (l < n && arr[l] > arr[largest])
75 largest = l;
76
77 // If right child is larger than largest so far
78 if (r < n && arr[r] > arr[largest])
79 largest = r;
80
81 // If largest is not root
82 if (largest != i)
83 {
84 int swap = arr[i];
85 arr[i] = arr[largest];
86 arr[largest] = swap;
87
88 // Recursively heapify the affected sub-tree
89 heapify(arr, n, largest);
90 }
91 }
92
93 /* A utility function to print array of size n */
94 static void printArray(int arr[])
95 {
96 int n = arr.length;
97 for (int i=0; i<n; ++i)
98 System.out.print(arr[i]+" ");
99 System.out.println();

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected