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)
EDIT :
상기 이진 검색 알고리즘과 동일한 복잡도를 갖는다.
정확함을 위해 "임의의 지점에서 스왑 정렬 된 배열을 분할하면 결과 배열 중 적어도 하나는 정렬되어야하고 다른 배열은 (적어도) 스왑 정렬되어야합니다. 정렬 된 배열 범위를 벗어났습니다. 범위 내에 있으면 정렬 된 배열 외부에있을 수 없습니다. 정렬 된 배열이나 스왑 정렬 된 배열에서 계속 검색합니다. 정렬 된 배열 또한 스왑을 통해 동일한 알고리즘을 다시 사용할 수 있습니다 (유도에 의한 증명). "
몇 가지 예를 제공해 줄 수 있습니까? – Zabuza
[회전 된 정렬 된 배열에서 번호 검색] (https://stackoverflow.com/questions/1878769/searching-a-number-in-a-rotated-sorted-array)의 가능한 복제본 –