-
Notifications
You must be signed in to change notification settings - Fork 0
/
HeapSort.cpp
72 lines (60 loc) · 1.02 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
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
void heapsort(int*,int);
void heapify(int*,int,int);
int main()
{
int n;
cout<<"Enter number of elements: "<<endl;
cin>>n;
int* arr = (int *)malloc(n * sizeof(int));
cout<<"Enter the elements of array."<<endl;
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
heapsort(arr,n);
cout<<"\nThe sorted Array is "<<endl;
for(int i=0;i<n;i++)
{
cout<<arr[i]<<" ";
}
}
void heapsort(int* x,int n)
{
int temp;
for (int i=n/2-1;i>=0;i--)
{
heapify(x, n, i);
}
for (int i=n-1; i>=0; i--)
{
temp = x[0];
x[0] = x[i];
x[i] = temp;
heapify(x, i, 0);
}
}
void heapify(int *x,int n,int t)
{
int largest = t,temp;
int l = 2*t+1;
int r = 2*t+2;
if ((l<n)&&(x[l]>x[largest]))
{
largest = l;
}
if ((r<n)&&(x[r]>x[largest]))
{
largest = r;
}
if (largest!=t)
{
temp = x[t];
x[t] = x[largest];
x[largest] = temp;
heapify(x, n, largest);
}
}