2016-04-25 152 views
0

這裏是我使用C++的合併排序算法的代碼,它實際上編譯,但它沒有給出正確的結果,我經歷了代碼幾次,但邏輯似乎對我來說如此,如果有人可以幫助我,這將是真正偉大:合併排序代碼C++

#include <iostream> 

using namespace std; 

void merge(int left[], int right[], int a[], int L_lengnth, int R_length){ 
    int l = L_lengnth; 
    int r = R_length; 

    int i = 0; 
    int j = 0; 
    int k = 0; 

    while(i<l && j<r){ 
     if(left[i]<right[j]){ 
      a[k]=left[i]; 
      i++; 
     } 
     else 
     { 
      a[k]=right[j]; 
      j++; 
     } 
     k++; 
    } 
    while(i<l){ 
     a[k]=left[i]; 
      i++; 
      k++; 
    } 
    while(j<r){ 
     a[k] = right[j]; 
      j++; 
      k++; 
    } 

} 
void mergeSort(int A[], int A_lenght){ 
    int n = A_lenght; 
    if(n<2){ 
     return; 
    } 
    int mid = n/2; 
    int left[mid]; 
    int right[n-mid]; 
    for(int i=0; i<mid-1; i++){ 
     left[i] = A[i]; 
    } 
    for(int i=mid; i<n-1; i++){ 
     right[i-mid] = A[i]; 
    } 
    mergeSort(left, mid); 
    mergeSort(right, n-mid); 
    merge(left,right,A,mid,n-mid); 
} 
int main() 
{ 
    int Array[11]={1,9,5,6,7,4,3,8,99,81,56}; 

    cout<<"unsorted"<<endl; 
    for(int i=0; i<11; i++){ 
     cout<<Array[i]<<" "; 
    } 
    cout<<endl; 

    mergeSort(Array,11); 

    cout<<"sorted"<<endl; 
    for(int i=0; i<11; i++){ 
     cout<<Array[i]<<" "; 
    } 

    return 0; 
} 

** here is a screenshot of the result after compilation **

+5

'int數組[N];' - 這是不合法的C++語法。其次,爲什麼不用一組已知的數字,4或5個數字進行測試,而不是要求輸入?這樣我們就可以看到你正在測試的數據,其次,你不會每次都無意中使用不同的數字。 'int main(){int data [] = {5,2,13,12,4}; mergeSort(data,5);}'類似的東西。 – PaulMcKenzie

+0

嘗試單步執行調試器中的代碼。這通常是比閱讀代碼更容易診斷錯誤的方法。 –

+0

請不要提示輸入。硬編碼輸入,然後告訴我們你得到了什麼輸出,以及你想要什麼。現在,這不是[mcve] –

回答

0

你可以用這個試試..

void mergeSort(int nElems) 
{ 
double *workSpace = new double [nElems]; 
recMergeSort(workSpace, 0, nElems-1); 
delete [] workSpace; 
} 
void recMergeSort(double workSpace[], int lowerBounds, int upperBound) 
{ 
if (lowerBound == upperBound) 
return; { else 


int mid = (lowerBound + upperBound)/2; 
recMergeSort(workSpace, lowerBound, mid); 
recMergeSort(workspace, mid+1, upperBound); 
merge(workSpace, lowerBound, mid+1, upperBound); 
} 
} 
void merge(double workSpace[],int lowPtr,int hightPtr,int upperBound){ 
int j = 0; 
int lowerBound = lowPtr; 
int mid = highPtr-1; 
int n = upperBound-lowerBound+1; 

while (lowPtr <= mid && highPtr <= upperBound) 
if (theArray[lowPtr] < theArray[highPtr]) 
workSpace[j++] = theArray[lowPtr++]; 
else 
workSpace[j++] = theArray[highPtr++]; 
while (lowPtr <= mid) 
workSpace[j++] = theArray[lowPtr++]; 
while (highPtr <= upperBound) 
workSpace[j++] = theArray[highPtr++]; 
for (j=0; j<n; j+++) 
    theArray[lowerBound+j] = workSpace[j]; 


}