冒泡排序c语言怎么写
时间: 2023-11-05 13:05:24 浏览: 36
冒泡排序是一种简单的排序算法,它通过重复地交换相邻的元素来将最大的元素逐渐移动到列表的末尾。下面是冒泡排序的C语言代码实现:
#include<stdio.h>
void BubbleSort(int array[],int len){
int temp;
for(int i=0;i<len-1;i++){
for(int j=0;j<len-1-i;j++){
if(array[j]>array[j+1]){
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
}
int main(){
int array[] = {3,44,38,5,47,15,36};
int len = sizeof(array) / sizeof(int);
printf("原始序列为:\n");
for(int i=0;i<len;i++){
printf("%d ",array[i]);
}
BubbleSort(array,len);
printf("\n排序后序列为:\n");
for(int i=0;i<len;i++){
printf("%d ",array[i]);
}
}
这段代码首先定义了一个BubbleSort函数,该函数接受一个整数数组和数组的长度作为参数。在函数内部,使用两个嵌套的循环来实现冒泡排序算法。外层循环控制排序的趟数,内层循环控制每一趟比较的次数。通过比较相邻的元素并交换位置,将最大的元素逐渐移动到列表的末尾。最后,打印排序后的序列。
运行结果如下:
原始序列为:
3 44 38 5 47 15 36
排序后序列为:
5 15 36 38 44 47
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)