Review data structure: Sorting Algorithm (2) -- Bubble sorting, data structure bubbling
This review is Bubble sorting.
Bubble Sorting is also a kind of stable and inner sorting.
The basic idea of Bubble Sorting: Compare and adjust the two adjacent numbers from top to bottom based on the total number in the range that has not yet been sorted, so that the larger number will sink, A relatively small amount of data goes up. That is, when the numbers of two adjacent parties are compared and their sorting and sorting requirements are opposite, they are exchanged.
Insert sorting is faster than Bubble Sorting!
The above is a general Bubble Sorting Algorithm with the time complexity of O (n ^ 2). This method can only find one maximum or minimum value for a single sorting operation, which consumes too much time.
Improvement Method 1: we can let the forward and reverse bubble methods in each sort to get the maximum and minimum values at the same time, so that the number of sorted shards is reduced by half. This method is like an oscillating ball. If the maximum and minimum values have been selected at both ends, the sorting distance will be reduced during the next sorting, and the amplitude of the subsequent oscillation will be reduced, when the amplitude is 0, is it very similar to that of the oscillating ball? due to the existence of damping, the amplitude is continuously reduced until it is stopped.
Improvement Method 2: during each sorting process, the tag bit is used to record the last exchange position in each sorting. If the last exchange position is 0, the entire array is sorted. The idea of this improvement is to use the prior information of the previous sorting to reduce the number of sorting times.
Implementation Code:
# Include <iostream> using namespace std; void BubbleSort (int a [], int n) {for (int I = 0; I <n-1; I ++) {for (int j = 0; j <n-i-1; j ++) {if (a [j]> a [j + 1]) swap (a [j], a [j + 1]) ;}} void BubbleSort_2 (int a [], int n) {int low = 0; int high = n-1; int j; while (low