帮我用c++写一个冒泡排序算法
时间: 2023-09-17 19:05:54 浏览: 120
### 回答1:
好的,这是一个用 C 语言实现的冒泡排序算法代码:
```
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void bubbleSort(int arr[], int n) {
int i, j;
for (i = 0; i < n-1; i++) {
for (j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
swap(&arr[j], &arr[j+1]);
}
}
}
}
void printArray(int arr[], int size) {
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
printf("排序后的数组: \n");
printArray(arr, n);
return 0;
}
```
这是一种经典的排序算法,它通过比较相邻两个元素的大小,如果前者比后者大,就交换它们的位置,直到整个数组有序。
### 回答2:
冒泡排序算法是一种简单而有效的排序算法,它通过比较相邻的元素并交换位置来实现排序。下面是一个使用C语言实现的冒泡排序算法:
```
#include <stdio.h>
void bubbleSort(int arr[], int n) {
int i, j, temp;
for (i = 0; i < n-1; i++) {
for (j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
// 交换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 n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
printf("排序后的数组:");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
以上代码实现了冒泡排序算法。在`bubbleSort`函数中,使用嵌套的循环来比较相邻的元素,并通过交换来正确地排列元素的顺序。在`main`函数中,我们定义了一个待排序的整数数组,然后调用`bubbleSort`函数对数组进行排序。最后,输出排序后的数组。以上代码输出结果为:11 12 22 25 34 64 90。这表示数组已经按照升序进行了排序。
### 回答3:
冒泡排序是一种基本的排序算法,通过不断比较相邻的元素并交换位置来实现排序。以下是使用C语言编写的冒泡排序算法示例:
```c
#include <stdio.h>
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[] = {5, 2, 7, 1, 3};
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
printf("排序后的数组:");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
在这个例子中,我们定义了一个bubbleSort函数来执行冒泡排序。它接受一个整数数组和数组长度作为参数。函数使用两个嵌套的循环来比较相邻元素并交换它们的位置。在内层循环中,如果当前元素大于后一个元素,则进行交换。通过外层循环的迭代,最大的元素会逐渐“冒泡”到数组的末尾,而内层循环会在每次迭代中比较更少的元素。最终,数组将按升序排序。
在主函数中,我们创建了一个包含5个整数的数组,并计算数组的长度。然后,我们调用bubbleSort函数对数组进行排序,并使用printf函数打印排序后的数组。
以上就是使用C语言编写的冒泡排序算法的示例。希望对你有帮助!
阅读全文
相关推荐
![text/x-c](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![cpp](https://img-home.csdnimg.cn/images/20250102104920.png)