-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInplace_Heap_Sort.txt
88 lines (72 loc) · 2.43 KB
/
Inplace_Heap_Sort.txt
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
76
77
78
79
80
81
82
83
84
85
86
87
88
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
// Code : In-place heap sort
// Send Feedback
// Given an integer array of size n. Sort this array (in decreasing order) using heap sort.
// Space complexity should be O(1).
// Input Format :
// Line 1 : Integer n, Array size
// Line 2 : Array elements, separated by space
// Output Format :
// Array elements after sorting
// Constraints :
// 1 <= n <= 10^6
// Sample Input:
// 6
// 2 6 8 5 4 3
// Sample Output:
// 8 6 5 4 3 2
public class Solution {
public static void inplaceHeapSort(int arr[]) {
int n = arr.length;
// Build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
// One by one extract an element from heap
for (int i=n-1; i>0; i--)
{
// Move current root to end
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
// call max heapify on the reduced heap
heapify(arr, i, 0);
}
}
static void heapify(int arr[], 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 && arr[l] < arr[largest])
largest = l;
// If right child is larger than largest so far
if (r < n && arr[r] < arr[largest])
largest = r;
// If largest is not root
if (largest != i)
{
int swap = arr[i];
arr[i] = arr[largest];
arr[largest] = swap;
// Recursively heapify the affected sub-tree
heapify(arr, n, largest);
}
}
}