Skip to content

Commit

Permalink
Add insertion-sort and associated test
Browse files Browse the repository at this point in the history
  • Loading branch information
dennis-johnson-dev committed Dec 28, 2013
1 parent 4045044 commit 2775410
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
44 changes: 44 additions & 0 deletions solutions/javascript/insertion-sort.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// insertion-sort
'use strict';

module.exports = function (array, compare) {
// Not an array, empty or array of 1 is already sorted
if (!Array.isArray(array) || array.length < 2) {
return array;
}

// Swap elements of the array
var swap = function (array, first, second) {
var temp = array[first];
array[first] = array[second];
array[second] = temp;
return array;
};

// Create a compare function if one is not passed in
if (typeof compare !== 'function') {
compare = function (a, b) {
return a > b ? 1 : -1;
};
}

var i, j;

/*
* Assume first element is sorted
* Add first unsorted element to sorted array
* Compare new element in sorted array with previous elements
* to determine correct destination index in sorted array
*/

for (i = 1; i < array.length; i++) {
j = i;
// Make sure we don't walk off the array and compare until sorted
while ((j - 1) >= 0 && compare(array[j], array[j - 1]) < 0) {
swap(array, j, j-1);
j--;
}
}

return array;
};
13 changes: 13 additions & 0 deletions tests/javascript/insertion-sort.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
var assert = require('assert');
var insertion = require('../../solutions/javascript/insertion-sort');

describe('sort functions ->', function(){
var sorted = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var array = [9, 8, 7, 6, 5, 4, 3, 2, 1];

it("sort array: " + sorted, function(){
array = insertion(array);
assert.deepEqual(array, sorted);
})
})

0 comments on commit 2775410

Please sign in to comment.