I have the following implementation of binary and sequential search. I'm not very experienced with Java, and somehow implementation of both methods always returns -1 when searching an element:
import java.util.Random;
import java.util.Scanner;
public class searchArrayDemo {
private static int binarySearch(int[] inputArr, int key) {
int start = 0;
int end = inputArr.length - 1;
while (start <= end) {
int middle = (start + end) / 2;
if (key < inputArr[middle]) {
end = middle - 1;
}
if (start > inputArr[middle]) {
start = middle + 1;
}
if (start == inputArr[middle]) {
return middle;
}
}
return -1;
}
// This function returns index of element x in arr[]
private static int search(int arr[],int x)
{
for (int i = 0; i < arr.length; i++) {
// Return the index of the element if the element
// is found
if (arr[i] == x)
return i;
}
// return -1 if the element is not found
return -1;
}
// Driver method to test above
public static void main(String args[])
{
int c, n, array[];
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements: ");
n = in.nextInt();
array = new int[n];
Random rand = new Random();
for (c = 0; c < n; c++)
{
array[c] = rand.nextInt(100);
}
System.out.println("Elements: ");
for (int i = 0; i < array.length; i++)
{
System.out.print(array[i] + " ");
}
Scanner sc = new Scanner(System.in);
System.out.println("Enter the element to be searched: ");
int k = sc.nextInt();
System.out.println("\nSelect type of search\n");
System.out.println("1. Binary search");
System.out.println("2. Sequential search");
int choice = in.nextInt();
int binarySearchResult = binarySearch(array, choice);
int sequentialSearchResult = search(array, choice);
switch(choice) {
case 1:
if (binarySearchResult == -1) {
System.out.println("\n" + k + " element not found");
}
else {
System.out.println("\n"+ k +" element found at position "+ binarySearchResult);
}
break;
case 2:
if (sequentialSearchResult == -1) {
System.out.println(sequentialSearchResult + "");
System.out.println("\n" + k + " element not found");
}
else {
System.out.println("\n" + k + " element found at position " + sequentialSearchResult);
}
break;
}
}
}
I'm suposing that this is some silly mistake, but can you please help me.