乐趣区

关于javascript:JS基本排序查找记录

一、二分查找

binarySearch=(arr,target)=>{
    let len=arr.length,max=len-1,min=0;
    while(min<=max){let mid=Math.floor((max+min)/2)
        if(arr[mid]>target){max=mid-1}else if(arr[mid]<target){min=mid+1}else{return mid}
    }
    return -1
}

二、归并排序 – 先拆后合 – 分治思维 –nlogn

mergeSort=(arr)=>{let len=arr.length,mid=Math.floor(len/2);
    if(len==1)return arr
    let left=arr.slice(0,mid)
    let right=arr.slice(mid)
    return merge(mergeSort(left),mergeSort(right))
}
merge=(left,right)=>{let result=[]
    while(left.length&&right.length){if(left[0]<=right[0]){result.push(left.shift())
        }else{result.push(right.shift())
        }
    }
    while(left.length){result.push(left.shift())
    }
    while(right.length){result.push(right.shift())
    }
    return result
}

三、冒泡排序

bubbleSort=(arr)=>{
    let len=arr.length;
    for(let i=0;i<len;i++){for(let j=0;j<len-1-i;j++){if(arr[j]>arr[j+1]){let temp=arr[j]
                arr[j]=arr[j+1]
                arr[j+1]=temp
            }
        }
    }
    return arr
}

四、希尔排序 – 距离比照 – 固定距离和动静距离

functtion shellSort(arr){
    let len=arr.length;
    let gap=Math.floor(len/2);
    while(gap!=0){for(var i=gap;i<len;i++){var temp=arr[i],j
             for(j=i-gap;j>=0&&temp<arr[j];j-=gap){arr[j+gap]=arr[j]
             }
             arr[j+gap]=temp
        }
        gap=Math.floor(gap/2)
    }
    return arr
}
动静距离版
function shellSort(arr){
    var len=arr.length,temp,gap=1;
    while(gap<len/3){gap=gap*3+1}
    while(gap!=0){console.log('gap 值',gap)
        for(var i=gap;i<len;i++){console.log('第一层循环',i)
            temp=arr[i]
            for(var j=i-gap;j>=0&&arr[j]>temp;j-=gap){console.log('第二层循环',j,arr[j],temp)
                arr[j+gap]=arr[j]
            }
            arr[j+gap]=temp
            console.log('第二层循环结束',arr)
        }
        gap=Math.floor(gap/3)
        console.log('第一层循环结束 arr',arr,gap)
    }
    return arr
}

五、插入排序 – 距离为 1 的希尔排序 – 图 https://www.cnblogs.com/cc-freiheit/p/10983395.html

function insertSort(arr){
    let len=arr.length
    for(var i=1;i<len;i++){var temp=arr[i]
        for(var j=i-1;j>=0&&arr[j]>temp;j-=1){arr[j+1]=arr[j]
        }
        arr[j+1]=temp
    }
    return arr
}

ps 参考文章:https://github.com/damonare/Sorts

退出移动版