美文网首页
WEEK#16 Divide and Conquer_Merge

WEEK#16 Divide and Conquer_Merge

作者: DarkKnightRedoc | 来源:发表于2017-09-14 13:44 被阅读0次

Recursive merge sort

Recursively divide the sorting array[0...size] into two parts, (until the array has only 2 entries)
part1 : [0...mid-1]
part2 : [mid...end]
For which on each division was done, size /= 2;
mid = begin + size / 2;
end = begin + size - 1;

Thinking Process

image.png
// operates on the original array, no extra space needed.
// recursively divide the array into two equally-long parts.
// when the array has only one entry(naturally sorted), merge it with another to form a sorted 2-entry array.
// go on merging, until the array is as long as the original one.
void Merge_Sort(vector<int>& Arr,int begin, int mid, int end, int size) {
    int arr1begin = begin;
    int arr2begin = mid;
    int arrend = end;
    if (size > 2) {
        Merge_Sort(Arr, begin, size / 4 + begin, begin + size /2 - 1, size / 2);
        Merge_Sort(Arr, mid, size / 4 + mid, mid + size / 2 - 1, size / 2);
    }
    _Merge(Arr, arr1begin, arr2begin, arrend);
}

Merging

The key in merging two sorted arrays is always choosing the smallest one in the two sorted array, and put that smallest value into a temp array.
This could be done by
1.using two 'pointers' always pointing the smallest value of each array
2.compared the two values that the two pointers are pointing to
3.put the smaller one into the temp array
4.each time a value is put into the temp array, move that pointer.

image.png
// give the array to merge, we see it as two separate sorted arrays (arr1, arr2).
// give the starting index of arr1 and arr2.
// give the ending index of the two merging array.
void _Merge(vector<int>& arr, int arr1start, int arr2start, int arrend) {
    vector<int> temp;
    int arr1index = arr1start;
    int arr2index = arr2start; // array index is the current(not put in composite array yet) smallest element in the corresponding array.
    int CompositeArrIndex = 0;
    
    // if neither array is empty
    while (arr1index < arr2start && arr2index < arrend) {
        if (arr[arr1index] < arr[arr2index]) // the smallest one of the two arraies should be pushed
            temp.push_back(arr[arr1index++]);
        else
            temp.push_back(arr[arr2index++]);
    }

    // if one of the merging arraies' all entries are put in temp array while the other array's are not,
    // put all the entries of the non-empty array into the temp vector.
    while (arr1index < arr2start) { 
        temp.push_back(arr[arr1index++]);
    }
    while (arr2index < arrend) {
        temp.push_back(arr[arr2index++]);
    }

    for (int i = arr1start; i < arrend; i++) // alter the original array
        arr[i] = temp[CompositeArrIndex++];
}

相关文章

网友评论

      本文标题:WEEK#16 Divide and Conquer_Merge

      本文链接:https://www.haomeiwen.com/subject/lbzxsxtx.html