Java 實(shí)例 - 數(shù)組排序及查找
以下實(shí)例演示了如何使用 sort () 和 binarySearch () 方法來對數(shù)組進(jìn)行排序及查找數(shù)組中的元素,我們定義了 printArray() 輸出結(jié)果:
/* author by w3cschool.cn 文件名:Main.java */ 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("Sorted array", array); int index = Arrays.binarySearch(array, 2); System.out.println("Found 2 @ " + index); } 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(); } }
以上代碼運(yùn)行輸出結(jié)果為:
Sorted array: [length: 10] -9, -7, -3, -2, 0, 2, 4, 5, 6, 8 Found 2 @ 5
更多建議: