[英]Recursive top down mergesort
我試圖繞過合並排序算法一部分的遞歸排序函數。 這是我的代碼,我幾乎可以肯定是正確的(在線課程之后)。
private static void sort(Comparable[] a, Comparable[] aux, int low, int high) {
if (high <= low) return;
int mid = low + (high - low) / 2;
sort (a, aux, low, mid);
sort (a, aux, mid+1, high);
merge(a, aux, low, mid, high);
}
我知道mergesort的作用-將每個子數組分解為2個較小的子數組,重復此操作直到子數組的長度為1(並按定義排序),然后合並。 但是,這種排序函數用來完成此操作的實際方法對我來說很難。 也許是因為我不習慣使用遞歸函數,但是我想知道是否有人可以闡明操作的順序以及第一次合並時的參數是什么。
例如,當它到達對sort(a,aux,low,mid)的FIRST遞歸調用時,它是否中斷操作並且不繼續進行第二個排序和下面的合並功能,而是立即使用新參數再次調用sort? 在這種情況下,何時調用第二次排序; 排序(a,aux,mid + 1,high); 發生?
謝謝你的幫助。 這是我第一次在這里發布,如果有任何格式問題,請告訴我。
當它到達對sort(a,aux,low,mid)的FIRST遞歸調用時,它會中斷操作,而不繼續進行第二個排序和下面的合並功能,而是立即使用新參數再次調用sort嗎?
在這種情況下,何時調用第二次排序; 排序(a,aux,mid + 1,high); 發生?
注釋說明每個步驟,以防萬一您一無所獲:
if (high <= low) return; // if your high and low numbers are the same then this part of the loop is finished and it will start going back up
int mid = low + (high - low) / 2;//sets mid
sort (a, aux, low, mid);//recursively calls itself so that it will eventually hit the first if. This handles from low to mid
sort (a, aux, mid+1, high); //this handles from mid+1 to high
merge(a, aux, low, mid, high); //This is where the merge starts.
我發現運行一個簡單的示例並在筆和紙上遍歷整個示例非常有幫助,如果您真的很難的話。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.