用c语言的sort函数写个排序
时间: 2023-03-29 17:02:37 浏览: 96
好的,我可以回答这个问题。使用C语言的sort函数可以对数组进行排序。下面是一个示例代码:
```
#include <stdio.h>
#include <stdlib.h>
int compare(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
int main() {
int arr[] = {5, 2, 8, 3, 1};
int n = sizeof(arr) / sizeof(arr[]);
qsort(arr, n, sizeof(int), compare);
for (int i = ; i < n; i++) {
printf("%d ", arr[i]);
}
return ;
}
```
这个程序将会输出:1 2 3 5 8,这是由小到大排序后的结果。
相关问题
C语言用函数写数组排序
可以使用以下代码来用函数实现数组排序(以升序排列为例):
```c
#include <stdio.h>
void sort(int arr[], int n);
int main() {
int arr[] = {5, 2, 8, 3, 1};
int n = sizeof(arr) / sizeof(arr[0]);
sort(arr, n);
printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
void sort(int arr[], int n) {
int temp;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
```
在 `main` 函数中,我们先定义一个数组 `arr` 和其元素个数 `n`,然后调用 `sort` 函数进行排序,并最后输出排序后的数组。
`sort` 函数使用冒泡排序算法,依次比较数组中相邻的元素,若前一个元素比后一个元素大,则交换它们的位置,直到整个数组都排序完成。
C语言用sort函数写一个冒泡程序
抱歉,您的问题有些不符合实际情况。sort函数是用于排序的,而冒泡排序是一种排序算法,它并不使用sort函数。以下是C语言实现冒泡排序的示例代码:
```c
#include <stdio.h>
void bubble_sort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int 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[] = {5, 2, 9, 1, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);
bubble_sort(arr, n);
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
这段代码先定义了一个名为`bubble_sort`的函数,它接受一个整型数组和数组长度作为参数,然后使用双重循环实现冒泡排序。最后在`main`函数中调用`bubble_sort`函数并输出排序后的结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)