Sort a Matrix in all way increasing order
Last Updated :
13 Sep, 2023
Given a square matrix of order N*N having distinct elements, the task is to sort given matrix in such a way that its rows, columns and both diagonals (diagonal and anti-diagonal) are in increasing order.
Examples:
Input : arr[3][3] = {1, 4, 2,
3, 5, 6,
9, 7, 8}
Output :{1, 2, 3,
4, 5, 6,
7, 8, 9}
Input : arr[2][2] = {0, 4,
5, 2}
Output :{0, 2,
4, 5}
Sorting any matrix in a way that its rows, columns and main diagonal are in increasing order is easy. If we consider matrix elements in sequence according to row-major order and sort the sequence, we get the desired result.
Example: arr[2][2] : {1, 2
3, 4}
Rows in increasing order: {1,2} and {3,4}
Columns in increasing order: {1,3} and {2,4}
Diagonal in increasing order: {1,4}
Anti-diagonal in increasing order: {2,3}
Implementation:
CPP
// C++ program to sort matrix in all-way
#include<bits/stdc++.h>
using namespace std;
#define N 3
// Sorts a matrix in increasing order
void sortAllWay(int arr[][N])
{
// Consider matrix elements (in row major
// order) and sort the sequence.
int *ptr = (int *)arr;
sort(ptr, ptr+N*N);
}
// driver program
int main()
{
int arr[N][N] = {1, 0, 3,
2, 5, 6,
9, 4, 8};
sortAllWay(arr);
// print resultant matrix
for (int i=0; i<N; i++)
{
for (int j=0; j<N; j++)
cout << arr[i][j] << " ";
cout <<"\n";
}
return 0;
}
Java
// Java program to sort matrix in all-way
import java.util.*;
class GFG{
static final int N = 3;
// Sorts a matrix in increasing order
static int[][] sortAllWay(int arr[][])
{
// Consider matrix elements (in row major
// order) and sort the sequence.
int []ar = new int[arr.length*arr.length];
int k = 0;
for(int i = 0; i < arr.length; i++) {
for(int j = 0; j < arr.length; j++) {
ar[k] = arr[i][j];
k++;
}
}
Arrays.sort(ar);
k = 0;
for(int i = 0; i < arr.length; i++) {
for(int j = 0; j < arr.length; j++) {
arr[i][j] = ar[k];
k++;
}
}
return arr;
}
// Driver program
public static void main(String[] args)
{
int arr[][] = {{1, 0, 3},
{ 2, 5, 6},
{ 9, 4, 8}};
arr = sortAllWay(arr);
// print resultant matrix
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
}
}
}
// This code is contributed by umadevi9616
Python3
# Python program to sort matrix in all-way
N = 3;
# Sorts a matrix in increasing order
def sortAllWay(arr):
# Consider matrix elements (in row major
# order) and sort the sequence.
ar = [0 for i in range(len(arr) * len(arr))];
k = 0;
for i in range(len(arr)):
for j in range(len(arr)):
ar[k] = arr[i][j];
k += 1;
ar.sort();
k = 0;
for i in range(len(arr)):
for j in range(len(arr)):
arr[i][j] = ar[k];
k += 1;
return arr;
# Driver program
if __name__ == '__main__':
arr = [[ 1, 0, 3 ],[ 2, 5, 6 ],[ 9, 4, 8 ]] ;
arr = sortAllWay(arr);
# print resultant matrix
for i in range(N):
for j in range(N):
print(arr[i][j], end=" ");
print();
# This code IS contributed by umadevi9616
C#
// C# program to sort matrix in all-way
using System;
public class GFG {
static readonly int N = 3;
// Sorts a matrix in increasing order
static int[,] sortAllWay(int [,]arr) {
// Consider matrix elements (in row major
// order) and sort the sequence.
int[] ar = new int[arr.GetLength(0) * arr.GetLength(1)];
int k = 0;
for (int i = 0; i < arr.GetLength(0); i++) {
for (int j = 0; j < arr.GetLength(1); j++) {
ar[k] = arr[i,j];
k++;
}
}
Array.Sort(ar);
k = 0;
for (int i = 0; i < arr.GetLength(0); i++) {
for (int j = 0; j < arr.GetLength(1); j++) {
arr[i,j] = ar[k];
k++;
}
}
return arr;
}
// Driver program
public static void Main(String[] args) {
int [,]arr = { { 1, 0, 3 }, { 2, 5, 6 }, { 9, 4, 8 } };
arr = sortAllWay(arr);
// print resultant matrix
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
Console.Write(arr[i,j] + " ");
Console.WriteLine();
}
}
}
// This code is contributed by umadevi9616
JavaScript
<script>
// Javascript program to sort matrix in all-way
var N = 3;
// Sorts a matrix in increasing order
function sortAllWay(arr)
{
// Consider matrix elements (in row major
// order) and sort the sequence.
arr.sort((a,b)=>a-b);
return arr;
}
// driver program
var arr = [1, 0, 3,
2, 5, 6,
9, 4, 8];
arr = sortAllWay(arr);
// print resultant matrix
for(var i=0; i<N; i++)
{
for (var j=0; j<N; j++)
document.write(arr[N*i+j] + " ");
document.write("<br>");
}
// This code is contributed by rutvik_56.
</script>
Time Complexity : O(N*N log N)
Auxiliary Space : (N*N), since N*N extra space has been taken.
Similar Reads
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to Sorting Techniques â Data Structure and Algorithm Tutorials Sorting refers to rearrangement of a given array or list of elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of elements in the respective data structure. Why Sorting Algorithms are ImportantThe sorting algorithm is important in Com
3 min read
Most Common Sorting Algorithms
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Heap Sort - Data Structures and Algorithms Tutorials Heap sort is a comparison-based sorting technique based on Binary Heap Data Structure. It can be seen as an optimization over selection sort where we first find the max (or min) element and swap it with the last (or first). We repeat the same process for the remaining elements. In Heap Sort, we use
14 min read
Counting Sort - Data Structures and Algorithms Tutorials Counting Sort is a non-comparison-based sorting algorithm. It is particularly efficient when the range of input values is small compared to the number of elements to be sorted. The basic idea behind Counting Sort is to count the frequency of each distinct element in the input array and use that info
9 min read