-
-
Notifications
You must be signed in to change notification settings - Fork 544
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
2f88cf0
commit 6bb3d8d
Showing
1 changed file
with
49 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
import java.util.Arrays; | ||
|
||
public class BinarySearchExample { | ||
|
||
// Method for performing binary search | ||
public static int binarySearch(int[] array, int key) { | ||
int left = 0; | ||
int right = array.length - 1; | ||
|
||
while (left <= right) { | ||
int mid = left + (right - left) / 2; | ||
|
||
// Check if the key is present at mid | ||
if (array[mid] == key) { | ||
return mid; // key found, return index | ||
} | ||
|
||
// If the key is greater, ignore the left half | ||
if (array[mid] < key) { | ||
left = mid + 1; | ||
} | ||
// If the key is smaller, ignore the right half | ||
else { | ||
right = mid - 1; | ||
} | ||
} | ||
|
||
// If we reach here, the element is not present in array | ||
return -1; | ||
} | ||
|
||
public static void main(String[] args) { | ||
// Example usage | ||
int[] array = {2, 3, 4, 10, 40, 50, 60}; | ||
int key = 10; | ||
|
||
// The array must be sorted | ||
Arrays.sort(array); | ||
|
||
// Perform binary search | ||
int result = binarySearch(array, key); | ||
|
||
if (result == -1) { | ||
System.out.println("Element not present in the array"); | ||
} else { | ||
System.out.println("Element found at index: " + result); | ||
} | ||
} | ||
} |