Open In App

Sort given words as Array of Strings

Last Updated : 30 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of strings Arr[]. The task is to sort them in lexicographic order.

Examples:

Input: Arr[] = {“sort”, “this”, “list”}
Output:  [list, sort, this]

Input: Arr[] = {“sun”, “earth”, “mars”, “mercury”}
Output: [earth, mars, mercury, sun]

 

Selection Sort Approach: The same problem can also be solved using selection sort

The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning

Below is the implementation of the above approach:

C++




// C++ Program to sort
// array of strings
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to compare 2 words
bool isAlphabeticallySmaller(string str1, string str2)
{
    transform(str1.begin(), str1.end(), str1.begin(),
              ::toupper);
    transform(str2.begin(), str2.end(), str2.begin(),
              ::toupper);
 
    if (str1 < str2) {
        return true;
    }
    return false;
}
 
void selectionSort(vector<string>& arr)
{
    int n = arr.size();
 
    // One by one move boundary of
    // unsorted subarray
    for (int i = 0; i < n - 1; i++) {
 
        // Find the minimum element
        // in unsorted array
        int min_idx = i;
        for (int j = i + 1; j < n; j++)
            if (isAlphabeticallySmaller(arr[j],
                                        arr[min_idx]))
                min_idx = j;
 
        // Swap the found minimum
        // element with the first element
        string temp = arr[min_idx];
        arr[min_idx] = arr[i];
        arr[i] = temp;
    }
}
 
// Driver code
int main()
{
    vector<string> Arr
        = { "sun", "earth", "mars", "mercury" };
    int N = Arr.size();
    selectionSort(Arr);
    for (int i = 0; i < N; i++) {
        cout << Arr[i] << "\n";
    }
 
    // This code is contributed by rakeshsahni
 
    return 0;
}


Java




// Java Program to sort
// array of strings
 
class GFG {
    static void selectionSort(String[] arr)
    {
        int n = arr.length;
 
        // One by one move boundary of
        // unsorted subarray
        for (int i = 0; i < n - 1; i++) {
 
            // Find the minimum element
            // in unsorted array
            int min_idx = i;
            for (int j = i + 1; j < n; j++)
                if (isAlphabeticallySmaller(
                        arr[j], arr[min_idx]))
                    min_idx = j;
 
            // Swap the found minimum
            // element with the first element
            String temp = arr[min_idx];
            arr[min_idx] = arr[i];
            arr[i] = temp;
        }
    }
    // Function to compare 2 words
    static boolean isAlphabeticallySmaller(
        String str1, String str2)
    {
        str1 = str1.toUpperCase();
        str2 = str2.toUpperCase();
        if (str1.compareTo(str2) < 0) {
            return true;
        }
        return false;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        String[] Arr
            = { "sun", "earth", "mars", "mercury" };
        int N = Arr.length;
        selectionSort(Arr);
        for (int i = 0; i < N; i++) {
            System.out.println(Arr[i]);
        }
    }
}


Python3




# Python3 code for the above approach
 
# function perform selection sorting on the array
def selectionSort(arr):
    n = len(arr)
 
    # One by one move boundary of
    # unsorted subarray
    for i in range(n - 1):
 
        # Find the minimum element
        # in unsorted array
        min_idx = i
        for j in range(i + 1, n):
            if (isAlphabeticallySmaller(arr[j], arr[min_idx])):
                min_idx = j
 
        # Swap the found minimum
        # element with the first element
        temp = arr[min_idx]
        arr[min_idx] = arr[i]
        arr[i] = temp
    return arr
 
# Function to compare 2 words
 
 
def isAlphabeticallySmaller(str1, str2):
    str1 = str1.upper()
    str2 = str2.upper()
    if str1 < str2:
        return True
    return False
 
 
# Driver code
Arr = ["sun", "earth", "mars", "mercury"]
N = len(Arr)
 
# function call
Arr = selectionSort(Arr)
for word in Arr:
    print(word)
 
 
# This code is contributed by phasing17


C#




// C# Program to sort
// array of strings
using System;
 
public class GFG
{
  static void selectionSort(string[] arr)
  {
    int n = arr.Length;
 
    // One by one move boundary of
    // unsorted subarray
    for (int i = 0; i < n - 1; i++) {
 
      // Find the minimum element
      // in unsorted array
      int min_idx = i;
      for (int j = i + 1; j < n; j++)
        if (isAlphabeticallySmaller(
          arr[j], arr[min_idx]))
          min_idx = j;
 
      // Swap the found minimum
      // element with the first element
      String temp = arr[min_idx];
      arr[min_idx] = arr[i];
      arr[i] = temp;
    }
  }
  // Function to compare 2 words
  static bool isAlphabeticallySmaller(
    string str1, String str2)
  {
    str1 = str1.ToUpper();
    str2 = str2.ToUpper();
    if (str1.CompareTo(str2) < 0) {
      return true;
    }
    return false;
  }
 
  // Driver code
  static public void Main (){
 
    string[] Arr  = { "sun", "earth", "mars", "mercury" };
    int N = Arr.Length;
    selectionSort(Arr);
    for (int i = 0; i < N; i++) {
      Console.WriteLine(Arr[i]);
    }
  }
}
 
// This code is contributed by hrithikgarg03188.


Javascript




<script>
    // JavaScript code for the above approach
 
    function selectionSort(arr)
    {
        let n = arr.length;
 
        // One by one move boundary of
        // unsorted subarray
        for (let i = 0; i < n - 1; i++) {
 
            // Find the minimum element
            // in unsorted array
            let min_idx = i;
            for (let j = i + 1; j < n; j++)
                if (isAlphabeticallySmaller(
                        arr[j], arr[min_idx]))
                    min_idx = j;
 
            // Swap the found minimum
            // element with the first element
            let temp = arr[min_idx];
            arr[min_idx] = arr[i];
            arr[i] = temp;
        }
    }
    // Function to compare 2 words
    function isAlphabeticallySmaller(
        str1, str2)
    {
        str1 = str1.toUpperCase();
        str2 = str2.toUpperCase();
        if (str1.localeCompare(str2) == -1) {
            return true;
        }
        return false;
    }
         
    // Driver Code
    let Arr
            = [ "sun", "earth", "mars", "mercury" ];
        let N = Arr.length;
        selectionSort(Arr);
        for (let i = 0; i < N; i++) {
            document.write(Arr[i] + "<br/>");
        }
 
// This code is contributed by sanjoy_62.
</script>


 
 

Output

earth
mars
mercury
sun

 

Time Complexity: O(K * N2)
Auxiliary Space: O(1)

 

Bubble Sort Approach: The basic approach to sort the given strings in lexicographic order is by using bubble sort.

 

In Bubble sort, the two successive strings Arr[i] and Arr[i+1] are exchanged whenever arr[i]> arr[i+1]. At the end of each pass, smaller values gradually “bubble” their way upward to the top and hence called bubble sort.

 

Below is the implementation of the above approach:

 

C++




// C++ Program for the above approach.
#include <bits/stdc++.h>
using namespace std;
 
 // Function to compare 2 words
bool isAlphabeticallySmaller(
        string str1, string str2)
    {
        transform(str1.begin(), str1.end(), str1.begin(),
              ::toupper);
        transform(str2.begin(), str2.end(), str2.begin(),
              ::toupper);
        if (str1 < str2) {
            return true;
        }
        return false;
    }
 
void bubbleSort(vector<string> &arr, int n)
    {
        int i, j;
        string temp;
        bool swapped;
        for (i = 0; i < n - 1; i++) {
            swapped = false;
            for (j = 0; j < n - i - 1; j++) {
                if (isAlphabeticallySmaller(
                        arr[j + 1], arr[j])) {
                    // Swap arr[j] and arr[j+1]
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    swapped = true;
                }
            }
  
            // If no two elements were
            // swapped by inner loop,
            // then break
            if (swapped == false)
                break;
        }
    }
 
// Driver code
int main()
{
    vector<string> Arr
        = { "sun", "earth", "mars", "mercury" };
    int N = Arr.size();
    bubbleSort(Arr,N);
    for (int i = 0; i < N; i++) {
        cout << Arr[i] << "\n";
    }
    return 0;
}
// This code is contributed by Pushpesh Raj


Java




// Java code for the above approach:
 
public class GFG {
 
