Skip to content

Commit 7f58d29

Browse files
committed
Add Shell Sorting
1 parent 2789ecf commit 7f58d29

1 file changed

Lines changed: 29 additions & 0 deletions

File tree

sorting/ShellSort.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/* "Shell sort or Shell's method, is an in-place comparison sort.
2+
It can be seen as either a generalization of sorting by exchange (bubble sort) or sorting by insertion (insertion sort).
3+
The method starts by sorting pairs of elements far apart from each other, then progressively reducing the gap between elements to be compared.
4+
Starting with far apart elements can move some out-of-place elements into position faster than a simple nearest neighbor exchange." */
5+
6+
function shellSort(arr) {
7+
var increment = arr.length / 2;
8+
while (increment > 0) {
9+
for (i = increment; i < arr.length; i++) {
10+
var j = i;
11+
var temp = arr[i];
12+
13+
while (j >= increment && arr[j-increment] > temp) {
14+
arr[j] = arr[j-increment];
15+
j = j - increment;
16+
}
17+
18+
arr[j] = temp;
19+
}
20+
21+
if (increment == 2) {
22+
increment = 1;
23+
} else {
24+
increment = parseInt(increment*5 / 11);
25+
}
26+
}
27+
return arr;
28+
}
29+

0 commit comments

Comments
 (0)