请用C++写个冒泡排序,要有英文注释
时间: 2024-03-26 12:40:40 浏览: 12
下面是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[] = {64, 25, 12, 22, 11};
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;
}
```
注释:
```c++
#include <iostream>
using namespace std;
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) { // Loop through all elements in the array except the last one
for (int j = 0; j < n - i - 1; j++) { // Loop through all the elements before the current unsorted element
if (arr[j] > arr[j + 1]) { // If the current element is greater than the next element
swap(arr[j], arr[j + 1]); // Swap the positions of the two elements
}
}
}
}
int main() {
int arr[] = {64, 25, 12, 22, 11};
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;
}
```