C++冒泡排序完整代码
时间: 2024-05-21 17:09:34 浏览: 20
好的,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]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
int main(){
int arr[] = {5, 3, 2, 4, 1};
int n = sizeof(arr)/sizeof(arr);
bubbleSort(arr, n);
cout<<"排序后的数组:";
for(int i=0; i<n; i++){
cout<<arr[i]<<" ";
}
return 0;
}
```
冒泡排序是一种比较简单的排序算法,它的基本思路是在每一轮排序中,相邻的两个元素进行比较,如果顺序不对就交换它们的位置,这样每一轮排序后最大(或最小)的元素就会被放到最后面。经过多次排序后,整个序列就变得有序了。
相关问题
C++ 冒泡排序 完整代码
以下是 C 冒泡排序的完整代码:
#include <stdio.h>
void bubble_sort(int arr[], int len)
{
int i, j, temp;
for (i = ; i < len - 1; i++)
{
for (j = ; j < len - 1 - i; j++)
{
if (arr[j] > arr[j + 1])
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main()
{
int arr[] = { 64, 34, 25, 12, 22, 11, 90 };
int len = sizeof(arr) / sizeof(arr[]);
int i;
printf("排序前的数组:\n");
for (i = ; i < len; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
bubble_sort(arr, len);
printf("排序后的数组:\n");
for (i = ; i < len; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
return ;
}
c++冒泡排序法完整代码
好的,下面是使用C++实现冒泡排序的完整代码:
```cpp
#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;
}
```
在这个代码中,我们首先定义了一个函数bubbleSort用于进行冒泡排序。在函数中,我们使用两个循环来实现排序。外层循环控制排序的次数,内层循环用于相邻元素的比较和交换。在比较过程中,如果相邻元素的顺序不正确,我们就将它们交换位置。
在主函数中,我们先定义一个数组arr,然后通过sizeof运算符来计算数组的长度n,然后调用bubbleSort函数进行排序。最后,我们使用一个循环来输出排序后的数组。
希望这个代码能够帮助你理解冒泡排序的实现过程。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)