zoukankan      html  css  js  c++  java
  • 归并排序

    代码如下:

    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    #define N 50000
    
    void merge(int [],int,int,int);//归并排序数组合并函数声明
    void mergesort(int [],int,int);//归并排序数组排序函数声明
    
    //主函数
    int  main()
    {
        int i,a1[N];
        double t1,t2,t3,t4;
            
        for(i=0;i<N;i++)
        {
            a1[i]=rand()%N;
        }
        
    
        //归并排序N个随机数字所用的时间
        t2=clock();
        mergesort(a1,0,N-1);
        t2=clock()-t2;
        
        /*排好序的结果*/
        for(i=0;i<N-1;i++)
        { 
            printf("%4d
    ",a1[i]);
        }
    
        printf("
    归并排序%d个随机数字所用时间为:%f毫秒
    ",N,(double)t2);
        getch();
        return 1;
    }
    
    
    
    //归并排序
    //归并排序合并数组函数的具体实现
    void merge(int a[],int low,int middle,int high)
    {
        int h,i,j,k;
        int b[N];
        h=low;
        i=low;
        j=middle+1;
    
        while(h<=middle&&j<=high)
        {
            if(a[h]<=a[j])
            {
                b[i]=a[h];
                h++;
            }
            else
            { 
                b[i]=a[j];
                j++;
            }
            i++;
        }
        if(h>middle)
        for(k=j;k<=high;k++)
        {
            b[i]=a[k];
            i++; 
        }
        else
        {
            for(k=h;k<=middle;k++)
            { 
                b[i]=a[k];
                i++;
            }
        }
        for(k=low;k<=high;k++)
        {
            a[k]=b[k];
        }
    }
    
    //归并排序函数的具体实现
    void mergesort(int a[],int low,int high)
    {
        int middle;
        if(low<high)
        {
            middle=(low+high)/2;
            mergesort(a,low,middle);
            mergesort(a,middle+1,high);
            merge(a,low,middle,high);
        }
    }

    完。

  • 相关阅读:
    maven
    Web开发入门
    网络编程之Socket
    自定义注解与设计模式
    数据交换格式与SpringIOC底层实现
    caffe笔记之例程学习(二)
    caffe笔记之例程学习
    ubuntu14.04 caffe环境配置
    Pattern Recognition (Fourth Edition)读书笔记之mvnrnd函数
    MIF文件编写小技巧
  • 原文地址:https://www.cnblogs.com/CoolSummer/p/3459689.html
Copyright © 2011-2022 走看看