希尔排序
九:希尔排序
//增量为5,排序,增量为2排序
//增量为1,相邻的数组两两比较
function shellSort(arr) {
for (var gap = 5; gap > 0; gap = Math.floor(gap / 2)) {
for (var i = 0; i < arr.length; i++) {
for (var j = i + gap; j < arr.length; j += gap) {
// if(i+gap<arr.length){
if (arr[i] > arr[j]) {
//alert("gap:"+gap+";arr[i]:"+arr[i]+";arr[i+gap]:"+arr[i+gap])
swap(arr, i, j);
}
}
}
}
}
shellSort(arr)
桶排序
//八:桶排序
//根据步长space,分到num个桶里(桶是二维数组,num个桶每个桶里有N个数字)
//给数组每个数放入不同桶里。(脑子不够,写得比较水)
function bucketSort(arr) {
//space=20
var buckets = [], space = 20, num, index;
var max = arr[0];
var min = arr[0];
for (var i = 0; i < arr.length; i++) {
max = max > arr[i] ? max : arr[i];
min = min < arr[i] ? min : arr[i];
}
num = Math.floor((max - min)/space) + 1;
for (var i = 0; i < num; i++) {
for (var j = 0; j < arr.length; j++) {
index = Math.floor((arr[j] - min) / space);
if (buckets[index] == null) {
buckets[index] = [];
}
if(i==index){
buckets[i].push(arr[j]);
}
}
}
for(var i=0;i<buckets.length;i++){
if(buckets[i]!=null){
for(var j=0;j<buckets[i].length;j++){
var temp;
for(var k=j;k<buckets[i].length;k++){
if(buckets[i][j]>buckets[i][k]){
temp=buckets[i][k];
buckets[i][k]=buckets[i][j];
buckets[i][j]=temp;
}
}
}
}
}
alert(buckets)
}
bucketSort(arr);