Last active
April 23, 2018 02:54
-
-
Save Darkborderman/5030177d231d54e13e018e9b75e411b9 to your computer and use it in GitHub Desktop.
A heap sort algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
void heapify(int* data,int size,int i); | |
void heapSort(int* data,int size); | |
void swap(int* data, int i,int j); | |
int main() | |
{ | |
int input[10]={1,0,2,8,3,6,7,9,4,5}; | |
int size=10; | |
heapSort(input, size); | |
for(int i=0;i<=size-1;i++) cout<<input[i]<<" "; | |
return 0; | |
} | |
void heapify(int* data, int size, int i) | |
{ | |
int largest=i; | |
int l=2*i+1; | |
int r=2*i+2; | |
if(l<size&&data[l]>data[largest]) largest=l; | |
if(r<size&&data[r]>data[largest]) largest=r; | |
if (largest != i) | |
{ | |
swap(data[i],data[largest]); | |
heapify(data,size,largest); | |
} | |
} | |
void heapSort(int* data, int size) | |
{ | |
for(int i=(size/2)-1;i>=0;i--) heapify(data, size, i); | |
for(int i=size-1;i>=0;i--) | |
{ | |
swap(data[0],data[i]); | |
heapify(data,i,0); | |
} | |
} | |
void swap(int* data,int i,int j) | |
{ | |
int temp=data[i]; | |
data[i]=data[j]; | |
data[j]=temp; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment