function findHelper(leftIndex, rightIndex,arr, el){
var left=arr[leftIndex]
var right=arr[rightIndex]
var centerIndex=Math.round((leftIndex+rightIndex)/2)
var center=arr[centerIndex]
console.log(leftIndex+":"+rightIndex)
if(right==el){
return rightIndex
}
if(left==el){
return leftIndex
}
if(center==el){
return centerIndex
}
if(Math.abs(leftIndex-rightIndex)<=2){ // no element found
return 0;
}
if(left<center){ //left to center are sorted
if(left<el && el<center){
return findHelper (leftIndex, centerIndex, arr, el)
}
else{
return findHelper (centerIndex, rightIndex, arr, el)
}
}
else if(center<right){//center to right are sorted
if(center<el && el<right){
return findHelper (centerIndex, rightIndex, arr, el)
}
else{
return findHelper (leftIndex, centerIndex, arr, el)
}
}
}
function find(el, arr){
return findHelper(0, arr.length-1, arr,el)+1
}
// some testcases
console.log(find(1, [1,2,5,8,11,22])==1)
console.log(find(2, [1,2,5,8,11,22])==2)
console.log(find(5, [1,2,5,8,11,22])==3)
console.log(find(8, [1,2,5,8,11,22])==4)
console.log(find(11, [1,2,5,8,11,22])==5)
console.log(find(22, [1,2,5,8,11,22])==6)
console.log(find(11, [11,22, 1,2,5,8])==1)
console.log(find(22, [11,22, 1,2,5,8])==2)
console.log(find(1, [11,22, 1,2,5,8])==3)
console.log(find(2, [11,22, 1,2,5,8])==4)
console.log(find(5, [11,22, 1,2,5,8])==5)
console.log(find(8, [11,22, 1,2,5,8])==6)
编辑:
上述算法的复杂度与二分查找相同。
为了正确起见,我会这样做:“如果您在任意点拆分交换排序数组,则必须至少对结果数组中的一个进行排序,而另一个必须(至少)对交换排序。如果元素是不在已排序数组的范围内,则不能在该数组中,如果在范围内,则不能在已排序数组之外。我们继续在已排序或交换排序数组中搜索。由于任何已排序的数组都是也交换排序,我们可以再次使用相同的算法。(归纳证明)。”