• 归并排序


    #include <stdio.h>
    #include <stdlib.h>
    
    int n;
    
    /*
     * 合并
     */
    void Merge(int *source, int *target, int i, int m, int n)
    {
        int j, k;
        for (j = m + 1, k = i; i <= m && j <= n; k++)
        {
            if (source[i] <= source[j])
            {
                target[k] = source[i++];
            }
            else
            {
                target[k] = source[j++];
            }
        }
        while (i <= m)
        {
            target[k++] = source[i++];
        }
        while (j <= n)
        {
            target[k++] = source[j++];
        }
    }
    
    /* 
     * 归并排序
     */
     void MergeSort(int *source, int *target, int s, int t)
     {
         int m, *temp;
         if (s == t)
         {
             target[s] = source[s];
         }
         else
         {
             temp = (int*) malloc(sizeof(int) * (t - s + 1));
             m = (s + t) / 2;
             MergeSort(source, temp, s, m);
             MergeSort(source, temp, m + 1, t);
             Merge(temp, target, s, m, t);
         }
     }
    
     int main()
     {
         int i;
        int *array;
        printf("请输入数组的大小:");
        scanf("%d", &n);
        array = (int*) malloc(sizeof(int) * n);
        printf("请输入数据(用空格分隔):");
        for (i = 0; i < n; i++)
        {
            scanf("%d", &array[i]);
        }
        MergeSort(array, array, 0, n - 1);
        printf("排序后为:");
        for (i = 0; i < n; i++)
        {
            printf("%d ", array[i]);
        }
        printf("
    ");
     }
  • 相关阅读:
    JCreator的配置
    哈夫曼编码
    最小生成树
    逻辑左移右移与算术左移右移
    原码 反码 补码 移码
    hdu 小希的迷宫
    (二)Qt窗口应用程序Widget
    (一)Qt5模块,QtCreator常用快捷键,命名规范
    if __name__="__main__"
    数据库之sql语句汇总
  • 原文地址:https://www.cnblogs.com/kxzh/p/10920058.html
Copyright © 2020-2023  润新知