Bubble Sort can be optimized by observing that the n-th pass finds the n-th largest element and puts it into its final place. So the inner loop can avoid looking at the last n-1 items when running for the n-th time.
function bubbleSort(items) {
n = count(items);
swapped = false;
while(!swapped) {
swapped = false;
for(i = 1; i < n; i++) {
if(items[i-1] > items[i]) {
tmp = items[i-1];
items[i-1] = items[i];
items[i] = tmp;
swapped = true;
}
}
n = n-1;
}
}
function bubbleSort(items) {
swapped = false;
while(!swapped) {
swapped = false;
for(i = 1; i < count(items); i++) {
if(items[i-1] > items[i]) {
tmp = items[i-1];
items[i-1] = items[i];
items[i] = tmp;
swapped = true;
}
}
}
}
Wikipedia Article: [http://en.wikipedia.org/wiki/Bubble_sort]