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++
#include <bits/stdc++.h>
using namespace std;
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();
for ( int i = 0; i < n - 1; i++) {
int min_idx = i;
for ( int j = i + 1; j < n; j++)
if (isAlphabeticallySmaller(arr[j],
arr[min_idx]))
min_idx = j;
string temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
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" ;
}
return 0;
}
|
Java
class GFG {
static void selectionSort(String[] arr)
{
int n = arr.length;
for ( int i = 0 ; i < n - 1 ; i++) {
int min_idx = i;
for ( int j = i + 1 ; j < n; j++)
if (isAlphabeticallySmaller(
arr[j], arr[min_idx]))
min_idx = j;
String temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
static boolean isAlphabeticallySmaller(
String str1, String str2)
{
str1 = str1.toUpperCase();
str2 = str2.toUpperCase();
if (str1.compareTo(str2) < 0 ) {
return true ;
}
return false ;
}
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
def selectionSort(arr):
n = len (arr)
for i in range (n - 1 ):
min_idx = i
for j in range (i + 1 , n):
if (isAlphabeticallySmaller(arr[j], arr[min_idx])):
min_idx = j
temp = arr[min_idx]
arr[min_idx] = arr[i]
arr[i] = temp
return arr
def isAlphabeticallySmaller(str1, str2):
str1 = str1.upper()
str2 = str2.upper()
if str1 < str2:
return True
return False
Arr = [ "sun" , "earth" , "mars" , "mercury" ]
N = len (Arr)
Arr = selectionSort(Arr)
for word in Arr:
print (word)
|
C#
using System;
public class GFG
{
static void selectionSort( string [] arr)
{
int n = arr.Length;
for ( int i = 0; i < n - 1; i++) {
int min_idx = i;
for ( int j = i + 1; j < n; j++)
if (isAlphabeticallySmaller(
arr[j], arr[min_idx]))
min_idx = j;
String temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
static bool isAlphabeticallySmaller(
string str1, String str2)
{
str1 = str1.ToUpper();
str2 = str2.ToUpper();
if (str1.CompareTo(str2) < 0) {
return true ;
}
return false ;
}
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]);
}
}
}
|
Javascript
<script>
function selectionSort(arr)
{
let n = arr.length;
for (let i = 0; i < n - 1; i++) {
let min_idx = i;
for (let j = i + 1; j < n; j++)
if (isAlphabeticallySmaller(
arr[j], arr[min_idx]))
min_idx = j;
let temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
function isAlphabeticallySmaller(
str1, str2)
{
str1 = str1.toUpperCase();
str2 = str2.toUpperCase();
if (str1.localeCompare(str2) == -1) {
return true ;
}
return false ;
}
let Arr
= [ "sun" , "earth" , "mars" , "mercury" ];
let N = Arr.length;
selectionSort(Arr);
for (let i = 0; i < N; i++) {
document.write(Arr[i] + "<br/>" );
}
</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++
#include <bits/stdc++.h>
using namespace std;
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])) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true ;
}
}
if (swapped == false )
break ;
}
}
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;
}
|
Java
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])) {
temp = arr[j];
arr[j] = arr[j + 1 ];
arr[j + 1 ] = temp;
swapped = true ;
}
}
if (swapped == false )
break ;
}
}
static boolean isAlphabeticallySmaller(
String str1, String str2)
{
str1 = str1.toUpperCase();
str2 = str2.toUpperCase();
if (str1.compareTo(str2) < 0 ) {
return true ;
}
return false ;
}
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
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]):
temp = arr[j]
arr[j] = arr[j + 1 ]
arr[j + 1 ] = temp
swapped = True
if not swapped:
break
arr = [ "sun" , "earth" , "mars" , "mercury" ]
bubble_sort(arr)
for i in arr:
print (i)
|
C#
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])) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true ;
}
}
if (swapped == false ) {
break ;
}
}
}
public static bool isAlphabeticallySmaller(String str1,
String str2)
{
str1 = str1.ToUpper();
str2 = str2.ToUpper();
if ( string .CompareOrdinal(str1, str2) < 0) {
return true ;
}
return false ;
}
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]);
}
}
}
|
Javascript
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])) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true ;
}
}
if (swapped == false )
break ;
}
}
let Arr
= [ "sun" , "earth" , "mars" , "mercury" ];
let N = Arr.length;
bubbleSort(Arr,N);
console.log(Arr);
|
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++
#include <bits/stdc++.h>
using namespace std;
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 insertionSort(vector<string> &arr)
{
int n = arr.size();
for ( int i = 1; i < n; ++i) {
string key = arr[i];
int j = i - 1;
while (j >= 0
&& isAlphabeticallySmaller(key, arr[j])) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
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;
}
|
Java
class GFG {
static void insertionSort(String[] arr)
{
int n = arr.length;
for ( int i = 1 ; i < n; ++i) {
String key = arr[i];
int j = i - 1 ;
while (j >= 0
&& isAlphabeticallySmaller(key, arr[j])) {
arr[j + 1 ] = arr[j];
j = j - 1 ;
}
arr[j + 1 ] = key;
}
}
static boolean isAlphabeticallySmaller(
String str1, String str2)
{
str1 = str1.toUpperCase();
str2 = str2.toUpperCase();
if (str1.compareTo(str2) < 0 ) {
return true ;
}
return false ;
}
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
def isAlphabeticallySmaller(str1, str2):
str1 = str1.upper()
str2 = str2.upper()
if (str1 < str2):
return True
return False
def insertionSort(arr):
n = len (arr)
for i in range ( 1 ,n):
key = arr[i]
j = i - 1
while j > = 0 and isAlphabeticallySmaller(key, arr[j]):
arr[j + 1 ] = arr[j]
j - = 1
arr[j + 1 ] = key
arr = [ "sun" , "earth" , "mars" , "mercury" ]
N = len (arr)
insertionSort(arr)
print (arr)
|
C#
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]))
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true ;
}
}
if (swapped == false )
{
break ;
}
}
}
public static bool isAlphabeticallySmaller(String str1, String str2)
{
str1 = str1.ToUpper();
str2 = str2.ToUpper();
if ( string .CompareOrdinal(str1,str2) < 0)
{
return true ;
}
return false ;
}
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]);
}
}
}
|
Javascript
function isAlphabeticallySmaller(str1, str2)
{
str1.toUpperCase();
str2.toUpperCase();
if (str1 < str2) {
return true ;
}
return false ;
}
function insertionSort(arr)
{
let n = arr.length;
for (let i = 1; i < n; ++i) {
let key = arr[i];
let j = i - 1;
while (j >= 0
&& isAlphabeticallySmaller(key, arr[j])) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
let Arr
= [ "sun" , "earth" , "mars" , "mercury" ];
let N = Arr.length;
insertionSort(Arr);
console.log(Arr);
|
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++
#include <bits/stdc++.h>
using namespace std;
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;
}
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;
}
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;
}
|
Java
class GFG {
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;
}
static boolean isAlphabeticallySmaller(
String str1, String str2)
{
str1 = str1.toUpperCase();
str2 = str2.toUpperCase();
if (str1.compareTo(str2) < 0 ) {
return true ;
}
return false ;
}
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
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
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
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()
|
C#
using System;
public class GFG {
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;
}
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()
{
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]);
}
}
}
|
Javascript
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 mergeSort(Arr, 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;
}
let Arr
= [ "sun" , "earth" , "mars" , "mercury" ];
let N = Arr.length;
let a = mergeSort(Arr, 0, N - 1);
console.log(a);
|
Output
earth
mars
mercury
sun
Time Complexity: O(K * N * (log(N))
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...