Binary Search tree

Hello,

For most of time i was wrote Binary search tree and find it's easy to implement you need to search for key in array check if key equal to current index return it if it's less than search in leftside and greater than search in write side Here's most of internet source code people use for BST




public class BinarySearch{
 static int search(int []a, int k){
  int low=0;
  int high=a.length-1;
  int middle;
  while(low <=high){
   middle = (low+high) /2;
   if(a[middle] == k){
    return middle;
   }else if(a[middle] < k){
    low = middle + 1;
   }else{
    high = middle-1;
   }
  }
  
 }
}

However this code has bug ! , yes exactly it's bug in line
middle = (low+high) / 2 
oops ? didn't understand it okay let me explain this

the error in assignment middle = (low+high)/2 can lead overflow and should replace with middle = low + ( high-low) /2


Well That's it !
Bye !

Comments

Popular Posts