Open In App

Sort an array of strings according to string lengths

Improve
Improve
Like Article
Like
Save
Share
Report

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: 

  1. Initialize the string with the input words.
  2. Calculate the string length.
  3. Sort the string array according to the length of words in ascending order With the help of insertion sort. 
  4. Print the sorted array.

Below is the implementation of the above approach:

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 

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:

  1. Initialize the string with the input words.
  2. Calculate the string length.
  3. Compare the strings and return the smallest one.
  4. Sort the string array with the help of the built-in sort function.
  5. Print the sorted array.

Below is the implementation of the above approach:

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;
}


Java




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, Comparator.comparing(s->s.length()));
 
    // Calling the function to print result
    printArrayString(arr, n);
  }
}
 
// This code is contributed by 29AjayKumar


Python3




from functools import cmp_to_key
 
# Function to check the small string
def compare(s1,s2):
    return len(s1) - len(s2)
 
# Function to print the sorted array of string
def printArraystring(str,n):
    for i in range(n):
        print(str[i],end = " ")
 
# Driver function
arr = ["GeeksforGeeks", "I", "from", "am"]
n = len(arr)
 
# Function to perform sorting
arr.sort(key = cmp_to_key(compare))
 
# Calling the function to print result
printArraystring(arr, n)
 
# This code is contributed by shinjanpatra.


C#




// Include namespace system
using System;
using System.Linq;
 
using System.Collections;
 
public class GFG
{
  // Function to check the small String
  // Function to print the sorted array of String
  public 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[] args)
  {
    string[] arr = {"GeeksforGeeks", "I", "from", "am"};
    var n = arr.Length;
 
    // Function to perform sorting
    Array.Sort(arr,(s1,s2)=>s1.Length-s2.Length);
 
    // Calling the function to print result
    GFG.printArrayString(arr, n);
  }
}
 
// This code is contributed by aadityaburujwale.


Javascript




<script>
 
// Function to check the small string
function compare(s1, s2) {
    return s1.length - s2.length;
}
 
// Function to print the sorted array of string
function printArraystring(str, n) {
    for (let i = 0; i < n; i++)
        document.write(str[i] + " ");
}
 
// Driver function
let arr = ["GeeksforGeeks", "I", "from", "am"]
let n = arr.length
 
// Function to perform sorting
arr.sort(compare);
 
// Calling the function to print result
printArraystring(arr, n);
 
// This code is contributed by gfgking.
</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

  1. Take string as a list.
  2. 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++




// C++ program for the above approach
 
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
 
using namespace std;
 
// Function to print the strings in sorted order by their length
void printsorted(vector<string>& arr)
{
    // Sorting the vector based on string length using sort function
    sort(arr.begin(), arr.end(), [](const string& a, const string& b) {
        return a.length() < b.length();
    });
 
    // Printing the sorted strings
    for (const auto& str : arr) {
        cout << str << " ";
    }
    cout << endl;
}
 
// Driver code
int main()
{
    vector<string> arr = {"GeeksforGeeks", "I", "from", "am"};
 
    // Calling the printsorted function
    printsorted(arr);
 
    return 0;
}
 
// This code is contributed by Prince


Java




// Java program for the above approach
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
 
public class Main {
     
    // Function to print the strings in sorted order by their length
    public static void printSorted(ArrayList<String> arr) {
       
        // Sorting the ArrayList based on string length using Collections.sort()
        Collections.sort(arr, Comparator.comparingInt(String::length));
 
        // Printing the sorted strings
        for (String str : arr) {
            System.out.print(str + " ");
        }
        System.out.println();
    }
 
    // Driver code
    public static void main(String[] args) {
        ArrayList<String> arr = new ArrayList<String>();
        arr.add("GeeksforGeeks");
        arr.add("I");
        arr.add("from");
        arr.add("am");
 
        // Calling the printSorted function
        printSorted(arr);
    }
}


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


C#




using System;
using System.Collections.Generic;
using System.Linq;
 
public class Program {
    // Function to print the strings in sorted order by their length
    static void printsorted(List<string> arr) {
        // Sorting the list based on string length using LINQ
        arr = arr.OrderBy(s => s.Length).ToList();
 
        // Printing the sorted strings
        foreach (var str in arr) {
            Console.Write(str + " ");
        }
        Console.WriteLine();
    }
 
    static void Main() {
        List<string> arr = new List<string> {"GeeksforGeeks", "I", "from", "am"};
 
        // Calling the printsorted function
        printsorted(arr);
    }
}


Javascript




// JavaScript code for the above approach
 
function printsorted(arr) {
// Sorting using sort method
// providing compare function as per length of elements
arr.sort((a, b) => a.length - b.length);
console.log(...arr);
}
 
// Driver code
let arr = ["GeeksforGeeks", "I", "from", "am"];
 
// Passing array to printsorted function
printsorted(arr);


Output

I am from GeeksforGeeks

Time Complexity: O(nlogn)
Auxiliary Space: O(1)



Last Updated : 07 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads