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 the solution that I was looking for:
var a = [34, 203, 3, 746, 200, 984, 198, 764, 9, 1, 32423, 3455, 23, 4234,23];
function bubbleSort(a)
{
var swapped;
var n = a.length-1;
var j = 0;
do {
swapped = false;
for (var i=0; i < n; i++) {
if (a[i] < a[i+1]) {
var temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
swapped = true;
}
}
n--;
} while (swapped);
}
bubbleSort(a);
alert(a);
Thanks all responses.