-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeapSort.cpp
More file actions
43 lines (37 loc) · 846 Bytes
/
Copy pathHeapSort.cpp
File metadata and controls
43 lines (37 loc) · 846 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
40
41
42
43
# include<iostream>
# include<vector>
using namespace std;
void Heaptify(vector<int>& arr,int start,int end){
int dad=start;
int son=dad*2+1;
while(son<=end){
if(son+1<=end && arr[son]<arr[son+1]){
son++;
}
if(arr[son]<arr[dad]){
return;
}else{
swap(arr[son],arr[dad]);
dad=son;
son=dad*2+1;
}
}
}
//时间复杂度 O(nlogn);
void HeapSort(vector<int>& arr,int size){
for(int i=size/2-1;i>=0;i--){
Heaptify(arr, i, size-1);
}
for(int i=size-1;i>0;i--){
swap(arr[0],arr[i]);
Heaptify(arr, 0, i-1);
}
}
int main(){
vector<int> arr={1,2,110,2,40,482,93,40,2,20,59,99};
HeapSort(arr,arr.size());
for(int i=0;i<arr.size();i++){
cout<<arr[i]<<" ";
}
return 0;
}