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)
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 Code // 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
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
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/C++ Code #include <stdio.h> #include <stdlib.h> #include
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 algori
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
Reverse words in a string
Given a string str, your task is to reverse the order of the words in the given string. Note that str may contain leading or trailing dots(.) or multiple trailing dots(.) between two words. The returned string should only have a single dot(.) separating the words. Examples: Input: str = "i.like.this
11 min read