I'm working on a program where I have to demonstrate the working of a linear and binary search algorithm. For that, I'm acceping an array of 20 numbers and a search key from the user. The code compiles, and no runtime errors are thrown. However, when I search for a number, say 12, in the array, instead of printing that the number was found in position 12, it says that the number was found in position 6:
import java.util.*;
class prg14
{
int num [] = new int [20];
int search;
public void lin (int arr[], int a)
{
num = arr;
search = a;
int i;
int flag = 0;
for (i=0; i<num.length; i++)
{
if (search == num[i])
{
flag = 1;
break;
}
}
if (flag == 1)
{
System.out.println("Linear Search : ");
System.out.println(a+ " found at position " + (i + 1));
}
else
{
System.out.println("Linear Search : ");
System.out.print(a+ " not present in the list \n");
}
}
public void binary(int array[], int a)
{
int first = 0;
int n = 20;
int last = n - 1;
int middle = (first + last)/2;
while( first <= last )
{
if ( array[middle] < search )
first = middle + 1;
else if ( array[middle] == search )
{
System.out.println("Binary search : ");
System.out.println(search + " found at position " + (middle+1) + ".");
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if ( first > last )
{System.out.println("Binary Search : ");
System.out.println(search + " not present in the list.\n");
}
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
prg14 obj = new prg14();
System.out.println("Enter any 20 numbers.");
String str;
int linn[] = new int[20];
int i;
for( i = 0; i<10; i++)
{
str = sc.next();
linn[i] = sc.nextInt();
}
System.out.println("Enter number to be searched.");
int search = sc.nextInt();
obj.lin(linn, search);
obj.binary(linn, search);
}
}
How do I resolve this issue? TIA.
Remove
String str
, likeYou aren't mixing line input and tokenized input so you don't need to worry about trailing newlines (in this case). Also, I would implement a linear search function by returning a matching index (or -1 if it isn't found)
I would do the same for the binarySearch. That way you can separate the message display from the calculation.