Как в двумерном динамическом массиве отсортировать четные столбцы по убыванию в С++?
Столкнулся с проблемой, сортировки. Пробовал использовать swap и сортировку пузырьком, ничто не помогает, помогите. Кину пример своего кода, 1 с swap, а 2 с сортировкой пузырьком. 1:
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
srand(time(0));
int v = 6;
int l = 0;
int m = 0;
int** arr = new int* [v];
for (int i = 0; i < v; i++) {
arr[i] = new int[v];
}
//рандомно задаём значения строкам и рядам в матрице
for (int i = 0; i < v; i++) {
for (int j = 0; j < v; j++) {
arr[i][j] =-3 + rand() % 10;
}
}
//выводим матрицу на экран
for (int i = 0; i < v; i++) {
for (int j = 0; j < v; j++) {
cout << arr[i][j] << "\t";
}
cout << endl;
}
cout << endl;
for (int i = 1; i < v+1; i++) {
for (int j = 1; j < v+1; j++) {
if (j % 2 == 0) {
l = j;
m = i;
cout << "\t" << "l "<< l << "\t";
cout << "\t" << "m" << m << "\t";
if ((m + 1) % 2 == 0) {
if (arr[m][l] < arr[m - 1][l]) {
cout << "!" << arr[m][l] << "\t" << "@" << arr[m - 1][l] << "\t";
swap(arr[m][l], arr[m - 1][l]);
cout << "!" << arr[m][l] << "\t" << "@" << arr[m - 1][l] << endl;
}
}
}
}
cout << endl;
}
for (int i = 0; i < v; i++) {
for (int j = 0; j < v; j++) {
cout << arr[i][j] << "\t";
}
cout << endl;
}
}
2:
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
srand(time(0));
int v = 6;
int l = 0;
int m = 0;
int** arr = new int* [v];
for (int i = 0; i < v; i++) {
arr[i] = new int[v];
}
//рандомно задаём значения строкам и рядам в матрице
for (int i = 0; i < v; i++) {
for (int j = 0; j < v; j++) {
arr[i][j] =-3 + rand() % 10;
}
}
//выводим матрицу на экран
for (int i = 0; i < v; i++) {
for (int j = 0; j < v; j++) {
cout << arr[i][j] << "\t";
}
cout << endl;
}
cout << endl;
for (int i = 1; i < v+1; i++) {
for (int j = 1; j < v+1; j++) {
if (j % 2 == 0) {
l = j;
m = i;
cout << "\t" << "l "<< l << "\t";
cout << "\t" << "m" << m << "\t";
if ((m + 1) % 2 == 0) {
if (arr[m][l] < arr[m - 1][l]) {
cout << "!" << arr[m][l] << "\t" << "@" << arr[m - 1][l] << "\t";
int t = arr[m][l];
arr[m][l] = arr[m - 1][l];
arr[m - 1][l] = t;
cout << "!" << arr[m][l] << "\t" << "@" << arr[m - 1][l] << endl;
}
}
}
}
cout << endl;
}
for (int i = 0; i < v; i++) {
for (int j = 0; j < v; j++) {
cout << arr[i][j] << "\t";
}
cout << endl;
}
}
Ответы (1 шт):
Автор решения: EOF
→ Ссылка
Код не компилировал, но должно работать.
for (int col = 0; col < v; col += 2) // Цикл, идущий по четным столбцам
{
for (int i = 0; i < v - 1; i++) // Обычная сортировка пузырьком
{
for (int j = 0; j < v - i - 1; j++)
{
if (arr[j][col] < arr[j + 1][col])
swap(arr[j][col], arr[j + 1][col]);
}
}
}