Skip to content

Commit

Permalink
Merge 072377e into 9716d2f
Browse files Browse the repository at this point in the history
  • Loading branch information
gyj963 committed Aug 15, 2014
2 parents 9716d2f + 072377e commit 49b2a31
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
29 changes: 29 additions & 0 deletions algorithms/sorting/shell_sort.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
'use strict';
var Comparator = require('../../util/comparator');
/**
* shell sort worst:O(n lg n) best:O(n)
*/
var shellSort = function (array, comparatorFn) {
var comparator = new Comparator(comparatorFn),
begin = 0,
end = array.length - 1,
gap = parseInt((end - begin + 1) / 2),
i = 0, j = 0, temp = 0;

while (gap >= 1) {
for (i = begin + gap;i <= end;i += 1) {
temp = array[i];
j = i - gap;
while (j >= begin && comparator.greaterThan(array[j], temp)) {
array[j + gap] = array[j];
j = j - gap;
}
array[j + gap] = temp;
}
gap = parseInt(gap / 2);
}

return array;
};

module.exports = shellSort;
42 changes: 42 additions & 0 deletions test/algorithms/sorting/shell_sort.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
'use strict';

var shellSort = require('../../../algorithms/sorting/shell_sort'),
assert = require('assert');

describe('shellSort', function () {
it('should sort the given array', function () {
assert.deepEqual(shellSort([]), []);
assert.deepEqual(shellSort([1]), [1]);
assert.deepEqual(shellSort([2, 1]), [1, 2]);
assert.deepEqual(shellSort([3, 1, 2]), [1, 2, 3]);
assert.deepEqual(shellSort([1, 2, 3, 4, 5, 6]), [1, 2, 3, 4, 5, 6]);
assert.deepEqual(shellSort([6, 5, 4, 3, 2, 1]), [1, 2, 3, 4, 5, 6]);
assert.deepEqual(shellSort([1, 295, 3, 6, 8, 10, 10, 20, 0, 5]),
[0, 1, 3, 5, 6, 8, 10, 10, 20, 295]);
});

it('should sort the array with a specific comparison function', function () {
var compare = function (a, b) {
if (a.length === b.length) return 0;
return a.length < b.length ? -1 : 1;
};
assert.deepEqual(shellSort([], compare), []);
assert.deepEqual(shellSort(['apple'], compare), ['apple']);
assert.deepEqual(shellSort(['apple', 'banana'], compare),
['apple', 'banana']);
assert.deepEqual(shellSort(['apple', 'banana', 'car'], compare),
['car', 'apple', 'banana']);
assert.deepEqual(shellSort(['apple', 'banana', 'car', 'z'], compare),
['z', 'car', 'apple', 'banana']);

var reverseSort = function (a, b) {
if (a == b) return 0;
return a < b ? 1 : -1;
};
assert.deepEqual(shellSort([1, 295, 3, 6, 8, 10, 10, 20, 0, 5],
reverseSort),
[295, 20, 10, 10, 8, 6, 5, 3, 1, 0]);
});
});


0 comments on commit 49b2a31

Please sign in to comment.