writing an algorithm in pseudocode - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

writing an algorithm in pseudocode

HAMISIHAMISI Posts: 2Member
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.

Comments

  • ActorActor Posts: 438Member
    [code]
    start
    read Largest [red]// algorithm assumes n >= 2[/red]
    read Second
    if Second > Largest [red]// swap[/red]
    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
    [/code]
  • MartianMartian Posts: 9Member
    : [code]:
    : start
    : read Largest [red]// algorithm assumes n >= 2[/red]
    : read Second
    : if Second > Largest [red]// swap[/red]
    : 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
    : [/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.


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

Sign In or Register to comment.