3 minutes to learn bubble sort

Ideas:

  1. Two elements relatively large place to the right
  2. From the beginning in order compare two adjacent elements, the purpose is to find the largest element into the end, this element is no longer involved Compare
  3. The second still from scratch, the second largest element in the correct position
  4. Compare a total of len -1 times, as it has been determined the position len -1 elements, then the n-th is certainly the smallest that
  5. Comparison of the number of times i is len - i -1, and the next because every time a comparison element
  6. When the two elements are not switched, the sorting algorithm is stable
  7. Optimization: When a trip without any exchange, explained that it had ordered the

 

Sort of 2,5,1,6,9,3

Algorithm:

/**
 * 冒泡排序
 */
public class Solution {
    public static void bubbleSort(int[] array) {
        boolean swap;    // 优化
        for (int i = 0; i < array.length; i++) {
            swap = false;
            // i 从第 0 次开始,没一趟都会少比较一个元素
            // -1 表示比较次数少于元素个数
            for (int j = 0; j < array.length - i - 1; j++) {
                if (array[j] > array[j + 1]) {
                    int temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                    swap = true;
                }
            }
            if (swap = false) {
                break;
            }
        }
    }

    public static void main(String[] args) {
        int[] array = new int[]{2, 5, 1, 6, 9, 3};
        bubbleSort(array);
        for (int i : array) {
            System.out.print(i + " "); // 1 2 3 5 6 9 
        }
    }
}

 

 

 

Published 242 original articles · won praise 16 · views 50000 +

Guess you like

Origin blog.csdn.net/qq_29150765/article/details/105184752