2014-12-03 62 views
-1

我想合併排序字符。每當我輸入一個字符數組時,數組的最後一個元素仍然是未識別/無法識別的。如何合併排序字符?

我該如何解決我的程序?

void Merge(char *array, int left, int mid, int right) { 

    char tempArray[right-left+1]; 
    int pos = 0, lpos = left, rpos = mid + 1; 

    while (lpos <= mid && rpos <= right) { 
    if (array[lpos] <= array[rpos]) { 
     tempArray[pos++] = array[lpos++]; 
    } else { 
     tempArray[pos++] = array[rpos++]; 
    } 
    } 

    while (lpos <= mid) 
    tempArray[pos++] = array[lpos++]; 
    while (rpos <= right) 
    tempArray[pos++] = array[rpos++]; 

    int iter; 
    for (iter = 0; iter < pos; iter++) { 
    array[iter+left] = tempArray[iter]; 
    } 

    return; 
} 

void MergeSort(char *array, int left, int right) { 
    int mid = (left + right)/2; 

    if (left < right) { 
    MergeSort(array, left, mid); 
    MergeSort(array, mid + 1, right); 
    Merge(array, left, mid, right); 
    } 
    return; 
} 

回答

1

您的程序看起來正確。你確定你用正確的邊界來調用它嗎?例如:

MergeSort(str, 0, strlen(str)-1);