Skip to content

Commit 0414cce

Browse files
author
Nicholas C. Zakas
committed
Updated bubble sort implementations
1 parent bf55a5c commit 0414cce

File tree

2 files changed

+50
-5
lines changed

2 files changed

+50
-5
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/*
2+
* Bubble sort implementation in JavaScript
3+
* Copyright (c) 2009 Nicholas C. Zakas
4+
* MIT Licensed - see LICENSE for details on license.
5+
*/
6+
7+
8+
/**
9+
* Swaps two values in an array.
10+
* @param {Array} items The array containing the items.
11+
* @param {int} firstIndex Index of first item to swap.
12+
* @param {int} secondIndex Index of second item to swap.
13+
* @return {void}
14+
*/
15+
function swap(items, firstIndex, secondIndex){
16+
var temp = items[firstIndex];
17+
items[firstIndex] = items[secondIndex];
18+
items[secondIndex] = temp;
19+
}
20+
21+
/**
22+
* A bubble sort implementation in JavaScript. The array
23+
* is sorted in-place. This uses two reversed loops that
24+
* count down instead of counting up.
25+
* @param {Array} items An array of items to sort.
26+
* @return {Array} The sorted array.
27+
*/
28+
function bubbleSort(items){
29+
var len = items.length,
30+
i, j;
31+
32+
for (i=len-1; i >= 0; i--){
33+
for (j=len-i; j >= 0; j--){
34+
if (items[j] < items[j-1]){
35+
swap(items, j, j-1);
36+
}
37+
}
38+
}
39+
40+
return items;
41+
}

algorithms/sorting/bubble-sort/bubble-sort.js

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,13 +25,17 @@ function swap(items, firstIndex, secondIndex){
2525
* @return {Array} The sorted array.
2626
*/
2727
function bubbleSort(items){
28-
for (var i=items.length-1; i >= 0; i--){
29-
for (var j=i; j >= 0; j--){
30-
if (items[j] < items[j-1]){
31-
swap(items, j, j-1);
28+
29+
var len = items.length,
30+
i, j, stop;
31+
32+
for (i=0; i < len; i++){
33+
for (j=0, stop=len-i; j < stop; j++){
34+
if (items[j] > items[j+1]){
35+
swap(items, j, j+1);
3236
}
3337
}
3438
}
3539

3640
return items;
37-
}
41+
}

0 commit comments

Comments
 (0)