-
Notifications
You must be signed in to change notification settings - Fork 0
/
Heap_sort.cpp
96 lines (94 loc) · 1.36 KB
/
Heap_sort.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
#include<iostream>
#include<vector>
#include<bits/stdc++.h>
using namespace std;
void sortofheap(vector<int> &v,int &n)
{
for(int i=((n/2)-1);i>=0;i--)
{
if(((2*i)+2)<n)
{
if(v[i]>v[(2*i)+1])
{
if(v[i]>v[(2*i)+2])
{
v[i]=v[i];
}
else
{
int temp;
temp= v[i];
v[i]=v[(2*i)+2];
v[(2*i)+2]=temp;
}
}
else
{
if(v[(2*i)+1]>v[(2*i)+2])
{
int temp;
temp= v[i];
v[i]=v[(2*i)+1];
v[(2*i)+1]=temp;
}
else
{
int temp;
temp= v[i];
v[i]=v[(2*i)+2];
v[(2*i)+2]=temp;
}
}
}
else
{
if(v[i]<v[(2*i)+1])
{
int temp;
temp= v[i];
v[i]=v[(2*i)+1];
v[(2*i)+1]=temp;
}
}
}
}
void swapPlusDecrease(vector<int> &v,int &n)
{
while(n>1)
{
int temp;
temp= v[0];
v[0]=v[n-1];
v[n-1]=temp;
n=n-1;
sortofheap(v,n);
}
}
int main()
{
vector<int> v;
int i,flag=1;
cout<<"1)Add More Value?Flag=1 \n2) Otherwise Flag=0."<<endl;
while(flag==1)
{
int x;
cin>>x;
v.push_back(x);
cout<<"Flag=";
cin>>flag;
}
cout<<"STARTING VECTOR: ";
for(i=0;i<v.size();i++)
{
cout<<v[i]<<" ";
}
int n=v.size();
sortofheap(v,n);
swapPlusDecrease(v,n);
cout<<"SORTED VECTOR:";
for(i=0;i<v.size();i++)
{
cout<<v[i]<<" ";
}
return 0;
}