Sort an Array of Strings according to the number of Vowels in them

11 Jun, 2021
Given an array arr[] of N strings, the task is to sort these strings according to the numbers of vowels in them.
Examples: 
Input: arr[] = { “geeks”, “for”, “coding” } Output: for, coding, geeks for -> o = 1 vowel coding -> o, i = 2 vowels geeks -> e, e = 2 vowels
Input: arr[] = { “lmno”, “pqrst”, “aeiou”, “xyz” } Output: pqrst, xyz, lmno, aeiou  
Approach: The idea is to store each element with its number of vowels in a vector pair and then sort all the elements of the vector according to the number of vowels stored. Finally, print the strings in order.
Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach #include <bits/stdc++.h>using namespace std; // Function to check the Vowelbool isVowel(char ch){    ch = toupper(ch);    return (ch == 'A' || ch == 'E'            || ch == 'I' || ch == 'O'            || ch == 'U');} // Returns count of vowels in strint countVowels(string str){    int count = 0;    for (int i = 0; i < str.length(); i++)        if (isVowel(str[i])) // Check for vowel            ++count;    return count;} // Function to sort the array according to// the number of the vowelsvoid sortArr(string arr[], int n){    // Vector to store the number of vowels    // with respective elements    vector<pair<int, string> > vp;     // Inserting number of vowels    // with respective strings    // in the vector pair    for (int i = 0; i < n; i++) {         vp.push_back(            make_pair(                countVowels(                    arr[i]),                arr[i]));    }     // Sort the vector, this will sort the pair    // according to the number of vowels    sort(vp.begin(), vp.end());     // Print the sorted vector content    for (int i = 0; i < vp.size(); i++)        cout << vp[i].second << " ";} // Driver codeint main(){    string arr[] = { "lmno", "pqrst",                     "aeiou", "xyz" };    int n = sizeof(arr) / sizeof(arr[0]);     sortArr(arr, n);     return 0;}
// Java implementation of the approachimport java.util.*;import java.lang.*;import java.io.*; class GFG{ static class pair{    int first;    String second;         pair(int first,String second)    {        this.first = first;        this.second = second;    }} // Function to check the Vowelstatic boolean isVowel(char ch){    ch = Character.toUpperCase(ch);    return (ch == 'A' || ch == 'E' ||            ch == 'I' || ch == 'O' ||            ch == 'U');} // Returns count of vowels in strstatic int countVowels(String str){    int count = 0;    for(int i = 0; i < str.length(); i++)             // Check for vowel        if (isVowel(str.charAt(i)))            ++count;                 return count;} // Function to sort the array according to// the number of the vowelsstatic void sortArr(String arr[], int n){         // Vector to store the number of vowels    // with respective elements    ArrayList<pair> vp = new ArrayList<>();     // Inserting number of vowels    // with respective strings    // in the vector pair    for(int i = 0; i < n; i++)    {        vp.add(new pair(countVowels(arr[i]),                                    arr[i]));    }     // Sort the vector, this will sort the pair    // according to the number of vowels    Collections.sort(vp, (a, b) -> a.first - b.first);         // Print the sorted vector content    for(int i = 0; i < vp.size(); i++)        System.out.print(vp.get(i).second + " ");} // Driver codepublic static void main(String[] args){    String arr[] = { "lmno", "pqrst",                     "aeiou", "xyz" };    int n = arr.length;         sortArr(arr, n);}} // This code is contributed by offbeat
# Python3 implementation of the approach # Function to check the Voweldef isVowel(ch) :         ch = ch.upper();    return (ch == 'A' or ch == 'E'or ch == 'I' or            ch == 'O'or ch == 'U'); # Returns count of vowels in strdef countVowels(string) :     count = 0;    for i in range(len(string)) :                 # Check for vowel        if (isVowel(string[i])) :            count += 1;                 return count; # Function to sort the array according to# the number of the vowelsdef sortArr(arr, n) :         # Vector to store the number of vowels    # with respective elements    vp = [];     # Inserting number of vowels    # with respective strings    # in the vector pair    for i in range(n) :         vp.append((countVowels(arr[i]),arr[i]));     # Sort the vector, this will sort the pair    # according to the number of vowels    vp.sort()     # Print the sorted vector content    for i in range(len(vp)) :        print(vp[i][1], end= " "); # Driver codeif __name__ == "__main__" :    arr = [ "lmno", "pqrst","aeiou", "xyz" ];    n = len(arr);     sortArr(arr, n); # This code is contributed by AnkitRai01
// C# implementation of the approachusing System;using System.Collections.Generic;class GFG{         // Function to check the Vowel    static bool isVowel(char ch)    {        ch = char.ToUpper(ch);        return (ch == 'A' || ch == 'E'                || ch == 'I' || ch == 'O'                || ch == 'U');    }          // Returns count of vowels in str    static int countVowels(string str)    {        int count = 0;        for (int i = 0; i < str.Length; i++)            if (isVowel(str[i])) // Check for vowel                ++count;        return count;    }          // Function to sort the array according to    // the number of the vowels    static void sortArr(string[] arr, int n)    {               // Vector to store the number of vowels        // with respective elements        List<Tuple<int, string>> vp = new List<Tuple<int, string>>();              // Inserting number of vowels        // with respective strings        // in the vector pair        for (int i = 0; i < n; i++)        {             vp.Add(new Tuple<int, string>(countVowels(arr[i]), arr[i]));        }              // Sort the vector, this will sort the pair        // according to the number of vowels        vp.Sort();              // Print the sorted vector content        for (int i = 0; i < vp.Count; i++)            Console.Write(vp[i].Item2 + " ");    }        // Driver code  static void Main()  {    string[] arr = { "lmno", "pqrst",                     "aeiou", "xyz" };    int n = arr.Length;    sortArr(arr, n);  }} // This code is contributed by divyesh072019
<script>     // JavaScript implementation of the approach         // Function to check the Vowel    function isVowel(ch)    {        ch = ch.toUpperCase();        return (ch == 'A' || ch == 'E'                || ch == 'I' || ch == 'O'                || ch == 'U');    }           // Returns count of vowels in str    function countVowels(str)    {        let count = 0;        for (let i = 0; i < str.length; i++)            if (isVowel(str[i])) // Check for vowel                ++count;        return count;    }           // Function to sort the array according to    // the number of the vowels    function sortArr(arr, n)    {                // Vector to store the number of vowels        // with respective elements        let vp = [];               // Inserting number of vowels        // with respective strings        // in the vector pair        for (let i = 0; i < n; i++)        {            vp.push([countVowels(arr[i]), arr[i]]);        }               // Sort the vector, this will sort the pair        // according to the number of vowels        vp.sort();               // Print the sorted vector content        for (let i = 0; i < vp.length; i++)            document.write(vp[i][1] + " ");    }         let arr = [ "lmno", "pqrst", "aeiou", "xyz" ];    let n = arr.length;    sortArr(arr, n);     </script>
pqrst xyz lmno aeiou
 
Time Complexity: O(N*log N) 
ankthon
offbeat
divyesh072019
suresh07
vowel-consonant
School Programming
Sorting
Strings
Strings
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Constructors in Java
Exceptions in Java
Python Exception Handling
Python Try Except
Ternary Operator in Python
Merge Sort
Bubble Sort Algorithm
QuickSort
Insertion Sort
Selection Sort Algorithm