java數組排序,二分查找

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;

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章