Skip to content

Instantly share code, notes, and snippets.

@psy901
Created February 5, 2020 10:04
Show Gist options
  • Save psy901/47a5cf701b2fb64e9f2d7b8c3b3caba8 to your computer and use it in GitHub Desktop.
Save psy901/47a5cf701b2fb64e9f2d7b8c3b3caba8 to your computer and use it in GitHub Desktop.
Basic binary search on a sorted list
// "static void main" must be defined in a public class.
public class Main {
public static void main(String[] args) {
int[] arr = {1,2,3,5,10,20,35,100};
int left = 0, right = arr.length - 1;
int target = 4;
while (left <= right) {
int mid = left + (right - left) / 2;
int num = arr[mid];
System.out.printf("L: %d M: %d R: %d\n", left, mid, right);
if (num == target) {
System.out.printf("Target %d exists!\n", target);
return;
} else if (num < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
System.out.printf("Target %d does not exists!\n", target);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment