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

Data Structures and Algorithms - Chapter 1 - LMS2020

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 28

DATA STRUCTURES

AND ALGORITHMS
MODULE 1 : ADTS AND RECURSION
LEARNING OUTCOMES

LO1. Explain and discuss the need for efficiency in


data structures and algorithms.
ABSTRACT DATA TYPES

• Data – the information gathered to express knowledge about a world or an


environment.
• Operations – to discuss, explain and calculate things about this environment.
• Abstract data type (ADT) – is a model or description of a type of data. It
identifies the components and properties of a type of data, as well as the
operations performed on the data of this type.
THREE STAGES OF ADT
• Specification – This is an identification of the data’s components, properties, relationships among its components,
and the operations performed on the data in the problem.
• It identifies what are involved in the problem and not how to solve the problem.
• Machine independent and programming language-independent.

• Representation – This design aims to show relationships among the components of the data storage. The result
is called a data structure.
• This is a design on how to store instances of the ADT.

• Implementation – This is a procedural description of how each operation is called out using the data structure.
• Each procedural description is an algorithm. Algorithms can be written using pseudocode or a specific programming
language.
EXAMPLE #1:

Ana Belen Kulas Maria Pedro


83 92 86 94 75

Fig. 1: Five nodes connected sequentially to show ordering (student’s name and
average grade)
A node is a container of data. It represents a group of data and separates data from other
data.
are often drawn in diagrams as closed figures such as circles and rectangles.
these nodes are then connected by lines to indicate some kind of relationship among
the nodes.
ADT can also be represented by a data structure that uses two
parallel arrays indexed from 1 to 5.

Index 1 2 3 4 5
name Ana Belen Kulas Maria Pedro

Index 1 2 3 4 5
Avg grade 83 92 86 94 75
The following algorithm can be used to implement the operation to
determine the topnotcher:

1. Initialize the ixMax variable with 1, to index the first student and grade.
2. For each of the other values in the array of grades.
3. if it is higher than the grade indexed of this higher grade
4. Return the name of the student indexed by ixMax from the array of
name as the topnotcher.
DATA STRUCTURE
Data structures show relationships among the data items using primitive
structures or other data structures available in a programming environment to
facilitate operations of the ADTs.
Data structures are programmed using features of programming languages. Simple
data structures are programmed using primitive data types while complex
data structures use composite or user-defined data types.
The programming language may also provide composite data types such as
the following:

Arrays – These allow data of the same type to be organized in cells. These cells are indexed from 1 to a given
size, or from 0 to a given size minus 1. Each array is stored in a contiguous part of memory allowing direct
access to each cell.
Strings – These are sequence of characters. Each string has a length. Some operations can be implemented by
the programming language such as getting substrings, converting to upper case, etc.
Structs – These allow data to be grouped as a single data type. Instances of structs can be created. Data within
the struct can be individually referenced.
Classes – These allow data and operations to be defined as a single data type. Instances of classes are called
objects. Classes are available in OOP languages. The fields of a class represent the data structure while the
methods of a class implement the algorithms.
ALGORITHMS
A computational problem is solved by performing a finite set of instructions called an algorithm.
Algorithm is a well-defined procedure that processes input values to generate desired output values to solve
a problem.
The following are some properties of a good algorithm:
Has input - has an instance of the problem to be solved.
Has output – produces results to solve the given instance of the problem.
Definite – Each step is unambiguous. These is only one way to interpret each step that is precisely specified.
Effective – Each step executes as expected in an finite amount of time.
Finite – terminates after producing the output in a finite number of steps.
Correct – produces the desired output corresponding to given input.
General – correctly solves the problem for all valid problem instances.
Efficient – solves the problem with less resources such as time and space.
An algorithm is often written in pseudocode before it is implemented in a specific programming
language.
Pseudocodes combine English with basic programming language constructs.
Data structures, together with algorithms, form programs.
Algorithms are implemented as methods or procedures in a programming language.
Some algorithms are functions. They perform computations on their inputs and return values.
Integer sum(integer x, integer y) {
1 integer z = x + y
2 return z
}
It could be called as part of a statement like:
Print(“The sum of 24 and 37 is”, sum(24,37))
Some algorithms are subroutines that produce results as side effects;
Example: Algorithm “sum” below is a subroutine.

1 z=0 //z is a global variable


2 sum(24,37)
3 print(“The sum of 24 and 37 is”,z)
4 end
5
6 void sum(integer x, integer y){
7 z=x+y
8 }
RECURSION

• Each execution of a loop’s body is called an iteration.


• An algorithm that solves a problem using iteration is an iterative algorithm.
Element of Recursion
A recursion defines, proves, or solves something in terms of smaller instances, versions, or parts
of that something.
A recursive definition defines a concept recursively. Mathematical induction is a technique
that uses recursion to prove statements. Recursive algorithms solve problems using recursive
procedures.
RECURSION

Every recursion has two parts:


1. The basis – which gives direct definition, proof, or solution to the smallest versions; and
2. The recursive step – which defines, proves, or solves something in terms of smaller
versions of itself.
RECURSION

Ex. The factorial, n!, of n≥0, may be defined recursively as follows:


Basis: if n = 0, n! = 0! = 1
Recursive Step: if n > 0, n! = n x (n – 1)!
This is often written mathematically as follows:

