|
2 | 2 | class binarySearch {
|
3 | 3 |
|
4 | 4 | public static void main(String[] args) {
|
5 | | - int arr[] = {1, 2, 3, 4, 5, 6, 57, }; |
6 | | - int target = 6; |
7 | | - int result = binarySearching(arr, target); |
8 | | - System.out.println("the target element index is: " + result); |
9 | | - |
10 | | - } |
11 | | - |
12 | | - public static int binarySearching(int arr[], int target) { |
| 5 | + int[] arr = {3, 5, 7, 9, 11, 13, 15, 17}; |
| 6 | + int target_item = 13; |
| 7 | + int result = binarySearching(arr, target_item); |
13 | 8 |
|
14 | | - int start = 0; |
15 | | - int end = arr.length - 1; |
16 | | - int mid; |
| 9 | + if (result != -1) { |
| 10 | + System.out.println("element in index of : " + result); |
| 11 | + } else { |
| 12 | + System.out.println("element not found.."); |
| 13 | + } |
| 14 | + } |
17 | 15 |
|
18 | | - while (start <= end) { |
19 | | - mid = (start + end) / 2; |
20 | | - if (arr[mid] == target) { |
| 16 | + public static int binarySearching(int[] a, int target) { |
| 17 | + int left = 0; |
| 18 | + int right = a.length - 1; |
| 19 | + while (left <= right) { |
| 20 | + int mid = (left + right) / 2; |
| 21 | + if (a[mid] == target) { |
21 | 22 | return mid;
|
22 | | - } else { |
23 | | - if(target < arr[mid]){ |
24 | | - end = mid - 1; |
25 | | - }else{ |
26 | | - start = mid + 1; |
27 | | - } |
28 | | - } |
29 | | - |
| 23 | + } else if (a[mid] < target) { |
| 24 | + left = mid + 1; |
| 25 | + }else{ |
| 26 | + right = mid - 1; |
30 | 27 | }
|
31 | | - |
32 | | - return -1; |
33 | 28 | }
|
| 29 | + return -1; |
34 | 30 | }
|
35 | | - |
| 31 | +} |
0 commit comments