首页 > 其他 > 详细

数据查询

时间:2020-06-16 15:36:45      阅读:44      评论:0      收藏:0      [点我收藏+]

二分查找法

/* 二分查找(前提数组是有序数组) */
function binarySearch(arr,target){
    var minIndex = 0;
    var maxIndex = arr.length - 1;
    if(arr.length == 0 || target <arr[0] || target > arr[arr.length -1 ])return false;
    while(minIndex <=maxIndex){
        var mid = Math.floor((maxIndex+minIndex) / 2)
        if(arr[mid] == target){
            return true
        }else if(arr[mid] > target){
            maxIndex = mid - 1
        }else{
            minIndex = mid + 1
        }
    }
    return false
}

插入查找

/* 插入查找(前提数组不重复并且是有序数组) */
//目标下标 = (目标值 - 最小值) / (最大值-最小值) *(最大下标- 最小下标) + 最小下标
function interpolationSearch(arr,target){
     var minIndex = 0;
    var maxIndex = arr.length - 1;
    if(arr.length == 0 || target <arr[0] || target > arr[arr.length -1 ])return false;
    while(minIndex <=maxIndex){
        var mid = (target - arr[minIndex]) /(arr[maxIndex] - arr[minIndex]) *(maxIndex - minIndex) + minIndex
        if(arr[mid] == target){
            return true
        }else if(arr[mid] > target){
            maxIndex = mid - 1
        }else{
            minIndex = mid + 1
        }
    }
    return false
}

 

技术分享图片

 

数据查询

原文:https://www.cnblogs.com/wangyisu/p/13141083.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!