2012-04-27 18 views
-4

我想按升序對二維數組進行排序,並將它們存儲在一維數組中(從低到高)。爲什麼我的程序保持循環?

16 22 99 4 18 
-258 4 101 5 98 
105 6 15 2 45 
33 88 72 16 3 

,但我有什麼是不斷循環,我不知道爲什麼

int main()     
{        
    const int SKIP=-999999; 
    const int SIZE=20; 
    const int ROWS=4; 
    const int COLS=5;   
    int unsorted_array[ROWS][COLS]= {(16,22,99,41,18), 
             (-258,4,101,5,98), 
             (105,6,15,2,45), 
             (33,88,72,16,3)}; 
    int s_index=0; 
    int min_value,rowMin,rowCol,row,col,colMin; 
    int sorted[SIZE]; 

    cout <<"Array Sorted"<<endl 
     <<"___________"<<endl<<endl; 


while (s_index < SIZE) 
{ 
    rowMin=0; 
    rowCol=0; 
    min_value = unsorted_array[0][0]; 
    row=0; 
    while (row < ROWS) 
    { 
     col=0; 
     while (col < COLS) 
     { 
      if (unsorted_array[row][col] < min_value) 
      { 
       min_value = unsorted_array[row][col]; 
       rowMin = row; 
       colMin = col; 
      } 
      ; 
      col = col + 1; 
     } 
     row = row + 1; 
    } 
    sorted[s_index] = min_value; 

    while (sorted[s_index] >= 0) 
    { 
     cout<<" "<<sorted[s_index]; 
    } 
    unsorted_array[rowMin][colMin]=SKIP; 
    s_index=s_index+1; 
} 
cout<<endl; 
+2

不是問題的答案,但我建議更換'col = 0; while(col hochl 2012-04-27 23:00:30

+3

請正確格式化您的代碼。我希望你的實際縮進看起來不像你的問題中展現的那樣。 – Bojangles 2012-04-27 23:00:32

+3

用附加的調試器運行你的程序。瀏覽程序,直到程序的實際狀態與預期狀態不符。堆棧溢出不是一個調試服務。 – 2012-04-27 23:00:41

回答

7

如果sorted[s_index] >= 0是真實的一次,這將是一個無限循環:

while (sorted[s_index]>=0) 
{ 
    cout<<" "<<sorted[s_index]; 
} 

s_index從未在該循環中得到改變。

2

如果斷言是真的,這是一個明顯的無限循環:

while (sorted[s_index]>=0) 
    { 
    cout<<" "<<sorted[s_index]; 

    } 
3

這是一個問題。 While條件在循環內不會改變,因此如果謂詞爲真,循環將永不終止

while (sorted[s_index]>=0){ 
    cout<<" "<<sorted[s_index]; 
} 
1

正如其他人已經指出的那樣,您的cout循環是無止境的。更好的使用:

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

或增加while循環內的's_index'變量,但是,這將工作! – 2012-04-28 11:41:38