0% found this document useful (0 votes)
102 views68 pages

Cc103data Structure Module Not For Sale With Cover

This document provides an introduction to data structures and algorithms using Python. It defines data structures as how data is organized in memory and algorithms as sets of instructions to process data. The document discusses primitive data types in Python like integers, floats, booleans and strings. It also covers non-primitive data structures like arrays, stacks, queues, linked lists and trees. The document explains how to install Python on Windows and use the QPython mobile app to write and run Python programs on Android phones.

Uploaded by

Kayce R. Tungol
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
102 views68 pages

Cc103data Structure Module Not For Sale With Cover

This document provides an introduction to data structures and algorithms using Python. It defines data structures as how data is organized in memory and algorithms as sets of instructions to process data. The document discusses primitive data types in Python like integers, floats, booleans and strings. It also covers non-primitive data structures like arrays, stacks, queues, linked lists and trees. The document explains how to install Python on Windows and use the QPython mobile app to write and run Python programs on Android phones.

Uploaded by

Kayce R. Tungol
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

1
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

UNIT I. INTRODUCTION TO DATA STRUCTURE AND


ALGORITHM

Overview

This unit enlightens the students about the basics of data structures and algorithms. It
also introduced the Python programming and showed how the primitive data structures are
implemented. The mobile engine for Python is also present to familiarize the students. Array
and its operations are also discussed.

Learning Objectives
In this unit, I will learn:
1. To define data structure;
2. To distinguish data structure from algorithm;
3. Understand the behavior of primitive from non-primitive data structures;
4. Implement array to python programs; and
5. Appreciate Python programming and its data structures using mobile phone.

Setting Up
1. Assume you have a plate of spaghetti. Can you enumerate your procedures on how you
eat this messy food?
2. You did laundry, and it was already dry. How can you manage those clean clothes?
3. If you have a ten stack of chairs, how can you remove the chair number 6?

Lesson Proper

Data Structure Overview

The data structures deal with how the data is organized and stored in the memory when
the program processes it and the algorithms are used to work data in these structures. It also
refers to a system for storing data. In other words, a data structure is an arrangement of data in
computer memory in such a way that it can quickly render the data accessible to the processor
for the necessary calculations.
An Algorithm is a set of instructions to process the data for a specific purpose.
Algorithms are implemented in the form of methods or functions or routines. An efficient
algorithm will be used to solve the problems quickly. One criterion of efficiency is the
algorithm's time, and another could be the memory it takes at run time.(
www.hashirharis.wordpress.com/category/python/)

Data Types

“The data structures are actually an implementation of Abstract Data Types or ADT. This
implementation requires a physical view of data using some collection of programming
constructs and basic data types.

2
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

• Data types are attributes or characteristics of data. It classifies data according to its
purpose.
• Data structures can have two categories, the primitive and non-primitive.
• The primitive is the simplest form of data representation, whereas the non-primitive is
more advanced.

Overview of Data Structure (Courtesy of DataCamp)

Primitive Data Structures

Jaiswal(2017) stated that the primitive data structures are the basic data structures. They
are the building blocks for data manipulation and contain pure, simple values of a data.

The following are the four primitive variable types of Python:

3
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

Characteristics of Non-Primitive Data Structures

Array

Courtesy from programiz.com

Stack

Queue

4
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

Data Structures in Python

The Python programming language was originally developed by Guido van Rossum in the
early 1990s, and has since become a prominently used language in industry and education. The
second major version of the language, Python 2, was released in 2000, and the third major
version, Python 3, released in 2008.
Python is formally an interpreted language. Commands are executed through a piece of
software known as the Python interpreter. The interpreter receives a command, evaluates that
command, and reports the result of the command.
For Python, source code is conventionally stored in a file named with the .py suffix (e.g.,
hello.py).

Python Applications

Python can be used to different aspects and scenarios. The following are the list of
different ways where you can apply Python.

1. Web and Internet Development


2. Desktop GUI Applications
3. Scientific and Numeric
4. Software Development
5. Education
6. Business Applications
7. Database Access
8. Network Programming
9. Games and 3D Graphics

Advantages of Python

There are many reasons you need to study Python, and the list below are some of its
advantages:

• Python is Interactive: You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.
• Python is Interpreted: Python is processed at runtime by the interpreter. You do not
need to compile your program before executing it.
• Python is Object-Oriented: Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
• Python is a Beginner’s Language: Python is an excellent language for the beginner-
level programmers and supports the development of a wide range of applications
from simple text processing to WWW browsers to games.
(https://hashirharis.wordpress.com/category/python/)

5
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

Built-in Data-structures in Python

User-defined Data-structures:

Arrays: It is similar to Lists, but the difference is it can store single element/datatype
Stack: Linear LIFO (Last-In-First-Out) Data structure
Queues: Linear FIFO (First-In-First-Out) data structure
Trees: Non-Linear data structures having a root and nodes
Linked Lists: Linear data structures that are linked with pointers
Graphs: Store a collection of points or nodes along with edges
Hash Maps: It is the same as Dictionaries.

6
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

Installing Python

Windows Installation

• Open a Web browser and go to https://www.python.org/downloads/.


• Download the
• Run the downloaded file. When the downloaded file is running the Python wizard
will show and process. It takes minutes to finish this wizard and you must set to the
default settings and wait until the installation is done.
• Click this icon

Python shell for instant calculations

7
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

Python script for coding

Save your file to your folder Python34/ and use .py extension name file.

How to Run

8
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

output

Python Engine for Mobile Phone

Due to pandemic situation, online learning and mobile learning are needed. Instead of using
the school computer laboratory, it is the new normal to use alternative device to sustain the
quality of education you need. In our case, when the students do not have their own laptop or
desktop, your mobile phone with QPython and Pydroid are recommended for you to perform
your laboratory exercises. QPython is the Python engine for android which contains some
amazing features such as Python interpreter, runtime environment and editor. It makes it easy
for you to use Python on Android and also it is open source or free. All you need to do is to
download it in https://apkpure.com/qpython-3l-python-for-android/org.qpython.qpy3

For different usage scenarios, QPython has two branches, namely QPython Ox and 3L.
QPython Ox is mainly aimed at programming learners, and it provides more friendly features
for beginners. The QPython 3L is mainly for experienced Python users, and it provides some
advanced technical features.

Here are some features of QPython 3L found in https://apkpure.com:


• Offline Python 3 interpreter: no Internet is required to run Python programs
• It supports running multiple types of projects, including: console program, SL4A
program, webapp program
• Convenient QR code reader for transferring codes to your phone
• QPYPI and a custom repository for prebuilt wheel packages for enhanced scientific
libraries, such as numpy, scipy, matplotlib, scikit-learn etc
• Easy-to-use editordx87c0020K./
• INTEGRATED & EXTENDED SCRIPT LAYER FOR ANDROID LIBRARY
(SL4A): IT LETS YOU DRIVE THE ANDROID WORK WITH PYTHON
• Good documentation and customer support

9
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

How QPython 3L works?

1. Install the QPython 3L App available in https://apkpure.com/qpython-3l-python-for-


android/org.qpython.qpy3.

2. From your phone, Click the QPython icon and the new screen will show

3. Click Console if you want an instant calculations and Click Editor if you want to type
your code. To save the file, Click the icon Save, the screen below will show.

4. To run the file, Click the Play button and you will see the screen below
.

10
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

Python Identifiers

“A Python identifier is a name used to identify a variable, function, class, module or other
object .”( www.studocu.com/de/document/wheaton-college/computer-literacy/uebungen/python-
tutorial/2712597/view).

• The identifier is also starts with a lowercase letter or capital letters or it has an
underscore (_) followed by letters or numbers (0 to 9).
• Punctuation characters like %, @, and $ within identifiers are not valid.89=]]
• It is also case sensitive programming language where Power and power are two
dissimilar identifiers” (”hashirharis.wordpress.com/category/python/).

Some Rules for Python identifiers

• Class names begins with the capital letter and other identifiers start with a lowercase
letter.
• An identifier with a single leading underscore specifies as private identifier.
• An identifier with two leading underscores specifies a strongly private identifier.
• The identifier with two trailing underscores ends defined as special name”(

Reserved Words

The following are the Python reserved words and cannot be used as constant or variable or
any other identifier names.

“Lines and Indentation of Python

11
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

• Python don’t have braces. The blocks of code are signified by line indentation which
is strictly required.
• The number of spaces in the indentation is variable, and all statements must be
indented all within the block.

Quotation in Python

• It accepts single (‘), double (“) and (‘’’ or “””) quotes to represent string literals, as
long as the same type of quote starts and ends the string.
• The triple quotes are used to span the string across multiple lines. The following
examples are valid:

How to use Comments in Python?

• A hash tag sign (#) is used to begin in a comment. All typescripts/characters after the
# and ip to the end of the physical line are part of the comments.

12
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

Output:

13
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

14
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

Python Strings

Strings are identified as a contiguous set of characters represented in the quotation marks.

Python allows for either pairs of single or double quotes. “Subsets of strings can be taken
using the slice operator ([] and [:]) with indexes starting at 0 in the beginning of the string and
working their way from -1 at the end. The plus (+) sign is the string concatenation operator and
the asterisk (*) is the repetition operator(www.studocu.com/de/document/wheaton-
college/computer-literacy/uebungen/python-tutorial/2712597/view).

Try This!

Output:

15
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

Array

An array is a data structure, which can store a fixed-size collection of elements of the same
data type. An array is used to store a collection of data, but it is often more useful to think of
an array as a collection of variables of the same type.

Python can also handle containers with specified data types. Array can be handled in python
by module named “array “. It can be useful in manipulating a specific data type value.(
www.datacamp.com/community/tutorials/data-structures-python)

Operations on Array

1. array(data type, value list) :- This function is used to make an array with data type and
value list specified in its arguments.

2. append() :- This function is used to add the value at the end of the array in its arguments.

3. insert(i,x) :- This function is used to add the value at the location specified in its argument.

Initializing array with array values

Try This!

16
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

Output:

4. pop() :- This function removes the element at the location mentioned in its argument, and
returns it.

5. remove() :- This function is used to remove the first occurrence of the value mentioned in
its arguments.

6. index() :- This function returns the index of the first occurrence of value mentioned in
arguments.

7. reverse() :- This function reverses the array.

Try This!

Output:

17
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

References

1. Urooj, Wajiha.How to Implement Data Structures and Algorithms in Python. Updated


last January 17, 2020 retrieved from http://www.edureka.co/blog/data-structures-and-
algorithms-in-python
2. Jaiswal, Sejal.Python Data Structures Tutorial. Updated December 8, 2017
retrieved from https://www.datacamp.com/community/tutorials/data-structures-
python
3. www.tutorialsduniya.com/notes/data-structures-notes
4. www.tutorialspoint.com/python/python_basic_syntax.htm
5. www.jiwaji.edu/pdf/ecourse/computer_sci_app/PGDCA Python Notes UNIT - 1.pdf
6. www.hashirharis.wordpress.com/category/python/
7. www.tehapps.com/basic-syntax-in-python/
8. https://blog.csdn.net/qq_27009517/article/details/87273744

18
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

NAME: ___________________________________DATE:_____/_____/2020__
SECTION:_BSIT-__________________________SCORE:_______/30_______
QUIZ

GENERAL INSTRUCTION: STRICTLY NO ERASURES. Any form of erasure will be


considered wrong.

ESSAY. Write the answer on the space provided.

1. Explain why data structures are important in programming?

_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
2. I discovered that_________________________________________________

_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
3. How does Python implement data structures?

_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________

19
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

NAME: _____________________________ DATE: _____/_____/2020__


SECTION:_BSIT-_______________________SCORE:_______/30_______
LABORATORY EXERCISE # 1: String

Direction: Make the output below using the string


str =” Hello Students of Data Structure and Algorithms”. Send the image of your script/code
and its output.

Hello
Students
Of
Data Structure
and Algorithms
Hello Students of Data Structure and Algorithms

20
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

NAME: _____________________________ DATE: _____/_____/2020__


SECTION:_BSIT-_______________________SCORE:_______/30_______
LABORATORY EXERCISE # 4: Array

Direction: Send the image of your script/code and its output.

Requirements:

1. Create an array with the following content:


“one”,” two”, “three”, “four”
2. Insert “five” in between of “two” and “three”
3. Delete “four”.
4. Display the array content

21
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

UNIT 2. LINKED LIST, STACK AND QUEUES

Overview

This unit kills four birds with one stone: You develop a strong understanding of
the stacks and queues, strengthen your abilities in working with arrays, and develop a
moderate facility with linked lists.

Learning Objectives
At the end of the lesson, you are expected to:
1. create a program using array-based lists;
2. create programs using linked lists; and
3. create a program using doubly linked list.
Setting-Up
1. What linked lists are and when you should use them
2. How to use collections.deque to implement queues and stacks
3. How to implement your own linked list and node classes, plus relevant methods
4. What the other types of linked lists are and what they can be used for

Lesson Proper

Linked list
Linked lists are an organized set of items. Linked lists are distinct from lists because they
retain items in memory. Although lists use a single block of memory to store their data
references, related lists store references as one of their own components.
Main Concepts
Each element of a linked list is called a node, and every node has two different fields:
1. Data contains the value to be stored in the node.
2. Next contains a reference to the next node on the list.
Here’s what a typical node looks like:

22
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

A linked list is a
collection of nodes. The first node is called the head, and it is used as the starting point for
any iteration through the list. The last node must have its next reference pointing to None to
determine the end of the list. Here’s how it looks:

Practical Applications
Linked lists represent a variety of real-world purposes. These will be used for the creation
of queues or stacks (spoiler alert!) as well as diagrams. These are often beneficial for even more
complicated functions, such as life-cycle management for an application to operating system.
Queues or Stacks
Queues and stacks only vary in how items are recovered. You'll need a First-In / First-Out
strategy (FIFO) with a line. This assumes the first item to be recovered added in the chart is the
first item to:

You can see the front and rear components of the queue in the image above. These can move
to the far end as you add new items to the list. They'll be pulled from the front of the list as you
grab objects.
You use a Last-In / Fist-Out method (LIFO) for a stack, implying the last item placed in the list
is the first one to be retrieved:

23
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

Within the example above it indicates that at the bottom is the first element placed on the
stack (index 0), and at the top is the last element placed. The last item inserted (at the top) would
be the first to be retrieved because stacks use the LIFO method.
One of the most convenient ways to implement those data structures is to insert and retrieve
elements from the edges of queues and stacks, linked lists.

Graphs
Graphs can be used to display object relationships, or to represent different network types.
A graphic depiction of a graph, for example — say a directed acyclic graph (DAG)—might
look like this:

24
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

There are different methods of applying graphs such as the above, but one of the more
common is to use an adjacency chart. An adjacency list is a set of linked lists in which each
graph vertex is placed alongside a selection of linked vertices:

In the table above, the left column lists every vertex in the line. The right column includes
a set of related lists that store the other vertices in the left column which are bound to the
corresponding vertex. This adjacency list may also be described with a dictum in code:

This dictionary's keys are the vertices of the source, and a list is the meaning for any
word. Typically the set is enforced as a connected array

Implementing graphs using adjacency lists is very effective in terms of both speed and
memory as contrasted with, for example, an adjacency matrix. For this function connected
lists are so useful to execute graphs.
Performance Comparison: Lists vs Linked Lists
Implementing graphs using adjacency lists is very effective both in terms of speed and
memory, as contrasted with an adjacency matrix, for example. Lists attached for this purpose
are so useful for executing graphs.
As the gap in memory use between the lists and the related lists is too small, when it comes
to time complexity, it is easier to concentrate on their output disparities.

25
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

Insertion and Deletion of Elements


List initialization times differ based on how often the current collection has to resize.
Python over allocates array space according to their production. This means that inserting a new
element into a list, depending on whether the existing array needs to be resized, can take
anywhere from Θ(n) to Θ(1)
The same holds true with the elimination of elements from the list. When the array size is
smaller than half the allocated height, otherwise Python must shorten the list. Or, all and all, the
addition or omission of elements from an array has an average complexity of Θ(n). time.
Nonetheless, connected lists are much easier when it comes to adding and removing items
at the beginning or end of the document, where the uncertainty of their duration is constant:
Θ(1) . This performance advantage is why linked lists are so useful for queues and stacks, where
elements are inserted and removed from the edges continuously.
Retrieval of Elements
Lists do even easier when it comes to the lookup of items than connected lists. Lists will
execute this procedure in Θ(1) time if you know which item you want to reach. Trying to do
the same for a connected list will take Θ(n) because to locate the item you need to go through
the entire list.
Nevertheless, all lists and connected lists behave quite similarly when looking for a
particular item, with a time-complexity of range(n). For all instances, to locate the thing you
are searching for, you will iterate over the whole collection.

Introducing collections.deque
In Python, the collections module contains a specific object you can use for linked lists
called deque(pronounced "deck"), which stands for double-ended queue.
Collections.deque uses a connected list application in which items may be viewed, added
or deleted from the beginning or end of a list with constant O(1) output.
How to Use collections.deque
There are quite a few methods which come with a deque object, by default. However,
you'll just focus on a couple of them in this post, mainly for incorporating or deleting
components.
Next, building a related chart. To do so with deque, you may use the following piece of
code:

The code above should generate a list of empty connections. If you want it to be filled in
at development, you may give it an iterable as input:

26
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

You may transfer any iterable as an input while initializing a deque object, including a string
(also an iterable) or a list of objects.
Now that you know how to create a deque object, by adding or removing elements, you
can interact with that. You can create a linked list with abcde and add a new element f like this:

Both append () and pop() add or subtract items from the related list on the right side.
Moreover, you may also use deque to add or delete items from the list easily from the left
side, or head:

27
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

Using the deque object, adding or removing elements from both ends of the list is fairly
straightforward. Then you're able to know how to build a list or a stack using
collections.deque.

How to Implement Queues and Stacks


The biggest distinction between a list and a stack is how items are extracted from each. You
can then figure out how sets should be found. Deque to have both data structures implemented.
Queues
For queues, you want to attach elements to a list (enqueue), and when the timing is right,
you want to delete the longest (dequeue) item in the list. Think of a line at a cool, completely
booked bar, for example. When you wanted to introduce a equal guest seating scheme then you
should start by establishing a queue and introducing people when they arrive:

Now you are in queue with Mary, John, and Susan. Know, because queues are FIFO, the
first person who has joined the queue will be the first one to get out.

28
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

Now assume that some time will pass and that a few tables will become available. You want
to bring people out of the queue in the appropriate order at this point. Then you'd put something
like this:

Each time you call popleft(), (the head item is removed from the linked list, mimicking a
real-life queue.
Stacks
What if then you wanted to build a stack? Ok, the principle is pretty much the same as for
the list. The only difference is that the stack uses the LIFO approach , which means the last
element to be inserted into the stack should be removed first.

If you want this action to be transformed into a stack so you could do something like this:

29
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

References
https://devsday.ru/blog/details/15450
https://www.tuicool.com/articles/fmaMFvY
https://realpython.com/linked-lists-python/
https://flosshub.org/aggregator/sources/13?page=36
https://www.flosshub.org/aggregator?page=115
moz-extension://a071a1d5-e026-4c58-a261-ddf2e8898cdb/html/block_page.html
https://digitechbuy.com/fkeujms/create-circular-queue-in-python.html
https://www.codementor.io/@codementorteam/a-comprehensive-guide-to-
implementation-of-singly-linked-list-using-c_plus_plus-ondlm5azr
https://www.cs.auckland.ac.nz/compsci105s1c/lectures/Bruce/19-LinkedList(3).pdf
https://www.softwaretestinghelp.com/linked-list/
https://smartcatcontrol.com/lgdrlg8/7aff9.php?qp=implement-queue-using-linked-list-
geeksforgeeks
http://core.loyc.net/collections/dlist.html
http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.27.4867
https://www.sitepoint.com/ruby-interview-questions-linked-lists-and-hash-tables/

30
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

NAME: _____________________________ DATE: _____/_____/2020__


SECTION:_BSIT-_______________________SCORE:_______/30_______
LABORATORY EXERCISE # 1:

Direction: Send the image of your script/code and its output.

1. Create a method to retrieve an element from a specific position: get(i) or even llist[i].

31
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

NAME: _____________________________ DATE: _____/_____/2020__


SECTION:_BSIT-_______________________SCORE:_______/30_______
LABORATORY EXERCISE # 2:

Direction: Send the image of your script/code and its output.

1. Create a method to reverse the linked list: llist.reverse().

32
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

UNIT 3. RECURSION
Overview
Often considered one of the more conceptually difficult concepts within the field of
Computer Science is recursion. In this unit, you will take an in-depth look at recursion,
learning the recursive steps, the role that recursion plays in common data structures, and what
happens inside the computer when a recursion function is invoked. By the end of this unit,
you will recognize situations that require recursion and be able to apply it appropriately

Learning Objectives

At the end of the unit, you should have the capacity to:

1. understand the definition of recursion as well as seeing how simple recursive


programs work.
2. demonstrate skills in tracing, analyzing and designing recursive algorithms and
recursive methods.

Setting Up
1. What is recursion?
2. What are the properties of recursion?
3. How to implement recursion in python?

Lesson Proper

What is recursion?
In literal definition, “It is the determination of a succession of elements by operation on one or
more preceding elements according to a rule or formula involving a finite number of steps” (
https://www.merriam-webster.com/dictionary/recursion)

In mathematical, a recursive method is one that is characterized by a base case and itself.

In programming, it is a procedure for taking care of issues by partitioning a bigger problem


into littler instances of the difficulty itself and afterward comprehending the littler, increasingly
unimportant parts. Recursion is a fantastic programming and critical thinking instrument. It can
be utilized with a broad scope of issues from essential customary emphases to the further
developed backtracking issues.

While recursion is amazing, recursive arrangements are not generally the most productive. In a
few occasions, in any case, recursion is the execution of decision as it permits us to handily build
up an answer for a confused issue that may some way or another be hard to unravel.

33
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

Recursive definitions

• It is a fundamental standard in characterizing new thoughts that they not be characterized


circularly.

• However, things being what they are, many programming construct are characterized as
far as themselves

• Luckily, the proper reason for these definitions is to such an extent that no infringement
of the guidelines happens

• These definitions are called recursive definitions and are frequently used to characterize
interminable sets

• This is on the grounds that a thorough list of such a set is inconceivable, so some others
intends to characterize it is required

• Thus, a method is called recursive if the body of the method calls the method itself, either
straightforwardly or by implication.

Properties of recursion
A recursive method can go unbounded like a circle. To maintain a strategic distance from
unbounded running of recursive method, there are two properties that a recursive method
must have :

• Base case − there must be at any rate one base measures or condition, to such an extent
that, when this condition is met the method quits calling itself recursively.

• Progressive action − the recursive calls should advance so that each time a recursive
call is made it comes nearer to the base case.

Method calls and recursive implementation

• What sort of data must we monitor when a method is invoked?

• If the method has boundaries, they should be introduced to their relating contentions

• In expansion, we have to realize where to continue the calling method once the called
method is finished

• Since methods can be called from different methods, we additionally need to monitor
neighborhood factors for scope purposes

• Because we may not know ahead of time what number of calls will happen, a stack is a
progressively proficient area to spare data

• So we can describe the condition of a method by a lot of data, called an actuation record
or stack outline

34
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

• This is put away on the runtime stack, and contains the accompanying data:
– Values of the method’s parameters, addresses of reference variables (including
arrays)
– Duplicates of local variables
– The return address of the calling method
– A dynamic connect to the calling method’s actuation record
– The method’s return value if it is not void
• Every time a method is called, its actuation record is made and placed on the runtime
stack
• So the runtime stack always contains the current state of the method
• As a representation, consider a method fun1() called from main()
• It thus calls method fun2(), which calls method fun3()
• The present status of the stack, with method fun3()executing, is manifest in fig 3.1
• Once fun3()completes, its record is popped, and method fun2()can resume and access
data in its record
• If fun3()calls another method, the new method has its actuation record pushed onto the
stack as fun3() is suspended

contents of the run-time stack when main()


Calls function func1(), func1()calls func2(), and func2()calls func3()

35
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

• The utilization of actuation records on the runtime stack permits recursion to be


executed and taken care of effectively

• Essentially, when a method calls itself recursively, it pushes a new actuation record of
itself on the stack

• This suspends the calling instance of the method, and permits the new
actuation to carry on the procedure

• Thus, a recursive call makes a progression of initiation records for various


cases of a similar method

Tail and non-tail recursion


❖ If the recursive call is the last thing done by the method it is tail recursion.. There is
no compelling reason to keep record of the past state. Essentially, tail recursion is a loop
; it very well may be supplanted by an iterative algorithm to achieve a similar undertaking.
Indeed, much of the time, languages supporting loops should utilize this build instead
of recursion.
❖ If the recursive call is not the last thing done by the method, it is non-tail recursive,.
Subsequent to returning back, there is some something left to assess.

Consider the basic problem of printing the numbers from 1 to n in reverse order. The
iterative solving for this problem is fairly basic when using a loop build. Be that as it may, it
can likewise be settled recursively, that is, utilizing a recursive method. Assume we have applied
the following tail recursive method in python:

Def printrev( n ):
if n > 0 :
print( n )
printrev ( n-1 )

And we call the method with a parameter of 4:


Printrev( 4 ) the current sequential flow of execution is interrupted and control is
transferred to the printrev() function with a value of 4 being assigned to argument n. The body
of printrev() begins execution at the first statement. Since 4 is greater than 0, the body of the
if statement is executed. When the flow of execution reaches the printrev(3) function call, the
sequential flow is once again interrupted as control is transferred to another instance of the
printrev() function. The body of this instance begins execution at the first statement, but this
time with n = 3. Figure 3.2 illustrates the execution of the recursive function as a group of
boxes with each box representing a single invocation of the printrev() function. The boxes

36
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

contain the contents of local variables and only the statements of the function actually
executed. Each recursive call to printrev() is shown inside its own box with the boxes
positioned at the point where the function was invoked.
These recursive calls precede until a value of zero is passed to the method, at which
time the body of the if statement is skipped and execution arrives at the end of the method.
Similarly as with any method call, when execution arrives at the end of the method or the return
statement, execution comes back to the area where the method was initially called. For this
situation, the call to printrev(0) was done using inside the printrev(1) instance. Along these lines,
execution comes back to the principal proclamation after that conjuring. After execution comes
back to the printrev(1) instance, the end of that method is reached and again execution is come
back to the area where that example was conjured. The outcome is a chain of recursive returns or
recursive loosening up back to the original printrev(4) function call.

Rrecursive flow of execution: (a) printrev() and (b) printinc().

What changes would be required to make a recursive method to print the similar
numbers in increasing order instead of reverse order? We can alter the location of the
recursive call to change the action of the recursive solution. Consider a non-tail recursive
print method:

Def printinc( n ):
if n > 0 :
printinc( n-1 )

37
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

print( n )

In this form, the recursive call is done ahead the value of n is printed. The outcome is
a series of recursive calls former to any other action is done. The actual printing of the values
is carry through after each instance of the method returns, as shown in figure 3.2(b).

Indirect recursion

• The earlier topics have concentrated on circumstances where a method, f(), calls itself
recursively which are examples of direct recursion.
• But, in certain circumstances, the method may be invoked not by itself, but by a method
that it calls, forming a chain:
F()→ g() → f()
• This is called as indirect recursion
• the chains of calls may be of discretionary length, such as:
F() → f1() → f2() → ∙∙∙ → fn() → f()
• It is likewise conceivable that a given method may be a part of multiple chains, based
on various calls
• So our past chain may resemble:

Nested recursion

• Another fascinating sort of recursion happens when a method invoke itself and is also
one of the arguments of the call
• Consider this example:

• From this definition, it is given that the method has solutions for n = 0 and n > 4

38
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

• On the other hand, for n = 1, 2, 3, and 4, the method determines a value depend on a
recursive call that requires assessing itself
• This is called nested recursion
• That signifies “recursion inside recursion”.
• Another model is the renowned (or perhaps infamous) ackermann function, defined as:

• first proposed by wilhelm ackermann in 1928 and later changed by rosza peter, it is
portrayed by its fast development

• to get a sense of this development, think about that a(3,m) = 2m+3 – 3, and

• There are (m – 1) 2s in the exponent, so a(4,1) = 216 - 3, which is 65533


• After all, altering m to 2 has a great impact as the value of has 19,729 digits in its
expansion
• As can be deduced from this, the method is splendidly expressed recursively, but quite
a problem to define iteratively

Excessive recursion

• Recursive algorithms will in general show straightforwardness in their usage and are
regularly simple to peruse and follow
• But, this straightforwardness has few downsides
• Generally, as the number of method calls raise, a program undergo some performance
decrease
• Besides, the amount of stack space required increments drastically with the amount of
recursion that happens
• This can prompt program crashes if the stack comes up short on memory
• More frequently, the expanded execution time produce poor program performance as
an example of this, consider the fibonacci numbers

39
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

• They are first referenced regarding sanskrit poetry as far back as 200 bce
• Leonardo pisano bigollo (also known as fibonacci), popularized them to the western
world in his book liber abaci in 1202 ce
• The initial few terms of the sequence are 0, 1, 1, 2, 3, 5, 8, … and can be produced
utilizing the method:

• This disclose us that that any fibonacci number after the initial two (0 and 1) is
characterized as the sum of the two past numbers
• But, as we move further on in the flow, the amount of calculation necessary to produce
successive terms becomes enormous
• This is because every computation ultimately has to depend on the base case to
calculate the values, since no intermediate values are recalled
• The following algorithm executes this definition; once more, notice the modesty of the
code that negates the underlying incapability.

Def fib(n):
if n < 2:
return n
else:
return fib(n-2) + fib(n-1)

• If we apply this to compute fibo(6)(which is 8), the algorithm starts by computing fibo
(4) + fibo (5)
• The algorithm then have to compute fibo (4) = fibo (2) + fibo (3), and lastly the first
term of that is fibo (2) = fibo (0) + fibo (1)= 0 + 1 = 1
• The whole procedure can be shown using a tree to represents the computation:

The tree of calls for fibo(6).

40
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

• Counting the branches, it takes 25 calls to fibo () to compute fibo (6)


• The absolute number of additions needed to compute the nth number can be presented
to be fibo(n + 1) – 1
• With two calls per addition, and the primary call considered, the total number of calls
is 2 ∙ fibo(n + 1) – 1
• values of this are appeared in the following table:

Number of addition operations and number of recursive calls to compute fibonacci numbers

• Notice that it takes right around 3 million calls to determine the 31st fibonacci
number
• This exponential development makes the algorithm inadmissible for anything besides
small values of n
• Fortunately there are adequate iterative algorithms that can be utilized unquestionably
more successfully

Backtracking

• Backtracking is a way to deal problem solving that utilizes a systematic search among
potential pathways to a solution
• As each path is analyzed, if it is determined the pathway isn’t suitable, it is disposed
and the algorithm comes back to the earlier branch with the goal that an alternate path
can be investigated
• Thus, the algorithm must have the capacity to come back to the past position, and
ensure that all pathways are inspected
• Backtracking is utilized in various applications, including compiling, optimization
problems and artificial intelligence
• Below is an example of searching all possible order of arrangements of a given set of
letters.
• When we pick a couple we apply backtracking to confirm if that exact pair has just
been made or not.

41
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

• If not already made, the pair is added to the result list else it is disregarded.

Def perm(list, s):


if list == 1:
return s
else:
return [ y + x
for y in perm (1, s)
for x in perm (list - 1, s)
]

Print(perm (1, ["a","b","c"]))


Print(perm (2, ["a","b","c"]))

• When the code above is performed, it produce the following outputs:

['a', 'b', 'c']


['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc']

When to use recursion?

▪ When a problem can be break down into pace.


▪ The result of one step can be used in a past step.
▪ There is a situation when you can stop breaking down the problem into pace (pace =
recursive call) and return to a past pace.
– Algorithm returns to former pace with a partial solution to the problem (back
tracking)
▪ All of the outcomes together solve the problem.

Consideration for alternatives to recursion:

▪ If a loop will answer the problem just as well

Drawbacks of recursion

• Method invocation can be costly


– Consuming up memory
– Consuming up time
Benefits of recursion

42
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

▪ Basic solution that’s neater (for some problems)


▪ Simpler to envision solutions (for some people and certain classes of problems – typically
require either: non-tail recursion to be implemented or some form of “backtracking”)

Common issues in recursion

▪ These three issues can brought a runtime error


– No base case
def sum (no): when it will stop?

return (no + sum (no - 1))

– No forwarding towards the base case


def summ (num):
The recursive case doesn’t
if (num == 1):
make any forwarding to the
return 1: base (stopping) case
else

return (num + summ (num - 1))

– Using up too many assets (e.g., var declarations) for each function call
Def func(num):

print(num)

amlist = []

for i in range (0, 10000000, 1):

amlist.append("*")

num = num + 1

func (num)

Func (1)

43
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

References:

Drozdek ,adam (2013). Data structures and algorithms in c++ fourth edition

Necaise rance d. (2011). Data structures and algorithms using python

https://www.geeksforgeeks.org/types-of-recursions/

https://www.merriam-webster.com/dictionary/recursion

https://www.tutorialspoint.com/data_structures_algorithms/recursion_basics.htm

44
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

NAME: _____________________________ DATE: _____/_____/2020__


SECTION:_BSIT-_______________________SCORE:_______/30_______
LABORATORY EXERCISE # 1:
Direction: Send the image of your script/code and its output
Write a recursive method to output numbers from 1 to 10 in such a way that when number is
odd, add 1 and when number is even, subtract 1.
Output: 2 1 4 3 6 5 8 7 10 9

45
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

NAME: _____________________________ DATE: _____/_____/2020__


SECTION:_BSIT-_______________________SCORE:_______/30_______
LABORATORY EXERCISE # 2:
Direction: Send the image of your script/code and its output

Write a recursive method to output a reversed string input from the user.

46
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

NAME: _____________________________ DATE: _____/_____/2020__


SECTION:_BSIT-_______________________SCORE:_______/30_______
LABORATORY EXERCISE # 3:
Direction: Send the image of your script/code and its output

Write a program with a recursive method that will compute a factorial of a number given by a
user.

47
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

UNIT IV. BINARY TREE

Overview
This unit covers the discussion on trees such as binary tree, healp, binary search tree
.and balancing a tree
Learning Objectives

At the end of the lesson, you should be able to:


1. define Trees, Binary Trees, Heaps and Binary Search Trees
2. demonstrate skills in Implementing Binary Trees, searching a Binary Search
Tree and Balancing a Tree

Setting Up
1. What is binary tree?
2. What is heap?
3. How to implement binary search tree in Python?

What is a tree?
A tree is a structure of data that is displayed similar to the structure of the real tree. But the
tree structure in real life has its leaves (or nodes) and branches located in the top while the tree
described in this lesson is opposite, the construction is upside down the nodes (or leaves) and
branches are downward and the root of the tree is at the top. Trees can contain a large volume
of connected data which is somehow do not contain a cycle.

Shows the representation of the real tree and the tree in data structure

48
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

What is a Binary Tree

A binary tree represents structure in which every part of branches in the structure contains
two or more children which we call it as nodes, these nodes can be called right node or left
node, we can also call it as left child or right child, Binary tree supports binary search tree and
heap, A binary tree can be characterized in dissimilar methods with independent structures of
data such as list or dictionary and class for a node.

Figure 4.2 Shows the Binary Tree types

The code below will create of Binary Tree that look like these:

/ \

2 3

/ \ / \

4 5 6 7

class Node(object):

def __init__(self, value):

self.value = value

self.left = None

self.right = None

49
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

class BinaryPuno(object):

def __init__(self, root):

self.root = Node(root)

# Set up tree:

tree = BinaryPuno(1)

tree.root.left = Node(2)

tree.root.right = Node(3)

tree.root.left.left = Node(4)

tree.root.left.right = Node(5)

tree.root.right.left = Node(6)

tree.root.right.right = Node(7)

What is the Binary Search Tree?

The subtree in the left of a node contains just node with keys lesser than the node’s key at the
right. The subtree right of a node contains just node with keys more superior than the node’s
key in left. The subtree in right and left must have be another binary search tree

In our Example we will create a tree similar to the figure below:

12

/ \

10 11

/ \ \

13 14 20

/ \ /

15 16 25

50
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

To perform Binary Tree searching we will input a number and our program will determine
which of this number is the closest number in our tree we will create a function
“def closest_value” to perform these action, below is the entirety of our example

class NodeOfTree(object):

def __init__(self, x):

self.val = x

self.left = None

self.right = None

def closest_value(ugat, target):

w = ugat.val

bata= ugat.left if target < w else ugat.right

if not bata:

return w

s = closest_value(bata, target)

return min((w,s), key=lambda x: abs(target-x))

myTree = NodeOfTree(12)

myTree.left = NodeOfTree(10)

myTree.right = NodeOfTree(11)

myTree.left.left = NodeOfTree(13)

myTree.left.right = NodeOfTree(14)

myTree.left.right.left = NodeOfTree(15)

myTree.left.right.right = NodeOfTree(16)

myTree.right.right = NodeOfTree(20)

myTree.right.right.left = NodeOfTree(25)

51
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

print("number 17 will be entered")

result = closest_value(myTree, 17)

print("The closest number to the number 17 is ")

print(result)

Output

number 17 will be entered

The closest number to the number 17 is

20

What is Balanced Binary Search Tree?

Balanced Binary Search Tree is a binary search tree which can balance and stabilize itself,
while this tree can adjust and correct itself to be able to maintain a logarithmic low height
allowing it to speed up operations particularly the insertions and the deletions.

The code below performs Balanced Binary Search Tree it accomplishes the
displaying(printing) of the searched values of the tree, and then balances and orders it by
moving and jumping (Traversing) from one node to another, this is in the form of preorder or
prearrange, in order or in Arrange and post order or postArrange.

class Node(object):

def __init__(self, value):

self.value = value

self.left = None

self.right = None

class BinaryPuno(object):

def __init__(self, root):

self.root = Node(root)

52
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

def print_tree(self, traverse_type):

if traverse_type == "preArrange":

return self.print_in_preArrange(tree.root, "")

elif traverse_type == "inArrange":

return self.print_in_inArrange(tree.root, "")

elif traverse_type == "postArrange":

return self.print_in_postArrange(tree.root, "")

else:

print("traverse type " + str(traverse_type) + " is not supported.")

return False

def print_in_preArrange(self, start, traverse):

"""Root->Left->Right"""

if start:

traverse += (str(start.value) + "->")

traverse = self.print_in_preArrange(start.left, traverse)

traverse = self.print_in_preArrange(start.right, traverse)

return traverse

def print_in_inArrange(self, start, traverse):

"""Left->Root->Right"""

if start:

traverse = self.print_in_inArrange(start.left, traverse)

traverse += (str(start.value) + "->")

traverse = self.print_in_inArrange(start.right, traverse)

return traverse

def print_in_postArrange(self, start, traverse):

53
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

"""Left->Right->Root"""

if start:

traverse = self.print_in_postArrange(start.left, traverse)

traverse = self.print_in_postArrange(start.right, traverse)

traverse += (str(start.value) + "->")

return traverse

tree = BinaryPuno(1)

tree.root.left = Node(2)

tree.root.right = Node(3)

tree.root.left.left = Node(4)

tree.root.left.right = Node(5)

tree.root.right.left = Node(6)

tree.root.right.right = Node(7)

print("preArrange")

print(tree.print_tree("preArrange"))

print("inArrange")

print(tree.print_tree("inArrange"))

print("postArrange")

print(tree.print_tree("postArrange"))

Output:

preArrange

1->2->4->5->3->6->7->

inArrange

4->2->5->1->6->3->7->

54
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

postArrange

4->5->2->6->7->3->1->

What is a Heap?

The Heap is the information structure essentially used to present the priority line. to utilize
this to Python we will use and import the "heapq" module. The property of this information
structure in python is that each time the smallest of load component is popped at whatever
point components are pushed or popped, and the structure is kept up. The heap [0] component
likewise restores the littlest component each time.

The following are the operations of the Heap shown by the comments(#) and the code
below
NOTE: when you put the hashtag (#) in your code with any text on it the Python will just
ignore it

import heapq

#create a list of numbers

lis1 = [1,5,3,7,11,15]

#Organizing lis1 Array as Heaps or in other terms convert the created list into heap

heapq.heapify(lis1)

#print the created heaped list/NOTES the end= is use to connect the print item below

print("The following are the heaped list", end="")

print(list(lis1))

#Lets put a number 87 in the list by using headpush

heapq.heappush(lis1,87)

#Lets see if 87 is inserted

print("the heaped list below inserts the number 87 it did becase of heappush")

55
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

print(list(lis1))

#Lets put a number 100 in the list by using heappushpop

heapq.heappushpop(lis1,100)

#Lets see if 100 is inserted

print("the heaped list inserted the number 100 but pops the number 1 in the list")

print("it happens beacuse of heappushpop")

print(list(lis1))

######################################################

#Now lets make another list

lis2= [2,4,6,8,10,12]

#convert the created list2 into heap

heapq.heapify(lis2)

# Lets display the List2

print("The following are the 2nd heaped list ")

print(list(lis2))

#Lets put a number 200 in the list by using heapreplace

heapq.heapreplace(lis2,200)

# Lets display the List2

print("The following are the 2nd heaped list inserts the ")

print("200 in the center and removes the first number which is number 2")

print(list(lis2))

#Lets perform priorities we now


use nlargest method directly to print to display 3 largest numbers

print("Here is the list2 displaying the 3 largest numbers")

print(heapq.nlargest(3,lis2))

56
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

#Lets use nlargest method directly to print to display 3 largest numbers

print("Here is the list2 displaying the 2 smallest numbers")

print(heapq.nsmallest(3,lis

References
https://pythonspot.com/python-tree/
https://www.geeksforgeeks.org/binarytree-module-in-python/
https://docs.python.org/2/library/heapq.html
https://gist.github.com/pavlin-policar/63e237b5e0b9c8dc1b47b0e4f780a88f
https://docs.python.org/2/library/heapq.html

57
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

NAME: _____________________________ DATE: _____/_____/2020__


SECTION:_BSIT-_______________________SCORE:_______/30_______
LABORATORY EXERCISE # 1:
Direction: Send the image of your script/code and its output

Write a python program that will create a binary tree shown below.

50

/ \
45 47
/ \ / \
32 34 35 38
/ \ / \ / \ / \
20 21 22 23 24 25 26 27
/ \ / \ /\ / \
11 12 13 14 16 17 18 19

58
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

NAME: _____________________________ DATE: _____/_____/2020__


SECTION:_BSIT-_______________________SCORE:_______/30_______
LABORATORY EXERCISE # 2:
Direction: Send the image of your script/code and its output

Create a Binary Tree use the answers in the multiplication table of 6 as the nodes of your
binary tree then display the number closest to number 15

59
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

NAME: _____________________________ DATE: _____/_____/2020__


SECTION:_BSIT-_______________________SCORE:_______/30_______
LABORATORY EXERCISE # 4:
Direction: Send the image of your script/code and its output

Create an array for these numbers 5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90 and


then convert it into heap, once converted heappush the numbers 90 and 100

60
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

UNIT V. SORTING AND GRAPH


Overview
This unit designed to give you an idea of how to rearrange and position the data in proper
order. The data sorted by numerical, alphabetical, and other means. You will need to filter the
data before using the search algorithms to find a specific piece of data. Also, in this lesson,
you will get an idea of a graph, a set of objects called vertices, together with a collection of
pairwise connections, known as edges. Graphs have applications in many modeling fields,
including geography, transport, computer networks, and electrical engineering application

Learning Objectives:
At the end of this lesson, I can:
1. Develop and implement the practical sorting algorithms; and
2. Use breadth-first, depth-first, and best-first search to introduce data structures for
graphs, and search approaches.

Setting Up
1. What are the different sorting algorithim?
2. What is Decision Tree?
3. What is Graphs Data Structure?

Learning Proper
Sorting
Sorting a process of a collection of items arranged or ordered each item and its successor
satisfies a prescribed relation. The objects may be fundamental values like integers and reals,
or more complex types like student records or dictionary entries. In either case, the items are
ordered based on the value of a sort key. The key is the value itself when sorting simple types,
or when sorting complex models, and it can be a Particular component or a
component combination. We encounter many examples of day-to-day sorting in life. Consider
the listings of a phone book, the definition in a dictionary, or the terms in an index,
all organized in alphabetic order to make it much easier to find an entry.
There are many different algorithms for sorting the data and among few popular ones are
Bubble Sort, Selection Sort and Insertion Sort

Bubble Sort
A simple solution to the problem of sorting is the bubble sort algorithm, which rearranges
the values several times by iterating over the list, allowing more massive amounts to bubble to
the top or end of the list. To illustrate how the algorithm of bubble sorting works,
suppose we have four play cards that we want to order from the smallest to the most
significant face value. As shown here, we start by laying the cards face up on a table:

61
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

The algorithm involves numerous card transfers, each pass starting with the first card and
ending one card earlier than the previous iteration. The cards in both the first and second
positions compared during each move. If the first one is greater than the latter, then the two
cards will be swapped.

Next, they compare the cards in positions two and three. When the first is more significant
than the second, otherwise, they will be swapped. Otherwise, we'll leave it as it was.

For each successive pair of cards, this process continues until the card with the highest face
value positioned at the end.

62
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

The next two passes over the cards shown below. In the second move, the card put in the
next-to-last slot with the second-largest face value. The first two cards will be positioned
correctly on the third and final pass.

(Pass 2) Repeat the process on the first three cards. Compare the 5
and 8. Since five is less than 8, leave them as is.

Compare the 8 and 3. Since eight is more significant than 3, swap


the two cards.

The second-largest card (8) is now in its ordered position.

(Pass 3) Repeat the process on the first two cards. Compare the 5 and 3. Since five is more
significant than 3, swap the two cards.

After swapping the two cards, all of the cards are now in their proper order, from smallest to
largest.

Listing 1. Implementation of the bubble sort algorithm.

# Sorts a sequence in ascending order using the bubble sort algorithm. 1


def bubbleSort( theSeq ): 2
n = len( theSeq ) 3

63
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

# Perform n-1 bubble operations on the sequence 4


for i in range( n - 1 ) : 5
# Bubble the largest item to the end. 6
for j in range( i + n - 1 ) : 7
if theSeq[j] > theSeq[j + 1] : # swap the j and j+1 items. 8
tmp = theSeq[j] 9
theSeq[j] = theSeq[j + 1] 10
theSeq[j + 1] = tmp 11

Selection Sort
A second sorting algorithm, which builds on the bubble sort and works in a manner close to
what an individual would use to sort a list of values, is called the kind of selection. We can
use the play cards set again to demonstrate the algorithm and start by placing five face-up
cards on a table to be sorted in ascending order.

Instead of swapping the cards, we did the bubble sort; we'll scan through the cards and select
the smallest of those on the table and put it in our hand. We identify the three as the lowest,
for our set of cards:

We take the three and put it in our hand, leaving the rest of the cards on the table:

64
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

Cards on the Table Our Hand

The process repeated, and we mark the five as the next smallest face value:
We pick up the five and move it to the proper sorted location on the right side as there are no
cards left on the table with a lower face value.

Card on the table Our Hand

The process continued until all the cards are picked up and placed in our hands from smallest
to most significant in the correct sorted order. The method we've used to sort the set of
five cards is similar to the selection sort algorithm approach. But the algorithm preserves both
the sorted and unsorted values within the same sequence-structure when
implementing insertion sort in code.

The selection sort, which improves on the kind of bubble, makes several passes over the
series, but unlike the bubble sort, after each pass, it only makes one swap. The selection sort
algorithm to implemented given in Listing 3.

the result pick up the last pick up the next Pick up the next
our hand

65
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

card (9) smallest card (8) smallest card (6)

66
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

References

1. http://home.ustc.edu.cn/~huang83/ds/Data%20Structures%20and%20Algorithms%20
Using%20Python.pdf

2. https://www.tutorialspoint.com/python_data_structure/python_graph_algorithms.htm

3. https://jeffe.cs.illinois.edu/teaching/algorithms/book/05-graphs.pdf

4. https://learn.saylor.org/course/view.php?id=39&sectionid=410

5. https://www.geeksforgeeks.org/graph-data-structure-and-algorithms/

67
CC103| Data Structures and Algorithms Worktext | NOT FOR SALE

NAME: _____________________________________________ DATE:


_____/_____/2020__
SECTION:_BSIT-______________ SCORE:_______/30_________
EXERCISE # 1:

Direction: Create an algorithm for the following key


1. Given the following list of keys (80, 7, 24, 16, 43, 91, 35, 2, 19, 72), show the contents
of the array after each iteration of the outer loop for the indicated algorithm when
sorting in ascending order.

(a) bubble sort

(b) selection sort

(c) insertion sort

68

You might also like