Given an N x N matrix, our task is to print the row of the matrix in ascending and descending order alternatively.
5 7 3 4
9 5 8 2
6 3 8 1
5 8 9 3
3 4 5 7
9 8 5 2
1 3 6 8
9 8 5 3
Here the first row is sorted in ascending order, second row sorted in descending order, third row sorted in ascending order and so on.
7 3 4
3 8 2
3 6 1
3 4 7
8 3 2
1 3 6
Here the first row is sorted in ascending order, second row sorted in descending order, third row sorted in ascending order.
Approach to solve
To solve the problem mentioned above we iterate 0 to N and check if the ith row is even or odd, if it is even then we sort the row in ascending order otherwise sort the ith row in descending order. Return the matrix after N iterations.
Below is the implementation of the above approach:
3 4 5 7 9 8 5 2 1 3 6 8 9 8 5 3
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Sort all even numbers in ascending order and then sort all odd numbers in descending order
- Sort a linked list that is sorted alternating ascending and descending orders?
- Sort first k values in ascending order and remaining n-k values in descending order
- Sorting rows of matrix in ascending order followed by columns in descending order
- Sorting rows of matrix in descending order followed by columns in ascending order
- Sort first half in ascending and second half in descending order | 1
- Sort first half in ascending and second half in descending order | Set 2
- Number of pairs of arrays (A, B) such that A is ascending, B is descending and A[i] ≤ B[i]
- Sorting Vector of Pairs in C++ | Set 2 (Sort in descending order by first and second)
- Python | Sort words of sentence in ascending order
- Sort an array of string of dates in ascending order
- Sort an array of Roman Numerals in ascending order
- Sort an Array of dates in ascending order using Custom Comparator
- Sort the given IP addresses in ascending order
- Program to sort string in descending order
- Stable sort for descending order
- Sort prime numbers of an array in descending order
- Sort an array in descending order based on the sum of its occurrence
- Arrange numbers 1 to N^2 in a Zig-Zag Matrix in ascending order
- Print number in ascending order which contains 1, 2 and 3 in their digits.
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.