Sort an array of strings according to string lengths | C ++ program to sort an Array of Strings according to their lengths ; Function to print the sorted array of string ; Function to Sort the array of string according to lengths . This function implements Insertion Sort . ; Insert s [ j ] at its correct position ; Function to print the sorted array of string ; Driver function ; Function to perform sorting ; Calling the function to print result
#include <iostream> NEW_LINE 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 ; }