• 归并排序


     1 #include <stdio.h>
     2 #include <malloc.h>
     3 
     4 typedef int ElementType;
     5 
     6 void _Merge(ElementType *Array,ElementType *TmpArray,int LeftStart,int RightStart,int RightEnd)
     7 {
     8     int i;
     9     int ArrayLen = RightEnd - LeftStart + 1;
    10     int LeftEnd = RightStart - 1;
    11     int TmpArrayEnd = LeftStart;
    12     
    13     while(LeftStart <= LeftEnd && RightStart <= RightEnd)
    14     {
    15         if(Array[LeftStart] <= Array[RightStart])
    16         {
    17             TmpArray[TmpArrayEnd++] = Array[LeftStart++];
    18         }
    19         else
    20         {
    21             TmpArray[TmpArrayEnd++] = Array[RightStart++];
    22         }
    23     }
    24     
    25     while(LeftStart <= LeftEnd)
    26     {
    27         TmpArray[TmpArrayEnd++] = Array[LeftStart++];
    28     }
    29     while(RightStart <= RightEnd)
    30     {
    31         TmpArray[TmpArrayEnd++] = Array[RightStart++];
    32     }
    33     
    34     //copy TmpArray back to Array
    35     for(i = 0;i < ArrayLen;i ++,RightEnd --)
    36     {
    37         Array[RightEnd] = TmpArray[RightEnd];
    38     }
    39 }
    40 
    41 void _MSort(ElementType *Array,ElementType *TmpArray,int Left,int Right)
    42 {
    43     int Center;
    44     
    45     if(Left < Right)
    46     {
    47         Center = (Left + Right) / 2;
    48         _MSort(Array,TmpArray,Left,Center);
    49         _MSort(Array,TmpArray,Center+1,Right);
    50         _Merge(Array,TmpArray,Left,Center+1,Right);
    51     }
    52 }
    53 
    54 void MergeSort(ElementType *Array,int ArrayLen)
    55 {
    56     ElementType *TmpArray;
    57     
    58     TmpArray = malloc(ArrayLen * sizeof(ElementType));
    59     
    60     _MSort(Array,TmpArray,0,ArrayLen-1);
    61     free(TmpArray);
    62 }
    63 
    64 int main()
    65 {
    66     ElementType TestArray[10] = {9,2,4,1,2,5,9,3,7};
    67     MergeSort(TestArray,10);
    68     int i;
    69     for(i = 0;i < 10;i ++)
    70     {
    71         printf("%d ",TestArray[i]);
    72     }
    73     printf("
    ");
    74     return 0;
    75 }
  • 相关阅读:
    mysql无法启动的结果问题解决
    pm2日志管理插件
    运维常用shell脚本之日志清理
    Centos7.x for aarch64 下载地址
    linux下使用openssl生成https的crt和key证书
    rsync+inotify百万级文件实时同步
    nginx访问url内容过滤
    docker-compose部署zabbix4.2.5
    postgresql从库提升为主库
    Nginx+keepalived 高可用双机热备(主从模式)
  • 原文地址:https://www.cnblogs.com/Asurudo/p/9427434.html
Copyright © 2020-2023  润新知