数据结构实验六:内部排序技术

内部排序——快速排序

#include<stdio.h>
#include<stdlib.h>
void myqsort( int *a, int low, int high)
{
     int i,j; 
     int c; 
    c=a[low]; 
    i=low; 
    j=high; 
     while(i<j) 
    { 
         while(a[j]>=c && i<j)--j; 
            a[i]=a[j]; 
         while(a[i]<=c && i<j)++i; 
            a[j]=a[i]; 
    } 
    a[i]=c; 
     if(i- 1>low) myqsort(a,low,i- 1); 
     if(high>i+ 1) myqsort(a,i+ 1,high);
}
int main()
{
     int a[ 30],i;
     for(i= 0;i< 20;i++)
        a[i]=rand()% 50;
     for(i= 0;i< 20;i++)
    printf( " %d  ",a[i]);
    printf( " \n ");
    myqsort(a, 0, 20);
     for(i= 0;i< 20;i++)
    printf( " %d  ",a[i]);
    printf( " \n ");        
}


内部排序——堆排序
#include <stdio.h>
#include <math.h>
#define LEFT(i) ((i)<<1)
#define RIGHT(i) (((i)<<1)+1)
void max_heapify( int a[],  int i,  int heapsize);
void heap_sort( int a[],  int heapsize);
void build_max_heap( int a[],  int heapsize);
void exchange( int *x,  int *y);
// 交换两个数的值
void exchange( int *x,  int *y) 
{
     int temp;
    temp = *x;
    *x = *y;
    *y = temp;
}
// 保持最大堆性质
void max_heapify( int a[],  int i,  int heapsize) 
{    
     int left, right, largerest;
    left = LEFT(i);
    right = RIGHT(i);
     if (left <= heapsize && a[left] > a[i])
    {
        largerest = left;
    }
     else
    {        
        largerest = i;
    }
     if (right <= heapsize && a[right] > a[largerest])
    {
        largerest = right;
    }
     if(largerest != i) 
    {        
        exchange(&a[i], &a[largerest]);
        max_heapify(a, largerest, heapsize);
    }
}
// 建造最大堆
void build_max_heap( int a[],  int heapsize) 
{    
     int i;
     for (i = ( int) ceil(heapsize/ 2); i >=  1 ; i--)
    {
        max_heapify(a, i, heapsize);
    }
}
// 堆排序
void heap_sort( int a[],  int heapsize) 
{    
     int i;
     // build heap
    build_max_heap(a, heapsize);
     while(heapsize >  1)
    {
         // exchange max
        exchange(&a[ 1], &a[heapsize]);
        heapsize--;
        max_heapify(a,  1, heapsize);
    }
}
int main() 
{    
     int a[] = 
    {
         020233819,
         98203803378,
         346849955};
     int array_size =  sizeof(a) / sizeof( int);
     int i, heapsize;
    heapsize = array_size -  1;
    heap_sort(a, heapsize);
     // 打印排序后的数组
     for (i =  1; i <= heapsize ; i++)
    {
        printf( " %d\t ", a[i]);
    }
    printf( " \n ");
    getchar();
     return  0;
}
复制代码

博主ma6174对本博客文章(除转载的)享有版权,未经许可不得用于商业用途。转载请注明出处http://www.cnblogs.com/ma6174/

对文章有啥看法或建议,可以评论或发电子邮件到ma6174@163.com


本文转自ma6174博客园博客,原文链接:http://www.cnblogs.com/ma6174/archive/2012/01/05/2313331.html ,如需转载请自行联系原作者
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值