DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 36

The task is to implement a bubble sort which sorts an integer array in ascending order, modifying it in place.

The boilerplate code:

function bubbleSort(arr) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

The BubbleSort is a sorting algorithm that sorts an array by comparing adjacent elements in an array, and swaps them if they are in the wrong order.

The outer loop ensures we go through the loop multiple times

for(let i = 0; i < arr.length - 1; i++) {
}
Enter fullscreen mode Exit fullscreen mode

The inner loop compares adjacent elements

for(let j = 0; j < arr.length-1; j++) {
}
Enter fullscreen mode Exit fullscreen mode

If the current element is larger than the next element, we swap them using a temporary variable

if (arr[j] > arr[j + 1]) {
  const temp = arr[j];
  arr[j] = arr[j + 1];
  arr[j + 1] = temp;
}
Enter fullscreen mode Exit fullscreen mode

After every inner loop, one large element towards the end. The sorting is completed when the array loops one time less than the length of the array.

The final code:

function bubbleSort(arr) {
  // your code here
  for(let i = 0; i < arr.length - 1; i++) {
    for(let j = 0; j < arr.length - 1; j++) {
      if(arr[j] > arr[j + 1]) {
        const temp = arr[j];
        arr[j] = arr[j + 1];
        arr[j + 1] = temp
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)