Blog for web developers

Bubble sort array JavaScript

Bubble sort is one of the design pattern in JavaScript to sort any array with best possible and efficient way for browser to execute to sort any given array. There are other high end function like “.sort()“ which can do the same but we will follow the design pattern technique in order to achieve this.

Let’s us suppose we have an array filled with some random number.

var x = [1,2,3,13,14,15,4,9,10,11,5,6,7,8,12,16,17,18,19,20];
var app = {
	bubbleSort: function(arr){
		var n = arr.length;
		for(let i=0; i<n-1; i++) {
			var minValue = arr[i];
			for(let j=i+1; j<n; j++) {
				if(arr[j] < minValue) {
					minValue = arr[j];
					let temp = arr[i];
					arr[i] = arr[j];
					arr[j] = temp;
				}
			}
		} 
		return arr;
	}
}
console.log(app.bubbleSort(x));
//output: (20) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
Bubble sort array JavaScript

In the above code I have used object oriented method to write function. You can see in the first loop I have start iterating from index 0 to less than array length and again subtracting it by 1. Which means I am not going to iterate over the last index.

Why ?

I am using the swapping variable pattern to sort the array. It will iterate each item in the array. If the current iterating value is less than all the item in the array the current value is swapped with that value so that the small value comes to the first.

In the second loop you can see how I am iterating each value starting from 1 step ahead from current value to compare rest of the array items. If the iterating value is less than current value it will swap the array items and start upper loop. The swapping take place until it finds the smallest of all items in an array.

It can be done with normal function also. But I did it show you how a small change in coding method allow you to write better code. Writing your code in object oriented method will always makes your code looks clean and maintain large files. Bubble sort array javascript, i hope it helps.

I hope my explanation is clear. Thank you for reading.

Please drop your comment and share what do you think of this method. Good luck!!

Santosh Shah

I am a JavaScript developer having enthusiasm on most frontend skills like JavaScript, HTML, CSS, SASS, node, gulp, angular etc. I love exploring new techniques and like to learn new technologies to keep my self up to date.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.