👋
Welcome to my blog!

Bubble Sort

Simplify data sorting with the fundamental principles of bubble sort, detailed in our easy-to-follow guide.

Bubble Sort
Sorting
easy

Published At

6/4/2021

Reading Time

~ 2 min read

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

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

Sample Output

js
[2, 3, 5, 5, 6, 8, 9]
js
[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

Solution-1
js
// O(n^2) time complexity
function bubbleSort(array) {
  let isSorted = false;
	let counter = 1
	while (!isSorted) {
		isSorted = true;
		for (let i = 0; i < array.length - counter; i++) {
			if (array[i] > array[i+1]) {
				isSorted = false;
				[array[i], array[i+1]] = [array[i+1], array[i]];
			}
		}
		counter++;
	}
	return array
}
Solution-1
js
// O(n^2) time complexity
function bubbleSort(array) {
  let isSorted = false;
	let counter = 1
	while (!isSorted) {
		isSorted = true;
		for (let i = 0; i < array.length - counter; i++) {
			if (array[i] > array[i+1]) {
				isSorted = false;
				[array[i], array[i+1]] = [array[i+1], array[i]];
			}
		}
		counter++;
	}
	return array
}

🐿

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 🙏

Join My Exclusive Newsletter Community

Step into a world where creativity intersects with technology. By subscribing, you'll get a front-row seat to my latest musings, full-stack development resources, and exclusive previews of future posts. Each email is a crafted experience that includes:

  • In-depth looks at my covert projects and musings to ignite your imagination.
  • Handpicked frontend development resources and current explorations, aimed at expanding your developer toolkit.
  • A monthly infusion of inspiration with my personal selection of quotes, books, and music.

Embrace the confluence of words and wonder, curated thoughtfully and sent straight to your inbox.

No fluff. Just the highest caliber of ideas.