2013-02-20 91 views
0

程序編譯並正常運行。從輸入文件讀取整數列表,但輸出顯示這些數字而沒有任何更改。我期望他們從最小到最大排序。作爲參考,我試圖實現一個類似於維基百科上的例子的版本。我在這個C++ mergesort中做了什麼錯誤?

// arrA contains items to sort; arrB is an array to work in 
void mergesort(int *arrA, int *arrB, int first, int last) { 

    // a 1 element array is already sorted 
    // make increasingly longer sorted lists 
    for (int width = 1; width < last; width = 2 * width) { 
     // arrA is made up of 1 or more sorted lists of size width   
     for (int i = 0; i < last; i += 2 * width) { 
      // merge two sorted lists 
      // or copy arrA to arrB if arrA is full 
      merge(arrA, i, min(i+width, last), min (i + 2 * width, 
        last), arrB); 
     } // end for 
     // now arrB is full of sorted lists of size 2* width 
     // copy arrB into arrA for next iteration 
     copy(arrB, arrA, last); 
    } // end for  
} // end mergesort 


void merge(int *arrA, int iLeft, int iRight, int iEnd, int *arrB) { 
    int i0 = iLeft, i1 = iRight; 

    // while either list contains integers 
    for (int j = iLeft; j < iEnd; j++) { 
     // if 1st integer in left list is <= 1st integer of right list 
     if (i0 < iRight && (i1 >= iEnd || arrA[i0] <= arrA[i1])) { 
      arrB[j] = arrA[i0]; 
      i0 += 1; 
     } // end if 
     else { // right head > left head 
      arrB[j] = arrA[i0]; 
      i0 += 1; 
     } // end else   
    } // end for 
} // end merge 


void copy(int *origin, int *destination, int size) { 
    for (int i = 0; i < size; i++) { 
     destination[i] = origin[i]; 
    } // end for 
} // end copy 

int main() { 
    int size = 0, first = 0, *arrA, *arrB; 

    // input data 
    read(&arrA, &arrB, &size); 

    // sorting 
    mergesort(arrA, arrB, first, size); 

    // output 
    write(arrA, first, size); 

    // cleanup 
    delete [] arrA; 
    delete [] arrB; 
} 

輸入

33 9 -2 

輸出

33 9 -2 
+0

也許你可以舉一個你得到的輸入和輸出的例子嗎? – 2013-02-20 17:33:51

+0

不變的整數列表,但是,如果有幫助,我會補充一點。 – Justin 2013-02-20 17:34:53

+0

那麼,如果我寫的答案沒有幫助,那麼是的。 – 2013-02-20 17:36:04

回答

5

我沒有在你的代碼看上去很深刻,但這種if語句似乎有點過我:

if (i0 < iRight && (i1 >= iEnd || arrA[i0] <= arrA[i1])) { 
     arrB[j] = arrA[i0]; 
     i0 += 1; 
    } // end if 
    else { // right head > left head 
     arrB[j] = arrA[i0]; 
     i0 += 1; 
    } // end else 

當然,一對if/else c缺點是你在if和else的部分做了不同的事情。據我所知,這裏是相同的。

+0

這是魔術。非常感謝你。 – Justin 2013-02-20 17:38:06

相關問題