欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【笔记】二分法,有序数组中快速寻找某个元素的下标

程序员文章站 2024-03-17 14:57:22
...
function indexOfSorted(arr,n){
	var low = 0; 
	var high = arr.length - 1; 
	var mid = Math.ceil((low + high) / 2);
	console.log(mid);
	
	while(high > low){
		if(n == arr[low]){return low;}
		if(n == arr[high]){return high;}
		if(n == arr[mid]){return mid;} 
		if(n > arr[mid]){ low = mid; mid = Math.ceil((low + high) / 2); } 
		if(n < arr[mid]){ high = mid; mid = Math.ceil((low + high) / 2); } 
	}
}  
var sortedArr = [1,4,7,9,11,12,21,26,33]; 
console.log(indexOfSorted(sortedArr,12));