Bubble Sort

A corgi smiling happily

Write a function that takes in an array of integers and returns a sorted version of that array. Use the Bubble Sort algorithm to sort the array.

If you’re unfamiliar with Bubble Sort, we recommend watching the Conceptual Overview section of this question’s video explanation before starting to code.

Sample Input

1array = [8, 5, 2, 9, 5, 6, 3]

Sample Output

1[2, 3, 5, 5, 6, 8, 9]

Hints

Hint 1

Traverse the input array, swapping any two numbers that are out of order and keeping track of any swaps that you make. Once you arrive at the end of the array, check if you have made any swaps; if not, the array is sorted and you are done; otherwise, repeat the steps laid out in this hint until the array is sorted.

Optimal Space & Time Complexity

Best: O(n) time | O(1) space - where n is the length of the input array Average: O(n^2) time | O(1) space - where n is the length of the input array Worst: O(n^2) time | O(1) space - where n is the length of the input array

1// O(n^2) time complexity
2function bubbleSort(array) {
3 let isSorted = false;
4 let counter = 1
5 while (!isSorted) {
6 isSorted = true;
7 for (let i = 0; i < array.length - counter; i++) {
8 if (array[i] > array[i+1]) {
9 isSorted = false;
10 [array[i], array[i+1]] = [array[i+1], array[i]];
11 }
12 }
13 counter++;
14 }
15 return array
16}

🐿

Do you have any questions, or simply wish to contact me privately? Don’t hesitate to shoot me a DM on Twitter.

Have a wonderful day.
Abhishek 🙏

Subscribe to my newsletter

Get email from me about my ideas, full-stack development resources, tricks and tips as well as exclusive previews of upcoming articles.

No spam. Just the highest quality ideas you’ll find on the web.