Home > Article > Backend Development > How to use bubble sort algorithm in C++
How to use the bubble sort algorithm in C
The bubble sort algorithm is a simple but inefficient sorting algorithm that uses multiple comparisons and exchanges to Arrange a sequence from smallest to largest (or largest to smallest). Here we will introduce how to implement the bubble sort algorithm using C language, and attach detailed code examples.
#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 - 1 - i; 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]); bubbleSort(arr, n); cout << "排序后的数组:"; for (int i = 0; i < n; i++) { cout << arr[i] << " "; } cout << endl; return 0; }
arr
and initialize it as needed. Then by calculating the length of the array n
, call the bubbleSort
function to sort the array. In the bubbleSort
function, two nested loops are used to implement the core logic of bubble sort: the outer loop controls the number of rounds of comparison and exchange, and the inner loop is responsible for the specific comparison and exchange of each round. . Finally, the sorted array is output in the main function. 排序后的数组:11 12 22 25 34 64 90
It can be seen that after bubble sorting, the array elements are arranged in order from small to small. The big ones are arranged in the correct order.
Summary:
The bubble sort algorithm is a simple but inefficient sorting algorithm. In practical applications, the bubble sort algorithm can be used for small-scale data sorting. However, for large-scale data, the bubble sort algorithm has high time complexity and is not recommended.
The above is the detailed content of How to use bubble sort algorithm in C++. For more information, please follow other related articles on the PHP Chinese website!