Saturday, 16 June 2012

Binary search program


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

Pass a HashMap from Angular Client to Spring boot API

This example is for the case where fileData is very huge and in json format   let map = new Map<string, string>()      map.set(this.ge...