Reputation:
I translated this code from a pseudo code example of the bubble sort algorithm, but when I implement it, it returns 2 values in the wrong place.
Here's the code:
var numbers = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
var swapMade;
var temp;
function setup() {
swapMade = true;
while (swapMade == true) {
swapMade = false;
for (var i = 0; i < numbers.length - 2 ; i++) {
if (numbers[i] > numbers[i+1]) {
temp = numbers[i];
numbers[i] = numbers[i+1];
numbers[i+1] = temp;
swapMade = true;
}
}
}
console.log(JSON.stringify(numbers));
}
setup();
This returns:
[2, 3, 4, 5, 6, 7, 8, 9, 10, 1]
So 10
and 1
are in the wrong place.
Does anyone know why?
Upvotes: 0
Views: 105
Reputation: 186
the code lacks one more iteration due to i < numbers.length -2
try changing that to i < numbers.length - 1
to fix it.
i < numbers.length - 1
will go from the first index (0) upto the second to the last index to account for the i+1
Upvotes: 0
Reputation: 89364
You should iterate until the index is equal to numbers.length - 1
. Currently, you are not comparing the second last element at index numbers.length - 2
with the last element since you stop right before numbers.length - 2
.
var numbers = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
var swapMade;
var temp;
function setup() {
swapMade = true;
while (swapMade) {
swapMade = false;
for (var i = 0; i < numbers.length - 1 ; i++) {
if (numbers[i] > numbers[i+1]) {
temp = numbers[i];
numbers[i] = numbers[i+1];
numbers[i+1] = temp;
swapMade = true;
}
}
}
console.log(JSON.stringify(numbers));
}
setup();
Upvotes: 1
Reputation: 1140
You need to change i < numbers.length - 2
to i < numbers.length - 1
in your for-loop.
With i < numbers.length - 2
your loop will quit before evaluating the last element.
Upvotes: 1