Sorting - heap sort
来源:互联网 发布:淘宝的火麻叶是真的么 编辑:程序博客网 时间:2024/06/07 02:10
#include "stdio.h"#include "string.h"#define MAX_LIST 50typedef 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-betweenvoid 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 swappingvoid 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;}
0 0
- Sorting - heap sort
- Sorting Algorithm-Heap Sort
- Heap Sort
- Heap Sort
- heap sort
- heap sort
- Heap Sort
- heap sort
- heap sort
- heap sort
- Heap-Sort
- Heap-sort
- Heap sort
- Heap Sort
- Heap Sort
- heap sort
- Heap Sort
- Heap Sort
- POJ2406 KMP next数组妙用
- HDU 1787 GCD Again 【欧拉函数模板】
- 【iOS开发】深入MVC---UITableView的数据源方法封装
- 百度地图、ECharts整合HT for Web网络拓扑图应用
- poj 2923
- Sorting - heap sort
- 有点迷茫
- iOS笔记:第七篇 C语言 数组
- 5-线程范围内共享变量
- 梳理《前目的地》
- poj 3070 Fibonacci 【矩阵快速幂】
- Python线程指南
- Sorting - bubble sort
- Android异步更新UI-线程池-Future-Handler实例分析