《JAVA啃骨头》之 JavaSE 章节
算法:冒泡、选择、二分
冒泡排序:
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {9, 8, 10, 7, 6, 0, 11};
for(int i = arr.length-1; i > 0; i--){
for(int j = 0; j < i; j++){
if(arr[j] > arr[j+1]){
int temp;
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
count2++;
}
}
}
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
选择排序:
public class SelectSort {
public static void main(String[] args) {
int[] arr = {9, 8, 10, 7, 6, 0, 11};
for(int i = 0; i < arr.length - 1; i++){
int min = i;
for(int j = i+1; j < arr.length; j++){
count++;
if(arr[j] < arr[min]){
min = j;
}
}
if(min != i){
int temp;
temp = arr[min];
arr[min] = arr[i];
arr[i] = temp;
count2++;
}
}
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
二分法:
public class ArrayUtil {
public static void main(String[] args) {
int[] arr = {100,200,230,235,600,1000,2000,9999};
int index = binarySearch(arr, 200);
System.out.println(index == -1 ? "该元素不存在!" : "该元素下标" + index);
}
public static int binarySearch(int[] arr, int dest) {
int begin = 0;
int end = arr.length - 1;
while(begin <= end) {
int mid = (begin + end) / 2;
if (arr[mid] == dest) {
return mid;
} else if (arr[mid] < dest) {
begin = mid + 1;
} else {
end = mid - 1;
}
}
return -1;
}
}