Markopolo
Markopolo

Reputation: 1

bubbleSort and swap method not working [Java]

In the main, whenever I call this method to sort the array, it stops as if it's waiting for a response. Any idea why it's not working?

public void bubbleSort(){
    boolean finished = false;
    boolean swapOccurred = false;
    int i = 0;
    int next = i + 1;

    while (finished == false)
    {

        for (; i < theArray.length - 1; i++)
        {
            if (theArray[i] > theArray[next])
            {
                swapValues(theArray[i], theArray[next]);
                swapOccurred = true;
            }
        }
        if (swapOccurred == false)
        {
            finished = true;
        }
    }
}

private void swapValues(int i, int next) {

    int temp;

    temp = i;
    i = next;
    next = temp;

}

Upvotes: 0

Views: 357

Answers (2)

Zielu
Zielu

Reputation: 8552

If it is java, then

  1. The next index is never updated so it stays 1 all the time.
  2. The swap method has no side effect, you want to swap the elements in theArray, but in java methods arguments are passed as values so the next and i variables change the value only inside the swap method, they have nothing to do with the cells of theArray array.

Upvotes: 2

Dov Rosenberg
Dov Rosenberg

Reputation: 805

The problem is with your swap.

In C, arguments are passed by value, so when you do the swap, the values being passed in aren't affected, so nothing is happening. You need to pass in pointers to the numbers instead (and then dereference them inside):

private void swapValues(int *i, int *next) {
    int temp;

    temp = *i;
    *i = *next;
    *next = temp;
}

And then call it with the address of the variables to swap:

swapValues(&theArray[i], &theArray[next]);

Edit: Ha - @Zielu saw Java, I saw C. Same problem in both cases, and as @Zielu points out, you also need to increment next. I believe you actually just want to use [i+1] as your index in place of next.

Upvotes: 1

Related Questions