Open In App

Sort an Array of Strings in Lexicographical order

Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of strings arr[] of length N, the task is to sort the strings in Lexicographical order.

Examples:

Input: arr[] = {“batman”, “bat”, “apple”} 
Output: 
apple
bat 
batman
Explanation: 
The lexicographical order of string is “apple”, “bat”, “batman”

Input: arr[] = {“geeks”, “for”, “geeksforgeeks”} 
Output: 
for
geeks
geeksforgeeks

Approach 1:

The array can be sorted in increasing order by comparing ASCII values of the leftmost character that are different among the strings.

To sort the strings we can use the inbuilt sort() function. The function sorts the string in lexicographical order by default.

Below is the implementation for the above approach:

C++




// C++ program for above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to sort the strings
// in lexicographical order
void Printlexiographically(int N, string arr[])
{
    // Sort the strings of the array
    sort(arr, arr + N);
 
    for (int i = 0; i < N; i++) {
 
        // Print each string of the array
        cout << arr[i] << '\n';
    }
}
 
// Driver Code
int main()
{
    string arr[] = { "batman", "bat", "apple" };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    Printlexiographically(N, arr);
 
    return 0;
}


Java




// Java program for above approach
import java.util.*;
import java.io.*;
 
class GFG
{
 
  // Function to sort the strings
  // in lexicographical order
  public static void Printlexiographically(int N,
                                           String arr[])
  {
 
    // Sort the strings of the array
    Arrays.sort(arr);
 
    for (int i = 0; i < N; i++) {
 
      // Print each string of the array
      System.out.println(arr[i]);
    }
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    String arr[] = { "batman", "bat", "apple" };
    int N = arr.length;
 
    // Function Call
    Printlexiographically(N, arr);
  }
}
 
// This code is contributed by Rohit Pradhan


Python3




# Python code to implement the approach
 
# Function to sort the strings
# in lexicographical order
def Printlexiographically(N, arr) :
     
    # Sort the strings of the array
    arr.sort()
  
    for i in range(N):
  
        # Preach string of the array
        print(arr[i])
     
# Driver Code
if __name__ == "__main__":
     
    arr= [ "batman", "bat", "apple" ]
    N = len(arr)
  
    # Function Call
    Printlexiographically(N, arr)
     
    # This code is contributed by code_hunt.


C#




using System;
public class GFG {
 
  // Function to sort the strings
  // in lexicographical order
  public static void Printlexiographically(int N,
                                           string[] arr)
  {
     
    // Sort the strings of the array
    // sort(arr, arr + N);
    Array.Sort(arr);
 
    for (int i = 0; i < N; i++) {
 
      // Print each string of the array
      // cout << arr[i] << '\n';
      Console.WriteLine(arr[i]);
    }
  }
 
  static public void Main()
  {
 
    // Code
    string[] arr = { "batman", "bat", "apple" };
    int N = arr.Length;
 
    // Function Call
    Printlexiographically(N, arr);
  }
}
 
// This code is contributed by akashish__


Javascript




<script>
  // Javascript code to implement the approach
   
  // Function to sort the strings
  // in lexicographical order
  function Printlexiographically(N, arr)
  {
 
    // Sort the strings of the array
    arr.sort();
 
    for (let i = 0; i < N; i++) {
 
      // Print each string of the array
      document.write(arr[i] + "<br/>");
    }
  }
   
  // Driver code
      let arr = [ "batman", "bat", "apple" ];
    let N = arr.length;
 
    // Function Call
    Printlexiographically(N, arr);
   
  // This code is contributed by sanjoy_62.
  </script>


Output

apple
bat
batman

Time Complexity: O(N * logN * M), where M is the average length of the strings
Auxiliary Space: O(1)

Approach 2: Using Sorting

Idea/Intuition
The idea is to sort the strings lexicographically using the sorting algorithms. The sorting algorithms basically works by comparing pairs of elements and sorting them based on the comparison result.

Algorithm

  • Create an array of strings, say arr[]
  • Sort the array using any sorting algorithm, say mergeSort()
       mergeSort(arr[], 0, n-1)
  • Steps to implement mergeSort():

Step 1: If it is only one element in the array then return.

Step 2: Else divide the array into two halves say left[] and right[].

Step 3: Sort the left array using mergeSort():
           mergeSort(left[], 0, mid-1)

Step 4: Sort the right array using mergeSort():
           mergeSort(right[], 0, mid)

Step 5: Merge the sorted left and right arrays:
           merge(left[], right[], arr[])

Step 6: Return the sorted array.

Implementation

Below is the implementation for the above approach:

C++




#include <bits/stdc++.h>
using namespace std;
   
// Merge two subarrays arr[l..m] and arr[m+1..r]
void merge(string arr[], int l, int m, int r)
{
    int i, j, k;
    int n1 = m - l + 1;
    int n2 =  r - m;
   
    /* create temp arrays */
    string L[n1], R[n2];
   
    /* Copy data to temp arrays L[] and R[] */
    for (i = 0; i < n1; i++)
        L[i] = arr[l + i];
    for (j = 0; j < n2; j++)
        R[j] = arr[m + 1+ j];
   
    /* Merge the temp arrays back into arr[l..r]*/
    i = 0; // Initial index of first subarray
    j = 0; // Initial index of second subarray
    k = l; // Initial index of merged subarray
    while (i < n1 && j < n2)
    {
        if (L[i] <= R[j])
        {
            arr[k] = L[i];
            i++;
        }
        else
        {
            arr[k] = R[j];
            j++;
        }
        k++;
    }
   
    /* Copy the remaining elements of L[], if there
       are any */
    while (i < n1)
    {
        arr[k] = L[i];
        i++;
        k++;
    }
   
    /* Copy the remaining elements of R[], if there
       are any */
    while (j < n2)
    {
        arr[k] = R[j];
        j++;
        k++;
    }
}
   
/* l is for left index and r is right index of the
   sub-array of arr to be sorted */
void mergeSort(string arr[], int l, int r)
{
    if (l < r)
    {
        // Same as (l+r)/2, but avoids overflow for
        // large l and h
        int m = l+(r-l)/2;
   
        // Sort first and second halves
        mergeSort(arr, l, m);
        mergeSort(arr, m+1, r);
   
        merge(arr, l, m, r);
    }
}
   
/* UTILITY FUNCTIONS */
/* Function to print an array */
void printArray(string A[], int size)
{
    int i;
    for (i=0; i < size; i++)
        cout << A[i] << " ";
    cout << endl;
}
   
/* Driver program to test above functions */
int main()
{
    string arr[] = {"batman", "bat", "apple"};
    int arr_size = sizeof(arr)/sizeof(arr[0]);
   
    cout << "Given array is \n";
    printArray(arr, arr_size);
   
    mergeSort(arr, 0, arr_size - 1);
   
    cout << "\nSorted array is \n";
    printArray(arr, arr_size);
    return 0;
}


Java




/*package whatever //do not write package name here */
import java.util.*;
class GFG {
 
  // Merge two subarrays arr[l..m] and arr[m+1..r]
  static void merge(String arr[], int l, int m, int r)
  {
    int i, j, k;
    int n1 = m - l + 1;
    int n2 =  r - m;
 
    /* create temp arrays */
    String L[] = new String[n1], R[] = new String[n2];
 
    /* Copy data to temp arrays L[] and R[] */
    for (i = 0; i < n1; i++)
      L[i] = arr[l + i];
 
    for (j = 0; j < n2; j++)
      R[j] = arr[m + 1+ j];
 
    /* Merge the temp arrays back into arr[l..r]*/
    i = 0; // Initial index of first subarray
    j = 0; // Initial index of second subarray
    k = l; // Initial index of merged subarray
    while (i < n1 && j < n2)
    {
      if (L[i].compareTo(R[j])<=0)
      {
        arr[k] = L[i];
        i++;
      }
      else
      {
        arr[k] = R[j];
        j++;
      }
      k++;
    }
 
    /* Copy the remaining elements of L[], if there
       are any */
    while (i < n1)
    {
      arr[k] = L[i];
      i++;
      k++;
    }
 
    /* Copy the remaining elements of R[], if there
       are any */
    while (j < n2)
    {
      arr[k] = R[j];
      j++;
      k++;
    }
  }
 
  /* l is for left index and r is right index of the
   sub-array of arr to be sorted */
  static void mergeSort(String arr[], int l, int r)
  {
    if (l < r)
    {
      // Same as (l+r)/2, but avoids overflow for
      // large l and h
      int m = l+(r-l)/2;
 
      // Sort first and second halves
      mergeSort(arr, l, m);
      mergeSort(arr, m+1, r);
 
      merge(arr, l, m, r);
    }
  }
 
  /* UTILITY FUNCTIONS */
  /* Function to print an array */
  static void printArray(String A[], int size)
  {
    int i;
    for (i=0; i < size; i++)
      System.out.print(A[i] + " ");
    System.out.println();
  }
 
 
  public static void main (String[] args) {
    String arr[] = {"batman", "bat", "apple"};
    int arr_size = arr.length;
 
    System.out.println("Given array is");
    printArray(arr, arr_size);
 
    mergeSort(arr, 0, arr_size - 1);
 
    System.out.println("\nSorted array is");
    printArray(arr, arr_size);
  }
}
 
// This code is contributed by aadityaburujwale.


Python3




# Merge two subarrays arr[l..m] and arr[m+1..r]
def merge( arr,  l,  m,  r) :
    n1 = m - l + 1;
    n2 =  r - m;
   
    # create temp arrays */
    L=[0]*(n1);
    R=[0]*(n2);
   
    # Copy data to temp arrays L[] and R[] */
    for i in range(0, n1):
        L[i] = arr[l + i];
    for j in range(0, n2):
        R[j] = arr[m + 1+ j];
   
    # Merge the temp arrays back into arr[l..r]*/
    i = 0; # Initial index of first subarray
    j = 0; # Initial index of second subarray
    k = l; # Initial index of merged subarray
    while (i < n1 and j < n2) :
        if (L[i] <= R[j]) :
            arr[k] = L[i];
            i+=1;
 
        else:
            arr[k] = R[j];
            j+=1;
        k+=1;
   
    # Copy the remaining elements of L[], if there  are any
    while (i < n1):
        arr[k] = L[i];
        i+=1;
        k+=1;
     
    # Copy the remaining elements of R[], if there are any
    while (j < n2) :
        arr[k] = R[j];
        j+=1;
        k+=1;
    
  # l is for left index and r is right index of the
  # sub-array of arr to be sorted */
def mergeSort(arr,  l,  r):
    if (l < r) :
        # Same as (l+r)/2, but avoids overflow for
        # large l and h
        m = l+(r-l)//2;
   
        # Sort first and second halves
        mergeSort(arr, l, m);
        mergeSort(arr, m+1, r);
   
        merge(arr, l, m, r);
     
# UTILITY FUNCTIONS */
# Function to print an array */
def printArray( A, size) :
    for i in range(0,size):
        print("%s" % A[i],end=" ")
 
 
# Driver program to test above functions */
arr = ["batman", "bat", "apple"];
arr_size = len(arr);
 
print("Given array is ");
printArray(arr, arr_size);
 
mergeSort(arr, 0, arr_size - 1);
 
print("\nSorted array is");
printArray(arr, arr_size);


C#




using System;
using System.Linq;
 
class GFG
{
    // Merge two subarrays arr[l..m] and arr[m+1..r]
    static void Merge(string[] arr, int l, int m, int r)
    {
        int i, j, k;
        int n1 = m - l + 1;
        int n2 = r - m;
 
        /* create temp arrays */
        string[] L = new string[n1];
        string[] R = new string[n2];
 
        /* Copy data to temp arrays L[] and R[] */
        for (i = 0; i < n1; i++)
            L[i] = arr[l + i];
 
        for (j = 0; j < n2; j++)
            R[j] = arr[m + 1 + j];
 
        /* Merge the temp arrays back into arr[l..r]*/
        i = 0; // Initial index of first subarray
        j = 0; // Initial index of second subarray
        k = l; // Initial index of merged subarray
        while (i < n1 && j < n2)
        {
            if (String.Compare(L[i], R[j]) <= 0)
            {
                arr[k] = L[i];
                i++;
            }
            else
            {
                arr[k] = R[j];
                j++;
            }
            k++;
        }
 
                /* Copy the remaining elements of L[], if there
        are any */
        while (i < n1)
        {
            arr[k] = L[i];
            i++;
            k++;
        }
 
        /* Copy the remaining elements of R[], if there
        are any */
        while (j < n2)
        {
            arr[k] = R[j];
            j++;
            k++;
        }
    }
 
