C语言数组排序完后输出第二个
时间: 2023-07-20 21:11:24 浏览: 47
好的,您可以使用以下代码来进行排序并输出第二个数:
```c
#include <stdio.h>
void swap(int *xp, int *yp) {
int temp = *xp;
*xp = *yp;
*yp = 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]);
}
}
}
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
printf("The second number after sorting the array is: %d", arr[1]);
return 0;
}
```
这段代码使用冒泡排序算法对数组进行排序,然后输出排序后的第二个元素。
相关问题
c语言数组排序函数sort
C语言中的数组排序函数是`qsort`,该函数使用快速排序算法。
函数原型为:
```c
void qsort(void *base, size_t nmemb, size_t size,
int (*compar)(const void *, const void *));
```
参数解释:
- `base`:待排序的数组首地址。
- `nmemb`:数组中元素个数。
- `size`:每个元素的大小,以字节为单位。
- `compar`:比较函数的指针,用于比较两个元素的大小。
比较函数的原型为:
```c
int (*compar)(const void *, const void *)
```
比较函数需要返回一个整数值,表示两个元素的大小关系:
- 若返回值小于0,则表示第一个元素小于第二个元素。
- 若返回值等于0,则表示两个元素相等。
- 若返回值大于0,则表示第一个元素大于第二个元素。
示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 比较函数
int compare(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
int main() {
int arr[] = {5, 1, 4, 2, 8};
int n = sizeof(arr) / sizeof(arr[0]);
// 排序
qsort(arr, n, sizeof(int), compare);
// 输出结果
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
输出结果:
```
1 2 4 5 8
```
c语言输出数组中第二大的数
可以使用选择排序或冒泡排序的方法,先把数组从小到大排序,然后输出倒数第二个数即为第二大的数。以下是选择排序的代码示例:
```
#include <stdio.h>
int main() {
int arr[] = {1, 8, 3, 7, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i < n-1; i++) {
int minIdx = i;
for (int j = i+1; j < n; j++) {
if (arr[j] < arr[minIdx])
minIdx = j;
}
// 交换 arr[i] 和 arr[minIdx]
int temp = arr[i];
arr[i] = arr[minIdx];
arr[minIdx] = temp;
}
printf("第二大的数是 %d", arr[n-2]);
return 0;
}
```
输出:第二大的数是 7
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.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)
![](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)