Please click on ads

Please click on ads

Wednesday, 6 January 2021

Binary in java

 import java.util.Scanner;public class Test1 {public static void main(String[] args){ //searching linear 7 3 5 11 1 9 2 8 6 4 Binarysearch n d e//1 2 3 4 5 6 7 8 9 11Scanner s = new Scanner(System.in); int a[]= new int[10];System.out.print("enter the elements ofarray");for (int i=0; i<a.length;i++){a[i]=s.nextInt(); }System.out.print("enter the elements tosearch");int search=s.nextInt();int first=0; int last=a.length-1; //10-1=9 1 2 3 4 int mid = (first + last)/2; //4 while( first <= last ){ //0<=3 if ( a[mid] < search ){ //a[2]<search 3<3 first = mid + 1; //5 last 9//2 } else if ( a[mid] == search ){ //5==3 System.out.println("Element is found at index: "+ mid); break; } else { last = mid - 1; } mid = (first + last)/2; } if ( first > last ){ System.out.println("Element is not found!"); } }}

No comments:

Post a Comment