Created
March 14, 2014 06:51
-
-
Save vo/9543136 to your computer and use it in GitHub Desktop.
Programming Practice: In-Place Heap Sort In C
This file contains hidden or 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 <cstdio> | |
#include <ctime> | |
#include <cstdlib> | |
void make_heap(int * a, size_t n) { | |
for(int heapsize = 0; heapsize < n; ++heapsize) { | |
int n = heapsize; | |
while(n > 0) { | |
int p = (n-1) / 2; | |
if (a[n] > a[p]) { | |
int t = a[n]; | |
a[n] = a[p]; | |
a[p] = t; | |
n = p; | |
} else break; | |
} | |
} | |
} | |
void sort_heap(int * a, size_t n) { | |
int heapsize = n; | |
while(heapsize > 0) { | |
int t = a[0]; | |
a[0] = a[--heapsize]; | |
a[heapsize] = t; | |
int p = 0; | |
int c = 1; | |
while(c < heapsize) { | |
if (c + 1 < heapsize && a[c + 1] > a[c]) c++; | |
if (a[c] > a[p]) { | |
int t = a[p]; | |
a[p] = a[c]; | |
a[c] = t; | |
p = c; | |
c = p * 2 + 1; | |
} else { | |
break; | |
} | |
} | |
} | |
} | |
int main() { | |
int a[30]; | |
srand(time(0)); | |
for (int i = 0; i < 30; ++i) | |
a[i] = rand() % 100; | |
make_heap(a, 30); | |
sort_heap(a, 30); | |
printf("array: "); | |
for(int i = 0; i < 30; ++i) | |
printf("%d ", a[i]); | |
printf("\n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment