sort 2d array colomun elements

Write your question here.
How can i sort 2d array column elemetns in descending order
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int main()
{
	int a[4][5];
	int i, j, s = 0, sum = 0;

	cout << "Ievadiet 20 matricas elementus \n";
	for (i = 0; i < 4; i++)
	{
		for (j = 0; j < 5; j++)
		{
			cin >> a[i][j];
		}
	}
	cout << "Jusu ievadita matrica ir \n";
	for (i = 0; i < 4; i++)
	{
		for (j = 0; j < 5; j++)
			cout << a[i][j] << " ";
		cout << endl;
	}
}

1
2
3
4
5
6
7
8
9
10
11
12
	for( int col = 0; col < 5; ++col)
	{
	    int tmp[4];
	    
	    for( int row = 0; row < 4; ++row)
	        tmp[row] = a[row][col];	
	        
	    std::sort( tmp, tmp+4, [](int a, int b){return a > b;} );
	    
	    for( int row = 0; row < 4; ++row)
	        a[row][col] = tmp[row];
	}

You need to include <algorithm>.
Last edited on
You need to include <algorithm>.

Not necessarily. It's always interesting to practice coding your own sorts. I personally never use the <algorithm> std::sort() function

You can use for instance
a bubble sort: https://www.geeksforgeeks.org/bubble-sort/
a selection sort: https://www.geeksforgeeks.org/selection-sort/
Last edited on
@H00G0 Your linked examples are bad practice; if someone wants to reinvent the wheel, he/she should at least assure that his code is STL conform so that the sorting function would be exchangeable later.
This means that the function takes a pointer to the first element and one beyond the last, and optionally taking an address to a comparing function.
@nuderobmonkey I didn't post those links so that OP could copy and paste the code in there, as I said I encouraged him
to practice coding [his] own sorts
. The links were merely a way of explaining how those sorts work, since they provide a pseudocode and video that explains quite well how they work. The way you go about implementing the logic is your choice.
Last edited on
Topic archived. No new replies allowed.