Created
September 6, 2016 09:46
-
-
Save dfparker2002/02f858f2d4e6aaf9967d22a584affb7a to your computer and use it in GitHub Desktop.
Binary Search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class BinarySearch { | |
// Find first target in array | |
public int binarySearch(int[] arr, int target){ | |
if (arr.length == 0){ | |
return -1; | |
} | |
int start = 0 ; | |
int end = arr.length - 1; | |
int mid; | |
while (start + 1 < end){ | |
mid = start + (end - start) / 2; | |
if (arr[mid] < target){ | |
start = mid; | |
}else{ | |
end = mid; | |
} | |
} | |
if (arr[start] == target){ | |
return start; | |
} | |
if (arr[end] == target){ | |
return end; | |
} | |
return -1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment