Sort an array of strings according to string lengths using Map

Given an array of strings, we need to sort the array in increasing order of string lengths, using Map Data Structure. Examples:

Input: str[] = {“GeeksforGeeeks”, “I”, “from”, “am”} Output: I am from GeeksforGeeks Input: str[] = {“You”, “are”, “beautiful”, “looking”} Output: You are looking beautiful

Approach: The given approach is for Java using TreeMap

Below is the implementation of the above approach:

C++

 `// C++ program to sort an Array of``// Strings according to their lengths``// using Map``#include ``using` `namespace` `std;` `// Function to Sort the array of string``// according to lengths using Map``vector sortS(vector& str, ``int` `n)``{``    ``map<``int``, vector > m;``    ``for` `(``int` `i = 0; i < n; i++) {``        ``m[str[i].length()].push_back(str[i]);``    ``}` `    ``int` `temp = 0;``    ``for` `(``auto` `i : m) {``        ``for` `(``int` `j = 0; j < i.second.size(); j++) {``            ``str[temp] = i.second[j];``            ``temp++;``        ``}``    ``}` `    ``return` `str;``}` `// Function to print the sorted array of string``void` `printArraystring(vector str, ``int` `n)``{``    ``for` `(``int` `i = 0; i < n; i++)``        ``cout << str[i] << ``" "``;``}` `// Driver function``int` `main()``{``    ``vector arr;``      ``arr = { ``"GeeksforGeeks"``, ``"I"``, ``"from"``, ``"am"` `};``    ``int` `n = arr.size();` `    ``// Function to perform sorting``    ``arr = sortS(arr, n);` `    ``// Calling the function to print result``    ``printArraystring(arr, n);``}` `// This code is contributed by akashish__`

Java

 `// Java program to sort an Array of``// Strings according to their lengths``// using Map` `import` `java.util.*;``import` `java.util.Map.Entry;``import` `java.io.*;` `public` `class` `GFG {` `    ``// Function to Sort the array of string``    ``// according to lengths using Map``    ``static` `String[] sort(String[] str, ``int` `n)``    ``{``        ``TreeMap > map``            ``= ``new` `TreeMap >();` `        ``for` `(``int` `i = ``0``; i < n; i++) {` `            ``map.putIfAbsent(str[i].length(),``                            ``new` `ArrayList());``            ``map.get(str[i].length()).add(str[i]);``        ``}` `        ``int` `temp = ``0``;` `        ``for` `(Entry >``                 ``e : map.entrySet()) {` `            ``for` `(``int` `i = ``0``; i < e.getValue().size(); i++) {` `                ``str[temp] = e.getValue().get(i);``                ``temp++;``            ``}``        ``}``        ``return` `str;``    ``}` `    ``// 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``        ``arr = sort(arr, n);` `        ``// Calling the function to print result``        ``printArraystring(arr, n);``    ``}``}`

Python3

 `from` `collections ``import` `defaultdict` `# Function to Sort the array of string``# according to lengths using Map``def` `sort(``str``, n):``    ``map` `=` `defaultdict(``list``)``    ` `    ``for` `i ``in` `range``(n):``        ``map``[``len``(``str``[i])].append(``str``[i])``        ` `    ``return` `[val ``for` `key ``in` `sorted``(``map``) ``for` `val ``in` `map``[key]]` `# Driver function``arr ``=` `[``"GeeksforGeeks"``, ``"I"``, ``"from"``, ``"am"``]``n ``=` `len``(arr)` `# Function to perform sorting``arr ``=` `sort(arr, n)` `# Calling the function to print result``print``(arr)` `#  This code is contributed by akashish__`

C#

 `using` `System;``using` `System.Collections.Generic;` `using` `System.Linq;`  `public` `class` `GFG``{``  ` `    ``// Function to Sort the array of string``    ``// according to lengths using Map``    ``public` `static` `string``[] sort(``string``[] str, ``int` `n)``    ``{``        ``var` `map = ``new` `SortedDictionary<``int``, List<``string``>>();``      ` `       ``for` `(``int` `i = 0; i < n; i++)``        ``{``           ``map[str[i].Length] = ``new` `List<``string``>();``          ``}``      ` `        ``for` `(``int` `i = 0; i < n; i++)``        ``{``            ``map[str[i].Length].Add(str[i]);``        ``}``         ``var` `temp = 0;``        ``foreach` `(KeyValuePair<``int``, List<``string``>> e ``in` `map)``        ``{``            ` `            ``for` `(``int` `i = 0; i < e.Value.Count; i++)``            ``{``                ``str[temp] = e.Value[i];``                ``temp++;``            ``}``        ``}``        ``return` `str;``    ``}``  ` `    ``// 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``        ``arr = GFG.sort(arr, n);``      ` `        ``// Calling the function to print result``        ``GFG.printArraystring(arr, n);``    ``}``}` `// This code is contributed by aadityaburujwale.`

Javascript

 `// Function to Sort the array of string``// according to lengths using Map``function` `sort(str, n) {``    ``let map = ``new` `Map();``    ` `    ``for` `(let i = 0; i < n; i++) {``        ``let list = map.get(str[i].length);``        ``if` `(list === undefined) {``            ``list = [];``            ``list.push(str[i]);``            ``map.set(str[i].length, list);``        ``} ``else` `{``            ``list.push(str[i]);``            ``map.set(str[i].length, list);``        ``}``    ``}``    ``let sortedKeys = Array.from(map.keys()).sort((a, b) => a - b);``    ``let result = [];``    ``for` `(let key of sortedKeys) {``        ``result = result.concat(map.get(key));``    ``}``    ``return` `result;``}` `// Driver function``let arr = [``"GeeksforGeeks"``, ``"I"``, ``"from"``, ``"am"``];``let n = arr.length;` `// Function to perform sorting``arr = sort(arr, n);` `// Calling the function to print result``console.log(arr);` `// This code is contributed by akashish.`

Output:
`I am from GeeksforGeeks`

Previous
Next