Я пытаюсь сортировать двухмерный динамический массив, когда строка 1 предназначена для идентификатора продукта, а строка 2 - для цены продукта. Я хочу, чтобы отсортировать по продукции ID, и есть результаты отображаются отформатирован с шириной 5. Вот мой код:Сортировка 2D динамического массива C++
Этот раздел прекрасно и делает то, что я ищу:
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 --;
}
Когда я забегаю, я получаю некоторые странные результаты в последнем разделе. Может быть, я пропустил что-то простое, не уверенное.
Используйте ['std :: sort'] (http://en.cppreference.com/w/cpp/algorithm/sort) с помощью специального компаратора (второго прототипа в списке). –
Не используйте пузырьки! N-квадрат времени выполнения делает ваш компьютер грустным! –
Когда вы меняете productID, поменяйте товарPrice на одни и те же индексы. – MASh