关于堆排序
数据结构基础的确很烂,想想还是多写写代码会好些,堆排序是选择排序的深化,是一种树型结构的排序.(老鸟不要笑我阿,小弟学习中)代码如下,gcc编译通过.
下载: HeapSort.c
- #include"stdio.h"
- #define MAX_SIZE 100
- void HeapAdjust(int R[],int s,int m);
- void HeapSort(int R[],int n);
- void HeapAdjust(int R[],int s,int m)
- {
- int j;
- R[0] = R[s];
- for(j = 2 * s; j <= m ; j *= 2)
- {
- if(j < m && R[j] < R[j+1])
- j++;/*j为左右子树中较大的下标*/
- if(R[0] >= R[j])
- break;/*j<=m-1和temp>=的排序的元素,均为结束条件*/
- R[s] = R[j];
- s = j;
- }
- R[s] = R[0];
- }
- void HeapSort(int R[],int n)
- {
- int i;
- for(i = n/2; i > 0; i--)
- HeapAdjust(R,i,n);/*建立大顶堆*/
- for(i = n; i > 1; i--)
- {
- R[0] = R[1];
- R[1] = R[i];
- R[i] = R[0];/*交换第一个和最后一个元素*/
- HeapAdjust(R,1,i-1);
- }
- }
- int main(void)
- {
- int i,a[MAX_SIZE],n;
- printf("请输入要排序的个数N\n");
- scanf("%d",&n);
- printf("请输入排序的数字(N个)\n");
- for(i = 1; i <=n ; i++)
- scanf("%d",&a[i]);
- HeapSort(a,n);
- printf("利用堆排序的结果为:\n");
- for( i = 1; i <= n; i++)
- printf("%3d",a[i]);
- printf("\n");
- return 0;
- }
阅读(1422 次)