int start = 0;
int end = nums.length - 1;
int mid = -1;
while (start <= end) {
mid = (start + end) / 2;
if (nums[mid] == key) {
return mid;//已經查到返回!
} else if (nums[mid] > key) {
end = mid - 1;
} else if (nums[mid] < key) {
start = mid + 1;
}
}
return -1;
private static void swap(int[] a, int i, int j) {
a[i] ^= a[j];
a[j] ^= a[i];
a[i] ^= a[j];
}
int len = a.length;
for (int i = 2; i < len; i++) {
if (a[i - 1] > a[i]) {
a[0] = a[i];
a[i] = a[i - 1];
int j = 0;
for (j = i - 2; a[j] > a[0]; j--) {
a[j + 1] = a[j];
}
a[j + 1] = a[0];
}
}
}
public static void selectSort(int[] a) {
for (int i = 1; i < a.length; i++) {
int j = selectMinKey(a, i); //從i開始a.length中找到最小的位置
if (i != j) {
swap(a, i, j);
}
}
}
// 查找從i開始到a.length中最小的位置
private static int selectMinKey(int[] a, int i) {
int key = i;
for (int j = i + 1; j < a.length; j++) {
if (a[j] < a[key]) {
key = j;
}
}
return key;
}
public static void bubbleSort(int[] a) {
int len = a.length;
for (int i = 1; i < len - 1; i++) {
for (int j = i; j < len - i; j++) {
if (a[j + 1] < a[j]) {
swap(a, j + 1, j);
}
}
}
}
public static void quickSort(int[] a, int low, int high) {
//遞歸快速排序
int pivotLoc = 0;//中心點
if (low < high) {
pivotLoc = partitionLoc(a, low, high);
quickSort(a, low, pivotLoc-1);
quickSort(a, pivotLoc+1, high);
}
}
//獲取到a的下標 low ~ high 中, a[low]的應該放的位置, 即左邊的數 < a[low] 右邊的數 > a[low]
private static int partitionLoc(int[] a, int low, int high) {
a[0] = a[low];
while (low < high) {
while (low < high && a[high] >= a[0]) {
high--;
}
a[low] = a[high];
while (low < high && a[low] <= a[0]) {
low++;
}
a[high] = a[low];
}
a[low] = a[0];
return low;
}