new tasks

This commit is contained in:
Ingy döt Net 2013-04-09 00:46:50 -07:00
parent 2a4d27cea0
commit 80737d5a6a
1194 changed files with 15353 additions and 1 deletions

View file

@ -0,0 +1,21 @@
public static void main(String[] args){
int[] searchMe;
int someNumber;
...
int index = binarySearch(searchMe, someNumber, 0, searchMe.length);
System.out.println(someNumber + ((index == -1) ? " is not in the array" : (" is at index " + index)));
...
}
public static int binarySearch(int[] nums, int check, int lo, int hi){
if(hi < lo){
return -1; //impossible index for "not found"
}
int guess = (hi + lo) / 2;
if(nums[guess] > check){
return binarySearch(nums, check, lo, guess - 1);
}else if(nums[guess]<check){
return binarySearch(nums, check, guess + 1, hi);
}
return guess;
}

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);

View file

@ -0,0 +1,27 @@
...
//check will be the number we are looking for
//nums will be the array we are searching through
public static int binarySearch(int[] nums, int check){
int hi = nums.length - 1;
int lo = 0;
while(hi >= lo){
guess = lo + ((hi - lo) / 2);
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[] searchMe;
int someNumber;
...
int index = binarySearch(searchMe, someNumber);
System.out.println(someNumber + ((index == -1) ? " is not in the array" : (" is at index " + index)));
...
}