Skip to content
Advertisement

Trying to sort by the number of vowels, the program does not sort at all

My intention was to count he number of vowels in each string in each index, add that number to an array, and then sort both the arrays using bubble sort. (this is for a class, and we are not allowed to use arrays.sort or any of the arrays.methods.) It is not sorting whatsoever and I’m unsure as to why.

public static String[] sortByVowels(String[] a) {
    String[] copy = a.clone();

    int[] numVowels = new int[copy.length];

    for(int i = 0; i < copy.length; i++) {
        for(int j = 0; j < copy[i].length(); j++) {
            int count = 0;
            char ch = copy[i].charAt(j);
            if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
            count++;
            }
            numVowels[i] = count;
        }
    }
    for (int c = 0; c < copy.length - 1; c++) {
        for(int d = 0; d < copy.length - c - 1; d++) {
            if (numVowels[d] > numVowels[d+1]) {
                int swapInt = numVowels[d];
                numVowels[d] = numVowels[d+1];
                numVowels[d+1] = swapInt;
                
                String swapString = copy[d];
                copy[d] = copy[d+1];
                copy[d+1] = swapString;
            }
        }
    }
    return copy;
}

Advertisement

Answer

Akarnokd in the comments solved it. My counter int count = 0; was inside the inner char loop when it should’ve been outside in the first for loop. Thank you!

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement