Bubble sorting and its time and space complexity analysis

1. Bubble sort

1. Concept and idea : Repeatedly visit the sequence to be sorted, compare two elements at a time, and exchange them if their order is wrong. The work of visiting the sequence is repeated until there is no need to exchange, that is to say, the sequence has been sorted. The name of this algorithm comes from the fact that larger elements will slowly "float" to the top of the sequence through exchange, so it is called "bubble sort".
2. Code implementation :

#include<iostream>
using namespace std;
void BubbleSort(int *a, int size)
{
    
    
 for (int i = 0; i < size; i++)//外循环,循环每个元素
 {
    
    
  for (int j = 1; j < size - i; j++)//内循环进行元素的两两比较
  {
    
    
   if (a[j] < a[j - 1])//判断相邻元素并进行交换
   {
    
    
    int temp = a[j];
    a[j] = a[j - 1];
    a[j - 1] = temp;
   }
  }
 }
}
int main()
{
    
    
 int a[10] = {
    
     2, 7, 34, 54, 12, 5, 19, 33, 88, 23 };
 cout << "原来的数组为:" << endl;
 for (int i = 0; i < 10; i++)
 {
    
    
  cout << a[i] << " ";
 }
 cout << endl;
 BubbleSort(a, 10);
 cout << "冒泡排序后的数组为:" << endl;
 for (int i = 0; i < 10; i++)
 {
    
    
  cout << a[i] << " ";
 }
 return 0;
}

The result of the operation is:insert image description here

Time complexity : the time overhead of the outer loop and inner loop, as well as judging and exchanging elements.
The optimal situation is that the order has been sorted at the beginning, then there is no need to exchange elements. Since the outer loop is n, the number of loop comparisons required by the inner loop is (n-1), (n-2)... 1 The time cost of summing the arithmetic series is: [ n(n-1) ] / 2; so the optimal time complexity is: O( n^2 ).
The worst case is that the elements are in reverse order at the beginning, then two elements must be exchanged for each sorting, and the time spent is: [ 3n(n-1) ] / 2; (the best case above The time spent is the three steps of exchanging elements); so the time complexity in the worst case is: O( n^2 ); space complexity: the auxiliary variable space of the
bubble sort is only a temporary variable, and It will not change with the expansion of the sorting scale, so the space complexity is O(1).

Guess you like

Origin blog.csdn.net/Wu_0526/article/details/107932941