Asking
Asking

Reputation: 4192

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?

Upvotes: 0

Views: 41

Answers (3)

user15388024
user15388024

Reputation:

arr[j] = arr[j + 1] overwrites arr[j]. arr[j + 1] = arr[j]; in the next line is equivalent to arr[j + 1] = arr[j + 1];. You can avoid an explicit temp variable with

if(arr[j] > arr[j+1]) {
  [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
}

but of course internally the temporary value has to be stored.

Example:

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())

Upvotes: 0

Guerric P
Guerric P

Reputation: 31815

If you want to swap items in an array, you have to use a temporary variable as a buffer to store one of the two values you're swapping:

In your second example, let's say you have this array:

const arr = [5, 6];

Now let's say j equals 0: arr[j] = arr[j + 1] will make your array become: [6, 6]

Then you execute arr[j + 1] = arr[j] which gives [6, 6] and you cannot retrieve 5 anymore as there is no more reference on it.

Upvotes: 1

Ant
Ant

Reputation: 1163

If you take a closer look at your second code you are doing the following:

      if(arr[j] > arr[j+1]) {
         arr[j] = arr[j + 1]
         arr[j + 1] = arr[j];
      }

So you set arr[j] equal to arr[j+1], the second line makes no change to the array, as you have over-written arr[j]'s value

Upvotes: 1

Related Questions