写一个冒泡程序用c语言
时间: 2023-10-03 10:07:01 浏览: 57
好的,以下是一个冒泡排序程序的C语言代码:
```c
#include <stdio.h>
int main() {
int arr[] = {5, 2, 8, 3, 1, 6};
int n = sizeof(arr) / sizeof(int);
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;
}
}
}
printf("排序后的数组:\n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
这段代码使用了双重循环来进行冒泡排序,首先外循环控制排序轮数,内循环控制每轮比较的次数。在每次比较中,如果前一个数比后一个数大,就交换位置。最终,数组中的元素就会按从小到大的顺序排列。
相关问题
写一个冒泡排序的c语言程序
下面是一个冒泡排序的C语言程序,可以实现从小到大排序:
```
#include <stdio.h>
void Bubble_sort(int arr[], int size) {
int j, i, tem;
for (i = 0; i < size - 1; i++) {
int count = 0;
for (j = 0; j < size - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
tem = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tem;
count = 1;
}
}
if (count == 0) {
break;
}
}
}
int main() {
int arr[10];
int i;
printf("请输入10个数\n");
for (i = 0; i < 10; i++) {
scanf("%d", &arr[i]);
}
printf("排序前的数组>");
for (i = 0; i < 10; i++) {
printf("%d ", arr[i]);
}
printf("\n排序后的数组>");
Bubble_sort(arr, 10);
for (i = 0; i < 10; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
写一个冒泡算法的C语言程序
#include<stdio.h>
int main()
{
int array[100], n, c, d, swap;
printf("输入元素个数\n");
scanf("%d", &n);
printf("输入%d个整数\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
for (c = 0 ; c < n - 1; c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
if (array[d] > array[d+1]) /* 比较相邻的元素 */
{
swap = array[d]; /* 交换数据 */
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
printf("排序后的结果:\n");
for (c = 0; c < n; c++)
printf("%d\n", array[c]);
return 0;
}
相关推荐
![](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)
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)