Advertisement
BetinaUKTC

binary search

May 4th, 2020
1,454
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.13 KB | None | 0 0
  1. import javax.swing.*;
  2. import java.util.Scanner;
  3.  
  4. public class main {
  5.  
  6.     public static void main(String[] args) {
  7.         Scanner scan = new Scanner(System.in);
  8.         int search = scan.nextInt();
  9.         int[] arr = {1, 3, 2, 34, 12, 21};
  10.         sort(arr);
  11.         int least = 0;
  12.         int most = arr.length - 1;
  13.  
  14.         while (least <= most) {
  15.             int middle = (least + most) / 2;
  16.             if (arr[middle] == search) {
  17.                 System.out.print("Index is: " + middle);
  18.                 break;
  19.             }
  20.             if (search > arr[middle]) {
  21.                 least = middle + 1;
  22.             }
  23.             if (search < arr[middle]) {
  24.                 most = middle - 1;
  25.             }
  26.         }
  27.     }
  28.  
  29.     public static void sort(int[] arr) {
  30.         for (int i = 1; i <= arr.length; i++) {
  31.             for (int j = 0; j < arr.length - 1; j++) {
  32.                 if (arr[j] > arr[j + 1]) {
  33.                     int one = arr[j];
  34.                     int two = arr[j + 1];
  35.                     arr[j] = two;
  36.                     arr[j + 1] = one;
  37.                 }
  38.             }
  39.         }
  40.     }
  41.  
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement