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?
arr[j] = arr[j + 1]overwritesarr[j].arr[j + 1] = arr[j];in the next line is equivalent toarr[j + 1] = arr[j + 1];