找出数组中前三个大数c语言
时间: 2023-05-15 19:07:30 浏览: 115
可以使用冒泡排序或快速排序等算法来找出数组中前三个大数。以下是使用冒泡排序的示例代码:
```c
#include <stdio.h>
void bubble_sort(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 main() {
int arr[] = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};
int n = sizeof(arr) / sizeof(arr[0]);
bubble_sort(arr, n);
printf("前三个大数为:%d %d %d\n", arr[0], arr[1], arr[2]);
return 0;
}
```
输出结果为:
```
前三个大数为:9 6 5
```
相关问题
帮我写一个取非空数组中第三大数的c语言程序
以下是一个简单的C语言程序,用于找到非空数组中的第三大数:
```c
#include <stdio.h>
int main() {
int n, i;
printf("Enter the size of array: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements of array: ", n);
for (i = 0; i < n; i++)
scanf("%d", &arr[i]);
int max1, max2, max3;
max1 = max2 = max3 = -2147483648; // 初始化为最小值
for (i = 0; i < n; i++) {
if (arr[i] > max1) {
max3 = max2;
max2 = max1;
max1 = arr[i];
} else if (arr[i] > max2 && arr[i] < max1) {
max3 = max2;
max2 = arr[i];
} else if (arr[i] > max3 && arr[i] < max2) {
max3 = arr[i];
}
}
if (max3 == -2147483648) {
printf("There is no third largest element in the array.");
} else {
printf("The third largest element in the array is: %d", max3);
}
return 0;
}
```
该程序首先要求用户输入数组的大小和元素,然后使用循环遍历该数组以找到第三大元素。在遍历过程中,使用三个变量 `max1`、`max2`、`max3` 来存储前三大的元素,如果当前元素大于 `max1`,则将 `max2` 和 `max3` 更新为之前的 `max1` 和 `max2`,并将当前元素赋值给 `max1`。如果当前元素大于 `max2` 且小于 `max1`,则将 `max3` 更新为之前的 `max2`,并将当前元素赋值给 `max2`。如果当前元素大于 `max3` 且小于 `max2`,则将当前元素赋值给 `max3`。最后,如果数组中没有第三大元素,则输出相应的消息;否则,输出第三大元素的值。
给你一个非空数组,返回此数组中的第三大数。如果不存在,则返回数组中最大的数,用java实现
好的,我会使用Java编写一个函数来解决这个问题。以下是代码示例:
```java
import java.util.Arrays;
public class ThirdLargestNumber {
public static int thirdMax(int[] nums) {
// 创建一个长度为3的数组来存储前三大的数
Integer[] maxNums = new Integer[3];
Arrays.fill(maxNums, null);
for (Integer num : nums) {
if (num.equals(maxNums[0]) || num.equals(maxNums[1]) || num.equals(maxNums[2])) {
// 如果当前数已经存在于前三大的数中,则跳过
continue;
}
if (maxNums[0] == null || num > maxNums[0]) {
// 更新最大的数
maxNums[2] = maxNums[1];
maxNums[1] = maxNums[0];
maxNums[0] = num;
} else if (maxNums[1] == null || num > maxNums[1]) {
// 更新第二大的数
maxNums[2] = maxNums[1];
maxNums[1] = num;
} else if (maxNums[2] == null || num > maxNums[2]) {
// 更新第三大的数
maxNums[2] = num;
}
}
if (maxNums[2] != null) {
return maxNums[2]; // 存在第三大的数,返回第三大的数
} else {
return maxNums[0]; // 不存在第三大的数,返回最大的数
}
}
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4, 5};
int result = thirdMax(nums);
System.out.println("第三大的数是:" + result);
}
}
```
您可以将您自己的数组传递给`thirdMax`函数,然后运行代码以获取结果。在这个示例中,数组`nums`为`{1, 2, 3, 4, 5}`,输出将是`3`,因为第三大的数是`3`。