Beginner C/C++

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

This Forum Only

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.
Re: writing an algorithm in pseudocode Posted by Actor on 14 Apr 2009 at 11:58 AM
```start
read Largest   // algorithm assumes n >= 2
if Second > Largest   // swap
S = Largest
Largest = Second
Second = S
for i = 2 to n
if (S > Largest) and (S > Second)
Second = Largest
Largest + S
else if S > Second
Second = S
write Largest, Second
stop
```

Re: writing an algorithm in pseudocode Posted by Martian on 19 Apr 2009 at 4:13 PM
:
```:
: start
:    read Largest   // algorithm assumes n >= 2
:    if Second > Largest   // swap
:       S = Largest
:       Largest = Second
:       Second = S
:    for i = 2 to n
:       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.

Re: writing an algorithm in pseudocode Posted by Actor on 19 Apr 2009 at 8:53 PM
: :
```: :
: : start
: :    read Largest   // algorithm assumes n >= 2
: :    if Second > Largest   // swap
: :       S = Largest
: :       Largest = Second
: :       Second = S
: :    for i = 2 to n
: :       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