Currently working with java basics.While learning I’ve written the following code.
import java.util.*; class RemoveDuplicates{ public static void main(String[] args) { int[] arr = {1,2,3,1,5,2,3}; int[] out = {1,2,3,1,5,2,3}; for(int each : arr){ System.out.println("Element "+each+" at "+Arrays.binarySearch(out,each)); } } }
My expected output:
Element 1 at 3
Element 2 at 5
Element 3 at 6
Element 1 at 3
Element 5 at 4
Element 2 at 5
Element 3 at 6
My actual output:
Element 1 at 3
Element 2 at 5
Element 3 at 6
Element 1 at 3
Element 5 at -8
Element 2 at 5
Element 3 at 6
In my actual output at element 5 why I’m getting -8 from Arrays.binarySeach(out,each)
function?
Explain me this please.
Advertisement
Answer
Always remember for binary search to work you must sort the array.
Use can use Arrays.sort()
for sorting
import java.util.*; class RemoveDuplicates{ public static void main(String[] args) { int[] arr = {1, 2, 3, 1, 5, 2, 3}; int[] out = {1, 2, 3, 1, 5, 2, 3}; Arrays.sort(out); for(int each : arr) { System.out.println("Element "+each+" at "+Arrays.binarySearch(out,each)); } } }