Java eight sort of bubble sort algorithm

First, the moving map presentation

Second, the idea of ​​analysis

1. pairwise adjacent two numbers, n [i] with n [j + 1] ratio, if n [i]> n [j + 1], then exchanged even number,

2. j ++, repeat the above steps, after the end of the first trip, the maximum number will be determined in the last one, which is also known as bubble sort large (small) number sink to the bottom,

3. i ++, repeat the above steps until i = n-1 ends, the sort is complete.

Third, the negative heteroaryl analysis

1. Regardless of whether the original array orderly and time complexity is O (n2),

Because no one should compare the number with a number of other, (n-1) 2 times, decomposition: n2 + 2n-1, and remove the low constant power, n2 remaining, so the final time complexity is n2

2. The space complexity is O (1), because only a defined auxiliary variable, regardless of the size of n, the spatial complexity is O (1)

Fourth, compare and choose Sort Bubble Sort

1. Time is responsible for the degree of O (n2)

2. The space complexity is O (1)

3. Select the sort is determined from the start of the first maximum or minimum number, to ensure that the number of front are orderly and relatively small or large number of back,

  Bubble sort is to determine the maximum or minimum number from the last start, ensure that the number of the latter are ordered and are larger or smaller than the previous number.

import java.util.Arrays;
public class 冒泡 {
    public static void main(String[] args) {
        int[] n = new int[]{1,6,3,8,33,27,66,9,7,88};
        int temp;
        for (int i = 0; i < n.length-1; i++) {
            for (int j = 0; j <n.length-1; j++) {
                if(n[j]>n[j+1]){
                    temp = n[j];
                    n[j] = n[j+1];
                    n[j+1] = temp;
                }
            }
        }
        System.out.println(Arrays.toString(n));
    }
}

Guess you like

Origin www.linuxidc.com/Linux/2019-08/159807.htm