    static void bubbleSort(String[] arr, int n)
    {
        int i, j;
        String temp;
        boolean swapped;
        for (i = 0; i < n - 1; i++) {
            swapped = false;
            for (j = 0; j < n - i - 1; j++) {
                if (isAlphabeticallySmaller(
                        arr[j + 1], arr[j])) {
                    // Swap arr[j] and arr[j+1]
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    swapped = true;
                }
            }
 
            // If no two elements were
            // swapped by inner loop,
            // then break
            if (swapped == false)
                break;
        }
    }
 
    // Function to compare 2 words
    static boolean isAlphabeticallySmaller(
        String str1, String str2)
    {
        str1 = str1.toUpperCase();
        str2 = str2.toUpperCase();
        if (str1.compareTo(str2) < 0) {
            return true;
        }
        return false;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        String[] Arr
            = { "sun", "earth", "mars", "mercury" };
        int N = Arr.length;
        bubbleSort(Arr, N);
        for (int i = 0; i < N; i++) {
            System.out.println(Arr[i]);
        }
    }
}


Python3




# Function to compare 2 words
def is_alphabetically_smaller(str1, str2):
    str1 = str1.upper()
    str2 = str2.upper()
    if str1 < str2:
        return True
    return False
 
def bubble_sort(arr):
    n = len(arr)
    for i in range(n - 1):
        swapped = False
        for j in range(n - i - 1):
            if is_alphabetically_smaller(arr[j + 1], arr[j]):
                # Swap arr[j] and arr[j+1]
                temp = arr[j]
                arr[j] = arr[j + 1]
                arr[j + 1] = temp
                swapped = True
         
        # If no two elements were
        # swapped by inner loop,
        # then break
        if not swapped:
            break
 
# Test case
arr = ["sun", "earth", "mars", "mercury"]
bubble_sort(arr)
 
# Print the sorted list
for i in arr:
    print(i)
 
# This code is contributed by divyansh2212


C#




// C# code for the above approach:
 
// Include namespace system
using System;
 
public class GFG {
  public static void bubbleSort(String[] arr, int n)
  {
    int i;
    int j;
    String temp;
    bool swapped;
    for (i = 0; i < n - 1; i++) {
      swapped = false;
      for (j = 0; j < n - i - 1; j++) {
        if (GFG.isAlphabeticallySmaller(arr[j + 1],
                                        arr[j])) {
          // Swap arr[j] and arr[j+1]
          temp = arr[j];
          arr[j] = arr[j + 1];
          arr[j + 1] = temp;
          swapped = true;
        }
      }
      // If no two elements were
      // swapped by inner loop,
      // then break
      if (swapped == false) {
        break;
      }
    }
  }
  // Function to compare 2 words
  public static bool isAlphabeticallySmaller(String str1,
                                             String str2)
  {
    str1 = str1.ToUpper();
    str2 = str2.ToUpper();
    if (string.CompareOrdinal(str1, str2) < 0) {
      return true;
    }
    return false;
  }
  // Driver code
  public static void Main(String[] args)
  {
    String[] Arr
      = { "sun", "earth", "mars", "mercury" };
    var N = Arr.Length;
    GFG.bubbleSort(Arr, N);
    for (int i = 0; i < N; i++) {
      Console.WriteLine(Arr[i]);
    }
  }
}
 
// This code is contributed by mukulsomukesh


Javascript




// Javascript Program for the above approach.
 
 // Function to compare 2 words
function isAlphabeticallySmaller(str1, str2)
    {
       str1.toUpperCase();
       str2.toUpperCase();
        if (str1 < str2) {
            return true;
        }
        return false;
    }
 
function bubbleSort(arr, n)
    {
        let i, j;
        let temp="";
        let swapped= false;
        for (i = 0; i < n - 1; i++) {
            swapped = false;
            for (j = 0; j < n - i - 1; j++) {
                if (isAlphabeticallySmaller(
                        arr[j + 1], arr[j])) {
                    // Swap arr[j] and arr[j+1]
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    swapped = true;
                }
            }
  
            // If no two elements were
            // swapped by inner loop,
            // then break
            if (swapped == false)
                break;
        }
    }
 
 
    let Arr
        = [ "sun", "earth", "mars", "mercury" ];
    let N = Arr.length;
    bubbleSort(Arr,N);
    console.log(Arr);
     
    // This code is contributed by garg28harsh.


Output

earth
mars
mercury
sun

 
 

Time Complexity: O(K * N2) where K is the length of each word.
Auxiliary Space: O(1)

 

Insertion Sort Approach: The problem can also be solved using Insertion sort

 

In Insertion sort the array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed at the correct position in the sorted part.

 

Below is the implementation of the above approach:

 

C++




// C++ Program for the above approach.
#include <bits/stdc++.h>
using namespace std;
 
 // Function to compare 2 words
bool isAlphabeticallySmaller(
        string str1, string str2)
    {
        transform(str1.begin(), str1.end(), str1.begin(),
              ::toupper);
        transform(str2.begin(), str2.end(), str2.begin(),
              ::toupper);
        if (str1 < str2) {
            return true;
        }
        return false;
    }
 
// Function to sort array
// using insertion sort
void insertionSort(vector<string> &arr)
    {
        int n = arr.size();
        for (int i = 1; i < n; ++i) {
            string key = arr[i];
            int j = i - 1;
  
            // Move elements of arr[0..i-1],
            // that are greater than key,
            // to one position ahead
            // of their current position
            while (j >= 0
                   && isAlphabeticallySmaller(key, arr[j])) {
  
                arr[j + 1] = arr[j];
                j = j - 1;
            }
            arr[j + 1] = key;
        }
    }
  
 
// Driver code
int main()
{
    vector<string> Arr
        = { "sun", "earth", "mars", "mercury" };
    int N = Arr.size();
    insertionSort(Arr);
    for (int i = 0; i < N; i++) {
        cout << Arr[i] << "\n";
    }
    return 0;
}
// This code is contributed by Pushpesh Raj


Java




// Java program to sort array of strings
 
class GFG {
 
    // Function to sort array
    // using insertion sort
    static void insertionSort(String[] arr)
    {
        int n = arr.length;
        for (int i = 1; i < n; ++i) {
            String key = arr[i];
            int j = i - 1;
 
            // Move elements of arr[0..i-1],
            // that are greater than key,
            // to one position ahead
            // of their current position
            while (j >= 0
                   && isAlphabeticallySmaller(key, arr[j])) {
 
                arr[j + 1] = arr[j];
                j = j - 1;
            }
            arr[j + 1] = key;
        }
    }
 
    // Function to compare 2 words
    static boolean isAlphabeticallySmaller(
        String str1, String str2)
    {
        str1 = str1.toUpperCase();
        str2 = str2.toUpperCase();
        if (str1.compareTo(str2) < 0) {
            return true;
        }
        return false;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        String[] Arr
            = { "sun", "earth", "mars", "mercury" };
        int N = Arr.length;
        insertionSort(Arr);
        for (int i = 0; i < N; i++) {
            System.out.println(Arr[i]);
        }
    }
}


Python3




# Python3 Program for the above approach
 
# Function to compare 2 words
def isAlphabeticallySmaller(str1, str2):
    str1 = str1.upper()
    str2 = str2.upper()
    if (str1 < str2):
        return True
    return False
 
# Function to sort array
# using insertion sort
def insertionSort(arr):
    n = len(arr)
    for i in range(1,n):
        key = arr[i]
        j = i - 1
  
        # Move elements of arr[0..i-1],
        # that are greater than key,
        # to one position ahead
        # of their current position
        while j >= 0 and isAlphabeticallySmaller(key, arr[j]):
            arr[j + 1] = arr[j]
            j -= 1
        arr[j + 1] = key
 
# Driver code
arr = ["sun", "earth", "mars", "mercury"]
N = len(arr)
insertionSort(arr)
print(arr)
 
# This code is contributed by phasing17.


C#




