Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding smallest and second smallest value of an array in C++

Tags:

c++

arrays

I have an array that will contains 5 random numbers between 0 to 99. I want to find the smallest and second smallest number of that array, I have the code below but it will not work if the first element is the smallest number. How can I fix this? Thank you for any help! :)

int numbers[5];

int main()
{
srand(time(NULL));

for(int i=0; i<5; i++){
    numbers[i]=rand()%100;
    cout<<numbers[i]<<" ";
}

cout<<endl;

int smallest = numbers[0], secondSmallest=numbers[0];

for(int i=0; i<5; i++){
    if(numbers[i]<smallest){
        secondSmallest=smallest;
        smallest=numbers[i];
    }
    else if(numbers[i]<secondSmallest)
        secondSmallest=numbers[i];
}
cout<<"Smallest number is : "<<smallest<<endl;
cout<<"Second smallest number is : "<<secondSmallest<<endl;
}

EDIT : this need to be done without sorting the array based on the requirements of the assignment.

like image 508
wesley Avatar asked Jan 22 '26 04:01

wesley


1 Answers

Yet another way to get this done without using two loops. Takes care of duplicates.

    int smallest = numbers[0],secondSmallest = numbers[0];
    for(int i=0;i<5;i++){
        if(numbers[i]>smallest){
            if(numbers[i]<secondSmallest || smallest==secondSmallest){
                secondSmallest = numbers[i];
            }
        }else{
            if(secondSmallest>smallest && numbers[i]!=smallest){
                secondSmallest=smallest;
            }
            smallest = numbers[i];
        }
    }
like image 179
Mrudav Shukla Avatar answered Jan 24 '26 20:01

Mrudav Shukla