How to write code for bubble sort algorithm in C++?
Here is the code for a bubble sort algorithm written in 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]) {
// 交换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] << " ";
}
return 0;
}
The code starts by defining a function called bubbleSort, which takes an integer array and the length of the array as parameters. Next, it uses two nested for loops to implement the bubble sort. The outer loop runs from 0 to n-1, and the inner loop runs from 0 to n-i-1, comparing adjacent elements in each iteration and swapping their positions if the previous element is greater than the next one. Finally, in the main function, an integer array is defined, the bubbleSort function is called to sort it, and the sorted array is printed.