Created
January 13, 2018 07:17
-
-
Save gauravbansal74/31295df86388edf41ce7f2c6301bbde7 to your computer and use it in GitHub Desktop.
BinarySearchIndex
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
public class BinarySearchIndex { | |
public static int binarySearchIndex(int[] arr, int item) { | |
int length = arr.length; | |
int hi = length-1; | |
int lo = 0; | |
int mid; | |
while (lo <= hi) { | |
mid = (hi + lo)/2; | |
if (item > arr[mid]) { | |
lo = mid + 1; | |
} | |
else if (item < arr[mid]) { | |
hi = mid - 1; | |
} | |
else { | |
return mid; | |
} | |
} | |
return -1; | |
} | |
public static void main(String[] args) { | |
int[] arr = {1,2,3,4,5,6}; | |
System.out.println(binarySearchIndex(arr,2)); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment