Java Arrays 二分查找 Super 索引


Java Arrays 二分查找 Super 索引

package com.codingdict;

import java.util.Arrays;
import java.util.Comparator;

public class ArrayDemo {

   public static void main(String[] args) {

      // initializing unsorted short array
      Short shortArr[] = new Short[]{5, 2, 15, 52, 10};

      // use comparator as null, sorting as natural ordering
      Comparator<Short> comp = null;

      // sorting array
      Arrays.sort(shortArr, comp);

      // let us print all the elements available in list
      System.out.println("The sorted short array is:");
      for (short number : shortArr) {
         System.out.println("Number = " + number);
      }

      // entering the value to be searched
      short searchVal = 15;

      // search between index 1 and 4
      int retVal = Arrays.binarySearch(shortArr, 1, 4, searchVal, comp);
      System.out.println("The index of element 15 is : " + retVal);

      // search between index 0 and 3, where searchVal doesn't exist
      retVal = Arrays.binarySearch(shortArr, 0, 3, searchVal, comp);
      System.out.println("The index of element 15 is : " + retVal);
   }
}