1. 程式人生 > >js的二分法求陣列中某個值的索引

js的二分法求陣列中某個值的索引

為了解決最後一個數字無法顯示正確索引的問題,我直接加了一個判斷最後一個索引的判斷

<!DOCTYPE html>
<html>
<head>
	<title>123</title>
	<meta charset="utf-8">
</head>
<body>
	<script type="text/javascript">
		var arr = [1,2,3,4,5,6,7,8,9];
		// var target = 4;
		function  two(arr,target,
left,right){ var mid = Math.floor((left + right)/2); if (arr[arr.length - 1] == target) { document.write("索引是" + (arr.length-1)); } else{ if (arr[mid] > target) { two(arr,target,left,mid); } else if (arr[mid] < target) { two(arr,target,mid,right); } else
{ document.write("索引是" + mid); } } } two(arr,6,0,arr.length-1);
</script> </body> </html>