Java Arrays binary search an array via Arrays.binarySearch()

Introduction

To Binary search an array in Java

Arrays.binarySearch(array, -9);  

Full source

import java.util.Arrays;

public class Main {
  public static void main(String args[]) {
    // Allocate and initialize array. 
    int array[] = new int[10];  
    for(int i = 0; i < 10; i++)  
      array[i] = -3 * i;  /*from w w  w .j av  a 2s.c  o m*/
  
    Arrays.sort(array);  
    System.out.println("Original contents: "+Arrays.toString(array));  

    // Binary search for -9. 
    System.out.println("The value -9 is at location ");  
    int index = Arrays.binarySearch(array, -9);  
    
    System.out.print(index);  

  }
}



PreviousNext

Related