Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 45 additions & 17 deletions core-java/basics/BinarySearch.java
Original file line number Diff line number Diff line change
@@ -1,19 +1,47 @@
package basics;
import java.util.Arrays;

public class BinarySearch {

public static void main(String[] args) {

int arr[] = {10, 20, 15, 22, 35};
Arrays.sort(arr);

int key = 35;
int res = Arrays.binarySearch(arr, key);
if(res >= 0){
System.out.println(key + " found at index = "+ res);
} else {
System.out.println(key + " not found");
}
// Java implementation of iterative Binary Search

import java.io.*;

class BinarySearch {

// Returns index of x if it is present in arr[].
int binarySearch(int arr[], int x)
{
int l = 0, r = arr.length - 1;
while (l <= r) {
int m = l + (r - l) / 2;

// Check if x is present at mid
if (arr[m] == x)
return m;

// If x greater, ignore left half
if (arr[m] < x)
l = m + 1;

// If x is smaller, ignore right half
else
r = m - 1;
}

// If we reach here, then element was
// not present
return -1;
}

// Driver code
public static void main(String args[])
{
BinarySearch ob = new BinarySearch();
int arr[] = { 2, 3, 4, 10, 40 };
int n = arr.length;
int x = 10;
int result = ob.binarySearch(arr, x);
if (result == -1)
System.out.println(
"Element is not present in array");
else
System.out.println("Element is present at "
+ "index " + result);
}
}