-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalgorithm2.cpp
More file actions
76 lines (66 loc) · 1.54 KB
/
Copy pathalgorithm2.cpp
File metadata and controls
76 lines (66 loc) · 1.54 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
73
74
75
76
//
// Created by timruning on 19-4-8.
//
#include <iostream>
using namespace std;
int split(int *a, int begin, int end) {
int i = begin - 1;
int j = begin;
int st = a[end - 1];
while (j < end - 1) {
if (a[j] < st) {
i += 1;
int tmp = a[j];
a[j] = a[i];
a[i] = tmp;
}
j += 1;
}
int tmp = a[i + 1];
a[i + 1] = a[end - 1];
a[end - 1] = tmp;
return i + 1;
}
void qsort(int *a, int begin, int end) {
int position = split(a, begin, end);
if (begin < position)
qsort(a, begin, position);
if (position < end - 1)
qsort(a, position, 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[begin] < a[left]) {
max = left;
}
if (right <= end && a[max] < a[right]) {
max = right;
}
if (max != begin) {
int tmp = a[begin];
a[begin] = a[max];
a[max] = tmp;
adjust_heap(a, max, end);
}
}
void build_heap(int *a, int begin, int end) {
int midel = (begin + end) / 2;
for (int i = midel; i >= begin; i--) {
adjust_heap(a, i, end);
}
}
void heap_sort(int *a, int begin, int end) {
build_heap(a, begin, end);
for (int j = begin; j <= end; ++j) {
cout << " " << a[j];
}
cout << endl;
for (int i = end; i >= begin; i--) {
adjust_heap(a, begin, i);
int tmp = a[i];
a[i] = a[begin];
a[begin] = tmp;
}
}