public static void main(String[] args) {數組
int[] a = { 5, 1, 10, 3, 8, 0 };ide
for (int i = 0; i < selectionSort(a).length; i++) {spa
System.out.println(selectionSort(a)[i]);排序
}it
System.out.println("-------------------------");io
for (int i = 0; i < bubbleSort(a).length; i++) {class
System.out.println(bubbleSort(a)[i]);select
}static
System.out.println("-------------------------");tab
int[] b = { 1, 6, 7, 8 };
System.out.println(bianrySearch(b, 6));
}
// 選擇排序(升序)
private static int[] selectionSort(int[] arr) {
if (arr != null) {
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] > arr[j]) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
return arr;
}
// 冒泡排序
private static int[] bubbleSort(int[] arr) {
if (arr != null) {
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - i - 1; j++) {
if (arr[j] < arr[j + 1]) {
int temp = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = temp;
}
}
}
}
return arr;
}
// 二分查找(數組必須是有序的)
private static int bianrySearch(int[] arr, int key) {
// 起始角標
int a = 0;
// 結束角標
int b = arr.length - 1;
int m = 0;
while (a <= b) {
int midx = (a + b) / 2;
m = arr[midx];
if (key > m) {
a = midx + 1;
} else if (key < m) {
b = midx - 1;
} else {
return midx;
}
}
return -1;
}