• 空间优化的归并排序


    #include <iostream>
    using namespace std;
    
    const int MAXSIZE = 100;
    
    typedef struct SQlist
    {
        int arr[MAXSIZE];
        int Len;
    } SQlist;
    
    bool Init_SQlist(SQlist &space)
    {
        memset(space.arr, 0, sizeof(space.arr));
        space.Len = 0;
        return true;
    }
    
    bool EnSQlist(SQlist &space)
    {
        space.Len = 10;
        for (int i = 0; i < space.Len; ++i)
        {
            space.arr[i] = rand() % 100;
        }
        return true;
    }
    
    bool Merge(SQlist &space, int left, int mid, int right)
    {
        int Length = (right - left) + 1;
        int *pData = new int[Length];
        memset(pData, 0, sizeof(int) * Length);
        int low = left;
        int hig = mid + 1;
        int Index = 0;
        while (low <= mid && hig <= right)
        {
            while (low <= mid && space.arr[low] <= space.arr[hig])
            {
                pData[Index++] = space.arr[low++];
            }
            while (hig <= right && space.arr[hig] < space.arr[low])
            {
                pData[Index++] = space.arr[hig++];
            }
        }
        while (low <= mid)
        {
            pData[Index++] = space.arr[low++];
        }
        while (hig <= right)
        {
            pData[Index++] = space.arr[hig++];
        }
        memcpy(&space.arr[left], pData, sizeof(int) * Length);
        return true;
    }
    
    bool Merger_sort(SQlist &space, int left, int right)
    {
        if (left >= right)
            return true;
        else
        {
            int mid = ((right - left) >> 1) + left;
            Merger_sort(space, left, mid);
            Merger_sort(space, mid + 1, right);
            Merge(space, left, mid, right);
        }
    }
    
    bool print(SQlist &space)
    {
        for (int i = 0; i < space.Len; ++i)
        {
            if (i == 0)
                cout << space.arr[i];
            else
                cout << " " << space.arr[i];
        }
        cout << endl;
        return true;
    }
    
    int main()
    {
        srand(time(NULL));
        SQlist space;
        Init_SQlist(space);
        EnSQlist(space);
        print(space);
        Merger_sort(space, 0, space.Len - 1);
        print(space);
        cin.get();
        return 0;
    }
  • 相关阅读:
    编程心得5
    编程心得2
    心得2
    心得1
    7-11
    7-13
    7-9
    7-8
    7-12
    7-14
  • 原文地址:https://www.cnblogs.com/z2529827226/p/11631376.html
Copyright © 2020-2023  润新知