Skip to content

Instantly share code, notes, and snippets.

@ivanursul
Last active March 31, 2016 15:37
Show Gist options
  • Save ivanursul/b1024e4f94dd64d394b37476acb1e8a7 to your computer and use it in GitHub Desktop.
Save ivanursul/b1024e4f94dd64d394b37476acb1e8a7 to your computer and use it in GitHub Desktop.
public static long getRightSibling(long[] arr, long nr) {
long startTime = System.nanoTime();
long result = 0;
if (nr > arr[arr.length - 1]) {
long stopTime = System.nanoTime();
long elapsedTime = stopTime - startTime;
System.out.println(elapsedTime);
return nr;
}
int index = Arrays.binarySearch(arr, nr);
if (index < 0) {
index = -index - 1;
}
long stopTime = System.nanoTime();
long elapsedTime = stopTime - startTime;
System.out.println(elapsedTime);
return arr[index];
}
public static long getRightSibling2(long[] arr, long nr) {
long startTime = System.nanoTime();
long result = 0;
if (nr > arr[arr.length - 1]) {
result = nr;
} else if (nr < arr[0]) {
result = arr[0];
} else {
for (int i = arr.length - 2; i >= 1; i--) {
if (arr[i] == nr) {
result = arr[i];
break;
} else if (arr[i] < nr) {
result = arr[i+1];
break;
} else if (arr[i] > nr && i > 1) {
continue;
}
}
}
long stopTime = System.nanoTime();
long elapsedTime = stopTime - startTime;
System.out.println(elapsedTime);
return result;
}
public static long getRightSibling2(List<Long> list, long nr) {
long startTime = System.nanoTime();
long result = 0;
if (nr > list.get(list.size() - 1)) {
result = nr;
} else if (nr < list.get(0)) {
result = list.get(0);
} else {
for (int i = list.size() - 2; i >= 1; i--) {
if (list.get(i) == nr) {
result = list.get(i);
break;
} else if (list.get(i) < nr) {
result = list.get(i + 1);
break;
} else if (list.get(i) > nr && i > 1) {
continue;
}
}
}
long stopTime = System.nanoTime();
long elapsedTime = stopTime - startTime;
System.out.println(elapsedTime);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment