gpt4 book ai didi

c++ - 排序二维动态数组 C++

转载 作者:行者123 更新时间:2023-11-27 22:53:44 25 4
gpt4 key购买 nike

当第 1 行用于产品 ID,第 2 行用于产品价格时,我正在尝试对二维动态数组进行排序。我想按产品 ID 排序,并以宽度为 5 的格式显示结果。这是我的代码:

这部分很好,可以满足我的要求:

void readData (int**, int, int);
void printData(int**, int, int);
void sortbyPartID(int**, int, int);

int main()
{
int index;
int **PriceSheet, rows, columns;
cout << "Enter the number of Products, and then the number of values associated with the products: ";
cout << "For default values, enter 5 (FIVE ITEMS, and enter 2 (TWO Values: ID and PRICE). ";
cin >> columns >> rows;
cout << endl;

PriceSheet = new int* [rows];
for (int row = 0; row < rows; row++)
PriceSheet [row] = new int[columns];

readData (PriceSheet, rows, columns);
cout << endl;

printData(PriceSheet, rows, columns);

sortbyPartID(PriceSheet, rows, columns);

return 0;

}

void readData (int **p, int rowSize, int colSize)
{
for (int row = 0; row < rowSize; row++)
{

cout << "Row ZERO is the Product ID and Row 1 is the Product Price\n";
cout << "Enter " << colSize << " numbers for the row number " << row << ": ";
for (int col = 0; col < colSize; col++)
cin >> p[row][col];
cout << endl;
}
}

void printData (int **p, int rowSize, int colSize)
{
cout << "\n\nThese are the Products IDs and Prices as entered in the system:\n";
for (int row = 0; row < rowSize; row++)
{
for (int col = 0; col < colSize; col++)
cout << setw(5) << p[row][col];
cout << endl;
}
}

这部分是我需要帮助的地方

它读取正确并打印未排序的数组也正确,但我想不出一种方法来排序数组。具体来说,我需要有关 void sortbyPartID 函数的帮助。我想使用冒泡排序,但我不知道如何让这个功能发挥作用。非常感谢对排序功能/算法的任何帮助。

void sortbyPartID (int **p, int rowSize, int colSize)
{
int swap = -1;
int end = colSize;
int sortedID = **p;
cout << "\n\nThese are the Products sorted Products IDs:\n";

for (int counter = colSize -1; counter >= 0; counter --)
for (int index = 0; index < end ; index ++)
{
if (sortedID[index] > sortedID[index + 1])
{
swap = *sortedID[index + 1];
sortedID[index + 1] = sortedID[index];
*sortedID[index] = swap;
}
}

for(int index = 0; index < end; index++)
{
cout << sortedID[index] << ", ";
}
cout << endl;
end --;
}

当我运行时,我在最后一部分得到了一些奇怪的结果。也许我错过了一些简单的东西,不确定。

最佳答案

我们还可以使用 do-while 执行此操作,如下所示:

bool isSwaped;
do
{
isSwaped = false;
for (int index = 0; index < end - 1 ; ++index)
{
if (p[index][0] > p[index + 1][0])
{
int swap = p[index + 1][0];
p[index + 1][0] = p[index][0];
p[index][0] = swap;
isSwaped = true;
}
}
} while (isSwaped);

关于c++ - 排序二维动态数组 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35146669/

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