-
Notifications
You must be signed in to change notification settings - Fork 527
/
heapSort.cpp
101 lines (87 loc) · 1.47 KB
/
heapSort.cpp
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include <iostream>
using namespace std;
int *arr;
int size;
void insert(int index)
{
int parent;
while (index > 1)
{
if (index % 2 == 0)
{
parent = index / 2;
}
else
{
parent = (index - 1) / 2;
}
if (arr[parent] > arr[index])
{
swap(arr[parent], arr[index]);
index = parent;
}
else
{
return;
}
}
}
void create(int size)
{
arr = (int *)malloc((size + 1) * sizeof(int));
arr[0] = 0;
for (int i = 1; i <= size; i++)
{
cin >> arr[i];
}
for (int i = 2; i <= size; i++)
{
insert(i);
}
}
int del(int endindex)
{
int i = 1, j = 2 * i;
int delval = arr[1];
arr[1] = arr[endindex];
arr[endindex] = delval;
while (j > endindex - 1)
{
if (arr[j + 1] < arr[j])
{
j++;
}
if (arr[i] > arr[j])
{
swap(arr[i], arr[j]);
i = j;
j = 2 * i;
}
else
{
break;
}
}
return delval;
}
int main()
{
int size = 0;
cin >> size;
create(size);
for (int i = 1; i <= size; i++)
{
cout << arr[i] << " ";
}
cout << "\n";
cout << arr[1] << "\n";
for (int i = size; i > 1; i--)
{
del(i);
}
for (int i = 1; i < size; i++)
{
cout << arr[i] << " ";
}
return 0;
}