// Include namespace system
using System;
 
 
// C# code for the above approach:
public class GFG
{
    public static void bubbleSort(String[] arr, int n)
    {
        int i;
        int j;
        String temp;
        bool swapped;
        for (i = 0; i < n - 1; i++)
        {
            swapped = false;
            for (j = 0; j < n - i - 1; j++)
            {
                if (GFG.isAlphabeticallySmaller(arr[j + 1], arr[j]))
                {
                    // Swap arr[j] and arr[j+1]
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    swapped = true;
                }
            }
            // If no two elements were
            // swapped by inner loop,
            // then break
            if (swapped == false)
            {
                break;
            }
        }
    }
    // Function to compare 2 words
    public static bool isAlphabeticallySmaller(String str1, String str2)
    {
        str1 = str1.ToUpper();
        str2 = str2.ToUpper();
        if (string.CompareOrdinal(str1,str2) < 0)
        {
            return true;
        }
        return false;
    }
    // Driver code
    public static void Main(String[] args)
    {
        String[] Arr = {"sun", "earth", "mars", "mercury"};
        var N = Arr.Length;
        GFG.bubbleSort(Arr, N);
        for (int i = 0; i < N; i++)
        {
            Console.WriteLine(Arr[i]);
        }
    }
}
// This code is contributed by mukulsomukesh


Javascript




// Javascript Program for the above approach.
 
 // Function to compare 2 words
function isAlphabeticallySmaller(str1, str2)
    {
        str1.toUpperCase();
        str2.toUpperCase();
        if (str1 < str2) {
            return true;
        }
        return false;
    }
 
// Function to sort array
// using insertion sort
function insertionSort(arr)
    {
        let n = arr.length;
        for (let  i = 1; i < n; ++i) {
            let key = arr[i];
            let j = i - 1;
  
            // Move elements of arr[0..i-1],
            // that are greater than key,
            // to one position ahead
            // of their current position
            while (j >= 0
                   && isAlphabeticallySmaller(key, arr[j])) {
  
                arr[j + 1] = arr[j];
                j = j - 1;
            }
            arr[j + 1] = key;
        }
    }
  
 
// Driver code
 
    let Arr
        = [ "sun", "earth", "mars", "mercury" ];
    let N = Arr.length;
    insertionSort(Arr);
    console.log(Arr);
     
    // This code is contributed by garg28harsh.


Output

earth
mars
mercury
sun

 
 

Output

earth
mars
mercury
sun

 

Time Complexity: O(K * N2)
Auxiliary Space: O(K) 

 

Efficient approach: The idea to solve the problem more efficiently is by using Merge Sort on the strings. 

 

Merge Sort is a Divide and Conquer algorithm. It divides the input array into two halves, calls itself for the two halves, and then merges the two sorted halves.

 

Follow the steps below to implement this approach:

 

If array has more than 1 element,

  • Divide the array Arr[] into two equal halves.
  • Call mergeSort() for first half and then second half.
  • Merge both the sorted array returned from above calls and return the merged array.

Else if array has only 1 element,

  • return an array consisting of this element only.

Function to merge 2 sorted arrays of string:

  • Create an array say arr3[].
  • Take another pointer say ‘idx’ initialized to 0.
  • Traverse both the arrays simultaneously using 2 pointers (lets say i and j)
  • If arr1[i] is lexicographically smaller than arr2[j].
    • Store arr1[i] in arr3[idx]
    • Increase i and idx by 1.
  • Else
    • Store arr2[j] in arr3[idx]
    • Increase j and idx by 1.

 

Below is the implementation of the above approach:

 

C++




// C++ program to sort
// arrays of strings using merge sort
#include <bits/stdc++.h>
using namespace std;
 
// Function to compare 2 words
bool isAlphabeticallySmaller(string str1, string str2)
{
    transform(str1.begin(), str1.end(), str1.begin(),
              ::toupper);
    transform(str2.begin(), str2.end(), str2.begin(),
              ::toupper);
    if (str1 < str2) {
        return true;
    }
    return false;
}
 
vector<string> merge(vector<string> Arr1,
                     vector<string> Arr2)
{
    int m = Arr1.size();
    int n = Arr2.size();
    vector<string> Arr3;
 
    int idx = 0;
 
    int i = 0;
    int j = 0;
    while (i < m && j < n) {
        if (isAlphabeticallySmaller(Arr1[i], Arr2[j])) {
            Arr3.push_back(Arr1[i]);
            i++;
            idx++;
        }
        else {
            Arr3.push_back(Arr2[j]);
            j++;
            idx++;
        }
    }
    while (i < m) {
        Arr3.push_back(Arr1[i]);
        i++;
        idx++;
    }
    while (j < n) {
        Arr3.push_back(Arr2[j]);
        j++;
        idx++;
    }
    return Arr3;
}
 
