1、二分查找
//循环
public static int bianrySearch(int[] temp, int target) { int mid, low, high; high = temp.length-1; low = 0; while (low <= high) { mid = (high + low) / 2; if (temp[mid] == target) { System.out.println(mid); break; } else if (temp[mid] < target) { low = mid + 1; } else { high = mid - 1; } } return -1; } //递归 public static int bianrySearch1(int[] temp, int target, int low, int high) { int mid = (high + low) / 2; if (temp[mid] == target) { System.out.println(mid); } else if (temp[mid] < target) { low = mid + 1; bianrySearch1(temp, target, low, high); } else { high = mid - 1; bianrySearch1(temp, target, low, high); } return -1; }
2、快排
private static void quick(int[] arr, int low, int high) { if (low < high) { int index = getIndex1(arr, low, high); quick(arr, low, index - 1); quick(arr, index + 1, high); } } private static int getIndex1(int[] arr, int low, int high) { int tam = arr[low]; while (low < high) { while (low < high && tam <= arr[high]) { high--; } arr[low] = arr[high]; while (low < high && tam >= arr[low]) { low++; } arr[high] = arr[low]; } arr[low] = tam; return low; }
3、插入排序
private static void insertSort(int[] arr) { int preindex, tam, i; for (i = 1; i < arr.length; i++) { tam = arr[i]; preindex = i - 1; while (preindex >= 0 && tam < arr[preindex]) { arr[preindex + 1] = arr[preindex]; preindex--; } arr[preindex + 1] = tam; } }