Beginner C/C++

Moderators: None (Apply to moderate this forum)
Number of threads: 5432
Number of posts: 16953

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
writing an algorithm in pseudocode Posted by HAMISI on 14 Apr 2009 at 11:16 AM
how to write an algorithm that outputs the largest and the second largest elemnts in a sequence s1....sn where s1 is the first element and sn is the last element.
Report
Re: writing an algorithm in pseudocode Posted by Actor on 14 Apr 2009 at 11:58 AM
start
   read Largest   // algorithm assumes n >= 2
   read Second
   if Second > Largest   // swap
      S = Largest
      Largest = Second
      Second = S
   for i = 2 to n
      read S
      if (S > Largest) and (S > Second)
         Second = Largest
         Largest + S
      else if S > Second
         Second = S
    write Largest, Second
stop

Report
Re: writing an algorithm in pseudocode Posted by Martian on 19 Apr 2009 at 4:13 PM
:
: 
: start
:    read Largest   // algorithm assumes n >= 2
:    read Second
:    if Second > Largest   // swap
:       S = Largest
:       Largest = Second
:       Second = S
:    for i = 2 to n
:       read S
:       if (S > Largest) and (S > Second)
:          Second = Largest
:          Largest + S
:       else if S > Second
:          Second = S
:     write Largest, Second
: stop
: 
:
:

The only thing I would change is remove the (S > Second) in the first part of the if statement since an invariant of the for loop is that Largest > Second.


Report
Re: writing an algorithm in pseudocode Posted by Actor on 19 Apr 2009 at 8:53 PM
: :
: : 
: : start
: :    read Largest   // algorithm assumes n >= 2
: :    read Second
: :    if Second > Largest   // swap
: :       S = Largest
: :       Largest = Second
: :       Second = S
: :    for i = 2 to n
: :       read S
: :       if (S > Largest) and (S > Second)
: :          Second = Largest
: :          Largest + S
: :       else if S > Second
: :          Second = S
: :     write Largest, Second
: : stop
: : 
: :
: :
:
: The only thing I would change is remove the (S > Second) in the
: first part of the if statement since an invariant of the for loop is
: that Largest > Second.
:
:
:
Right. And the line
         Largest + S

is a typo that should be
         Largest = S





 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.