خوارزميات وهياكل البيانات الأصل
خوارزميات وهياكل البيانات الأصل
Applied College
Applied Information Systems Dept.
1333 CIS-4
Algorithms and
Data Structures
Prepared by:
Maha al Otiabi
Level 3
1
دبلوم أنظمة اإلنترنت الذكية – المستوى األول
Algorithms and Data Structures
1333 CIS-4
Course Description
This course enhances the programming skills of the students. Data Structures
(Array, Stacks, queues, strings, graph and trees) are described as abstract data types
with their methods by training extensive examples and applications. Designing and
analyzing different searching and sorting algorithms in terms of time and space,
which must be taken into consideration in any program. Brief introduction to binary
trees and graphs is also covered.
Course Objectives
• Familiarize with the concepts and fundamentals of basics Data structures and
algorithms.
• Describe generic principles for data representation and manipulation with
a view for efficiency, maintainability, and code-reuse.
• Demonstrate analytical comprehension of concepts such as abstract data types
(Arrays, Vectors and Linked lists), algorithms (Stacks, Queues, Searching and
sorting techniques), and Complexity Analysis and Asymptotic notations.
• Categorize complexities of algorithms and data structures. Select appropriate
methods for organizing data files and implement file-based data structures.
• Design, write and analysis the performance of programs that handle
structured data and perform more complex tasks and software projects.
• Recent research on Algorithms and Data Structures will be incorporated
2
Algorithms and Data Structures
Contents
Course Description ..................................................................................................... 2
Course Objectives ........................................................................................................ 2
Contents .......................................................................................................................... 3
Chapter 1 ......................................................................................................................... 6
Algorithms & ....................................................................................................................... 6
Complexity Analysis ........................................................................................................... 6
Properties of an Algorithm? .......................................................................................................................8
Examples of Algorithm .................................................................................................................................8
Algorithms Categories ............................................................................................................................... 10
Algorithm Complexity................................................................................................................................ 10
Asymptotic Notations: ............................................................................................................................... 10
Big Oh Notation, Ο: ................................................................................................................................ 11
OMEGA NOTATION, Ω: .................................................................................................................... 11
Theta Notation, Θ: ................................................................................................................................... 12
Time Complexity: ........................................................................................................................................ 12
COMMON ASYMPTOTIC NOTATIONS: ..................................................................................... 14
ORDER OF GROWTH : ....................................................................................................................... 15
Chapter 2 ...................................................................................................................... 16
Arrays-vectors .................................................................................................................. 16
Introduction ................................................................................................................................................. 17
Data Structure............................................................................................................................................. 17
Multidimensional Arrays ......................................................................................................................... 21
Chapter 3 ...................................................................................................................... 23
Introduction ................................................................................................................................................. 24
Introduction ................................................................................................................................................. 24
Objects in Java ............................................................................................................................................. 25
Classes in Java ............................................................................................................................................. 25
Constructors ................................................................................................................................................. 27
Imports ........................................................................................................................................................... 28
3
Algorithms and Data Structures
Creating an Object...................................................................................................................................... 29
Chapter 4 ...................................................................................................................... 30
Linked Lists ....................................................................................................................... 30
Introduction ................................................................................................................................................. 31
Types of Linked List .................................................................................................................................. 32
Singly Linked List ...................................................................................................................................... 32
Doubly Linked List .................................................................................................................................... 40
Circular Linked List .................................................................................................................................. 46
Chapter 5 ...................................................................................................................... 53
Stacks ............................................................................................................................... 53
Introduction ................................................................................................................................................. 54
Basic Operations performed on Stack................................................................................................. 55
Chapter 6 ...................................................................................................................... 60
Queue ................................................................................................................................ 60
Introduction ................................................................................................................................................. 61
Queues Definition....................................................................................................................................... 61
Chapter 7 ...................................................................................................................... 67
Introduction to.................................................................................................................. 67
Tree and Graph ................................................................................................................. 67
Tree.................................................................................................................................................................. 68
Trees Basic terminology : .................................................................................................................... 68
Binary Tree ................................................................................................................................................... 71
Advantages of trees ................................................................................................................................. 76
Introduction to Graphs ............................................................................................................................ 77
Graph Terminologies ................................................................................................................................ 80
Types of Graphs........................................................................................................................................... 80
Graph Traversal Algorithms ................................................................................................................... 85
Depth First Search (DFS) .................................................................................................................. 86
Breadth First Search (BFS) .............................................................................................................. 86
Chapter 8 ...................................................................................................................... 88
4
Algorithms and Data Structures
Searching ......................................................................................................................... 88
Introduction ................................................................................................................................................. 89
Linear Search .............................................................................................................................................. 90
Binary Search .............................................................................................................................................. 91
5
CH01 –algorithms & complexity analysis
Chapter 1
Algorithms &
Complexity Analysis
1
By the end of teaching this chapter, the student will be able to
Understand:
➢ What is Algorithm ?
➢ Properties of an Algorithm
➢ Examples of Algorithm
➢ S asymptotic notations O, Ω, θ
➢ Time Complexity
➢ Running time
6
CH01 –algorithms & complexity analysis
Chapter 1
ALGORITHMS &
Complexity Analysis
Introduction To Algorithms
The transition from one state to the next is not necessarily deterministic; some algorithms,
known as randomized algorithms, incorporate random input. Investing additional money
or time to buy and install a new computer holds the potential for speeding up a program
by perhaps a factor of only 10 or 100. Careful algorithm design is an extremely effective
part of the process of solving a huge problem, whatever the applications area.
7
CH01 –algorithms & complexity analysis
Properties of an Algorithm?
Examples of Algorithm
Start:
End
Start:
End
8
CH01 –algorithms & complexity analysis
Start:
End
Start:
1. If(number /2==0)
Then
1.1. Print : Even Number.
Else
End if
End
Start:
Else
End if
End
9
CH01 –algorithms & complexity analysis
Algorithms Categories
Algorithm Complexity
Suppose X is an algorithm and n is the size of input data, the time and space used by the
algorithm X are the two main factors, which decide the efficiency of X.
Asymptotic Notations:
10
CH01 –algorithms & complexity analysis
Big Oh Notation, Ο:
The notation Ο(n) is the formal way to express the upper bound of an
algorithm's running time. It measures the worst case time complexity or
the longest amount of time an algorithm can possibly take to complete.
Note: This notation is the most important one that we will try to avoid our
algorithm from taking a big oh case which represent the worst case time
for an algorithm to execute.
Figure 1: O(N)
OMEGA NOTATION, Ω:
The notation Ω(n) is the formal way to express the lower bound of an
algorithm's running time. It measures the best case time complexity or the
best amount of time an algorithm can possibly take to complete.
Figure 2: Ω(n)
11
CH01 –algorithms & complexity analysis
Theta Notation, Θ:
The notation θ(n) is the formal way to express both the lower bound and
the upper bound of an algorithm's running time. It is represented as
follows
Figure 3: θ(n)
Time Complexity:
The time complexity is the computational complexity that describes the amount of time
it takes to run an algorithm. Time complexity is commonly estimated by counting the
number of elementary operations performed by the algorithm, supposing that each
elementary operation takes a fixed amount of time to perform. Thus, the amount of time
taken and the number of elementary operations performed by the algorithm are taken to
differ by at most a constant factor.
12
CH01 –algorithms & complexity analysis
Running Time
The running time of an algorithm for a specific input depends on the number of
operations executed. The greater the number of operations, the longer the running time
of an algorithm. We usually want to know how many operations an algorithm will
execute in proportion to the size of its input, which we will call.
1) The running time of an algorithm for a specific input depends on the number of
operations executed (we mean here)
2) The greater the number of operations, the longer the running time of an
algorithm.
3) We usually want to know how many operations an algorithm will execute in
proportion to the size of its input, which we will call.
13
CH01 –algorithms & complexity analysis
Constant Ο(1)
logarithmic Ο(log n)
Linear Ο(n)
linearithmic Ο(n log n)
Quadratic Ο(n 2)
Cubic Ο(n 3)
polynomial n Ο(1)
exponential 2 Ο(n)
14
CH01 –algorithms & complexity analysis
ORDER OF GROWTH :
cubic
n3
15
CH02 – Arrays-vectors
Chapter 2
Data Structure
Arrays-vectors
2
By the end of teaching this chapter, the student will be able to:
➢ Study and understand Data Structure.
➢ Distinguish the different between Arrays and vectors.
➢ Arrays - Static
➢ Vectors - Dynamic
16
CH02 – Arrays-vectors
Chapter 2
Data Structure
Arrays-vectors
Introduction
A data structure is a group of data elements that provides the easiest way to store and
perform different actions on the data of the computer. A data structure is a particular
way of organizing data in a computer so that it can be used effectively.
The idea is to reduce the space and time complexities of different tasks.
The choice of a good data structure makes it possible to perform a variety of critical
operations effectively. An efficient data structure also uses minimum memory space and
execution time to process the structure.
Data Structure
➢ A data structure is the logical and mathematical organization of Data.
➢ They are used to organize data and provide various operations upon data.
➢ Examples of Data Structures are:
o Arrays, Stacks, Queues, Trees etc.
17
CH02 – Arrays-vectors
Array:
Array is a data structure that represents a collection of the same types of data.
Declaration of an array:
Arrays must be declared before they can be used in the program.
Data type.
• Here the range of array starts from 0-9 ,where 0 is the lower bound and 9 is the
upper bound.
18
CH02 – Arrays-vectors
Initializing an Array :
Initial values are assigned to each element of an array by enclosing the values in braces {
}.
Creating Arrays
arrayRefVar = new datatype[arraySize];
Example: myList = new double[10];
myList[0] references the first element in the array.
IT CAN BE
19
CH02 – Arrays-vectors
• Once an array is created, its size is fixed. It cannot be changed. You can find its
size using
When an array is created, its elements are assigned the default value of
INDEXED VARIABLES
The array elements are accessed through the index. The array indices are 0-based, i.e., it
starts from 0 to arrayRefVar.length-1. Each element in the array is represented using the
following syntax, known as an indexed variable: arrayRefVar[index];
After an array is created, an indexed variable can be used in the same way as a regular
variable.
11 3 5 2 9
A [2] = 5.
20
CH02 – Arrays-vectors
Arrays are static, it means when you write your code you actually tells the compiler that
how many element you want to store in your array. That means the array size is fixed in
compile time.
Multidimensional Arrays
Multidimensional arrays can be defined as "arrays of arrays".
Number of columns
Number of rows
Name of Array
Data type
21
CH02 – Arrays-vectors
Vectors – Dynamic
– Vector is synchronized.
– Vector contains many legacy methods that are not part of the collections
framework.
• Vector proves to be very useful if you don't know the size of the array in advance
or you just need one that can change sizes over the lifetime of a program.
VECTORS METHODS
• Vectors have predefine methods or built-in functions that helps to create, remove,
add, edit, capacity, clear, copy, etc.
• We should import java utility class to load all tools of that class.
–import java.util.*;
EXAMPLE:
import java.util.*;
v.add(2);
v.add(3);
v.add(4);
} }
22
CH03 – class & object
Chapter 3
23
CH03 – class & object
Chapter 3
Introduction
This chapter is intended to give you a solid foundation in working with Boolean
Algebra. Boolean Algebra is also sometimes referred to as Boolean Logic or just
Logic. It is a method of representing expressions using only two values (True and
False typically) and was first proposed by George Boole in 1847.
Introduction
In this chapter, we will look into the concepts - Classes and Objects. Object −
Objects have states and behaviors. Example: A dog has states - color, name, breed
as well as behaviors – wagging the tail, barking, eating. An object is an instance of
a class. Class − A class can be defined as a template/blueprint that describes the
behavior/state that the object of its type support.
24
CH03 – class & object
Objects in Java
Let us now look deep into what are objects. If we consider the real-world, we can
find many objects around us, cars, dogs, humans, etc. All these objects have a state
and a behavior. If we consider a dog, then its state is - name, breed, color, and the
behavior is - barking, wagging the tail, running. If you compare the software object
with a real-world object, they have very similar characteristics.
Software objects also have a state and a behavior. A software object's state is stored
in fields and behavior is shown via methods. So in software development, methods
operate on the internal state of an object and the object-to-object communication is
done via methods.
Classes in Java
A class is a blueprint from which individual objects are created. A class can
have any number of methods to access the value of various kinds of
methods. Example:
• barking( )
• hungry( )
• sleeping( )
Local variables
25
CH03 – class & object
– Example:
Instance variables
Instance variables are variables within a class but outside any method. These
variables are initialized when the class is instantiated. Instance variables can be
accessed from inside any method, constructor or blocks of that particular class.
Example:
26
CH03 – class & object
Class variables
Class variables are variables declared within a class, outside any method, with the
static keyword.
Example:
Constructors
any. When discussing about classes, one of the most important sub topic
would be constructors.
Rules for creating Java constructor
Example :
Imports
In Java if a fully qualified name, which includes the package and the class name is
given, then the compiler can easily locate the source code or classes. Import
statement is a way of giving the proper location for the compiler to find that
particular class.
For example, the line on next slide would ask the compiler to load all the classes
available in directory java_installation/java/io
28
CH03 – class & object
Creating an Object
If we compile and run the above program, then it will produce the following result −
Output : Passed Name is :tommy
29
CH04 – linked list
Chapter 4
Linked Lists
4
By the end of teaching this chapter, the student will be able to
Introduce the basics:
➢ Linked List
➢ Single linked list
o Create a linked list
o Insert at the beginning
o Remove from the beginning
o Insert at the end
o Remove from the end
o Insert at anywhere
o remove from anywhere
➢ Doubly Linked List
➢ Circular Linked List
30
Prepared by:Maha al Otibi
CH04 – linked list
Chapter 4
Linked Lists
Introduction
It is a data structure which consists group of nodes that forms a sequence. Linked List
can be defined as collection of objects called nodes that are randomly stored in the
memory. A node contains two fields i.e. data stored at that particular address and the
pointer which contains the address of the next node in the memory.
Uses:
It is a very common data structure that is used to create tree, graph and other abstract
data types. The list is not required to be contiguously present in the memory. The node
can reside any where in the memory and linked together to make a list. This achieves
optimized utilization of space. list size is limited to the memory size and doesn't need to
be declared in advance. Empty node can not be present in the linked list. We can store
values of primitive types or objects in the singly linked list.
Linked List can be defined as collection of objects called nodes that are
randomly stored in the memory. node in the memory.
31
Prepared by:Maha al Otibi
CH04 – linked list
In Singly Linked List Each node in linked lists consists of two parts
• Data Part
• Pointer Point
o Pointer part stores address of next node
Node
Address of
Value
Next Node
• The Head pointer points to the first node and the last node is called
Tail Node.
32
Prepared by:Maha al Otibi
CH04 – linked list
Traversing the linked list means visiting each and every node of the Single
linked list.
Steps for Traversing the Single Linked list:
1. Firstly move to first node
2. Fetch the data and perform any operations on it
3. After performing operations advance the pointer and continue again
from step 1 until all nodes are traversed
33
Prepared by:Maha al Otibi
CH04 – linked list
34
Prepared by:Maha al Otibi
CH04 – linked list
35
Prepared by:Maha al Otibi
CH04 – linked list
36
Prepared by:Maha al Otibi
CH04 – linked list
Step1: Create a temporary node (temp) which will point to the firstNode
37
Prepared by:Maha al Otibi
CH04 – linked list
Step1:Traverse the singly linked list till reach to the node pointed by temp
(lastNode).
38
Prepared by:Maha al Otibi
CH04 – linked list
Exercise
39
Prepared by:Maha al Otibi
CH04 – linked list
is a type of linked list in which each node contains pointers to the next and
previous node in the list.
• The doubly linked lists require more space per node as compared to
singly linked list.
• The doubly linked lists are often easier to manipulate than singly linked
list because they allow sequential access to the list in both directions.
Steps:
Steps:
41
Prepared by:Maha al Otibi
CH04 – linked list
Steps:
Steps :
42
Prepared by:Maha al Otibi
CH04 – linked list
1. Step1: Traverse the doubly linked list till reach to the node using temp (node2)
43
Prepared by:Maha al Otibi
CH04 – linked list
2. Step2: Make the pointer next of the node1 to point to the node3 and Make the pointer prev of
the node3 to point to the node1.
Step1: Traverse the doubly linked list till reach to the last node (node3)
44
Prepared by:Maha al Otibi
CH04 – linked list
Exercise
45
Prepared by:Maha al Otibi
CH04 – linked list
Circular Linked List is a variation of Linked list in which the first element
points to the last element and the last element points to the first element. Both
Circular Linked List and Doubly Linked List can be made into a circular
linked list.
Steps:
46
Prepared by:Maha al Otibi
CH04 – linked list
Assume that the new node is the one to be added between prevnode and next node
Steps:
47
Prepared by:Maha al Otibi
CH04 – linked list
Steps:
Steps:
1. Create a temporary node (temp) on the first node.
2. Make a head node point to the next node
48
Prepared by:Maha al Otibi
CH04 – linked list
Steps:
1. Traverse the doubly linked list till reach to the node using temp (next node)
2. Make the first node point to the last node
49
Prepared by:Maha al Otibi
CH04 – linked list
Steps:
1. Traverse the doubly linked list till reach to the last node.
2. Make a second node point to the head.
50
Prepared by:Maha al Otibi
CH04 – linked list
Exercise:
Perform the following Operations on the circular Linked List given below.
51
Prepared by:Maha al Otibi
CH04 – linked list
1. Elements in array are in adjacent memory locations, where nodes in a list don't
have to be in adjacent locations.
2. Arrays offer random access to their elements; lists only offer sequential access
(i.e., you have to walk down the list to find an element).
3. Arrays are (usually) fixed in length - adding elements to or removing elements
from the array doesn't change the array's size. Lists can grow or shrink as
needed.
4. Linked lists can be circular, or doubly-linked (pointers forward and backward),
and new nodes can be inserted anywhere in the chain which is not the case in
Array.
52
Prepared by:Maha al Otibi
CH05 – Stack
Chapter 5
Stacks
5
By the end of teaching this chapter, the student will be able to:
➢ The fundamental concepts in graph theory.
➢ Define the basic concepts of a Stack (FILO)
➢ Create a Stack
➢ Understand the basic operations are performed in the stack:
o push(item)
o pop( )
o peek( )
o isEmpty( )
o size( )
o search(item).
53
Prepared by:Maha al Otibi
CH05 – Stack
Chapter 5
Stack
Introduction
Stack is a linear data structure which follows a particular order in which the
operations are performed. The order may be :
Stack:
• It is a restricted linear data structure.
• Elements can only be inserted and deleted at one end.
• This end is known as Top of the Stack.
• The last index of the stack is known as Top of the stack.
• A stack can be implemented by means of Array or Linked List.
• Stack can either be a fixed size or it may have a sense of dynamic resizing.
54
Prepared by:Maha al Otibi
CH05 – Stack
➢ Push
➢ Pop
➢ peek( )
➢ isEmpty( )
➢ size( )
1. Push:
• Push refers to adding an element at the top of stack.
• Push operation is carried out in following two steps
a. First increment variable top so that now it refers to next memory
location.
b. Secondly Add element on to stack by accessing array
Stack Overflow:
55
Prepared by:Maha al Otibi
CH05 – Stack
When the stack is full there is not enough room to add element at the Top of stack. This
condition is known as Stack Overflow.
The value of Top=n-1 when stack is full. Where N is the number of stack elements
Top
2. Pop:
• Allows removing an element from the top of the stack.
• Pop operation is carried out in following two steps
a. Delete the Top most element
b. Decrement Top pointer by 1.
Stack Underflow:
The value of Top is -1 when the stack is empty. This condition is known as Stack
Underflow.
2
Top [3] [3] [3]
[3]
8 [2] Top8 [2] [2]
[2]
4 [1] 4 Top [1]
[1] 4 [1]
10 [0] 10 [0] 10
Top
10 [0] [0]
4 2 1
3
56
Prepared by:Maha al Otibi
CH05 – Stack
1. Push(S1,14)
2. Push(S1,20)
3. Push(S1,90)
4. Pop
1 2 3 4
3.peek
Stack. peek() method in Java is used to retrieve or fetch the first element of the Stack or the
element present at the top of the Stack. The element retrieved does not get deleted or removed
from the Stack This operation returns the element on the top of the stack, but does
not remove it. The syntax: peek( );
4.isEmpty()
It returns true if nothing is on the top of the stack. Else, returns false. Tests if this stack
is empty. Returns true if the stack is empty, and returns
57
Prepared by:Maha al Otibi
CH05 – Stack
5. size( );
This operation displays the number of elements in a Stack. If a Stack is empty, it will
return zero otherwise return the number of the Stack elements.
Applications of Stacks:
The logic for transforming a decimal number into a binary number is as follows:
Start
Input: number
End
However, there is a problem with this logic. Suppose the number, whose binary form
we want to find is 23. Using this logic, we get the result as 11101, instead of getting
10111. To solve this problem, we use a stack. We make use of the LIFO property of
the stack. Initially we push the binary digit formed into the stack, instead of printing it
directly. After the entire digit has been converted into the binary form, we pop one
58
Prepared by:Maha al Otibi
CH05 – Stack
digit at a time from the stack and print it. Therefore we get the decimal number is
converted into its proper binary form.
Start
Input: number
1. Create a stack
3. End iteration1
59
Prepared by:Maha al Otibi
CH06 – Queues
Chapter 6
Queue 6
By the end of teaching this chapter, the student will be able to
Introduce the basics:
➢ Introduction to a Queue (FIFO)
➢ Create a Queue
➢ The basic operations are performed in the Queue : –
o Enqueue-add(item)
o Dequeue - poll( )
o peek( )
o isEmpty( )
o size( )
60
CH06 – Queues
Chapter 6
Queues
Introduction
Queues Definition
61
CH06 – Queues
A queue is a linear data structure open at both its ends. One end is
always used to insert data (enqueue) and the other is used to remove
data (dequeue). also known as FIFO (First in First out) Data
Structure.
Operations on Queues
➢ Enqueue- add(item)
➢ Dequeue- poll( )
➢ peek( )
➢ isEmpty( )
➢ size( )
62
CH06 – Queues
Enqueue
Queue Overflow:
When the Queue is full there is not enough room to add element/value at the
Rear End of Queue. This State is known as Overflow State.
In this state the value of rear==n-1;
Example of enqueue operation:
Enqueue(Q , 23);
Element to be added
Name of the Queue
Add Operation
enqueue (Q,23) enqueue(Q,8) enqueue(Q,10)
23 23 8 23 8 10
[0] [1] [2] [0] [1] [2] [0] [1] [2] [0] [1] [2]
63
CH06 – Queues
Dequeue
Queue Underflow:
When all elements are removed from the queue and there is no element to be
deleted at front end the state is known as Underflow State.
In this state the value of front==n-1;
The rear and front are initialized to -1 when the queue is empty.
Rear = front = -1
23 8 10 8 10 10
[2] [2] [0] [1] [2]
[0] [1] [2] [0] rear=2
front=0 [1] front=1[0]rear=2
[1]
front=2 rear=2
front=-1 rear=-1
64
CH06 – Queues
0 1 2 3
32 97
Front=0 Rear=1
0 1 2 3
32 97 50
Front=0 Rear=2
0 1 2 3
32 97 50 56
Front=0 Rear=3
0 1 2 3
97 50 56
Front=1 Rear=3
0 1 2 3
50 56
Front=2 Rear=3
65
CH06 – Queues
3.peek
Queue. peek() method in Java is used to retrieve or fetch the first element of the
Queue or the element present at the top of the Stack. The element retrieved does not
get deleted or removed from the queue. This operation returns the element on the
first of the Queue, but does not remove it
4.isEmpty()
It returns true if nothing is on the top of the stack. Else, returns false. Tests if this Queue
is empty. Returns true if the stack is empty, and returns
5. size( );
This operation displays the number of elements in a Queue. If a Queue is empty, it will
return zero otherwise return the number of the Queue elements.
66
CH07 – tree and graph
Chapter 7
Introduction to
Tree and Graph
7
By the end of teaching this chapter, the student will be able to:
➢ Define the basic concepts of tree graphs.
➢ Understand the fundamental concepts in tree graph theory.
➢ Learn the different types of graphs.
67
CH07 – tree and graph
Chapter 7
Tree
A Tree is a recursive data structure containing the set of one or more data nodes
where one node is designated as the root of the tree while the remaining nodes are
called as the children of the root. o The nodes other than the root node are partitioned
into the non empty sets where each one of them is to be called sub-tree. o Nodes of
a tree either maintain a parent-child relationship between them or they are sister
nodes. o In a general tree, A node can have any number of children nodes but it can
have only a single parent. o The following image shows a tree, where the node A is
the root node of the tree while the other nodes can be seen as the children of A.
• A tree is a useful non-linear data structure for rapidly storing data and rapidly
retrieving stored data.
68
CH07 – tree and graph
• A tree consists of a finite set of elements, called nodes and finite set of directed
lines called branches that connect nodes.
• When a branch is directed towards the nodes it is called an indegree branch.
• When a branch is directed away from the node it is called an outdegree branch.
• Root Node :- The root node is the topmost node in the tree hierarchy. In other
words, the root node is the one which doesn't have any parent.
• Sub Tree :- If the root node is not null, the tree T1, T2 and T3 is called sub-trees
of the root node.
• Leaf Node :- The node of tree, which doesn't have any child node, is called leaf
node.
• Leaf node is the bottom most node of the tree. There can be any number of leaf
nodes present in a general tree. Leaf nodes can also be called external nodes
• . Path :- The sequence of consecutive edges is called path. In the tree shown in the
above image, path to the node E is A→ B → E.
• Ancestor node :- An ancestor of a node is any predecessor node on a path from root
to that node. The root node doesn't have any ancestors. In the tree shown in the
above image, the node F have the ancestors, B and A.
• Degree :- Degree of a node is equal to number of children, a node have. In the tree
shown in the above image, the degree of node B is 2. Degree of a leaf node is always
0 while in a complete binary tree, degree of each node is equal to 2.
• Level Number :- Each node of the tree is assigned a level number in such a way
that each node is present at one level higher than its parent.
• Root node of the tree is always present at level 0
Example:
69
CH07 – tree and graph
Level 0
Level 1
Level 2
☞ Indegree of A=0,B=1,C=1,D=1,E=1,F=1,G=1
☞ Outdegree of A=2,B=2,C=2,D=0,E=0,F=0,G=0
70
CH07 – tree and graph
☞ Node A is at Level 0,Node B,C are at Level 1,Nodes D,E,F,G are at Level 2
Binary Tree
71
CH07 – tree and graph
1. Right skewed binary tree :- a tree in which every node has no left.
2. Left skewed binary tree – a tree in which every node has no right subtrees
72
CH07 – tree and graph
Balance Factor: of a tree is the difference in height between its left and right
subtrees.
73
CH07 – tree and graph
Eg : In above figure the height of left subtree is 2 and that of right is also 2 . So the
balance factor (BF) is given as:
BF=3-3=0
So the above tree is balanced. When the balanced factor of a tree is 0 the tree is said to
be balanced and its subtrees are also balanced.
Tree Traversal:
1. Breadth-first
2. Depth-first.
1. Breadth-first
2. Depth-first
In a preorder traversal, the root node of the tree is processed first, then the left
subtree is traversed, then the right subtree.
Inorder Traversal:
In an inorder traversal, the left subtree is traversed first, then the root node is
processed, then the right subtree is traversed.
Inorder traversal= D,B,E,A,F,C,G
75
CH07 – tree and graph
Advantages of trees
Trees are so useful and frequently used, because they have some very serious
advantages:
• Trees are very flexible data, allowing to move subtrees around with
minimum effort
76
CH07 – tree and graph
Introduction to Graphs
▪ Finding whether one can traverse all edges without traversing any twice
(an Euler Path).
▪ Finding the "minimal spanning tree" - finding a tree (with the least-cost
edges) that includes all nodes
A set of items are connected by edges. Each item is called a vertex or node.
Edges can have a cost associated with them, and the cost may depend on the
direction taken along the edge
There are two important sets of objects, which specify graph and its structure.
First set is V, which is called vertex-set. Each vertex can be drawn as a circle
with vertex's number inside.
77
CH07 – tree and graph
Vertices/Nodes
Next important set is E, which is called edge-set. E is a subset of V x V. Simply
speaking, each edge connects two vertices, including a case, when a vertex is connected
to itself (such an edge is called a loop).
All graphs are divided into two big groups: directed and undirected graphs.
Directed Graph
A directed graph is a graph in which the edges are directed by arrows. Directed
graph is also known as digraphs.
78
CH07 – tree and graph
Undirected Graph
Undirected Graph
Directed Graph
79
CH07 – tree and graph
Graph Terminologies
➢ A path can be defined as the sequence of nodes that are followed in order to
reach some terminal node V from the initial node U.
➢ Closed Path A path will be called as closed path if the initial node is same as
terminal node. A path will be closed path if V0=VN.
➢ Isolated vertex (i.e. an “edge-less” vertex);
➢ Loop (i.e. a vertex connected to itself by an edge);
➢ Adjacent vertices (vertices connected by one edge);
➢ Any edge is incident on its (endpoint) vertices;
➢ Adjacent edges (i.e. two edges incident on same vertex);
Types of Graphs
Though, there are a lot of different types of graphs depending upon the number of
vertices, number of edges, interconnectivity, and their overall structure, some of
such common types of graphs are as follows:
80
CH07 – tree and graph
Trivial Graph
A trivial graph is the graph which has only one vertex.
Simple Graph
A simple graph is the undirected graph with no parallel edges and no loops.
81
CH07 – tree and graph
Second graph is a simple graph because it does not contain any loop
and parallel edges.
Undirected Graph
Directed Graph
A directed graph is a graph in which the edges are directed by arrows. Directed
graph is also known as digraphs.
82
CH07 – tree and graph
Complete Graph
A graph in which every pair of vertices is joined by exactly one edge is called
complete graph. It contains all possible edges.
Connected Graph
A connected graph is a graph in which we can visit from any one vertex to any
other vertex. In a connected graph, at least one edge or path exists between every
pair of vertices.
83
CH07 – tree and graph
In the above example, we can traverse from any one vertex to any
other vertex. It means there exists at least one path between every
pair of vertices therefore, it a connected graph.
Disconnected Graph
A disconnected graph is a graph in which any path does not exist between every
pair of vertices.
Graph Terminology
Path: A path can be defined as the sequence of nodes that are followed in
order to reach some terminal node V from the initial node U.
Closed Path: A path will be called as closed path if the initial node is same as
terminal node. A path will be closed path if V0=VN.
Simple Path: If all the nodes of the graph are distinct with an exception
V0=VN, then such path P is called as closed simple path.
84
CH07 – tree and graph
Cycle: A cycle can be defined as the path which has no repeated edges or
vertices except the first and last vertices.
Connected Graph: A connected graph is the one in which some path exists
between every two vertices (u, v) in V. There are no isolated nodes in
connected graph.
graph in which each edge of the graph is associated with some direction and
the traversing can be done only in the specified direction.
Loop :An edge that is associated with the similar end points can be called as
Loop. Adjacent Nodes: If two nodes u and v are connected via an edge e,
then the nodes u and v are called as neighbors or adjacent nodes.
Degree of the Node :A degree of a node is the number of edges that are
connected with that node. A node with degree 0 is called as isolated node.
Weighted Graph :In a weighted graph, each edge is assigned with some data
such as length or weight. The weight of an edge e can be given as w(e) which
must be a positive (+) value indicating the cost of traversing the edge.
85
CH07 – tree and graph
The aim of DFS algorithm is to traverse the graph in such a way that it tries to
go far from the root node. Stack is used in the implementation of the depth first
search. Let’s see how depth first search works with respect to the following
graph:
As stated before, in DFS, nodes are visited by going through the depth of the
tree from the starting node. If we do the depth first traversal of the above graph
and print the visited node, it will be “A B E F C D”. DFS visits the root node
and then its children nodes until it reaches the end node, i.e. E and F nodes,
then moves up to the parent nodes.
Algorithmic Steps
1. Step 1: Push the root node in the Stack.
2. Step 2: Loop (step3,4,5) until stack is empty.
3. Step 3: Peek the node of the stack.
4. Step 4: If the node has unvisited child nodes, get the unvisited child node,
mark it as traversed and push it on stack.
5. Step 5: If the node does not have any unvisited child nodes, pop the node
from the stack.
This is a very different approach for traversing the graph nodes. The aim of
BFS algorithm is to traverse the graph as close as possible to the root node.
Queue is used in the implementation of the breadth first search. Let’s see how
BFS traversal works with respect to the following graph:
86
CH07 – tree and graph
If we do the breadth first traversal of the above graph and print the visited node
as the output, it will print the following output. “A B C D E F”. The BFS visits
the nodes level by level, so it will start with level 0 which is the root node, and
then it moves to the next levels which are B, C and D, then the last levels
which are E and F.
Algorithmic Steps
1. Step 1: Push the root node in the Queue.
2. Step 2: Loop (step3,4,5) until the queue is empty.
3. Step 3: Remove the node from the Queue.
4. Step 4: If the removed node has unvisited child nodes, mark them as visited
and insert the unvisited children in the queue.
Exercise:
87
CH09 – Sorting
Chapter 8
Searching
8
By the end of teaching this chapter, the student will be able to:
88
CH09 – Sorting
Chapter 8
Searching
Introduction
Searching is the process of finding some particular element in the list. If the
element is present in the list, then the process is called successful and the
process returns the location of that element, otherwise the search is called
unsuccessful.
Searching Techniques
89
CH09 – Sorting
Linear Search
Linear search is the simplest search algorithm and often called sequential search. In this
type of searching, we simply traverse the list completely and match each element of the
list with the item whose location is to be found. If the match found then location of the
item is returned otherwise the algorithm return NULL or -1. Linear search is mostly
used to search an unordered list in which the items are not sorted.
• Linear Search is a search algorithm that searches a list of data for a particular
value.
• It operates by checking every element of a list one at a time in sequence until a
match is found.
Example
• The array shown in the figure below consists of 6 numbers. Suppose the element
to searched is 5. So 5 is compared with all the elements starting with 0th element
.
• The searching process will end either when 5 is found or the list ends.
21 33 10 3 5 44
21 33 10 3 5 44
21 33 10 3 5 44
21 33 10 3 5 44
21 33 10 3 5 44
90
CH09 – Sorting
Time Complexity
The time complexity of linear search algorithm is O(n). linear search is rarely used
practically because other search algorithms such as the binary search algorithm and hash
tables allow significantly faster searching comparison to Linear search.
Binary Search
Binary search is the search technique which works efficiently on the sorted
lists. Hence, in order to search an element into some list by using binary
search technique, we must ensure that the list is sorted.
• Binary search method is very fast and efficient. This method requires that a list of
elements be in a sorted order.
• In this method, to search an element we compare it with the element present at the
center of the list, if it matches then the search is successful.
• Otherwise, the list is divided into two halves: one from 0th element to center
element and other from center element to the last element.
• If the element to be searched is less than the center element, then it is searched in
first half and if it is greater than the center element then it is to be searched in the
second half of the list.
• Binary search follows divide and conquer approach in which, the list is divided
into two halves and the item is compared with the middle element of the list. If the
match is found then, the location of middle element is returned otherwise, we
search into either of the halves depending upon the result produced through the
match.
91
CH09 – Sorting
Example
Binary Search Algorithm can be implemented in two ways which are discussed below.
1. Iterative Method
2. Recursive Method
3. Find the middle element mid of the array ie. arr[(low + high)/2] = 6.
4. If x == mid, then return mid. Else, compare the element to be searched with m.
5. If x > mid, compare x with the middle element of the elements on the right side of mid. This is
done by setting low to low = mid + 1.
6. Else, compare x with the middle element of the elements on the left side of mid. This is done
by setting high to high = mid - 1.
92
CH09 – Sorting
8. x = 4 is found.
Time Complexity
The time complexity of binary search algorithm is O(log n). Which means, it does not
visit all element on a list. It will divide the list over and over until get the element and
return the position.
1. If the elements are ordered, the best way to search is using binary search.
2. If the elements are not ordered, then the only way to search a key through a list is
using linear search which visits all the elements.
93
CH08 – searching
Chapter 9
Sorting
9
By the end of teaching this chapter, the student will be able to:
94
CH08 – searching
Chapter 5
Sorting
Introduction
Sorting algorithm refers to arranging data in a particular format and order. Most
common orders are in numerical or lexicographical order. The importance of sorting
lies in the fact that data searching can be optimized to a very high level, if data is stored
in a sorted manner. Sorting is also used to represent data in more readable formats.
Sorting means arranging a set of data in some order i.e. ascending (from smallest to
largest) or descending order (from largest to smallest). Following are some of the
examples of sorting in real-life scenarios
There are two methods of Sorting: Internal Sorting and External Sorting
95
CH08 – searching
Internal Sorting
If all the data that is to be sorted is stored in memory then internal sorting methods are
used.The different methods of internal sorting are:
o Bubble sort
o Selection sort
o Insertion Sort
o Quick Sort
External Sorting
When the data to be sorted is so large that some of the data is present in the memory and
some is kept in auxiliary memory (Hard disk, CD’s, Floppy, Tape, etc.), then external
sorting methods are used. The different methods of external sorting are:
Selection sort is a sorting algorithm that selects the smallest element from an unsorted
list in each iteration and places that element at the beginning of the unsorted list.
Working of Selection Sort
96
CH08 – searching
3. After each iteration, minimum is placed in the front of the unsorted list.
4. For each iteration, indexing starts from the first unsorted element. Step 1 to 3 are
repeated until all the elements are placed at their correct positions.
97
CH08 – searching
98
CH08 – searching
99
CH08 – searching
We assume that the first card is already sorted then, we select an unsorted card. If the
unsorted card is greater than the card in hand, it is placed on the right otherwise, to the
left. In the same way, other unsorted cards are taken and put in their right place.
1. The first element in the array is assumed to be sorted. Take the second element
and store it separately in key.
Compare key with the first element. If the first element is greater than key,
then key is placed in front of the first element.
100
CH08 – searching
If the first element is greater than key, then key is placed in front of the first
element.
2. Now, the first two elements are sorted.
Take the third element and compare it with the elements on the left of it. Placed it
just behind the element smaller than it. If there is no element smaller than it, then
101
CH08 – searching
102
CH08 – searching
Place 4 behind 1
103
CH08 – searching
104
CH08 – searching
105
CH08 – searching
Using the Divide and Conquer technique, we divide a problem into subproblems.
When the solution to each subproblem is ready, we 'combine' the results from the
subproblems to solve the main problem.
Suppose we had to sort an array A. A subproblem would be to sort a sub-section of this
array starting at index p and ending at index r, denoted as A[p..r].
Divide
If q is the half-way point between p and r, then we can split the subarray A[p..r] into two
arrays A[p..q] and A[q+1, r].
Conquer
In the conquer step, we try to sort both the subarrays A[p..q] and A[q+1, r]. If we haven't
yet reached the base case, we again divide both these subarrays and try to sort them.
Combine
When the conquer step reaches the base step and we get two sorted
subarrays A[p..q] and A[q+1, r] for array A[p..r], we combine the results by creating a
sorted array A[p..r] from two sorted subarrays A[p..q] and A[q+1, r].
MergeSort Algorithm
The MergeSort function repeatedly divides the array into two halves until we reach a
stage where we try to perform MergeSort on a subarray of size 1 i.e. p == r.
After that, the merge function comes into play and combines the sorted arrays into larger
arrays until the whole array is merged.
MergeSort(A, p, r):
if p > r
return
106
CH08 – searching
q = (p+r)/2
mergeSort(A, p, q)
mergeSort(A, q+1, r)
merge(A, p, q, r)
107
CH08 – searching
The merge step is the solution to the simple problem of merging two sorted lists(arrays)
to build one large sorted list(array).
The algorithm maintains three pointers, one for each of the two arrays and one for
maintaining the current index of the final sorted array.
No:
108
CH08 – searching
Merge step
A noticeable difference between the merging step we described above and the one we
use for merge sort is that we only perform the merge function on consecutive sub-arrays.
This is why we only need the array, the first position, the last index of the first
subarray(we can calculate the first index of the second subarray) and the last index of
the second subarray.
109
CH08 – searching
Our task is to merge two subarrays A[p..q] and A[q+1..r] to create a sorted array A[p..r].
So the inputs to the function are A, p, q and r
The merge function works as follows:
110