|
| 1 | +//LINEAR SEARCH |
| 2 | + |
| 3 | +class LinearSearch { |
| 4 | + // This function returns index of element x in arr[] |
| 5 | + static int search(int arr[], int n, int x) |
| 6 | + { |
| 7 | + for (int i = 0; i < n; i++) { |
| 8 | + // Return the index of the element if the element |
| 9 | + // is found |
| 10 | + if (arr[i] == x) |
| 11 | + return i; |
| 12 | + } |
| 13 | + |
| 14 | + // return -1 if the element is not found |
| 15 | + return -1; |
| 16 | + } |
| 17 | + |
| 18 | + public static void main(String[] args) |
| 19 | + { |
| 20 | + int[] arr = { 3, 4, 1, 7, 5 }; |
| 21 | + int n = arr.length; |
| 22 | + |
| 23 | + int x = 4; |
| 24 | + |
| 25 | + int index = search(arr, n, x); |
| 26 | + if (index == -1) |
| 27 | + System.out.println("Element is not present in the array"); |
| 28 | + else |
| 29 | + System.out.println("Element found at position " + index); |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | + |
| 34 | +//BINARY SEARCH |
| 35 | + |
| 36 | +class BinarySearch { |
| 37 | + // Returns index of x if it is present in arr[l.. |
| 38 | + // r], else return -1 |
| 39 | + int binarySearch(int arr[], int l, int r, int x) |
| 40 | + { |
| 41 | + if (r >= l) { |
| 42 | + int mid = l + (r - l) / 2; |
| 43 | + |
| 44 | + // If the element is present at the |
| 45 | + // middle itself |
| 46 | + if (arr[mid] == x) |
| 47 | + return mid; |
| 48 | + |
| 49 | + // If element is smaller than mid, then |
| 50 | + // it can only be present in left subarray |
| 51 | + if (arr[mid] > x) |
| 52 | + return binarySearch(arr, l, mid - 1, x); |
| 53 | + |
| 54 | + // Else the element can only be present |
| 55 | + // in right subarray |
| 56 | + return binarySearch(arr, mid + 1, r, x); |
| 57 | + } |
| 58 | + |
| 59 | + // We reach here when element is not present |
| 60 | + // in array |
| 61 | + return -1; |
| 62 | + } |
| 63 | + |
| 64 | + |
| 65 | + public static void main(String args[]) |
| 66 | + { |
| 67 | + BinarySearch ob = new BinarySearch(); |
| 68 | + int arr[] = { 2, 3, 4, 10, 40 }; |
| 69 | + int n = arr.length; |
| 70 | + int x = 10; |
| 71 | + int result = ob.binarySearch(arr, 0, n - 1, x); |
| 72 | + if (result == -1) |
| 73 | + System.out.println("Element not present"); |
| 74 | + else |
| 75 | + System.out.println("Element found at index " + result); |
| 76 | + } |
| 77 | +} |
0 commit comments