Created
April 13, 2011 23:42
-
-
Save radiofreejohn/918665 to your computer and use it in GitHub Desktop.
a very janky indirect heap sort adapted from the C++ version in Sedgewick's Algorithms 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 <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include "numbers.h" //https://gist.github.com/911872 | |
void insert(int,int); | |
int hremove(void); | |
int hEmpty(void); | |
void swapsies(int*, int, int); //anandkunal knows | |
int *indirectHeapSort(struct numbers*); //heapsort conflicts with stdlib | |
int *heapArray; | |
int *pArray; | |
int *pInfo; | |
int N=0; | |
int main() | |
{ | |
int i; | |
int *values; | |
struct numbers vals = generateRandoms(2, 11); | |
// values will return indicies of vals->values in sorted order | |
values = indirectHeapSort(&vals); | |
for (i=0; i<vals.size; i++) | |
printf("%d ", vals.values[values[i]]); | |
printf("\n"); | |
return 0; | |
} | |
void insert(int pidx, int item) | |
{ | |
heapArray[++N] = item; | |
pInfo[N] = pidx; | |
pArray[pidx] = N; | |
} | |
int hremove(void) | |
{ | |
int j, min = 1; | |
for (j = 2; j <= N; j++) | |
if (heapArray[j] < heapArray[min]) min = j; | |
swapsies(heapArray, min, N); | |
swapsies(pInfo, min, N); | |
pArray[pInfo[min]] = min; | |
return pInfo[N--]; | |
} | |
int hEmpty(void) | |
{ | |
return (N <= 0); | |
} | |
void swapsies(int *a, int t, int s) | |
{ | |
int temp; | |
temp = a[t]; | |
a[t] = a[s]; | |
a[s] = temp; | |
} | |
int *indirectHeapSort(struct numbers *vals) | |
{ | |
heapArray = malloc(vals->size * sizeof(int) + 1); | |
pArray = malloc(vals->size * sizeof(int) + 1); | |
pInfo = malloc(vals->size * sizeof(int) + 1); | |
int *scratchArray = malloc(vals->size * sizeof(int)); | |
int i=0; | |
for (i = 0; i < vals->size; i++) | |
insert(i, vals->values[i]); | |
for (i = 0; i < vals->size; i++) | |
scratchArray[i] = hremove(); | |
free(heapArray); | |
return scratchArray; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment