Binary search program
import java.util.Arrays;
import java.util.Scanner;
public class ArrayList {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter howmany numbers are in in the array ");
int n = sc.nextInt();
int[] arr = new int[n];
int key = 0;
System.out.println("Enter "+n+" numbers");
for (int i = 0; i < arr.length; i++)
{
arr[i] = sc.nextInt();
}
System.out.print("Enter any number to search in array using binary search ");
key =sc.nextInt();
System.out.print("Given List of Numbers : ");
for (int i=0;i<=arr.length-1;i++) System.out.print(arr[i] + " ");
System.out.println(" ");
Arrays.sort(arr);
System.out.print("List of Numbers after Sort ");
for (int i=0;i<=arr.length-1;i++) System.out.print(arr[i] +" ");
System.out.println(" ");
int pos=binsearch(key,arr);
if (pos==-1) System.out.println("Given Number " + key + " Not Found"); else System.out.println("Given Number " + key + " Found at Position "+ (pos+1));
}
//Binary Search algorithm
public static int binsearch(int searchValue, int[] searchList) {
int high = searchList.length - 1;
int low=0;
while (low<=high)
{
int mid = (low + high ) / 2;
if ( searchValue > searchList[mid]) low = mid + 1;
else if (searchValue < searchList[mid]) high = mid - 1;
else return mid;
}
return -1;
}
}
No comments:
Post a Comment