请生成一段C语言的冒泡排序算法
时间: 2023-10-24 18:08:50 浏览: 47
以下是一段C语言的冒泡排序算法:
```
void bubble_sort(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]) {
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
```
该算法使用两个嵌套的循环来遍历数组,并比较相邻的元素。如果左边的元素大于右边的元素,则交换它们的位置。每次内层循环结束后,数组的最大值都会被放在最右边。这样,通过多次遍历和交换,就可以将整个数组排序。
相关问题
生成一段c语言冒泡排序代码
好的,以下是一段使用C语言实现冒泡排序的代码:
```
#include <stdio.h>
void bubble_sort(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]) {
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]);
int i;
printf("Before sorting: \n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
bubble_sort(arr, n);
printf("After sorting: \n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
这段代码包含一个 `bubble_sort` 函数,它接收一个整型数组和数组中元素的个数作为参数,然后使用冒泡排序算法对数组进行排序。在主函数中,我们定义了一个包含一些随机整数的数组,并调用 `bubble_sort` 函数对其进行排序,最终输出排序前和排序后的数组。
使用C语言生成一段冒泡排序
好的,以下是使用C语言生成一段冒泡排序的代码示例:
```c
#include <stdio.h>
void bubble_sort(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]) {
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]);
printf("Original array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
bubble_sort(arr, n);
printf("\nSorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
这段代码实现了冒泡排序算法,将数组中的元素按照从小到大的顺序进行排序。你可以将需要排序的数组存储在`arr`中,将数组的长度存储在`n`中,然后调用`bubble_sort(arr, n)`函数进行排序。
相关推荐
![application/octet-stream](https://img-home.csdnimg.cn/images/20210720083646.png)
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.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)