// Function to mergeSort 2 arrays
vector<string> mergeSort(vector<string> Arr, int lo, int hi)
{
    if (lo == hi) {
        vector<string> A = { Arr[lo] };
        return A;
    }
    int mid = lo + (hi - lo) / 2;
    vector<string> arr1 = mergeSort(Arr, lo, mid);
    vector<string> arr2 = mergeSort(Arr, mid + 1, hi);
 
    vector<string> arr3 = merge(arr1, arr2);
    return arr3;
}
 
// Driver code
int main()
{
    vector<string> Arr
        = { "sun", "earth", "mars", "mercury" };
    int N = Arr.size();
    vector<string> a = mergeSort(Arr, 0, N - 1);
    for (int i = 0; i < N; i++) {
        cout << a[i] << "\n";
    }
    return 0;
}
 
// This code is contributed by karandeep1234.


Java




// Java program to sort
// arrays of strings using merge sort
 
class GFG {
 
    // Function to mergeSort 2 arrays
    static String[] mergeSort(String[] Arr,
                              int lo, int hi)
    {
        if (lo == hi) {
            String[] A = { Arr[lo] };
           
            return A;
        }
        int mid = lo + (hi - lo) / 2;
        String[] arr1 = mergeSort(Arr, lo, mid);
        String[] arr2 = mergeSort(Arr, mid + 1, hi);
 
        String[] arr3 = merge(arr1, arr2);
        return arr3;
    }
 
    static String[] merge(
        String[] Arr1, String[] Arr2)
    {
        int m = Arr1.length;
        int n = Arr2.length;
        String[] Arr3 = new String[m + n];
 
        int idx = 0;
 
        int i = 0;
        int j = 0;
 
        while (i < m && j < n) {
            if (isAlphabeticallySmaller(
                    Arr1[i], Arr2[j])) {
 
                Arr3[idx] = Arr1[i];
                i++;
                idx++;
            }
            else {
                Arr3[idx] = Arr2[j];
                j++;
                idx++;
            }
        }
        while (i < m) {
            Arr3[idx] = Arr1[i];
            i++;
            idx++;
        }
        while (j < n) {
            Arr3[idx] = Arr2[j];
            j++;
            idx++;
        }
        return Arr3;
    }
 
    // Return true if str1 appears before
    // str2 in alphabetical order
    static boolean isAlphabeticallySmaller(
        String str1, String str2)
    {
        str1 = str1.toUpperCase();
        str2 = str2.toUpperCase();
        if (str1.compareTo(str2) < 0) {
            return true;
        }
        return false;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        String[] Arr
            = { "sun", "earth", "mars", "mercury" };
        String[] a = mergeSort(Arr, 0, Arr.length - 1);
        for (int i = 0; i < a.length; i++) {
            System.out.println(a[i]);
        }
    }
}


Python3




# Python program to sort arrays of strings using merge sort
 
# Function to compare 2 words
def is_alphabetically_smaller(str1, str2):
    str1 = str1.upper()
    str2 = str2.upper()
    if str1 < str2:
        return True
    return False
 
def merge(arr1, arr2):
    m = len(arr1)
    n = len(arr2)
    arr3 = []
 
    i = 0
    j = 0
    while i < m and j < n:
        if is_alphabetically_smaller(arr1[i], arr2[j]):
            arr3.append(arr1[i])
            i += 1
        else:
            arr3.append(arr2[j])
            j += 1
    while i < m:
        arr3.append(arr1[i])
        i += 1
    while j < n:
        arr3.append(arr2[j])
        j += 1
    return arr3
 
# Function to mergeSort 2 arrays
def merge_sort(arr, lo, hi):
    if lo == hi:
        return [arr[lo]]
    mid = lo + (hi - lo) // 2
    arr1 = merge_sort(arr, lo, mid)
    arr2 = merge_sort(arr, mid + 1, hi)
 
    arr3 = merge(arr1, arr2)
    return arr3
 
