中位插入法 中位查询法
DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>title>
head>
<body>
body>
<script>
var a = [391,5,11,304,166,638,592,760,206,183,926,220,431,134,949,281,994,876,385,162,336,478,70,304,231,633,624,155,563,426,305,499,244,448,811,349,797,408,84,219,281,985,31,451,492,756,637,690,678,545,969,102,82,677,494,291,60,762,746,313,922,830,457,971,232,405,218,316,964,739,572,992,437,364,973,111,868,921,205,647,643,762,294,763,786,294,170,859,365,600,219,42,294,173,103,204,253,118,236,732,786]
// 随机生成100个随机数
// for( var i = 0; i < 101; i++ ) a.push(parseInt(Math.random()*1000))
// 中位插入发
function centerAdd (array, sum, find, filter){
// 首先查询
var index = centerFind(array, find, filter);
index = index.index;
array.splice(index,0,sum)
}
// 中位查询法
function centerFind (array, find, order , start, end){
// 数组为空是返回空
if( array.length <= 0 ) return { data: undefined, index: 0 };
// 初始化起始数
start = start || 0;
// 初始化末尾值
end = end || array.length - 1;
// 查询方法
find = find; // function(e){ return e.lon }
// 如果length大于2的时候
if( end - start > 2 ){
// 获取中位数
const center = parseInt(start+(end - start)/ 2)+1;
// 获取中文个数
const centerGraphic = array[center]
// 判断是否相等
if( find(centerGraphic) ){
// 如果相等判断存在
return { data: centerGraphic, index: center };
}else if( order(centerGraphic) ){
// 说明数值小于当前数据
end = center;
}else{
start = center;
}
return centerFind(array, find, order, start, end)
}else{
// 如果只剩2个 则直接默认
var i;
for( i = start; i <= end; i++ ){
if( find(array[i]) ){
return { data: array[i], index: i };
}else if( order(array[i]) ){
// 说明数值小于当前数据
return { data: array[i], index: i }
}
}
return { data: undefined, index: i };
}
}
var b = a[5];
var c = [];
a.forEach((ee)=>{
centerAdd(c,ee,function(e){ return e == ee }, function(e){ return e > ee; });
})
a.forEach((ee)=>{
console.log("要查询的数据为" ,ee);
console.log("查询结果为", centerFind(a, function(e){ return e == ee }, function(e){ return e > ee; }) )
})
script>
html>
没撒好说地。。。