-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInplaceHeapSort.java
More file actions
69 lines (65 loc) · 2.2 KB
/
InplaceHeapSort.java
File metadata and controls
69 lines (65 loc) · 2.2 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
// Inplace Heap Sort
// Send Feedback
// Given an integer array of size N. Sort this array (in decreasing order) using
// heap sort.
// Note: Space complexity should be O(1).
// Input Format:
// The first line of input contains an integer, that denotes the value of the
// size of the array or N.
// The following line contains N space separated integers, that denote the value
// of the elements of the array.
// Output Format :
// The first and only line of output contains array elements after sorting. The
// elements of the array in the output are separated by single space.
// Constraints :
// 1 <= n <= 10^6
// Time Limit: 1 sec
// Sample Input 1:
// 6
// 2 6 8 5 4 3
// Sample Output 1:
// 8 6 5 4 3 2
public class Solution {
public static void downHeapify(int arr[], int i, int n) {
int parentIndex = i;
int leftChildIndex = 2 * parentIndex + 1;
int rightChildIndex = 2 * parentIndex + 2;
while (leftChildIndex < n) {
int minIndex = parentIndex;
if (arr[leftChildIndex] < arr[minIndex]) {
minIndex = leftChildIndex;
}
if (rightChildIndex < n && arr[rightChildIndex] < arr[minIndex]) {
minIndex = rightChildIndex;
}
if (minIndex == parentIndex) {
break;
}
int temp = arr[minIndex];
arr[minIndex] = arr[parentIndex];
arr[parentIndex] = temp;
parentIndex = minIndex;
leftChildIndex = 2 * parentIndex + 1;
rightChildIndex = 2 * parentIndex + 2;
}
}
public static void inplaceHeapSort(int arr[]) {
/*
* Your class should be named Solution
* Don't write main().
* Don't read input, it is passed as function argument.
* Change in the given input itself.
* Taking input and printing output is handled automatically.
*/
int n = arr.length;
for (int i = (n / 2) - 1; i >= 0; i--) {
downHeapify(arr, i, n);
}
for (int i = n - 1; i >= 0; i--) {
int temp = arr[i];
arr[i] = arr[0];
arr[0] = temp;
downHeapify(arr, 0, i);
}
}
}