這篇我們來復習下針對數組常用的一些方法。
1、優(yōu)化過的快速排序法
int[] array = {11,12,232,32,23,18,34};
Arrays.sort(array);// 升序
System.out.println(Arrays.toString(array)); // [11, 12, 18, 23, 32, 34, 232]
對數組中的元素,從第幾個到第幾個進行排序
int[] array = {7, 18, 32, 3, 12, 10, 6, 3, 5};
// 對數組中的元素,從第3個到第7個進行排序
Arrays.sort(array, 2, 7);
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
// result=[7, 18, 3, 6, 10, 12, 32, 3, 5]
從結果我們可以看到是這樣的一個區(qū)間"[...)",包括索引是2的元素,不包括索引是7的元素
2、二分查找法,返回元素在數組中的索引
int[] array = {11, 12, 32, 34, 28, 29, 100};
int index = Arrays.binarySearch(array, 32);
System.out.println("index = " + index); // result=2
若是查找不到,則返回(-插入點-1)
int[] array = {11, 12, 32, 34, 28, 29, 100};
int index = Arrays.binarySearch(array, 23);
System.out.println("index = " + index); // result=-3 (-3 = -2 - 1)
3、System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length);
int[] src = {1, 2, 3, 4, 5};
int[] dest = {18, 27};
// 第一個參數:原數組
// 第二個參數:從原數組的第幾個元素開始取
// 第三個參數:目標數組
// 第四個參數:將從原數組中取到的第一個元素,存入目標數組的第幾個元素
// 第五個參數:從原數組取幾個數據,這個值的大小要小于等于目標數組的大小
System.arraycopy(src, 1, dest, 0, 2); // result=[2, 3]
for (int i = 0; i < dest.length; i++) {
System.out.println(dest[i]);
}
注意: 第五個參數,這個值要是大于目標數組的大小,就會報如下錯誤
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
at java.lang.System.arraycopy(Native Method)
at com.miliyo.test.Main.main(Main.java:25)
4、比較兩個數組中的元素是否完全一致
int[] array1 = {7, 18, 32, 3, 12, 10, 6, 3, 5};
int[] array2 = {7, 18, 32, 3, 12, 10, 6, 3, 5};
boolean result = Arrays.equals(array1, array2);
System.out.println("result = " + result); // result = true