Sort an array of strings according to string lengths
Last Updated :
17 Jul, 2025
Given an array arr[] of strings, which needs to be sorted in ascending order based on the lengths of the strings. If two strings have the same length, their original relative order must be preserved in the final output.
Examples:
Input: arr[] = ["GeeksforGeeeks", "I", "from", "am"]
Output: ["I", "am", "from", "GeeksforGeeks"]
Explanation: The strings are sorted in increasing order of their lengths, starting from the shortest string "I" to the longest one "GeeksforGeeeks".
Input: arr[] = ["You", "are", "beautiful", "looking"]
Output: ["You", "are", "looking", "beautiful"]
Explanation: The strings are sorted by length: "You", "are", "looking", and then "beautiful", with the shortest words appearing first and the longest last.
[Approach 1] Stable Sort - O(nlogn) in Time and O(n) in Space
Using a custom comparator, which compares two strings by checking if the first string’s length is smaller than the second. The stable_sort ensures that if two strings have the same length, their original relative order is preserved.
C++
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
// Function to sort strings based on their length
void sortByLength(vector<string> &s)
{
stable_sort(s.begin(), s.end(), [](const string &a, const string &b) {
return a.length() < b.length();
});
}
int main()
{
vector<string> arr = {"GeeksforGeeks", "I", "from", "am"};
sortByLength(arr);
for (const string &str : arr)
cout << str << " " ;
return 0;
}
Java
import java.util.Arrays;
import java.util.Comparator;
public class GfG {
// Function to sort strings based on their length
static void sortByLength(String[] s) {
Arrays.sort(s, Comparator.comparingInt(String::length));
}
public static void main(String[] args) {
String[] arr = {"GeeksforGeeks", "I", "from", "am"};
sortByLength(arr);
for (String str : arr) {
System.out.print(str + " ");
}
}
}
Python
# Function to sort strings based on their length
def sortByLength(s):
s.sort(key=len)
if __name__ == "__main__":
arr = ["GeeksforGeeks", "I", "from", "am"]
sortByLength(arr)
for word in arr:
print(word, end=" ")
C#
using System;
using System.Linq;
using System.Collections.Generic;
class GfG{
// Function to sort strings based on their length
static void sortByLength(ref string[] s){
s = s.OrderBy(str => str.Length).ToArray();
}
static void Main()
{
string[] arr = { "GeeksforGeeks", "I", "from", "am" };
sortByLength(ref arr);
foreach (string str in arr)
{
Console.Write(str + " ");
}
}
}
JavaScript
// Function to sort strings based on their length
function sortByLength(s) {
s.sort((a, b) => a.length - b.length);
}
// Driver Code
let arr = ["GeeksforGeeks", "I", "from", "am"];
sortByLength(arr);
for (let str of arr) {
process.stdout.write(str + " ");
}
OutputI am from GeeksforGeeks
[Approach 2] Merge Sort - O(nlogn) in Time and O(n) in Space
The main idea of this approach is to use the Merge Sort algorithm to sort a list of strings based on their lengths while maintaining their original order for strings of equal length, ensuring stability. The array is recursively divided into halves, and during the merge step, strings are compared by length and combined in sorted order.
C++
#include <iostream>
#include <vector>
using namespace std ;
// Merge two halves in a stable way
void merge(vector<string>& arr, int left, int mid, int right) {
int n1 = mid - left + 1 ;
int n2 = right - mid ;
vector<string> L(n1), R(n2) ;
// Copy data to temporary arrays
for (int i = 0; i < n1; i++)
L[i] = arr[left + i];
for (int j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];
int i = 0, j = 0, k = left;
// Merge the two halves in a stable way (by length)
while (i < n1 && j < n2) {
if (L[i].length() <= R[j].length()) {
arr[k++] = L[i++] ;
} else {
arr[k++] = R[j++] ;
}
}
// Copy remaining elements of L[]
while (i < n1) {
arr[k++] = L[i++] ;
}
// Copy remaining elements of R[]
while (j < n2) {
arr[k++] = R[j++] ;
}
}
// Merge Sort (recursive)
void mergeSort(vector<string>& arr, int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
mergeSort(arr, left, mid) ;
mergeSort(arr, mid + 1, right) ;
merge(arr, left, mid, right) ;
}
}
// Function to sort strings based on their length
void sortByLength(vector<string>& arr) {
mergeSort(arr, 0, arr.size() - 1) ;
}
int main() {
vector<string> arr = {"GeeksforGeeks", "I", "from", "am"} ;
sortByLength(arr) ;
for (auto& s : arr)
cout << s << " " ;
return 0 ;
}
Java
import java.util.Arrays;
public class GfG {
// Merge two halves in a stable way
static void merge(String[] arr, int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
String[] L = new String[n1];
String[] R = new String[n2];
// Copy data to temporary arrays
for (int i = 0; i < n1; i++)
L[i] = arr[left + i];
for (int j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];
int i = 0, j = 0, k = left;
// Merge the two halves in a stable way (by length)
while (i < n1 && j < n2) {
if (L[i].length() <= R[j].length()) {
arr[k++] = L[i++];
} else {
arr[k++] = R[j++];
}
}
// Copy remaining elements of L[]
while (i < n1) {
arr[k++] = L[i++];
}
// Copy remaining elements of R[]
while (j < n2) {
arr[k++] = R[j++];
}
}
// Merge Sort (recursive)
static void mergeSort(String[] arr, int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
// Function to sort strings based on their length
static void sortByLength(String[] arr) {
mergeSort(arr, 0, arr.length - 1);
}
public static void main(String[] args) {
String[] arr = {"GeeksforGeeks", "I", "from", "am"};
sortByLength(arr);
for (String s : arr)
System.out.print(s + " ");
}
}
Python
# Merge two halves in a stable way
def merge(arr, left, mid, right):
L = arr[left:mid + 1]
R = arr[mid + 1:right + 1]
i = j = 0
k = left
# Merge the two halves in a stable way (by length)
while i < len(L) and j < len(R):
if len(L[i]) <= len(R[j]):
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
# Copy remaining elements of L[]
while i < len(L):
arr[k] = L[i]
i += 1
k += 1
# Copy remaining elements of R[]
while j < len(R):
arr[k] = R[j]
j += 1
k += 1
# Merge Sort (recursive)
def mergeSort(arr, left, right):
if left < right:
mid = left + (right - left) // 2
mergeSort(arr, left, mid)
mergeSort(arr, mid + 1, right)
merge(arr, left, mid, right)
# Function to sort strings based on their length
def sortByLength(arr):
mergeSort(arr, 0, len(arr) - 1)
if __name__ == "__main__":
arr = ["GeeksforGeeks", "I", "from", "am"]
sortByLength(arr)
for s in arr:
print(s, end=" ")
C#
using System;
class GfG{
// Merge two halves in a stable way
static void Merge(string[] arr, int left, int mid, int right){
int n1 = mid - left + 1;
int n2 = right - mid;
string[] L = new string[n1];
string[] R = new string[n2];
// Copy data to temporary arrays
for (int i = 0; i < n1; i++)
L[i] = arr[left + i];
for (int j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];
int ii = 0, jj = 0, k = left;
// Merge the two halves in a stable way (by length)
while (ii < n1 && jj < n2){
if (L[ii].Length <= R[jj].Length)
arr[k++] = L[ii++];
else
arr[k++] = R[jj++];
}
// Copy remaining elements of L[]
while (ii < n1)
arr[k++] = L[ii++];
// Copy remaining elements of R[]
while (jj < n2)
arr[k++] = R[jj++];
}
// Merge Sort (recursive)
static void MergeSort(string[] arr, int left, int right)
{
if (left < right)
{
int mid = left + (right - left) / 2;
MergeSort(arr, left, mid);
MergeSort(arr, mid + 1, right);
Merge(arr, left, mid, right);
}
}
// Function to sort strings based on their length
static void sortByLength(ref string[] arr) {
MergeSort(arr, 0, arr.Length - 1);
}
static void Main()
{
string[] arr = { "GeeksforGeeks", "I", "from", "am" };
sortByLength(ref arr);
foreach (string s in arr)
Console.Write(s + " ");
}
}
JavaScript
// Merge two halves in a stable way
function merge(arr, left, mid, right) {
const L = arr.slice(left, mid + 1);
const R = arr.slice(mid + 1, right + 1);
let i = 0, j = 0, k = left;
// Merge the two halves in a stable way (by length)
while (i < L.length && j < R.length) {
if (L[i].length <= R[j].length) {
arr[k++] = L[i++];
} else {
arr[k++] = R[j++];
}
}
// Copy remaining elements of L[]
while (i < L.length) {
arr[k++] = L[i++];
}
// Copy remaining elements of R[]
while (j < R.length) {
arr[k++] = R[j++];
}
}
// Merge Sort (recursive)
function mergeSort(arr, left, right) {
if (left < right) {
const mid = Math.floor(left + (right - left) / 2);
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
// Function to sort strings based on their length
function sortByLength(arr) {
mergeSort(arr, 0, arr.length - 1);
}
let arr = ["GeeksforGeeks", "I", "from", "am"];
sortByLength(arr) ;
for (let s of arr) {
process.stdout.write(s + " ");
}
OutputI am from GeeksforGeeks
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
12 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Linked List Data Structure A linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read