С++ Сортировка Двумерного массива по строчно
Задача: Двумерный массив. Целочисленный. Клавиатура. Всё через уазатели: Сортировать каждую строку в массиве чередуя по убыванию и по возрастанию. Т.е. первая строчка отсортирована по убыванию, вторая по возрастания, третья снова по убыванию, четвертая по возрастанию и т.д.
Не могу реализовать сортировку каждой строки двумерного массива.
Вот мой пример кода
srand(time(NULL));
int row = 3;
int colm = 5;
int swap = 0;
int** numbers = new int* [row];
for (int i = 0; i < row; i++) {
numbers[i] = new int[colm];
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < colm; j++) {
numbers[i][j] = (int)rand() % 10;
}
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < colm; j++) {
cout << " " << numbers[i][j];
}
cout << endl;
}
Ответы (1 шт):
Автор решения: Maggot
→ Ссылка
Ну как то так напишите - максимальн просто
#include <random>
#include <algorithm>
#include <iostream>
unsigned int GenRandomUInt(unsigned int l_bound, unsigned int h_bound) {
static std::random_device r_dev{};
static std::mt19937_64 mt_engine(r_dev());
static std::uniform_int_distribution<> u_int_d(l_bound, h_bound);
return static_cast<unsigned int>(u_int_d(mt_engine));
}
void FreeMultiArray(unsigned int** array, const unsigned int size) {
if (array == nullptr || size == 0) {
return;
}
for (unsigned int i{0}; i < size; ++i) {
if (array[i] != nullptr) {
delete[] array[i];
}
}
if (array != nullptr) {
delete[] array;
}
}
void FillRandom(unsigned int* array, const unsigned int size) {
if (0 == size || array == nullptr) {
return;
}
for (unsigned int i{0}; i < size; ++i) {
array[i] = GenRandomUInt(0, 100);
}
}
unsigned int** GenMultiArray(const unsigned int size) {
if (0 == size) {
return nullptr;
}
unsigned int** array = new unsigned int*[size];
if (array == nullptr) {
return nullptr;
}
for (unsigned int i{0}; i < size; ++i) {
array[i] = new unsigned int[size];
if (array[i] == nullptr) {
FreeMultiArray(array, size);
return nullptr;
}
FillRandom(array[i], size);
}
return array;
}
void PrintMultiArray(unsigned int** array, const unsigned int h_size, const unsigned int v_size) {
if (array == nullptr || h_size == 0 || v_size == 0) {
return;
}
for (unsigned int i{0}; i < v_size; ++i) {
if (array[i] == nullptr) {
return;
}
}
for (unsigned int i{0}; i < v_size; ++i) {
for (unsigned int j{0}; j < h_size; ++j) {
std::cout << array[i][j] << "\t";
}
std::cout << std::endl;
}
}
int main() {
const unsigned int size = 10;
unsigned int** array = GenMultiArray(size);
if (array == nullptr) {
return 1;
}
for (unsigned int i{0}; i < size; ++i) {
if (i % 2) {
std::sort(&array[i][0], &array[i][0] + size, std::greater<unsigned int>());
} else {
std::sort(&array[i][0], &array[i][0] + size, std::less<unsigned int>());
}
}
PrintMultiArray(array, size, size);
FreeMultiArray(array, size);
return 0;
}