c语言 一维数组折半查找法
Problem statement: Write a C program to find two largest elements in a one dimensional array.
问题陈述:编写一个C程序以在一维数组中找到两个最大的元素。
Example: Type1: (all the elements are not same & no of element is more than two)
示例:Type1 :(所有元素都不相同且元素不超过两个)
Input:
Array size: 4
Elements: 32 54 -6 43
Output:
54 43
Example: Type2: (second maximum doesn’t exist as size of array < 2)
示例:Type2 :(第二个最大值不存在,因为数组的大小<2)
Input:
Array size : 1
Elements: 4
Output:
4
Example: Type3: (all elements are same, thus only one largest element)
示例:Type3 :(所有元素都相同,因此只有一个最大元素)
Input:
Array size : 4
Elements: 12 12 12 12
Output:
12
Algorithm:
算法:
Define two variable max & sec_max
定义两个变量max和sec_max
Initialize max to array[0] & sec_max to INT_MIN
初始化max与阵列[0]&sec_max到INT_MIN
Scan the entire array
扫描整个阵列
a. For(int i=0;i<n;i++) if array[i]>max then update max to array[i]&sec_max to previous max value else if array[i] is greater than sec_max but less than max then update sec_max to array value do nothing to max End for loop
If still sec_max has the value INT_MIN
如果sec_max的值为INT_MIN
Only one largest value exists, print it
仅存在一个最大值,将其打印出来
Else
其他
Print
打印
max & sec_max
max & sec_max
在一维数组中查找两个最大元素的C实现 (C implementation to find two largest elements in a one dimensional array)
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
void findTwoMax(int* a,int n){
int max=a[0]; //initialize max to first array element
int sec_max=INT_MIN,temp=0; //initialize max to first array element
for(int i=0;i<n;i++){ //scan the entire array
//if a[i]> max then update max to array value &
//second max to previous max value
if(a[i]>max){
sec_max=max;
max=a[i];
}
//else if a[i] is greater than second max but less
//than max then update second max to array value
else if (a[i] > sec_max && a[i] < max)
sec_max=a[i];
//do nothing to max
}
//if second max is still at its initialized value
//then no second maximum exists at all
if(sec_max==INT_MIN)
printf("only one large element: %d ",max);
else
printf("First largest element: %d & second largest element : %d",max,sec_max);
}
int main(){
int n;
printf("enter no of elements\n");
scanf("%d",&n);
//dynamic array created
int *a=malloc(sizeof(int)*n);
printf("enter the elements........\n");
//taking input
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
//find two largest no
findTwoMax(a,n);
return 0;
}
Output
输出量
First run:
enter no of elements
4
enter the elements........
32 54 -6 43
First largest element: 54 & second largest element : 43
Second run:
enter no of elements
1
enter the elements........
4
only one large element: 4
Third run:
enter no of elements
4
enter the elements........
12 12 12 12
only one large element: 12
翻译自: https://www.includehelp.com/c-programs/find-two-largest-elements-in-a-one-dimensional-array.aspx
c语言 一维数组折半查找法