Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create Binary_Search #127

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions Java/Binary_Search
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import java.util.*;

//this function will return -1 if the element is not found
//returns the index if element is found

class binarysearch {
int binarySearch(int arr[], int l, int r, int x) {
if (r >= l) {
int mid = l + (r - l) / 2;

if (arr[mid] == x)
return mid;

if (arr[mid] > x)
return binarySearch(arr, l, mid - 1, x);

return binarySearch(arr, mid + 1, r, x);
}

return -1; //element not found
}

public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
BinarySearch ob = new BinarySearch();
System.out.println("Enter array size");
int l = sc.nextInt();
int arr[] = new int[l];
System.out.println("Enter the array");
for (int i = 0; i < l; i++) {
arr[i] = sc.nextInt();
}
System.out.println("Enter the number to be searched");
int n = sc.nextInt();
int result = ob.binarySearch(arr, 0, n - 1, x);
if (result == -1)
System.out.println("Element not present");
else
System.out.println("Element found at index " + result);
}
}