[Sorting Algorithm] Bubble Sort

Reference: "Comic Algorithm - Xiao Hui's Algorithmic Journey"

Table of contents

Reference: "Comic Algorithm - Xiao Hui's Algorithmic Journey"

1. The idea of ​​bubble sorting

2. Examples

3. Time complexity

4. Code


1. The idea of ​​bubble sorting

(Assuming that an unordered array is sorted from small to large)

Compare adjacent elements two by two. When an element is greater than the adjacent element on the right, their positions are exchanged; when an element is less than or equal to the adjacent element on the right, the position remains unchanged.

2. Examples

The unordered sequence {5, 8, 6, 3, 9, 2, 1, 7} is sorted in ascending order.

process:

first round:

 second round:

The steps of the subsequent rounds of exchange are omitted.

3. Time complexity

Bubble sort is a stable sort, elements with equal value will not disturb the original order. Since each round of the sorting algorithm traverses all elements and traverses (number of elements - 1) rounds in total, the average time complexity is O(n^2).

4. Code

void bubbleSort(vector<int>& a,int n){
     for (int i = 0; i<n;++i){
         for (int j = 0; j < n - i - 1; ++j) {
             if (a[j] > a[j + 1]){
                swap(a[j], a[j + 1]);}
         }
     }
}

Guess you like

Origin blog.csdn.net/weixin_45922730/article/details/129104021