-
Notifications
You must be signed in to change notification settings - Fork 0
/
堆排序.txt
62 lines (58 loc) · 1.05 KB
/
堆排序.txt
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
#include<vector>
#include<sstream>
#include<iostream>
using namespace std;
void MaxHeapify(vector<int>& data, int i, int start, int end)
{
int leftchild = 2 * i + 1;
int rightchild = 2 * i + 2;
int largest;
if (leftchild <= end && data[leftchild] > data[i])
{
largest = leftchild;
}
else
largest = i;
if (rightchild <= end && data[rightchild] > data[largest])
largest = rightchild;
if (largest != i)
{
swap(data[i], data[largest]);
MaxHeapify(data, largest, start, end);
}
}
void BuildMaxHeap(vector<int>& data, int length)
{
for (int i = length / 2 - 1; i >= 0; i--)
{
MaxHeapify(data, i, 0, length - 1);
}
}
void heapSort(vector<int>& data, int length)
{
BuildMaxHeap(data, length);
for (int i = length - 1; i >= 1; i--)
{
swap(data[0], data[i]);
MaxHeapify(data, 0, 0, i - 1);
}
}
int main()
{
stringstream ss;
string str;
int temp;
vector<int> data;
getline(cin, str);
ss << str;
while (ss >> temp)
{
data.push_back(temp);
}
heapSort(data,(int)data.size());
for (auto ele : data)
{
cout << ele << " ";
}
cout << endl;
}