Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
134 views

Module 1 CS104 Data Structures and Algorithms

This document provides an overview of an introductory course on data structures and algorithms. The course is divided into two units. Unit 1 covers algorithmic problem solving and introduces key concepts like algorithms, pseudo code, and flowcharts. It provides examples of using algorithms to solve problems and represents algorithms using pseudo code and flowcharts. Unit 2 covers the topic of recursion, its introduction and examples of recursive algorithms. The document outlines learning objectives, activities and assessments for both units to help learners understand fundamental concepts related to data structures and algorithms.

Uploaded by

Kobe Bry
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
134 views

Module 1 CS104 Data Structures and Algorithms

This document provides an overview of an introductory course on data structures and algorithms. The course is divided into two units. Unit 1 covers algorithmic problem solving and introduces key concepts like algorithms, pseudo code, and flowcharts. It provides examples of using algorithms to solve problems and represents algorithms using pseudo code and flowcharts. Unit 2 covers the topic of recursion, its introduction and examples of recursive algorithms. The document outlines learning objectives, activities and assessments for both units to help learners understand fundamental concepts related to data structures and algorithms.

Uploaded by

Kobe Bry
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 17

DATA STRUCTURES AND ALGORITHMS

MODULE 1
ALGORITHMIC PROBLEM SOLVING AND
RECURSION

Mr. Paul B. Bokingkito Jr.


Instructor
1
Table of Contents

UNIT 1. ALGORITHMIC PROBLEM SOLVING………………………………………………2


Introduction……………………………………………………………………………….2
Objectives …………………………………………………………………….………….2
Learning Activities…………………………………………………………………….…3
Activity 1 - Introduction to Algorithms and problem solving…………………………3
Activity 2 - The characteristics of an algorithm……………………………………….5
Activity 3 - Using pseudo-codes and flowcharts to represent algorithms………….6
UNIT SUMMARY………………………………………………………………………..11
Unit Assessment…………………………………………………………………………11
Unit Readings and Other Resources………………………………………………….11
Answers………………………………………………………………………………….11

UNIT 2. RECURSION……………………………………………………………………………13
Introduction……………………………………………………………………………….13
Objectives…………………………………………………………………………….…..13
Learning Activities……………………………………………………………………….13
Activity 1 - Recursive Algorithm………………………………………………………..13
UNIT SUMMARY………………………………………………………………………..16
Unit Assessment…………………………………………………………………………16
Unit Readings and Other Resources………………………………………………….16
Answers……………………………………………………………………………….….17

2
UNIT 1
ALGORITHMIC PROBLEM SOLVING

INTRODUCTION
This unit introduces learners to data structures and algorithm course. The unit is on the
different data structures and their algorithms that can help implement the different data structures in
the computer. The application of the different data structures is presented by using examples of
algorithms and which are not confined to a particular computer programming language.

OBJECTIVES
Upon completion of this unit the learner should be able to:
1. Describe an algorithm
2. Explain the relationship between data and algorithm
3. Outline the characteristics of algorithms
4. Apply pseudo codes and flowcharts to represent algorithms

KEY TERMS
Data: the structural representation of logical relationships between elements of data
Algorithm: finite sequence of steps for accomplishing some computational task

Pseudo code: an informal high-level description of the operating principle of a


computer program or other algorithm.
Flow chart: diagrammatic representation illustrates a solution model to a given
problem.

LEARNING ACTIVITIES
ACTIVITY 1 - INTRODUCTION TO ALGORITHMS AND PROBLEM SOLVING
Introduction

In this learning activity section, the learner will be introduced to algorithms and how to
write algorithms to solve tasks faced by learners or everyday problems. Examples of the
algorithm are also provided with a specific application to everyday problems that the learner is
familiar with. The learners will particularly learn what is an algorithm, the process of developing
a solution for a given task, and finally examples of application of the algorithms are given

