Eight major sorts of data structures - bubble sort


Table of contents

1. Sorting process

Two, the code

3. Performance and stability analysis

1. Space complexity

2. Time complexity

3. Stability


1. Sorting process

Compare the values ​​of adjacent elements in pairs from back to front (front to back). If the front element is greater than the back element, exchange their positions (ascending order).

If the result needs to be in descending order , they are exchanged when the preceding element is smaller than the following element.

Until the sequences are compared, this is called the first pass sorting. The result is that the position of the smallest element (the first position) is determined, and the elements whose positions have been determined during the next sorting do not need to be compared. The whole process slowly floats up like a bubble.

Bubble Sort

Two, the code

package sort;

public class BubboSort {
    public static void main(String[] args) {
        int[] arr = {3, 6, 4, 1, 9, 6, 5, 8, 7, 2};
        System.out.print("排序前为:");
        for (int i : arr) {
            System.out.print(i + " ");
        }
        System.out.println();
        bubbosort(arr);
        System.out.print("排序后为:");
        for (int i : arr) {
            System.out.print(i + " ");
        }
    }

    public static void bubbosort(int[] arr) {
        int temp = 0;
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }
}

The first sorting process:

result:

 

3. Performance and stability analysis

1. Space complexity

Because the entire process of sorting is only operated in the current array, no other empty array is used, and only Changshu auxiliary units are used, so the space complexity is O(1) .

2. Time complexity

  • Best case: when the initial sequence is sorted, only one comparison is required, so the time complexity is O(n).
  • Worst case: When the initial sequence and the result sequence are in reverse order, n-1 sorting is required, and the i-th sorting requires ni keyword comparisons. The time complexity is O( n^{2})

So the average time complexity of bubble sort is O( n^{2}). 

3. Stability

From the analysis of the first pass of bubble sorting in the figure above, the black 6 starts at the front and the red 6 is behind, and after the sorting, the black 6 is still in front of the red 6, so the bubble sort is a stable sort .


Guess you like

Origin blog.csdn.net/weixin_55166132/article/details/125838621