Outputs the largest and the second largest of a group of Numbers

Time:2019-10-23

The first method:

This method can be selected when the data is in basic order (ascending order) and the output order in the original data is not required 

void select_1(int a[],int length,int *min1,int *min2){
     int i,j;
     bool change = true; 
     for(i = 1;i <= 2 && change;i++){
         change = false;
         for(j = 0;j < length - i;j++){
             if(a[j] > a[j+1]){
                 int temp;
                 temp = a[j];
                 a[j] = a[j+1];
                 a[j+1] = temp;
                 Change = true; // if swapped, it is not sorted 
             }
         }
     }
     
     *min1 = a[length - 2];
     *min2 = a[length - 1];  
 }

 

The second method:

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

void select_2(int *x1,int *x2,int x){
     if(*x1 >= *x2){
         if(x > *x2){
             *x2 = x;
         }
     }
     else{//x1 < x2
         if(x >= *x2){
             *x1 = *x2;
             *x2 = x;
         }
         else if(x > *x1 && x < *x2){
             *x1 = *x2;
             *x2 = x;
         }
     }
 }

 

Test data:
  I don’t want to type, I just initialize it

Note: when using the same set of data for the second time, you need to re-enter or define another array assignment, which should not be used directly, because bubble sorting has changed the order of the original data, or a[10] = {2,3,1,4,7,3,5,1,6,0}. Such assignment statements, because only in this way of using initialization time, you can write in other places can’t, will go wrong, the cause of the error was not use next initialization, and a [10] said a value, rather than a set of number, if the length of the array is 10, a [10] is a out an array of values, will go wrong.

int main(){
     int a[10] = {2,3,1,4,7,3,5,1,6,0};
     int b[10] = {2,3,1,4,7,3,5,1,6,0};
     int min1,min2;
     select_1(a,10,&min1,&min2);
     Printf (" do not guarantee the order, just find the maximum and the next largest value \n"); 
     printf("min1: %d\nmin2: %d\n",min1,min2);
     
     int i,j;
     min1 = b[0];
     min2 = b[1];
     for(i = 2;i < 10;i++){
         select_2(&min1,&min2,b[i]);
     }
     Printf (" size unchanged \n"); 
     printf("min1: %d\nmin2: %d\n",min1,min2);
     
     return 0;
 }

 

Output screenshot: