Skip to content

Commit afbb8d2

Browse files
committed
shell sort
1 parent 8aecf0b commit afbb8d2

1 file changed

Lines changed: 35 additions & 0 deletions

File tree

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// The Shellsort algorithm
2+
3+
// Definition
4+
5+
// Shellsort is an in-place comparison sort which can be seen as either a generalization of sorting by exchange
6+
// (bubble sort) or sorting by insertion (insertion sort).
7+
// The method starts by sorting pairs of elements far apart from each other, then progressively reducing
8+
// the gap between elements to be compared. Starting with far apart elements can move some out-of-place
9+
// elements into position faster than a simple nearest neighbor exchange. From Wikipedia
10+
11+
// Shellsort is a generalization of insertion sort that allows the exchange of items that are far apart.
12+
// It is worth noting that for a value of gap equals to 1, this algorithm is equal to insertion sort.
13+
// Have a look at the code below and you will quickly notice the similarities.
14+
15+
// array to sort
16+
var array = [9, 2, 5, 6, 4, 3, 7, 10, 1, 8];
17+
18+
// gaps
19+
var gaps = [701, 301, 132, 57, 23, 10, 4, 1];
20+
21+
function shellsort(array) {
22+
for(var g = 0; g < gaps.length; g++) {
23+
var gap = gaps[g];
24+
for(var i = gap; i < array.length; i++) {
25+
var temp = array[i];
26+
for(var j = i; j >= gap && array[j - gap] > temp; j -= gap) {
27+
array[j] = array[j - gap];
28+
}
29+
array[j] = temp;
30+
}
31+
}
32+
return array;
33+
}
34+
35+
console.log(shellsort(array)); // => [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

0 commit comments

Comments
 (0)