From c2050482c662ef0976d9ee6fa8c97cf1276b169a Mon Sep 17 00:00:00 2001 From: vyom18 <62300723+vyom18@users.noreply.github.com> Date: Wed, 4 Oct 2023 11:46:50 +0530 Subject: [PATCH] Create binarysearch --- binarysearch | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 binarysearch diff --git a/binarysearch b/binarysearch new file mode 100644 index 00000000..421f93b9 --- /dev/null +++ b/binarysearch @@ -0,0 +1,25 @@ +class BinarySearchExample{ + public static void binarySearch(int arr[], int first, int last, int key){ + int mid = (first + last)/2; + while( first <= last ){ + if ( arr[mid] < key ){ + first = mid + 1; + }else if ( arr[mid] == key ){ + System.out.println("Element is found at index: " + mid); + break; + }else{ + last = mid - 1; + } + mid = (first + last)/2; + } + if ( first > last ){ + System.out.println("Element is not found!"); + } + } + public static void main(String args[]){ + int arr[] = {10,20,30,40,50}; + int key = 30; + int last=arr.length-1; + binarySearch(arr,0,last,key); + } +}