Array Sorting and Binary Search

This topic discuss about array with sorting and unsorting with binary search.

With a origin sequent array number not in sequence, search result is unpredictable.

public static void main(String[] args) {
  int[] a = { 3 , 2 , 1, 7 , 6 , 9 };
  System.out.println(Arrays.binarySearch(a, 3)); // -4
  System.out.println(Arrays.binarySearch(a, 2)); // -4
  System.out.println(Arrays.binarySearch(a, 1)); // 2
  System.out.println(Arrays.binarySearch(a, 7)); // -6
  System.out.println(Arrays.binarySearch(a, 6)); // 4
  System.out.println(Arrays.binarySearch(a, 9)); // 5
  System.out.println(Arrays.binarySearch(a, 5)); // -4
}

With a origin sequent array number in sequence or sorted. Search result is predictable and showing negative value smaller than the negative of index where the position suppose to be.

public static void main(String[] args) {
  int[] number = { 1 ,3 , 5, 7, 9 };
  System.out.println(Arrays.binarySearch(number, 1)); // 0
  System.out.println(Arrays.binarySearch(number, 2)); // -2
  System.out.println(Arrays.binarySearch(number, 3)); // 1
  System.out.println(Arrays.binarySearch(number, 4)); // -3
  System.out.println(Arrays.binarySearch(number, 5)); // 2
  System.out.println(Arrays.binarySearch(number, 6)); // 4
}

Array Sorting and Binary Search

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.