# writing an algorithm in pseudocode

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.

• [code]
start
read Largest [red]// algorithm assumes n >= 2[/red]
if Second > Largest [red]// swap[/red]
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
[/code]
• : [code]:
: start
: read Largest [red]// algorithm assumes n >= 2[/red]
: if Second > Largest [red]// swap[/red]
: 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
: [/code]:
:

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.

• : : [code]: :
: : start
: : read Largest [red]// algorithm assumes n >= 2[/red]
: : if Second > Largest [red]// swap[/red]
: : 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
: : [/code]: :
: :
:
: 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
[code]
Largest + S
[/code]
is a typo that should be
[code]
[red]Largest = S[/red]
[/code]