Skip to content

Instantly share code, notes, and snippets.

@Jeffwan
Last active August 29, 2015 13:56
Show Gist options
  • Save Jeffwan/8836853 to your computer and use it in GitHub Desktop.
Save Jeffwan/8836853 to your computer and use it in GitHub Desktop.
DataStructure & Algorithms
public static int binarySearch(int[] A, int target){
if (A.length ==0 || A == null ) {
return -1;
}
int start = 0;
int end = A.length - 1;
int mid;
if (target == A[start]) {
return start;
}
if (target == A[end]) {
return end;
}
while(start + 1 < end) {
mid = start + (end - start) / 2;
System.out.println("Before" + start + " " + end + " " + mid );
if (target == A[mid]){
return mid;
} else if (target < A[mid]) {
end = mid;
} else if (target > A[mid]) {
start = mid;
}
System.out.println("After" + start + " " + end + " " + mid );
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment