Search code examples
javascriptarraysprintingiterationbubble-sort

How to get the array after nth iteration in bubble sort?


Here is the bubble sort algorithm in javascript(removed swap function for brevity)

const bubbleSort = (arr, iter) => {
  for (let i = 0; i < arr.length - 1; i++) {
    for (let j = 0; j < arr.length - i - 1; j++) {
      if (arr[j] > arr[j + 1]) {
        swap(arr, j, j + 1);
      }
    }
  }
  return arr;
};

The second argument iter represents iteration. I want this method to return the array after iter number of iterations. For example, consider this array

array = [3, 5, 8, 4, 1, 9, -2]

After iteration 1: array = [3, 5, 4, 1, 8, -2, 9]  
After iteration 2: array = [3, 4, 1, 5, -2, 8, 9]  
.  
.  
After iteration 5: array = [1, -2, 3, 4, 5, 8, 9]  
After iteration 6: array = [-2, 1, 3, 4, 5, 8, 9]

So essentially if I call bubblesort(array, 5), it should return [1, -2, 3, 4, 5, 8, 9]


Solution

  • You could use for loop and forEach loop inside to swap elements.

    let array = [3, 5, 8, 4, 1, 9, -2]
    
    function bubblesort(arr, n) {
      for (let x = 0; x < n; x++) {
        arr.forEach((e, i) => {
          if (arr[i + 1] < e) {
            arr[i] = arr[i + 1]
            arr[i + 1] = e
          }
        })
      }
      return arr
    }
    
    console.log(bubblesort(array, 5))