Given a 2D array arr[] having N rows of variable size, the task is to sort the array in lexicographical order i.e., sort each row lexicographically and then sort those sorted rows.
Examples:
Input: arr[][] = { {23}, {59}, {23, 59} }
Output: { {23}, {23, 59}, {59} }
Explanation: The rows are sorted lexicographically.
Here the row {23, 59} is lexicographically smaller than {59}Â
because the first element (23) is smaller than 59.
Though {23} and {23, 59} both have 23 as the first element but {23} has only one element.
Hence {23} is lexicographically smaller than {23, 59}Input: arr[][] = { {3, 2, 5, 6}, {1, 2, 3}, {6, 3}, {5, 4, 2} }
Output: { {1, 2, 3}, {2, 3, 5, 6}, {2, 4, 5}, {3, 6} }Input: arr[][] = { {3, 2, 5, 6}, {, 2, 3, 5}, {2, 4, 2, 1}, {6, 3, 7, 8} }
Output: { {1, 2, 2, 4}, {1, 2, 3, 5}, {2, 3, 5, 6}, {3, 6, 7, 8} }
Approach: The idea to solve the problem is as follows:Â
Smallest lexicographical order can be obtained by sorting the elements of each row and first then sorting the whole 2D array based on the lexicographical order of elements in each row.
Follow the below steps to solve this problem:
- First, lexicographically sort every row of the given 2D array.
- Sort the whole 2D array based on the lexicographic ordering of the elements of each row. The row which is lexicographically smaller will arrive first in the sorted matrix..
- Print the 2D array.
Below is the implementation of the above approach:
C++
// C++ code to implement the approachÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to sort the 2D array// lexicographicallyvoid sort_lexicographically(vector<vector<int> >& arr){Â Â Â Â for (int i = 0; i < arr.size(); ++i) {Â
        // Initially sorting the array row-wise        sort(arr[i].begin(), arr[i].end());    }Â
    // Sort the whole array in lexicographically    sort(arr.begin(), arr.end());}Â
// Driver's codeint main(){    vector<vector<int> > arr        = { { 3, 2, 5, 6 }, { 1, 2, 3 }, { 5, 4, 2 }, { 6, 3 }, { 9, 99 }, { 6, 3, 2 } };    sort_lexicographically(arr);Â
    // Resultant 2-d array after    // sorting lexicographically    for (int i = 0; i < arr.size(); ++i) {        for (int j = 0; j < arr[i].size();             ++j) {            cout << arr[i][j] << " ";        }        cout << endl;    }    return 0;} |
Java
// Java code to implement the approachimport java.io.*;import java.util.*;Â
class GFG {    // Function to sort the 2D array    // lexicographically    public static void sort_lexicographically(int arr[][])    {        for (int i = 0; i < arr.length; ++i) {Â
            // Initially sorting the array row-wise            Arrays.sort(arr[i]);        }Â
        // Sort the whole array in lexicographically        Arrays.sort(arr,                    (a, b) -> Integer.compare(a[0], b[0]));    }Â
    // Driver Code    public static void main(String[] args)    {        int arr[][]            = { { 3, 2, 5, 6 }, { 1, 2, 3 }, { 6, 3 },                { 9, 99 },     { 6, 3, 2 }, { 5, 4, 2 } };        sort_lexicographically(arr);Â
        // Resultant 2-d array after        // sorting lexicographically        for (int i = 0; i < arr.length; ++i) {            for (int j = 0; j < arr[i].length; ++j) {                System.out.print(arr[i][j] + " ");            }            System.out.println();        }    }}Â
// This code is contributed by Rohit Pradhan |
Python3
# Python program for above approach   # Function to sort the 2D array# lexicographicallydef sort_lexicographically(arr) :         for i in range(0, len(arr)) : Â
        # Initially sorting the array row-wise        arr[i].sort()     Â
    # Sort the whole array in lexicographically    arr.sort()Â
Â
# Driver codeif __name__ == "__main__":Â Â Â Â Â Â Â Â Â arr = [[ 3, 2, 5, 6 ], [ 1, 2, 3 ], [ 5, 4, 2 ], [ 6, 3 ], [ 9, 99 ], [ 6, 3, 2 ]]Â Â Â Â sort_lexicographically(arr)Â
    # Resultant 2-d array after    # sorting lexicographically    for i in range(0, len(arr)) :        for j in range(0, len(arr[i])) :            print(arr[i][j] , end = " ")                 print()Â
        # This code is contributed by code_hunt. |
C#
// C# program to implement above approachusing System;using System.Collections;using System.Collections.Generic;Â
class GFG{Â
  // Function to sort the 2D array  // lexicographically  public static void sort_lexicographically(int[][] arr)  {    for (int i = 0 ; i < arr.Length ; ++i) {Â
      // Initially sorting the array row-wise      Array.Sort(arr[i]);    }Â
    // Sort the whole array in lexicographically    Array.Sort(arr, new comp());  }Â
  public static void Main(string[] args){Â
    int[][] arr = new int[][]{      new int[]{ 3, 2, 5, 6 },      new int[]{ 1, 2, 3 },      new int[]{ 6, 3 },      new int[]{ 9, 99 },      new int[]{ 6, 3, 2 },      new int[]{ 5, 4, 2 }    };    sort_lexicographically(arr);Â
    // Resultant 2-d array after    // sorting lexicographically    for (int i = 0 ; i < arr.Length ; ++i) {      for (int j = 0 ; j < arr[i].Length ; ++j) {        Console.Write(arr[i][j] + " ");      }      Console.WriteLine("");    }Â
  }}Â
class comp : IComparer<int[]>{Â Â public int Compare(int[] a1, int[] a2){Â Â Â Â return a1[0]-a2[0];Â Â }}Â
// This code is contributed by subhamgoyal2014. |
Javascript
<script>// JavaScript code to implement the approachÂ
// Function to sort the 2D array// lexicographicallyfunction sort_lexicographically(arr){    for (var i = 0; i < arr.length; i++)             // Initially sorting the array row-wise        arr[i].sort();             // Sort the whole array in lexicographically    arr.sort();}Â
// Driver's codearr = [ [ 3, 2, 5, 6 ], [ 1, 2, 3 ], [ 5, 4, 2 ], [ 6, 3 ], [ 9, 99 ], [ 6, 3, 2 ]];sort_lexicographically(arr);Â
// Resultant 2-d array after// sorting lexicographicallyfor (var i = 0; i < arr.length; ++i) {Â Â Â Â for (var j = 0; j < arr[i].length; ++j)Â Â Â Â {Â Â Â Â Â Â Â Â document.write(arr[i][j] + " ");Â Â Â Â }Â Â Â Â document.write("\n");}Â Â Â Â Â // This code is contributed by phasing17</script> |
1 2 3 2 3 5 6 2 3 6 2 4 5 3 6 9 99
Time Complexity: O(N*M*log(M)), Where N is the number of rows, M is the maximum size of a row in arr
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

… [Trackback]
[…] Find More on on that Topic: geeksforgeeks.org/sort-2d-array-lexicographically/ […]
… [Trackback]
[…] Information to that Topic: geeksforgeeks.org/sort-2d-array-lexicographically/ […]
… [Trackback]
[…] Read More on on that Topic: geeksforgeeks.org/sort-2d-array-lexicographically/ […]