The eight sorts of bubble sorting (must learn sorting algorithm)

Sorting Algorithm

Bubble Sort

Simple selection sort

Direct insertion sort

Hill (shell) sort

Quick sort

Merge sort

Bubble Sort

Sorting principle

  1. Compare adjacent elements. If the previous element is larger than the next element, the positions of the two elements are swapped.
  2. Do the same for each pair of adjacent elements, from the first pair of elements at the beginning to the last pair of elements at the end. The element at the final position is the maximum.

Insert picture description here
Take the first bubbling as an example

Insert picture description here
Simply put, each bubble is to find the maximum value in the unsorted array and put it in the last position.

Java code

import java.util.Arrays;
//不要问我问什么用汉语拼音,因为不知道冒泡英语咋写,哈哈哈哈!
public class MaoPao {
    
    

    public static void sort(int[] a){
    
    
        //需要冒泡的次数
        for(int i = a.length-1 ; i>0 ;i--){
    
    
            //对未排序数组依次比较,并放在最后。
            for(int j = 0;j<i ; j++){
    
    
                if(a[j]>a[j+1]){
    
    
                    int temp = a[j];
                    a[j] = a[j+1];
                    a[j+1] = temp;
                }
            }
        }

    }

    public static void main(String[] args) {
    
    
        int[] a = {
    
    1,5,3,2,6,4,9,8,7};
        sort(a);
        System.out.println(Arrays.toString(a));
    }
}

Time complexity analysis of bubble sort

Bubble sort uses a double-layer for loop, in which the loop body of the inner loop is the code that actually completes the sorting. Therefore,
we analyze the time complexity of the bubble sort and mainly analyze the number of executions of the inner loop body.
In the worst case, that is, if the elements to be sorted are {6,5,4,3,2,1} reverse order, then:
the number of element comparisons is:
(N-1)+(N-2)+( N-3)+…+2+1=((N-1)+1) (N-1)/2=N^2/2-N/2;
The number of element exchanges is:
(N-1)+ (N-2)+(N-3)+…+2+1=((N-1)+1)
(N-1)/2=N^2/2-N/2; The
total number of executions is:
(N^2/2-N/2)+(N^2/2-N/2)=N^2-N;
According to the big-O derivation rule, keep the highest order term in the function then the final bubble sort time The complexity is O(N^2).

Guess you like

Origin blog.csdn.net/ren9436/article/details/108890004