Skip to content

Commit

Permalink
bubble sort algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
vrgamespace committed May 18, 2017
1 parent 228818f commit 1e0dea3
Show file tree
Hide file tree
Showing 2 changed files with 104 additions and 5 deletions.
37 changes: 34 additions & 3 deletions src/sort/bubble.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,34 @@
module.exports = function (arr, comp) {
console.log('ok')
}
function normalCompare(prev, next) {
if (prev < next) {
return -1;
} else if (prev == next) {
return 0;
} else {
return 1;
}
}
/**
* explaining here: https://visualgo.net/en/sorting?slide=5
*
* @param {Array} src - source data, it should be an Array
* @return {Array}
*/
function sort (src, comp = normalCompare) {
if (! (src instanceof Array)) {
throw new Error('expect param 1 to be an Array')
}
let result = [].concat(src);

for (let i = 0, len = result.length; i < len - 1; i++) {
for (let j = 0; j < len - 1 - i; j++) {
// if prev value greater than next value, just exchange them
if (comp(result[j], result[j + 1]) === 1) {
let temp = result[j];
result[j] = result[j + 1];
result[j + 1] = temp;
}
}
}
return result;
}
module.exports = sort;
72 changes: 70 additions & 2 deletions test/sort/bubble.spec.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,71 @@
describe('> bubble sort', () => {
it('ok', () => {})
const sort = require('../../src/sort/bubble');
const expect = require('chai').expect

describe('> bubble sort algorithm', () => {
describe('> Wrong Usage', () => {
it('wrong parameter', () => {
try {
sort(5)
} catch(e) {
expect(e.message).to.equal('expect param 1 to be an Array');
}
});
});

it('sort number', () => {
let arr = [5, 4, 3, 1, 2];
let result = sort(arr);
expect(result).to.deep.equal(
[1, 2, 3, 4, 5]
);

arr = [-4, -4, -2, -2, 4, 3, 1, 2];
result = sort(arr);
expect(result).to.deep.equal(
[-4, -4, -2, -2, 1, 2, 3, 4]
);
});

it('sort letter', () => {
let arr = ['a', 'c', 'd', 'b', 'e'];
let result = sort(arr);
expect(result).to.deep.equal(
['a', 'b', 'c', 'd', 'e']
);
});

it('custom comparator', () => {
let arr = [
{
value: 6,
},
{
value: 3,
},
{
value: 1,
},
{
value: 4,
}
];
let result = sort(arr, (prev, next) => {
if (prev.value > next.value) return 1;
return -1;
});
expect(result).to.deep.equal([
{
value: 1,
},
{
value: 3,
},
{
value: 4,
},
{
value: 6,
}
]);
});
});

0 comments on commit 1e0dea3

Please sign in to comment.