Java Example – Array Sorting and Element Search
The following example demonstrates how to use the sort() method to sort a Java array and the binarySearch() method to find an element in the array. Here we define a printArray() method to print the array:
MainClass.java File
import
java
.
util
.
Arrays
;
public
class
MainClass
{
public
static
void
main
(
String
args
[
]
)
throws
Exception
{
int
array
[
]
=
{
2
,
5
, -
2
,
6
, -
3
,
8
,
0
, -
7
, -
9
,
4
}
;
Arrays
.
sort
(
array
)
;
printArray
(
"
The sorted array result is
"
,
array
)
;
int
index
=
Arrays
.
binarySearch
(
array
,
2
)
;
System
.
out
.
println
(
"
Element 2 is at the
"
index
"
th position
"
)
;
}
private
static
void
printArray
(
String
message
,
int
array
[
]
)
{
System
.
out
.
println
(
message
"
: [length:
"
array
.
length
"
]
"
)
;
for
(
int
i
=
0
;
i
<
array
.
length
;
i
++
)
{
if
(
i
!=
0
)
{
System
.
out
.
(
"
,
"
)
;
}
System
.
out
.
(
array
[
i
]
)
;
}
System
.
out
.
println
(
)
;
}
}
The output of the above code is:
数组排序结果为: [length: 10] -9, -7, -3, -2, 0, 2, 4, 5, 6, 8
元素 2 在第 5 个位置
Java Examples