2015-04-15 83 views
0
#include "stdafx.h" 
#include <iostream> 

using namespace std; 
using namespace System; 

void mergesort(int a[], int p, int r); 
void merge(int a[], int p, int q, int r); 
int main(array<System::String ^> ^args) 
{ 
    int result[2] = { 1, 0 }; 
    int *p; 
    p = result; 
    mergesort(p, 0,1); 
    while (1); 
    return 0; 
} 

void mergesort(int a[],int p, int r) 
{ 
    if (p < r) 
    { 
     int q = (p + r)/2; 
     mergesort(a, p, q); 
     cout << endl; 
     mergesort(a, q + 1, r); 
     cout << endl; 
     merge(a,p,q,r); 
     for (int i = 0; i < 2; i++) 
     { 
      cout << a[i] << " "; 
     } 
     cout << endl; 
    } 
} 

void merge(int a[], int p, int q, int r) 
{ 
    int left[100] = {}; 
    int right[100] = {}; 
    for (int i = 0; i < (q - p + 1); i++) 
    { 
     left[i] = *(a + p + i); 
     left[i + 1] = 999; 
    } 
    for (int i = 0; i < (r - q); i++) 
    { 
     right[i] = *(a + q + 1 + i); 
     right[i + 1] = 999; 
    } 
    for (int k = p; k < r+1; k++) 
    { 
     int i = 0; 
     int j = 0; 
     if (left[i] <= right[j]) 
     { 
      a[k] = left[i++]; 
     } 
     else 
     { 
      a[k] = right[j++];  **// it always goes into this route? why does not left[i]<=right[j] work?** 
     } 
    } 
} 

這是我關於基本合併排序的代碼。我無法在合併函數中輸入第一個IF語句。爲什麼if (left[i] <= right[j])不起作用?我已經嘗試過可能不管什麼left[i]。該程序只是去了else語句。C++中的mergesort

回答

4
for (int k = p; k < r+1; k++) 
{ 
    int i = 0; 
    int j = 0; 
    if (left[i] <= right[j]) 
    { 
     a[k] = left[i++]; 
    } 
    else 
    { 
     a[k] = right[j++];  **// it always goes into this route? why does not left[i]<=right[j] work?** 
    } 
} 

這不符合你的想法。它總會將left[0]right[0]進行比較,因爲您在for循環內聲明瞭ij,因此它們將在每次迭代中重置爲0。

爲了讓他們保留他們的價值觀,宣佈他們外循環:

int i = 0; 
int j = 0; 
for (int k = p; k < r+1; k++) 
{ 
    if (left[i] <= right[j]) 
    { 
     a[k] = left[i++]; 
    } 
    else 
    { 
     a[k] = right[j++];  **// it always goes into this route? why does not left[i]<=right[j] work?** 
    } 
} 
0

如果你的目的是使用變量i和j在循環才試圖限制我的範圍和j的循環做下面的事情。

for (int k = p, i = 0, j = 0; k < r+1; k++) 
{ 
    if (left[i] <= right[j]) 
    { 
     a[k] = left[i++]; 
    } 
    else 
    { 
     a[k] = right[j++];  
    } 
}