- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSort.cpp
More file actions
Latest commit
executable file
·39 lines (35 loc) · 727 Bytes
/
Copy pathSort.cpp
File metadata and controls
executable file
·39 lines (35 loc) · 727 Bytes
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
#include"head.h"
//typedef ListNode *heapType;
intleft(int i){
return (i<<1)+1;//这里注意加上括号,否则优先级会出问题
}
intright(int i){
return ((i+1)<<1);
}
voidswap(int *a,int *b){
*a=*a^*b;
*b=*a^*b;
*a=*a^*b;
}
voidheapIfy(int arr[],int n,int i){
int largest=i;
if(left(i)<n && arr[left(i)]>arr[i])
largest=left(i);
if(right(i)<n && arr[right(i)]>arr[largest])
largest=right(i);
if(i!=largest){
swap(&arr[i],&arr[largest]);
heapIfy(arr,n,largest);
}
}
voidbuildHeap(int arr[],int n){
for(int i=n/2-1;i>=0;--i)
heapIfy(arr,n,i);
}
voidheapSort(int arr[],int n){
buildHeap(arr,n);
for(int i=n-1;i>0;--i){
swap(&arr[0],&arr[i]);
heapIfy(arr,i,0);
}
}