Find the highest n second highest numbers in an array within a single iteration.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • SrikanthBichala
    New Member
    • Oct 2010
    • 2

    Find the highest n second highest numbers in an array within a single iteration.

    For example a[]={0,100,5,2,3,2 00}
    Ouput: {200,100}
  • Turktaeteh
    New Member
    • Feb 2011
    • 2

    #2
    You might try this solution which has an array of 2 integers to contain the answer. While traversing the a[] , if the value is greater than the 1 in your answer's array, replace it in the answer's array. And then compare values in the answer to decide which is the greatest. Repeat this until a[] traversing is done and you will get the answer.

    Here's the guide code.


    Code:
    int answer[2] = {0,0} ;
    int a[]={0,100,5,2,3,200}
    
    for(int i=0 ; i < a. length; i++)
    {
     if(answer[1] < a[i])
     {
        answer[1] = a[i];
        if(answer[0] < answer[1])
        {
           int temp = answer[1];
           answer[1] = answer[0];
           answer[0] = temp;
        }
     }
    }
    
    return answer;
    hope this helps. I'm not sure with c syntax but the algo should be fine. :)

    Comment

    • whodgson
      Contributor
      • Jan 2007
      • 542

      #3
      I may be wrong but I don't think it is necessary to have a second array.
      Using a loop to iterate once through the array do the following:
      1) assign "hi" to first element array[0]
      2)go to the next element in the array[i=1] and assign it to "hi" iff it is larger than "hi". Look at element array[i-1] (array[0]) and assign it to "hinext" iff it is less in value to "hi"
      3)go to 3rd element array[2] and assign it to "hi" iff it is larger than "hi"
      4)look at element i-1 (in this casee array[1] and assign it to "hinext" iff it is larger than "hinext" and smaller than "hi"
      5) after exiting the loop (at completion of one iteration print "hi" and "hinext"
      iff=="if and only if"
      Last edited by whodgson; Feb 15 '11, 02:30 AM. Reason: To clarify item 2)

      Comment

      • johny10151981
        Top Contributor
        • Jan 2010
        • 1059

        #4
        Anyway, Can I ask why you two are doing homework for some one who even dont like to ask question in a proper way?

        Comment

        Working...