Guest User

Untitled

a guest
Oct 14th, 2025
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.11 KB | None | 0 0
  1. public static String BinarySearch(ArrayList<String> array, String input) {
  2.         //First part of making sure word is found no matter the capitalization.
  3.         String underput = input.toLowerCase();
  4.         int leftpos = 0;
  5.         int rightpos = array.size() - 1;
  6.         int middlepos = (leftpos + rightpos) / 2;
  7.         int tarpos = 0;
  8.         int count = 0;
  9.        
  10.         //While I found an easier way to do this using streams, I will use what I know to be fair.
  11.         int i = 0;
  12.         String word;
  13.         while(i < (array.size()-1)) {
  14.             word = array.get(i).toString().toLowerCase();
  15.             array.set(i, word);
  16.             i++;
  17.         }
  18.        
  19.         while(leftpos < rightpos || tarpos != middlepos) {
  20.             if(array.get(middlepos).compareTo(underput) == 0 ) {
  21.                 tarpos = middlepos;
  22.             }
  23.             else if(array.get(middlepos).compareTo(underput) < 0) {
  24.                 leftpos = middlepos + 1;
  25.             }
  26.             else if(array.get(middlepos).compareTo(underput) > 0) {
  27.                 rightpos = middlepos - 1;
  28.             }
  29.             count++;
  30.         }
  31.        
  32.         if(count == 1) {
  33.             return ("Word found at position " + tarpos + " in " + count + "cycle.");
  34.         }
  35.         else {
  36.             return ("Word found at position " + tarpos + " in " + count + "cycles.");
  37.         }
Advertisement
Add Comment
Please, Sign In to add comment