有10个互不相同的整数:99、200、95、87、98、-12、30、87、75、-25,不用排序,每当输入一个1-10之间的数n,即可输出第n个大的数。比如,输入2,则输出99. 请设计并实现一算法,传入数字n即可输出第n个大的数。用C语言算法设计
时间: 2024-05-11 18:15:08 浏览: 20
以下是用C语言实现的解题思路:
1.定义一个大小为10的整数数组,将给定的十个整数存入数组;
2.定义函数bubbleSort()来对数组进行排序,使用冒泡排序算法;
3.定义一个函数getNthLargest(),该函数接受一个整数n作为参数,然后调用bubbleSort()函数进行排序,最后返回第n个大的数;
4.在主函数中,使用scanf()函数读入一个1-10之间的整数n,然后调用getNthLargest()函数来输出第n个大的数。
以下是代码实现:
```c
#include <stdio.h>
void bubbleSort(int arr[], int n)
{
int i, j, temp;
for (i = 0; i < n - 1; i++)
{
for (j = 0; j < n - i - 1; j++)
{
if (arr[j] < arr[j + 1])
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int getNthLargest(int arr[], int n)
{
bubbleSort(arr, 10);
return arr[n - 1];
}
int main()
{
int arr[10] = { 99, 200, 95, 87, 98, -12, 30, 87, 75, -25 };
int n;
printf("请输入一个1-10之间的整数n: ");
scanf("%d", &n);
printf("第%d个大的数是:%d\n", n, getNthLargest(arr, n));
return 0;
}
```
当输入n为2时,输出结果为:第2个大的数是:99。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)