Find the first value smaller than target value in sorted array

By | January 31, 2015
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.

  1. public class FindFirstSmallerInSortedArray {
  2.     public static void main(String[] args) {
  3.         // System.out.println((4>>1));
  4.         int[] arr = { 3, 4, 5, 6, 6, 6, 6, 6, 6, 6, 7, 8 };
  5.         int index = findIndexBS(arr, 3);
  6.         if (index == -1) {
  7.             System.out.println(“no exist”);
  8.         } else {
  9.             System.out.println(arr[index]);
  10.         }
  11.     }
  12.     /*
  13.      * Return the index in sorted array, which value in index is the first one smaller than value.
  14.      * Return -1 if the result is not found.
  15.      * It uses binary search.
  16.      * For example, arr = {1, 3, 4, 6, 7}, value = 5. It returns 2.
  17.      * arr = {1, 2, 5, 5, 5, 5, 6}, value = 5. It returns 1.
  18.      * arr = {2, 3, 4}, value = 5. Return 2.
  19.      * arr = {2, 3, 4}, value = 1. Return -1.
  20.      *
  21.      * @param, arr[]. arr is a sorted input array
  22.      * @param, value. The value which is firstly larger than result.
  23.      */
  24.     public static int findIndexBS(int[] arr, int value) {
  25.         if (arr == null || value <= arr[0]) {
  26.             return -1;
  27.         }
  28.         if(value > arr[arr.length – 1]){
  29.             return arr.length – 1;
  30.         }
  31.         return findIndexBSUtil(arr, 0, arr.length – 1, value);
  32.     }
  33.     public static int findIndexBSUtil(int[] arr, int start, int end, int value) {
  34.         if (start > end) {
  35.             return -1;
  36.         }
  37.         int mid = start + ((end – start) >> 1);
  38.         if (value > arr[mid] && value <= arr[mid + 1]) {
  39.             return mid;
  40.         }
  41.         if (arr[mid] >= value) {
  42.             return findIndexBSUtil(arr, start, mid – 1, value);
  43.         }
  44.         return findIndexBSUtil(arr, mid + 1, end, value);
  45.     }
  46. }