Sorting algorithm Summary - merge sort (C ++ to achieve)

1, merge sort (merge sort)

Works merge operation are as follows:

1: space applications, it has the size of two sorting sequences and the space for storing the combined sequence;

2: two setting pointers , respectively, the first position of the starting position of the two sorted sequence;

3: Comparison of two pointer points to an element, the selected element into a relatively small space to merge, and move the cursor to the next position;

Repeat step 3 until the pointer beyond the end of the sequence a. All remaining elements of another sequence directly copied to the merging of the sequence.

  Merge sort efficiency is relatively high, set the number of columns of length N, the number of columns separated into decimal columns to a total of logN steps, each step is a combined ordered sequence of processes, the time complexity can be referred to as O (N), so merge sort time complexity is O (NlogN).

class Solution
{
public:
    void mergeSort(int* data, int length)
    {
        if (data == nullptr || length <= 0)
            return;

        int* copy = new int[length];
        for (int i = 0; i < length; ++i)
            copy[i] = data[i];

        mergesort(data, copy, 0, length - 1);

        delete[] copy;
    }

private:
    void mergesort(int* data, int* copy, int start, int end)
    {
        if (start == end)
            return;

        if (start < end)
        {
            int mid = ((end - start) >> 1) + start;
            mergesort (Data, Copy, Start, MID);         // left ordered 
            mergesort (Data, Copy, MID + . 1 , End);     // the right order 
            mergedata (Data, Copy, Start, MID, End);         // The two the number of ordered columns merger

        }
    }
    void mergedata(int* data, int* copy, int start, int mid, int end)
    {
        int i = start;
        int j = mid + 1;
        int k = 0;

        while (i <= mid && j <= end)
        {
            if (data[i] < data[j])
                copy[k++] = data[i++];
            else
                copy[k++] = data[j++];
        }

        while (i <= mid)
            copy[k++] = data[i++];
        while (j <= end)
            copy[k++] = data[j++];
        for (int i = 0; i < k; ++i)
            data[start + i] = copy[i];
    }
};

Test Case:

void test()
{
    int data[] = { 9, 8, 7, 8, 8, 3, 2, 1 };
    //int data[] = { 1 };
    int length = sizeof(data) / sizeof(int);

    Solution M;
    M.mergeSort(data, length);

    for (int i = 0; i < length; ++i)
        cout << data[i] << "  ";
    cout << endl;
}

Guess you like

Origin www.cnblogs.com/wyr-123-wky/p/11090124.html