gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
用c++写一个冒泡排序
- User
用c++写一个冒泡排序
- Assistant
以下是用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 << "排序后的数组:" << endl; for (int i = 0; i < n; i++) { cout << arr[i] << " "; } cout << endl; return 0; }这段代码首先定义了一个名为
bubbleSort的函数,该函数接受一个整数数组arr和数组的长度n作为参数,并使用冒泡排序算法来对数组进行排序。接下来,在main函数中创建了一个整数数组arr并赋予初始值,然后计算数组的长度并调用bubbleSort函数来对数组进行排序。最后,输出排序后的数组。