冒泡排序优化算法
import java.util.Arrays;
public class Arithmetic {
public static void main(String[] args) {
int[] arr = {3, 1, 6 ,2, 9, 0, 7, 4, 8, 5 };
System.out.println(Arrays.toString(arr));
bubbleSort(arr);
System.out.println(Arrays.toString(arr));
}
public static void bubbleSort(int[] arr){
boolean flag = true;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]){
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
flag = false;
}
System.out.println("第" + i + "躺第" + j + "次" + Arrays.toString(arr));
}
if(flag){
System.out.println("冒泡优化,结束排序");
break;
}else{
flag = true;
}
}
}
}
二分法查找算法
import java.util.Arrays;
public class Query {
public static void main(String[] args) {
int[] arr = {30, 20, 50, 10, 80, 9, 7, 12, 100, 40, 8};
int index = findIndex(30, arr);
System.out.println(index);
}
public static int findIndex(int x, int[] arr) {
Arithmetic.bubbleSort(arr);
System.out.println(Arrays.toString(arr));
int start = 0;
int end = arr.length - 1;
while(start <= end){
int mid = (start + end)/ 2;
if(arr[mid] == x){
return mid;
}
if(arr[mid] > x){
end = mid - 1;
}
if(arr[mid] < x){
start = mid + 1;
}
}
return -1;
}
}