Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.24 KB | None | 0 0
  1. package com.company;
  2.  
  3. import java.util.*;
  4.  
  5. public class Main {
  6.  
  7.     public static void main(String[] args) {
  8.     // write your code here
  9.         List<Integer> list = new ArrayList<>();
  10.         list.add(1);
  11.         list.add(5);
  12.         list.add(7);
  13.         list.add(12);
  14.         list.add(25);
  15.         list.add(30);
  16.         list.add(36);
  17.  
  18.  
  19.         Collections.sort(list);
  20.         System.out.println(binarySearch(list, 2, 0));
  21.         System.out.println(list);
  22.     }
  23.  
  24.     static int binarySearch(List<Integer> list, Integer element, Integer index){
  25.         if (list.isEmpty()){
  26.             return -1;
  27.         }
  28.         int listSizeIndex = list.size();
  29.         int listMiddleIndex = listSizeIndex / 2;
  30.         if (list.get(listMiddleIndex) == element){
  31.             return index + listMiddleIndex;
  32.         }
  33.         else if (list.get(listMiddleIndex) < element){
  34.             List<Integer> newList = new ArrayList<>(list.subList(listMiddleIndex + 1, listSizeIndex));
  35.             return binarySearch(newList, element, index + listMiddleIndex + 1);
  36.         }
  37.         else {
  38.             List<Integer> newList = new ArrayList<>(list.subList(0, listMiddleIndex));
  39.             return binarySearch(newList, element, index);
  40.         }
  41.     }
  42.  
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement