<!doctype html>
<html>
<head>
</head>
<body >
</body>
<script >
function shellSort(arr) {
var step = 5;
while (step > 0) {
for (var i = step;i<arr.length;i++) {
var j = i-step;
var key = arr[i];
while (j>=0 && key<arr[j]) {
arr[j+step] = arr[j];
j-=step;
}
arr[j+step] = key;
}
step = Math.floor(step/2);
}
return arr;
}
function shellSort2(arr) {
var step = 5;
for(;step>0;step=Math.floor(step/2)) {
for (var i = step;i<arr.length;i++) {
var key = arr[i];
for (var j=i-step;j>=0;j=j-step) {
if (arr[j]>key) {
arr[j+step] = arr[j];
}
else{
break;
}
}
arr[j+step] = key;
}
}
return arr;
}
function shellSortRecursion(arr,step) {
if(step<1) {
return;
}
for (var i = step;i<arr.length;i++) {
var j = i-step;
var key = arr[i];
while (j>=0 && key<arr[j]) {
arr[j+step] = arr[j];
j-=step;
}
arr[j+step] = key;
}
step = Math.floor(step/2);
shellSortRecursion(arr,step);
}
var arr =[];
for (var i=0;i<30;i++) {
arr.push(~~(Math.random()*100))
}
shellSortRecursion(arr,5)
console.log(arr)
</script>
<html>
<head>
</head>
<body >
</body>
<script >
function shellSort(arr) {
var step = 5;
while (step > 0) {
for (var i = step;i<arr.length;i++) {
var j = i-step;
var key = arr[i];
while (j>=0 && key<arr[j]) {
arr[j+step] = arr[j];
j-=step;
}
arr[j+step] = key;
}
step = Math.floor(step/2);
}
return arr;
}
function shellSort2(arr) {
var step = 5;
for(;step>0;step=Math.floor(step/2)) {
for (var i = step;i<arr.length;i++) {
var key = arr[i];
for (var j=i-step;j>=0;j=j-step) {
if (arr[j]>key) {
arr[j+step] = arr[j];
}
else{
break;
}
}
arr[j+step] = key;
}
}
return arr;
}
function shellSortRecursion(arr,step) {
if(step<1) {
return;
}
for (var i = step;i<arr.length;i++) {
var j = i-step;
var key = arr[i];
while (j>=0 && key<arr[j]) {
arr[j+step] = arr[j];
j-=step;
}
arr[j+step] = key;
}
step = Math.floor(step/2);
shellSortRecursion(arr,step);
}
var arr =[];
for (var i=0;i<30;i++) {
arr.push(~~(Math.random()*100))
}
shellSortRecursion(arr,5)
console.log(arr)
</script>
</html>
希尔排序主要是每次步长里执行插入排序,这个插入排序的元素是相隔一定步长的而已,主要是三次循环,其中for和while可以替换使用,最后一种是递归实现,在v8下会进行尾调优化,这样可以避免递归栈溢出。