Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- package searchingtechniques;
- import java.util.Arrays;
- import java.util.Scanner;
- /**
- *
- * @author manth
- */
- public class SearchingTechniques {
- /**
- * @param args the command line arguments
- */
- static double input[];
- static int n;
- static String ALGO="BINARY SEARCH";
- public static void main(String[] args) {
- // TODO code application logic here
- Scanner sc=new Scanner(System.in);
- randinput();
- System.out.println(" INPUT IS ");
- Arrays.sort(input);
- display(input);
- System.out.println("Which value to find? ");
- double to_find=Double.parseDouble(sc.nextLine());
- System.out.println(" Search by which algorithm? \n1.LinearSearch\n2.BinarySearch");
- long startTime=0 ;
- int at_location=0;
- switch(sc.nextLine())
- {
- case "1":
- startTime= System.currentTimeMillis();
- at_location=linearsearch(input,to_find);
- break;
- case "2":
- startTime= System.currentTimeMillis();
- at_location=binarysearch(input,to_find);
- }
- long endTime=System.currentTimeMillis();
- System.out.println("\n\ntime elapsed in sorting is "+ (endTime-startTime)+" Milliseconds \n\n");
- System.out.println("The number "+to_find+" is at location "+ at_location+" using algorithm "+ALGO);
- }
- public static int binarysearch(double input[],double to_find)
- {
- int index=0;
- int left=0;
- int right=input.length-1;
- int mid=0;
- while(left<=right)
- {
- mid=(left+right)/2;
- if(to_find==input[mid])
- return mid+1;
- if(to_find<input[mid])
- right=mid-1;
- if(to_find>input[mid])
- left=mid+1;
- }
- return -1;
- }
- public static int linearsearch(double input[],double to_find)
- {
- int index=0;
- for(int i=0;i<input.length;i++)
- {
- if(input[i]==to_find)
- {
- return i+1;
- }
- }
- return -1;
- }
- public static void display(double [] input)
- {
- for(int i=0;i<input.length;i++)
- {
- System.out.println(input[i]+" ");
- }
- }
- public static void randinput()
- {
- Scanner sc=new Scanner(System.in);
- System.out.println(" BUBBLE SORT \n ENTER TOTAL NUMBERS TO SORT");
- try{
- n=Integer.parseInt(sc.nextLine());
- }catch(Exception e)
- {
- System.out.println(" Please Enter a valid integer "+e);
- }
- input=new double[n];
- for(int i=0;i<n;i++)
- {
- input[i]=Math.random()*1000;
- }
- }
- public static void input()
- {
- Scanner sc=new Scanner(System.in);
- System.out.println(" \n ENTER TOTAL NUMBERS TO SORT");
- try{
- n=Integer.parseInt(sc.nextLine());
- }catch(Exception e)
- {
- System.out.println(" Please Enter a valid integer "+e);
- }
- input=new double[n];
- for(int i=0;i<n;i++)
- {
- input[i]=sc.nextInt();
- }
- System.out.println(" INPUT RECORDED ");
- System.out.println(" Numbers are getting sorted by algorithm: "+ ALGO);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment