Skip to content

Instantly share code, notes, and snippets.

@JorgeOlvera
Created March 13, 2014 06:08
Show Gist options
  • Save JorgeOlvera/9522653 to your computer and use it in GitHub Desktop.
Save JorgeOlvera/9522653 to your computer and use it in GitHub Desktop.
/* Modify the binarySearch method so that if the search key is not in the
array, it returns the largest index i for which a[i] is smaller than key (or -1 if
no such index exists).*/
import java.io.*;
import java.util.Scanner;
//For testing
public class modifiedBinary{
public static int binarySearch(int numbers[], int key) {
// Select highest and lowest indexes on the array
int mid, binaryMod;
int low = 0;
int high = numbers.length - 1;
// Continue searching while low is still smaller than high
while (low <= high) {
mid = (low + high) / 2; // Binary partition
if (key < number[mid]) {
high = mid - 1;
} else if (key > numbers[mid]) {
low = mid + 1;
} else {
if (mid != key){
binaryMod = largestIndex(int numbers[]; int key)
}
else{
return mid;
}
int test = mid
}
}
}
/* Modify the binarySearch method so that if the search key is not in the
array, it returns the largest index i for which a[i] is smaller than key (or -1 if
no such index exists).*/
int[] numbers = {1,4,3,5,10,6,7,9,8};
{0,3,6,8,12,15}
public static int largestIndex(int numbers[], int key){
// Select highest and lowest indexes on the array
int mid;
int low = 0;
int high = numbers.length - 1;
while (low <= high) {
mid = (low + high) / 2;
if (key < number[mid]) {
high = mid - 1;
} else if (key > numbers[mid]) {
low = mid + 1;
} else {
//nope
if (mid<key || key-mid > key - (mid-1)){
return mid;
}
else{
return -1;
}
}
//Find largest index
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment