SlideShare a Scribd company logo
DATA STRUCTURES
DR M.RANI REDDY
FACULTY
DEFINITION
 Data structure is representation of the logical relationship
existing between individual elements of data.
 In other words, a data structure is a way of organizing all data
items that considers not only the elements stored but also
their relationship to each other.
INTRODUCTION
 Data structure affects the design of both structural &
functional aspects of a program.
Program=algorithm + Data Structure
 You know that a algorithm is a step by step procedure to solve
a particular function.
INTRODUCTION
 That means, algorithm is a set of instruction written to carry
out certain tasks & the data structure is the way of
organizing the data with their logical relationship retained.
 To develop a program of an algorithm, we should select an
appropriate data structure for that algorithm.
 Therefore algorithm and its associated data structures from a
program.
CLASSIFICATION OF DATA
STRUCTURE
 Data structure are normally divided into two broad
categories:
 Primitive Data Structure
 Non-Primitive Data Structure
CLASSIFICATION OF DATA
STRUCTURE
Data structure
Primitive DS Non-Primitive DS
Integer Float Character Pointer
Float
Integer Float
CLASSIFICATION OF DATA
STRUCTURE
Non-Primitive DS
Linear List Non-Linear List
Array
Link List Stack
Queue Graph Trees
PRIMITIVE DATA STRUCTURE
 There are basic structures and directly operated upon by
the machine instructions.
 In general, there are different representation on different
computers.
 Integer, Floating-point number, Character constants,
string constants, pointers etc, fall in this category.
NON-PRIMITIVE DATA STRUCTURE
 There are more sophisticated data structures.
 These are derived from the primitive data structures.
 The non-primitive data structures emphasize on
structuring of a group of homogeneous (same type) or
heterogeneous (different type) data items.
NON-PRIMITIVE DATA STRUCTURE
 Lists, Stack, Queue, Tree, Graph are example of non-
primitive data structures.
 The design of an efficient data structure must take
operations to be performed on the data structure.
NON-PRIMITIVE DATA STRUCTURE
 The most commonly used operation on data structure are
broadly categorized into following types:
 Create
 Selection
 Updating
 Searching
 Sorting
 Merging
 Destroy or Delete
DIFFERENT BETWEEN THEM
 A primitive data structure is generally a basic structure
that is usually built into the language, such as an integer,
a float.
 A non-primitive data structure is built out of primitive
data structures linked together in meaningful ways, such
as a or a linked-list, binary search tree, AVL Tree, graph
etc.
DESCRIPTION OF VARIOUS
DATA STRUCTURES : ARRAYS
 An array is defined as a set of finite number of
homogeneous elements or same data items.
 It means an array can contain one type of data only,
either all integer, all float-point number or all character.
ARRAYS
 Simply, declaration of array is as follows:
int arr[10]
 Where int specifies the data type or type of elements arrays
stores.
 “arr” is the name of array & the number specified inside the
square brackets is the number of elements an array can store,
this is also called sized or length of array.
ARRAYS
 Following are some of the concepts to be remembered
about arrays:
 The individual element of an array can
be accessed by specifying name of the
array, following by index or subscript
inside square brackets.
 The first element of the array has index
zero[0]. It means the first element and
last element will be specified as:arr[0] &
arr[9]
Respectively.
ARRAYS
 The elements of array will always be stored
in the consecutive (continues) memory
location.
 The number of elements that can be stored
in an array, that is the size of array or its
length is given by the following equation:
(Upperbound-lowerbound)+1
ARRAYS
 For the above array it would be
(9-0)+1=10,where 0 is the lower bound
of array and 9 is the upper bound of
array.
 Array can always be read or written
through loop. If we read a one-
dimensional array it require one loop for
reading and other for writing the array.
ARRAYS
 For example: Reading an array
For(i=0;i<=9;i++)
scanf(“%d”,&arr[i]);
 For example: Writing an array
For(i=0;i<=9;i++)
printf(“%d”,arr[i]);
ARRAYS
 If we are reading or writing two-
dimensional array it would require two
loops. And similarly the array of a N
dimension would required N loops.
 Some common operation performed on
array are:
Creation of an array
Traversing an array
ARRAYS
 Insertion of new element
 Deletion of required element
 Modification of an element
 Merging of arrays
LISTS
 A lists (Linear linked list) can be defined as a collection of
variable number of data items.
 Lists are the most commonly used non-primitive data
structures.
 An element of list must contain at least two fields, one for
storing data or information and other for storing address of
next element.
 As you know for storing address we have a special data
structure of list the address must be pointer type.
LISTS
 Technically each such element is referred to as a node,
therefore a list can be defined as a collection of nodes as
show bellow:
Head
AAA BBB CCC
Information field Pointer field
[Linear Liked List]
LISTS
 Types of linked lists:
 Single linked list
 Doubly linked list
 Single circular linked list
 Doubly circular linked list
STACK
 A stack is also an ordered collection of elements like
arrays, but it has a special feature that deletion and
insertion of elements can be done only from one end
called the top of the stack (TOP)
 Due to this property it is also called as last in first out
type of data structure (LIFO).
STACK
 It could be through of just like a stack of plates placed on table in
a party, a guest always takes off a fresh plate from the top and the
new plates are placed on to the stack at the top.
 It is a non-primitive data structure.
 When an element is inserted into a stack or removed from the
stack, its base remains fixed where the top of stack changes.
STACK
 Insertion of element into stack is called PUSH and
deletion of element from stack is called POP.
 The bellow show figure how the operations take place on
a stack:
PUSH POP
[STACK]
STACK
 The stack can be implemented into two ways:
 Using arrays (Static implementation)
 Using pointer (Dynamic
implementation)
QUEUE
 Queue are first in first out type of data structure (i.e. FIFO)
 In a queue new elements are added to the queue from one end
called REAR end and the element are always removed from
other end called the FRONT end.
 The people standing in a railway reservation row are an
example of queue.
QUEUE
 Each new person comes and stands at the end of the row
and person getting their reservation confirmed get out of
the row from the front end.
 The bellow show figure how the operations take place on
a stack:
10 20 30 40 50
front rear
QUEUE
 The queue can be implemented into two ways:
 Using arrays (Static implementation)
 Using pointer (Dynamic
implementation)
TREES
 A tree can be defined as finite set of data items (nodes).
 Tree is non-linear type of data structure in which data
items are arranged or stored in a sorted sequence.
 Tree represent the hierarchical relationship between
various elements.
TREES
 In trees:
 There is a special data item at the top of hierarchy called the
Root of the tree.
 The remaining data items are partitioned into number of
mutually exclusive subset, each of which is itself, a tree
which is called the sub tree.
 The tree always grows in length towards bottom in data
structures, unlike natural trees which grows upwards.
TREES
 The tree structure organizes the data into branches,
which related the information.
A
B C
D E F G
root
GRAPH
 Graph is a mathematical non-linear data structure
capable of representing many kind of physical structures.
 It has found application in Geography, Chemistry and
Engineering sciences.
 Definition: A graph G(V,E) is a set of vertices V and a set
of edges E.
GRAPH
 An edge connects a pair of vertices and many have
weight such as length, cost and another measuring
instrument for according the graph.
 Vertices on the graph are shown as point or circles and
edges are drawn as arcs or line segment.
GRAPH
 Example of graph:
v2
v1
v4
v5
v3
10
15
8
6
11
9
v4
v1
v2
v4
v3
[a] Directed &
Weighted Graph
[b] Undirected Graph
GRAPH
 Types of Graphs:
 Directed graph
 Undirected graph
 Simple graph
 Weighted graph
 Connected graph
 Non-connected graph
Algorithm Efficiency
Dr M.Rani Reddy
Contents
• What Is a Good Solution?
• Measuring the Efficiency of Algorithms
Algorithm Efficiency
• There are often many approaches
(algorithms) to solve a problem.
– How do we choose between them?
• At the heart of computer program design
are two (sometimes conflicting) goals
– To design an algorithm that
• is easy to understand, code, debug.
• makes efficient use of the resources.
Algorithm Efficiency (cont)
• Goal (1) is the concern of Software
Engineering.
• Goal (2) is the concern of data structures
and algorithm analysis.
• When goal (2) is important,
– how do we measure an algorithm’s cost?
What Is a Good Solution?
• Criterion
A solution is good if the total cost it incurs over
all phases of its life is minimal.
• Keep in mind, efficiency is only one aspect of a
solution’s cost
• Note: Relative importance of various
components of a solution’s cost has changed
since early days of computing.
Measuring Efficiency of Algorithms
• Comparison of algorithms should focus on
significant differences in efficiency
• Difficulties with comparing programs instead
of algorithms
– How are the algorithms coded?
– What computer should you use?
– What data should the programs use?
Execution Time of Algorithm
• Traversal of linked nodes – example:
• Displaying data in linked chain of n nodes
requires time proportional to n
Algorithm Growth Rates
• Measure algorithm’s time requirement as a
function of problem size
• Compare algorithm efficiencies for large
problems
• Look only at significant differences.
Algorithm Growth Rates
Time requirements as a function of the problem size n
Best, Worst, Average Cases
• Not all inputs of a given size take the
same time to run.
• Sequential search for K in an array of n
integers:
– Begin at first element in array and look at
each element in turn until K is found
– Best case:
– Worst case:
– Average case:
Time Analysis
Lower Bound RunningTime Upper Bound
 
• Provides upper and lower bounds of running time.
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.
Lower Bound RunningTime Upper Bound
 
Best Case
• Provides a lower bound on running time.
• Input is the one for which the algorithm runs the
fastest.
Lower Bound RunningTime Upper Bound
 
Average Case
• Provides an estimate of “average” running time.
• Assumes that the input is random.
• Useful when best/worst cases do not happen
very often
– i.e., few input cases lead to best/worst cases.
Lower Bound RunningTime Upper Bound
 
Which Analysis to Use?
• While average time appears to be the
fairest measure,
– it may be difficult to determine.
• When is the worst case time important?
How to Measure Efficiency?
• Critical resources:
– Time, memory, battery, bandwidth, programmer
effort, user effort
• Factors affecting running time:
– For most algorithms, running time depends on
“size” of the input.
– Running time is expressed as T(n) for some
function T on input size n.
53
How do we analyze an algorithm?
• Need to define objective measures.
(1) Compare execution times?
Empirical comparison (run programs)
Not good: times are specific to a particular machine.
(2) Count the number of statements?
Not good: number of statements varies with
programming language and programming style.
How do we analyze an algorithm?
(cont.)
(3) Express running time t as a function
of problem size n (i.e., t=f(n) )
Asymptotic Algorithm Analysis
- Given two algorithms having running times
f(n) and g(n),
- find which functions grows faster
- Such an analysis is independent of
machine time, programming style, etc.
Comparing algorithms
• Given two algorithms having running times
f(n) and g(n), how do we decide which one
is faster?
• Compare “rates of growth” of f(n) and g(n)
Understanding Rate of Growth
• The low order terms of a function are relatively
insignificant for large n
n4 + 100n2 + 10n + 50
Approximation:
n4
• Highest order term determines rate of growth!
Visualizing Orders of Growth
• On a graph, as
you go to the
right, a faster
growing
function
eventually
becomes
larger...
fA(n)=30n+8
Increasing n 
fB(n)=n2+1
Value
of
function

Rate of growth
• The graphs of 3  n2 and n2 - 3  n + 10
Rate of Growth ≡ Asymptotic Analysis
• Using rate of growth as a measure to
compare different functions implies
comparing them asymptotically
– i.e., as n 
• If f(x) is faster growing than g(x), then f(x)
always eventually becomes larger than g(x)
in the limit
– i.e., for large enough values of x