3
Algorithm
An algorithm is a finite sequence of steps for accomplishing some computational task. it
must
• Have steps that are simple and definite enough to be done by a computer, and
• Terminate after finitely many steps.

An algorithm can be considered as a computational procedure that consists of a set of


instructions, that takes some value or set of values, as input, and produces some value or set of
values, as output, as illustrated in the fig 1 below. It can also be described as a procedure that
accepts data, manipulate them following the prescribed steps, so as to eventually fill the
required unknown with the desired value(s). The concept of an algorithm is best illustrated by
the example of a recipe, although many algorithms are much more complex; algorithms often
have steps that repeat (iterate) or require decisions (such as logic or comparison) until the task
is completed. Correctly performing an algorithm will not solve a problem if the algorithm is
flawed or not appropriate to the problem. A recipe is a set of instructions that show how to
prepare or make something, especially a culinary dish.

Different algorithms may complete the same task with a different set of instructions in
more or less time, space, or effort than others. Algorithms are essential to the way computers
process information, because a computer program is essentially an algorithm that tells the
computer what specific steps to perform (in what specific order) in order to carry out a specified
task Algorithmic problem solving comes in two phases. These includes:
1. derivation of an algorithm that solves the problem, and
2. conversion of the algorithm into code.
It is worth noting that;
1. an algorithm is a sequence of steps, not a program.
2. same algorithm can be used in different programs, or the same algorithm can be
expressed in different languages, because an algorithm is an entity that is abstracted
from implementation details.
An algorithm can be expressed in following ways;
a) human language
b) pseudo code
c) flow chart

Example
Problem: Given a list of positive numbers, return the largest number on the list.
Inputs: A list L of positive numbers. This list must contain at least one number.
Outputs: A number n, which will be the largest number of the list.

4
Algorithm:
Step 1 Set max to 0.
Step 2 For each number x in the list L, compare it to max.
Step 3 If x is larger, set max to x.
Step 4 max is now set to the largest number in the list.
Conclusion

The learner was introduced to the concept of algorithm and the various ways he/she can
develop a solution to a task. In particular, the learner was introduced to the definition/s of an
algorithm, the three main ways of developing or expressing an algorithm which are the human
language, Pseudo code and the flow chart. Examples was also given to reinforce the concept of
the algorithm.

Assessment
1. Outline the algorithmic steps that can be used to add two given numbers
2. By using an example, describe how the concept of algorithms can be
well presented to a group of students being introduced to it.

ACTIVITY 2 - THE CHARACTERISTICS OF AN


ALGORITHM Introduction

This section introduces the learners to the characteristics of algorithms. These


characteristics makes the learner to become aware of what to ensure is basic, present and
mandatory for any algorithm to qualify to be one. It also exposes the learner to what to expect
from an algorithm to achieve or indicate. Key expectations are; the fact that an algorithm must
be exact, terminate, effective, general among others.
Characteristics of an Algorithm
There following are some key characteristics of an algorithm

1. Each step of an algorithm must be exact; this means that an algorithm must be
precise and ambiguously described. This eliminates any uncertainty. it can also be
said to the characteristic of precision, i.e. the steps are precisely stated(defined).

2. Algorithm must terminate; since the ultimate aim of an algorithm is to solve a problem,
then it must terminate otherwise there won’t be a solution for the problem. This leads
to the fact that an algorithm must have a finite number of steps in its execution. the
presence of endless (infinite) loops must be avoided

3. An algorithm must be effective; this means that an algorithm must provide the correct
answers at all times

4. An algorithm must be general; this means that an algorithm must solve every instance
of a problem

5
5. Uniqueness: results of each step are uniquely defined and only depend on the input
and the result of the preceding steps.
6. Finiteness: the algorithm stops after a finite number of instructions are executed.
7. Output: the algorithm produces output
Conclusion

This section has highlighted the properties of algorithms to the learner who is new to the
concept of data structure and algorithm. It also alerts the learner on what to do to ensure the
expected outcomes can be obtained when the algorithm is implemented in any computer
programming language. This will ensure the learner comes up with very correct and accurate
algorithms for solving any task at hand.

Assessment

1. With the aid of an appropriate example, explain the characteristics of


algorithms.

ACTIVITY 3 - USING PSEUDO-CODES AND FLOWCHARTS TO


REPRESENT ALGORITHMS
Introduction

The student will learn how to design an algorithm using either a pseudo code or
flowchart. Pseudo code is a mixture of English like statements, some mathematical notations
and a selected keyword from a programming language. It is one of the tools used to design and
develop the solution to a task or problem. Pseudo codes have different ways of representing the
same thing and emphasis is on the clarity and not style.
Pseudo Code

Is an informal high-level description of the operating principle of a computer program or


other algorithm. It is a procedure for solving a problem in terms of the actions to be executed
and the order in which those actions are to be executed.

Pseudo code uses the structural conventions of a programming language, but is


intended for human reading rather than machine reading. Typically omits details that are not
essential for human understanding of the algorithm, such as variable declarations, system-
specific code and some subroutines. The programming language is augmented with natural
language description details, where convenient, or with compact mathematical notation.
The purpose of using pseudo code is that it is easier for people to understand than
conventional programming language code, and that it is an efficient and environment independent
description of the key principles of an algorithm. It is commonly used in textbooks and scientific
publications that are documenting various algorithms, and also in planning of computer program
development, for sketching out the structure of the program before the actual coding takes place.

6
Example

In the following example, the pseudo code is on program that can add 2
numbers together then display the result.
Solution
Initialize sum to 0.
Calculate sum = num1 + num2
Display sum
Flow chart
Flowchart is a type of diagram that represents an algorithm, workflow or process. it shows
the steps in the form of boxes of various kinds and their order by connecting them with arrows. The
diagrammatic representation illustrates a solution model to a given problem. Flowcharts can be used
in the analysis, design, documenting or managing a process or program in various fields. They are
also used in designing and documenting complex processes or programs.

Flowchart building blocks

1. Start and end symbols. They are represented as circles, ovals or rounded (fillet)
rectangles. They contain the word “Start” or “End”, or another phrase signaling the start
or end of a process, such as “submit inquiry” or “receive product”.

Start End

2. Arrows. They show “flow of control”. For example an arrow coming from one symbol and
ending at another symbol represents that control passes to the symbol the arrow points
to. The line for the arrow can be solid or dashed. The meaning of the arrow with dashed
line may differ from one flowchart to another and can be defined in the legend.

3. Generic processing steps. These are represented as rectangles.

4. Subroutines. They are represented as rectangles with double-struck vertical edges. They are
used to show complex processing steps which may be detailed in a separate flowchart.

7
5. Input/Output. These are represented as a parallelogram.

6. Prepare conditional. These are represented as a hexagon. They normally show


operations which have no effect other than preparing a value for a subsequent
conditional or decision step.

7. Conditional or decision. These are normally represented as a diamond showing where a


decision is necessary. They commonly test a Yes/No question or True/False condition. It
has two arrows coming out of it, usually from the bottom point and right point, one
corresponding to Yes or True, and one corresponding to No or False.

No

Yes

8. Junction symbol. It’s generally represented with a black blob, showing where multiple
control flows converge in a single exit flow. A junction symbol will have more than one
arrow coming into it, but only one going out.

9. Labeled connectors. They are represented by an identifying label inside a circle.


Normally used in complex or multiset diagrams to substitute for arrows. For each label,
the “outflow” connector must always be unique, but there may be any number of “inflow”
connectors. In this case, a junction in control flow is implied.

A B C

8
10. Concurrency symbol. It is normally represented by a double transverse line with any
number of entry and exit arrows. They can be used whenever two or more control flows
must operate simultaneously. The exit flows are activated concurrently when all of the
entry flows have reached the concurrency symbol. A concurrency symbol with a single
entry flow is a fork; one with a single exit flow is a join.

Note: All processes should flow from top to bottom and left to right
EXAMPLE
Problem: Calculate and report the grade-point average for a class
Discussion: The average grade equals the sum of all grades divided by the number of students
Output: Average grade
Input: Student grades

Processing: Find the sum of the grades; count the number of students;
calculate average
PSEUDO CODE
Program: Determine the average grade of a class
Initialize counter and sum to 0

Repeat while there is more data


Get the next grade
Add the grade to the sum
Increment the counter (increment: add one to)
End Repeat

Calculate average = sum/counter


Display average

9
FLOW CHART

Figure 1. The Average of a Class Flowchart


Conclusion
This section covered the algorithm development tools, that is, the pseudo codes, flowcharts
and how to design and develop them. This tools are not hinged to any programming language but
can be implemented in any language of choice. Basically this are the initial steps of designing a
program for any given task. Examples for both are given to try and show the learner how they look
like. On the flow charts, it has further included the building blocks of a flow chart.

10
Assessment
1. Give two important differences between the flowchart and the pseudocode
2. Give two examples of selection control structures. Use flowchart
3. Draw the different types of symbols used in the flowchart. Explain the
role of each types.

UNIT SUMMARY

In this unit, you have seen what an algorithm is. Based on this knowledge, you should
now be able to characterize an algorithm by stating its properties. We have explored the
different ways of representing an algorithm such as using human language, pseudo codes and
flow chart. You should now be able to present solutions to problems in form of an algorithm”.

Unit Assessment
The following section will test the learners understanding of this module
Answer the following questions
1. Design an algorithm to add two numbers and display result.
2. Write pseudocode to input the dimensions of a rectangle and print
area and perimeter
3. Give an algorithm to find the maximum number.

Unit Readings and Other Resources


Lecture Notes, Data Structures and Algorithms - http://gg.gg/lmyyo

Answers
1. An algorithm to add two numbers can be written as below;
Step 1 Initialize sum to 0
Step 2 Get values of A and B

Step 3 Calculate sum = A + B


Step 4 Display sum
Step 5 End

11
2. The pseudocode is:
Read length, width
Calculate area = length * width
Calculate perimeter = 2*(length + width)
Display area and perimeter
3. The algorithm is:

Step 1 Pick up the first number and suppose it is maximum.


Step 2 Pick up a number from the remaining numbers.
Step 3 Compare the picked number and current maximum.
Step 4 Throw out the smaller and suppose the larger one as the new maximum.
Step 5 Repeat 2~4 until there’s no number remaining.
Step 6 Output the current maximum.

12
UNIT 2
RECURSION

INTRODUCTION

This unit introduces the learner to the processes that repeat themselves in a self-similar
way. The processes can either call themselves directly or indirectly during their execution. The
unit will enable the learner to understand the recursion process and solve problems that are
recursive in nature.
OBJECTIVES
Upon completion of this unit the learner should be able to:
1. develop algorithms for recursive programs
2. implement recursive formulation of a problem
3. explain recursion as a form of iteration

KEY TERMS

Recursion. This is a process whereby a method calls itself so as to achieve


repetitious

Base case. Is a boolean test at which the recursion ceases to “wind up” and starts
to “unwind”.

Recursive step. Is a method call which causes the recursion to “repeat” on each
successive iteration (unless the base case is reached).

LEARNING ACTIVITIES
ACTIVITY 1 - RECURSIVE ALGORITHM
Introduction

The learners are introduced to recursive processes learn how a method calls itself in
order to achieve repetitious behavior. By using recursive algorithms, the learners will be in a
position to solve problems of this nature.
Recursive Algorithm

Recursion is defined as a method of solving problems that involves breaking a problem


