帮我用C语言写一个泡沫排序函数
时间: 2023-05-31 14:06:17 浏览: 62
以下是使用C语言编写的冒泡排序函数:
```c
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;
}
}
}
}
```
该函数接受一个整数数组和数组大小作为参数,然后使用冒泡排序算法对数组进行排序。在每一轮循环中,它比较相邻的两个元素,如果它们的顺序错误,则交换它们的位置。这样,最大的元素会被交换到数组的末尾,然后算法会重复这个过程,直到所有元素都被正确排序。
相关问题
用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语言写一个选择排序函数
我不是很熟悉C语言,但是我知道一般来说,选择排序函数可以使用以下代码实现:for (int i=0; i<n-1; i++)
{
int min_idx = i;
for (int j=i+1; j<n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
swap(&arr[min_idx], &arr[i]);
}
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![application/octet-stream](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)