Skip to content

Instantly share code, notes, and snippets.

@svpino
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save svpino/328f528e9c3ad1715b63 to your computer and use it in GitHub Desktop.
Save svpino/328f528e9c3ad1715b63 to your computer and use it in GitHub Desktop.
Programming challenge: the position of the element
// Programming challenge: the position of the element
// Original post: https://blog.svpino.com/2015/05/24/programming-challenge-the-position-of-the-element
public class Main {
private static int[] array = { 1, 3, 5, 6 };
// Solution using a sequential search - O(n)
private static int sequential(int target) {
if (target < array[0]) {
return 0;
}
if (target > array[array.length - 1]) {
return array.length;
}
for (int i = 0; i < array.length; i++) {
if (array[i] >= target) {
return i;
}
}
return 0;
}
// Solution using a binary search - O(log n)
private static int binary(int target) {
int left = 0;
int right = array.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (target < array[mid]) {
right = mid - 1;
}
else if (target > array[mid]) {
left = mid + 1;
}
else {
return mid;
}
}
return left;
}
public static void main(String[] args) {
String format = "* Target %d should return %d [%s]";
System.out.println("Using a sequential search solution:");
System.out.println(String.format(format, 0, 0, sequential(0) == 0));
System.out.println(String.format(format, 1, 0, sequential(1) == 0));
System.out.println(String.format(format, 2, 1, sequential(2) == 1));
System.out.println(String.format(format, 3, 1, sequential(3) == 1));
System.out.println(String.format(format, 4, 2, sequential(4) == 2));
System.out.println(String.format(format, 5, 2, sequential(5) == 2));
System.out.println(String.format(format, 6, 3, sequential(6) == 3));
System.out.println(String.format(format, 7, 4, sequential(7) == 4));
System.out.println("\r\nUsing a binary search solution:");
System.out.println(String.format(format, 0, 0, binary(0) == 0));
System.out.println(String.format(format, 1, 0, binary(1) == 0));
System.out.println(String.format(format, 2, 1, binary(2) == 1));
System.out.println(String.format(format, 3, 1, binary(3) == 1));
System.out.println(String.format(format, 4, 2, binary(4) == 2));
System.out.println(String.format(format, 5, 2, binary(5) == 2));
System.out.println(String.format(format, 6, 3, binary(6) == 3));
System.out.println(String.format(format, 7, 4, binary(7) == 4));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment