-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsort2.cpp
More file actions
70 lines (64 loc) · 1.27 KB
/
Copy pathsort2.cpp
File metadata and controls
70 lines (64 loc) · 1.27 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
//
// Created by timruning on 2019/4/9.
//
#include <iostream>
using namespace std;
int split(int *a,int begin,int end){
int i=begin-1;
int j=begin;
int st=a[end];
while (j<end){
if(a[j]<st){
i+=1;
int tmp=a[i];
a[i]=a[j];
a[j]=tmp;
}
j+=1;
}
i+=1;
int tmp=a[i];
a[i]=a[j];
a[j]=tmp;
return i;
}
void qsort2(int *a,int begin,int end){
int i=split(a,begin,end);
if(begin<i){
qsort2(a,begin,i-1);
}
if(i<end){
qsort2(a,i+1,end);
}
}
void adjust_heap(int *a,int begin,int end){
int left=begin*2+1;
int right=begin*2+2;
int max=begin;
if(left<=end && a[left]>a[max]){
max=left;
}
if(right<=end && a[right]>a[max]){
max=right;
}
if (max != begin) {
int tmp = a[max];
a[max] = a[begin];
a[begin] = tmp;
adjust_heap(a, max, end);
}
}
void build_heap(int *a,int begin,int end){
for(int i=(begin+end)/2;i>=begin;i--){
adjust_heap(a,i,end);
}
}
void heap_sort(int *a,int begin,int end){
build_heap(a,begin,end);
for(int i=end;i>=begin;i--){
adjust_heap(a,begin,i);
int tmp=a[i];
a[i]=a[begin];
a[begin]=tmp;
}
}