C++ 冒泡排序算法实现详解
以下是使用 C++ 编写的冒泡排序算法:
#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]){
swap(arr[j], arr[j+1]);
}
}
}
}
int main(){
int arr[] = {5, 3, 8, 2, 1, 4};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
cout << 'Sorted array: ';
for (int i = 0; i < n; i++){
cout << arr[i] << ' ';
}
cout << endl;
return 0;
}
在这个算法中,我们使用了两个嵌套的循环来遍历数组,并在每次比较时交换需要交换的元素。在外层循环中,我们遍历整个数组,而在内层循环中,我们只遍历尚未排序的元素。这样做可以确保在每次循环中将最大的元素移到数组的末尾。
原文地址: https://www.cveoy.top/t/topic/mEX8 著作权归作者所有。请勿转载和采集!