Share the joy
This is a practice for binary search. The aim is to find the first element in an sorted array, which is smaller than a target value.
For example:
arr = {1, 3, 4, 6, 7}, value = 5. Returns 2.
arr = {1, 2, 5, 5, 5, 5, 6}, value = 5. Returns 1.
arr = {2, 3, 4}, value = 5. Return 2.
arr = {2, 3, 4}, value = 1. Return -1.
- public class FindFirstSmallerInSortedArray {
- public static void main(String[] args) {
- // System.out.println((4>>1));
- int[] arr = { 3, 4, 5, 6, 6, 6, 6, 6, 6, 6, 7, 8 };
- int index = findIndexBS(arr, 3);
- if (index == -1) {
- System.out.println(“no exist”);
- } else {
- System.out.println(arr[index]);
- }
- }
- /*
- * Return the index in sorted array, which value in index is the first one smaller than value.
- * Return -1 if the result is not found.
- * It uses binary search.
- * For example, arr = {1, 3, 4, 6, 7}, value = 5. It returns 2.
- * arr = {1, 2, 5, 5, 5, 5, 6}, value = 5. It returns 1.
- * arr = {2, 3, 4}, value = 5. Return 2.
- * arr = {2, 3, 4}, value = 1. Return -1.
- *
- * @param, arr[]. arr is a sorted input array
- * @param, value. The value which is firstly larger than result.
- */
- public static int findIndexBS(int[] arr, int value) {
- if (arr == null || value <= arr[0]) {
- return -1;
- }
- if(value > arr[arr.length – 1]){
- return arr.length – 1;
- }
- return findIndexBSUtil(arr, 0, arr.length – 1, value);
- }
- public static int findIndexBSUtil(int[] arr, int start, int end, int value) {
- if (start > end) {
- return -1;
- }
- int mid = start + ((end – start) >> 1);
- if (value > arr[mid] && value <= arr[mid + 1]) {
- return mid;
- }
- if (arr[mid] >= value) {
- return findIndexBSUtil(arr, start, mid – 1, value);
- }
- return findIndexBSUtil(arr, mid + 1, end, value);
- }
- }