90% of programmers cannot implement the binary search algorithm correctly? ? ?

     Preface

           Jon Bentley, the author of ProgrammingPearls ("Programming Pearls"), once said something similar: "90% of programmers cannot correctly implement binary search algorithms..."

     The implication is that only 1/10 of the programmers can write a "binary search algorithm". I saw this sentence again yesterday, so I opened eclipse at any time and wrote it down, and it went smoothly.


About "Binary Search Algorithm"

The "binary search algorithm" is also called "half search" or "half search" in many places. It is a more commonly used "search/find" algorithm. The basic idea is to find the minimum, maximum, and intermediate values, and then compare them. The search speed is fast and the performance is good. But the table being looked up needs to be in order (the popular point is that it needs to be sorted).


Not much nonsense, just go to the code.


package com.dylan.algorithm;

import javax.sound.sampled.Mixer;

public class BinarySearch {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
      
		 int arr[] ={10,24,36,47,68,89,130};
		 int index = Search(arr, 89);
		 System.out.println(index);
	}
	/*实现二分查找算法(折半算法)
	 *要确定数组是排序好的
	 *最好是里面一定包含该元素
	 */
	public static int  Search(int[] arr,int key ) {
		 
		  int min =0;
		  int max=arr.length-1;
		  int mid = (min+max)/2;
		  while(arr[mid]!=key){		  
			  if (arr[mid]<key) {
				 min=mid+1;
		    	}else if (arr[mid]>key) {			
		    	 max=mid-1;
			   }
			 if(max<min){			 
				 return -1;//里面不存在值为key的元素
			 }
			 //继续折半
			 mid=(min+max)/2;
		  }
		  
		return mid;
	}

}

      Interested students, you can try to run it according to the code to see if it can be found correctly, whether there will be problems such as endless loops. To be honest, I rarely use this thing in my work. I had "slammed" for an interview a few years ago. I didn't expect it to be able to write something out of my impression. If I have time in the near future, it is time to review the basics.

Maybe most of the coders now have some "fear" or even "disgust" about "data structure and algorithm". When I have time in the next day, I will use the form of drawing to describe in detail the basic idea of ​​the "binary search algorithm" and detailed derivation steps.

Guess you like

Origin blog.csdn.net/dinglang_2009/article/details/20404323