Home > Mobile >  In one pass through the array, find the numbers of the two smallest elements (in C language and with
In one pass through the array, find the numbers of the two smallest elements (in C language and with

Time:10-12

just got on of my tasks, can't figure out how to do it in one pass. For example, for this array: {9,5,6,2,6,7,1,3} the result should be 1 and 2. I'd appreciate any help :)

CodePudding user response:

Keep two variables, one to hold the lowest entry you've seen so far and one to hold the second-lowest entry you've seen so far. Traverse the array once updating those two variables as you go. When you finish traversing the array, they will hold the lowest and second-lowest entries in the array.

CodePudding user response:

Use two variables to hold the two lowest values of your for loop.

Then iterate over your for loop comparing the current to your two values. If lower replace. Else moveon

int smallest,small=0;
myArr[ARR_LEN] = {9,5,6,2,6,7,1,3};

for (int i=0; i< ARR_LEN; i  ){
    if (myArr[i] < small){
        
    }
    ... fill in as needed // Dont forget about the improper init smallest & small values
}

I'll let you figure out the rest

  • Related