src/headers/heap.h
#include <selection.h> #ifndef HEAPSORT #define HEAPSORT #include <stdlib.h> #include <stdio.h> #include <string.h> char** hsort(unsigned int, char**); void heapify(int, unsigned int, char**); void prnTree(unsigned int, char**); #endif
src/heap.c
#include <heap.h> /** * This is an example of the heap sort. * one thing I never realised in the past is that it's more or less a glorified * bubble it just limits the number of bubble comparisons to log2(n) so very * quick. It does have the advantage of in place sorting. * */ char** hsort(const unsigned int count, char** values) { unsigned int i; char* tmp; while(count>0) { heapify(0, count, values); tmp = values[--count]; values[count] = values[0]; values[0] = tmp; } return values; } void heapify(int index, unsigned int size, char** values) { char* tmp; unsigned int count, child = 2*index + 1; prnTree(size, values); for(count=0;child<size && count<2;child++) { count++; if(child<size) { heapify(child, size, values); if(strcmp(values[child], values[index])>0) { tmp=values[index]; values[index]=values[child]; values[child]=tmp; } } } } void prnTree(unsigned int count, char** values) { unsigned int i; printf("["); for(i=0; i < count; i++) { printf("%s, ", values[i]); } printf("\b\b]\n"); }
No comments:
Post a Comment