This document discusses data structures and algorithm efficiency. It defines data structures as representations of logical relationships between data elements. Data structures are classified as primitive (basic types like integers) and non-primitive (derived types like lists, stacks, queues, trees, graphs). The document explains various non-primitive data structures and their implementations. It also discusses measuring algorithm efficiency, including analyzing best, worst, and average cases. Asymptotic analysis using Big O notation is introduced as a machine-independent way to compare algorithm growth rates and determine asymptotic complexity classes.
A data structure is a specialized format for organizing, processing, retrieving and storing data. There are several basic and advanced types of data structures, all designed to arrange data to suit a specific purpose
data structure programing language in c.pptLavkushGupta12
A data structure is a specialized format for organizing, processing, retrieving and storing data. There are several basic and advanced types of data structures, all designed to arrange data to suit a specific purpose
A data structure is a specialized format for organizing, processing, retrieving and storing data. There are several basic and advanced types of data structures, all designed to arrange data to suit a specific purpose
data structure programing language in c.pptLavkushGupta12
A data structure is a specialized format for organizing, processing, retrieving and storing data. There are several basic and advanced types of data structures, all designed to arrange data to suit a specific purpose
In computer science, a data structure is a data organization, management, and storage format that enables efficient access and modification. More precisely, a data structure is a collection of data values, the relationships among them, and the functions or operations that can be applied to the data. https://apkleet.com
<a href="https://apkleet.com" >games apk </a>
Which data structure is it? What are the various data structure kinds and wha...Tutort Academy
Data structures matter because they boost efficiency. Efficiency: By using the appropriate data structures, programmers can create code that runs faster and uses less memory. Reusability: By employing standard data structures, programmers can abstract the crucial operations that are carried out over numerous Data structures using libraries that are specific to Data Structures.
basics of data structure operations
In computer science, a data structure is a data organization, management, and storage format that enables efficient access and modification. More precisely, a data structure is a collection of data values, the relationships among them, and the functions or operations that can be applied to the data. https://apkleet.com
<a href="https://apkleet.com" >games apk </a>
Which data structure is it? What are the various data structure kinds and wha...Tutort Academy
Data structures matter because they boost efficiency. Efficiency: By using the appropriate data structures, programmers can create code that runs faster and uses less memory. Reusability: By employing standard data structures, programmers can abstract the crucial operations that are carried out over numerous Data structures using libraries that are specific to Data Structures.
basics of data structure operations
To better understand the behavior of servlets, let’s take a look at the life cycle of servlets.
A servlet is basically a small Java program that runs within a Web server. It can receive requests from clients and return responses. The whole life cycle of a servlet breaks up into 3 phases:
• Initialization: A servlet is first loaded and initialized usually when it is requested by the corresponding clients. Some websites allow the users to load and initialize servlets when the server is started up so that the first request will get responded more quickly.
• Service: After initialization, the servlets serve clients on request, implementing the ap- plication logic of the web application they belong to.
• Destruction: When all pending requests are processed and the servlets have been idle for a specific amount of time, they may be destroyed by the server and release all the resources they occupy.
More specifically, the behavior of a servlet is described in javax.servlet.Servlet interface, in which the following methods are defined:
• public void init(ServletConfig config) throws ServletException
This method is called once when the servlet is loaded into the servlet engine, before the servlet is asked to process its first request.
The init method has a ServletConfig parameter. The servlet can read its initialization arguments through the ServletConfig object. How the initialization arguments are set is servlet engine dependent but they are usually defined in a configuration file.
A typical example of an initialization argument is a database identifier. A servlet can read this argument from the ServletConfig at initialization and then use it later to open a connection to the database during processing of a request:
private String databaseURL;
public void init(ServletConfig config) throws ServletException { super.init(config);
databaseURL = config.getInitParameter("database");
}
• public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException
This method is called to process a request. It can be called zero, one or many times until the servlet is unloaded.
Once a servlet is loaded, it remains in the server’s memory as a single object instance. Thereafter, the server invokes the servlet to handle a request using a simple, lightweight method invocation. Unlike with CGI, there’s no process to spawn or interpreter to invoke, so the servlet can begin handling the request almost immediately. Multiple, concurrent requests are handled by separate threads, so servlets are highly scalable.
Servlets are naturally enduring objects. Because a servlet stays in the server’s memory as a single object instance, it automatically maintains its state and can hold on to external resources, such as database connections, that may otherwise take several seconds to establish. The following servlet presents information about how many times it has been accessed:
To better understand the behavior of servlets, let’s take a lo
4. Use the AM for posting within scientific collaboration networks (SCNs). For a detailed description of our policy on posting to SCNs, please see our Web Posting Guidelines (https://publishing.aip.org/authors/web-posting-guidelines).
5. Reprint the Version of Record (VOR) in print collections written by the Author, or in the Author’s thesis or dissertation. It is understood and agreed that the thesis or dissertation may be made available electronically on the university’s site or in its repository and that copies may be offered for sale on demand.
6. Reproduce copies of the VOR for courses taught by the Author or offered at the institution where the Author is employed, provided no fee is charged for access to the Work.
7. Use the VOR for internal training and noncommercial business purposes by the Author’s employer.
8. Use the VOR in oral presentations made by the Author, such as at conferences, meetings, seminars, etc., provided those receiving copies are informed that they may not further copy or distribute the Work.
9. Distribute the VOR to colleagues for noncommercial scholarly use, provided those receiving copies are informed that they may not further copy or distribute the Work.
10. Post the VOR to their personal web page or their employer’s web page 12 months after publication by AIP Publishing.
11. Deposit the VOR in an institutional or funder-designated repository 12 months after publication by AIP Publishing.
12. Update a prior posting with the VOR on a noncommercial server such as arXiv, 12 months after publication by AIP Publishing.
Author Warranties
Each Author and Copyright Owner represents and warrants to AIP Publishing the following:
1. The Work is the original independent creation of each Author and does not infringe any copyright or violate any other right of any third party.
2. The Work has not been previously published and is not being considered for publication elsewhere in any form, except as a preprint on a noncommercial server such as arXiv, or in a thesis or dissertation.
3. Written permission has been obtained for any material used from other sources and copies of the permission grants have been supplied to AIP Publishing to be included in the manuscript file.
4. All third-party material for which permission has been obtained has been properly credited within the manuscript.
5. In the event that the Author is subject to university open access policies or other institutional restrictions that conflict with any of the rights or provisions of this License, such Author has obtained the necessary waiver from his or her university or institution.
This License must be signed by the Author(s) and, in the case of a Work Made for Hire, also by the Copyright Owners. One Author/Copyright Owner may sign on behalf of all the contributors/owners only if they all have authorized the signing, approved of the License, and agreed to be bound by it. The signing Author and, in the case of a Work Made for Hire, the signing Copyright Owne
4. Use the AM for posting within scientific collaboration networks (SCNs). For a detailed description of our policy on posting to SCNs, please see our Web Posting Guidelines (https://publishing.aip.org/authors/web-posting-guidelines).
5. Reprint the Version of Record (VOR) in print collections written by the Author, or in the Author’s thesis or dissertation. It is understood and agreed that the thesis or dissertation may be made available electronically on the university’s site or in its repository and that copies may be offered for sale on demand.
6. Reproduce copies of the VOR for courses taught by the Author or offered at the institution where the Author is employed, provided no fee is charged for access to the Work.
7. Use the VOR for internal training and noncommercial business purposes by the Author’s employer.
8. Use the VOR in oral presentations made by the Author, such as at conferences, meetings, seminars, etc., provided those receiving copies are informed that they may not further copy or distribute the Work.
9. Distribute the VOR to colleagues for noncommercial scholarly use, provided those receiving copies are informed that they may not further copy or distribute the Work.
10. Post the VOR to their personal web page or their employer’s web page 12 months after publication by AIP Publishing.
11. Deposit the VOR in an institutional or funder-designated repository 12 months after publication by AIP Publishing.
12. Update a prior posting with the VOR on a noncommercial server such as arXiv, 12 months after publication by AIP Publishing.
Author Warranties
Each Author and Copyright Owner represents and warrants to AIP Publishing the following:
1. The Work is the original independent creation of each Author and does not infringe any copyright or violate any other right of any third party.
2. The Work has not been previously published and is not being considered for publication elsewhere in any form, except as a preprint on a noncommercial server such as arXiv, or in a thesis or dissertation.
3. Written permission has been obtained for any material used from other sources and copies of the permission grants have been supplied to AIP Publishing to be included in the manuscript file.
4. All third-party material for which permission has been obtained has been properly credited within the manuscript.
5. In the event that the Author is subject to university open access policies or other institutional restrictions that conflict with any of the rights or provisions of this License, such Author has obtained the necessary waiver from his or her university or institution.
This License must be signed by the Author(s) and, in the case of a Work Made for Hire, also by the Copyright Owners. One Author/Copyright Owner may sign on behalf of all the contributors/owners only if they all have authorized the signing, approved of the License, and agreed to be bound by it. The signing Author and, in the case of a Work Made for Hire, the signing Copyright Owne
How to Split Bills in the Odoo 17 POS ModuleCeline George
Bills have a main role in point of sale procedure. It will help to track sales, handling payments and giving receipts to customers. Bill splitting also has an important role in POS. For example, If some friends come together for dinner and if they want to divide the bill then it is possible by POS bill splitting. This slide will show how to split bills in odoo 17 POS.
Read| The latest issue of The Challenger is here! We are thrilled to announce that our school paper has qualified for the NATIONAL SCHOOLS PRESS CONFERENCE (NSPC) 2024. Thank you for your unwavering support and trust. Dive into the stories that made us stand out!
Palestine last event orientationfvgnh .pptxRaedMohamed3
An EFL lesson about the current events in Palestine. It is intended to be for intermediate students who wish to increase their listening skills through a short lesson in power point.
Unit 8 - Information and Communication Technology (Paper I).pdfThiyagu K
This slides describes the basic concepts of ICT, basics of Email, Emerging Technology and Digital Initiatives in Education. This presentations aligns with the UGC Paper I syllabus.
How to Make a Field invisible in Odoo 17Celine George
It is possible to hide or invisible some fields in odoo. Commonly using “invisible” attribute in the field definition to invisible the fields. This slide will show how to make a field invisible in odoo 17.
2024.06.01 Introducing a competency framework for languag learning materials ...Sandy Millin
http://sandymillin.wordpress.com/iateflwebinar2024
Published classroom materials form the basis of syllabuses, drive teacher professional development, and have a potentially huge influence on learners, teachers and education systems. All teachers also create their own materials, whether a few sentences on a blackboard, a highly-structured fully-realised online course, or anything in between. Despite this, the knowledge and skills needed to create effective language learning materials are rarely part of teacher training, and are mostly learnt by trial and error.
Knowledge and skills frameworks, generally called competency frameworks, for ELT teachers, trainers and managers have existed for a few years now. However, until I created one for my MA dissertation, there wasn’t one drawing together what we need to know and do to be able to effectively produce language learning materials.
This webinar will introduce you to my framework, highlighting the key competencies I identified from my research. It will also show how anybody involved in language teaching (any language, not just English!), teacher training, managing schools or developing language learning materials can benefit from using the framework.
Instructions for Submissions thorugh G- Classroom.pptxJheel Barad
This presentation provides a briefing on how to upload submissions and documents in Google Classroom. It was prepared as part of an orientation for new Sainik School in-service teacher trainees. As a training officer, my goal is to ensure that you are comfortable and proficient with this essential tool for managing assignments and fostering student engagement.
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxEduSkills OECD
Andreas Schleicher presents at the OECD webinar ‘Digital devices in schools: detrimental distraction or secret to success?’ on 27 May 2024. The presentation was based on findings from PISA 2022 results and the webinar helped launch the PISA in Focus ‘Managing screen time: How to protect and equip students against distraction’ https://www.oecd-ilibrary.org/education/managing-screen-time_7c225af4-en and the OECD Education Policy Perspective ‘Students, digital devices and success’ can be found here - https://oe.cd/il/5yV
Ethnobotany and Ethnopharmacology:
Ethnobotany in herbal drug evaluation,
Impact of Ethnobotany in traditional medicine,
New development in herbals,
Bio-prospecting tools for drug discovery,
Role of Ethnopharmacology in drug evaluation,
Reverse Pharmacology.
We all have good and bad thoughts from time to time and situation to situation. We are bombarded daily with spiraling thoughts(both negative and positive) creating all-consuming feel , making us difficult to manage with associated suffering. Good thoughts are like our Mob Signal (Positive thought) amidst noise(negative thought) in the atmosphere. Negative thoughts like noise outweigh positive thoughts. These thoughts often create unwanted confusion, trouble, stress and frustration in our mind as well as chaos in our physical world. Negative thoughts are also known as “distorted thinking”.
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdfTechSoup
In this webinar you will learn how your organization can access TechSoup's wide variety of product discount and donation programs. From hardware to software, we'll give you a tour of the tools available to help your nonprofit with productivity, collaboration, financial management, donor tracking, security, and more.
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
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.
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.
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
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 5106 steps,
– while B requires 2.51041 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
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
}
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
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
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
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
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
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
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…
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.
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)