Binary search method of java learning notes

Keywords: Java PHP less

java binary search method

I saw a binary search method of php when I was browsing the code cloud tonight. I was familiar with the word. (I learned it when I was learning php, but I didn't use it in my work, and I was confused when I was in school, and I forgot it slowly). I clicked in, wrote it in java, and used recursion.

Personal understanding of dichotomy:

First of all, you have to be an array in the order of small to large, and take the middle of the array index. Compare the size of the elements in the middle index with the elements to be searched. If the value of the elements to be searched is greater than the middle elements, then take the middle index to the last index in the next round to take the middle index and compare the size. If the value of the element to be found is less than the intermediate element, then the next round will take the range from the array start index to the intermediate index to take the intermediate index, and then compare the size, so we will continue to find.


php source code:

 1 <?php
 3 // Dichotomy search
 4   function search(&$arr,$final,$leftIndex,$rightIndex){
 5      if($leftIndex>$rightIndex){
 6         echo "Can not find";
 7         return;
 8      }
10      $middleIndex=round(($leftIndex+$rightIndex)/2);
12      //If it is greater than, look like the back
13      if($final>$arr[$middleIndex]){
14         search($arr,$final,$middleIndex+1,$rightIndex);
15      //If less than, look ahead
16      }else if($final<$arr[$middleIndex]){
17        search($arr,$final,$leftIndex,$middleIndex-1);
18      }else{
19         echo "Found the subscript yes$middleIndex";
20      }
21   }
22  $arr=array(10,88,99,888,7777);
23   search($arr,99,0,count($arr)-1);
24 ?>

java code implementation:

 1 public class Demo02 {
 2     public static void main(String[] args) {
 3         int[]  arr={34,32,44,23,43,24};
 4         Arrays.sort(arr);
 5         System.out.println(Arrays.toString(arr));
 6         search(arr, 32, 0, arr.length-1);
 7     }
 9     public static void search(int[] arr,int searchNum,int leftIndex,int rightIndex){
10         if(leftIndex>rightIndex){
11             System.out.println("Can not find");
12             return;
13         }
14         int middleIndex=Math.round((leftIndex+rightIndex)/2);
15         if(searchNum>arr[middleIndex]){
16             search(arr, searchNum, middleIndex+1, rightIndex);
17         }else if(searchNum<arr[middleIndex]){
18             search(arr, searchNum, leftIndex, middleIndex-1);
19         }else {
20             System.out.println("Target found:"+middleIndex);
21         }    
22     }
25 }

Posted by ognotongo on Mon, 04 May 2020 22:05:08 -0700