I have this code which sort a numeric array using bubble sort algorithm.
var a = [34, 203, 3, 746, 200, 984, 198, 764, 9];
function bubbleSort(a)
{
var swapped;
do {
swapped = false;
for (var i=0; i < a.length-1; i++) {
if (a[i] < a[i+1]) {
var temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
swapped = true;
}
}
} while (swapped);
}
bubbleSort(a);
alert(a);
You can see it here: http://jsfiddle.net/x7VpJ/
Well, it works perfect as you can check, but I wondered if there is another way to optimize this to do fewer loops using the actual method. I mean, using swapped variable. Maybe omiting the sorted items... some idea?
Thanks in advance.
Here is a list of different sorting algorithms in JS. I made a page that compares sorting times and from what I noticed "Quick" seems the best option.
Bubble Sort:
Insertion:
Shell:
Quick:
Merge:
Built in JS Sort:
Of course I would suggest using your arrays outside of the function so you can continue using it after the data is sorted.
Here is the solution that I was looking for:
http://jsfiddle.net/x7VpJ/1/
Thanks all responses.
If I stick with the original question (and I will not suggest completely different algorithms...).
Yes, there is another improvement - bi-direction bubble sort, called shaker sort. It eliminates problem of turtles and rabbits. In one-directional bubble sort light bubbles are moving fastly towards the end of the array (rabbits), while the heavy bubbles are moving towards the start very slowly. But if you sort in bi-directional manner, both types of bubbles are sorted pretty fast (still in O(n^2), but usually faster than with the conventional bubble sort).