Complexity
• Let us assume two algorithms A and B that solve
the same class of problems.
• The time complexity of A is 5,000n,
the one for B is 1.1n for an input with n elements
• For n = 10,
– A requires 50,000 steps,
– but B only 3,
– so B seems to be superior to A.
• For n = 1000, A requires 5106 steps,
– while B requires 2.51041 steps.
Names of Orders of Magnitude
O(1) bounded (by a constant) time
O(log2N) logarithmic time
O(N) linear time
O(N*log2N) N*log2N time
O(N2) quadratic time
O(N3) cubic time
O(2N ) exponential time
Order of growth of common functions
< O(n!)
Example
Growth
Rate
Graph
A comparison of growth-rate functions
N log2N N*log2N N2 2N
1 0 0 1 2
2 1 2 4 4
4 2 8 16 16
8 3 24 64 256
16 4 64 256 65,536
32 5 160 1024 4.29*109
64 6 384 4096 1.84*1019
128 7 896 16,384 3.40*1038
A comparison of growth-rate functions
Sample Execution Times
The Growth of Functions
• A problem that can be solved with polynomial
worst-case complexity is called tractable
• Problems of higher complexity are called
intractable
• Problems that no algorithm can solve are called
unsolvable
Analysis and Big O Notation
• Definition:
– Algorithm A is order f ( n )
• Denoted O( f ( n ))
– If constants k and n0 exist
– Such that A requires no more than k  f ( n ) time
units to solve a problem of size n ≥ n0 .
Asymptotic Notation
O notation: asymptotic “less than”:
f(n)=O(g(n)) implies: f(n) “≤” c g(n) in the limit*
(used in worst-case analysis)
*formal definition in CS477/677
c is a constant
Asymptotic Notation
 notation: asymptotic “greater than”:
f(n)=  (g(n)) implies: f(n) “≥” c g(n) in the limit*
(used in best-case analysis)
*formal definition in CS477/677
c is a constant
Asymptotic Notation
 notation: asymptotic “equality”:
f(n)=  (g(n)) implies: f(n) “=” c g(n) in the limit*
(provides a tight bound of running time)
(best and worst cases are same)
*formal definition in CS477/677
c is a constant
More on big-O
f(n) ϵ O(g(n)) if “f(n)≤cg(n)”
O(g(n)) is a set of functions f(n)
A Common Misunderstanding
Confusing worst case with upper bound.
Upper bound refers to a growth rate.
Worst case refers to the worst input from
among the choices for possible inputs of
a given size.
Algorithm speed vs function growth
• An O(n2) algorithm will be slower than an O(n)
algorithm (for large n).
• But an O(n2) function will grow faster than an O(n)
function.
fA(n)=30n+8
Increasing n 
fB(n)=n2+1
Value
of
function

Faster Computer or Algorithm?
• Suppose we buy a computer 10 times faster.
– n: size of input that can be processed in one
second on old computer
• in 1000 computational units
– n’: size of input that can be processed in one
second on new computer
T(n) n n’ Change n’/n
10n 100 1,000 n’ = 10n 10
10n2 10 31.6 n’= 10n 3.16
10n 3 4 n’ = n + 1 1 + 1/n
How do we find f(n)?
(1) Associate a "cost" with each statement
(2) Find total number of times each statement
is executed
(3) Add up the costs
Properties of Growth-Rate Functions
• Ignore low-order terms
• Ignore a multiplicative constant in the high-
order term
• O(f(n)) + O(g(n)) = O(f(n) + g(n))
• Be aware of worst case, average case
Keeping Your Perspective
• Array-based getEntry is O(1)
• Link-based getEntry is O(n)
• Consider how frequently particular ADT
operations occur in given application
• Some seldom-used but critical operations
must be efficient
Keeping Your Perspective
• If problem size always small, ignore an
algorithm’s efficiency
• Weigh trade-offs between algorithm’s time
and memory requirements
• Compare algorithms for both style and
efficiency
Efficiency of Searching Algorithms
• Sequential search
– Worst case O(n)
– Average case O(n)
– Best case O(1)
• Binary search of sorted array
– Worst case O(log2n)
– Remember required overhead for keeping array
sorted
i = 0;
while (i<N) {
X=X+Y; // O(1)
result = mystery(X); // O(N)
i++; // O(1)
}
• The body of the while loop: O(N)
• Loop is executed: N times
N x O(N) = O(N2)
Running Time Examples
if (i<j)
for ( i=0; i<N; i++ )
X = X+i;
else
X=0;
Max ( O(N), O(1) ) = O (N)
O(N)
O(1)
Running Time Examples
Running Time Examples (cont.’d)
Algorithm 1 Cost
arr[0] = 0; c1
arr[1] = 0; c1
arr[2] = 0; c1
...
arr[N-1] = 0; c1
-----------
c1+c1+...+c1 = c1 x N
Algorithm 2 Cost
for(i=0; i<N; i++) c2
arr[i] = 0; c1
-----------
(N+1) x c2 + N x c1 = (c2 + c1) x N + c2
Cost
sum = 0; c1
for(i=0; i<N; i++) c2
for(j=0; j<N; j++) c2
sum += arr[i][j]; c3
------------
c1 + c2 x (N+1) + c2 x N x (N+1) + c3 x N x N
87
Running Time Examples (cont.’d)
Complexity Examples
What does the following algorithm compute?
int who_knows(int a[n]) {
int m = 0;
for {int i = 0; i<n; i++}
for {int j = i+1; j<n; j++}
if ( abs(a[i] – a[j]) > m )
m = abs(a[i] – a[j]);
return m;
}
returns the maximum difference between any two
numbers in the input array
Comparisons: n-1 + n-2 + n-3 + … + 1 = (n-1)n/2 = 0.5n2 - 0.5n
Time complexity is O(n2)
Complexity Examples
Another algorithm solving the same problem:
int max_diff(int a[n]) {
int min = a[0];
int max = a[0];
for {int i = 1; i<n; i++}
if ( a[i] < min )
min = a[i];
else if ( a[i] > max )
max = a[i];
return max-min;
}
Comparisons: 2n - 2
Time complexity is O(n).
Examples of Growth Rate
/* @return Position of largest value in "A“ */
static int largest(int[] A) {
int currlarge = 0; // Position of largest
for (int i=1; i<A.length; i++)
if (A[currlarge] < A[i])
currlarge = i; // Remember position
return currlarge; // Return largest
position
}
Examples (cont)
sum = 0;
for (i=1; i<=n; i++)
for (j=1; j<=n; j++)
sum++;
Time Complexity Examples (1)
a = b;
This assignment takes constant time, so it is
(1).
sum = 0;
for (i=1; i<=n; i++)
sum += n;
Time Complexity Examples (2)
sum = 0;
for (j=1; j<=n; j++)
for (i=1; i<=j; i++)
sum++;
for (k=0; k<n; k++)
A[k] = k;
Time Complexity Examples (3)
sum1 = 0;
for (i=1; i<=n; i++)
for (j=1; j<=n; j++)
sum1++;
sum2 = 0;
for (i=1; i<=n; i++)
for (j=1; j<=i; j++)
sum2++;
Time Complexity Examples (4)
sum1 = 0;
for (k=1; k<=n; k*=2)
for (j=1; j<=n; j++)
sum1++;
sum2 = 0;
for (k=1; k<=n; k*=2)
for (j=1; j<=k; j++)
sum2++;
Example
Analyze the complexity of the following code
Linked Lists
By
Dr M.Rani Reddy
Concepts of linked list
• A linked list is a linear collection of data elements
called nodes in which linear representation is given by
links from one node to the next node.
• Similar to array, it is a linear collection of data
elements of the same type.
• Different from array, data elements of linked list are
generally not lined in consecutive memory space;
instead they are dispersed in various locations
Concepts of linked list
• Linked list is a data structure which in turn can be
used to implement other data structures. Thus, it acts
as building block to implement data structures like
stacks, queues and their variations.
• A linked list can be perceived as a train or a sequence
of nodes in which each node contains one or more
data fields and a pointer to the next node.
Element of linked list
• Linked list element (node) is user defined structure
data type, typically contains two parts
 data variables
 pointers to next elements, hold the addresses of
