BrianRT
BrianRT

Reputation: 1962

Why is my swap method not working?

I have successfully written a Bubblesort class. Now I am trying to break the functions apart to make the code cleaner. Here is the working code:

public class BubbleSortTest {

    public static void main(String[] args) {
        int[] array = {93, 60, 65, 45, 50};
        bubbleSort(array);
        printArray(array);
    }

    public static int[] bubbleSort(int[] array) {
        for(int i = 0; i < array.length - 1; i++) {
            for(int j = 0; j < array.length - 1 - i; j++) {
                if(array[j] < array[j + 1]) {
                    int temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                 }
             }
         }
         return array;
    }

    public static void printArray(int[] array) {
        for(int i = 0; i < array.length; i++) {
            System.out.print(array[i] + " ");
        }
    }
}

For this example, I want to take the functionality of the if statement in the bubbleSort function and make it into its own swap function. So the code I want would look like:

public class BubbleSortTest {

    public static void main(String[] args) {
        int[] array = {93, 60, 65, 45, 50};
        bubbleSort(array);
        printArray(array);
    }

    public static int[] bubbleSort(int[] array) {
        for(int i = 0; i < array.length - 1; i++) {
            for(int j = 0; j < array.length - 1 - i; j++) {
                if(array[j + 1] > array[j]) {
                    swap(array[j + 1], array[j]);
                }
             }
         }
         return array;
    }

    public static void swap(int largerElement, int smallerElement) {
        int temp = largerElement;
        largerElement = smallerElement;
        smallerElement = temp;
    }

    public static void printArray(int[] array) {
        for(int i = 0; i < array.length; i++) {
            System.out.print(array[i] + " ");
        }
    }
}

When I run the latter code, swap is essentially doing nothing. I thought a fix to this was to create a non-void function to return the values, but I can't return both values without encapsulating them in an object (correct me if I'm wrong). There must be something wrong with the swap function. I'm probably missing something fundamental. What's wrong with the latter code?

Upvotes: 1

Views: 651

Answers (1)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

Java is Pass By Value. Your swap method must receive the array and the indexes to swap rather than the int variables:

public static void swap(int[] array, int index1, int index2) {
    int temp = array[index1];
    array[index1] = array[index2];
    array[index2] = temp;
}

Upvotes: 3

Related Questions