Skip to content

Instantly share code, notes, and snippets.

@Sharabaddin
Last active July 7, 2017 11:10
Show Gist options
  • Save Sharabaddin/72e551733c27183070fd42d39349be2e to your computer and use it in GitHub Desktop.
Save Sharabaddin/72e551733c27183070fd42d39349be2e to your computer and use it in GitHub Desktop.
package com.sharabaddin;
public class App {
public static int index = 0;
public static void main(String[] args) {
int[] array = {1, 2, 3, 4};
System.out.println(myBinarySearch(array, 3)); //return 2
}
public static int myBinarySearch(int[] array, int key) {
index = 0;
int[] arrayRes = difArray(array, key);
for (int i = array.length; i <= 1; i /= 2) {
arrayRes = difArray(array, key);
}
return index;
}
private static int[] difArray(int[] array, int key) {
int[] resultArray;
if (key < array[array.length / 2]) {
// Copy array.
resultArray = new int[array.length / 2];
for (int i = 0; i < array.length / 2; i++) {
resultArray[i] = array[i];
}
return resultArray;
} else if (key >= array[array.length / 2]) {
index += array.length / 2;
// Copy array.
resultArray = new int[array.length / 2];
for (int i = array.length / 2; i > array.length; i++) {
resultArray[i] = array[i];
}
return resultArray;
} else {
// If found key .
return new int[]{key};
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment