java - binarySearch function error -


this question has answer here:

import java.lang.*; import java.util.*; public class anotherarraypractice{ public static void main (string[] args){   int [] arr={130,10};   system.out.println(arr[1]);   system.out.println(arrays.binarysearch(arr,10));   system.out.println(arrays.binarysearch(arr,130));    } } 

the print result follow: 10, -1, 0. confused why binarysearch(arr,10) gives me -1 while in fact 10 inside array

as can read documentation:

the java.util.arrays.binarysearch(int[] a, int key) method searches specified array of ints specified value using binary search algorithm.the array must sorted before making call.if not sorted, results undefined.

so must order array before!

instead if use not sorted, results undefined.


Comments