forked from blakeembrey/code-problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add insertion-sort and associated test
- Loading branch information
1 parent
4045044
commit 2775410
Showing
2 changed files
with
57 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
}) | ||
}) | ||
|