+ 1
Can anyone say how to use binary search in array
3 Answers
+ 10
class BinarySearchExample
{
public static void main(String args[])
{
int counter, num, item, array[], first, last, middle;
//To capture user input
Scanner input = new Scanner(System.in); System.out.println("Enter number of elements:"); num = input.nextInt();
//Creating array to store the all the numbers
array = new int[num];
System.out.println("Enter " + num + " integers");
//Loop to store each numbers in array
for (counter = 0; counter < num; counter++) array[counter] = input.nextInt(); System.out.println("Enter the search value:");
item = input.nextInt();
first = 0;
last = num - 1;
middle = (first + last)/2;
while( first <= last )
{
if ( array[middle] < item )
first = middle + 1;
else if ( array[middle] == item )
{
System.out.println(item + " found at location " + (middle + 1) + ".");
break; }
else { last = middle - 1; }
middle = (first + last)/2; }
if ( first > last )
System.out.println(item + " is not found.\n"); }
0
Ensure that your array is sorted since this is the crux of a binary search.
Any indexed/random-access data structure can be binary searched. So when you say using "just an array", I would say arrays are the most basic/common data structure that a binary search is employed on.
You can do it recursively (easiest) or iteratively. Time complexity of a binary search is O(log N) which is considerably faster than a linear search of checking each element at O(N).
0
Remmae if you have the time, could you please take a look at a question i posted about binary search on 2d array? Iâd really appreciate it