2012-04-27 8 views
-4

私は2次元配列を昇順でソートしようとしており、それらを1次元配列(低から高へ)で格納しようとしています。私のプログラムはなぜループを続けるのですか?

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

しかし、私は何を持っていることはループし続けると私はsorted[s_index] >= 0が一度trueの場合、これは無限ループになりますなぜ

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 = 0; col hochl

+3

コードを正しくフォーマットしてください。私はあなたの実際の圧痕があなたの質問に出現したように見えないことを願っています。 – Bojangles

+3

デバッガを接続してプログラムを実行します。プログラムの実際の状態が予想される状態と一致しなくなるまで、プログラムをステップ実行します。スタックオーバーフローはデバッグサービスではありません。 –

答えて

7

を知らない:

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

s_index決してループ内で変更されます。

2

述語が真であるならば、これは明らかに無限ループです:ここでは

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

    } 
3

が問題です。述語がtrueの場合、ループを終了することはありませんので、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'変数を増やしてください。しかし、うまくいくでしょう! –

関連する問題