2012-04-27 17 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