Search code examples
javaarrayssortingbubble-sort

Java - Bubble Sort Acting Strange


I have been trying to sort an array of integers using bubble sort. I have an ArrayList of chars that also corresponds with the array of integers (eg: integerArray[0] and charArray[0] go together), so when I apply the bubble sort to the array of integers, I want the same changes in ordering also be made to the char array. I am trying to do that with the code below. The problem is clearer if you look at the input and output. I would really appreciate your help, thanks.

Bubble Sort:

    public static void BubbleSort() {
    int temp;
    char temp2;
    for (int x = 0; x < numberOfOccurences.length - 1; x ++) {
    for (int i = 0; i < numberOfOccurences.length - 1; i++) {
        if (numberOfOccurences[i] < numberOfOccurences[i + 1]) {
            temp = numberOfOccurences[i];
            temp2 = characters.get(i);
            numberOfOccurences[i] = numberOfOccurences[i + 1];
            characters.set(i, characters.get(i+1));
            numberOfOccurences[i + 1] = temp;
            characters.set(i + 1, characters.get(i));

        }
    }

    }
}

Corrosponding array values as intended:

3 : S
22 : i
14 : d
28 : h
30 : a
20 : r
34 : t
60 :  
11 : w
43 : e
14 : n
16 : o
2 : K
12 : m
16 : s
7 : c
9 : ,
7 : u
4 : v
7 : l
2 : b
2 : p
2 : f
3 : .
8 : y
6 : g
1 : P

After bubble sorted:

60 :  
43 : e
34 : e
30 : e
28 : e
22 : e
20 : e
16 : o
16 : s
14 : s
14 : s
12 : s
11 : s
9 : ,
8 : y
7 : y
7 : y
7 : y
6 : g
4 : g
3 : g
3 : g
2 : g
2 : g
2 : g
2 : g
1 : P

Solution

  • The last line of the if statement has a typo. It should be

    characters.set(i + 1, temp2);
    

    instead of

    characters.set(i + 1, characters.get(i));