Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I am trying to keep track of the two largest numbers in an array

I know that my array has the correct information (i checked) but in my for loop it is coming up with the wrong values.

        int mostFrequent = 0;
        int secondMost = 0;
        for(int i =0;i<256;i++){
            if (counter[i] > mostFrequent) {
                secondMost = mostFrequent;
                mostFrequent = i
            } else if (counter[i] < mostFrequent && counter[i] > secondMost){
                secondMost = i;
            }
        }

I know that I am saving the integers mostFrequent and secondMost as the index of the array, that is on purpose. I am comparing the values of the array but I want to save the indexes of those values. The correct values should be 32 and 101 for the indexes but it is not coming out correctly.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are comparing value with index!
Use counter[i] > counter[mostFrequent] instead of counter[i] > mostFrequent

        int mostFrequent = 0;
        int secondMost = 0;
        for(int i =0;i<256;i++){
            if (counter[i] > counter[mostFrequent]) {
                secondMost = mostFrequent;
                mostFrequent = i
            } else if (counter[i] < counter[mostFrequent] && counter[i] > counter[secondMost]){
                secondMost = i;
            }
        }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading