# 中位插入法 中位查詢法

```<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title></title>
<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>```