user12354664
user12354664

Reputation:

Largest and second largest number in array C++ problem

I want to find the largest and second-largest number in the array. I can find the largest but second largest becomes same as largest and don't know why


int main()
{
    int number[10];
    cout<<"enter 10 numbers\n";
    for (int i =0;i<=9;++i){
        cin>>number[i];
    }

    int larger2=number[0],larger=number[0];
    for(int a=0;a<=9;++a){
       if(number[a]>larger) {
           larger=number[a];
       }
    }

    for(int b=0;b<=9;++b){
       if(  number[b]>larger2 && larger>larger2 ){
           larger2=number[b];
       }
    }


    cout<<"larger       "<<larger<<endl;
    cout<<"larger 2     "<<larger2<<endl;
    return 0;
}

Upvotes: 1

Views: 533

Answers (2)

Alberto
Alberto

Reputation: 12899

Have a look at this (this works only if there are at least 2 element in the array, otherwise number[1] will produce a segmentation fault):

int main()
{
    int number[10];
    cout<<"enter 10 numbers\n";
    for (int i =0;i<=9;++i){
        cin>>number[i];
    }

    int larger2=min(number[0],number[1]) ,larger=max(number[1],number[0]);
    for(int a=0;a<=9;++a){
       if(number[a]>larger2) {
           if(number[a]>larger1){
               larger2=larger;
               larger = number[a];
           }
           else larger2=number[a];
       }
    }


    cout<<"larger       "<<larger<<endl;
    cout<<"larger 2     "<<larger2<<endl;
    return 0;
}

The explanation is this:

  1. take the biggest from the first 2 number and assign to larger and the smallest to larger2
  2. loop through the array and if the current number is bigger than larger2 we need to store that value in larger if it's the bigger, and so the second bigger will be the olfd value of larger, else we need to store it in larger2

And that's it.

Also take in account that this algorithm is O(n), because we need to travel the whole array just one time, instead of the original one that i O(n*2) because you have to travel the whole array two times, so with bigger array size, this will end about in half the time

Upvotes: 0

Grantly
Grantly

Reputation: 2556

I would modify your second evaluating loop to this:

As you have not correctly assigned larger2 in at least one iteration, so you should not use it for comparisons. (ie Do not do this larger>larger2)

for(int b=0;b<=9;++b){
   if(  number[b]>larger2 && larger>number[b]){
       larger2=number[b];
   }
}

Upvotes: 2

Related Questions