Number of the largest and the next largest of a set of outputs

Keywords: C

The first method is:

This method can be selected when the data is basically ordered (ascending order) and does not require sequential output according to the original data.

 1 void select_1(int a[],int length,int *min1,int *min2){
 2     int i,j;
 3     bool change = true; 
 4     for(i = 1;i <= 2 && change;i++){
 5         change = false;
 6         for(j = 0;j < length - i;j++){
 7             if(a[j] > a[j+1]){
 8                 int temp;
 9                 temp = a[j];
10                 a[j] = a[j+1];
11                 a[j+1] = temp;
12                 change = true; //If swapping, it means that there is no ordering. 
13             }
14         }
15     }
16     
17     *min1 = a[length - 2];
18     *min2 = a[length - 1];  
19 } 

 

The second method:

The output data is arranged in the order of the original data.

 1 void select_2(int *x1,int *x2,int x){
 2     if(*x1 >= *x2){
 3         if(x > *x2){
 4             *x2 = x;
 5         }
 6     }
 7     else{//x1 < x2
 8         if(x >= *x2){
 9             *x1 = *x2;
10             *x2 = x;
11         }
12         else if(x > *x1 && x < *x2){
13             *x1 = *x2;
14             *x2 = x;
15         }
16     }
17 } 

 

Test data:
If you don't bother to type, you initialize it directly.

Note: When using the same set of data for the second time, you need to re-enter or define another array to assign initial values, which should not be used directly, because bubble sorting has changed the order of the original data and can not use a[10]= {2,3,1,4,7,3,5,1,6,0}; such an assignment statement, because it can only be written in this way at initialization, but not elsewhere. The reason for the error is that the later use is not initialization, and a[10] represents a value, not a set of numbers. If the array length is 10, a[10] is an out-of-bound array value, it will also lead to errors.

 1 int main(){
 2     int a[10] = {2,3,1,4,7,3,5,1,6,0};
 3     int b[10] = {2,3,1,4,7,3,5,1,6,0};
 4     int min1,min2;
 5     select_1(a,10,&min1,&min2);
 6     printf("There is no guarantee of order, just to find the maximum and the second largest values.\n"); 
 7     printf("min1: %d\nmin2: %d\n",min1,min2);
 8     
 9     int i,j;
10     min1 = b[0];
11     min2 = b[1];
12     for(i = 2;i < 10;i++){
13         select_2(&min1,&min2,b[i]);
14     }
15     printf("Keep the original order of size unchanged\n"); 
16     printf("min1: %d\nmin2: %d\n",min1,min2);
17     
18     return 0;
19 } 

 

Output result screenshot:

Posted by me1000 on Fri, 04 Oct 2019 14:51:00 -0700