簡體   English   中英

如何在合並排序中找到最低和最高

[英]How to find the low & high in Merge Sort

我對合並排序算法有基本的了解。 但是由於某些原因,我無法確定低值和高值的來源。 這是我正在使用的合並代碼。

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--;
    }
}

讓我通過注釋您的代碼進行解釋:

//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--;
    }
}

基本上,低,中和高是您要查看的數組“ a”的邊界。 “ a”可以更大。 例如:

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

在這里,您正在排序a的前半部分。

編輯:您的函數合並數組。 主要的合並排序功能可拆分數組。 這將是:

void merge_sort(int a[], int lo, int hi) {
   if (low >= hi)
      return; //Nothing to sort
   int mid = (lo+hi)/2; //The guy between lo and hi.
   merge_sort(a,lo, mid); //sort the left
   merge_sort(a, mid, hi); //sort the right
   practiceMerge(a, lo, mid, hi); //This merges the array
}

要理解(不只是復制粘貼!),請這樣考慮:merge_sort對數組的一部分而不是整個數組進行排序,僅對lo和hi之間的位進行排序。 為此,它先排序一半,然后再排序另一半。 然后它將結果合並到數組中。 因此,在merge_sort內部,根據參數計算“ hi”和“ lo”。 現在,您(用戶)可能希望將數組從0到結尾或從第10到第99個索引排序。 那是你的選擇。 這就是您傳遞給調用的參數。

void main() {
   //Bla bla bla
   merge_sort(songs, 89, 250); //Only sort some songs
}

將此視為一個黑匣子。 您用一些參數調用它,盒子完成它的任務。 因為盒子是使用自己的,所以它知道如何調用自己(即知道如何計算低,高和中),但是遞歸中的初始調用是您作為用戶的責任。

PS:我覺得我不太清楚...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM