Skip to content

Commit 4e820cc

Browse files
committed
Adds comparator for bubble sort
1 parent 50f812f commit 4e820cc

2 files changed

Lines changed: 34 additions & 15 deletions

File tree

‎src/sorting/bubblesort/bubblesort.js‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,22 @@
11
(function (exports) {
2+
3+
function comparator(a, b) {
4+
return a - b;
5+
}
6+
27
/**
38
* The bubblesort algorithm. Complexity O(n^2).
49
*
510
* @public
611
* @param {array} array Input array
712
* @returns {array} array Sorted array
813
*/
9-
function bubbleSort(array) {
14+
function bubbleSort(array, cmp) {
15+
cmp = cmp || comparator;
1016
var temp;
1117
for (var i = 0; i < array.length; i += 1) {
1218
for (var j = i; j > 0; j -= 1) {
13-
if (array[j] < array[j - 1]) {
19+
if (cmp(array[j], array[j - 1]) < 0) {
1420
temp = array[j];
1521
array[j] = array[j - 1];
1622
array[j - 1] = temp;

‎test/bubblesort.spec.js‎

Lines changed: 26 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,19 @@ var bubbleSort = require('../src/sorting/bubblesort/bubblesort.js')
22

33
describe('Bubble sort', function () {
44

5+
function createRandomArray(options) {
6+
options = options || {};
7+
var size = options.size || 100,
8+
precision = options.precision || 2,
9+
multiplier = options.multiplier || 100;
10+
11+
var result = [];
12+
for (var i = size; i > 0; i -= 1) {
13+
result.push(parseFloat((Math.random() * multiplier).toFixed(precision)));
14+
}
15+
return result;
16+
}
17+
518
it('should work with empty array', function () {
619
expect(bubbleSort([])).toEqual([]);
720
});
@@ -12,19 +25,6 @@ describe('Bubble sort', function () {
1225

1326
it('should work with random non-sorted arrays', function () {
1427

15-
function createRandomArray(options) {
16-
options = options || {};
17-
var size = options.size || 100,
18-
precision = options.precision || 2,
19-
multiplier = options.multiplier || 100;
20-
21-
var result = [];
22-
for (var i = size; i > 0; i -= 1) {
23-
result.push(parseFloat((Math.random() * multiplier).toFixed(precision)));
24-
}
25-
return result;
26-
}
27-
2828
var array = createRandomArray();
2929
bubbleSort(array);
3030

@@ -33,4 +33,17 @@ describe('Bubble sort', function () {
3333
}
3434
});
3535

36+
it('should sort the numbers in descending order when such comparator is provided', function () {
37+
function comparator(a, b) {
38+
return b - a;
39+
}
40+
41+
var array = createRandomArray();
42+
bubbleSort(array, comparator);
43+
44+
for (var i = 0; i < array.length - 1; i += 1) {
45+
expect(array[i] >= array[i + 1]).toBeTruthy();
46+
}
47+
});
48+
3649
});

0 commit comments

Comments
 (0)