Binary Search

 1 public class Solution
 2 {
 3     public boolean binarySearchForNormal(int[] data, int target)
 4     {
 5         int left = 0;
 6         
 7         int right = data.length - 1;
 8         
 9         while(left <= right)
10         {
11             int middle = (left + right) / 2;
12             
13             if(data[middle] == target)
14             {
15                 return true;
16             }
17             
18             if(data[middle] < target)
19             {
20                 left = middle + 1;
21             }
22             
23             if(data[middle] > target)
24             {
25                 right = middle - 1;
26             }
27         }
28         
29         return false;
30     }
31     
32     public boolean binarySearchForRecursive(int[] data, int target, int left, int right)
33     {
34         if(left > right)
35         {
36             return false;
37         }
38         
39         int middle = (left + right) / 2;
40         
41         if(data[middle] == target)
42         {
43             return true;
44         }
45         
46         if(data[middle] < target)
47         {
48             binarySearchForRecursive(data, target, middle + 1, right);
49         }
50         
51         if(data[middle] > target)
52         {
53             binarySearchForRecursive(data, target, left, middle - 1);
54         }
55         
56         return false;
57     }
58     
59     public boolean binarySearchForRecursiveAdapter(int[] data, int target)
60     {
61         return binarySearchForRecursive(data, target, 0, data.length - 1);
62     }
63     
64     public boolean checkOrder(int[] data, boolean isDesc)
65     {
66         for(int i = 0; i < data.length - 1; i ++)
67         {
68             if((isDesc == false) && (data[i] > data[i + 1]))
69             {
70                 return false;
71             }
72             
73             if((isDesc == true) && (data[i] < data[i + 1]))
74             {
75                 return false;
76             }
77         }
78         
79         return true;
80     }
81     
82 }
相關文章
相關標籤/搜索