File 3
File 3
Level II - Semester 3
Array
Linked list
Queue
Stack
Examples:
• A personnel record describes an actual human being.
• An inventory record describes an existing car part or
grocery items.
• Financial transaction record describes an actual check
written to pay the electric bill.
11
© e-Learning Centre, UCSC
1.2.3 Real-world Modeling
Examples
• evaluation of mathematical expressions
• Queue of print jobs to the printer
• Queue of programs/process to be run
• Queue of network data packets to be send
• Graphs to represent airline routes between cities or
connections in an electric circuit or tasks in a project.
• Queues to model customers waiting in line at a bank or
cars waiting at a toll booth.
Examples:
Arrays, Linked Lists, Stacks and Queues.
Level II - Semester 3
• Array Representation
• Array Representation
t
Amy reference
variable
myList(0]
myLutfl]
myLLst[2)
myList(3] 13.2
4.5
3.3
myList(4j 4
Array element at,
index 5 myListf 5] 34.33 4 Element value
myLiit(6] 34
myUst(7j 45.45
myList(S) 99.993
myList(9] 11123
• Initialization
• Say you create an array of objects like this:
autoData[] carArray = new autoData[4000];
• Until the array elements are given explicit values, they
contain the special null object.
• You can initialize an array of a primitive type to
something besides 0 using this syntax:
int[] intArray = { 0, 3, 6, 9, 12, 15, 18, 21, 24, 27 };
• this single statement takes the place of both the
reference declaration and the use of new to create
the array.
• The numbers within the curly brackets are called the
initialization list.
• The size of the array is determined by the number of
values in this list.
© e-Learning Centre, UCSC 11
2.1.1 One dimensional arrays cont.
//--------------------------------------------------------------
arr[0] = 77; // insert 10 items
arr[1] = 99;
arr[2] = 44;
arr[3] = 55;
arr[4] = 22;
arr[5] = 88;
arr[6] = 11;
arr[7] = 00;
arr[8] = 66;
arr[9] = 33;
nElems = 10; // now 10 items in array
//--------------------------------------------------------------
for(j=0; j<nElems; j++) // display items
System.out.print(arr[j] + “ “);
System.out.println(“”);
• For example
int[][] a = new int[3][4];
You can think the array as a table with 3 rows and each row has 4 columns.
© e-Learning Centre, UCSC 15
2.1.2 Multi dimensional arrays cont.
• Insertion
• Inserting an item into the array is easy; we use the normal array syntax:
arr[0] = 77;
• We also keep track of how many items we’ve inserted into the array
Add new
element
here
Upper
bound
Step 1: Set upper_bound = upper_bound + 1
Step 2: Set A[upper_bound] = VAL
Step 3: EXIT
• Searching
• To search for an item, we step through the array, comparing a
particular value with each element.
Step 1:Start
Step 2:Set J=0
Step 3:Repeat Step 4 & 5 while J<N
Step 4: If A[J] = ITEM THEN GO TO Step 6
Step 5:Set J=J+1
Step 6:Print J, Item
Step 7:Stop
• Deletion
• Deletion begins with a search for the specified item.
• For simplicity, we assume that the item is present.
• When we find it, we move all the items with higher index
values down one element to fill in the “hole” left by the
deleted element, and we decrement nElems.
• In a real program, we would also take appropriate action if the
item to be deleted could not be found.
© e-Learning Centre, UCSC 23
2.1.3 Basic operations on arrays cont.
• Display elements
Data
Structure Arrays
Stacks
Array Queues
data --->
Pointer to the next
Head node
A Node
5 ---) 7 2 -- 15
A Linked List
¥
NULL
28
●Removal of a piece
○ breaking its two connections
○ removing the piece, and then reconnecting the chain.
• Advantages of Arrays
• Disadvantages of Arrays
• Fixed size: The size of the array is static (specify the array
size before using it).
• One block allocation: To allocate the array itself at the
beginning, sometimes it may not be possible to get the
memory for the complete array (if the array size is big).
• Complex position-based insertion: To insert an element
at a given position, we may need to shift the existing
elements. This will create a position for us to insert the
new element at the desired position. If the position at
which we want to add an element is at the beginning,
then the shifting operation is more expensive.
© e-Learning Centre, UCSC 35
2.2 Comparison of Arrays and Linked Lists cont.
• Linked lists contain a pointer variable START /HEAD that stores the
address of the first node in the list.
• We can traverse the entire list using START which contains the
address of the first node;
• If START = NULL, then the linked list is empty and contains no
nodes
• Linked List type declaration example :
Public class ListNode {
private int data;
private ListNode next;
© e-Learning Centre, UCSC 38
2.3 Singly Linked Lists
START
● Every linked list has a 1 Roll No Marks Next
list. 4 5 S04 98 7
AVAIL 2) Avail 6
Likewise, for the free
9
●
7 S05 55 8
pool (which is a linked 8 S06 34 10
list of all free memory 9 14
Let us assume that the head points to the first node of the list.
To traverse the list we do the following
• Follow the pointers.
• Display the contents of the nodes (or count) as they are
traversed.
• Stop when the next pointer points to NULL.
5 +> 1 17 * 4 NULL
i L
Head
The function given below can be used for printing the list data
with extra print function.
Go to Step 7
[END OF IF]
Step 2: SET NEW_NODE = AVAIL
Step 3: SET AVAIL = AVAIL.NEXT
Step 4: SET NEW_NODE.DATA = VAL
Step 5: SET NEW_NODE.NEXT = START
Step 6: SET START = NEW_NODE
Step 7: EXIT
© e-Learning Centre, UCSC 49
2.3 Singly Linked Lists cont.
• Algorithm to insert a new node after a node that has value NUM
Step 1: IF AVAIL = NULL
Write OVERFLOW
Go to Step 12
[END OF IF]
Step 2: SET NEW_NODE = AVAIL
Step 3: SET AVAIL = AVAIL.NEXT
Step 4: SET NEW_NODE.DATA = VAL
Step 5: SET PTR = START
Step 6: SET PREPTR = PTR
Step 7: Repeat Steps 8 and 9 while PREPTR.DATA != NUM
Step 8: SET PREPTR = PTR
Step 9: SET PTR = PTR.NEXT
[END OF LOOP]
Step 1 : PREPTR .NEXT == NEW_NODE
Step 11: SET NEW_NODE. NEXT = PTR
Step 12: EXIT © e-Learning Centre, UCSC 54
2.3 Singly Linked Lists cont.
• Now, move the head nodes pointer to the next node and
dispose of the temporary node.
if(head == null) {
return null;
}
return head;
}
© e-Learning Centre, UCSC 68
2.4 Doubly Linked Lists
• Update the right pointer of the new node to point to the current
head node (dotted link in below figure) and also make left
pointer of new node as NULL.
• Update head node’s left pointer to point to the new node and
make new node as head. Head
• Move the head nodes pointer to the next node and change
the heads left pointer to NULL. Then, dispose of the
temporary node.
• Traverse the list and while traversing maintain the previous node
address also. By the time we reach the end of the list, we will have
two pointers, one pointing to the tail and the other pointing to
the node before the tail.
• Update the next pointer of previous node to the tail node with
NULL.
• In singly linked lists and doubly linked lists, the end of lists
are indicated with NULL value.
• But circular linked lists do not have ends. While traversing
the circular linked lists we should be careful; otherwise we
will be traversing the list infinitely.
• Create a new node and initially keep its next pointer pointing to
itself.
• Update the next pointer of the new node with the head node and
also traverse the list to the tail. That means in a circular list we
should stop at the node whose next node is head.
•Update the next pointer of the previous node to point to the new
node and we get the list as shown below.
• Create a new node and initially keep its next pointer pointing to
itself.
• Update the next pointer of the new node with the head node and
also traverse the list until the tail. That means in a circular list we
should stop at the node which is its previous node in the list.
• Update the previous head node in the list to point to the new
node.
• This means that every second node points to the node two
positions ahead, every fourth node points to the node four
positions ahead, and so on.
• This is accomplished by having different numbers of
reference fields in nodes on the list:
- Half of the nodes have just one reference field
- one-fourth of the nodes have two reference fields
- one-eighth of the nodes have three reference fields and
etc.
• The number of reference fields indicates the level of each
node, and the number of levels is maxLevel = [lg n] + 1.
We will start from highest level in the list and compare key of next node of
the current node with the key to be inserted. Basic idea is If :
a. Key of next node is less than key to be inserted then we keep
Insert(key)
p = Search(key)
q = null
i=1
repeat
i=i+1 //Height of tower for new element
if i >= h
h=h+1
createNewLevel() //Creates new linked list level
• First, we always insert the key into the bottom list at the correct
location.
• Then, we have to promote the new element. We do so by flipping a
fair coin.
• If it comes up heads, we promote the new element. By flipping this
fair coin, we are essentially deciding how big to make the tower for
the new element.
• We scan backwards from our position until we can go up, and then
we go up a level and insert our key right after our current position.
• While we are flipping our coin, if the number of heads starts to
grow larger than our current height, we have to make sure to
create new levels in our skip list to accommodate this.
1. Key of next node is less than search key then we keep on moving
the pointer to current node i at update[i] and move one level down
and continue our search.
At the lowest level (0), if the element next to the rightmost element
(update[0]) has key equal to the search key, then we have found key
otherwise failure.
© e-Learning Centre, UCSC 122
2.6 Skip Lists Cont.
Delete(key)
Search for all positions p_0, ..., p_i where key exists
return
Delete can be implemented in many ways. Since we know when we find our first
instance of key, it will be connected to all others instances of key, and we can easily
delete them all at once.
Level II - Semester 3
3.1 Stacks
3.1.1 Introduction to Stacks [Ref 4:pg.163-165,Ref 2:pg.232]
3.1.1.1 Array based Stack implementation [Ref 4:pg.165-167, Ref 3:pg.
116-123, Ref 1:pg.596-599, Ref 2:pg.233-234]
3.1.1.2 Linked List based Stack implementation [Ref 4:pg.171-175,
Ref1:pg.606-609]
3.1.2 Applications of Stacks [Ref 4:pg.165, Ref 4:pg.174-185]
3.2 Queues
3.2.1 Introduction to queues [Ref 4:pg.205-206, Ref 2:pg.234]
3.2.1.1 Array based Queue implementation [Ref 1:pg.260-261, pg.600-
604, Ref 3:pg.132-142, Ref 2:pg.235]
3.2.1.2 Linked List based Queue implementation [Ref 4: pg. 212-213,
Ref1:pg.609-612]
3.2.2 Applications of queues [Ref 4:pg.207]
3.2.3 Circular queue [Ref 4:pg.207-208, Ref 3:pg.36-137]
3.2.4 Priority queue [Ref 4:pg.369-371, Ref 1:pg.274-276, Ref 3:pg.143-149]
https://miro.medium.com/max/800/0*SESFJYWU5a-3XM9m.gif
end procedure
end procedure
• To push the next item into the location 0 over the location
to make room for new item.
PUSH
POP
public stackar( )
/* construct the stack
{
thearray= new object[default-capacity];
Tos = -1;
}
Isempty( )
Isfull( )
Return and remove the most recently inserted item from the
stack
Exception underflow if the stack is empty
//-------------------------------------------------------------
-
public boolean isFull() // true if stack is full
{
return (top == maxSize-1);
}
//-------------------------------------------------------------
-
} // end class StackX
if( !theStack.isFull() )
insert(item);
else
System.out.print("Can't insert, stack is full");
Direct Applications
• Balancing of symbols
• Infix-to-postfix conversion
• Evaluation of postfix expression
• Implementing function calls (including recursion)
• Finding of spans (finding spans in stock markets, refer to
Problems section)
• Page-visited history in a Web browser [Back Buttons]
• Undo sequence in a text editor
• Matching Tags in HTML and XML
• more direct applications using stacks?
Indirect Applications
• Auxiliary data structure for other algorithms
(Example: Tree traversal algorithms)
• Component of other data structures
(Example: Simulating queues)
https://i1.faceprep.in/Companies-1/queue-operations.gif
end procedure
© e-Learning Centre, UCSC 50
3.2.1 Introduction to queues cont.
//-------------------------------------------------------------
public int size() { // number of items in queue
return nItems;
}
//-------------------------------------------------------------
} // end class Queue
System.out.print(" ");
}
System.out.println("");
} // end main()
} // end class QueueApp
public ListQueue( ){
front = back = null;
}
C D E F G H I
© e-Learning Centre, UCSC 80
Wraparound routine(increment)
Level II - Semester 3
Recursion Iteration
Each recursive call requires extra space on Each iteration does not require extra space.
the stack frame (memory).
If we get infinite recursion, the program An infinite loop could loop forever since
may run out of memory and result in stack there is no extra memory being created.
overflow.
Solutions to some problems are easier to Iterative solutions to a problem may not
formulate recursively. always be as obvious as a recursive
solution.
recursiveMethod(parameters) {
if (stopping condition) {
// handle the base case
} else {
// recursive case:
// possibly do something here
recursiveMethod(modified parameters);
possibly do something here
}
}
© e-Learning Centre, UCSC 10
4.3. How Recursion Works Contd.
n * (n – 1) * (n – 2) * … * 1
n! = n * (n – 1)
5! = 5 * 4!
4! = 4 * 3!
3! = 3 * 2!
2! = 2 * 1!
Fact(n)
Begin
if n == 0 or 1 then
Return 1;
else
Return n*Call Fact(n-1); // recursive call
endif
End
• Tail Recursion
• NonTail Recursion
• Indirect Recursion
• Nested Recursion
• Excessive Recursion
• Recursions that are not tail recursions are called non- tail
recursions.
void reverse() {
char ch = getChar();
if (ch != '\n') {
reverse() ;
System.out.print(ch);
}
}
receive (buffer)
while buffer is not filled up
if information is still incoming
get a character and store it in buffer;
else exit( );
decode (buffer);
decode (buffer)
decode information in buffer;
store (buffer);
store (buffer)
transfer information from buffer to file;
receive (buffer);
• The definition translates very nicely into Java, but the task
of expressing it in a non-recursive form is truly troublesome.
• The definition states that if the first two numbers are 0 and
1, then any number in the sequence is the sum of its two
predecessors. But these predecessors are in turn sums of
their predecessors, and so on, to the beginning of the
sequence. The sequence produced by the definition is
int Fib(int n) {
if (n < 2)
return n;
else return Fib(n-2) + Fib(n-l);
}
Level II - Semester 3
Non-recursive definition:
• A (rooted) tree consists of a set of nodes, and a set of directed
edges between nodes.
• One node is the root; For every node c that is not the root, there
is exactly one edge (p, c) pointing to c;
• For every node c there is a unique path from the root to c.
• Basic Terminology
• tree - a non-empty collection of vertices & edges
• vertex (node) - can have a name and carry other associated
information
• path - list of distinct vertices in which successive vertices are
connected by edges
• Sub-trees -If the root node R is not NULL, then the trees T1,
T2, and T3 are called the sub-trees of R.
• Leaf node -A node that has no children is called the leaf node
or the terminal node.
• Non-leaf node-In any tree the node which has at least one
child is called internal/non-leaf node.
• Basic Terminology
• Level number Every node in the tree is assigned a level
number in such a way that the root node is at level 0, children
of the root node are at level number 1.
• Thus, every node is at one level higher than its parent. So, all
child nodes have a level number given by parent’s level
number + 1.
Example:
• Basic Terminology
• Degree: Degree of a node is equal to the number of children
that a node has.
• The degree of a leaf node is zero.
• In-degree: In-degree of a node is the number of edges
arriving at that node. For example, in degree of the node B is
one i.e. one edge merges.
• Out-degree: Out-degree of a node is the number of edges
leaving that node. For example, out degree of the node A is
two i.e. two edges comes out of this root node.
Representation of Trees
• Every tree node:
• object – useful information
• children – pointers to its children nodes
•A tree consists of set of nodes and set of edges that connected pair
of nodes.
● In worst case we need n links and for best case, we need 2 links
• Implementation
• One way to implement a tree would be to have in each node a
link to each child of the node in addition to its data.
• However, as the number of children per node can vary greatly
and is not known in advance, making the children direct links
in the data structure might not be feasible.
• There would be too much wasted space.
• The solution is called the first child/next sibling method
• A binary tree is a tree in which no node can have more than two
children.
• The two children of each node in a binary tree are called the left
child and the right child.
• A node in a binary tree doesn’t necessarily have the maximum of
two children; it may have only a left child, or only a right child, or
it can have no children at all (in which case it’s a leaf).
• Full Binary Tree: A binary tree is called full binary tree if each
node has exactly two children and all leaf nodes are at the
same level.
The above tree is represented in the main memory using a linked list
as follows:
• Pre-order traversal
• In preorder traversal, each node is processed before (pre)
either of its sub trees.
• Even though each node is processed before the sub trees, it
still requires that some information must be maintained
while moving down the tree.
• In the figure below, 1 is processed first, then the left sub
tree, and this is followed by the right sub tree.
• Pre-order traversal
• Therefore, processing must return to the right sub tree after
finishing the processing of the left sub tree.
• To move to the right sub tree after processing the left sub
tree, we must maintain the root information.
• Algorithm
• Preorder traversal is defined as follows:
• Visit the root.
• Traverse the left sub tree in Preorder.
• Traverse the right sub tree in Preorder.
• Pre-order traversal
• Pre-order traversal
Example 2 :
• Pre-order traversal
Code segment :
private void preOrder(Node localRoot)
{
if(localRoot != null)
{
System.out.print(localRoot.iData + “ “);
preOrder(localRoot.leftChild);
preOrder(localRoot.rightChild);
}
}
• In-order traversal
• In In-order Traversal the root is visited between the sub
trees.
• Algorithm
• In-order traversal is defined as follows:
• Traverse the left sub tree in In-order.
• Visit the root.
• Traverse the right sub tree in In-order.
• In-order traversal
Example 1 :Traversal order
Algorithm
• In-order traversal
Example 2 :
• In-order traversal
Code segment :
private void inOrder(Node localRoot)
{
if(localRoot != null)
{
inOrder(localRoot.leftChild);
System.out.print(localRoot.iData + “ “);
inOrder(localRoot.rightChild);
}
}
• Post-order traversal
• In post-order traversal, the root is visited after both sub
trees.
• Algorithm
• Post-order traversal is defined as follows:
• Traverse the left sub tree in Post-order.
• Traverse the right sub tree in Post-order.
• Visit the root.
• Post-order traversal
• Post-order traversal
Example 2 :
• Post-order traversal
Code segment :
private void postOrder(Node localRoot)
{
if(localRoot != null)
{
postOrder(localRoot.leftChild);
postOrder(localRoot.rightChild);
System.out.print(localRoot.iData + “ “);
}
}
© e-Learning Centre, UCSC 58
5.2.1 Depth First Traversal
Example:
• How it works
• In the breadth first traversal, the nodes are visited level by level,
from left to right.
• Example:
• Applications of BFS
• Example
• Example
Next, we go through all the neighbors of node(1) Again, we dequeue from the queue and this time we
and put all the unvisited node on the queue. node(2) get node(2). We print it and go for all the neighbor
and node(5) will go on to the queue and marked as node, node(3) and node(4) and mark them as
visited.Traversal = {1} visited.Traversal = {1,2}
• Example
node(5) is dequeued next and printed. Here, even though Now, we pop node(3) and print it, however,
node(4) is a neighbor of node(5), it is already visited and node(4) is already visited. Hence, nothing is
hence not put on to the queue again. But node(6) is not added to the queue. Traversal = {1,2,5,3}
yet visited, so put it on to the queue.Traversal = {1,2,5}
• Example
Next, node(4) is taken out from queue and Last, we pop node(6) and print it.
printed, nothing goes on to queue. Traversal = Traversal = {1,2,5,3,4,6}.
{1,2,5,3,4}
Final Tree
current = current.leftChild;
if(current == null) // if end of the line,
{ // insert on left
parent.leftChild = newNode;
return;
}
} // end if go left
else // or go right?
{
current = current.rightChild;
if(current == null) // if end of the line
{ // insert on right
parent.rightChild = newNode;
return;
}
} // end else go right
} // end while
} // end else not root
} // end insert()
Example :
If (t = = null)
return 0;
else
return 1+maximum(height(t->left),height(t- >right);
Hence, for self-balancing BSTs, the minimum height must always be log₂(n)
rounded down. Moreover, a binary tree is said to be balanced if the height
of left and right children of every node differ by either -1, 0 or +1. This value
is known as the balance factor.
• Left rotation
When we left rotate about node x, node y becomes the new root of
the subtree. Node x becomes the left child of node y and subtree b
becomes the right child of node x.
• Right rotation
When we right rotate about node y, node x becomes the new root
of the subtree. Node y becomes the right child of node x and
subtree b becomes the left child of node y.
• AVL trees
• Red-black trees
• Splay trees
• Treaps
• How to balance?
Template < T>
Void BST <T>:: Balance (T Data[], int First, int last){
If (first<=last) {
int middle=(first+last)/2;
insert(data[middle]);
balance(data, first,middle-1);
balance (data,middle+1, last);
}
}
• The very elegant DSW algorithm was devised by Colin Day and
later improved by Quentin F. Stout and Bette L.Warren.
• The building block for tree transformations in this algorithm is
the rotation.
• There are two types of rotation, left and right, which are
symmetrical to one another.
• The right rotation of the node Ch about its parent Par is
performed according to the following algorithm:
Example :
Example :
• Each time the tree structure is changed, the balance factors are
checked and if an imbalance is recognized, then the tree is
restructured.
• For insertion there are four cases to be concerned with.
• Deletion is a little trickier
• The balance factor of any node in the tree is -1 , o or +1. It
implies that the tree is an AVL tree.
• Example :
• Rotations
• When the tree structure changes (e.g., with insertion or
deletion), we need to modify the tree to restore the AVL tree
property.
• This can be done using single rotations or double rotations.
Since an insertion/deletion involves adding/deleting a single
node, this can only increase/decrease the height of a sub
tree by 1.
• So, if the AVL tree property is violated at a node X, it means
that the heights of left(X) and right(X) differ by exactly 2.
This is because, if we balance the AVL tree every time, then
at any point, the difference in heights of left(X) and right(X)
differ by exactly 2.
• Rotations is the technique used for restoring the AVL tree
property. This means, we need to apply the rotations for the
node X.
© e-Learning Centre, UCSC 136
5.4.3 Local tree balancing (AVL Tree)
• Rotations
• Types of Violations
• Let us assume the node that must be rebalanced is X. Since any
node has at most two children, and a height imbalance requires
that X’s two sub tree heights differ by two, we can observe that a
violation might occur in four cases:
1. An insertion into the left sub tree of the left child of X.
2. An insertion into the right sub tree of the left child of X.
3. An insertion into the left sub tree of the right child of X.
4. An insertion into the right sub tree of the right child of X
Cases 1 and 4 are symmetric and easily solved with single rotations.
Similarly, cases 2 and 3 are also symmetric and can be solved with double
rotations
• Single Rotations
• Single Rotations
• Left Left Rotation (LL Rotation) [Case-1]:
For example, in the figure above, after the insertion of 7 in the original AVL tree
on the left, node 9 becomes unbalanced. So, we do a single left-left rotation at
9. As a result we get the tree on the right.
© e-Learning Centre, UCSC 140
5.4.3 Local tree balancing (AVL Tree)
• Single Rotations
• Left Left Rotation (LL Rotation):
Example 2
• Single Rotations
• Right Right Rotation (RR Rotation) [Case-4]: In this case, node X
is not satisfying the AVL tree property.
• Single Rotations
• Right Right Rotation (RR Rotation) [Case-4]:
For example, in the figure, after the insertion of 29 in the original AVL tree on
the left, node 15 becomes unbalanced. So, we do a single right-right rotation
at 15. As a result we get the tree on the right.
© e-Learning Centre, UCSC 143
5.4.3 Local tree balancing (AVL Tree)
• Single Rotations
• Right Right Rotation (RR Rotation):
Example 2 :
• Double Rotations
• Left Right Rotation (LR Rotation) [Case-2]: For case-2 and
case-3 single rotation does not fix the problem. We need to
perform two rotations.
• Double Rotations
• Left Right Rotation (LR Rotation) [Case-2]:
• Double Rotations
• Left Right Rotation (LR Rotation):
Example 2:
• Double Rotations
• Right Left Rotation (RL Rotation) [Case-3]: Similar to
case-2, we need to perform two rotations to fix this
scenario.
• Double Rotations
• Right Left Rotation (RL Rotation) [Case-3]:
• Double Rotations
• Right Left Rotation (RL Rotation):
Example 2:
Insert 105
Do RL rotation
• Case 1: Deletion from a left subtree from a tree with a right high
root and a right high right subtree.
• Requires one left rotation about the root
• Case 2: Deletion from a left subtree from a tree with a right high
root and a balanced right subtree.
• Requires one left rotation about the root
• Case 3: Deletion from a left subtree from a tree with a right high
root and a left high right subtree with a left high left subtree.
• Requires a right rotation around the right subtree root and
then a left rotation about the root
• Case 4: Deletion from a left subtree from a tree with a right high
root and a left high right subtree with a right high left subtree
• Requires a right rotation around the right subtree root and
then a left rotation about the root
© e-Learning Centre, UCSC 156
5.4.3 Local tree balancing (AVL Tree)
Code Segment :
Node rotateRight(Node y) {
Node x = y.left;
Node z = x.right;
x.right = y;
y.left = z;
updateHeight(y);
updateHeight(x);
return x;
}
Node rotateLeft(Node y) {
Node x = y.right;
Node z = x.left;
x.left = y;
y.right = z;
updateHeight(y);
updateHeight(x);
return x;
}
Node rebalance(Node z) {
updateHeight(z);
int balance = getBalance(z);
if (balance > 1) {
if (height(z.right.right) >
height(z.right.left)) {
z = rotateLeft(z);
} else {
z.right = rotateRight(z.right);
z = rotateLeft(z);
}
else {
Node mostLeftChild =
mostLeftChild(node.right);
node.key = mostLeftChild.key;
node.right = delete(node.right, node.key);
}
}
if (node != null) {
node = rebalance(node);
}
return node;
}
• Example :
Binary Heap
• A Binary Heap is a Binary Tree with following properties.
● Applications of Heaps
● Example : 3,1,6,5,2,4
First Insert 3 in root of the empty heap:
Next Insert 1 at the bottom of the heap. No need to swap the child
node (1) with the parent node (3) , because 3 is greater than 1.
● Example : 3,1,6,5,2,4
Next insert 6 to the bottom of the heap, and since 6 is greater than 3,
swapping is needed
● Example : 3,1,6,5,2,4
Next insert 5 to the bottom of the heap, and since 5 is greater than 1,
swapping is needed
● Example : 3,1,6,5,2,4
Next insert 2 to the bottom of the heap, and since 2 is less than 5, no
need to swap the 5 with the 2.
Next insert 4 to the bottom of the heap, and since 4 is greater than 3,
we need to swap the 4 and the 3.
● Example : 3,1,6,5,2,4
Swap the 4 and the 3. Since 4 is less than 6 no further swapping
needed, and we are done.
• Example :
• Example :
Delete node 10
• Example :
• Example :
Code Segment :
public class deletionHeap {
static void heapify(int arr[], int n, int i)
{
int largest = i; // Initialize largest as root
int l = 2 * i + 1; // left = 2*i + 1
int r = 2 * i + 2; // right = 2*i + 2
if (l < n && arr[l] > arr[largest])
largest = l;
if (r < n && arr[r] > arr[largest])
largest = r;
if (largest != i) {
int swap = arr[i];
arr[i] = arr[largest];
arr[largest] = swap;
heapify(arr, n, largest);
}
}
© e-Learning Centre, UCSC 189
5.5 Heaps
Code Segment :
static int deleteRoot(int arr[], int n)
{
int lastElement = arr[n - 1];
arr[0] = lastElement;
n = n - 1;
heapify(arr, n, 0);
return n;
}
static void printArray(int arr[], int n)
{
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
int n = arr.length;
n = deleteRoot(arr, n);
printArray(arr, n);
}
}
Level II - Semester 3
Components of a Graph
Graph Terminology
• Circuit: A path whose first and last vertices are the same
and no edge is repeated then the path is called a circuit.
• Cycle: A cycle where all the vertices are distinct except for
the first (and the last) vertex.
1,4,5,3,1 is a cycle
1,4,5,3,2,1 is a Hamiltonian
Cycle
• Directed Graph
• A graph in which edge has direction. That is the nodes are
ordered pairs in the definition of every edge.
• Undirected Graph
• A graph in which edges do not have any direction. That is the
nodes are unordered pairs in the definition of every edge.
• Weighted Graph
• A graph in which a weight, or number, associated with each
edge.
103KM
222KM
146KM 251KM
44KM
Graph Terminology
In-degree of 1 is 3
Out-degree of 1 is 1
• Adjacency Matrix
• In this method, the graph is stored in the form of the 2D matrix
where rows and column denote vertices.
• Each entry in the matrix represents the weight of the edge
between those vertices.
• The values of the Adjacency matrix are represented as
follows: 1 or sometimes denoted as true. That indicates an
edge from one node to another node; otherwise, 0 or false.
• Path Matrix
• Path matrix has the same concept of adjacency matrix. But
instead of having an edge from one node to another, this
indicates whether there is a path from one node another.
• The values of the path matrix are represented as follows: 1 or
sometimes denoted as true. That indicates a path from one
node to another node with the given length; otherwise, 0 or
false.
• For an example, path matrix of length 2 denotes whether there
is a path from one node to another with length 2.
• Hence, we can get the path matrix of length n by taking path
matrix of length n-1 and multiplying it with path matrix of
length 1.
V1 V2 V3 V4 V1 V2 V3 V4
V1 0 1 1 0 V1 1 1 0 1
V2 1 0 0 1 V2 0 1 1 0
V3 0 1 0 1 V3 1 0 1 1
V4 0 0 1 0 V4 0 1 0 1
• Adjacency List
• This graph is represented as a collection of linked lists.
• There is an array of pointer which points to the edges
connected to that vertex.
Algorithm
DFT-Visit(u)
color[u]=:gray; time:=time+1; d[u]:=time
for each v in adj[u] do
if color[v]=white then
parent[v]:=u; DFT-Visit(v);
end if
end for
color[u]:=black; time:=time+1; f[u]:=time;
end DFT-Visit
Notation
In what follows:
• dl denotes the distance value of a node l.
The state of a node l is the ordered pair of its distance value dl and
its status label.
Algorithm
• Step 1 : Initialization
Step 1 : Initialization
• Otherwise, go to step 2.
Example
Example contd.
• The set sptSet is initially empty and distances assigned to
vertices are {0, INF, INF, INF, INF, INF, INF, INF} where INF
indicates infinite.
• Now pick the vertex with minimum distance value. The vertex 0
is picked, include it in sptSet. So sptSet becomes {0}. After
including 0 to sptSet, update distance values of its adjacent
vertices.
Example contd.
0 1 2 3 4 5 6 7 8
0 ∞ ∞ ∞ ∞ ∞ ∞ ∞ ∞
4 8
• Pick the vertex with minimum distance value and not already
included in SPT (not in sptSET). The vertex 1 is picked and
added to sptSet. So sptSet now becomes {0, 1}. Update the
distance values of adjacent vertices of 1. The distance value of
vertex 2 becomes 12.
Example contd.
0 1 2 3 4 5 6 7 8
0 ∞ ∞ ∞ ∞ ∞ ∞ ∞ ∞
4 8
12
• Pick the vertex with minimum distance value and not already
included in SPT (not in sptSET). Vertex 7 is picked. So sptSet
now becomes {0, 1, 7}. Update the distance values of adjacent
vertices of 7. The distance value of vertex 6 and 8 becomes
finite (15 and 9 respectively).
Example contd.
0 1 2 3 4 5 6 7 8
0 ∞ ∞ ∞ ∞ ∞ ∞ ∞ ∞
4 ∞ ∞ ∞ ∞ ∞ 8 ∞
12 ∞ ∞ ∞ ∞ 8 ∞
12 ∞ ∞ ∞ 9 ∞ 15
• Pick the vertex with minimum distance value and not already
included in SPT (not in sptSET). Vertex 6 is picked. So sptSet
now becomes {0, 1, 7, 6}. Update the distance values of
adjacent vertices of 6. The distance value of vertex 5 and 8 are
updated.
Example contd.
0 1 2 3 4 5 6 7 8
0 ∞ ∞ ∞ ∞ ∞ ∞ ∞ ∞
4 ∞ ∞ ∞ ∞ ∞ 8 ∞
12 ∞ ∞ ∞ ∞ 8 ∞
12 ∞ ∞ ∞ 9 ∞ 15
12 ∞ ∞ 11 ∞ 15
• We repeat the above steps until sptSet does include all vertices
of given graph. Finally, we get the following Shortest Path Tree
(SPT).
Example contd.
0 1 2 3 4 5 6 7 8
0 ∞ ∞ ∞ ∞ ∞ ∞ ∞ ∞
4 ∞ ∞ ∞ ∞ ∞ 8 ∞
12 ∞ ∞ ∞ ∞ 8 ∞
12 ∞ ∞ ∞ 9 15
12 ∞ ∞ 11 15
12 25 21 15
19 21 14
19 21
21
Algorithm
• Step 01: This step initializes distances from the source to all
vertices as infinite and distance to the source itself as 0. Create
an array dist[] of size |V| with all values as infinite except
dist[src] where src is source vertex.
Algorithm contd.
Example
Example contd.
• Let all edges are processed in the following order: (B, E), (D, B),
(B, D), (A, B), (A, C), (D, C), (B, C), (E, D).
Example contd.
Example contd.
• The first iteration guarantees to give all shortest paths which are
at most 1 edge long. We get the following distances when all
edges are processed second time (The last row shows final
values).
Example contd.
// Step 01
// Step 02
// Step 03
Different Types of
Graph Adjacency Matrix, Path Matrix and Adjacency list.
Representations
Shortest Path
Algorithms in Dijkstra's Algorithm and Bellman-Ford Algorithm
Graphs
Level II - Semester 3
What is an Algorithm?
Analyzing an algorithm
• Such analysis may indicate more than one viable candidate, but
we can often discard several inferior algorithms in the process.
Comparing Algorithms?
Cost
arr[i] = 0; C1
Cost
sum = 0; C1
for (i=0; i>n ; i++) C2
for (j=0; j<n; j++) C2
sum += arr[i][j] C3
Rate of Growth
This is because the cost of the car is high compared to the cost
of the bicycle (approximating the cost of the bicycle to the cost
of the car).
• As an example, in the case below, n4, 2n2, 100n and 500 are the
individual costs of some function and approximate to n4 since n4
is the highest rate of growth.
𝑓 𝑛 = 𝑛2 + 100𝑛 + 102
Similarly for the average case. The expression defines the inputs
with which the algorithm takes the average running time (or
memory).
• Worst case
• Provides an upper bound on running time
• An absolute guarantee that the algorithm would not run
longer, no matter what the inputs are.
• Best case
• Provides a lower bound on running time
• Input is the one for which algorithm runs the fastest
• Average case
• Provides a prediction about the running time of the algorithm.
• Assumes that the input is random
Asymptotic Analysis
Notations used.
• Big-O (O)
• Omega (Ω)
• Theta (ϴ)
• The statement “ f(n) = O(g(n))” means that the growth rate of f(n)
is no more than the growth rate of g(n).
Properties of Big-O
• If f(n) = n2+200n+45
• Big-O is transitive.
If f(n) is O(g(n))
and
g(n) is O(h(n))
then
f(n) is O(h(n))
Big-O Summary
The Running Time Analysis of The process of determining how processing time
an Algorithm increases with respect to the input time.
The Rate of Growth of an The rate at which the running time increases as a
Algorithm function of input size.
Level II - Semester 3
Iterative Method
• An iterative algorithm executes steps in iterations.
• Repetitive structure is used in the iterative methodology.
• Eg : Bubble sort
• One of the simplest sorting is algorithm is known
as bubble sort. The algorithm as follows.
• Beginning at the last element in the list
• Compare each element with the previous
element in the list. If an element is less than its
predecessor, swap these two element.
• To completely sort the list, you need to perform
this process n-1 times on a list of length n
https://commons.wikimedia.org/wiki/File:Bubble-sort.gif
begin BubbleSort(list)
for all elements of list (iterate through all the data elements)
if list[i] > list[i+1] (check whether the two data elements are in correct order)
swap(list[i], list[i+1]) (if the data elements are not in the correct order, swap
the two data elements)
end if
end for
return list
end BubbleSort
Second pass
• ( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
• ( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ),
• Elements are not in the correct order (4 > 2)
• Swaps element 4 with element 2
• ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
End of the second pass (All data elements are iterated)
Eg :
• (a)Run through the bubble sort algorithm by hand on the
list :44,55,12,42,94,18,06,67
• (b) Write a Java program to implementing the bubble sort
algorithm on an array.
• The basic idea underlying the bubble sort is to pass
through the file sequentially several times.
• Each pass consists of comparing each element in the file
with its predecessor [x[i] and x[i-1] and interchanging the
two elements if they are not proper order.
int n = arr.length;
int temp = 0;
}
} © e-Learning Centre, UCSC 19
8.2.1.1 Bubble sort
• Point 01
84
Begin SelectionSort(list, n)
for i = 1 to n - 1
min = i (take 1st element of the unsorted list as min)
if indexMin != i then (if 1st element of the unsorted list and min is different)
swap list[min] and list[i] (swap 1st element of unsorted list with min)
end if
end for
end selectionSort © e-Learning Centre, UCSC 26
8.2.1.2 Selection sort
Let's consider an array with values (5 1 4 2 8).
• ( 5 1 4 2 8 ) –> ( 1 5 4 2 8 )
• take 1st element of the unsorted list as min = 5
• find and update the min of the unsorted list = 1
• swap 1st element of the unsorted list with min
• Swaps element 5 with element 1
• ( 1 5 4 2 8 ) –> ( 1 2 4 5 8 )
• take 1st element of the unsorted list as min = 5
• find and update the min of the unsorted list = 2
• swap 1st element of the unsorted list with min
• Swaps element 5 with element 2
• ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
• take 1st element of the unsorted list as min = 4
• find and update the min of the unsorted list = 4
• 1st element and the min is the same
• ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
• take 1st element of the unsorted list as min = 5
• find and update the min of the unsorted list = 5
• 1st element and the min is the same
End of the iteration © e-Learning Centre, UCSC 27
8.2.1.2 Selection sort
• Java code for selection sort algorithm
Runtime = (C1 *1) + (C2 *(n+1)) + (C3 *n) + (C4 * ((n²-n)/2) + n) + (C5 * (n²-n) / 2) +
(C6 * (n²-n) / 2) + (C7 * n)+ (C8 * n)+ (C9 * n)
Where U,V, and W are constants
= U +Vn + Wn²
= O(n²) © e-Learning Centre, UCSC 31
8.2.1.3 Insertion sort
• Point 01
Begin insertionSort(A)
for i = 1 to n
key ← A [i]
j←i–1
while j > = 0 and A[j] > key (compare the adjacent elements and if not in the correct
order)
A[j+1] ← A[j] (replace j+1 indexed element with j indexed element)
j←j–1
End while
End for
array[j+1] = key;
}
© e-Learning Centre, UCSC 37
8.2.1.3 Insertion sort
• Point 01
Example 01
https://en.wikipedia.org/wiki/Merge_sort
// base case:
if len(data) < 2:
return data
// recursive case:
left_half = data[:mid_index]
right_half = data[mid_index:]
left_half = mergeSort(left_half)
right_half = mergeSort(right_half)
return data
} © e-Learning Centre, UCSC 44
8.2.2.1 Merge sort
• Java code for merge sort algorithm
• Point 01
• Point 01
while(digit--) do:
temp := number % 10 © e-Learning Centre, UCSC 65
8.2.2.3 Radix sort
number := floor(number-temp/10)
digit := temp
if bucket[digit] exists then
bucket[digit] := bucket[digit]
if bucket[digit] is undefined then
bucket[digit] := empty list
add L[j] to bucket[digit]
reset index to 0
for digit to length(bucket) do:
if bucket[digit] exists then
for j to length(bucket[digit])
L[index++] := bucket[digit][j]
return L
end-function © e-Learning Centre, UCSC 66
8.2.2.3 Radix sort
• Point 01
https://commons.wikimedia.org/wiki/File:Heap_sort_exa
mple.gif
def heap_sort(array):
length = len(array)
array = build_heap(array)
heapify(array[:i], 0)
return array
heapify(arr, i, 0);
}
}
• Point 01
https://www.tutorialspoint.com/data_structures_algorithms/linear_search_algorithm.htm
https://brilliant.org/wiki/binary-search/
binarySearch(arr, size)
loop until beg is not equal to end
midIndex = (beg + end)/2
if (item == arr[midIndex] )
return midIndex
else if (item > arr[midIndex] )
beg = midIndex + 1
else
end = midIndex - 1
return -1
public static void binarySearch(int arr[], int first, int last, int key){
int mid = (first + last)/2;
while( first <= last ){
if ( arr[mid] < key ){
first = mid + 1;
}else if ( arr[mid] == key ){
System.out.println("Element is found at index: " + mid);
break;
}else{
last = mid - 1;
}
mid = (first + last)/2;
}
if ( first > last ){
System.out.println("Element is not found!");
}
}
© e-Learning Centre, UCSC 85
8.3.2 Binary search
• Java code for binary search - recursive approach
public static int binarySearch(int arr[], int first, int last, int key){
if (last>=first){
int mid = first + (last - first)/2;
if (arr[mid] == key){
return mid;
}
if (arr[mid] > key){
return binarySearch(arr, first, mid-1, key);//search in left subarray
}else{
return binarySearch(arr, mid+1, last, key);//search in right subarray
}
}
return -1;
}
A = list
Lo = Lowest index of the list
Hi = Highest index of the list
A[n] = Value stored at index n in the list
© e-Learning Centre, UCSC 88
8.3.3 Interpolation search
• Following is a illustration of how interpolation search
works.
Example 01
A → Array list
N → Size of A
X → Target Value
Procedure Interpolation_Search()
Set Lo → 0
Set Mid → -1
Set Hi → N-1
if A[Mid] = X
EXIT: Success, Target found at Mid
else
if A[Mid] < X
Set Lo to Mid+1
else if A[Mid] > X
Set Hi to Mid-1
end if
end if
End While
End Procedure