tampurus

23 linear and binary search

Apr 25th, 2022 (edited)
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.56 KB | None | 0 0
  1. // Q23 linear search
  2. import java.util.*;
  3. public class Main
  4. {
  5.     public static void main(String[] args) {
  6.         Scanner sc= new Scanner(System.in);
  7.         int[] arr = {1,2,3,4,5,6,7,9};
  8.         System.out.println("Enter the number");
  9.         int n = sc.nextInt(),check=0;
  10.         for(int i=0 ; i<8 ; i++){
  11.             if(arr[i]==n){
  12.                 check=1;
  13.                 break;
  14.             }
  15.         }
  16.         if(check==1){
  17.             System.out.println("Number found");  
  18.         }
  19.         else{
  20.             System.out.println("Not found");
  21.         }
  22.     }
  23. }
  24. /*
  25. Enter the number 0
  26. Not found
  27. */
  28.  
  29. Q 24 Binary search
  30. // Q21 Maximum element of array
  31. import java.util.*;
  32. public class Main
  33. {
  34.     static boolean Binary_Search(int arr[] , int find , int n)
  35.     {
  36.  
  37.         int low = 0 , high = n-1 , mid = (high + low) / 2, check=0;
  38.  
  39.         while(low<=high){
  40.      
  41.             if(arr[mid] == find){
  42.                 return true;
  43.             }
  44.             else if(find > arr[mid]){
  45.                 low = mid + 1;
  46.             }
  47.             else{
  48.                 high = mid - 1;
  49.             }
  50.             mid = (high + low) /2;
  51.         }
  52.         return false;
  53.     }
  54.     public static void main(String[] args) {
  55.         Scanner sc= new Scanner(System.in);
  56.         int[] arr = {1,2,3,4,5,6,7,9};
  57.         System.out.println("Enter the number");
  58.         int n = sc.nextInt();
  59.         if( Binary_Search(arr,n,8) ){
  60.             System.out.println("Number found");  
  61.         }
  62.         else{
  63.             System.out.println("Not found");
  64.         }
  65.     }  
  66. }
  67. /*
  68. Enter the number 3
  69. Number found
  70. */
Add Comment
Please, Sign In to add comment