Java Examples - Array Sorting and Element Search
The following example demonstrates how to use the sort() method to sort a Java array, and how to use the binarySearch() method to find elements in the array. Here we define the 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 array sorting result is", array);
int index = Arrays.binarySearch(array, 2);
System.out.println("Element 2 is at the" + index + "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.print(", ");
}
System.out.print(array[i]);
}
System.out.println();
}
}
The output of running the above code is:
数组排序结果为: [length: 10] -9, -7, -3, -2, 0, 2, 4, 5, 6, 8 元素 2 在第 5 个位置Other Extensions
Java Examples