Search code examples
javaarraysbubble-sort

How solve: Array type expected, found int? in bubble sort using array not the list


I have a task where I need to do a Bubble Sort program. I have to use array, not the list. I receive couple of errors, where it says that

"Array type expected, found int"

public class BubbleSort {

    public static void main(String[] args) {
        int array[] = {9, 7, 5, 8, 1, -5};
        System.out.println(Arrays.toString(sort(array)));
    }

    public static int[] sort(int[] array) {
        int n = array.length;
        for (int i = 0; i < n - 1; i++)
            for (int j = 0; j < n - i - 1; j++)
                if (array[j] > array[j + 1]) {

                }
        return swapElementsInArray(array);
    }

    private static void swapElementsInArray(int[] array, int indexOfFirstElement, int indexOfSecondElement) {
        if (array[indexOfSecondElement] > array[indexOfSecondElement + 1]) {
            array [] = indexOfFirstElement[indexOfSecondElement];
            indexOfFirstElement[indexOfSecondElement] = indexOfFirstElement[indexOfSecondElement + 1];
            indexOfFirstElement[indexOfSecondElement + 1] = array;
        }
    }
}

I need to keep this structure, it's my tutor requirement to use these long names. And I cannot modify methods.


Solution

  • so the method was wrong about what to swap and the error was wrong attribution - int into array.

    Here is your example working:

    public static void main(String[] args) {
        int[] array = {9, 7, 5, 8, 1, -5};
        System.out.println(Arrays.toString(sort(array)));
    }
    
    public static int[] sort(int[] array) {
        int n = array.length;
        for (int i = 0; i < n - 1; i++) {
            for (int j = i+1; j < n; j++) {
                if (array[i] > array[j]) {
                    swapElementsInArray(array, i, j);
                }
            }
        }
        return array;
    }
    
    private static void swapElementsInArray(int[] array, int indexOfFirstElement, int indexOfSecondElement) {
        if (array[indexOfFirstElement] > array[indexOfSecondElement]) {
            int oldVal = array[indexOfFirstElement];
            array[indexOfFirstElement] = array[indexOfSecondElement];
            array[indexOfSecondElement] = oldVal;
        }
    }
    

    This prints:

    [-5, 1, 5, 7, 8, 9]