# Driver code
def main():
    arr = ["sun", "earth", "mars", "mercury"]
    n = len(arr)
    a = merge_sort(arr, 0, n - 1)
    for i in range(n):
        print(a[i])
 
main()
 
# This code is contributed by divyansh2212


C#




// C# program to sort arrays of
// strings using merge sort
using System;
 
public class GFG {
 
  // Function to mergeSort 2 arrays
  static string[] mergeSort(string[] Arr, int lo, int hi)
  {
    if (lo == hi) {
      string[] A = { Arr[lo] };
      return A;
    }
    int mid = lo + (hi - lo) / 2;
    string[] arr1 = mergeSort(Arr, lo, mid);
    string[] arr2 = mergeSort(Arr, mid + 1, hi);
 
    string[] arr3 = merge(arr1, arr2);
    return arr3;
  }
 
  static string[] merge(string[] Arr1, string[] Arr2)
  {
    int m = Arr1.Length;
    int n = Arr2.Length;
    string[] Arr3 = new string[m + n];
 
    int idx = 0;
 
    int i = 0;
    int j = 0;
 
    while (i < m && j < n) {
      if (isAlphabeticallySmaller(Arr1[i], Arr2[j])) {
 
        Arr3[idx] = Arr1[i];
        i++;
        idx++;
      }
      else {
        Arr3[idx] = Arr2[j];
        j++;
        idx++;
      }
    }
    while (i < m) {
      Arr3[idx] = Arr1[i];
      i++;
      idx++;
    }
    while (j < n) {
      Arr3[idx] = Arr2[j];
      j++;
      idx++;
    }
    return Arr3;
  }
 
  // Return true if str1 appears before
  // str2 in alphabetical order
  static bool isAlphabeticallySmaller(string str1,
                                      string str2)
  {
    str1 = str1.ToUpper();
    str2 = str2.ToUpper();
    if (string.Compare(str1, str2) < 0) {
      return true;
    }
    return false;
  }
 
  static public void Main()
  {
 
    // Code
    string[] Arr
      = { "sun", "earth", "mars", "mercury" };
    string[] a = mergeSort(Arr, 0, Arr.Length - 1);
    for (int i = 0; i < a.Length; i++) {
      Console.WriteLine(a[i]);
    }
  }
}
 
// This code is contributed by lokesh.


Javascript




// Javascript program to sort
// arrays of strings using merge sort
 
// Function to compare 2 words
function isAlphabeticallySmaller(str1, str2)
    {
        str1.toUpperCase();
        str2.toUpperCase();
        if (str1 < str2) {
            return true;
        }
        return false;
    }
 
 
function merge( Arr1, Arr2)
{
    let m = Arr1.length;
    let n = Arr2.length;
    let Arr3=[];
 
    let idx = 0;
 
    let i = 0;
    let j = 0;
    while (i < m && j < n) {
        if (isAlphabeticallySmaller(Arr1[i], Arr2[j]) == true) {
            Arr3.push(Arr1[i]);
            i++;
            idx++;
        }
        else {
            Arr3.push(Arr2[j]);
            j++;
            idx++;
        }
    }
    while (i < m) {
        Arr3.push(Arr1[i]);
        i++;
        idx++;
    }
    while (j < n) {
        Arr3.push(Arr2[j]);
        j++;
        idx++;
    }
    return Arr3;
}
 
// Function to mergeSort 2 arrays
function mergeSort(Arr, lo,  hi)
{
    // document.write(lo + " " + hi);
    if (lo >= hi) {
       let A = [ Arr[lo] ];
        return A;
    }
    let mid = lo + (hi - lo) / 2;
    mid = Math.round(mid-0.5);
    let arr1 = mergeSort(Arr, lo, mid);
    let arr2 = mergeSort(Arr, mid + 1, hi);
 
    let arr3 = merge(arr1, arr2);
    return arr3;
}
 
// Driver code
 
   let Arr
        = [ "sun", "earth", "mars", "mercury" ];
    let N = Arr.length;
    let a = mergeSort(Arr, 0, N - 1);
    console.log(a);
     
    // This code is contributed by garg28harsh.


 
 

Output

earth
mars
mercury
sun

 

Time Complexity: O(K * N * (log(N))
Auxiliary Space: O(N)

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads