如何找到低和低合并排序高

时间:2016-02-07 23:11:54

标签: c++ algorithm mergesort

我对Merge Sort算法有基本的了解。但出于某种原因,我无法绕过低价和高价的来源。这是我为Merge工作的代码。

void practiceMerge(int a[], int low, int mid, int high)
{
    int b[10000];
    int i = low, j = mid + 1, k = 0;

    while (i <= mid && j <= high) {
        if (a[i] <= a[j])
            b[k++] = a[i++];
        else
            b[k++] = a[j++];
    }
    while (i <= mid)
    b[k++] = a[i++];

    while (j <= high)
        b[k++] = a[j++];

    k--;
    while (k >= 0) {
        a[low + k] = b[k];
        k--;
    }
}

1 个答案:

答案 0 :(得分:1)

让我通过评论您的代码来解释:

toStartOf

基本上,低,中,高是阵列的边界&#34; a&#34;你在看。 &#34;&#34;可能更大。例如:

TextView

在这里,您要对a的前半部分进行排序。

编辑: 您的函数合并数组。主合并排序函数拆分数组。它将是:

//Sort an array a from its index low to its index high by merging two
//subarrays of a that go from low to mid and mid to high.
void practiceMerge(int a[], int low, int mid, int high)
{
    int b[10000]; //Buffer
    int i = low; //starting index in first sub array
    int j = mid + 1; //starting index in second sub array
    int k = 0; //starting index in buffer

    //While you DO NOT go beyond the limit of the first subarray
    //nor the second
    while (i <= mid && j <= high) {
        if (a[i] <= a[j])
            //Put the value of the first subarray, and move 
            b[k++] = a[i++];
        else
            //Put the value of the first subarray, and move
            b[k++] = a[j++];
    }
    //Finish copying first subarray if not done yet
    while (i <= mid)
    b[k++] = a[i++];
    //Finish copying second subarray if not done yet
    while (j <= high)
        b[k++] = a[j++];

    //Copy buffer to array a
    k--;
    while (k >= 0) {
        a[low + k] = b[k];
        k--;
    }
}

要理解(不要只是复制粘贴!)这样想:merge_sort对一大块数组进行排序,而不是整个数组,只是lo和hi之间的位。为了做到这一点,它分为一半,然后另一半。然后它将该结果合并到数组中。因此,在merge_sort里面,&#34; hi&#34;和&#34; lo&#34;从参数计算。现在,您,用户,可能希望将数组从0到结尾,或从第10到第99个索引进行排序。这是你的选择。这就是您传递给电话的参数。

a =  3 2 1 5 6 7 0 1 
low = 0
mid = 2
high = 4

把它想象成一个黑盒子。你用一些参数调用它,盒子做它的事情。因为盒子使用它自己,它知道如何调用自身(即它知道如何计算低,高和中)但是递归中的初始调用是你作为用户的责任。

P.S。:我觉得我不是很清楚...