let array = [24,1,6,45,23,11,2,34,8,54,14];
/*
//直接插入排序 O(n2)
for (let i=0;i<array.length;i++){
for (let j=0;j<i;j++){
if(array[i]<array[j]){
let siwt = array[i];
for (let k=i;k>j;k--){
array[k] = array[k-1];
}
array[j] = siwt;
}
}
}
*/
//折半插入排序
/*
伪代码
for(i in arr.length){
}
*/
for (let i=0;i<array.length;i++){
let low = 0;
let high = i-1;
let middle = Math.floor(((low+high)/2));
while(low<high){
console.log(`${low},${high},${middle} | ` + [...array]);
if(array[i]<array[middle]){
high = middle-1;
}else{
low = middle+1;
}
middle = Math.floor(((low+high)/2));
}
middle = array[middle]>array[i]?middle:(middle+1);
let dist = array[i];
for(let j=i;j>middle;j--){
array[j]=array[j-1];
}
array[middle] = dist;
}
console.log([...array]);
//冒泡排序
太简单就不写了
//快速排序
/*
伪代码
quickSort(low,high){
let middle = (low+high)/2
let i=low,j=high;
while(i<j){
while(arr[i++]>arr[middle]){
exchange
}
while(arr[j--]<arr[middle]){
exchange
}
}
return middle;
}
sort(low,high){
if(low>=high) return;
middle = quickSort(low,high)//middle为选中的数字排完序之后所处的位置
sort(low,middle)
sort(middle+1,low)
}
*/
let i = 0;
let quickSort = (low,high)=>{
let middle = Math.floor((low+high)/2);
console.log(`low:${low},high:${high},middle:${middle}`);
let i = low;
let j = high;
while(i<j){
while(i<middle){
if(array[i]>array[middle]){
console.log(`before : ${array[i]},${array[middle]}`);
let dist = array[i];
array[i] = array[middle];
array[middle] = dist;
middle = i;
i++;
break;
}
i++;
}
while(j>middle){
if(array[j]<array[middle]){
console.log(`after : ${array[i]},${array[middle]}`);
let dist = array[j];
array[j] = array[middle];
array[middle] = dist;
middle = j;
j--;
break;
}
j--;
}
}
return middle;
};
let mainQuickSort = (low,high)=>{
console.log([...array]);
let middle = quickSort(low,high);
if (low>=high) {
return;
}
mainQuickSort(low,middle);
mainQuickSort(middle+1,high);
};
mainQuickSort(0,array.length-1);
js实现排序(持续更新)
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...