冒泡排序优化算法

  1. import java.util.Arrays;
  2. public class Arithmetic {
  3. public static void main(String[] args) {
  4. int[] arr = {3, 1, 6 ,2, 9, 0, 7, 4, 8, 5 };
  5. System.out.println(Arrays.toString(arr));
  6. bubbleSort(arr);
  7. System.out.println(Arrays.toString(arr));
  8. }
  9. public static void bubbleSort(int[] arr){
  10. boolean flag = true;
  11. for (int i = 0; i < arr.length; i++) {
  12. for (int j = 0; j < arr.length - 1 - i; j++) {
  13. if (arr[j] > arr[j + 1]){
  14. int temp = arr[j];
  15. arr[j] = arr[j + 1];
  16. arr[j + 1] = temp;
  17. flag = false;
  18. }
  19. System.out.println("第" + i + "躺第" + j + "次" + Arrays.toString(arr));
  20. }
  21. if(flag){
  22. System.out.println("冒泡优化,结束排序");
  23. break;
  24. }else{
  25. flag = true;
  26. }
  27. }
  28. }
  29. }

二分法查找算法

  1. import java.util.Arrays;
  2. public class Query {
  3. public static void main(String[] args) {
  4. int[] arr = {30, 20, 50, 10, 80, 9, 7, 12, 100, 40, 8};
  5. int index = findIndex(30, arr);
  6. System.out.println(index);
  7. }
  8. public static int findIndex(int x, int[] arr) {
  9. Arithmetic.bubbleSort(arr);
  10. System.out.println(Arrays.toString(arr));
  11. int start = 0;
  12. int end = arr.length - 1;
  13. while(start <= end){
  14. int mid = (start + end)/ 2;
  15. if(arr[mid] == x){
  16. return mid;
  17. }
  18. if(arr[mid] > x){
  19. end = mid - 1;
  20. }
  21. if(arr[mid] < x){
  22. start = mid + 1;
  23. }
  24. }
  25. return -1;
  26. }
  27. }