Example of C++ bubble sort algorithm

  • 2020-04-02 02:49:05
  • OfStack

Bubble sort

At the very beginning of the university study of data structures and algorithms, we talked about bubble sort; So you can see how classic this sorting algorithm is. Bubble sort is a very simple sorting algorithm that repeatedly visits the sequence to be sorted and compares two Numbers each time, swapping the two Numbers in ascending or descending order. For example, now I want to sort the following data:

10, 3, 8, 0, 6, 9, 2

When using bubble sort for ascending sort, the sort steps are as follows:

Three, ten, eight, zero, six, nine, two   // 10 versus 3, 10 > 3. Switch places

3, 8, 10, 0, 6, 9, 2   // 10 versus 8, 10 > 8. Switch places

3, 8, 0, 10, 6, 9, 2   // 10 versus 0, 10 > Zero, switch places

...

3, 8, 0, 6, 9, 2, 10   // at this point, 10 reaches the far right and is the largest number. At this point, we are comparing from the beginning

3, 8, 0, 6, 9, 2, 10   PI over PI over 3 is less than 8, so we don't have to switch places

3, 0, 8, 6, 9, 2, 10   // 8 is greater than 0, so we switch places

...

0, 2, 3, 6, 8, 9, 10

Very simple, just let the large number sink down and the decimal float up. The time complexity of bubble sort is also order n^2.

Code implementation


#include <iostream>
using namespace std;
 
void BubbleSort(int arr[], int length)
{
     int temp;
     for (int i = 0; i < length; ++i)
     {
          for (int j = 0; j < length - i - 1; ++j)
          {
               if (arr[j] > arr[j + 1])
               {
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
               }
          }
     }
}
 
int main()
{
     int arr[10] = {2, 4, 1, 0, 8, 4, 8, 9, 20, 7};
 
     BubbleSort(arr, sizeof(arr) / sizeof(arr[0]));
 
     for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); ++i)
     {
          cout<<arr[i]<<" ";
     }
     cout<<endl;
 
     return 0;
}


Related articles: