Java Reference
In-Depth Information
the point at which
key
would be inserted into the array (the index of the first
element greater than
key
, or
a.length
if all elements in the array are less
than
key
)andguaranteesthatthereturnvaluewillbegreaterthanorequalto
0ifandonlyif
key
isfound.Forexample,
Arrays.binarySearch(new
String[] {"Robin", "Oriole", "Bluejay"}, "Oriole")
re-
turns 1,
"Oriole"
's index.
•
static void fill(char[] a, char ch)
stores
ch
ineachelement
ofthespecifiedcharacterarray.Forexample,
Arrays.fill(screen[i],
' ');
fills the
i
th row of a 2D
screen
array with spaces.
•
static void sort(long[] a)
sortstheelementsinlongintegerarray
a
into ascending numerical order; for example,
long lArray = new
long[] { 20000L, 89L, 66L, 33L}; Arrays.sort(lArray);
.
•
static <T> void sort(T[] a, Comparator<? super T> c)
sorts the elements in array
a
using comparator
c
to order them. For example,
when given
Comparator<String> cmp = new Comparator-
<String>() { public int compare(String e1, String
e2) { return e2.compareTo(e1); } }; String[] in-
nerPlanets = { "Mercury", "Venus", "Earth", "Mars"
};
,
Arrays.sort(innerPlanets, cmp);
uses
cmp
tohelpinsorting
innerPlanets
into descending order of its elements:
Venus
,
Mercury
,
Mars
,
Earth
is the result.
Therearetwocommonalgorithmsforsearchinganarrayforaspecificelement.
Lin-
ear search
searches the array element by element from index 0 to the index of the
searched-forelementortheendofthearray.Onaverage,halfoftheelementsmustbe
searched;largerarraystakelongertosearch.However,thearraysdonotneedtobesor-
ted.
Incontrast,
binary search
searchesorderedarray
a
's
n
itemsforelement
e
inamuch
faster amount of time. It works by recursively performing the following steps:
1. Set low index to 0.
2. Set high index to n-1.
3. If low index > high index, then Print “Unable to find ” e. End.
4. Set middle index to (low index+high index)/2.
5. If e > a[middle index], then set low index to middle index+1. Go to 3.
6. If e < a[middle index], then set high index to middle index-1. Go to 3.
7. Print “Found ” e “ at index ” middle index.