00001 #include "heapsort.h"
00002
00003
00004
00005 static void add_to_sort_heap(int *heap,
00006 float *sort_values,
00007 int index,
00008 int heap_tail);
00009
00010 static int get_top_of_heap_index(int *heap,
00011 float *sort_values,
00012 int heap_tail);
00013
00014
00015
00016
00017
00018 void
00019 heapsort(int *sort_index,
00020 float *sort_values,
00021 int nelem)
00022 {
00023
00024
00025
00026
00027
00028 int i;
00029
00030
00031
00032 for(i = 1; i <= nelem; i++)
00033 add_to_sort_heap(sort_index, sort_values, i, i);
00034
00035
00036
00037
00038
00039
00040 for(i = nelem; i >= 1; i--)
00041 sort_index[i] = get_top_of_heap_index(sort_index, sort_values, i);
00042 }
00043
00044
00045 static void
00046 add_to_sort_heap(int *heap,
00047 float *sort_values,
00048 int index,
00049 int heap_tail)
00050 {
00051
00052
00053
00054
00055 unsigned int ifrom, ito;
00056 int temp;
00057
00058 heap[heap_tail] = index;
00059 ifrom = heap_tail;
00060 ito = ifrom / 2;
00061
00062 while(ito >= 1 && sort_values[heap[ifrom]] < sort_values[heap[ito]])
00063 {
00064 temp = heap[ito];
00065 heap[ito] = heap[ifrom];
00066 heap[ifrom] = temp;
00067 ifrom = ito;
00068 ito = ifrom / 2;
00069 }
00070 }
00071
00072
00073 static int
00074 get_top_of_heap_index(int *heap,
00075 float *sort_values,
00076 int heap_tail)
00077 {
00078
00079
00080
00081
00082
00083 int index_of_smallest, temp;
00084 unsigned int ifrom, ito, heap_end;
00085
00086 index_of_smallest = heap[1];
00087 heap[1] = heap[heap_tail];
00088 heap_end = heap_tail - 1;
00089 ifrom = 1;
00090 ito = 2 * ifrom;
00091
00092 while(ito <= heap_end)
00093 {
00094 if(sort_values[heap[ito + 1]] < sort_values[heap[ito]])
00095 ito++;
00096
00097 if(sort_values[heap[ito]] > sort_values[heap[ifrom]])
00098 break;
00099
00100 temp = heap[ito];
00101 heap[ito] = heap[ifrom];
00102 heap[ifrom] = temp;
00103 ifrom = ito;
00104 ito = 2 * ifrom;
00105 }
00106
00107 return (index_of_smallest);
00108 }