next elements
Example:
struct node {
int data; // data
struct node *next; // pointer to next element
};
Simple Linked List
1 2 3 4 5 6 7 X
START
• In the above linked list, every node contains two parts - one
integer and the other a pointer to the next node.
• The data part of the node which contains data may include a
simple data type, an array or a structure.
• The pointer part of the node contains a pointer to the next node
(or address of the next node in sequence).
• The last node will have no next node connected to it, so it will
store a NULL value.
• A linked list is defined by the pointer pointing to the first node,
e.g START
Linked List Operations
1. Create a node and linked list
2. Traversal, e.g. display all elements
3. Search node
4. Insert node
at beginning, at end, after/before a node
5. Delete node
at beginning, at end, after/before a node
6. Sort
How to create nodes
A node is a structure data type, can be created in
two methods, statically and dynamically.
•Static method
– use array of structures
– declared as globally outside functions
– declared locally within a function
•Dynamic method (mostly used for linked list)
– use stdlib function malloc(size) get memory space
struct node *np = (struct node*) malloc(sizeof(struct node));
How to create nodes
struct node *np = (struct node*) malloc(sizeof(struct node));
At run time, OS allocates consecutive sizeof(struct node)
bytes in the heap region,
return the address of the address of the first memory cell,
store the address to struct node type pointer np.
Need (struct node*) to cast the return address to struct
node pointer value.
Need use free(np) to release when deleting the node!!!
Otherwise cause memory leaking
Traversing Linked Lists
• We can traverse the entire linked list using a
single pointer variable called START.
• The START node contains the address of the first
node; the next part of the first node in turn
stores the address of its succeeding node.
• Using this technique the individual nodes of the
list will form a chain of nodes.
• If START = NULL, this means that the linked list is
empty and contains no nodes.
Singly Linked Lists
• A singly linked list is the simplest type of linked list in which
every node contains some data and a pointer to the next node
of the same data type.
Example:
struct node {
int data;
struct node *next;
};
1 2 3 4 5 6 7 X
START
Traversal Singly Linked Lists
ALGORITHM FOR TRAVERSING A LINKED LIST
Step 1: [INITIALIZE] SET PTR = START
Step 2: Repeat Steps 3 and 4 while PTR != NULL
Step 3: Apply Process to PTR->DATA
Step 4: SET PTR = PTR->NEXT
[END OF LOOP]
Step 5: EXIT
void display(struct node *ptr) {
while(ptr != NULL) {
printf("%d ", ptr->data); // process
ptr = ptr->next;
}
}
Call as display(START);
Searching for Val 4 in Linked List
1 7 3 4 2 6 5 X
PTR
1 7 3 4 2 6 5 X
PTR
1 7 3 4 2 6 5 X
PTR
1 7 3 4 2 6 5 X
PTR
Searching a Linked List
ALGORITHM TO SEARCH A LINKED LIST
Step 1: [INITIALIZE] SET PTR = START
Step 2: Repeat Step 3 while PTR != NULL
Step 3: IF VAL = PTR->DATA
SET POS = PTR
Go To Step 5
ELSE
SET PTR = PTR->NEXT
[END OF IF]
[END OF LOOP]
Step 4: SET POS = NULL // not found
Step 5: EXIT // found, output POS
struct node* search(struct node *ptr, int num) {
while((ptr != NULL) && (ptr->data != num)) {
ptr = ptr->next;
}
return ptr;
}
// call example, search(START, 4)
Inserting a Node at the Beginning
1 7 3 4 2 6 5 X
START
START
9 1 7 3 4 2 6 5 X
ALGORITHM: INSERT A NEW NODE IN THE BEGINNING OF THE LINKED LIST
Step 1: IF AVAIL = NULL, then
Write OVERFLOW
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
See example
Inserting a Node at the End
1 7 3 4 2 6 5 X
START, PTR
1 7 3 4 2 6 5 9 X
START
ALGORITHM TO INSERT A NEW NODE AT THE END OF THE LINKED LIST
Step 1: IF AVAIL = NULL, then
Write OVERFLOW
Go to Step 10
[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 = NULL
Step 6: SET PTR = START
Step 7: Repeat Step 8 while PTR->NEXT != NULL
Step 8: SET PTR = PTR ->NEXT
[END OF LOOP]
Step 9: SET PTR->NEXT = New_Node
Step 10: EXIT
Inserting a Node after Node that ahs Value NUM
ALGORITHM TO INSERT A NEW NODE AFTER A NODE THAT HAS VALUE
NUM
Step 1: IF AVAIL = NULL, then
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 10: PREPTR->NEXT = New_Node
Step 11: SET New_Node->NEXT = PTR
Step 12: EXIT
Deleting the First Node
1 7 3 4 2 6 5 X
7 3 4 2 6 5 X
START
START
Algorithm to delete the first node from the linked
list
Step 1: IF START = NULL, then
Write UNDERFLOW
Go to Step 5
[END OF IF]
Step 2: SET PTR = START
Step 3: SET START = START->NEXT
Step 4: FREE PTR
Step 5: EXIT
Deleting the Last Node
1 7 3 4 2 6 5 X
START, PREPTR, PTR
1 7 3 4 2 6 X 5 X
PREPTR PTR
START
ALGORITHM TO DELETE THE LAST NODE OF THE LINKED LIST
Step 1: IF START = NULL, then
Write UNDERFLOW
Go to Step 8
[END OF IF]
Step 2: SET PTR = START
Step 3: Repeat Steps 4 and 5 while PTR->NEXT != NULL
Step 4: SET PREPTR = PTR
Step 5: SET PTR = PTR->NEXT
[END OF LOOP]
Step 6: SET PREPTR->NEXT = NULL
Step 7: FREE PTR
Step 8: EXIT
Deleting the Node After a Given Node
1 7 3 4 2 6 5 X
START, PREPTR, PTR
1 7 3 4 2 6 5 X
PREPTR PTR
START
1 7 3 4 2 6 5 X
START
1 7 3 4 6 5 X
Deleting the Node After a Given Node
ALGORITHM TO DELETE THE NODE AFTER A GIVEN NODE FROM THE
LINKED LIST
Step 1: IF START = NULL, then
Write UNDERFLOW
Go to Step 10
[END OF IF]
Step 2: SET PTR = START
Step 3: SET PREPTR = PTR
Step 4: Repeat Step 5 and 6 while PRETR->DATA != NUM
Step 5: SET PREPTR = PTR
Step 6: SET PTR = PTR->NEXT
[END OF LOOP]
Step7: SET TEMP = PTR->NEXT
Step 8: SET PREPTR->NEXT = TEMP->NEXT
Step 9: FREE TEMP
Step 10: EXIT
Circular Linked List
• In a circular linked list, the last node contains a pointer to the first
node of the list. We can have a circular singly listed list as well as
circular doubly linked list. While traversing a circular linked list,
we can begin at any node and traverse the list in any direction
forward or backward until we reach the same node where we had
started. Thus, a circular linked list has no beginning and no
ending.
1 2 3 4 5 6 7
START
Circular Linked List
Algorithm to insert a new node in the beginning of
circular the linked list
Step 1: IF AVAIL = NULL, then
Write OVERFLOW
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 PTR = START
Step 6: Repeat Step 7 while PTR->NEXT != START
Step 7: PTR = PTR->NEXT
Step 8: SET New_Node->Next = START
Step 8: SET PTR->NEXT = New_Node
Step 6: SET START = New_Node
Step 7: EXIT
Circular Linked List
1 7 3 4 2 6 5
START, PTR
1 7 3 4 2 6 5
START
PTR
9 1 7 3 4 2 6 5
START
Circular Linked List
Algorithm to insert a new node at the end of the circular
linked list
Step 1: IF AVAIL = NULL, then
Write OVERFLOW
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 PTR = START
Step 7: Repeat Step 8 while PTR->NEXT != START
Step 8: SET PTR = PTR ->NEXT
[END OF LOOP]
Step 9: SET PTR ->NEXT = New_Node
Step 10: EXIT
Circular Linked List
1 7 3 4 2 6 5
START, PTR
1 7 3 4 2 6 5 9
START PTR
Circular Linked List
Algorithm to insert a new node after a node that has
value NUM
Step 1: IF AVAIL = NULL, then
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 Step 8 and 9 while PTR->DATA != NUM
Step 8: SET PREPTR = PTR
Step 9: SET PTR = PTR->NEXT
[END OF LOOP]
Step 10: PREPTR->NEXT = New_Node
Step 11: SET New_Node->NEXT = PTR
Step 12: EXIT
Circular Linked List
Algorithm to delete the first node from the circular linked list
Step 1: IF START = NULL, then
Write UNDERFLOW
Go to Step 8
[END OF IF]
Step 2: SET PTR = START
Step 3: Repeat Step 4 while PTR->NEXT != START
Step 4: SET PTR = PTR->NEXT
[END OF IF]
Step 5: SET PTR->NEXT = START->NEXT
Step 6: FREE START
Step 7: SET START = PTR->NEXT
Step 8: EXIT
Circular Linked List
1 7 3 4 2 6 5
START, PTR
1 7 3 4 2 6 5
START
PTR
7 3 4 2 6 5
START
Circular Linked List
Algorithm to delete the last node of the circular linked
list
Step 1: IF START = NULL, then
Write UNDERFLOW
Go to Step 8
[END OF IF]
Step 2: SET PTR = START
Step 3: Repeat Step 4 while PTR->NEXT != START
Step 4: SET PREPTR = PTR
Step 5: SET PTR = PTR->NEXT
[END OF LOOP]
Step 6: SET PREPTR->NEXT = START
Step 7: FREE PTR
Step 8: EXIT
Circular Linked List
1 7 3 4 2 6 5
START, PREPTR, PTR
1 7 3 4 2 6 5
START
PTR
PREPTR
1 7 3 4 2 6
START
Circular Linked List
Algorithm to delete the node after a given node from the circular linked list
Step 1: IF START = NULL, then
Write UNDERFLOW
Go to Step 9
[END OF IF]
Step 2: SET PTR = START
Step 3: SET PREPTR = PTR
Step 4: Repeat Step 5 and 6 while PREPTR->DATA != NUM
Step 5: SET PREPTR = PTR
Step 6: SET PTR = PTR->NEXT
[END OF LOOP]
Step 7: SET PREPTR->NEXT = PTR->NEXT
Step 8: FREE PTR
Step 9: EXIT
Circular Linked List
1 7 3 4 2 6 5
START, PREPTR, PTR
1 7 3 4 2 6 5
START PREPTR PTR
1 7 3 4 6 5
START
Doubly Linked List
 A doubly linked list or a two way linked list is a more complex
type of linked list which contains a pointer to the next as well
as previous node in the sequence. Therefore, it consists of
three parts and not just two. The three parts are data, a
pointer to the next node and a pointer to the previous node
1
X 1 2 3 4 X
START
Doubly Linked List
• In C language, the structure of a doubly linked list is given as,
struct node
{ struct node *prev;
int data;
struct node *next;
};
• The prev field of the first node and the next field of the last
node will contain NULL. The prev field is used to store the
address of the preceding node. This would enable to traverse
the list in the backward direction as well.
Doubly Linked List
1 7 3 4 2 X
X
9 1 7 3 4
X 2 X
START
START
Algorithm to insert a new node in the beginning of the
doubly linked list
Step 1: IF AVAIL = NULL, then
Write OVERFLOW
Go to Step 8
[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->PREV = NULL
Step 6: SET New_Node->Next = START
Step 7: SET START = New_Node
Step 8: EXIT
Doubly Linked List
1 7 3 4 2 X
X
START, PTR
1 7 3 4 2
X 9 X
PTR
Algorithm to insert a new node at the end of the doubly linked list
Step 1: IF AVAIL = NULL, then
Write OVERFLOW
Go to Step 11
[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 = NULL
Step 6: SET PTR = START
Step 7: Repeat Step 8 while PTR->NEXT != NULL
Step 8: SET PTR = PTR->NEXT
[END OF LOOP]
Step 9: SET PTR->NEXT = New_Node
Step 10: New_Node->PREV = PTR
Step 11: EXIT
Doubly Linked List
Algorithm to insert a new node after a node that has
value NUM
Step 1: IF AVAIL = NULL, then
Write OVERFLOW
Go to Step 11
[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: Repeat Step 8 while PTR->DATA != NUM
Step 7: SET PTR = PTR->NEXT
[END OF LOOP]
Step 8: New_Node->NEXT = PTR->NEXT
Step 9: SET New_Node->PREV = PTR
Step 10: SET PTR->NEXT = New_Node
Step 11: EXIT
Doubly Linked List
1 7 3 4 2 X
X
START, PTR
1 7 3 4 2 X
X
9
1 7 3 9 4
X 2 X
START
START PTR
Doubly Linked List
1 7 3 4 2 X
X
START, PTR
7 3 4 2 X
Algorithm to delete the first node from the doubly linked
list
Step 1: IF START = NULL, then
Write UNDERFLOW
Go to Step 6
[END OF IF]
Step 2: SET PTR = START
Step 3: SET START = START->NEXT
Step 4: SET START->PREV = NULL
Step 5: FREE PTR
Step 6: EXIT
Doubly Linked List
1 3 5 7 8
X 9
1
X
START, PTR
1 3 5 7 8
X 9
1
X
START PTR
1 3 5 7 8 X
X
START
Algorithm to delete the last node of the doubly linked list
Step 1: IF START = NULL, then
Write UNDERFLOW
Go to Step 7
[END OF IF]
Step 2: SET PTR = START
Step 3: Repeat Step 4 and 5 while PTR->NEXT != NULL
Step 4: SET PTR = PTR->NEXT
[END OF LOOP]
Step 5: SET PTR->PREV->NEXT = NULL
Step 6: FREE PTR
Step 7: EXIT
Doubly Linked List
Algorithm to delete the node after a given node from the
doubly linked list
Step 1: IF START = NULL, then
Write UNDERFLOW
Go to Step 9
[END OF IF]
Step 2: SET PTR = START
Step 3: Repeat Step 4 while PTR->DATA != NUM
Step 4: SET PTR = PTR->NEXT
[END OF LOOP]
Step 5: SET TEMP = PTR->NEXT
Step 6: SET PTR->NEXT = TEMP->NEXT
Step 7: SET TEMP->NEXT->PREV = PTR
Step 8: FREE TEMP
Step 9: EXIT
Doubly Linked List
1 3 4 7 8
X 9
1
X
1 3 4 7 8
X 9
1
X
1 3 4 8 9 X
X
START, PTR
START
PTR
START
Atomic Node Linked List
© Oxford University Press 2013. All rights
reserved.
Linked List in Arrays
•An array is the data structure contains a collection of similar
type data elements whereas the Linked list is considered as
non-primitive data structure contains a collection of unordered
linked elements known as nodes.
•In the array the elements belong to indexes, i.e., if you want
to get into the fourth element you have to write the variable
name with its index or location within the square bracket.
In a linked list though, you have to start from the head and
work your way through until you get to the fourth element.
•While accessing an element array is fast while Linked list
takes linear time so, it is quite bit slower.
Key Differences Between Array and Linked List
•Operations like insertion and deletion in arrays consume a lot
of time. On the other hand, the performance of these
operations in Linked lists is fast.
•Arrays are of fixed size. In contrast, Linked lists are dynamic
and flexible and can expand and contract its size.
•In an array, memory is assigned during compile time while in
a Linked list it is allocated during execution or runtime.
•Elements are stored consecutively in arrays whereas it is
stored randomly in Linked lists.
•The requirement of memory is less due to actual data being
stored within the index in the array. As against, there is a
need for more memory in Linked Lists due to storage of
additional next and previous referencing elements.
•In addition memory utilization is inefficient in the array.
Conversely, memory utilization is efficient in the array.
Contd…
CIRCULAR & DEQUEUE
BY
Dr M.RANI REDDY
Limitation of Simple Queue
 At that time our program will flash the message
“Queue is full”.
 But if the queue is too large of say 5000 elements it
will be a tedious job to do and time consuming too.
 To remove this problem we use circular queue.
Circular Queue
 A circular queue is one in which the insertion of a
new element is done at the very first location of the
queue if the last location of the queue is full.
 In other words if we have a queue Q of say n
elements, then after inserting an element last (n-1th)
location of the array the next elements will be
inserted at the very first location (0) of the array.
 It is possible to insert new elements, if and only if
those location (slots) are empty.
Circular Queue
 We can say that a circular queue is one in which the
first element comes just after the last element.
 It can be viewed as a mesh or loop of wire, in which
the two ends of the wire are connected together.
 A circular queue overcomes the problem of
unutilized space in linear queues implemented as
arrays.
 A circular queue also have a Front and Rear to keep
the track of the elements to be deleted and inserted
and therefore to maintain the unique characteristic
of the queue.
Circular Queue
 Bellow show a figure a empty circular queue Q[5]
which can accommodate five elements.
`
Q[0] Q[1]
Q[2]
Q[3]
Q[4]
Fig: Circular Queue
Double Ended Queue (Deque)
 It is also a homogeneous list of elements in which
insertion and deletion operations are performed
from both the ends.
 That is, we can insert elements from the rear end or
from the front ends.
 Hence it is called double-ended queue. It is
commonly referred as a Deque.
 There are two types of Deque. These two types are
due to the restrictions put to perform either the
insertions or deletions only at one end.
Double Ended Queue (Deque)
 There are:
 Input-restricted Deque.
 Output-restricted Deque.
 Bellow show a figure a empty Deque Q[5] which
can accommodate five elements.
Q[0] Q[1] Q[2] Q[3] Q[4]
deletion
deletion
insertion
insertion
Fig: A Deque
Double Ended Queue (Deque)
 There are:
 Input-restricted Deque: An input restricted
Deque restricts the insertion of the elements at
one end only, the deletion of elements can be
done at both the end of a queue.
10 20 30 40 50
Q[0] Q[1] Q[2] Q[3] Q[4]
deletion
deletion
insertion
Fig: A representation of an input-restricted Deque
F R
Double Ended Queue (Deque)
 There are:
 Output-restricted Deque: on the contrary, an
Output-restricted Deque, restricts the deletion of
elements at one end only, and allows insertion to
be done at both the ends of a Deque.
10 20 30 40 50
Q[0] Q[1] Q[2] Q[3] Q[4]
insertion
deletion
insertion
Fig: A representation of an Output-restricted Deque
F R
Double Ended Queue (Deque)
 The programs for input-restricted Deque and
output-restricted Deque would be similar to the
previous program of Deque except for a small
difference.
 The program for the input-restricted Deque would
not contain the function addqatbeg().
 Similarly the program for the output-restricted
Deque would not contain the function delatbeg().
Priority Queue
 A priority queue is a collection of elements where
the elements are stored according to their priority
levels.
 The order in which the elements should get added or
removed is decided by the priority or the element.
 Following rules are applied to maintain a priority
queue.
 The element with a higher priority is processes
before any element of lower priority.
Priority Queue
 If there are elements with same priority, then the
element added first in the queue would get
processed
 Here, smallest number that is most highest priority
and greater number that is less priority.
 Priority queues are used for implementing job
scheduling by the operating system.
 Where jobs with higher priorities are to be processed
first.
 Another application of priority queue is simulation
systems where priority corresponds to event times.
Applications of Queues
 Round robin technique for processor scheduling is
implemented using queues.
 All types of customer service (like railway ticket
reservation) center software’s are designed using
queues to store customers information.
 Printer server routines are designed using queues. A
number of users share a printer using printer server
the printer server then spools all the jobs from all the
users, to the server’s hard disk in a queue. From here
jobs are printed one-by-one according to their
number in the queue.
Stack and Queue
Dr M.Rani Reddy
159
Stack From Two Queues
Describe how to implement the stack
ADT using two queues
The solution should only use the
standard queue operations:
ENQUEUE, DEQUEUE, IS-EMPTY
What will be the running times
of the PUSH and POP operations?
160
Stack From Two Queues –
Solution
We will call the two queues Q1 and Q2
Additionally, we will hold a variable
called curQueue, which points to the
queue that holds the last value pushed
to our stack
Initialization: curQueue  Q1
161
Stack From Two Queues –
Solution (continued)
IS-EMPTY
return IS-EMPTY (curQueue)
PUSH (val)
ENQUEUE (curQueue, val)
TOP
val  POP
PUSH (val)
return val
162
Stack From Two Queues –
Solution (continued)
POP
otherQueue  (curQueue = Q1)? Q2: Q1
while (!IS-EMPTY (curQueue))
temp  DEQUEUE (curQueue)
if (!IS-EMPTY (curQueue)) // Not last?
ENQUEUE (otherQueue, temp)
curQueue  otherQueue
return temp
163
Stack From Two Queues –
Solution Complexity
Since PUSH is simply implemented as a
single ENQUEUE operation, its running
time is O(1)
For POP operations, we always need to
transfer the complete stack contents
from one queue to the other, therefore
performing a POP takes O(n) time
164
Two Stacks in a Single Array
Describe how to implement two stacks
inside a single array
The total number of elements in both
stacks is limited by the array length
Therefore, just splitting the array into two
equally-sized parts will not do
All stack operations should run in O(1)
165
Two Stacks in a Single Array –
Solution Concept
We are given an array A with n
elements, numbered 0 to n – 1
We define two markers t1 and t2
that point to the next free cell in
stacks S1 and S2 respectively
Initialization:
t1 = 0
t2 = n – 1
166
Two Stacks in a Single Array –
Solution Concept
S1 grows up from the beginning of the
array, S2 grows down from its end
We know that the array is full when the
two markers switch places (t1 > t2)
The complexity is O(1) for all operations
The array usage is optimal
167
Two Stacks in a Single Array –
Solution Visualization
7 3 2 9 5 6 2
t1 t2
S1 S2
168
Two Stacks in a Single Array –
Solution Details
S1.IS-EMPTY
if (t1 = 0)
return true
else
return false
S2.IS-EMPTY
if (t2 = n - 1)
return true
else
return false
169
Two Stacks in a Single Array –
Solution Details (continued)
S1.PUSH (val)
if (t1 > t2)
error "stack overflow"
A[t1] = val
t1++
S2.PUSH (val)
if (t1 > t2)
error "stack overflow"
A[t2] = val
t2--
170
Two Stacks in a Single Array –
Solution Details (continued)
S1.POP
if (t1 = 0)
error "stack underflow"
t1--
return A[t1]
S2.POP
if (t2 = n - 1)
error "stack underflow"
t2++
return A[t2]
171
Two Stacks in a Single Array –
Solution Details (continued)
S1.TOP
if (t1 = 0)
error "stack is empty"
return A[t1]
S2.TOP
if (t2 = n - 1)
error "stack is empty"
return A[t2]
172
Evaluating Arithmetic
Expressions
Fully parenthesized arithmetic
expressions can be evaluated using
Dijkstra's two-stack algorithm
Uses two separate stacks – one for the
operators and another for the operands
See Java code in: Evaluate.java.html
173
Deque
(or Double-Ended Queue)
A deque is a generalization of the
Queue ADT, that supports reading and
writing from both ends of the queue
We would like to support an input-
restricted deque :
Deletion can be made from both ends
Input can only be made at one end
174
Deque
We note that an input-restricted deque
is a combination of a queue and a stack
We use a standard queue, and modify it
to also support PUSH and POP
The tail (or rear) of the queue will
also be used as the stack top
175
Deque
Implementing PUSH is now trivial –
simply call ENQUEUE
POP is very similar to DEQUEUE, accept
that it returns tail instead of head
The same IS-EMPTY function will work
for both the stack and the queue
Check if head = tail
176
Deque
9 5 6 2 0 3
head
(front)
DEQUEUE
ENQUEUE
PUSH
POP
tail
(rear)

More Related Content

Similar to data structures module I & II.pptx

intr_ds.ppt
intr_ds.pptintr_ds.ppt
intr_ds.ppt
PrakharNamdev3
 
DS_PPT.ppt
DS_PPT.pptDS_PPT.ppt
DS_PPT.ppt
MeghaKulkarni27
 
Data structures - Introduction
Data structures - IntroductionData structures - Introduction
Data structures - Introduction
DeepaThirumurugan
 
DS Module 1.pptx
DS Module 1.pptxDS Module 1.pptx
DS Module 1.pptx
sarala9
 
DS Module 1.pptx
DS Module 1.pptxDS Module 1.pptx
DS Module 1.pptx
SaralaT3
 
Datastructures and algorithms prepared by M.V.Brehmanada Reddy
Datastructures and algorithms prepared by M.V.Brehmanada ReddyDatastructures and algorithms prepared by M.V.Brehmanada Reddy
Datastructures and algorithms prepared by M.V.Brehmanada ReddyMalikireddy Bramhananda Reddy
 
Introduction to data structure ppt
Introduction to data structure pptIntroduction to data structure ppt
Introduction to data structure ppt
NalinNishant3
 
UNITIII LDS.pdf
UNITIII LDS.pdfUNITIII LDS.pdf
UNITIII LDS.pdf
meenamadhuvandhi2
 
Introduction to Data Structure.pptx
Introduction to Data Structure.pptxIntroduction to Data Structure.pptx
Introduction to Data Structure.pptx
GlenardDSarmiento
 
Introduction to data structure
Introduction to data structureIntroduction to data structure
Introduction to data structure
adeel hamid
 
Data structure ppt
Data structure pptData structure ppt
Data structure ppt
Prof. Dr. K. Adisesha
 
2. Introduction to Data Structure.pdf
2. Introduction to Data Structure.pdf2. Introduction to Data Structure.pdf
2. Introduction to Data Structure.pdf
SulabhPawaia
 
DS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and EngineeringDS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and Engineering
RAJASEKHARV8
 
Unit 1.ppt
Unit 1.pptUnit 1.ppt
Unit 1.ppt
Minakshee Patil
 
Which data structure is it? What are the various data structure kinds and wha...
Which data structure is it? What are the various data structure kinds and wha...Which data structure is it? What are the various data structure kinds and wha...
Which data structure is it? What are the various data structure kinds and wha...
Tutort Academy
 
Presentation on Data Structure
Presentation on Data StructurePresentation on Data Structure
Presentation on Data Structure
A. N. M. Jubaer
 
Bc0038– data structure using c
Bc0038– data structure using cBc0038– data structure using c
Bc0038– data structure using chayerpa
 
Data structure
 Data structure Data structure
Data structure
Shahariar limon
 

Similar to data structures module I & II.pptx (20)

intr_ds.ppt
intr_ds.pptintr_ds.ppt
intr_ds.ppt
 
DS_PPT.pptx
DS_PPT.pptxDS_PPT.pptx
DS_PPT.pptx
 
DS_PPT.ppt
DS_PPT.pptDS_PPT.ppt
DS_PPT.ppt
 
Data structures - Introduction
Data structures - IntroductionData structures - Introduction
Data structures - Introduction
 
Intro ds
Intro dsIntro ds
Intro ds
 
DS Module 1.pptx
DS Module 1.pptxDS Module 1.pptx
DS Module 1.pptx
 
DS Module 1.pptx
DS Module 1.pptxDS Module 1.pptx
DS Module 1.pptx
 
Datastructures and algorithms prepared by M.V.Brehmanada Reddy
Datastructures and algorithms prepared by M.V.Brehmanada ReddyDatastructures and algorithms prepared by M.V.Brehmanada Reddy
Datastructures and algorithms prepared by M.V.Brehmanada Reddy
 
Introduction to data structure ppt
Introduction to data structure pptIntroduction to data structure ppt
Introduction to data structure ppt
 
UNITIII LDS.pdf
UNITIII LDS.pdfUNITIII LDS.pdf
UNITIII LDS.pdf
 
Introduction to Data Structure.pptx
Introduction to Data Structure.pptxIntroduction to Data Structure.pptx
Introduction to Data Structure.pptx
 
Introduction to data structure
Introduction to data structureIntroduction to data structure
Introduction to data structure
 
Data structure ppt
Data structure pptData structure ppt
Data structure ppt
 
2. Introduction to Data Structure.pdf
2. Introduction to Data Structure.pdf2. Introduction to Data Structure.pdf
2. Introduction to Data Structure.pdf
 
DS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and EngineeringDS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and Engineering
 
Unit 1.ppt
Unit 1.pptUnit 1.ppt
Unit 1.ppt
 
Which data structure is it? What are the various data structure kinds and wha...
Which data structure is it? What are the various data structure kinds and wha...Which data structure is it? What are the various data structure kinds and wha...
Which data structure is it? What are the various data structure kinds and wha...
 
Presentation on Data Structure
Presentation on Data StructurePresentation on Data Structure
Presentation on Data Structure
 
Bc0038– data structure using c
Bc0038– data structure using cBc0038– data structure using c
Bc0038– data structure using c
 
Data structure
 Data structure Data structure
Data structure
 

More from rani marri

NAAC PPT M.B.A.pptx
NAAC PPT M.B.A.pptxNAAC PPT M.B.A.pptx
NAAC PPT M.B.A.pptx
rani marri
 
must.pptx
must.pptxmust.pptx
must.pptx
rani marri
 
node.js.pptx
node.js.pptxnode.js.pptx
node.js.pptx
rani marri
 
oops with java modules iii & iv.pptx
oops with java modules iii & iv.pptxoops with java modules iii & iv.pptx
oops with java modules iii & iv.pptx
rani marri
 
oops with java modules i & ii.ppt
oops with java modules i & ii.pptoops with java modules i & ii.ppt
oops with java modules i & ii.ppt
rani marri
 
software engineering modules iii & iv.pptx
software engineering  modules iii & iv.pptxsoftware engineering  modules iii & iv.pptx
software engineering modules iii & iv.pptx
rani marri
 
software engineering module i & ii.pptx
software engineering module i & ii.pptxsoftware engineering module i & ii.pptx
software engineering module i & ii.pptx
rani marri
 
ADVANCED JAVA MODULE III & IV.ppt
ADVANCED JAVA MODULE III & IV.pptADVANCED JAVA MODULE III & IV.ppt
ADVANCED JAVA MODULE III & IV.ppt
rani marri
 
ADVANCED JAVA MODULE I & II.ppt
ADVANCED JAVA MODULE I & II.pptADVANCED JAVA MODULE I & II.ppt
ADVANCED JAVA MODULE I & II.ppt
rani marri
 
data structures module III & IV.pptx
data structures module III & IV.pptxdata structures module III & IV.pptx
data structures module III & IV.pptx
rani marri
 
php programming.pptx
php programming.pptxphp programming.pptx
php programming.pptx
rani marri
 
NodeJS.ppt
NodeJS.pptNodeJS.ppt
NodeJS.ppt
rani marri
 
J2EEFeb11 (1).ppt
J2EEFeb11 (1).pptJ2EEFeb11 (1).ppt
J2EEFeb11 (1).ppt
rani marri
 
CODING QUESTIONS.pptx
CODING QUESTIONS.pptxCODING QUESTIONS.pptx
CODING QUESTIONS.pptx
rani marri
 
OOPS IN PHP.pptx
OOPS IN PHP.pptxOOPS IN PHP.pptx
OOPS IN PHP.pptx
rani marri
 
12-OO-PHP.pptx
12-OO-PHP.pptx12-OO-PHP.pptx
12-OO-PHP.pptx
rani marri
 
PHP-05-Objects.ppt
PHP-05-Objects.pptPHP-05-Objects.ppt
PHP-05-Objects.ppt
rani marri
 

More from rani marri (17)

NAAC PPT M.B.A.pptx
NAAC PPT M.B.A.pptxNAAC PPT M.B.A.pptx
NAAC PPT M.B.A.pptx
 
must.pptx
must.pptxmust.pptx
must.pptx
 
node.js.pptx
node.js.pptxnode.js.pptx
node.js.pptx
 
oops with java modules iii & iv.pptx
oops with java modules iii & iv.pptxoops with java modules iii & iv.pptx
oops with java modules iii & iv.pptx
 
oops with java modules i & ii.ppt
oops with java modules i & ii.pptoops with java modules i & ii.ppt
oops with java modules i & ii.ppt
 
software engineering modules iii & iv.pptx
software engineering  modules iii & iv.pptxsoftware engineering  modules iii & iv.pptx
software engineering modules iii & iv.pptx
 
software engineering module i & ii.pptx
software engineering module i & ii.pptxsoftware engineering module i & ii.pptx
software engineering module i & ii.pptx
 
ADVANCED JAVA MODULE III & IV.ppt
ADVANCED JAVA MODULE III & IV.pptADVANCED JAVA MODULE III & IV.ppt
ADVANCED JAVA MODULE III & IV.ppt
 
ADVANCED JAVA MODULE I & II.ppt
ADVANCED JAVA MODULE I & II.pptADVANCED JAVA MODULE I & II.ppt
ADVANCED JAVA MODULE I & II.ppt
 
data structures module III & IV.pptx
data structures module III & IV.pptxdata structures module III & IV.pptx
data structures module III & IV.pptx
 
php programming.pptx
php programming.pptxphp programming.pptx
php programming.pptx
 
NodeJS.ppt
NodeJS.pptNodeJS.ppt
NodeJS.ppt
 
J2EEFeb11 (1).ppt
J2EEFeb11 (1).pptJ2EEFeb11 (1).ppt
J2EEFeb11 (1).ppt
 
CODING QUESTIONS.pptx
CODING QUESTIONS.pptxCODING QUESTIONS.pptx
CODING QUESTIONS.pptx
 
OOPS IN PHP.pptx
OOPS IN PHP.pptxOOPS IN PHP.pptx
OOPS IN PHP.pptx
 
12-OO-PHP.pptx
12-OO-PHP.pptx12-OO-PHP.pptx
12-OO-PHP.pptx
 
PHP-05-Objects.ppt
PHP-05-Objects.pptPHP-05-Objects.ppt
PHP-05-Objects.ppt
 

Recently uploaded

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
Celine George
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
AzmatAli747758
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
PedroFerreira53928
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
Fundacja Rozwoju Społeczeństwa Przedsiębiorczego
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
EduSkills OECD
 
Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
Col Mukteshwar Prasad
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
rosedainty
 

Recently uploaded (20)

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
 
Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
 

data structures module I & II.pptx

  • 2. DEFINITION  Data structure is representation of the logical relationship existing between individual elements of data.  In other words, a data structure is a way of organizing all data items that considers not only the elements stored but also their relationship to each other.
  • 3. INTRODUCTION  Data structure affects the design of both structural & functional aspects of a program. Program=algorithm + Data Structure  You know that a algorithm is a step by step procedure to solve a particular function.
  • 4. INTRODUCTION  That means, algorithm is a set of instruction written to carry out certain tasks & the data structure is the way of organizing the data with their logical relationship retained.  To develop a program of an algorithm, we should select an appropriate data structure for that algorithm.  Therefore algorithm and its associated data structures from a program.
  • 5. CLASSIFICATION OF DATA STRUCTURE  Data structure are normally divided into two broad categories:  Primitive Data Structure  Non-Primitive Data Structure
  • 6. CLASSIFICATION OF DATA STRUCTURE Data structure Primitive DS Non-Primitive DS Integer Float Character Pointer Float Integer Float
  • 7. CLASSIFICATION OF DATA STRUCTURE Non-Primitive DS Linear List Non-Linear List Array Link List Stack Queue Graph Trees
  • 8. PRIMITIVE DATA STRUCTURE  There are basic structures and directly operated upon by the machine instructions.  In general, there are different representation on different computers.  Integer, Floating-point number, Character constants, string constants, pointers etc, fall in this category.
  • 9. NON-PRIMITIVE DATA STRUCTURE  There are more sophisticated data structures.  These are derived from the primitive data structures.  The non-primitive data structures emphasize on structuring of a group of homogeneous (same type) or heterogeneous (different type) data items.
  • 10. NON-PRIMITIVE DATA STRUCTURE  Lists, Stack, Queue, Tree, Graph are example of non- primitive data structures.  The design of an efficient data structure must take operations to be performed on the data structure.
  • 11. NON-PRIMITIVE DATA STRUCTURE  The most commonly used operation on data structure are broadly categorized into following types:  Create  Selection  Updating  Searching  Sorting  Merging  Destroy or Delete
  • 12. DIFFERENT BETWEEN THEM  A primitive data structure is generally a basic structure that is usually built into the language, such as an integer, a float.  A non-primitive data structure is built out of primitive data structures linked together in meaningful ways, such as a or a linked-list, binary search tree, AVL Tree, graph etc.
  • 13. DESCRIPTION OF VARIOUS DATA STRUCTURES : ARRAYS  An array is defined as a set of finite number of homogeneous elements or same data items.  It means an array can contain one type of data only, either all integer, all float-point number or all character.
  • 14. ARRAYS  Simply, declaration of array is as follows: int arr[10]  Where int specifies the data type or type of elements arrays stores.  “arr” is the name of array & the number specified inside the square brackets is the number of elements an array can store, this is also called sized or length of array.
  • 15. ARRAYS  Following are some of the concepts to be remembered about arrays:  The individual element of an array can be accessed by specifying name of the array, following by index or subscript inside square brackets.  The first element of the array has index zero[0]. It means the first element and last element will be specified as:arr[0] & arr[9] Respectively.
  • 16. ARRAYS  The elements of array will always be stored in the consecutive (continues) memory location.  The number of elements that can be stored in an array, that is the size of array or its length is given by the following equation: (Upperbound-lowerbound)+1
  • 17. ARRAYS  For the above array it would be (9-0)+1=10,where 0 is the lower bound of array and 9 is the upper bound of array.  Array can always be read or written through loop. If we read a one- dimensional array it require one loop for reading and other for writing the array.
  • 18. ARRAYS  For example: Reading an array For(i=0;i<=9;i++) scanf(“%d”,&arr[i]);  For example: Writing an array For(i=0;i<=9;i++) printf(“%d”,arr[i]);
  • 19. ARRAYS  If we are reading or writing two- dimensional array it would require two loops. And similarly the array of a N dimension would required N loops.  Some common operation performed on array are: Creation of an array Traversing an array
  • 20. ARRAYS  Insertion of new element  Deletion of required element  Modification of an element  Merging of arrays
  • 21. LISTS  A lists (Linear linked list) can be defined as a collection of variable number of data items.  Lists are the most commonly used non-primitive data structures.  An element of list must contain at least two fields, one for storing data or information and other for storing address of next element.  As you know for storing address we have a special data structure of list the address must be pointer type.
  • 22. LISTS  Technically each such element is referred to as a node, therefore a list can be defined as a collection of nodes as show bellow: Head AAA BBB CCC Information field Pointer field [Linear Liked List]
  • 23. LISTS  Types of linked lists:  Single linked list  Doubly linked list  Single circular linked list  Doubly circular linked list
  • 24. STACK  A stack is also an ordered collection of elements like arrays, but it has a special feature that deletion and insertion of elements can be done only from one end called the top of the stack (TOP)  Due to this property it is also called as last in first out type of data structure (LIFO).
  • 25. STACK  It could be through of just like a stack of plates placed on table in a party, a guest always takes off a fresh plate from the top and the new plates are placed on to the stack at the top.  It is a non-primitive data structure.  When an element is inserted into a stack or removed from the stack, its base remains fixed where the top of stack changes.
  • 26. STACK  Insertion of element into stack is called PUSH and deletion of element from stack is called POP.  The bellow show figure how the operations take place on a stack: PUSH POP [STACK]
  • 27. STACK  The stack can be implemented into two ways:  Using arrays (Static implementation)  Using pointer (Dynamic implementation)
  • 28. QUEUE  Queue are first in first out type of data structure (i.e. FIFO)  In a queue new elements are added to the queue from one end called REAR end and the element are always removed from other end called the FRONT end.  The people standing in a railway reservation row are an example of queue.
  • 29. QUEUE  Each new person comes and stands at the end of the row and person getting their reservation confirmed get out of the row from the front end.  The bellow show figure how the operations take place on a stack: 10 20 30 40 50 front rear
  • 30. QUEUE  The queue can be implemented into two ways:  Using arrays (Static implementation)  Using pointer (Dynamic implementation)
  • 31. TREES  A tree can be defined as finite set of data items (nodes).  Tree is non-linear type of data structure in which data items are arranged or stored in a sorted sequence.  Tree represent the hierarchical relationship between various elements.
  • 32. TREES  In trees:  There is a special data item at the top of hierarchy called the Root of the tree.  The remaining data items are partitioned into number of mutually exclusive subset, each of which is itself, a tree which is called the sub tree.  The tree always grows in length towards bottom in data structures, unlike natural trees which grows upwards.
  • 33. TREES  The tree structure organizes the data into branches, which related the information. A B C D E F G root
  • 34. GRAPH  Graph is a mathematical non-linear data structure capable of representing many kind of physical structures.  It has found application in Geography, Chemistry and Engineering sciences.  Definition: A graph G(V,E) is a set of vertices V and a set of edges E.
  • 35. GRAPH  An edge connects a pair of vertices and many have weight such as length, cost and another measuring instrument for according the graph.  Vertices on the graph are shown as point or circles and edges are drawn as arcs or line segment.
  • 36. GRAPH  Example of graph: v2 v1 v4 v5 v3 10 15 8 6 11 9 v4 v1 v2 v4 v3 [a] Directed & Weighted Graph [b] Undirected Graph
  • 37. GRAPH  Types of Graphs:  Directed graph  Undirected graph  Simple graph  Weighted graph  Connected graph  Non-connected graph
  • 39. Contents • What Is a Good Solution? • Measuring the Efficiency of Algorithms
  • 40. Algorithm Efficiency • There are often many approaches (algorithms) to solve a problem. – How do we choose between them? • At the heart of computer program design are two (sometimes conflicting) goals – To design an algorithm that • is easy to understand, code, debug. • makes efficient use of the resources.
  • 41. Algorithm Efficiency (cont) • Goal (1) is the concern of Software Engineering. • Goal (2) is the concern of data structures and algorithm analysis. • When goal (2) is important, – how do we measure an algorithm’s cost?
  • 42. What Is a Good Solution? • Criterion A solution is good if the total cost it incurs over all phases of its life is minimal. • Keep in mind, efficiency is only one aspect of a solution’s cost • Note: Relative importance of various components of a solution’s cost has changed since early days of computing.
  • 43. Measuring Efficiency of Algorithms • Comparison of algorithms should focus on significant differences in efficiency • Difficulties with comparing programs instead of algorithms – How are the algorithms coded? – What computer should you use? – What data should the programs use?
  • 44. Execution Time of Algorithm • Traversal of linked nodes – example: • Displaying data in linked chain of n nodes requires time proportional to n
  • 45. Algorithm Growth Rates • Measure algorithm’s time requirement as a function of problem size • Compare algorithm efficiencies for large problems • Look only at significant differences.
  • 46. Algorithm Growth Rates Time requirements as a function of the problem size n
  • 47. Best, Worst, Average Cases • Not all inputs of a given size take the same time to run. • Sequential search for K in an array of n integers: – Begin at first element in array and look at each element in turn until K is found – Best case: – Worst case: – Average case:
  • 48. Time Analysis Lower Bound RunningTime Upper Bound   • Provides upper and lower bounds of running time.
  • 49. 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. Lower Bound RunningTime Upper Bound  
  • 50. Best Case • Provides a lower bound on running time. • Input is the one for which the algorithm runs the fastest. Lower Bound RunningTime Upper Bound  
  • 51. Average Case • Provides an estimate of “average” running time. • Assumes that the input is random. • Useful when best/worst cases do not happen very often – i.e., few input cases lead to best/worst cases. Lower Bound RunningTime Upper Bound  
  • 52. Which Analysis to Use? • While average time appears to be the fairest measure, – it may be difficult to determine. • When is the worst case time important?
  • 53. How to Measure Efficiency? • Critical resources: – Time, memory, battery, bandwidth, programmer effort, user effort • Factors affecting running time: – For most algorithms, running time depends on “size” of the input. – Running time is expressed as T(n) for some function T on input size n. 53
  • 54. How do we analyze an algorithm? • Need to define objective measures. (1) Compare execution times? Empirical comparison (run programs) Not good: times are specific to a particular machine. (2) Count the number of statements? Not good: number of statements varies with programming language and programming style.
  • 55. How do we analyze an algorithm? (cont.) (3) Express running time t as a function of problem size n (i.e., t=f(n) ) Asymptotic Algorithm Analysis - Given two algorithms having running times f(n) and g(n), - find which functions grows faster - Such an analysis is independent of machine time, programming style, etc.
  • 56. Comparing algorithms • Given two algorithms having running times f(n) and g(n), how do we decide which one is faster? • Compare “rates of growth” of f(n) and g(n)
  • 57. Understanding Rate of Growth • The low order terms of a function are relatively insignificant for large n n4 + 100n2 + 10n + 50 Approximation: n4 • Highest order term determines rate of growth!
  • 58. Visualizing Orders of Growth • On a graph, as you go to the right, a faster growing function eventually becomes larger... fA(n)=30n+8 Increasing n  fB(n)=n2+1 Value of function 
  • 59. Rate of growth • The graphs of 3  n2 and n2 - 3  n + 10
  • 60. Rate of Growth ≡ Asymptotic Analysis • Using rate of growth as a measure to compare different functions implies comparing them asymptotically – i.e., as n  • If f(x) is faster growing than g(x), then f(x) always eventually becomes larger than g(x) in the limit – i.e., for large enough values of x 
  • 61. Complexity • Let us assume two algorithms A and B that solve the same class of problems. • The time complexity of A is 5,000n, the one for B is 1.1n for an input with n elements • For n = 10, – A requires 50,000 steps, – but B only 3, – so B seems to be superior to A. • For n = 1000, A requires 5106 steps, – while B requires 2.51041 steps.
  • 62. Names of Orders of Magnitude O(1) bounded (by a constant) time O(log2N) logarithmic time O(N) linear time O(N*log2N) N*log2N time O(N2) quadratic time O(N3) cubic time O(2N ) exponential time
  • 63. Order of growth of common functions < O(n!)
  • 66. A comparison of growth-rate functions
  • 67. N log2N N*log2N N2 2N 1 0 0 1 2 2 1 2 4 4 4 2 8 16 16 8 3 24 64 256 16 4 64 256 65,536 32 5 160 1024 4.29*109 64 6 384 4096 1.84*1019 128 7 896 16,384 3.40*1038
  • 68. A comparison of growth-rate functions
  • 70. The Growth of Functions • A problem that can be solved with polynomial worst-case complexity is called tractable • Problems of higher complexity are called intractable • Problems that no algorithm can solve are called unsolvable
  • 71. Analysis and Big O Notation • Definition: – Algorithm A is order f ( n ) • Denoted O( f ( n )) – If constants k and n0 exist – Such that A requires no more than k  f ( n ) time units to solve a problem of size n ≥ n0 .
  • 72. Asymptotic Notation O notation: asymptotic “less than”: f(n)=O(g(n)) implies: f(n) “≤” c g(n) in the limit* (used in worst-case analysis) *formal definition in CS477/677 c is a constant
  • 73. Asymptotic Notation  notation: asymptotic “greater than”: f(n)=  (g(n)) implies: f(n) “≥” c g(n) in the limit* (used in best-case analysis) *formal definition in CS477/677 c is a constant
  • 74. Asymptotic Notation  notation: asymptotic “equality”: f(n)=  (g(n)) implies: f(n) “=” c g(n) in the limit* (provides a tight bound of running time) (best and worst cases are same) *formal definition in CS477/677 c is a constant
  • 75. More on big-O f(n) ϵ O(g(n)) if “f(n)≤cg(n)” O(g(n)) is a set of functions f(n)
  • 76. A Common Misunderstanding Confusing worst case with upper bound. Upper bound refers to a growth rate. Worst case refers to the worst input from among the choices for possible inputs of a given size.
  • 77. Algorithm speed vs function growth • An O(n2) algorithm will be slower than an O(n) algorithm (for large n). • But an O(n2) function will grow faster than an O(n) function. fA(n)=30n+8 Increasing n  fB(n)=n2+1 Value of function 
  • 78. Faster Computer or Algorithm? • Suppose we buy a computer 10 times faster. – n: size of input that can be processed in one second on old computer • in 1000 computational units – n’: size of input that can be processed in one second on new computer T(n) n n’ Change n’/n 10n 100 1,000 n’ = 10n 10 10n2 10 31.6 n’= 10n 3.16 10n 3 4 n’ = n + 1 1 + 1/n
  • 79. How do we find f(n)? (1) Associate a "cost" with each statement (2) Find total number of times each statement is executed (3) Add up the costs
  • 80. Properties of Growth-Rate Functions • Ignore low-order terms • Ignore a multiplicative constant in the high- order term • O(f(n)) + O(g(n)) = O(f(n) + g(n)) • Be aware of worst case, average case
  • 81. Keeping Your Perspective • Array-based getEntry is O(1) • Link-based getEntry is O(n) • Consider how frequently particular ADT operations occur in given application • Some seldom-used but critical operations must be efficient
  • 82. Keeping Your Perspective • If problem size always small, ignore an algorithm’s efficiency • Weigh trade-offs between algorithm’s time and memory requirements • Compare algorithms for both style and efficiency
  • 83. Efficiency of Searching Algorithms • Sequential search – Worst case O(n) – Average case O(n) – Best case O(1) • Binary search of sorted array – Worst case O(log2n) – Remember required overhead for keeping array sorted
  • 84. i = 0; while (i<N) { X=X+Y; // O(1) result = mystery(X); // O(N) i++; // O(1) } • The body of the while loop: O(N) • Loop is executed: N times N x O(N) = O(N2) Running Time Examples
  • 85. if (i<j) for ( i=0; i<N; i++ ) X = X+i; else X=0; Max ( O(N), O(1) ) = O (N) O(N) O(1) Running Time Examples
  • 86. Running Time Examples (cont.’d) Algorithm 1 Cost arr[0] = 0; c1 arr[1] = 0; c1 arr[2] = 0; c1 ... arr[N-1] = 0; c1 ----------- c1+c1+...+c1 = c1 x N Algorithm 2 Cost for(i=0; i<N; i++) c2 arr[i] = 0; c1 ----------- (N+1) x c2 + N x c1 = (c2 + c1) x N + c2
  • 87. Cost sum = 0; c1 for(i=0; i<N; i++) c2 for(j=0; j<N; j++) c2 sum += arr[i][j]; c3 ------------ c1 + c2 x (N+1) + c2 x N x (N+1) + c3 x N x N 87 Running Time Examples (cont.’d)
  • 88. Complexity Examples What does the following algorithm compute? int who_knows(int a[n]) { int m = 0; for {int i = 0; i<n; i++} for {int j = i+1; j<n; j++} if ( abs(a[i] – a[j]) > m ) m = abs(a[i] – a[j]); return m; } returns the maximum difference between any two numbers in the input array Comparisons: n-1 + n-2 + n-3 + … + 1 = (n-1)n/2 = 0.5n2 - 0.5n Time complexity is O(n2)
  • 89. Complexity Examples Another algorithm solving the same problem: int max_diff(int a[n]) { int min = a[0]; int max = a[0]; for {int i = 1; i<n; i++} if ( a[i] < min ) min = a[i]; else if ( a[i] > max ) max = a[i]; return max-min; } Comparisons: 2n - 2 Time complexity is O(n).
  • 90. Examples of Growth Rate /* @return Position of largest value in "A“ */ static int largest(int[] A) { int currlarge = 0; // Position of largest for (int i=1; i<A.length; i++) if (A[currlarge] < A[i]) currlarge = i; // Remember position return currlarge; // Return largest position }
  • 91. Examples (cont) sum = 0; for (i=1; i<=n; i++) for (j=1; j<=n; j++) sum++;
  • 92. Time Complexity Examples (1) a = b; This assignment takes constant time, so it is (1). sum = 0; for (i=1; i<=n; i++) sum += n;
  • 93. Time Complexity Examples (2) sum = 0; for (j=1; j<=n; j++) for (i=1; i<=j; i++) sum++; for (k=0; k<n; k++) A[k] = k;
  • 94. Time Complexity Examples (3) sum1 = 0; for (i=1; i<=n; i++) for (j=1; j<=n; j++) sum1++; sum2 = 0; for (i=1; i<=n; i++) for (j=1; j<=i; j++) sum2++;
  • 95. Time Complexity Examples (4) sum1 = 0; for (k=1; k<=n; k*=2) for (j=1; j<=n; j++) sum1++; sum2 = 0; for (k=1; k<=n; k*=2) for (j=1; j<=k; j++) sum2++;
  • 97. Analyze the complexity of the following code
  • 99. Concepts of linked list • A linked list is a linear collection of data elements called nodes in which linear representation is given by links from one node to the next node. • Similar to array, it is a linear collection of data elements of the same type. • Different from array, data elements of linked list are generally not lined in consecutive memory space; instead they are dispersed in various locations
  • 100. Concepts of linked list • Linked list is a data structure which in turn can be used to implement other data structures. Thus, it acts as building block to implement data structures like stacks, queues and their variations. • A linked list can be perceived as a train or a sequence of nodes in which each node contains one or more data fields and a pointer to the next node.
  • 101. Element of linked list • Linked list element (node) is user defined structure data type, typically contains two parts  data variables  pointers to next elements, hold the addresses of next elements Example: struct node { int data; // data struct node *next; // pointer to next element };
  • 102. Simple Linked List 1 2 3 4 5 6 7 X START • In the above linked list, every node contains two parts - one integer and the other a pointer to the next node. • The data part of the node which contains data may include a simple data type, an array or a structure. • The pointer part of the node contains a pointer to the next node (or address of the next node in sequence). • The last node will have no next node connected to it, so it will store a NULL value. • A linked list is defined by the pointer pointing to the first node, e.g START
  • 103. Linked List Operations 1. Create a node and linked list 2. Traversal, e.g. display all elements 3. Search node 4. Insert node at beginning, at end, after/before a node 5. Delete node at beginning, at end, after/before a node 6. Sort
  • 104. How to create nodes A node is a structure data type, can be created in two methods, statically and dynamically. •Static method – use array of structures – declared as globally outside functions – declared locally within a function •Dynamic method (mostly used for linked list) – use stdlib function malloc(size) get memory space struct node *np = (struct node*) malloc(sizeof(struct node));
  • 105. How to create nodes struct node *np = (struct node*) malloc(sizeof(struct node)); At run time, OS allocates consecutive sizeof(struct node) bytes in the heap region, return the address of the address of the first memory cell, store the address to struct node type pointer np. Need (struct node*) to cast the return address to struct node pointer value. Need use free(np) to release when deleting the node!!! Otherwise cause memory leaking
  • 106. Traversing Linked Lists • We can traverse the entire linked list using a single pointer variable called START. • The START node contains the address of the first node; the next part of the first node in turn stores the address of its succeeding node. • Using this technique the individual nodes of the list will form a chain of nodes. • If START = NULL, this means that the linked list is empty and contains no nodes.
  • 107. Singly Linked Lists • A singly linked list is the simplest type of linked list in which every node contains some data and a pointer to the next node of the same data type. Example: struct node { int data; struct node *next; }; 1 2 3 4 5 6 7 X START
  • 108. Traversal Singly Linked Lists ALGORITHM FOR TRAVERSING A LINKED LIST Step 1: [INITIALIZE] SET PTR = START Step 2: Repeat Steps 3 and 4 while PTR != NULL Step 3: Apply Process to PTR->DATA Step 4: SET PTR = PTR->NEXT [END OF LOOP] Step 5: EXIT void display(struct node *ptr) { while(ptr != NULL) { printf("%d ", ptr->data); // process ptr = ptr->next; } } Call as display(START);
  • 109. Searching for Val 4 in Linked List 1 7 3 4 2 6 5 X PTR 1 7 3 4 2 6 5 X PTR 1 7 3 4 2 6 5 X PTR 1 7 3 4 2 6 5 X PTR
  • 110. Searching a Linked List ALGORITHM TO SEARCH A LINKED LIST Step 1: [INITIALIZE] SET PTR = START Step 2: Repeat Step 3 while PTR != NULL Step 3: IF VAL = PTR->DATA SET POS = PTR Go To Step 5 ELSE SET PTR = PTR->NEXT [END OF IF] [END OF LOOP] Step 4: SET POS = NULL // not found Step 5: EXIT // found, output POS struct node* search(struct node *ptr, int num) { while((ptr != NULL) && (ptr->data != num)) { ptr = ptr->next; } return ptr; } // call example, search(START, 4)
  • 111. Inserting a Node at the Beginning 1 7 3 4 2 6 5 X START START 9 1 7 3 4 2 6 5 X ALGORITHM: INSERT A NEW NODE IN THE BEGINNING OF THE LINKED LIST Step 1: IF AVAIL = NULL, then Write OVERFLOW 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 See example
  • 112. Inserting a Node at the End 1 7 3 4 2 6 5 X START, PTR 1 7 3 4 2 6 5 9 X START ALGORITHM TO INSERT A NEW NODE AT THE END OF THE LINKED LIST Step 1: IF AVAIL = NULL, then Write OVERFLOW Go to Step 10 [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 = NULL Step 6: SET PTR = START Step 7: Repeat Step 8 while PTR->NEXT != NULL Step 8: SET PTR = PTR ->NEXT [END OF LOOP] Step 9: SET PTR->NEXT = New_Node Step 10: EXIT
  • 113. Inserting a Node after Node that ahs Value NUM ALGORITHM TO INSERT A NEW NODE AFTER A NODE THAT HAS VALUE NUM Step 1: IF AVAIL = NULL, then 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 10: PREPTR->NEXT = New_Node Step 11: SET New_Node->NEXT = PTR Step 12: EXIT
  • 114. Deleting the First Node 1 7 3 4 2 6 5 X 7 3 4 2 6 5 X START START Algorithm to delete the first node from the linked list Step 1: IF START = NULL, then Write UNDERFLOW Go to Step 5 [END OF IF] Step 2: SET PTR = START Step 3: SET START = START->NEXT Step 4: FREE PTR Step 5: EXIT
  • 115. Deleting the Last Node 1 7 3 4 2 6 5 X START, PREPTR, PTR 1 7 3 4 2 6 X 5 X PREPTR PTR START ALGORITHM TO DELETE THE LAST NODE OF THE LINKED LIST Step 1: IF START = NULL, then Write UNDERFLOW Go to Step 8 [END OF IF] Step 2: SET PTR = START Step 3: Repeat Steps 4 and 5 while PTR->NEXT != NULL Step 4: SET PREPTR = PTR Step 5: SET PTR = PTR->NEXT [END OF LOOP] Step 6: SET PREPTR->NEXT = NULL Step 7: FREE PTR Step 8: EXIT
  • 116. Deleting the Node After a Given Node 1 7 3 4 2 6 5 X START, PREPTR, PTR 1 7 3 4 2 6 5 X PREPTR PTR START 1 7 3 4 2 6 5 X START 1 7 3 4 6 5 X
  • 117. Deleting the Node After a Given Node ALGORITHM TO DELETE THE NODE AFTER A GIVEN NODE FROM THE LINKED LIST Step 1: IF START = NULL, then Write UNDERFLOW Go to Step 10 [END OF IF] Step 2: SET PTR = START Step 3: SET PREPTR = PTR Step 4: Repeat Step 5 and 6 while PRETR->DATA != NUM Step 5: SET PREPTR = PTR Step 6: SET PTR = PTR->NEXT [END OF LOOP] Step7: SET TEMP = PTR->NEXT Step 8: SET PREPTR->NEXT = TEMP->NEXT Step 9: FREE TEMP Step 10: EXIT
  • 118. Circular Linked List • In a circular linked list, the last node contains a pointer to the first node of the list. We can have a circular singly listed list as well as circular doubly linked list. While traversing a circular linked list, we can begin at any node and traverse the list in any direction forward or backward until we reach the same node where we had started. Thus, a circular linked list has no beginning and no ending. 1 2 3 4 5 6 7 START
  • 119. Circular Linked List Algorithm to insert a new node in the beginning of circular the linked list Step 1: IF AVAIL = NULL, then Write OVERFLOW 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 PTR = START Step 6: Repeat Step 7 while PTR->NEXT != START Step 7: PTR = PTR->NEXT Step 8: SET New_Node->Next = START Step 8: SET PTR->NEXT = New_Node Step 6: SET START = New_Node Step 7: EXIT
  • 120. Circular Linked List 1 7 3 4 2 6 5 START, PTR 1 7 3 4 2 6 5 START PTR 9 1 7 3 4 2 6 5 START
  • 121. Circular Linked List Algorithm to insert a new node at the end of the circular linked list Step 1: IF AVAIL = NULL, then Write OVERFLOW 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 PTR = START Step 7: Repeat Step 8 while PTR->NEXT != START Step 8: SET PTR = PTR ->NEXT [END OF LOOP] Step 9: SET PTR ->NEXT = New_Node Step 10: EXIT
  • 122. Circular Linked List 1 7 3 4 2 6 5 START, PTR 1 7 3 4 2 6 5 9 START PTR
  • 123. Circular Linked List Algorithm to insert a new node after a node that has value NUM Step 1: IF AVAIL = NULL, then 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 Step 8 and 9 while PTR->DATA != NUM Step 8: SET PREPTR = PTR Step 9: SET PTR = PTR->NEXT [END OF LOOP] Step 10: PREPTR->NEXT = New_Node Step 11: SET New_Node->NEXT = PTR Step 12: EXIT
  • 124. Circular Linked List Algorithm to delete the first node from the circular linked list Step 1: IF START = NULL, then Write UNDERFLOW Go to Step 8 [END OF IF] Step 2: SET PTR = START Step 3: Repeat Step 4 while PTR->NEXT != START Step 4: SET PTR = PTR->NEXT [END OF IF] Step 5: SET PTR->NEXT = START->NEXT Step 6: FREE START Step 7: SET START = PTR->NEXT Step 8: EXIT
  • 125. Circular Linked List 1 7 3 4 2 6 5 START, PTR 1 7 3 4 2 6 5 START PTR 7 3 4 2 6 5 START
  • 126. Circular Linked List Algorithm to delete the last node of the circular linked list Step 1: IF START = NULL, then Write UNDERFLOW Go to Step 8 [END OF IF] Step 2: SET PTR = START Step 3: Repeat Step 4 while PTR->NEXT != START Step 4: SET PREPTR = PTR Step 5: SET PTR = PTR->NEXT [END OF LOOP] Step 6: SET PREPTR->NEXT = START Step 7: FREE PTR Step 8: EXIT
  • 127. Circular Linked List 1 7 3 4 2 6 5 START, PREPTR, PTR 1 7 3 4 2 6 5 START PTR PREPTR 1 7 3 4 2 6 START
  • 128. Circular Linked List Algorithm to delete the node after a given node from the circular linked list Step 1: IF START = NULL, then Write UNDERFLOW Go to Step 9 [END OF IF] Step 2: SET PTR = START Step 3: SET PREPTR = PTR Step 4: Repeat Step 5 and 6 while PREPTR->DATA != NUM Step 5: SET PREPTR = PTR Step 6: SET PTR = PTR->NEXT [END OF LOOP] Step 7: SET PREPTR->NEXT = PTR->NEXT Step 8: FREE PTR Step 9: EXIT
  • 129. Circular Linked List 1 7 3 4 2 6 5 START, PREPTR, PTR 1 7 3 4 2 6 5 START PREPTR PTR 1 7 3 4 6 5 START
  • 130. Doubly Linked List  A doubly linked list or a two way linked list is a more complex type of linked list which contains a pointer to the next as well as previous node in the sequence. Therefore, it consists of three parts and not just two. The three parts are data, a pointer to the next node and a pointer to the previous node 1 X 1 2 3 4 X START
  • 131. Doubly Linked List • In C language, the structure of a doubly linked list is given as, struct node { struct node *prev; int data; struct node *next; }; • The prev field of the first node and the next field of the last node will contain NULL. The prev field is used to store the address of the preceding node. This would enable to traverse the list in the backward direction as well.
  • 132. Doubly Linked List 1 7 3 4 2 X X 9 1 7 3 4 X 2 X START START Algorithm to insert a new node in the beginning of the doubly linked list Step 1: IF AVAIL = NULL, then Write OVERFLOW Go to Step 8 [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->PREV = NULL Step 6: SET New_Node->Next = START Step 7: SET START = New_Node Step 8: EXIT
  • 133. Doubly Linked List 1 7 3 4 2 X X START, PTR 1 7 3 4 2 X 9 X PTR Algorithm to insert a new node at the end of the doubly linked list Step 1: IF AVAIL = NULL, then Write OVERFLOW Go to Step 11 [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 = NULL Step 6: SET PTR = START Step 7: Repeat Step 8 while PTR->NEXT != NULL Step 8: SET PTR = PTR->NEXT [END OF LOOP] Step 9: SET PTR->NEXT = New_Node Step 10: New_Node->PREV = PTR Step 11: EXIT
  • 134. Doubly Linked List Algorithm to insert a new node after a node that has value NUM Step 1: IF AVAIL = NULL, then Write OVERFLOW Go to Step 11 [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: Repeat Step 8 while PTR->DATA != NUM Step 7: SET PTR = PTR->NEXT [END OF LOOP] Step 8: New_Node->NEXT = PTR->NEXT Step 9: SET New_Node->PREV = PTR Step 10: SET PTR->NEXT = New_Node Step 11: EXIT
  • 135. Doubly Linked List 1 7 3 4 2 X X START, PTR 1 7 3 4 2 X X 9 1 7 3 9 4 X 2 X START START PTR
  • 136. Doubly Linked List 1 7 3 4 2 X X START, PTR 7 3 4 2 X Algorithm to delete the first node from the doubly linked list Step 1: IF START = NULL, then Write UNDERFLOW Go to Step 6 [END OF IF] Step 2: SET PTR = START Step 3: SET START = START->NEXT Step 4: SET START->PREV = NULL Step 5: FREE PTR Step 6: EXIT
  • 137. Doubly Linked List 1 3 5 7 8 X 9 1 X START, PTR 1 3 5 7 8 X 9 1 X START PTR 1 3 5 7 8 X X START Algorithm to delete the last node of the doubly linked list Step 1: IF START = NULL, then Write UNDERFLOW Go to Step 7 [END OF IF] Step 2: SET PTR = START Step 3: Repeat Step 4 and 5 while PTR->NEXT != NULL Step 4: SET PTR = PTR->NEXT [END OF LOOP] Step 5: SET PTR->PREV->NEXT = NULL Step 6: FREE PTR Step 7: EXIT
  • 138. Doubly Linked List Algorithm to delete the node after a given node from the doubly linked list Step 1: IF START = NULL, then Write UNDERFLOW Go to Step 9 [END OF IF] Step 2: SET PTR = START Step 3: Repeat Step 4 while PTR->DATA != NUM Step 4: SET PTR = PTR->NEXT [END OF LOOP] Step 5: SET TEMP = PTR->NEXT Step 6: SET PTR->NEXT = TEMP->NEXT Step 7: SET TEMP->NEXT->PREV = PTR Step 8: FREE TEMP Step 9: EXIT
  • 139. Doubly Linked List 1 3 4 7 8 X 9 1 X 1 3 4 7 8 X 9 1 X 1 3 4 8 9 X X START, PTR START PTR START
  • 141. © Oxford University Press 2013. All rights reserved. Linked List in Arrays
  • 142.
  • 143. •An array is the data structure contains a collection of similar type data elements whereas the Linked list is considered as non-primitive data structure contains a collection of unordered linked elements known as nodes. •In the array the elements belong to indexes, i.e., if you want to get into the fourth element you have to write the variable name with its index or location within the square bracket. In a linked list though, you have to start from the head and work your way through until you get to the fourth element. •While accessing an element array is fast while Linked list takes linear time so, it is quite bit slower. Key Differences Between Array and Linked List
  • 144. •Operations like insertion and deletion in arrays consume a lot of time. On the other hand, the performance of these operations in Linked lists is fast. •Arrays are of fixed size. In contrast, Linked lists are dynamic and flexible and can expand and contract its size. •In an array, memory is assigned during compile time while in a Linked list it is allocated during execution or runtime. •Elements are stored consecutively in arrays whereas it is stored randomly in Linked lists. •The requirement of memory is less due to actual data being stored within the index in the array. As against, there is a need for more memory in Linked Lists due to storage of additional next and previous referencing elements. •In addition memory utilization is inefficient in the array. Conversely, memory utilization is efficient in the array. Contd…
  • 145. CIRCULAR & DEQUEUE BY Dr M.RANI REDDY
  • 146. Limitation of Simple Queue  At that time our program will flash the message “Queue is full”.  But if the queue is too large of say 5000 elements it will be a tedious job to do and time consuming too.  To remove this problem we use circular queue.
  • 147. Circular Queue  A circular queue is one in which the insertion of a new element is done at the very first location of the queue if the last location of the queue is full.  In other words if we have a queue Q of say n elements, then after inserting an element last (n-1th) location of the array the next elements will be inserted at the very first location (0) of the array.  It is possible to insert new elements, if and only if those location (slots) are empty.
  • 148. Circular Queue  We can say that a circular queue is one in which the first element comes just after the last element.  It can be viewed as a mesh or loop of wire, in which the two ends of the wire are connected together.  A circular queue overcomes the problem of unutilized space in linear queues implemented as arrays.  A circular queue also have a Front and Rear to keep the track of the elements to be deleted and inserted and therefore to maintain the unique characteristic of the queue.
  • 149. Circular Queue  Bellow show a figure a empty circular queue Q[5] which can accommodate five elements. ` Q[0] Q[1] Q[2] Q[3] Q[4] Fig: Circular Queue
  • 150. Double Ended Queue (Deque)  It is also a homogeneous list of elements in which insertion and deletion operations are performed from both the ends.  That is, we can insert elements from the rear end or from the front ends.  Hence it is called double-ended queue. It is commonly referred as a Deque.  There are two types of Deque. These two types are due to the restrictions put to perform either the insertions or deletions only at one end.
  • 151. Double Ended Queue (Deque)  There are:  Input-restricted Deque.  Output-restricted Deque.  Bellow show a figure a empty Deque Q[5] which can accommodate five elements. Q[0] Q[1] Q[2] Q[3] Q[4] deletion deletion insertion insertion Fig: A Deque
  • 152. Double Ended Queue (Deque)  There are:  Input-restricted Deque: An input restricted Deque restricts the insertion of the elements at one end only, the deletion of elements can be done at both the end of a queue. 10 20 30 40 50 Q[0] Q[1] Q[2] Q[3] Q[4] deletion deletion insertion Fig: A representation of an input-restricted Deque F R
  • 153. Double Ended Queue (Deque)  There are:  Output-restricted Deque: on the contrary, an Output-restricted Deque, restricts the deletion of elements at one end only, and allows insertion to be done at both the ends of a Deque. 10 20 30 40 50 Q[0] Q[1] Q[2] Q[3] Q[4] insertion deletion insertion Fig: A representation of an Output-restricted Deque F R
  • 154. Double Ended Queue (Deque)  The programs for input-restricted Deque and output-restricted Deque would be similar to the previous program of Deque except for a small difference.  The program for the input-restricted Deque would not contain the function addqatbeg().  Similarly the program for the output-restricted Deque would not contain the function delatbeg().
  • 155. Priority Queue  A priority queue is a collection of elements where the elements are stored according to their priority levels.  The order in which the elements should get added or removed is decided by the priority or the element.  Following rules are applied to maintain a priority queue.  The element with a higher priority is processes before any element of lower priority.
  • 156. Priority Queue  If there are elements with same priority, then the element added first in the queue would get processed  Here, smallest number that is most highest priority and greater number that is less priority.  Priority queues are used for implementing job scheduling by the operating system.  Where jobs with higher priorities are to be processed first.  Another application of priority queue is simulation systems where priority corresponds to event times.
  • 157. Applications of Queues  Round robin technique for processor scheduling is implemented using queues.  All types of customer service (like railway ticket reservation) center software’s are designed using queues to store customers information.  Printer server routines are designed using queues. A number of users share a printer using printer server the printer server then spools all the jobs from all the users, to the server’s hard disk in a queue. From here jobs are printed one-by-one according to their number in the queue.
  • 158. Stack and Queue Dr M.Rani Reddy
  • 159. 159 Stack From Two Queues Describe how to implement the stack ADT using two queues The solution should only use the standard queue operations: ENQUEUE, DEQUEUE, IS-EMPTY What will be the running times of the PUSH and POP operations?
  • 160. 160 Stack From Two Queues – Solution We will call the two queues Q1 and Q2 Additionally, we will hold a variable called curQueue, which points to the queue that holds the last value pushed to our stack Initialization: curQueue  Q1
  • 161. 161 Stack From Two Queues – Solution (continued) IS-EMPTY return IS-EMPTY (curQueue) PUSH (val) ENQUEUE (curQueue, val) TOP val  POP PUSH (val) return val
  • 162. 162 Stack From Two Queues – Solution (continued) POP otherQueue  (curQueue = Q1)? Q2: Q1 while (!IS-EMPTY (curQueue)) temp  DEQUEUE (curQueue) if (!IS-EMPTY (curQueue)) // Not last? ENQUEUE (otherQueue, temp) curQueue  otherQueue return temp
  • 163. 163 Stack From Two Queues – Solution Complexity Since PUSH is simply implemented as a single ENQUEUE operation, its running time is O(1) For POP operations, we always need to transfer the complete stack contents from one queue to the other, therefore performing a POP takes O(n) time
  • 164. 164 Two Stacks in a Single Array Describe how to implement two stacks inside a single array The total number of elements in both stacks is limited by the array length Therefore, just splitting the array into two equally-sized parts will not do All stack operations should run in O(1)
  • 165. 165 Two Stacks in a Single Array – Solution Concept We are given an array A with n elements, numbered 0 to n – 1 We define two markers t1 and t2 that point to the next free cell in stacks S1 and S2 respectively Initialization: t1 = 0 t2 = n – 1
  • 166. 166 Two Stacks in a Single Array – Solution Concept S1 grows up from the beginning of the array, S2 grows down from its end We know that the array is full when the two markers switch places (t1 > t2) The complexity is O(1) for all operations The array usage is optimal
  • 167. 167 Two Stacks in a Single Array – Solution Visualization 7 3 2 9 5 6 2 t1 t2 S1 S2
  • 168. 168 Two Stacks in a Single Array – Solution Details S1.IS-EMPTY if (t1 = 0) return true else return false S2.IS-EMPTY if (t2 = n - 1) return true else return false
  • 169. 169 Two Stacks in a Single Array – Solution Details (continued) S1.PUSH (val) if (t1 > t2) error "stack overflow" A[t1] = val t1++ S2.PUSH (val) if (t1 > t2) error "stack overflow" A[t2] = val t2--
  • 170. 170 Two Stacks in a Single Array – Solution Details (continued) S1.POP if (t1 = 0) error "stack underflow" t1-- return A[t1] S2.POP if (t2 = n - 1) error "stack underflow" t2++ return A[t2]
  • 171. 171 Two Stacks in a Single Array – Solution Details (continued) S1.TOP if (t1 = 0) error "stack is empty" return A[t1] S2.TOP if (t2 = n - 1) error "stack is empty" return A[t2]
  • 172. 172 Evaluating Arithmetic Expressions Fully parenthesized arithmetic expressions can be evaluated using Dijkstra's two-stack algorithm Uses two separate stacks – one for the operators and another for the operands See Java code in: Evaluate.java.html
  • 173. 173 Deque (or Double-Ended Queue) A deque is a generalization of the Queue ADT, that supports reading and writing from both ends of the queue We would like to support an input- restricted deque : Deletion can be made from both ends Input can only be made at one end
  • 174. 174 Deque We note that an input-restricted deque is a combination of a queue and a stack We use a standard queue, and modify it to also support PUSH and POP The tail (or rear) of the queue will also be used as the stack top
  • 175. 175 Deque Implementing PUSH is now trivial – simply call ENQUEUE POP is very similar to DEQUEUE, accept that it returns tail instead of head The same IS-EMPTY function will work for both the stack and the queue Check if head = tail
  • 176. 176 Deque 9 5 6 2 0 3 head (front) DEQUEUE ENQUEUE PUSH POP tail (rear)