    /* l is for left index and r is right index of the
    sub-array of arr to be sorted */
    static void MergeSort(string[] arr, int l, int r)
    {
        if (l < r)
        {
            // Same as (l+r)/2, but avoids overflow for
            // large l and h
            int m = l + (r - l) / 2;
 
            // Sort first and second halves
            MergeSort(arr, l, m);
            MergeSort(arr, m + 1, r);
 
            Merge(arr, l, m, r);
        }
    }
 
    /* UTILITY FUNCTIONS */
    /* Function to print an array */
    static void PrintArray(string[] A, int size)
    {
        for (int i = 0; i < size; i++)
            Console.Write(A[i] + " ");
        Console.WriteLine();
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        string[] arr = { "batman", "bat", "apple" };
        int arr_size = arr.Length;
 
        Console.WriteLine("Given array is");
        PrintArray(arr, arr_size);
 
        MergeSort(arr, 0, arr_size - 1);
 
        Console.WriteLine("\nSorted array is");
        PrintArray(arr, arr_size);
    }
}


Javascript




// Merge two subarrays arr[l..m] and arr[m+1..r]
function merge(arr, l, m, r)
{
    var n1 = m - l + 1;
    var n2 = r - m;
 
    // Create temp arrays
    var L = new Array(n1);
    var R = new Array(n2);
 
    // Copy data to temp arrays L[] and R[]
    for (var i = 0; i < n1; i++)
        L[i] = arr[l + i];
    for (var j = 0; j < n2; j++)
        R[j] = arr[m + 1 + j];
 
    // Merge the temp arrays back into arr[l..r]
 
    // Initial index of first subarray
    var i = 0;
 
    // Initial index of second subarray
    var j = 0;
 
    // Initial index of merged subarray
    var k = l;
 
    while (i < n1 && j < n2) {
        if (L[i] <= R[j]) {
            arr[k] = L[i];
            i++;
        }
        else {
            arr[k] = R[j];
            j++;
        }
        k++;
    }
 
    // Copy the remaining elements of
    // L[], if there are any
    while (i < n1) {
        arr[k] = L[i];
        i++;
        k++;
    }
 
    // Copy the remaining elements of
    // R[], if there are any
    while (j < n2) {
        arr[k] = R[j];
        j++;
        k++;
    }
}
 
// l is for left index and r is
// right index of the sub-array
// of arr to be sorted */
function mergeSort(arr,l, r){
    if(l>=r){
        return;//returns recursively
    }
    var m =l+ parseInt((r-l)/2);
    mergeSort(arr,l,m);
    mergeSort(arr,m+1,r);
    merge(arr,l,m,r);
}
 
// UTILITY FUNCTIONS
// Function to print an array
function printArray( A, size)
{
    for (var i = 0; i < size; i++)
    document.write( A[i] + " ");
}
 
 
    let arr = ["batman", "bat", "apple"]; 
      var arr_size = arr.length;
 
    document.write( "Given array is");
    document.write("<br>");
    printArray(arr, arr_size);
     
    document.write("<br>");
 
    mergeSort(arr, 0, arr_size - 1);
 
    document.write( "Sorted array is");
    document.write("<br>");
    printArray(arr, arr_size);


Output

Given array is 
batman bat apple 

Sorted array is 
apple bat batman 

Time complexity: O(n * log n * m) (where m is average length of strings)
Auxiliary Space: O(n)



Last Updated : 20 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads