Advertisement
Guest User

Untitled

a guest
May 27th, 2018
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. /*
  2. * To change this license header, choose License Headers in Project Properties.
  3. * To change this template file, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6. package javaapplication2;
  7.  
  8. import java.util.Scanner;
  9.  
  10. /**
  11. *
  12. * @author GDRVE
  13. */
  14. public class binary {
  15.  
  16. public static void main(String args[])
  17. {
  18. int c, first, last, middle, n, search, array[];
  19.  
  20. Scanner in = new Scanner(System.in);
  21. System.out.println("Enter number of elements");
  22. n = in.nextInt();
  23. array = new int[n];
  24.  
  25. System.out.println("Enter " + n + " integers");
  26.  
  27.  
  28. for (c = 0; c < n; c++)
  29. array[c] = in.nextInt();
  30.  
  31. System.out.println("Enter value to find");
  32. search = in.nextInt();
  33.  
  34. first = 0;
  35. last = n - 1;
  36. middle = (first + last)/2;
  37.  
  38. while( first <= last )
  39. {
  40. if ( array[middle] < search )
  41. first = middle + 1;
  42. else if ( array[middle] == search )
  43. {
  44. System.out.println(search + " found at location " + (middle + 1) + ".");
  45. break;
  46. }
  47. else
  48. last = middle - 1;
  49.  
  50. middle = (first + last)/2;
  51. }
  52. if ( first > last )
  53. System.out.println(search + " isn't present in the list.\n");
  54.  
  55. }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement