Sorting - heap sort
Posted 小马识图
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Sorting - heap sort相关的知识,希望对你有一定的参考价值。
#include "stdio.h"
#include "string.h"
#define MAX_LIST 50
typedef struct _SqList
int data[MAX_LIST];
int length;
SqList;
void swap( SqList* L, unsigned index1, unsigned index2 )
if( index1 >= L->length || index2 >= L->length ) return;
if( index1 == index2 ) return;
L->data[index1] = L->data[index1] ^ L->data[index2];
L->data[index2] = L->data[index1] ^ L->data[index2];
L->data[index1] = L->data[index1] ^ L->data[index2];
enum HEAP_ADJUST_METHOD HA1, HA2 ;
//heap adjust method 1: recursive invoking HeapAdjust
//with a swapping in-between
void HeapAdjust1(SqList* L, int s, int m)
int start = s;
int l_child = 2*start + 1;
int r_child = l_child + 1;
if( m < l_child ) return;
int j = l_child;
if( m >= r_child && L->data[r_child] > L->data[l_child] ) j = r_child;
if( L->data[j] > L->data[start] )
swap(L, start, j);
HeapAdjust1(L, j, m );
//heap adjust method 2: no swapping
void HeapAdjust2(SqList* L, int s, int m)
int j;
int temp = L->data[s];
for( j = 2*s + 1; j <=m; j*=2 )
if( j < m && L->data[j] < L->data[j+1] )
++j;
if( temp >= L->data[j] ) break;
L->data[s] = L->data[j];
s = j;
L->data[s] = temp;
void HeapAdjust( SqList* L, int s, int m, HEAP_ADJUST_METHOD ha )
if( ha == HA1 )
HeapAdjust1( L, s, m );
else
HeapAdjust2( L, s, m );
void HeapSort( SqList* L, HEAP_ADJUST_METHOD ha )
int i;
for( i = L->length/2-1; i>-1; i--)
HeapAdjust( L, i, L->length-1, ha);
for( i=L->length-1; i>0;i--)
swap(L, 0, i);
HeapAdjust(L, 0, i-1, ha);
int main()
SqList d;
int intarr[] = 1,10,23,48,65,31,-21,9,88,100;
memcpy( d.data, intarr, sizeof(intarr));
d.length = sizeof(intarr)/sizeof(int);
printf("Original array:\\n");
int index = 0;
for( ; index < d.length; index++ )
printf(" %d", d.data[index] );
printf("\\nHeap sort...\\n");
HeapSort( &d, HA2 );
for( index = 0; index < d.length; index++ )
printf(" %d", d.data[index] );
printf("\\n");
return 0;
以上是关于Sorting - heap sort的主要内容,如果未能解决你的问题,请参考以下文章
Jquery datatable Date Column Sorting not sorting based on recent Dates