首页 > 解决方案 > 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?

标签: javascript

解决方案


如果您仔细查看第二个代码,您正在执行以下操作:

      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]的值


推荐阅读