Skip to content

Commit 62349fb

Browse files
authored
Create Inplace Heap Sort
1 parent 29fa0c0 commit 62349fb

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
/*
2+
Given an integer array of size N. Sort this array (in decreasing order) using heap sort.
3+
Note: Space complexity should be O(1).
4+
Input Format:
5+
The first line of input contains an integer, that denotes the value of the size of the array or N.
6+
The following line contains N space separated integers, that denote the value of the elements of the array.
7+
Output Format :
8+
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.
9+
Constraints :
10+
1 <= n <= 10^6
11+
Time Limit: 1 sec
12+
Sample Input 1:
13+
6
14+
2 6 8 5 4 3
15+
Sample Output 1:
16+
8 6 5 4 3 2
17+
*/
18+
19+
public class Solution {
20+
21+
public static void inplaceHeapSort(int arr[]) {
22+
/* Your class should be named Solution
23+
* Don't write main().
24+
* Don't read input, it is passed as function argument.
25+
* Change in the given input itself.
26+
* Taking input and printing output is handled automatically.
27+
*/
28+
//Find length of arr
29+
int n=arr.length;
30+
//Step 1 - Build heap using optimized method with time complexity O(n)
31+
for(int i=(n/2)-1;i>=0;i--)
32+
{
33+
//Perform down-heapfiy operation for node at index i, starting at index i and going to down to the last node (end of arr)
34+
downHeapify(arr,i,n);
35+
}
36+
37+
//Step 2 - Perform remove minimum element, put them at respective last position in the heap and heap re-balancing until all the elements are out of the heap
38+
for(int i=n-1;i>=0;i--)
39+
{
40+
int temp=arr[i];
41+
arr[i]=arr[0];
42+
arr[0]=temp;
43+
44+
//Apply down-heapify from index 0 to index i
45+
downHeapify(arr,0,i);
46+
}
47+
}
48+
49+
//Down-heapify for min. heap order property
50+
private static void downHeapify(int[] arr, int i, int n)
51+
{
52+
int parentIndex=i;
53+
int leftChildIndex=2*parentIndex+1, rightChildIndex=2*parentIndex+2;
54+
55+
while(leftChildIndex<n)
56+
{
57+
int minIndex=parentIndex;
58+
if(arr[minIndex]>arr[leftChildIndex])
59+
minIndex=leftChildIndex;
60+
61+
if(rightChildIndex<n && arr[minIndex]>arr[rightChildIndex])
62+
minIndex=rightChildIndex;
63+
64+
if(minIndex==parentIndex)
65+
return;
66+
67+
int temp=arr[parentIndex];
68+
arr[parentIndex]=arr[minIndex];
69+
arr[minIndex]=temp;
70+
71+
parentIndex=minIndex;
72+
leftChildIndex=2*parentIndex+1;
73+
rightChildIndex=2*parentIndex+2;
74+
75+
}
76+
}
77+
78+
}

0 commit comments

Comments
 (0)