javascript - Sort numbers using special function in Javascript
问题描述
I have this way of sorting the array:
const arr = [0,6,8,7,1,2,3];
const sortBubble = () => {
for (let index = 0; index < arr.length; index++) {
for (let j = 0; j < arr.length; j++) {
if(arr[j] > arr[j+1]) {
const temp = arr[j];
arr[j] = arr[j + 1]
arr[j + 1] = temp;
}
}
}
return arr;
}
console.log(sortBubble())
Also this function:
const arr = [0,6,8,7,1,2,3];
const sortBubble = () => {
for (let index = 0; index < arr.length; index++) {
for (let j = 0; j < arr.length; j++) {
if(arr[j] > arr[j+1]) {
arr[j] = arr[j + 1]
arr[j + 1] = arr[j];
}
}
}
return arr;
}
console.log(sortBubble())
I can't understand, why in the last function i get a different result than in the first function. How you can see in the last function i didn't use: temp
variable, but anyway in my vision temp
and arr[j]
should be equal and i expect in both function the result as in first function, but last one has a different result.
Why the last function acts different if i don't use temp
variable?
解决方案
如果您仔细查看第二个代码,您正在执行以下操作:
if(arr[j] > arr[j+1]) {
arr[j] = arr[j + 1]
arr[j + 1] = arr[j];
}
所以你设置arr[j]
equal to arr[j+1]
,第二行不会改变数组,因为你已经覆盖了arr[j]
的值
推荐阅读
- php - 如何在 Visual Studio Code 中运行与 PHP 集成的 HTML 代码
- r - 检查 R 中两个单独数据帧的日期和时间是否重叠
- python - 如何在我的 python 脚本中存储密码,但在部署到 Github 时是否会被任何用户隐藏?
- java - 第二个活动无法从意图中读取 getExtras
- c - recv 在套接字编程中是如何工作的?
- firebase - 未来的 for 循环在 Flutter 中不起作用并打印错误
- python - $ pytest 和 $ python -m pytest 测试之间的区别
- c# - ACTION_BOOT_COMPLETED 接收器不工作
- ios - Swift 重置约束崩溃
- reactjs - ts:“道具”可以用与另一种类型无关的任意类型实例化