• 合并排序


      1)把0~length-1的数组分成左数组和右数组
      2)对左数组和右数组进行迭代排序
      3)将左数组和右数组进行合并,那么生成的整个数组就是有序的数据数组(关键)

    #include <stdio.h>
    #include <assert.h>
    #include <string.h>
    #include <malloc.h>

    void merge(int *array, int start, int middle, int end)
    {
        int left = start;
        int right = middle + 1;
        int length = end - start + 1;
        int *p = malloc(sizeof(int) * length);
        assert(NULL != p);
        int index = 0;
        int i;
        while(index < length)
        {
            while(left <= middle && right <= end)
            {
                if(array[left] <= array[right])
                {
                    p[index] = array[left];
                    left ++;
                    index ++;
                }
                else
                {
                    p[index] = array[right];
                    index ++;
                    right ++;
                }
            }
            while(left <= middle)
            {
                p[index] = array[left];
                left ++;
                index ++;
            }
            while(right <= end)
            {
                p[index] = array[right];
                index ++;
                right ++;
            }
        }
        for(i = 0; i < length; i ++)
            printf("%d,", p[i]);
        printf(" ");
        memmove(array + start, p, length * sizeof(int));
    }

    void _merge_sort(int *array, int start, int end)
    {
        int middle = start + ((end - start) >> 1);
        if(start >= end)
            return;
        _merge_sort(array, start, middle);
        _merge_sort(array, middle + 1, end);
        merge(array, start, middle, end);
    }

    void merge_sort(int *array, int length)
    {
        assert(NULL != array || 0 != length);
        _merge_sort(array, 0, length - 1);
    }


    void test()
    {
        int i;
        int array[10] = {1,3,4,5,8,6,7,9,0,2};
        merge_sort(array, 10);
        for(i = 0; i < 10; i ++)
        {
            printf("%d, ", array[i]);
        }
        printf(" ");
    }

    int main()
    {
        test();
    }

  • 相关阅读:
    VS2008开发的MFC程序,静态连接的方法
    [delphi]参数带有默认值的函数
    __cplusplus的用处
    去掉输入法上的CH和EN
    Linux下Socket的简单使用及最简化封装
    VS2008 _CRT_SECURE_NO_WARNINGS 的问题
    VC:对话框中菜单的使用(WM_INITMENUPOPUP)
    VC:CFindReplaceDialog(非模态对话框、IsWindow()、m_fr、GetFindString())
    献给初学编程者
    VC:状态栏(AfxGetMainWnd()、GetDescendantWindow()、SetPaneInfo()、SetPaneText())
  • 原文地址:https://www.cnblogs.com/chengxuyuandashu/p/3572808.html
Copyright © 2020-2023  润新知