package cn.itcast_05;
import java.util.Arrays;
/*
* Arrays:針對陣列進行操作的工具類。比如說排序和查詢。
* 1:public static String toString(int[] a) 把陣列轉成字串
* 2:public static void sort(int[] a) 對陣列進行排序
* 3:public static int binarySearch(int[] a,int key) 二分查詢
*/
public class ArraysDemo {
public static void main(String[] args) {
// 定義一個陣列
int[] arr = { 24, 69, 80, 57, 13 };
// public static String toString(int[] a) 把陣列轉成字串
System.out.println("排序前:" + Arrays.toString(arr));//排序前:[24, 69, 80, 57, 13]
// public static void sort(int[] a) 對陣列進行排序
Arrays.sort(arr);
System.out.println("排序後:" + Arrays.toString(arr));//排序後:[13, 24, 57, 69, 80]
// [13, 24, 57, 69, 80]
// public static int binarySearch(int[] a,int key) 二分查詢
System.out.println("binarySearch:" + Arrays.binarySearch(arr, 57)); //binarySearch:2
System.out.println("binarySearch:" + Arrays.binarySearch(arr, 577));//binarySearch:-6
}
}
public static String toString(int[] a)
public static void sort(int[] a) 底層是快速排序,比較麻煩,知道就可以了。有空看,有問題再問我
public static int binarySearch(int[] a,int key)
開發原則:
只要是物件,我們就要判斷該物件是否為null。否則會出現空指標異常。
看原始碼沒有其他技巧,一步一步地看,實在不行,把原始碼拷貝出去作為你的方法斷點
int[] arr = { 24, 69, 80, 57, 13 };
System.out.println("排序前:" + Arrays.toString(arr));
public static String toString(int[] a) {
//a -- arr -- { 24, 69, 80, 57, 13 }
if (a == null)
return "null"; //說明陣列物件不存在
int iMax = a.length - 1; //iMax=4;
if (iMax == -1)
return "[]"; //說明陣列存在,但是沒有元素。
StringBuilder b = new StringBuilder();
b.append('['); //"["
for (int i = 0; ; i++) {
b.append(a[i]); //"[24, 69, 80, 57, 13"
if (i == iMax)
return b.append(']').toString(); //"[24, 69, 80, 57, 13]"
b.append(", "); //"[24, 69, 80, 57, "
}
}
----------------------------------------------------------------------
int[] arr = {13, 24, 57, 69, 80};
System.out.println("binarySearch:" + Arrays.binarySearch(arr, 577));
public static int binarySearch(int[] a, int key) {
//a -- arr -- {13, 24, 57, 69, 80}
//key -- 577
return binarySearch0(a, 0, a.length, key);
}
private static int binarySearch0(int[] a, int fromIndex, int toIndex, int key) {
//a -- arr -- {13, 24, 57, 69, 80}
//fromIndex -- 0
//toIndex -- 5
//key -- 577
int low = fromIndex; //low=0
int high = toIndex - 1; //high=4
while (low <= high) {
int mid = (low + high) >>> 1; //mid=2,mid=3,mid=4
int midVal = a[mid]; //midVal=57,midVal=69,midVal=80
if (midVal < key)
low = mid + 1; //low=3,low=4,low=5
else if (midVal > key)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found.
}