This page looks best with JavaScript enabled

Use Bubble Sort to Manually Sort an Array

 ·   ·  ☕ 2 min read

How can we use our beloved bubble sort in Javascript?

We have seen examples of how to sort an array and sorting with multiple attributes.

The easiest way is to sort an array is to just use Array.sort(). But that alone will not show you the complexity that you want to show in your program (for e.g. for your next college thesis work that requires you to write minimum 100 pages of code).

Ergo, the need for a bubble sort algorithm.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
function bubbleSort(arr, desc = false) {
  let sortArr = arr;

  for (let i = 0; i < sortArr.length; i++) {
    for (let j = 1; j < sortArr.length; j++) {
      if (sortArr[j - 1] > sortArr[j])
        [sortArr[j - 1], sortArr[j]] = [sortArr[j], sortArr[j - 1]];
    }
  }

  return sortArr;
}

console.log(bubbleSort([5, 1, 4, 2, 7, 3]));
// [ 1, 2, 3, 4, 5, 7 ]

console.log(bubbleSort(["a", "abc", "ABC", "x", "z"]));
// [ 1, 2, 3, 4, 5, 7 ]

The code is quite simple -

  • We take a given array and iterate through the array in two loops
  • We just use a modern Javascript notation to replace elements in j and j-1 positions whenever element at j < element at j-1
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things