1 𝑖𝑓 𝑛 = 0
n!=
𝑛𝑥 𝑛−1 ! 𝑖𝑓 𝑛 > 0
To compute fo n!, the value of (n – 1)! Must be computed first. (n – 1) is a simpler or smaller part of
the factorial of n. Thus for 4!, the computation proceeds as follows:
RECURSION
4! = 4 x 3!
= 4 x (3 x 2!)
= 4 x (3 x (2 x 1!))
= 4 x (3 x (2 x (1 x 0!)))
= 4 x (3 x (2 x (1 x 1)))
= 4 x (3 x (2 x 1))
= 4 x (3 x 2)
=4x6
= 24
RECURSIVE ALGORITHMS

The Recursive algorithm can be translated directly from the recursive definitions.
Ex. The following pseudocode computes the factorial of n using the recursive definition in
example 7:
Integer factorialR(n: a non-negative integer) {
1 if n = 0 then return 1 // basis
2 Else return n x factorialR(n – 1) // recursive step
}
RECURSIVE ALGORITHMS

Then the output below is produced:


The factorial of 4 is 24
Compare the factorialR with the iterative factorial function below:
Integer factorial(n ≥ 0: integer){
1 p=1
2 for i = n downto 1
3 p= p x i
4 return p
This is less straightforward than the recursive algorithm. It is based on the iterative formula n! = n
x (n-1) x (n-2) x …x 1 if n ≥ 1 and the definition that 0!=1.
RECURSION
Ex. The Fibonacci sequence is naturally defined recursively. Let Fib(n) denote the nth term of
the Fibonacci sequence with n ≥ 0. Then,
Basis: Fib(0)=0 and Fib(1)=1
Recursive Step: Fib(n)=F(n-1)+F(n-2), if n > 1
Mathematically,

𝑛 𝑖𝑓 𝑛=0 𝑜𝑟 1
𝐹𝑖𝑏 𝑛 = 𝐹𝑖𝑏 𝑛 − 1 + 𝐹𝑖𝑏 𝑛 − 2 𝑖𝑓 𝑛 > 1
The Fibonacci sequence is 0, 1,1,2,3,5,8,13,21,… The value of Fib(4) is 3. The Fibonacci
sequence requires two basis values since the recursive step refers back to the previous two
terms. Repeated application of this step ends with the two lowest n’s that can be reached:
namely 0 and 1.
First, the terms are numbered from 0 onwards like this:
n= 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ...

xn = 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 ...

So term number 6 is called x6 (which equals 8).

So we can write the rule:


The Rule is xn = xn-1 + xn-2
where:
 xn is term number "n"
 xn-1 is the previous term (n-1)
 xn-2 is the term before that (n-2)
Example: term 9 is calculated like this:
x9= x9-1 + x9-2
= x8 + x7
= 21 + 13
= 34
Ex. The following pseudocode computes the nth term of the Fibonacci sequence recursively using the recursive definition in
Previous (Fibonacci Example) example:
Integer fibR( n ≥ 0: integer) {
1 if n =1 or 0 the return n // basis
2 Else return fibR(n-1)+ fibR(n-2) // recursive step
}

The reference to fibR(n-1) and fibR(n-2) result in two recursive calls with parameters (n – 1) and (n – 2) respectively.
Suppose fibR is called for the first time by the statement:

print(“The 4th term of the Fibonacci sequence is”, fibR(4))

Compare fibR with the iterative Fibonacci function fib below:


integer fib(n ≥ 0: integer) {
1 if n=0 then return 0
2 else x= 0 // initially, x is Fib(0)
3 y= 1 // initially, y is Fib(1)
4 for i=2 to n
5 z=x+y // Fib(i)
6 x=y // the new 2nd to the last term known
7 y=z // the new last term known
8 return y
}
Writing Recursive Algorithm
Writing recursive algorithms is easy when the recursive definition is given, if it is not, the
recursive definition or recurrence relation is often determined first.
However, figuring out the recursive step is the biggest challenge. Answering the following
questions can help overcome this challenge:

In the process of solving the problem for a large input, is the problem also being solved for a
subset of the input or for
a smaller input?

How can the problem be broken down into one or more smaller versions of the problem?

How can the solution for the problem on a subset of the input be used to solve the problem
on the entire input?
THE TOWER OF HANOI PROBLEM
There are three posts: the left, the middle, and the right. n ≥ 0 disks of increasing radii are resting on the left
post. The other two posts are empty. The objective is to move the n disks to the right post. Only one disk
may be moved at a time from one post to another, and no larger disk can be placed on top of a smaller disk.
How should the disk be moved to accomplish this task
The mission is to move all the disks to some another tower without
violating the sequence of arrangement. A few rules to be followed for Tower
of Hanoi are −

 Only one disk can be moved among the towers at any given time.
 Only the "top" disk can be removed.
 No large disk can sit over a small disk.
PROS AND CONS OF RECURSION

Recursion provides an alternative way to solve a problem. It is useful when the problem
to be solved involves a countable number of items (eg. A number n, n characters, a set
with n elements, an array with length n, etc.
The biggest obstacle in writing recursive algorithms is coming up with a recurrence
relation for a solution to the problem. It often requires inventiveness to identify a
subproblem whose solution can be manipulated to solve the original problem.
SUGGESTED READINGS:
READ THE POSTED PDF FILES

REFERENCES AND RESOURCES:


DATA STRUCTURES AND ALGORITHMS IN JAVA, 6TH EDITION
2014, M. GOODRICH, R. TAMASSIA, M. GOLDWASSER
JAVA: DATA STRUCTURES AND ALGORITHMS, ADAM DROZDEK,
2008, CENGAGE LEARNING ASIA PTE LTD.
END OF THE MODULE 1

You might also like