Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static String BinarySearch(ArrayList<String> array, String input) {
- //First part of making sure word is found no matter the capitalization.
- String underput = input.toLowerCase();
- int leftpos = 0;
- int rightpos = array.size() - 1;
- int middlepos = (leftpos + rightpos) / 2;
- int tarpos = 0;
- int count = 0;
- //While I found an easier way to do this using streams, I will use what I know to be fair.
- int i = 0;
- String word;
- while(i < (array.size()-1)) {
- word = array.get(i).toString().toLowerCase();
- array.set(i, word);
- i++;
- }
- while(leftpos < rightpos || tarpos != middlepos) {
- if(array.get(middlepos).compareTo(underput) == 0 ) {
- tarpos = middlepos;
- }
- else if(array.get(middlepos).compareTo(underput) < 0) {
- leftpos = middlepos + 1;
- }
- else if(array.get(middlepos).compareTo(underput) > 0) {
- rightpos = middlepos - 1;
- }
- count++;
- }
- if(count == 1) {
- return ("Word found at position " + tarpos + " in " + count + "cycle.");
- }
- else {
- return ("Word found at position " + tarpos + " in " + count + "cycles.");
- }
Advertisement
Add Comment
Please, Sign In to add comment