Sort an array of strings according to string lengths

22 Jun, 2022
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.
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++
Java
Python3
C#
Javascript
// C++ program to sort an Array of// Strings according to their lengths#include<iostream>using namespace std; // Function to print the sorted array of stringvoid printArraystring(string,int); // Function to Sort the array of string// according to lengths. This function// implements Insertion Sort.void sort(string s[], int n){    for (int i=1 ;i<n; i++)    {        string temp = s[i];         // Insert s[j] at its correct position        int j = i - 1;        while (j >= 0 && temp.length() < s[j].length())        {            s[j+1] = s[j];            j--;        }        s[j+1] = temp;    }}  // Function to print the sorted array of stringvoid printArraystring(string str[], int n){    for (int i=0; i<n; i++)        cout << str[i] << " ";} // Driver functionint main(){    string arr[] = {"GeeksforGeeks", "I", "from", "am"};    int n = sizeof(arr)/sizeof(arr[0]);         // Function to perform sorting    sort(arr, n);     // Calling the function to print result    printArraystring(arr, n);         return 0;}
// Java program to sort an Array of// Strings according to their lengthsimport java.util.*; class solution{ // Function to print the sorted array of string// void printArraystring(string,int); // Function to Sort the array of string// according to lengths. This function// implements Insertion Sort.static void sort(String []s, int n){    for (int i=1 ;i<n; i++)    {        String temp = s[i];         // Insert s[j] at its correct position        int j = i - 1;        while (j >= 0 && temp.length() < s[j].length())        {            s[j+1] = s[j];            j--;        }        s[j+1] = temp;    }} // Function to print the sorted array of stringstatic void printArraystring(String str[], int n){    for (int i=0; i<n; i++)        System.out.print(str[i]+" ");} // Driver functionpublic static void main(String args[]){    String []arr = {"GeeksforGeeks", "I", "from", "am"};    int n = arr.length;         // Function to perform sorting    sort(arr,n);    // Calling the function to print result    printArraystring(arr, n);     }}
# Python3 program to sort an Array of# Strings according to their lengths # Function to print the sorted array of stringdef printArraystring(string, n):    for i in range(n):        print(string[i], end = " ") # Function to Sort the array of string# according to lengths. This function# implements Insertion Sort.def sort(s, n):    for i in range(1, n):        temp = s[i]         # Insert s[j] at its correct position        j = i - 1        while j >= 0 and len(temp) < len(s[j]):            s[j + 1] = s[j]            j -= 1         s[j + 1] = temp # Driver codeif __name__ == "__main__":    arr = ["GeeksforGeeks", "I", "from", "am"]    n = len(arr)     # Function to perform sorting    sort(arr, n)     # Calling the function to print result    printArraystring(arr, n) # This code is contributed by# sanjeev2552
     // C# program to sort an Array of// Strings according to their lengthsusing System;  public class solution{     // Function to print the sorted array of string    // void printArraystring(string,int);     // Function to Sort the array of string    // according to lengths. This function    // implements Insertion Sort.    static void sort(String []s, int n)    {        for (int i=1 ;i<n; i++)        {            String temp = s[i];             // Insert s[j] at its correct position            int j = i - 1;            while (j >= 0 && temp.Length < s[j].Length)            {                s[j+1] = s[j];                j--;            }            s[j+1] = temp;        }    }     // Function to print the sorted array of string    static void printArraystring(String []str, int n)    {        for (int i=0; i<n; i++)            Console.Write(str[i]+" ");    }     // Driver function    public static void Main()    {        String []arr = {"GeeksforGeeks", "I", "from", "am"};        int n = arr.Length;         // Function to perform sorting        sort(arr,n);        // Calling the function to print result        printArraystring(arr, n);     }} // This code is contributed by Rajput-Ji
<script>    // Javascript program to sort an Array of    // Strings according to their lengths         // Function to print the sorted array of string    // void printArraystring(string,int);      // Function to Sort the array of string    // according to lengths. This function    // implements Insertion Sort.    function sort(s, n)    {        for (let i = 1 ; i < n; i++)        {            let temp = s[i];              // Insert s[j] at its correct position            let j = i - 1;            while (j >= 0 && temp.length < s[j].length)            {                s[j + 1] = s[j];                j--;            }            s[j + 1] = temp;        }    }      // Function to print the sorted array of string    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;     // Function to perform sorting    sort(arr,n);    // Calling the function to print result    printArraystring(arr, n); // This code is contributed by vaibhavrabadiya117.</script>
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++, 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.
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
Java
Javascript
Python3
#include <bits/stdc++.h>using namespace  std; // Function to check the small stringbool compare(string &s1,string &s2){    return s1.size() < s2.size();} // Function to print the sorted array of stringvoid printArraystring(string str[], int n){    for (int i=0; i<n; i++)        cout << str[i] << " ";} // Driver functionint main(){    string arr[] = {"GeeksforGeeks", "I", "from", "am"};    int n = sizeof(arr)/sizeof(arr[0]);         // Function to perform sorting    sort(arr, arr+n, compare);     // Calling the function to print result    printArraystring(arr, n);         return 0;}
import java.util.Arrays;import java.util.Comparator; class GFG {   // Function to check the small String   // Function to print the sorted array of String  static void printArrayString(String str[], int n) {    for (int i = 0; i < n; i++)      System.out.print(str[i] + " ");  }   // Driver function  public static void main(String[] args) {    String arr[] = { "GeeksforGeeks", "I", "from", "am" };    int n = arr.length;     // Function to perform sorting    Arrays.sort(arr, new Comparator<String>() {       @Override      public int compare(final String s1, final String s2) {        return s1.length() < s2.length() ? -1 : 1;      }    });     // Calling the function to print result    printArrayString(arr, n);  }} // This code is contributed by 29AjayKumar
<script> // Function to check the small stringfunction compare(s1, s2) {    return s1.length - s2.length;} // Function to print the sorted array of stringfunction printArraystring(str, n) {    for (let i = 0; i < n; i++)        document.write(str[i] + " ");} // Driver functionlet arr = ["GeeksforGeeks", "I", "from", "am"]let n = arr.length // Function to perform sortingarr.sort(compare); // Calling the function to print resultprintArraystring(arr, n); // This code is contributed by gfgking.</script>
from functools import cmp_to_key # Function to check the small stringdef compare(s1,s2):    return len(s1) - len(s2) # Function to print the sorted array of stringdef printArraystring(str,n):    for i in range(n):        print(str[i],end = " ") # Driver functionarr = ["GeeksforGeeks", "I", "from", "am"]n = len(arr) # Function to perform sortingarr.sort(key = cmp_to_key(compare)) # Calling the function to print resultprintArraystring(arr, n) # This code is contributed by shinjanpatra.
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 sorted() function in python
Take string as a list.Use the sorted function in python by providing the key as len.
Take string as a list.
Use the sorted function in python by providing the key as len.
Below is the implementation of the above approach:
Python3
# Python code for the above approachdef printsorted(arr):       # Sorting using sorted function    # providing key as len    print(*sorted(arr, key=len))  # Driver codearr = ["GeeksforGeeks", "I", "from", "am"] # Passing list to printsorted functionprintsorted(arr) # this code is contributed by vikkycirus
I am from GeeksforGeeks
Time Complexity: O(nlogn)Auxiliary Space: O(1)
This article is contributed by Rishabh jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. 
SURENDRA_GANGWAR
Rajput-Ji
sanjeev2552
vikkycirus
vaibhavrabadiya117
surinderdawra388
gfgking
29AjayKumar
shinjanpatra
youmailmahibagi
lucidcoder121
cpp-strings-library
STL
Sorting
Strings
Strings
Sorting
STL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge Sort
Bubble Sort Algorithm
QuickSort
Insertion Sort
Selection Sort Algorithm
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Different Methods to Reverse a String in C++