05 Algorithms
05 Algorithms
Lect. 5: Algorithms
Fall 2015
Example
RemainingFunds = CheckingBalance +
SavingsBalance
INTERNATIONAL UNIVERSITY, VNU-HCM 7
Pseudocode Primitives
(continued)
Conditional selection
if (condition):
activity
Example
if (sales have decreased):
low er the price by 5%
Example
if (year is leap year):
daily total= total/ 366
else:
daily total= total/ 365
INTERNATIONAL UNIVERSITY, VNU-HCM 9
Pseudocode Primitives
(continued)
Repeated execution
w hile (condition):
body
Example
w hile (tickets rem ain to be sold):
sella ticket
Example
def ProcessLoan():
Executing a function
if (. . .):
ProcessLoan()
else:
RejectApplication()
INTERNATIONAL UNIVERSITY, VNU-HCM 12
The procedure Greetings in pseudocode
def G reetings():
Count = 3
w hile (Count > 0):
print('H ello')
Count = Count - 1
def Sort(List):
N = 2
w hile (N < = length of List):
Pivot = N th entry in List
Rem ove N th entry leaving a hole in List
w hile (there is an Entry above the
hole and Entry > Pivot):
M ove Entry dow n into the hole leaving
a hole in the list above the Entry
M ove Pivot into the hole
N = N + 1
if (List is em pty):
Report that the search failed
else:
TestEntry = m iddle entry in the List
if (TargetValue = = TestEntry):
Report that the search succeeded
if (TargetValue < TestEntry):
Search the portion of List preceding TestEntry for
TargetValue, and report the result of that search
if (TargetValue > TestEntry):
Search the portion of List follow ing TestEntry for
TargetValue, and report the result of that search