1.冒泡排序:
private static void bubbleSort(int[] arr) { for(int j=0;j<arr.length-1;j++){ //外层循环 控制排序的次数 for(int m=0;m<arr.length-1-j;m++){ //内层循环 控制每一趟排序多少次 if(arr[m]>arr[m+1]){ int temp = arr[m]; arr[m] = arr[m+1]; arr[m+1] = temp; } } } }
2.二分查找
二分查找算法分为循环查找和递归查找
01.循环查找
/** * * @param arr 数组 * @param x 查找值 * @return 查到的值 */ public static int binarySearch(int[] arr, int x) { int low= 0; int high = arr.length-1; while (low <= high){ int middle = (low+high)/2; if(x==arr[middle]){ return arr[middle]; }else if(x < arr[middle]){ high = middle - 1; }else if(x > arr[middle]){ low = middle + 1; } } return -1; }
02.递归查找
/** * 递归查找 * @param arr 数组 * @param key 需要查询的值 * @param start 开始上标 * @param end 开始下标 * @return 找到的值 */ public static int binarySearch(int[] arr,int key,int start,int end){ if(start>end||start<0){ return -1; }else{ int middle = (start+end)/2; if(key == arr[middle]){ return key; } if(key < arr[middle]){ return binarySearch(arr,key,start,middle-1); } if(key>arr[middle]){ return binarySearch(arr,key,middle+1,end); } return -1; } }
测试:
public static void main(String[] args) { int[] arr = { 6, 12, 33, 87, 90, 97, 108, 561 }; System.out.println("循环查找:" + binarySearch(arr, 87)); System.out.println("递归查找:"+binarySearch(arr,87,0,arr.length-1)); }
输出结果:
循环查找:87
递归查找:87
Process finished with exit code 0