Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,29 @@
public class BinarySearchIterative {
public static int binarySearch(int[] nums, int check) {
int hi = nums.length - 1;
int lo = 0;
while (hi >= lo) {
int guess = (lo + hi) >>> 1; // from OpenJDK
if (nums[guess] > check) {
hi = guess - 1;
} else if (nums[guess] < check) {
lo = guess + 1;
} else {
return guess;
}
}
return -1;
}
public static void main(String[] args) {
int[] haystack = {1, 5, 6, 7, 8, 11};
int needle = 5;
int index = binarySearch(haystack, needle);
if (index == -1) {
System.out.println(needle + " is not in the array");
} else {
System.out.println(needle + " is at index " + index);
}
}
}

View file

@ -0,0 +1,28 @@
public class BinarySearchRecursive {
public static int binarySearch(int[] haystack, int needle, int lo, int hi) {
if (hi < lo) {
return -1;
}
int guess = (hi + lo) / 2;
if (haystack[guess] > needle) {
return binarySearch(haystack, needle, lo, guess - 1);
} else if (haystack[guess] < needle) {
return binarySearch(haystack, needle, guess + 1, hi);
}
return guess;
}
public static void main(String[] args) {
int[] haystack = {1, 5, 6, 7, 8, 11};
int needle = 5;
int index = binarySearch(haystack, needle, 0, haystack.length);
if (index == -1) {
System.out.println(needle + " is not in the array");
} else {
System.out.println(needle + " is at index " + index);
}
}
}

View file

@ -0,0 +1,8 @@
import java.util.Arrays;
int index = Arrays.binarySearch(array, thing);
int index = Arrays.binarySearch(array, startIndex, endIndex, thing);
// for objects, also optionally accepts an additional comparator argument:
int index = Arrays.binarySearch(array, thing, comparator);
int index = Arrays.binarySearch(array, startIndex, endIndex, thing, comparator);

View file

@ -0,0 +1,4 @@
import java.util.Collections;
int index = Collections.binarySearch(list, thing);
int index = Collections.binarySearch(list, thing, comparator);