冒泡排序2d阵列

问题描述 投票:-2回答:1

我试图使用冒泡排序算法对二维数组进行排序,我经常失败。我需要做的是创建一个随机数为10-90的二维数组,并在排序后找出每行中最大的元素,使用冒号排序按升序排列最大元素。我一直在找到每行中最大的元素,但我不能对该列表进行排序。最大元素列表保存在名为max的变量中。如何使用冒泡排序对该列表进行排序。任何帮助将不胜感激。

以下是我到目前为止所尝试的内容:

//编写一个程序,用10到90之间的随机数填充二维数组A [N,M]的值,并确定每行中的最大值。 //行最大元素值按升序排列,使用“气泡”排序算法。 N和M由用户输入。

int i,j,rows, columns, temp, swapped;
cout<<"How many rows? ";
cin>> rows;
cout<< "how many columns? ";
cin>>columns;

int array[rows][columns];

for(i = 0; i<rows; i++){
    for(j=0; j<columns; j++){
        array[i][j] = rand()%90+10;
    }cout<<endl;
}

for(i = 0; i<rows; i++){
    for(j=0; j<columns; j++){
        cout<<array[i][j]<<" ";
    }
    cout<<endl;
}
for(i=0;i<rows;i++){

int max=array[i][0];

    for(j=0;j<columns;j++){

        if(max  <  array[i][j]){

        max = array[i][j];
    }

    }
        cout<<"Largest element in row" << i << "is: "<< max << endl;
}



    for(i=0; i<rows;rows++){

for(j=0; j<columns; j++){
    if(max > max+[1]){
        temp = max;
        max = max+[1];
        max+[1] = temp;

    }
}
    }



    for(i=0; i<rows;rows++){
for(j=0; j<columns; j++){
    cout<< max << endl; 
}

}

return 0 ;

}

c++ arrays sorting
1个回答
0
投票

看起来您无法理解数组和循环的工作方式。首先,阅读这篇关于loops的文章,然后阅读关于multidimensional arrays的文章。现在,至于你的代码:

for (i = 0; i < rows - 1; rows++) {

你在这里真正做的是确定rows变量,它存储你的array[rows][columns]中的行数。因此,您的循环无法正常工作。要遍历数组,您需要确定i变量,因此您可以通过带方括号的索引访问数组的元素。

例如:调用array[i],而i = 3,将返回数组的第四个元素。 (因为数组从0开始)

现在,排序。您正在尝试使用while (1)循环,这是无限的,并且中断,这将无法正常执行。

二维数组的排序实际上是排序x个单维数组。因此,您需要做的是为单维数组实现简单的冒泡排序,并将其包含在额外的for循环中以遍历行。

int m;
int temp;
for (i = 0; i < rows; i++) { // this will "switch" actual rows
    for (j = 0; j < columns; j++) { // this will traverse through elements
        for (m = 0; m < columns - 1; m++) {   // this will traverse just like the 
            if (array[i][j] > array[i][m]) {  // previous loop, but one element 
               temp = array[i][j];            // ahead, so you can compare them 
               array[i][j] = array[i][m];
               array[i][m] = temp;   // swapping elements array[row][element] 
                                     // with array[row][one element ahead]
            }
        }
    }
}

UPD:

要显示最大元素数组,首先要创建一个数组,以保持最大值。对于我的片段,它是int array_max[rows]。它将在我们找到它们时记录您的最大值。要做到这一点,添加这个:(那个cout在哪里)

cout << "Largest element in row" << i << "is: " << max << endl;
        array_max[i] = max;

现在,要对新阵列进行排序并正确打印,请尝试以下方法:

for (i = 0; i < rows; i++) {
    for (j = 0; j < rows - 1; j++) {
        if (array_max[i] > array_max[j]) {
           temp = array_max[i];
           array_max[i] = array_max[j];
           array_max[j] = temp;
        }
    }
}

for (i = 0; i < rows; i++) {
        cout << array_max[i] << " ";
}

最后,将#include <ctime>添加到项目中,以便在每次运行程序时获得新的随机值。

© www.soinside.com 2019 - 2024. All rights reserved.