Skip to content

Commit da2e2ff

Browse files
committed
Added InsertionSort algorithm implementation and test
1 parent 43b6fb5 commit da2e2ff

File tree

3 files changed

+521
-0
lines changed

3 files changed

+521
-0
lines changed

sorting/insertion-sort.js

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* Implement [Insertion sort]
3+
*
4+
* Copyright (c) 2018, Ionut Alixandroae.
5+
* Licensed under the MIT License.
6+
*/
7+
8+
'use strict';
9+
10+
/**
11+
* Bubble sort algorithm.
12+
* Complexity: O(N^2).
13+
*
14+
* @example
15+
* console.log(insertionSort([54, 26, 93, 17, 77, 31, 44, 55, 20])); // [ 17, 20, 26, 31, 44, 54, 55, 77, 93 ]
16+
*
17+
* @public
18+
* @module sorting/insertionsort
19+
* @param {Array} array Input array.
20+
* @return {Array} Sorted array.
21+
*/
22+
function insertionSort(array) {
23+
for (var i = 0; i < array.length; i++) {
24+
var temp = array[i];
25+
var j = i - 1;
26+
while (j >= 0 && array[j] > temp) {
27+
array[j + 1] = array[j];
28+
j--;
29+
}
30+
array[j + 1] = temp;
31+
}
32+
return array;
33+
}
34+
35+
module.exports = insertionSort;

tests/sorting/insertion-sort.spec.js

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
const chai = require('chai');
2+
const expect = chai.expect;
3+
const sort = require('../../sorting/insertion-sort.js');
4+
5+
describe('Insertion sort', function() {
6+
it('should work with empty arrays', function() {
7+
expect(sort([])).deep.equal([]);
8+
});
9+
10+
it('should work with sorted arrays', function() {
11+
expect(sort([1, 2, 3, 4])).to.have.ordered.members([1, 2, 3, 4]);
12+
});
13+
14+
it('should work with non-sorted arrays', function() {
15+
let array = [2, 5, 1, 0, 4, 3];
16+
array = sort(array);
17+
for (let i = 0; i < array.length - 1; i += 1) {
18+
expect(array[i] <= array[i + 1]).to.be.true;
19+
}
20+
});
21+
});

0 commit comments

Comments
 (0)