Skip to content
Related Articles

Related Articles

Improve Article
Sort an array of strings according to string lengths
  • Difficulty Level : Easy
  • Last Updated : 14 Jun, 2021

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.  

C++




// C++ program to sort an Array of
// Strings according to their lengths
#include<iostream>
using namespace std;
 
// 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.
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
void printArraystring(string str[], int n)
{
    for (int i=0; i<n; i++)
        cout << str[i] << " ";
}
 
// Driver function
int 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




// Java program to sort an Array of
// Strings according to their lengths
import 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 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
    sort(arr,n);
    // Calling the function to print result
    printArraystring(arr, n);
     
}
}

Python3




# Python3 program to sort an Array of
# Strings according to their lengths
 
# Function to print the sorted array of string
def 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 code
if __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#




     
// C# program to sort an Array of
// Strings according to their lengths
using 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

Javascript




<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>
Output
I am from GeeksforGeeks 

A better solution is to use 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

CPP




#include <bits/stdc++.h>
using namespace  std;
 
// Function to check the small string
bool compare(string &s1,string &s2)
{
    return s1.size() < s2.size();
}
 
// Function to print the sorted array of string
void printArraystring(string str[], int n)
{
    for (int i=0; i<n; i++)
        cout << str[i] << " ";
}
 
// Driver function
int 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;
}
Output



I am from GeeksforGeeks 

Method #2: Simplied solution using sorted() function in python

  1. Take string as list.
  2. Use the sorted function in python by providing key as len.

Below is the implementation:

Python3




# Python code for the above approach
def printsorted(arr):
   
    # Sorting using sorted function
    # providing key as len
    print(*sorted(arr, key=len))
 
 
# Driver code
arr = ["GeeksforGeeks", "I", "from", "am"]
 
# Passing list to printsorted function
printsorted(arr)
 
# this code is contributed by vikkycirus
Output
I am from GeeksforGeeks

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 you want to share more information about the topic discussed above. 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer DSA Live Classes




My Personal Notes arrow_drop_up
Recommended Articles
Page :