Sort an array of strings according to string lengths
Last Updated :
07 Mar, 2023
We are given an array of strings, we need to sort the array in increasing order of string lengths.
Examples:
Input : {“GeeksforGeeeks”, “I”, “from”, “am”}
Output : I am from GeeksforGeeks
Input : {“You”, “are”, “beautiful”, “looking”}
Output : You are looking beautiful
A simple solution is to write our own sort function that compares string lengths to decide which string should come first. Below is the implementation, that uses Insertion Sort to sort the array.
Algorithm:
- Initialize the string with the input words.
- Calculate the string length.
- Sort the string array according to the length of words in ascending order With the help of insertion sort.
- Print the sorted array.
Below is the implementation of the above approach:
C++
#include<iostream>
using namespace std;
void printArraystring(string, int );
void sort(string s[], int n)
{
for ( int i=1 ;i<n; i++)
{
string temp = s[i];
int j = i - 1;
while (j >= 0 && temp.length() < s[j].length())
{
s[j+1] = s[j];
j--;
}
s[j+1] = temp;
}
}
void printArraystring(string str[], int n)
{
for ( int i=0; i<n; i++)
cout << str[i] << " " ;
}
int main()
{
string arr[] = { "GeeksforGeeks" , "I" , "from" , "am" };
int n = sizeof (arr)/ sizeof (arr[0]);
sort(arr, n);
printArraystring(arr, n);
return 0;
}
|
Java
import java.util.*;
class solution
{
static void sort(String []s, int n)
{
for ( int i= 1 ;i<n; i++)
{
String temp = s[i];
int j = i - 1 ;
while (j >= 0 && temp.length() < s[j].length())
{
s[j+ 1 ] = s[j];
j--;
}
s[j+ 1 ] = temp;
}
}
static void printArraystring(String str[], int n)
{
for ( int i= 0 ; i<n; i++)
System.out.print(str[i]+ " " );
}
public static void main(String args[])
{
String []arr = { "GeeksforGeeks" , "I" , "from" , "am" };
int n = arr.length;
sort(arr,n);
printArraystring(arr, n);
}
}
|
Python3
def printArraystring(string, n):
for i in range (n):
print (string[i], end = " " )
def sort(s, n):
for i in range ( 1 , n):
temp = s[i]
j = i - 1
while j > = 0 and len (temp) < len (s[j]):
s[j + 1 ] = s[j]
j - = 1
s[j + 1 ] = temp
if __name__ = = "__main__" :
arr = [ "GeeksforGeeks" , "I" , "from" , "am" ]
n = len (arr)
sort(arr, n)
printArraystring(arr, n)
|
C#
using System;
public class solution{
static void sort(String []s, int n)
{
for ( int i=1 ;i<n; i++)
{
String temp = s[i];
int j = i - 1;
while (j >= 0 && temp.Length < s[j].Length)
{
s[j+1] = s[j];
j--;
}
s[j+1] = temp;
}
}
static void printArraystring(String []str, int n)
{
for ( int i=0; i<n; i++)
Console.Write(str[i]+ " " );
}
public static void Main()
{
String []arr = { "GeeksforGeeks" , "I" , "from" , "am" };
int n = arr.Length;
sort(arr,n);
printArraystring(arr, n);
}
}
|
Javascript
<script>
function sort(s, n)
{
for (let i = 1 ; i < n; i++)
{
let temp = s[i];
let j = i - 1;
while (j >= 0 && temp.length < s[j].length)
{
s[j + 1] = s[j];
j--;
}
s[j + 1] = temp;
}
}
function printArraystring(str, n)
{
for (let i = 0; i < n; i++)
document.write(str[i]+ " " );
}
let arr = [ "GeeksforGeeks" , "I" , "from" , "am" ];
let n = arr.length;
sort(arr,n);
printArraystring(arr, n);
</script>
|
Output
I am from GeeksforGeeks
Time Complexity: O(n*m), where m is the length of the string and n is the size of the input array.
Auxiliary Space: O(1)
A better solution is to use the sort function provided by programming languages like C++, and Java. These functions also allow us to write our own custom comparator. Below is C++ implementation that uses C++ STL Sort function.
Algorithm:
- Initialize the string with the input words.
- Calculate the string length.
- Compare the strings and return the smallest one.
- Sort the string array with the help of the built-in sort function.
- Print the sorted array.
Below is the implementation of the above approach:
CPP
#include <bits/stdc++.h>
using namespace std;
bool compare(string &s1,string &s2)
{
return s1.size() < s2.size();
}
void printArraystring(string str[], int n)
{
for ( int i=0; i<n; i++)
cout << str[i] << " " ;
}
int main()
{
string arr[] = { "GeeksforGeeks" , "I" , "from" , "am" };
int n = sizeof (arr)/ sizeof (arr[0]);
sort(arr, arr+n, compare);
printArraystring(arr, n);
return 0;
}
|
Java
import java.util.Arrays;
import java.util.Comparator;
class GFG {
static void printArrayString(String str[], int n) {
for ( int i = 0 ; i < n; i++)
System.out.print(str[i] + " " );
}
public static void main(String[] args) {
String arr[] = { "GeeksforGeeks" , "I" , "from" , "am" };
int n = arr.length;
Arrays.sort(arr, Comparator.comparing(s->s.length()));
printArrayString(arr, n);
}
}
|
Python3
from functools import cmp_to_key
def compare(s1,s2):
return len (s1) - len (s2)
def printArraystring( str ,n):
for i in range (n):
print ( str [i],end = " " )
arr = [ "GeeksforGeeks" , "I" , "from" , "am" ]
n = len (arr)
arr.sort(key = cmp_to_key(compare))
printArraystring(arr, n)
|
C#
using System;
using System.Linq;
using System.Collections;
public class GFG
{
public static void printArrayString( string [] str, int n)
{
for ( int i = 0; i < n; i++)
{
Console.Write(str[i] + " " );
}
}
public static void Main(String[] args)
{
string [] arr = { "GeeksforGeeks" , "I" , "from" , "am" };
var n = arr.Length;
Array.Sort(arr,(s1,s2)=>s1.Length-s2.Length);
GFG.printArrayString(arr, n);
}
}
|
Javascript
<script>
function compare(s1, s2) {
return s1.length - s2.length;
}
function printArraystring(str, n) {
for (let i = 0; i < n; i++)
document.write(str[i] + " " );
}
let arr = [ "GeeksforGeeks" , "I" , "from" , "am" ]
let n = arr.length
arr.sort(compare);
printArraystring(arr, n);
</script>
|
Output
I am from GeeksforGeeks
Time Complexity: O(nlogn), where n is the size of the array.
Auxiliary Space: O(1)
Method 2: Simplified solution using sort function in python and javascript
- Take string as a list.
- Use the sort function in python and javascript, providing the key as len, in the python code.
Below is the implementation of the above approach:
C++
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
void printsorted(vector<string>& arr)
{
sort(arr.begin(), arr.end(), []( const string& a, const string& b) {
return a.length() < b.length();
});
for ( const auto & str : arr) {
cout << str << " " ;
}
cout << endl;
}
int main()
{
vector<string> arr = { "GeeksforGeeks" , "I" , "from" , "am" };
printsorted(arr);
return 0;
}
|
Java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class Main {
public static void printSorted(ArrayList<String> arr) {
Collections.sort(arr, Comparator.comparingInt(String::length));
for (String str : arr) {
System.out.print(str + " " );
}
System.out.println();
}
public static void main(String[] args) {
ArrayList<String> arr = new ArrayList<String>();
arr.add( "GeeksforGeeks" );
arr.add( "I" );
arr.add( "from" );
arr.add( "am" );
printSorted(arr);
}
}
|
Python3
def printsorted(arr):
print ( * sorted (arr, key = len ))
arr = [ "GeeksforGeeks" , "I" , "from" , "am" ]
printsorted(arr)
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
public class Program {
static void printsorted(List< string > arr) {
arr = arr.OrderBy(s => s.Length).ToList();
foreach ( var str in arr) {
Console.Write(str + " " );
}
Console.WriteLine();
}
static void Main() {
List< string > arr = new List< string > { "GeeksforGeeks" , "I" , "from" , "am" };
printsorted(arr);
}
}
|
Javascript
function printsorted(arr) {
arr.sort((a, b) => a.length - b.length);
console.log(...arr);
}
let arr = [ "GeeksforGeeks" , "I" , "from" , "am" ];
printsorted(arr);
|
Output
I am from GeeksforGeeks
Time Complexity: O(nlogn)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...