So how can the values from 0 to 3 be returned?
If search = "aaaa"
the output will be 3
, since that's the position (index) returned by the method binarySearch
. Something similiar will happen if:
search = "aaa"
, output will be 2
search = "aa"
, output will be 1
search = "a"
, output will be 0
To understand this, try printing the elements of the array sa
:
System.out.println(sa[0]); // index 0
System.out.println(sa[1]); // index 1
System.out.println(sa[2]); // index 2
System.out.println(sa[3]); // index 3
Output:
a
aa
aaa
aaaa