Reputation: 1
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
Reputation: 8552
If it is java, then
i
variables change the value only inside the swap method, they have nothing to do with the cells of theArray array. Upvotes: 2
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