搜尋此網誌

2012年3月23日 星期五

Binary Search (Recursive version)

Before you do binary search, you should sort the unsorted elements first 在使用binary搜尋之前, 要先把資料排序過. Sort(排序)

public class BinarySearch {
 
 public static void main(String [] args){
  int [] i ={2,3,4,4,5,6,7,87};
  System.out.println(binarySearch(i,0,i.length-1,5));
  
 }
 
 public static int binarySearch(int[] i, int left, int right, int target) {
  int middle = (left+right)/2;
  if (i[middle] == target) {
   return middle;
  } else if (i[middle] > target) {
   return binarySearch(i,left,middle,target);
  } else{
   return binarySearch(i,middle,right,target);
  }
 }
}



A c++ binary search tree

Iterative and Recursive

沒有留言:

張貼留言