C语言求数组中最大的数
2021-07-07 06:59:30
深夜i
--
--
C
语
言
求
数
组
中
最
大
的
数
C 程序使用函数和不使用函数查找数组中的最大数。 我们还打印了它所在的索引。
如何在数组中找到最大值?
获取最大值的算法:我们假设它出现在数组的开头。 然后将其与第二个元素进行比较。 如果第二个元素大于第一个元素,则更新索引。 重复它直到数组的最后一个索引。 类似地,我们可以找到数组中的最小元素。
C程序在数组中查找最大数
#include <stdio.h>
int main()
{
int array[100], size, c, location = 0;
printf("Enter the number of elements in array\n");
scanf("%d", &size);
printf("Enter %d integers\n", size);
for (c = 0; c < size; c++)
scanf("%d", &array[c]);
for (c = 1; c < size; c++)
if (array[c] > array[location])
location = c;
printf("Maximum element is present at location %d and its value is %d.\n", location+1, array[location]);
return 0;
}
如果最大元素在数组中出现两次或更多次,则打印它首先出现的索引或最小索引处的最大值。 您可以轻松修改程序以打印它所在的最大索引。 您还可以存储它在数组中出现的所有索引。
下载数组程序中的最大元素。
程序输出:
C程序使用函数查找数组中的最大数
我们的函数返回存在最大元素的索引。
#include <stdio.h>
int find_maximum(int[], int);
int main() {
int c, array[100], size, location, maximum;
printf("Input number of elements in array\n");
scanf("%d", &size);
printf("Enter %d integers\n", size);
for (c = 0; c < size; c++)
scanf("%d", &array[c]);
location = find_maximum(array, size);
maximum = array[location];
printf("Maximum element location = %d and value = %d.\n", location + 1, maximum);
return 0;
}
int find_maximum(int a[], int n) {
int c, index = 0;
for (c = 1; c < n; c++)
if (a[c] > a[index])
index = c;
return index;
}
C程序使用指针查找数组中的最大元素
#include <stdio.h>
int main()
{
long array[100], *maximum, size, c, location = 1;
printf("Enter the number of elements in array\n");
scanf("%ld", &size);
printf("Enter %ld integers\n", size);
for (c = 0; c < size; c++)
scanf("%ld", &array[c]);
maximum = array;
*maximum = *array;
for (c = 1; c < size; c++)
{
if (*(array+c) > *maximum)
{
*maximum = *(array+c);
location = c+1;
}
}
printf("Maximum element found at location %ld and its value is %ld.\n", location, *maximum);
return 0;
}
程序的时间复杂度为 O(n),因为使用的时间取决于输入数组的大小。 换句话说,找到最大值的时间随着数组大小的增加而线性增加。
我们还可以按升序/降序对数组进行排序以找到其中的最大数。 排序后,最后一个/第一个元素是最大值。 使用比较排序算法进行排序的复杂度为 O(nlogn)。
上一篇:
idea打包java可执行jar包
下一篇:
C程序在数组中查找最小值
评论区