Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit b1a2d7e

Browse files
Create Code : In-place heap sort
1 parent 1ee9775 commit b1a2d7e

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
2+
void heapSort(int arr[], int n) {
3+
for(int i=1;i<n;i++){
4+
int childindex=i;
5+
while(childindex>0){
6+
int parentindex=(childindex-1)/2;
7+
if(arr[parentindex]>arr[childindex]){
8+
int temp=arr[parentindex];
9+
arr[parentindex]=arr[childindex];
10+
arr[childindex]=temp;
11+
}
12+
else{
13+
break;
14+
}
15+
childindex=parentindex;
16+
}
17+
}
18+
19+
for(int i=n-1;i>=1;i--){
20+
int ans=arr[0];
21+
arr[0]=arr[i];
22+
arr[i]=ans;
23+
int parentindex=0;
24+
int lci=2*parentindex+1;
25+
int rci=2*parentindex+2;
26+
while(lci<i){
27+
int minIndex=parentindex;
28+
if(arr[minIndex]>arr[lci]){
29+
minIndex=lci;
30+
}
31+
if(rci<i&&arr[minIndex]>arr[rci]){
32+
minIndex=rci;
33+
}
34+
if(minIndex==parentindex){
35+
break;
36+
}
37+
int temp=arr[parentindex];
38+
arr[parentindex]=arr[minIndex];
39+
arr[minIndex]=temp;
40+
parentindex=minIndex;
41+
lci=2*parentindex+1;
42+
rci=2*parentindex+2;
43+
44+
}
45+
}
46+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /