首页 > 解决方案 > 冒泡排序二维数组

问题描述

我正在尝试使用冒泡排序算法对二维数组进行排序,但我一直在失败。我需要做的是创建一个随机数 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++arrayssorting

解决方案


看起来你很难理解数组和循环是如何工作的。首先,阅读这篇关于循环的文章,然后阅读这篇关于多维数组的文章。现在,至于您的代码:

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

你在这里实际做的是有罪的rows变量,它将行数存储在你的array[rows][columns]. 结果,您的循环无法正常工作。要遍历数组,您需要关联i变量,因此您可以通过方括号内的索引来访问数组的元素。

例如:调用array[i], whilei = 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]
            }
        }
    }
}

升级版:

要显示最大元素的数组,首先创建一个数组,您将在其中保留最大值。对于我的片段,它是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>到您的项目中以在每次运行程序时获取新的随机值。


推荐阅读