Sort given words as Array of Strings
Last Updated :
30 Jan, 2023
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>
Outputearth
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.
Outputearth
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.
Outputearth
mars
mercury
sun
Outputearth
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.
Outputearth
mars
mercury
sun
Time Complexity: O(K * N * (log(N))
Auxiliary Space: O(N)
Similar Reads
How to sort an Array of Strings in Java
Array Of StringsTo sort an array of strings in Java, we can use Arrays.sort() function. Java // A sample Java program to // sort an array of strings // in ascending and descending // orders using Arrays.sort(). import java.util.Arrays; import java.util.Collections; // Driver Class public class SortE
3 min read
Sorting array of strings (or words) using Trie
Given an array of strings, print them in alphabetical (dictionary) order. If there are duplicates in input array, we need to print them only once. Examples: Input : "abc", "xy", "bcd" Output : abc bcd xy Input : "geeks", "for", "geeks", "a", "portal", "to", "learn", "can", "be", "computer", "science
8 min read
Most frequent word in an array of strings
Given an array of words arr[], The task is to find the most occurring word in arr[]. Examples: Input : arr[] = {"geeks", "for", "geeks", "a", "portal", "to", "learn", "can", "be", "computer", "science", "zoom", "yup", "fire", "in", "be", "data", "geeks"}Output : geeks Explanation : "geeks" is the mo
15+ min read
Sort the Array of Strings on the basis of given substring range
Given two positive integers I and X and an array of strings arr[], the task is to sort the given array of strings on the basis of substrings starting from index I of size X. Examples: Input: I = 2, X = 2, arr[] = { "baqwer", "zacaeaz", "aaqzzaa", "aacaap", "abbatyo", "bbbacztr", "bbbdaaa" } Output:
6 min read
Sort an array of strings based on the frequency of good words in them
Given a set of product reviews (R) by different customers and a string S containing good words separated by a _, the task is to sort the reviews in decreasing order of their goodness value. Goodness Value is defined by the number of good words present in that review. Examples: Input: S = "geeks_for_
15+ min read
Program to extract words from a given String
The task is to extract words from a given string. There may be one or more space between words. Examples: Input : geeks for geeks Output : geeks for geeks Input : I love coding. Output: I love coding We have discussed a solution in the below post. How to split a string in C/C++, Python and Java? In
3 min read
C Program to Sort an array of names or strings
Given an array of strings in which all characters are of the same case, write a C function to sort them alphabetically. The idea is to use qsort() in C and write a comparison function that uses strcmp() to compare two strings. C #include <stdio.h> #include <stdlib.h> #include <string.
2 min read
Count words present in a string
Given an array of words and a string, we need to count all words that are present in given string. Examples: Input : words[] = { "welcome", "to", "geeks", "portal"} str = "geeksforgeeks is a computer science portal for geeks." Output : 2 Two words "portal" and "geeks" is present in str. Input : word
6 min read
Sort string of characters
Given a string of lowercase characters from 'a' - 'z'. We need to write a program to print the characters of this string in sorted order.Examples: Input : "dcab" Output : "abcd"Input : "geeksforgeeks"Output : "eeeefggkkorss"Naive Approach - O(n Log n) TimeA simple approach is to use sorting algorith
5 min read
Sorting array of strings (or words) using Trie | Set-2 (Handling Duplicates)
Given an array of strings, print them in alphabetical (dictionary) order. If there are duplicates in input array, we need to print all the occurrences.Examples: Input : arr[] = { "abc", "xyz", "abcd", "bcd", "abc" } Output : abc abc abcd bcd xyz Input : arr[] = { "geeks", "for", "geeks", "a", "porta
9 min read