-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheap_sort.cpp
More file actions
72 lines (62 loc) · 1.24 KB
/
heap_sort.cpp
File metadata and controls
72 lines (62 loc) · 1.24 KB
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
#include<iostream>
#include<stdio.h>
#include<fstream>
#include<chrono>
#define NU 100001
using namespace std;
void heapsort(int arr[],unsigned int N){
if(N==0)
return;
int t;
unsigned int n=N, parent=N/2, index,child;
while(1){
if(parent>0){
t=arr[--parent];
}else {
n--;
if(n==0)
return;
t=arr[n];
arr[n]=arr[0];
}
index= parent;
child= index * 2 + 1;
while(child<n){
if(child +1 <n && arr[child+1] > arr[child])
child++;
if(arr[child] > t){
arr[index] = arr[child];
index = child;
child = index * 2 + 1;
}else {
break;
}
}
arr[index] = t;
}
}
int main(){
//int arr[]={0,7,5,4,3,2,19,201,22};
int arr[NU]={0};
ifstream in("random.txt");
ofstream out("random_out.txt");
if(!in.is_open()){
cout<<"Can not open the random.txt file"<<endl;
exit(1);
}
if(!out.is_open()){
cout<<"Can not open the random.out file"<<endl;
exit(1);
}
auto start =chrono::high_resolution_clock::now();
for(int i=0;i<NU && in>>arr[i];i++)
;
heapsort(arr,NU);
for(int i=0;i<NU;i++)
out<<arr[i]<<" ";
cout<<endl;
auto end = chrono::high_resolution_clock::now();
auto duration = chrono::duration_cast<chrono::microseconds>(end-start).count();
cout<<duration<<endl;
return 0;
}