gpt4 book ai didi

c++ - 对二维 int 数组的特定列进行排序 (C++)

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:39:42 25 4
gpt4 key购买 nike

我有一个难题。我目前正在尝试创建一个用户定义的函数来对我在主函数中创建并填充的二维 int 数组的列(按升序)进行排序。我觉得我很接近,但由于某种原因最终输出不正确,它提供了一个甚至不在数组中的最终值的数字。从提供的值和编译所需的额外几秒钟来看,我假设我在代码中的某个点搞砸了我的界限/超出了界限,但我已经为此奋斗了几个小时但无济于事我觉得新鲜(而且可能更有经验)的眼睛会有一些用处。我仍然在我的编程“入门”类(class)中,因此鼓励我为明显的错误撕掉一个新的类(class),因为我的期末考试是这个星期四,任何和所有的指针/提示都将受到赞赏。干杯!

    #include <iostream>

using namespace std;


void sort2D(int arr[3][5], int rows, int columns) //the problem child
{
int userCol;
cout<<"Please enter the number of the column you'd like to sort: "<<endl;
cin>>userCol; //ask for appropriate column


for (int row_index=0; row_index<rows; row_index++) //start with first row and continue for all values in code
{
int temp;

if ((arr[row_index][userCol-1]<arr[row_index+1][userCol-1]))//if first value of selected column is less than next value
{
temp = arr[row_index+1][userCol-1];//create copy of second value
arr[row_index+1][userCol-1]=arr[row_index][userCol-1]; //replace second value with first value
arr[row_index][userCol-1]=temp;//set first equal to second's original value
}
}

for(int i=0; i<rows; i++)//print that shiz
{
for(int j=0; j<columns; j++)
{
cout<<arr[i][j]<<" ";
}
cout<<endl;
}
}

int main()
{
const int rows = 3;
const int columns = 5;

int arr[rows][columns];

for (int row_index=0; row_index<rows; row_index++)
{
for (int column_index=0; column_index<columns; column_index++)
{
arr[row_index][column_index] = (50+rand()%51);
cout << arr[row_index][column_index]<<" ";
}
cout << endl;
}

findMaxandIndex(arr, rows, columns);//i left my code for this out because it's working and isn't utilized in the problem code
cout << endl;
sort2D(arr, rows, columns);
return 0;

最佳答案

您的排序函数非常接近冒泡排序,这是最容易理解和实现的排序算法之一。稍微修改一下,您的代码就可以工作了:

    void sort2D(int arr[3][5], int rows, int columns) //the problem child
{

//input userCol ...

//sorting start here ...
bool found = true; //we can quit the loop if the array is already sorted.

for (int bubble = 0; bubble < rows-1 && found ; bubble++)
{
found = false;

for (int row_index=0; row_index < rows - bubble - 1; row_index++)
{
int temp;

if ((arr[row_index][userCol-1] < arr[row_index+1][userCol-1]))//if first value of selected column is less than next value
{
//swap two elements.
temp = arr[row_index+1][userCol-1];//create copy of second value
arr[row_index+1][userCol-1]=arr[row_index][userCol-1]; //replace second value with first value
arr[row_index][userCol-1]=temp;//set first equal to second's original value

found = true; //we found something, continue to sort.
}
}
}
//print out the result ...
}

当您开始使用 C++ 时,建议尽可能使用 C++ 工具:std::vector 用于数组,std::qsort 用于元素排序。

关于c++ - 对二维 int 数组的特定列进行排序 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53719742/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com