Helle everyone I want sort two dimensional array's columns.I want to take the dimensions and elements of the array from the user and display it as a matrix. Then subtract the sorted form of the same array. We just need to sort the columns of the array. Please help.
Something like that
{{0, 1, 3},
{6, 0, 8},
{5, 9, 2}}
{{0, 0, 2},
{5, 1, 3},
{6, 9, 8}}
I wrote code in C for this, I can just sort the first column of the array and display it, but I can't do the other columns. I appeal to you for this.
#include <iostream>
using namespace std;
int main()
{
int column, row;
cout << "Column = ";
cin >> column;
cout << "Row = ";
cin >> row;
int array[column][row];
int sortedarray[column];
for (int z = 0; z < column; z ) {
for (int a = 0; a < row; a ) {
cin >> array[z][a];
}
}
for (int i = 0; i < column; i ) {
sortedarray[i] = array[i][0];
}
cout << "\n";
for (int y = 0; y < column; y ) {
for (int i = 0; i < row; i ) {
cout << array[y][i] << " ";
}
cout << endl;
}
cout << "\n";
int temp = 0;
for (int i = 1; i < column; i )
for (int j = 0; j < column - i; j ) {
if (sortedarray[j] > sortedarray[j 1]) {
temp = sortedarray[j];
sortedarray[j] = sortedarray[j 1];
sortedarray[j 1] = temp;
}
}
cout << "COUT sorted array \n ";
for (int i = 0; i < column; i ) {
cout << sortedarray[i] << " ";
}
}
CodePudding user response:
From what I understand, you want something as below :
1 5 6
2 8 4
9 7 3
to be sorted into :
1 2 3
4 5 6
7 8 9
the most simplest way would be u have to map the 2-D array into a 1-D array - “1 5 6 2 8 4 9 7 3”, sort them using most optimal algorithm. which would return “ 1 2 3 4 5 6 7 8 9 “ , and then map it back to 2-D array from 1-D array.
In effect you could achieve any sort of ordering, it just depends on your mapping.
You could even achieve something like this
1 4 7
2 5 8
3 6 9
What you need is the mapping from 2-D to 1-D.
CodePudding user response:
@Farhad you can convert 2D array into 1D array as follow:
array_1d = array_2d.flatten()
print(array_1d)
Hope this will helpful!
CodePudding user response:
#Convert 2d array into 1d as follow:
array_1d = array_2d.flatten()
print(array_1d)