Data structure: common sorting algorithm (1): bubble sorting (C++ implementation)

Common sorting of bubble sort

1. Basic idea:

In a set of numbers to be sorted, compare and adjust the two adjacent numbers from top to bottom for all numbers in the range that is not currently sorted, so that the larger number sinks, The little ones are going up.

2. Algorithm description:

① When two adjacent numbers are compared and found that their ordering is contrary to the ordering requirement, they are exchanged. Compare two adjacent numbers in turn, placing the decimal number in front and the large number in the back.

②First compare the first and second numbers, put the decimal number before, and put the big number after; then compare the second number and the third number, put the decimal number before and after the big number, and continue like this until the end of the comparison For two numbers, put the decimal number before the big number.

③Repeat the first round of steps until all sorts are completed

3. Examples:

Example 1:

(1) To sort the array: [10,1,35,61,89,36,55]

Insert picture description here

(2) The first time sequence:

The first sort: 10 and 1, 10 is greater than 1, exchange positions [1,10,35,61,89,36,55]

The second round of sorting: compare 10 and 35, 10 is less than 35, do not swap positions [1,10,35,61,89,36,55]

The third round of sorting: compare 35 and 61, 35 is less than 61, do not swap positions [1,10,35,61,89,36,55]

The fourth round of sorting: compare 61 and 89, 61 is less than 89, do not swap positions [1,10,35,61,89,36,55]

Fifth pass sorting: compare 89 and 36, 89 is greater than 36, exchange positions [1,10,35,61,36,89,55]

The sixth time sequence: compare 89 and 55, 89 is greater than 55, exchange positions [1,10,35,61,36,55,89]

A total of six comparisons were made in the first trip, and the sorted results: [1,10,35,61,36,55,89]

img

(3) The second time sequence:

The first sorting: 1 and 10 are compared, 1 is less than 10, and positions 1,10,35,61,36,55,89 are not exchanged

The second sort: 10 and 35 comparison, 10 is less than 35, do not swap positions 1,10,35,61,36,55,89

The third order: 35 and 61 comparison, 35 is less than 61, do not swap positions 1,10,35,61,36,55,89

The fourth order: compare 61 and 36, 61 is greater than 36, exchange positions 1,10,35,36,61,55,89

Fifth order: compare 61 and 55, 61 is greater than 55, exchange positions 1,10,35,36,55,61,89

A total of 5 comparisons were made in the second pass, and the sorted results: 1,10,35,36,55,61,89

(4) The third time sequence:

1 and 10 are compared, 1 is less than 10, and the positions are not exchanged 1,10,35,36,55,61,89

The second order: 10 and 35 comparison, 10 is less than 35, do not swap positions 1,10,35,36,55,61,89

The third order: 35 and 36 comparison, 35 is less than 36, do not exchange positions 1,10,35,36,55,61,89

The fourth order: compare 36 and 61, 36 is less than 61, do not swap positions 1,10,35,36,55,61,89

In the third round, a total of 4 comparisons were made, and the sorted results: 1,10,35,36,55,61,89

So far, the position is already in order.

C++ code implementation:

#include<iostream>
using namespace std;
 
void print(int arr[], int n)
{  
    for(int j= 0; j<n; j++)
	{  
           cout<<arr[j] <<"  ";  
        }  
    cout<<endl;  
}  
 
void BubbleSort(int arr[], int n)
{
    for (int i = 0; i < n - 1; i++)
	{
            for (int j = 0; j < n - i - 1; j++)
	        {
                    if (arr[j] > arr[j + 1]) 
			{
                            int temp = arr[j];
                            arr[j] = arr[j + 1];
                            arr[j + 1] = temp;
                        }
                 }
         }
}
 
int main()
{  
    int s[7] = {10,1,35,61,89,36,55};  
    cout<<"初始序列:";  
    print(s,7);  
    BubbleSort(s,7);  
    cout<<"排序结果:";  
    print(s,7);  
    system("pause"); 
} 

Example 2:

Sort array: [3,44,38,5,47,15,36,26,27,2,46,4,19,50,48]

Since the first example has already explained the process, the order of the second example is shown in the following dynamic diagram:

img

4. Algorithm analysis:

(1) It can be seen that: N numbers need to be sorted, a total of N-1 passes are sorted, and the number of sorts for each i pass is (Ni) times, so double loop statements can be used, the outer layer controls how many times the loop is, the inner layer Control the number of cycles per pass

(2) The advantage of bubble sorting: every time sorting is performed, there will be less comparison, because every time sorting is performed, a larger value will be found. As in the above example: after the first comparison, the last number must be the largest number. In the second time sorting, you only need to compare other numbers except the last number, and you can also find the largest number. The number of is ranked behind the number participating in the second round of comparison. In the third round of comparison, you only need to compare the other numbers except the last two numbers, and so on... That is to say, there is no comparison, every time Comparing less once per trip reduces the amount of algorithms to a certain extent.

(3) Time complexity

1. If our data is in positive order, we only need to take one trip to complete the sorting. The required number of comparisons C and the number of recorded moves M both reach the minimum, namely: Cmin=n-1; Mmin=0; Therefore, the best time complexity for bubble sorting is O(n).

2. If unfortunately our data is in reverse order, we need to sort by n-1 times. Each sorting requires ni comparisons (1≤i≤n-1), and each comparison must move the record three times to reach the exchange record position. In this case, the number of comparisons and moves reaches the maximum:

img

In summary: The total average time complexity of bubble sorting is: O (n 2), the time complexity has nothing to do with the data status. To sum up: the total average time complexity of bubble sorting is: O(n^2), and the time complexity has nothing to do with the data status.Fully on the said : take bubble discharge sequence of the total of the flat average time between re- heteroaryl degree is : O ( n-2),When inter complex hetero degree and the number of data -like conditions without clearance .

5. Summary:

  • Worst case: Bubbling sorting requires n-1 rounds of sorting cycles. In each round of sorting cycles, the sequence is not in positive order, so ni comparisons (1<=i<=n-1) are required in each round of sorting cycle. , That is, the outer loop is executed n-1 times, the inner loop is executed n times at most, and the inner loop is executed at least once. Since the inner loop execution times are linear, the inner loop is executed on average (n+1)/2 times, and the time complexity is calculated For ((n-1)(n+1))/2=(-1)/2, the time complexity is O(n2)

  • Best case: The array to be sorted is in positive order, and sorting can be completed in one round of scanning. At this time, the time complexity is only the time complexity of comparison, which is O(n)

  • Average time complexity: O (n 2) Average time complexity: O(n^2) When inter complex hetero degree level average case conditions : O ( n-2)

  • Space complexity is the memory space occupied by the temporary variable when exchanging elements. The optimal space complexity is that the starting element order is already arranged, then the space complexity is 0, and the worst space complexity is starting element reverse order sorting. , The space complexity is O(n), and the average space complexity is O(1)

Guess you like

Origin blog.csdn.net/qq_43801020/article/details/107937787