Using C++ algorithm to implement bubble sort algorithm

Table of contents

  • introduction
  • Bubble sort principle
  • Specific implementation steps
  • Sample code
  • Time complexity and stability
  • Optimization possibilities
  • Conclusion

introduction

As a developer with a background in computer science and a small partner engaged in software development, I must be familiar with the C++ language. It is a very powerful programming language. It is not only a language based on the bottom layer of the program, but also a "money-making" language. "Language, I personally feel that friends who learn C++ well will have very good development (only personal opinion, please don't criticize). At the same time, the syntax of the C++ language is also very classic, and it can also be used to implement many classic algorithms, such as bubble sort. Everyone knows that bubble sort is a simple but effective sorting algorithm that uses multiple comparisons and exchanges. Sort the sequence by adjacent elements. Therefore, in this article, I will briefly share how to implement the bubble sort algorithm using C++ language, and also introduce its principles and implementation steps. By learning and understanding the bubble sort algorithm, we can deepen our understanding and application of the sort algorithm.

Bubble sort algorithm principle

Let’s review the principle of the classic bubble sorting algorithm. The core idea of ​​the bubble sorting algorithm is to traverse the sequence to be sorted multiple times, comparing two adjacent elements each time. If their order is incorrect, swap them. Location. By continuously comparing and exchanging, the largest (or smallest) element gradually "bubbles" to the end (or beginning) of the sequence, thereby achieving the purpose of sorting. The specific principle flow chart is as follows:

Specific implementation steps

Next, let’s take a look at the core implementation steps. In fact, there are only five steps to implement bubble sort using C++ language. The specific steps to implement bubble sort using C++ language are as follows:

  1. First, you need to define an array to be sorted and determine the length of the array;
  2. Then use two levels of nested loops. The outer loop controls the number of rounds of traversal, and the inner loop is used to compare adjacent elements and exchange them;
  3. Then in the inner loop, compare the size relationship between the current element and the next element. If the current element is larger than the next element, swap their positions;
  4. Immediately after each round of the inner loop is completed, the largest (or smallest) element will "bubble" to the end (or beginning) of the sequence;
  5. Finally, the outer loop is executed repeatedly until all elements are sorted.

Sample code

Through the above introduction to the core steps of bubble sorting in C++ language, it can be seen that it is very simple. Next, I will share the specific implementation code of bubble sorting in C++ language. The specific code examples of using C++ language to implement bubble sorting are as follows Shown:

#include <iostream>
using namespace std;

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 arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr) / sizeof(arr[0]);
    
    cout << "排序前的数组:";
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    
    bubbleSort(arr, n);
    
    cout << "\n排序后的数组:";
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    
    return 0;
}

By running the above specific code directly, you will see the following output:

Array before sorting: 64 34 25 12 22 11 90

Sorted array: 11 12 22 25 34 64 90

The results output through the console are as follows:

The above is the result of sorting the given array using the bubble sort algorithm. The initial array is {64, 34, 25, 12, 22, 11, 90}. After being processed by the bubble sort algorithm, the final sorted array is obtained. is {11, 12, 22, 25, 34, 64, 90}. It is not difficult to see that all elements are arranged in order from small to large, which proves that the bubble sort algorithm of the code successfully sorts the array and is successful.

Time complexity and stability

Let me share some content related to the time complexity and stability of bubble sort. Seeing this, the big guys in the C++ field will definitely smile knowingly, because this is a very easy knowledge category for C++ big guys, because bubble sorting The time complexity of the algorithm is O(n^2), where n is the length of the sequence to be sorted, and the bubble sort algorithm only exchanges adjacent elements each time, so the bubble sort is a stable sorting algorithm, equal to The relative position of elements does not change after sorting, which is a great advantage.

Optimization possibilities

Let’s talk about a more in-depth topic, about the optimization of bubble sorting in C++. Although the bubble sort algorithm is simple and easy to understand, in practical applications, its efficiency is relatively low. Especially for large-scale data sorting, the performance of bubble sort is not ideal or even poor. Therefore, developers need to pay attention to optimization when using C++ to implement bubble sort. There are many common optimization methods, such as setting flag bits to determine whether exchange occurs. If no exchange occurs in a certain inner loop, it means The sequence is already in order, and the sorting process can be ended in advance, which greatly saves the processing process steps, which is equivalent to optimizing the operation process.

Conclusion

Through the introduction and sharing of this article, as well as the demonstration of specific practical examples, especially the use of C++ language to implement the bubble sort algorithm, as well as its principles, implementation steps and optimization methods, readers must have mastered the steps to implement bubble sort in C++. Bar. And everyone should have also learned that bubble sorting is a simple but effective sorting algorithm, especially its principle. The sequence is sorted by comparing and exchanging adjacent elements multiple times. After learning the bubble sorting algorithm, we can Deeply understand the working principles of sorting algorithms and apply them flexibly in practical applications. At the same time, this article only briefly introduces the implementation and principles of bubble sorting in C++. I also hope that the big guys in C++ related fields will let it go, and the experts will please pass by. Finally, when using bubble sorting in actual development, you must consider the actual situation and be selective. Especially for sorting large-scale data, we can also consider other more efficient sorting algorithms to improve the speed of sorting. And performance, not all situations are suitable for using bubble sort, remember!

Guess you like

Origin blog.csdn.net/CC1991_/article/details/134167627