Bubble Sort Algorithm In Javascript
Bubble Sort is a very simple sorting algorithm. It works by stepping through a list to be sorted repeatedly while comparing each pair of coinsiding items and switching them if they are ordered incorrectly. This is a useful algorithm for doing simple comparisons in lists, but there are much more efficient algorithms for larger lists.
Bubble Sort example in JavaScript:
var numbers = [3,5,2,4,7,9,6,4,5]; var tmp; for (var i = 0; i < numbers.length; i += 1) { for (var j = i; j > 0; j -= 1) { if (numbers[j] < numbers[j - 1]) { tmp = numbers[j]; numbers[j] = numbers[j - 1]; numbers[j - 1] = tmp; } } } console.log(numbers);
For more information on the Bubble Sort check the Wikipedia page here: Bubble Sort - Wikipedia.org.
Written on September 6, 2013