Skip to content

Commit 3b5229f

Browse files
author
Nicholas C. Zakas
committed
Updated bubble sort to more traditional style (using swap method)
1 parent 67269fd commit 3b5229f

File tree

1 file changed

+16
-5
lines changed

1 file changed

+16
-5
lines changed

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

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,16 +8,27 @@
88
* A bubble sort implementation in JavaScript. The array
99
* is sorted in-place.
1010
* @param {Array} items An array of items to sort.
11+
* @return {void}
1112
*/
12-
13-
function sort(items){
13+
function bubbleSort(items){
1414
for (var i=items.length-1; i >= 0; i--){
1515
for (var j=i; j >= 0; j--){
1616
if (items[j] < items[j-1]){
17-
var temp = items[j];
18-
items[j] = items[j-1];
19-
items[j-1] = temp;
17+
swap(items, j, j-1);
2018
}
2119
}
2220
}
21+
}
22+
23+
/**
24+
* Swaps two values in an array.
25+
* @param {Array} items The array containing the items.
26+
* @param {int} firstIndex Index of first item to swap.
27+
* @param {int} secondIndex Index of second item to swap.
28+
* @return {void}
29+
*/
30+
function swap(items, firstIndex, secondIndex){
31+
var temp = items[firstIndex];
32+
items[firstIndex] = items[secondIndex];
33+
items[secondIndex] = temp;
2334
}

0 commit comments

Comments
 (0)