zoukankan      html  css  js  c++  java
  • 冒泡排序与选择排序的联系

    冒泡排序与选择排序的联系

    冒泡排序的两种写法,第二种写法的变形,就是选择排序。并且第二种写法好理解些。

    第一种写法:

        public static void maoPai() {
            int[] arr = {13, 11, 15, -11, 99, -10, 0, 22};
            for (int i = 0; i < arr.length - 1; i++) {
                for (int j = 0; j < arr.length - (i + 1); j++) {
                    if (arr[j + 1] < arr[j]) {
                        int temp = arr[j];
                        arr[j] = arr[j + 1];
                        arr[j + 1] = temp;
                    }
                }
            }
    
            System.out.println(Arrays.toString(arr));
            //[-11, -10, 0, 11, 13, 15, 22, 99]
        }
    

    第二种写法:

        public static void maoPai() {
            int[] arr = {13, 11, 15, -11, 99, -10, 0, 22};
            for (int i = 0; i < arr.length - 1; i++) {
                for (int j = i+1; j < arr.length; j++) {
                    if (arr[j] < arr[i]) {
                        int temp = arr[j];
                        arr[j] = arr[i];
                        arr[i] = temp;
                    }
                }
            }
    
            System.out.println(Arrays.toString(arr));
            //[-11, -10, 0, 11, 13, 15, 22, 99]
        }
    

    选择排序

        public static void xuanPai() {
            int[] arr = {13, 11, 15, -11, 99, -10, 0, 22};
            for (int i = 0; i < arr.length - 1; i++) {
                int index = i;
                for (int j = i+1; j < arr.length; j++) {
                    if (arr[j] < arr[index]) {
                       index = j;
                    }
                }
    			//比完再交换
                int temp = arr[index];
                arr[index] = arr[i];
                arr[i] = temp;
            }
    
            System.out.println(Arrays.toString(arr));
        }
    






    备注:最近来手感,写了个类似Tomcat服务

    github地址:https://github.com/cnamep001/my_tomcat.git






  • 相关阅读:
    求一个字符串中连续出现次数最多的子串
    LintCode: Longest Common Substring
    LintCode: O(1) Check Power of 2
    LintCode: Fizz Buzz
    LintCode: 3 Sum
    LintCode: Two Sum
    LintCode: Sort Colors
    LintCode: Median of two Sorted Arrays
    LintCode: Search A 2d Matrix
    Lintcode: Sqrt(X)
  • 原文地址:https://www.cnblogs.com/k-class/p/13684410.html
Copyright © 2011-2022 走看看