public static void main(String[] args) {

int[] a = { 5, 1, 10, 3, 8, 0 };

for (int i = 0; i < selectionSort(a).length; i++) {

System.out.println(selectionSort(a)[i]);

}

System.out.println("-------------------------");

for (int i = 0; i < bubbleSort(a).length; i++) {

System.out.println(bubbleSort(a)[i]);

}

System.out.println("-------------------------");

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;

}