0

I have a code for bubble sort:

      var ani = []
export const Bubblesort =(arr) =>{
    for(var i = 0; i < arr.length; i++){
     
        // Last i elements are already in place  
        for(var j = 0; j < ( arr.length - i -1 ); j++){
            
          // Checking if the item at present iteration 
          // is greater than the next iteration
          if(arr[j] > arr[j+1]){
            // If the condition is true then swap them
            var temp = arr[j]
            arr[j] = arr[j + 1]
            arr[j+1] = temp
          }
          console.log (arr)

        }
      }
      // Print the sorted array
      return arr
}

enter image description here

Here I want to get all the position of the elements in array when I print the array, it shows me multiple array in my console. Like it should, but when I make it group of arrays, all the group array are having same number.

Replacing this

console.log (arr)

to this

 ani.push(arr)
 console.log(arr)

enter image description here

this gives me wrong output. Please help.....

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • try `console.log(arr.slice())` - see, the console sometimes lies - not really, it shows the current state of things like Objects/Arrays, not the state they were in at the moment they are logged – Jaromanda X Jun 29 '21 at 16:23
  • The content of `arr` is a reference to an array. `.push(arr)` puts a copy of that reference into `ani`. You want an actual copy of the array referenced by `arr`, hence this should be a dupe of [Copy array by value](https://stackoverflow.com/questions/7486085/copy-array-by-value) – Andreas Jun 29 '21 at 16:24
  • i tried creating copy of array using: "let unsortedarray = arr.slice() " and then printed unsortedarray ,but no changes – Haseef Azhaan Jun 29 '21 at 16:34
  • i even tried console.log(unsortedarray.slice()) but not changes to the bug – Haseef Azhaan Jun 29 '21 at 16:36
  • Please add a [mcve] and not just parts of the actual script and some images – Andreas Jun 29 '21 at 18:42
  • Hey guys I have solved my problem . I actually did arr.splice() instead of are.slice() to print my array state . So because of my carelessness it created a problem . Sorry for the trouble guys. And thank you – Haseef Azhaan Jul 01 '21 at 18:57

0 Answers0