[英]Why does this bubble sort leave 2 elements in the wrong order?
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.我从冒泡排序算法的伪代码示例中翻译了这段代码,但是当我实现它时,它在错误的地方返回了 2 个值。
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.所以
10
和1
在错误的地方。
Does anyone know why?有谁知道为什么?
You need to change i < numbers.length - 2
to i < numbers.length - 1
in your for-loop.您需要在 for 循环中将
i < numbers.length - 2
更改为i < numbers.length - 1
。
With i < numbers.length - 2
your loop will quit before evaluating the last element.使用
i < numbers.length - 2
您的循环将在评估最后一个元素之前退出。
You should iterate until the index is equal to numbers.length - 1
.您应该迭代直到索引等于
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
.目前,您没有将索引
numbers.length - 2
处的倒数第二个元素与最后一个元素进行比较,因为您在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();
the code lacks one more iteration due to i < numbers.length -2
由于
i < numbers.length -2
,代码缺少一次迭代
try changing that to i < numbers.length - 1
to fix it.尝试将其更改为
i < numbers.length - 1
以修复它。
i < numbers.length - 1
will go from the first index (0) upto the second to the last index to account for the i+1
i < numbers.length - 1
将 go 从第一个索引 (0) 到倒数第二个索引占i+1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.