down into smaller and smaller sub problems until you get to a small enough problem that it can
be solved trivially. simply this is done by the program calling itself to repeat the same steps.
Recursive problems are solved by developing a recursive algorithm. A recursive algorithm is
defined as an algorithm which can call itself with smaller (or simpler) input values, and which obtains
the result for the current input by applying simple operations to the returned value for the

13
smaller (or simpler) input. Thus, if a problem can be solved by utilizing solutions to smaller
versions of the same problem, and the smaller versions reduce to easily solvable cases, then it
means that one can use a recursive algorithm to solve that problem.
The recursive method comprises the following;
1. A base case where the recursion stops and begins to unwind, and
2. A recursive step where the method calls itself

A point worth noting is that a recursive algorithm is said to wind up until the base case is
reached and then unwinds. During the unwinding process, further statement programs
“pending” may be called.

Recursion is a mechanism whereby repetition can be achieved using a method that


continues to call itself until some terminating value is reached, i.e. without using some specific
repetition construct.

Example 1
The factorial function “!”.
Its definition is:

Thus, by repeatedly using the definition, we can work out that

function factorial is:


input: integer n such that n >= 0
output: [n × (n-1) × (n-2) × … × 1]
1. if n is 0, return 1
2. otherwise, return [ n × factorial(n-1) ]
end factorial

Again, notice that the definition of “!” includes both a base case (the definition of 0!) and
a recursive part.

14
Laws of Recursion
Recursive algorithms must obey the following laws;
1. A recursive algorithm must have a base case.
2. A recursive algorithm must change its state and move toward the base case.
3. A recursive algorithm must call itself, recursively
An explanation of the laws is as follows;

First law; -The base case allows the algorithm to stop recursing, i.e a problem small
enough to solve directly.
Second law; - a change of state occurs moving the algorithm towards the base case.
This occurs when a change of state takes place and which is best illustrated when a data
modification happens.
Finally; Third law; - the algorithm must call itself.

Example 2
Find the maximum value in a list of numbers;
The solution to the problem would look like the following

function find_max is:


input: integers in the list[ ] and n such that n >= 0
output: max(list[0], list[1], list[2]..., list[n])
1. if n is 1, return list[0]
2. otherwise, return max(list[n],find_max(list, n-1))
end find_max

Example 3
Adding numbers in the list;
The solution will be something like

function list_sum is:


input: integers in the list[ ] and n such that n >= 0
output: list[0] + list[1] + list[2] +...+ list[n]
3. if n is 0, return list[n]
4. otherwise, return list[n] + list_sum(list, n-1)
end find_max
15
Conclusion

This unit introduced the learner to the recursive algorithms. Examples were used to
teach the learner how to write recursive algorithms that can solve self-repeating functions. The
examples used in the teaching of recursion are also not hinged on any computing language and
can thus apply across all the languages. Finally, the learners were introduced to the laws of
recursion.

Assessment
1. List the three key features of a recursive algorithm.
2. Write an algorithm that can multiply two numbers using recursion

UNIT SUMMARY

In this unit, recursion was introduced. you should now be in a position to describe
recursion and where it can be applied. The laws that a recursive algorithm must obey were also
introduced as well as condition necessary for a process to be said to have recursive. Examples
accompanied these explanations were provided where necessary.

Unit Assessment
Check your understanding!
Class exercise
Instructions
Answer the following questions on recursion
1. Write an algorithm for finding the k-th even natural number
2. Explain how a recursive algorithm works

Unit Readings and Other Resources


Lecture Notes, Data Structures and Algorithms - http://gg.gg/lmyyo

16
Answers
1. The algorithm is:
function even_num(positive integer k):
Input: k , a natural number
Output: k-th even natural number (the first even being 0)
if k = 1, then return 0;
else return (even_num(k-1) + 2);

2. The result of one recursion is the input for the next recursion. The repletion is in the self-
similar fashion. The algorithm calls itself with smaller input values and obtains the results
by simply performing the operations on these smaller values. Generation of factorial,
Fibonacci number series are the examples of recursive algorithms

17

You might also like