c语言写一个冒泡排序函数
时间: 2024-01-21 11:02:20 浏览: 31
以下是用C语言实现的冒泡排序函数:
```c
#include <stdio.h>
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]) {
int 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("Sorted array: \n");
for (int i=0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
相关问题
用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;
} 我不了解用C语言写一个冒泡排序函数,但我可以给你一些参考资料,希望能帮到你!
用C语言写一个冒泡排序函数,并详细注释
#include <stdio.h> // 冒泡排序函数,arr为要排序的数组,n为要排序的数组长度
void bubbleSort(int arr[], int n)
{
int i, j;
// 外层循环控制趟数,一共需要排序n-1趟
for (i = 0; i < n-1; i++)
{
// 内层循环控制每一趟排序多少次
for (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[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
printf("排序后的结果是:");
int i;
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}我可以为你提供一份C语言中的冒泡排序函数的详细注释:此函数的功能是根据输入的数组arr,对数组中的元素进行冒泡排序,排序后的结果从小到大排列。函数中有两个循环,外层循环控制排序趟数,内层循环控制每趟排序的次数,每次比较两个相邻的元素,小的放在前面,大的放在后面,一趟比较完毕后,最大值就在最后,最小值在最前。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)