Advertisement
binibiningtinamoran

NullsArray

Jun 1st, 2019
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.39 KB | None | 0 0
  1. // Count how many nulls are in an array using binary search
  2.  
  3. public class NullsArray {
  4.  
  5.     public static void main(String[] args) {
  6.         String[] stringArr = {"ant", null, null, "ball", null, null, null, "drive", null, null,
  7.                 "food"};
  8.         String[] stringArr2 = {"ant", "drive", null, "food"};
  9.  
  10.         for (int i = 0; i < stringArr.length; i++) {
  11.             System.out.println(stringArr[i]);
  12.         }
  13.  
  14.         System.out.println(binarySearchWithNulls(stringArr, "drive"));
  15.     }
  16.  
  17.     public static int binarySearchWithNulls(String[] words, String target) {
  18.         int first = 0;
  19.         int last = words.length-1;
  20.         while (first <= last) {
  21.             // skips nulls on either end of the list;
  22.             if (words[first] == null) first++;
  23.             else if (words[last] == null) last--;
  24.             else {
  25.                 int mid = (last + first)/2;
  26.                 // if mid is null, move mid index to the left
  27.                 while (words[mid] == null && mid >= first) {
  28.                     mid--;
  29.                 }
  30.                 if (words[mid].equals(target)) {
  31.                     return mid;
  32.                 } else if (words[mid].compareTo(target) > 0) {
  33.                     last = mid - 1;
  34.                 } else {
  35.                     first = (last + first)/2 + 1;
  36.                 }
  37.             }
  38.         }
  39.         return -1;
  40.     }
  41.  
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement