(Ebook) Quantum Series- Data Structure by Prashant Agarwal
(Ebook) Quantum Series- Data Structure by Prashant Agarwal
(Ebook) Quantum Series- Data Structure by Prashant Agarwal
(Ebook) Quantum Series- Data Structure by Prashant Agarwal
(Ebook) Quantum Series- Data Structure by Prashant Agarwal
1.
Instant Ebook Access,One Click Away – Begin at ebooknice.com
(Ebook) Quantum Series- Data Structure by Prashant
Agarwal
https://ebooknice.com/product/quantum-series-data-
structure-36460690
OR CLICK BUTTON
DOWLOAD EBOOK
Get Instant Ebook Downloads – Browse at https://ebooknice.com
2.
Instant digital products(PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...
Start reading on any device today!
(Ebook) Productizing Quantum Computing by Dhairyya Agarwal
https://ebooknice.com/product/productizing-quantum-computing-54388500
ebooknice.com
(Ebook) Quantum Mechanics Mathematical Structure and Physical Structure Part I by
John Boccio
https://ebooknice.com/product/quantum-mechanics-mathematical-structure-and-
physical-structure-part-i-34493418
ebooknice.com
(Ebook) Productizing Quantum Computing: Bring Quantum Computing Into Your
Organization by Agarwal, Dhairyya, D, Shalini, Ganguly, Srinjoy ISBN 9781484299852,
1484299841
https://ebooknice.com/product/productizing-quantum-computing-bring-quantum-
computing-into-your-organization-54394916
ebooknice.com
(Ebook) Quantum Mechanics Mathematical Structure and Physical Structure Part II
(Revised 2022) by John Boccio
https://ebooknice.com/product/quantum-mechanics-mathematical-structure-and-
physical-structure-part-ii-revised-2022-43013758
ebooknice.com
3.
(Ebook) Measurement, Analysisand Remediation of Environmental Pollutants by Tarun
Gupta, Swatantra Pratap Singh, Prashant Rajput, Avinash Kumar Agarwal ISBN
9789811505393, 9789811505409, 981150539X, 9811505403
https://ebooknice.com/product/measurement-analysis-and-remediation-of-
environmental-pollutants-10805986
ebooknice.com
(Ebook) Upanishads- Acharya Prashant by Acharya Prashant
https://ebooknice.com/product/upanishads-acharya-prashant-45326436
ebooknice.com
(Ebook) Capital structure decisions : evaluating risk and uncertainty by Agarwal,
Yamini ISBN 9781118203149, 9781118203163, 9781119199144, 9781118203132, 1118203143,
111820316X, 111919914X, 1118203135
https://ebooknice.com/product/capital-structure-decisions-evaluating-risk-and-
uncertainty-5300744
ebooknice.com
(Ebook) Phacoemulsification by Sunita Agarwal, Amar Agarwal, Athiya Agarwal ISBN
9781841844701, 1841844705
https://ebooknice.com/product/phacoemulsification-1187976
ebooknice.com
(Ebook) ON THE MATHEMATICAL STRUCTURE OF QUANTUM MEASUREMENT THEORY by GEOFFREY
SEWELL ISBN 9781119598244, 1119598249
https://ebooknice.com/product/on-the-mathematical-structure-of-quantum-
measurement-theory-43760714
ebooknice.com
6.
QUANTUM SERIES
TM
QUANTUM PAGEPVT. LTD.
Ghaziabad New Delhi
For
B.Tech Students of Second Year
of All Engineering Colleges Affiliated to
Dr. A.P.J. Abdul Kalam Technical University,
Uttar Pradesh, Lucknow
(FormerlyUttar Pradesh Technical University)
DATA STRUCTURES
By
Prashant Agarwal
1 A (CS/IT-Sem-3)
UNIT - 1: ARRAYS AND LINKED LISTS (1–1 A to 1–51 A)
Introduction: Basic Terminology, Elementary Data Organization, Built in
Data Types in C. Algorithm, Efficiency of an Algorithm, Time and Space
Complexity, Asymptotic notations: Big Oh, Big Theta and Big Omega,
Time-Space trade-off. Abstract Data Types (ADT).
Arrays: Definition, Single and Multidimensional Arrays, Representation
of Arrays: Row Major Order, and Column Major Order, Derivation of
Index Formulae for 1-D, 2-D, 3-D and n-D Array. Application of arrays,
Sparse Matrices and their representations.
Linkedlists: ArrayImplementation &Pointer Implementationof SinglyLinked
Lists, Doubly Linked List, Circularly Linked List, Operations on Linked List.
Insertion,Deletion,Traversal,PolynomialRepresentation&AdditionSubtraction
& Multiplications of Single variable & Two variables Polynomial.
UNIT - 2 : STACKS AND QUEUES (2–1 A to 2–38 A)
Stacks: Abstract Data Type, Primitive Stack operations: Push & Pop, Array
& Linked Implementation of Stack in C, Application of stack: Prefix and
PostfixExpressions, Evaluationofpostfixexpression,Iteration and Recursion-
Principles of recursion, Tail recursion, Removal ofrecursion Problem solving
using iteration and recursion with examples such as binary search, Fibonacci
numbers and Hanoi towers. Tradeoffs between iteration and recursion.
Queues:Operations onQueue:Create,Add,Delete,Full &Empty,Circularqueues,
Array & linked implementation of queues in C, Dequeue & Priority Queue.
UNIT - 3 : SEARCHING & SORTING (3–1 A to 3–24 A)
ConceptofSearching, Sequentialsearch, Index SequentialSearch,BinarySearch.
Concept of Hashing & Collision resolution Techniques used in Hashing.
Sorting: Insertion Sort, Selection, Bubble Sort, Quick Sort, Merge Sort, Heap Sort
and Radix Sort.
UNIT - 4 : GRAPHS (4–1 A to 4–41 A)
Terminology used with Graph, Data Structure for Graph Representations:
Adjacency Matrices, Adjacency List, Adjacency. Graph Traversal: Depth
First Search & Breadth First Search, Connected Component, Spanning Trees,
Minimum Cost Spanning Trees: Prims and Kruskal algorithm. Transitive
Closure &ShortestPath algorithm:Warshal Algorithm& Dijikstra Algorithm.
UNIT - 5 : TREES (5–1 A to 5–51 A)
Basic terminology used with Tree, Binary Trees, Binary Tree
Representation: Array Representation and Pointer (Linked List)
Representation, Binary Search Tree, Strictly Binary Tree, Complete Binary
Tree. A Extended Binary Trees, Tree Traversal algorithms: Inorder,
Preorder and Postorder, Constructing Binary Tree from given Tree
Traversal, Operation of Insertation, Deletion, Searching & Modification of
data in Binary Search. Threaded Binary trees, Traversing Threaded Binary
trees. Huffman coding using Binary Tree. Concept & Basic Operations for
AVL Tree, B Tree & Binary Heaps.
SHORT QUESTIONS (SQ–1 A to SQ–15 A)
SOLVED PAPERS (2014-15 TO 2019-20) (SP–1 A to SP–33 A)
3 A (CS/IT-Sem-3)
CONTENTS
KCS 301 : DATA STRUCTURE
10.
B.TECH. (COMPUTER SCIENCEAND ENGINEERING)
THIRD SEMESTER (DETAILED SYLLABUS)
DATA STRUCTURE (KCS301)
Course Outcome ( CO) Bloom’s Knowledge Level (KL)
At the end of course , the student will be able to understand
CO 1
Describe how arrays, linked lists, stacks, queues, trees, and graphs are represented in memory,
used by the algorithms and their common applications.
K1, K2
CO 2 Discuss the computational efficiency of the sorting and searching algorithms. K2
CO 3 Implementation of Trees and Graphs and perform various operations on these data structure. K3
CO 4
Understanding the concept of recursion, application of recursion and its implementation and
removal of recursion.
K4
CO 5
Identify the alternative implementations of data structures with respect to its performance to
solve a real world problem.
K5, K6
DETAILED SYLLABUS 3-1-0
Unit Topic Proposed
Lecture
I
Introduction: Basic Terminology, Elementary Data Organization, Built in Data Types in C.
Algorithm, Efficiency of an Algorithm, Time and Space Complexity, Asymptotic notations: Big
Oh, Big Theta and Big Omega, Time-Space trade-off. Abstract Data Types (ADT)
Arrays: Definition, Single and Multidimensional Arrays, Representation of Arrays: Row Major
Order, and Column Major Order, Derivation of Index Formulae for 1-D,2-D,3-D and n-D Array
Application of arrays, Sparse Matrices and their representations.
Linked lists: Array Implementation and Pointer Implementation of Singly Linked Lists, Doubly
Linked List, Circularly Linked List, Operations on a Linked List. Insertion, Deletion, Traversal,
Polynomial Representation and Addition Subtraction & Multiplications of Single variable & Two
variables Polynomial.
08
II
Stacks: Abstract Data Type, Primitive Stack operations: Push & Pop, Array and Linked
Implementation of Stack in C, Application of stack: Prefix and Postfix Expressions, Evaluation of
postfix expression, Iteration and Recursion- Principles of recursion, Tail recursion, Removal of
recursion Problem solving using iteration and recursion with examples such as binary search,
Fibonacci numbers, and Hanoi towers. Tradeoffs between iteration and recursion.
Queues: Operations on Queue: Create, Add, Delete, Full and Empty, Circular queues, Array and
linked implementation of queues in C, Dequeue and Priority Queue.
08
III
Searching: Concept of Searching, Sequential search, Index Sequential Search, Binary Search.
Concept of Hashing & Collision resolution Techniques used in Hashing. Sorting: Insertion Sort,
Selection, Bubble Sort, Quick Sort, Merge Sort, Heap Sort and Radix Sort.
08
IV
Graphs: Terminology used with Graph, Data Structure for Graph Representations: Adjacency
Matrices, Adjacency List, Adjacency. Graph Traversal: Depth First Search and Breadth First
Search, Connected Component, Spanning Trees, Minimum Cost Spanning Trees: Prims and
Kruskal algorithm. Transitive Closure and Shortest Path algorithm: Warshal Algorithm and
Dijikstra Algorithm.
08
11.
V
Trees: Basic terminologyused with Tree, Binary Trees, Binary Tree Representation: Array
Representation and Pointer(Linked List) Representation, Binary Search Tree, Strictly Binary Tree
,Complete Binary Tree . A Extended Binary Trees, Tree Traversal algorithms: Inorder, Preorder
and Postorder, Constructing Binary Tree from given Tree Traversal, Operation of Insertation ,
Deletion, Searching & Modification of data in Binary Search . Threaded Binary trees, Traversing
Threaded Binary trees. Huffman coding using Binary Tree. Concept & Basic Operations for AVL
Tree , B Tree & Binary Heaps
08
Text books:
1. Aaron M. Tenenbaum, Yedidyah Langsam and Moshe J. Augenstein, “Data Structures Using C and C++”,
PHI
Learning Private Limited, Delhi India
2. Horowitz and Sahani, “Fundamentals of Data Structures”, Galgotia Publications Pvt Ltd Delhi India.
3. Lipschutz, “Data Structures” Schaum’s Outline Series, Tata McGraw-hill Education (India) Pvt. Ltd.
4. Thareja, “Data Structure Using C” Oxford Higher Education.
5. AK Sharma, “Data Structure Using C”, Pearson Education India.
6. Rajesh K. Shukla, “Data Structure Using C and C++” Wiley Dreamtech Publication.
7. Michael T. Goodrich, Roberto Tamassia, David M. Mount “Data Structures and Algorithms in C++”,
Wiley India.
8. P. S. Deshpandey, “C and Data structure”, Wiley Dreamtech Publication.
9. R. Kruse etal, “Data Structures and Program Design in C”, Pearson Education.
10. Berztiss, AT: Data structures, Theory and Practice, Academic Press.
11. Jean Paul Trembley and Paul G. Sorenson, “An Introduction to Data Structures with applications”,
McGraw Hill.
12. Adam Drozdek “Data Structures and Algorithm in Java”, Cengage Learning
12.
1–1 A (CS/IT-Sem-3)
DataStructure
CONTENTS
Part-1 : Introduction : ............................................... 1–3A to 1–5A
Basic Terminology,
Elementary Data Organization
Built in Data Types in C
Part-2 : Algorithm, Efficiency of ............................ 1–5A to 1–8A
an Algorithm, Time and
Space Complexity
Part-3 : Asymptotic Notations : ............................. 1–8A to 1–10A
Big Oh, Big Theta, and
Big Omega
Part-4 : Time-Space Trade-Off, .......................... 1–10A to 1–13A
Abstract Data Types (ADT)
Part-5 : Array : Definition, Single and .............. 1–13A to 1–14A
Multidimensional Array
Part-6 : Representation of Arrays : ................... 1–14A to 1–17A
Row Major Order, and Column
Major Order, Derivation of Index
Formulae for
1-D, 2-D, 3-D and n-D Array
Part-7 : Application of Arrays, Sparse ............... 1–18A to 1–20A
Matrices and their Representation
Array and Linked List
1
13.
1–2 A (CS/IT-Sem-3)Array and Linked List
Part-8 : Linked List : Array.................................. 1–20A to 1–29A
Implementation and
Pointer Implementation
of Singly Linked List
Part-9 : Doubly Linked List ................................. 1–29A to 1–37A
Part-10 : Circular Linked List ............................... 1–37A to 1–43A
Part-11 : Operation on a Linked ........................... 1–43A to 1–49A
List, Insertion,
Deletion, Traversal
Polynomial Representation
and Addition, Subtraction
and Multiplication of Single
Variable and Two
Variable Polynomial
14.
1–3 A (CS/IT-Sem-3)
DataStructure
Introduction : Basic Terminology, Elementary Data Organization
Built in Data Types in C.
Questions-Answers
Long Answer Type and Medium Answer Type Questions
Que 1.1. Define data structure. Describe about its need and types.
Why do we need a data type ? AKTU 2014-15, Marks 05
Answer
Data structure :
1. 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.
2. Data structure is the representation of the logical relationship existing
between individual elements of data.
3. Data structure is define as a mathematical or logical model of particular
organization of data items.
Data structure is needed because :
1. It helps to understand the relationship of one element with the other.
2. It helps in the organization of all data items within the memory.
The data structures are divided into following categories :
1. Linear data structure :
a. A linear data structure is a data structure whose elements form a
sequence, and every element in the structure has a unique
predecessor and unique successor.
b. Examples of linear data structure are arrays, linked lists, stacks
and queues.
2. Non-linear data structure :
a. Anon-linear data structure it is a datastructure whose elements do not
form a sequence. There is no unique predecessor or unique successor.
b. Examples of non-linear data structures are trees and graphs.
Need of data type : The data type is needed because it determines what type
of information can be stored in the field and how the data can be formatted.
Que 1.2. Discuss some basic terminology used and elementary
data organization in data structures.
15.
1–4 A (CS/IT-Sem-3)Array and Linked List
Answer
Basic terminologies used in data structure :
1. Data : Data are simply values or sets of values. A data item refers to a
single unit of values.
2. Entity : An entity is something that has certain attributes or properties
which may be assigned values.
3. Field : A field is a single elementary unit of information representing an
attribute of an entity.
4. Record : A record is the collection of field values of a given entity.
5. File : A file is the collection of records of the entities in a given entity set.
Data organization : Each record in a file may contain many field items, but
the value in a certain field may uniquely determine the record in the file.
Such a field K is called a primary key, and the values k1
, k2
,... in such a field
are called keys or key values.
Que 1.3. Define data types. What are built in data types in C ?
Explain.
Answer
1. C data types are defined as the data storage format that a variable can
store a data to perform a specific operation.
2. Data types are used to define a variable before to use in a program.
3. There are two types of built in data types in C :
a. Primitive data types : Primitive data types are classified as :
i. Integer type : Integers are used to store whole numbers.
Size and range of integer type on 16-bit machine :
Type Size (bytes) Range Format
specifier
int or signed int 2 – 32,768 to 32,767 %d
unsigned int 2 0 to 65,535 %u
short int or signed
short int 1 – 128 to 127 %hd
unsigned short int 1 0 to 255 %hu
long int or signed
long int 4 – 2,147,483,648 %ld
to 2,147,483,647
unsigned long int 4 0 to 4,294,967,295 %lu
ii. Floating point type : Floating types are used to store real numbers.
16.
1–5 A (CS/IT-Sem-3)
DataStructure
Size and range of floating point type on 16-bit machine :
Type Size (bytes) Range Format
specifier
Float 4 3.4E – 38 to 3.4E+38 %f
double 8 1.7E – 308 to 1.7E+308 %lf
long double 10 3.4E – 4932 to 1.1E+4932 %lf
iii. Character type : Character types are used to store characters value.
Size and range of character type on 16-bit machine :
Type Size (bytes) Range Format
specifier
char or signed char 1 – 128 to 127 %c
unsigned char 1 0 to 255 %c
iv. Void type : Void type is usually used to specify the type of functions
which returns nothing.
b. Non-primitive data types :
i. These are more sophisticated data types. These are derived from
the primitive data types.
ii. The non-primitive data types emphasize on structuring of a group
of homogeneous (same type) or heterogeneous (different type)
items. For example, arrays, lists and files.
Algorithm, Efficiency of an Algorithm, Time and Space Complexity.
Questions-Answers
Long Answer Type and Medium Answer Type Questions
Que 1.4. Define algorithm. Explain the criteria an algorithm must
satisfy. Also, give its characteristics.
Answer
1. An algorithm is a step-by-step finite sequence of instructions, to solve a
well-defined computational problem.
2. Every algorithm must satisfy the following criteria :
i. Input : There are zero or more quantities which are externally
supplied.
17.
1–6 A (CS/IT-Sem-3)Array and Linked List
ii. Output : At least one quantity is produced.
iii. Definiteness : Each instruction must be clear and unambiguous.
iv. Finiteness : If we trace out the instructions of an algorithm, then
for all cases the algorithm will terminate after a finite number of
steps.
v. Effectiveness : Every instruction must be basic and essential.
Characteristics of an algorithm :
1. It should be free from ambiguity.
2. It should be concise.
3. It should be efficient.
Que 1.5. How the efficiency of an algorithm can be checked ?
Explain the different ways of analyzing algorithm.
Answer
The efficiency of an algorithm can be checked by :
1. Correctness of an algorithm
2. Implementation of an algorithm
3. Simplicity of an algorithm
4. Execution time and memory requirements of an algorithm
Different ways of analyzing an algorithm :
a. Worst case running time :
1. The behaviour of an algorithm with respect to the worst possible
case of the input instance.
2. The worst case running time of an algorithm is an upper bound on
the running time for any input.
b. Average case running time :
1. The expected behaviour when the input is randomly drawn from a
given distribution.
2. The average case running time of an algorithm is an estimate of
the running time for an “average” input.
c. Best case running time :
1. The behaviour of the algorithm when input is already in order. For
example, in sorting, if elements are already sorted for a specific
algorithm.
2. The best case running time rarely occurs in practice comparatively
with the first and second case.
Que 1.6. Define complexity and its types.
Answer
1. The complexity of an algorithm M is the function f(n) which gives the
running time and/or storage space requirement of the algorithm in
terms of the size n of the input data.
18.
1–7 A (CS/IT-Sem-3)
DataStructure
2. The storage space required by an algorithm is simply a multiple of the
data size n.
3. Following are various cases in complexity theory :
a. Worst case : The maximum value of f(n) for any possible input.
b. Average case : The expected value of f(n) for any possible input.
c. Best case : The minimum possible value of f(n) for any possible
input.
Types of complexity :
1. Space complexity : The space complexity of an algorithm is the amount
of memory it needs to run to completion.
2. Time complexity : The time complexity of an algorithm is the amount
of time it needs to run to completion.
Que 1.7. What do you understand by complexity of an
algorithm ? Compute the worst case complexity for the following
C code :
main()
{
int s = 0, i, j, n;
for (j = 0; j < (3 * n); j++)
{
for (i = 0; i < n; i++)
{
s = s + i;
}
printf(“%d”, i);
}} AKTU 2014-15, Marks 05
Answer
Complexity of an algorithm : Refer Q. 1.6, Page 1–6A, Unit-1.
Worst case complexity : (n) + (3n) = (n)
Que 1.8. How do you find the complexity of an algorithm ? What
is the relation between the time and space complexities of an
algorithm ? Justify your answer with an example.
AKTU 2015-16, Marks 10
Answer
Complexity of an algorithm : Refer Q. 1.6, Page 1–6A, Unit-1.
Relation between the time and space complexities of an algorithm :
1. The time and space complexities are not related to each other.
2. They are used to describe how much space/time our algorithm takes
based on the input.
3. For example, when the algorithm has space complexity of :
19.
1–8 A (CS/IT-Sem-3)Array and Linked List
a. O(1) i.e., constant then the algorithm uses a fixed (small) amount
of space which does not depend on the input. For every size of the
input the algorithm will take the same (constant) amount of space.
b. O(n), O(n2
), O(log (n)) - these indicate that we create additional
objects based on the length of our input.
4. In contrast, the time complexity describes how much time our algorithm
consumes based on the length of the input.
5. For example, when the algorithm has time complexity of :
a. O(1) i.e., constant then no matter how big is the input it always
takes a constant time.
b. O(n), O(n2
), O(log (n)) - again it is based on the length of the input.
For example :
function(list l) { function(list l) {
for (node in l) { print(“I got a list”); }
print(node) ;
}
}
In this example, both take O(1) space as we do not create additional
objects which shows that time and space complexity might be different.
Asymptotic Notations : Big Oh, Big Theta, and Big Omega.
Questions-Answers
Long Answer Type and Medium Answer Type Questions
Que 1.9. What is asymptotic notation ? Explain the big ‘Oh’
notation.
Answer
1. Asymptotic notation is a shorthand way to describe running times for an
algorithm.
2. It is a line that stays within bounds.
3. These are also referred to as ‘best case’ and ‘worst case’ scenarios
respectively.
Big ‘Oh’ notation :
1. Big-Oh is formal method of expressing the upper bound of an algorithm’s
running time.
2. It is the measure of the longest amount of time it could possibly take for
the algorithm to complete.
3. More formally, for non-negative functions, f (n) and g(n), if there exists
an integer n0 and a constant c > 0 such that for all integers n > n0.
20.
1–9 A (CS/IT-Sem-3)
DataStructure
f (n) cg(n)
4. Then, f (n) is Big-Oh of g (n). This is denoted as : f (n) O(g (n))
i.e., the set of functions which, as n gets large, grow faster than a
constant time f (n).
cg(n)
f(n)
n
f(n) = O(g(n))
n0
Fig. 1.9.1.
Que 1.10. What is complexity of an algorithm ? Explain various
notations used to express the complexity of an algorithm.
OR
What are the various asymptotic notations ? Explain Big O notation.
AKTU 2017-18, Marks 07
Answer
Complexity of an algorithm : Refer Q. 1.6, Page 1–6A, Unit-1.
Notations used to express the complexity of an algorithm :
1. -Notation (Same order) :
a. This notation bounds a function to within constant factors.
b. We say f(n) = g(n) if there exist positive constants n0
, c1
and c2
such that to the right of n0
the value of f(n) always lies between
c1
g(n) and c2
g(n) inclusive.
c g(n)
2
f(n)
c g(n)
1 f(n) = (g(n))
n
Fig. 1.10.1.
n0
2. Oh-Notation (Upper bound) : Refer Q. 1.9, Page 1–8A, Unit-1.
3. -Notation (Lower bound) :
a. This notation gives a lower bound for a function to within a constant
factor.
21.
1–10 A (CS/IT-Sem-3)Array and Linked List
b. We write f(n) = g(n)) if there are positive constants n0
and c such
that to the right of n0
, the value of f(n) always lies on or above cg(n).
f(n) = (g(n))
f(n)
cg(n)
n0
n
Fig. 1.10.2.
4. Little - Oh notation (o) :
a. It is used to denote an upper bound that is asymptotically tight
because upper bound provided by O-notation is not tight.
b. We write o(g(n)) = {f(n) : For any positive constant c > 0, if a
constant n0
> 0 such that 0 < f(n) < cg(n) V n > n0
}
5. Little omega notation () :
a. It is used to denote lower bound that is asymptotically tight.
b. We write(g(n)) = {f(n) : For any positive constant c > 0, if a
constant n0
> 0 such that 0 < cg(n) < f(n)}
Time-Space Trade-off, Abstract Data Types (ADT).
Questions-Answers
Long Answer Type and Medium Answer Type Questions
Que 1.11. Explain time-space trade-off in brief with suitable
example.
OR
What do you understand by time and space trade-off ? Define the
various asymptotic notations. Derive the O-notation for linear
search. AKTU 2018-19, Marks 07
Answer
Time-space trade-off :
1. The time-space trade-off refers to a choice between algorithmic solutions
of data processing problems that allows to decrease the running time of
an algorithmic solution by increasing the space to store data and
vice-versa.
22.
1–11 A (CS/IT-Sem-3)
DataStructure
2. Time-space trade-off is basically a situation where either space efficiency
(memory utilization) can be achievedat the cost of time or time efficiency
(performance efficiency) can be achieved at the cost of memory.
For Example : Suppose, in a file, if data stored is not compressed, it
takes more space but access takes less time. Now if the data stored is
compressed the access takes more time because it takes time to run
decompression algorithm.
Various asymptotic notation : Refer Q. 1.10, Page 1–9A, Unit-1.
Derivation :
Best case : In the best case, the desired element is present in the first
position of the array, i.e., only one comparison is made.
So, T(n) = O(1).
Average case : Here we assume that ITEM does appear, and that is equally
likely to occur at any position in the array. Accordingly the number of
comparisons can be any of the number 1, 2, 3, ......, n and each number occurs
with the probability p = 1/n. Then
T(n) = 1 . (1/n) + 2 . (1/n) + 3 . (1/n) ...... + n . (1/n)
= (1 + 2 + 3 + ...... + n) . (1/n)
= n . (n + 1)/2 . (1/n)
= (n + 1)/2
= O((n + 1)/2) O(n)
Worst case : Worst case occurs when ITEM is the last element in the array
or is not there at all. In this situation n comparison is made
So, T(n) = O(n + 1) O(n)
Que 1.12. What do you understand by time-space trade-off ?
Explain best, worst and average case analysis in this respect with
an example. AKTU 2017-18, Marks 07
Answer
Time-space trade-off : Refer Q. 1.11, Page 1–10A, Unit-1.
Best, worst and average case analysis : Suppose we are implementing
an algorithm that helps us to search for a record amongst a list of records. We
can have the following three cases which relate to the relative success our
algorithm can achieve with respect to time :
1. Best case :
a. The record we are trying to search is the first record of the list.
b. If f(n) is the function which gives the running time and / or storage
space requirement of the algorithm in terms of the size n of the
input data, this particular case of the algorithm will produce a
23.
1–12 A (CS/IT-Sem-3)Array and Linked List
complexity C(n) = 1 for our algorithm f(n) as the algorithm will run
only 1 time until it finds the desired record.
2. Worst case :
a. The record we are trying to search is the last record of the list.
b. If f(n) is the function which gives the running time and / or storage
space requirement of the algorithm in terms of the size n of the
input data, this particular case of the algorithm will produce a
complexity C(n) = n for our algorithm f(n), as the algorithm will run
n times until it finds the desired record.
3. Average case :
a. The record we are trying to search can be any record in the list.
b. In this case, we do not know at which position it might be.
c. Hence, we take an average of all the possible times our algorithm
may run.
d. Hence assuming for n data, we have a probability of finding any
one of them is 1/n.
e. Multiplying each of these with the number of times our algorithm
might run for finding each of them and then taking a sum of all
those multiples, we can obtain the complexity C(n) for our algorithm
f(n) in case of an average case as following :
C(n) = 1·
1
2
+ 2·
1
2
+ ... + n·
1
2
C(n) = (1 + 2 + ... + n) ·
1
2
C(n) =
( 1) 1 1
·
2 2
n n n
n
Hence in this way, we can find the complexity of an algorithm for
average case as
C(n) = O((n + 1)/2)
Que 1.13. What do you mean by Abstract Data Type ?
Answer
1. An Abstract Data Type (ADT) is defined as a mathematical model of the
data objects that make up a data type as well as the functions that
operate on these objects.
2. An Abstract Data Type (ADT) is the specification of the data type which
specifies the logical and mathematical model of the data type.
3. It does not specify how data will be organized in memory and what
algorithm will be used for implementing the operations.
24.
1–13 A (CS/IT-Sem-3)
DataStructure
4. An implementation chooses a data structure to represent the ADT.
5. The important step is the definition of ADT that involves mainly two
parts :
a. Description of the way in which components are related to each
other.
b. Statements of operations that can be performed on the data type.
Array : Definition, Single and Multidimensional Array.
Questions-Answers
Long Answer Type and Medium Answer Type Questions
Que 1.14. Define array. How arrays can be declared ?
Answer
1. An array can be defined as the collection of the sequential memory
locations, which can be referred to by a single name along with a number
known as the index, to access a particular field or data.
2. The general form of declaration is :
type variable-name [size];
a. Type specifies the type of the elements that will be contained in the
array, such as int, float or char and the size indicates the maximum
of elements that can be stored inside the array.
b. For example, when we want to store 10 integer values, then we can
use the following declaration, int A[10].
Que 1.15. Write short note on types of an array.
Answer
There are two types of array :
1. One-dimensional array :
a. An array that can be represented by only one-one dimension such
as row or column and that holds finite number of same type of data
items is called one-dimensional (linear) array.
b. One dimensional array (or linear array) is a set of ‘n’ finite numbers
of homogeneous data elements such as :
i. The elements of the array are referenced respectively by an
index set consisting of ‘n’ consecutive number.
25.
1–14 A (CS/IT-Sem-3)Array and Linked List
ii. The elements of the array are stored respectively in successive
memory locations.
‘n’ number of elements is called the length or size of an array.
The elements of an array ‘A’ may be denoted in C language as :
A[0], A[1], A[2], ... A[n –1]
2. Multidimensional arrays :
a. An array can be of more than one dimension. There are no
restrictions to the number of dimensions that we can have.
b. As the the dimensions increase the memory requirements increase
drastically which can result in shortage of memory.
c. Hence a multidimensional array must be used with utmost care.
d. For example, the following declaration is used for 3-D array :
int a [50] [50] [50];
Representation of Arrays : Row Major Order, and Column
Major Order, Derivation of Index Formulae for
1–D, 2–D, 3–D and n–D Array.
Questions-Answers
Long Answer Type and Medium Answer Type Questions
Que 1.16. What is row major order ? Explain with an example.
AKTU 2014-15, Marks 05
Answer
1. In row major order, the element of an array is stored in computer
memory as row-by-row.
2. Under row major representation, the first row of the array occupies the
first set of memory locations reserved for the array, the second row
occupies the next set, and so forth.
3. In row major order, elements of a two-dimensional array are ordered
as :
A11
, A12
, A13
, A14
, A15
, A16
, A21
, A22
, A23
, A24
, A25
, A26
, A31
, ....., A46
, A51
, A52
,
......, A56
Example :
Let us consider the following two-dimensional array :
a b c d
e f g h
i j k l
26.
1–15 A (CS/IT-Sem-3)
DataStructure
a. Move the elements of the second row starting from the first element
to the memory location adjacent to the last element of the first row.
b. When this step is applied to all the rows except for the first row, we
have a single row of elements. This is the row major representation.
c. By application of above mentioned process, we get
{a, b, c, d, e, f, g, h, i, j, k, l}
Que 1.17. Explain column major order with an example.
Answer
1. In column major order the elements of an array is stored as column-by-
column, it is called column major order.
2. Under column major representation, the first column of the array
occupies the first set of memory locations reserved for the array, the
second column occupies the next set, and so forth.
3. In column major order, elements are ordered as :
A11
, A21
, A31
, A41
, A51
, A12
, A22
, A32
, A42
, A52
, A13
, ....., A55
, A16
, A26
, ......., A56
.
Example : Consider the following two-dimensional array :
a b c d
e f g h
i j k l
a. Transpose the elements of the array. Then, the representation will
be same as that of the row major representation.
b. Then perform the process of row-major representation.
c. By application of above mentioned process, we get
{a, e, i, b, f, j, c, g, k, d, h, l}.
Que 1.18. Write a short note on address calculation for 2D array.
OR
Determine addressing formula to find the location of (i, j)th element
of a m × n matrix stored in column major order.
OR
Derive the index formulae for 1-D and 2-D array.
Answer
1. Let us consider a two-dimensional array A of size m × n. Like linear
array system keeps track of the address of first element only, i.e., base
address of the array (Base (A)).
2. Using the base address, the computer computes the address of the
element in the ith
row and jth
column i.e., LOC (A[i][j]).
Formulae :
a. Column major order :
LOC(A[i][j]) = Base (A) + w[m(j – lower bound for column index)
27.
1–16 A (CS/IT-Sem-3)Array and Linked List
+ (i – lower bound for row index)]
LOC(A[i][j]) = Base (A) + w[mj + i] in C/C++
b. Row major order :
LOC(A[i][j]) = Base (A) + w[n(i – lower bound for column index)
+ (j – lower bound for row index)]
LOC(A[i][j]) = Base (A) + w[ni + j] in C/C++
where w denotes the number of words per memory location for the
array A or the number of bytes per storage location for one element of
the array.
Que 1.19. Explain the formulae for address calculation for 3-D
array with example.
Answer
In three-dimensional array, address is calculated using following two
methods :
Row major order :
Location (A[i, j, k]) = Base (A) + mn (k – 1) + n (i – 1) + (j – 1)
Column major order :
Location (A[i, j, k] ) = Base (A) + mn (k – 1) + m (j – 1) + (i – 1)
For example : Given an array [1..8, 1..5, 1..7] of integers. If Base (A) = 900
then address of element A[5, 3, 6], by using rows and columns methods are :
The dimensions of A are : M = 8, N = 5, R = 7, i = 5, j = 3, k = 6
Row major order :
Location (A[i, j, k]) = Base (A) + mn (k – 1) + n (i – 1) + (j – 1)
Location (A[5, 3, 6]) = 900 + 8 × 5(6 – 1) + 5(5 – 1) + (3 – 1)
= 900 + 40 × 5 + 5 × 4 + 2
= 900 + 200 + 20 + 2 = 1122
Column major order :
Location (A[i, j, k]) = Base (A) + mn (k – 1) + m (j – 1) + (i – 1)
Location (A[5, 3, 6]) = 900 + 8 × 5(6 – 1) + 8(3 – 1) + (5 – 1)
= 900 + 40 × 5 + 8 × 2 + 4
= 900 + 200 +16 + 4 = 1120
Que 1.20. Consider the linear arrays AAA [5 : 50], BBB [– 5 : 10] and
CCC [1 : 8].
a. Find the number of elements in each array.
b. Suppose base (AAA) = 300 and w = 4 words per memory cell for
AAA. Find the address of AAA [15], AAA [35] and AAA [55].
AKTU 2015-16, Marks 10
Answer
a. The number of elements is equal to the length; hence use the formula :
28.
1–17 A (CS/IT-Sem-3)
DataStructure
Length = UB – LB + 1
Length (AAA) = 50 – 5 + 1 = 46
Length (BBB) = 10 – (– 5) + 1 = 16
Length (CCC) = 8 – 1 + 1 = 8
b. Use the formula
LOC (AAA [i]) = Base (AAA) + w (i – LB)
LOC (AAA [15]) = 300 + 4 (15 – 5) = 340
LOC (AAA [35]) = 300 + 4 (35 – 5) = 420
AAA [55] is not an element of AAA, since 55 exceeds UB = 50.
Que 1.21. Suppose multidimensional arrays P and Q are declared
as P(– 2: 2, 2: 22) and Q(1: 8, – 5: 5, – 10 : 5) stored in column major order
i. Find the length of each dimension of P and Q.
ii. The number of elements in P and Q.
iii. Assuming base address (Q) = 400, W = 4, find the effective indices
E1
, E2
, E3
and address of the element Q[3, 3, 3].
AKTU 2018-19, Marks 07
Answer
i. The length of a dimension is obtained by
Length = Upper Bound – Lower Bound + 1
Hence, the lengths of the dimension of P are,
L1 = 2 – (– 2) + 1 = 5; L2 = 22 – 2 + 1 = 21
The lengths of the dimension of Q are,
L1 = 8 – 1 + 1 = 8; L2 = 5 – (– 5) + 1 = 11; L3 = 5 – (– 10) + 1 = 16
ii. Number of elements in P = 21 × 5 = 105 elements
Number of elements in Q = 8 × 11 × 16 = 1408 elements
iii. The effective index Ei is obtained from Ei = ki – LB, where ki is the given
index and LB, is the Lower Bound. Hence,
E1 = 3 – 1 = 2; E2 = 3 – (– 5) = 8; E3 = 3 – (– 10) = 13
The address depends on whether the programming language stores Q
in row major order or column major order. Assuming Q is stored in
column major order.
E3L2 = 13 × 11 = 143
E3L2 + E2 = 143 + 8 = 151
(E3L2)L1 = 151 * 8 = 1208
(E2L2+E2)L1 + E1 = 1208 + 2 = 1210
Therefore, LOC(Q[3,3,3]) = 400 + 4(1210) = 400 + 4840 = 5240
29.
1–18 A (CS/IT-Sem-3)Array and Linked List
Application of Arrays, Sparse Matrices and their Representation.
Questions-Answers
Long Answer Type and Medium Answer Type Questions
Que 1.22. Write a short note on application of arrays.
Answer
1. Arrays are used to implement mathematical vectors and matrices, as
well as other kinds of rectangular tables. Many databases, small and
large, consist of one-dimensional arrays whose elements are records.
2. Arrays are used to implement other data structures, such as lists, heaps,
hash tables, queues and stacks.
3. Arrays are used to emulate in-program dynamic memory allocation,
particularly memory pool allocation.
4. Arrays can be used to determine partial or complete control flow in
programs, as a compact alternative to multiple “if” statements.
5. The array may contain subroutine pointers (or relative subroutine
numbers that can be acted upon by SWITCH statements) that direct the
path of the execution.
Que 1.23. What are sparse matrices ? Explain.
Answer
1. Sparse matrices are the matrices in which most of the elements of the
matrix have zero value.
2. Two general types of n-square sparse matrices, which occur in various
applications, as shown in Fig. 1.23.1.
3. It is sometimes customary to omit block of zeros in a matrix as in
Fig. 1.23.1. The first matrix, where all entries above the main diagonal
are zero or, equivalently, where non-zero entries can only occur on or
below the main diagonal, is called a lower triangular matrix.
4. The second matrix, where non-zero entries can only occur on the diagonal
or on elements immediately above or below the diagonal, is called
tridiagonal matrix.
30.
1–19 A (CS/IT-Sem-3)
DataStructure
4
3
1
– 7
– 5
0
8
6
– 1 3
5
1
– 3
4
9
3
– 3
2
6
4 – 7
( ) Triangular matrix
a ( ) Tridiagonal matrix
b
Fig. 1.23.1.
Que 1.24. Write a short note on representation of sparse matrices.
Answer
There are two ways of representing sparse matrices :
1. Array representation :
i. In the array representation of a sparse matrix, only the non-zero
elements are stored so that storage space can be reduced.
ii. Each non-zero element in the sparse matrix is represented as (row,
column, value).
iii. For this a two-dimensional array containing three columns can be
used. The first column is for storing the row numbers, the second
column is for storing the column numbers and the third column
represents the value corresponding to the non-zero element at
(row, column) in the first two columns.
iv. For example, consider the following sparse matrix :
2 0 0 0
0 1 0 0
0 4 3 0
The above matrix can be represented as :
Row Column Value
0 0 2
1 1 1
2 1 4
2 2 3
2. Linked representation :
i. In the linked list representation each node has four fields. These
four fields are defined as :
a. Row : Index of row, where non-zero element is located.
b. Column : Index of column, where non-zero element is located.
c. Value : Value of non-zero element located at index – (row,
column).
d. Next node : Address of next node.
Node structure : Column
Row Value Address
31.
1–20 A (CS/IT-Sem-3)Array and Linked List
Example :
0 0 3 0
0 0 5 7
0 2 0 0
Start
0 2 3 1 2 5 1 3 7 2 1 2 Null
Que 1.25. Explain the upper triangular and lower triangular
sparse matrices. Suggest a space efficient representation for sparse
matrices.
Answer
1. The matrix, where all entries above the main diagonal are zero or
equivalently, where non-zero entries can only occur, on or below the
main diagonal, is called lower triangular matrix.
2. A matrix in which all the entries below the main diagonal are zero is
called upper triangular matrix.
Space efficient representation for sparse matrices : Refer Q. 1.24,
Page 1–19A, Unit-1.
Linked List : Array Implementation and
Pointer Implementation of Singly Linked List.
Questions-Answers
Long Answer Type and Medium Answer Type Questions
Que 1.26. Define the term linked list. Write a C program to
implement singly linked list for the following function using array :
i. Insert at beginning ii. Insert at end
iii. Insert after element iv. Delete at end
v. Delete at beginning vi. Delete after element
vii. Display in reverse order
Answer
i. Linked list :
1. A linked list, or one-way list, is a linear collection of data elements,
called nodes, where the linear order is given by means of pointers.
32.
1–21 A (CS/IT-Sem-3)
DataStructure
Information part of third node
Next pointer field of third node
Start
Fig. 1.26.1.
×
2. Each node is divided into two parts: the first part contains the
information of the element, and the second part, called the link
field or next pointer field, contains the address of the next node in
the list.
Program :
#includestdio.h
#includeconio.h
#includealloc.h
struct node {
int info;
struct node *link;
} ;
struct node *first;
void main( )
i. Insert at beginning :
void insert_beginning( ) {
struct node *ptr;
ptr = (struct node*)malloc(sizeof(struct node));
if (ptr == NULL) {
printf (“overflown” ) ;
return;
}
printf (“input new node information”);
scanf (“%d”, ptr - info) ;
ptr - link = first;
first = ptr;
}
ii. Insert at end :
void insert_end( ) {
struct node *ptr; *cpt;
ptr = (struct node*)malloc(sizeof(struct node));
if (ptr == NULL) {
printf (“Link list is overflown”);
return;
}
printf (“input new node information”);
scanf (“%d”, ptr - info);
cpt = first;
while (cpt - link != NULL)
cpt = cpt - link;
33.
1–22 A (CS/IT-Sem-3)Array and Linked List
cpt - link = ptr;
ptr - link = NULL;
iii. Insert after element :
void insert_given_node( ) {
struct node *ptr, *cpt;
int data;
ptr = (struct node*)malloc(sizeof(struct node));
if (ptr == NULL) {
printf (“overflown”);
return;
}
printf (“input new node information”);
scanf (“%d”, ptr - info);
printf (“input information of node after which insertion will be made”) ;
scanf (“%d”, data) ;
cpt = first;
while (cpt - info != data)
cpt = cpt - link;
ptr - link = cpt - link;
cpt - link = ptr;
}
iv. Delete at end :
void delete_end( ) {
struct node *ptr, *cpt;
if (first == NULL) {
printf (“underflown”);
return;
}
ptr = first;
while (ptr - link != NULL) {
cpt = ptr;
ptr = ptr - link;
}
cpt - link = NULL;
free (ptr);
}
v. Delete at beginning :
void delete_beginning( ) {
struct node *ptr;
if (first == NULL) {
printf (“underflown”) ;
return;
}
ptr = first;
first = ptr - link;
free (ptr) ;
}
34.
1–23 A (CS/IT-Sem-3)
DataStructure
vi. Delete after element :
void delete_given_info( ) {
struct node *ptr, *cpt;
int data;
if (first == NULL) {
printf (“underflown” ) ;
return;
}
ptr = first;
printf (“input information of node to be deleted”) ;
scanf (“%d”, data);
while (ptr - info != data) {
cpt = ptr;
ptr = ptr - link;
}
cpt - link = ptr - link;
free (ptr);
}
vii. Display in reverse order :
reverse_list( ) {
ptr = First;
cpt = NULL;
while (ptr != NULL) {
cpt = ptr - link;
ptr - link = tpt;
cpt = ptr;
ptr = cpt;
} }
Que 1.27. Write algorithm of following operation for linear linked
list :
i. Traversal ii. Insertion at beginning
iii. Search an element iv. Delete node atspecified location
v. Deletion at end
Answer
i. Traversing a linked list : Let LIST be a linked list in memory. This
algorithm traverses LIST, applying an operation PROCESS to each
element of LIST. The variable PTR points to the node currently being
processed.
1. Set PTR := START [Initializes pointer PTR]
2. Repeat Steps 3 and 4 while PTR != NULL
3. Apply PROCESS to PTR - INFO
4. Set PTR := PTR - LINK [PTR now points to the next node]
[End of Step 2 loop]
5. Exit
35.
1–24 A (CS/IT-Sem-3)Array and Linked List
ii. Insertion at beginning : Here START is a pointer variable which
contains the address of first node. ITEM is the value to be inserted.
1. If (START == NULL) Then
2. START = New Node [Create a new node]
3. START-INFO = ITEM [Assign ITEM to INFO field]
4. START-LINK = NULL [Assign NULL to LINK field]
Else
5. Set PTR = START [Initialize PTR with START]
6. START = New Node [Create a new node]
7. START-INFO = ITEM [Assign ITEM to INFO field]
8. START-LINK = PTR [Assign PTR to LINK field]
[End of If]
9. Exit
iii. Search an element : Here START is a pointer variable which contains
the address of first node. ITEM is the value to be searched.
1. Set PTR = START, LOC = 1 [Initialize PTR and LOC]
2. Repeat While (PTR != NULL)
3. If (ITEM == PTR - INFO) Then [Check if ITEM matches with
INFO field]
4. Print: ITEM is present at location LOC
5. Return
6. Else
7. PTR = PTR - LINK [Move PTR to next node]
8. LOC = LOC + 1 [Increment LOC]
9. [End of If]
10. [End of While Loop]
11. Print: ITEM is not present in the list
12. Exit
iv. Delete node at specified position : Here START is a pointer variable
which contains the address of first node. PTR is a pointer variable which
contains address of node to be deleted. PREV is a pointer variable which
points to previous node. ITEM is the value to be deleted.
1. If (START == NULL) Then [Check whether list is empty]
2. Print: Linked-List is empty.
3. Else If (START - INFO == ITEM) Then
[Check if ITEM is in 1st node]
4. PTR = START
5. START = START - LINK [START now points to 2nd node]
6. Delete PTR
7. Else
8. PTR = START, PREV = START
9. Repeat While (PTR != NULL)
10. If (PTR - INFO == ITEM) Then
[If ITEM matches with PTR-INFO]
11. PREV - LINK = PTR - LINK [AssignLINK field of PTR to PREV]
12. Delete PTR
13. Else
36.
1–25 A (CS/IT-Sem-3)
DataStructure
14. PREV = PTR [Assign PTR to PREV]
15. PTR = PTR - LINK [Move PTR to next node]
[End of Step 10 If]
[End of While Loop]
16. Print: ITEM deleted
[End of Step 1 If]
17. Exit
v. Deletion at end : Here START is a pointer variable which contains the
address of first node. PTR is a pointer variable which contains address of
node to be deleted. PREV is a pointer variable which points to previous
node. ITEM is the value to be deleted.
1. If (START == NULL) Then [Check whether list is empty]
2. Print: Linked-List is empty.
3. Else
4. PTR = START, PREV = START
5. Repeat While (PTR - LINK != NULL)
6. PREV = PTR [Assign PTR to PREV]
7. PTR = PTR - LINK [Move PTR to next node]
[End of While Loop]
8. ITEM = PTR - INFO [Assign INFO of last node to ITEM]
9. If (START - LINK == NULL) Then
[If only one node is left]
10. START = NULL [Assign NULL to START]
11. Else
9. PREV - LINK = NULL
[Assign NULL to link field of second last node]
[End of Step 9 If]
10. Delete PTR
11. Print : ITEM deleted
[End of Step 1 If]
12. Exit
Que 1.28. Implement linear linked list using pointer for following
functions :
i. Insert at beginning ii. Insert at end
iii. Insert after element iv. Delete at end
v. Delete at beginning vi. Delete after element
vii. Display in reverse order
Answer
#includestdio.h
#includeconio.h
#includeprocess.h
typedef struct simplelink {
int data;
struct simplelink *next;
37.
1–26 A (CS/IT-Sem-3)Array and Linked List
} node;
i. Function to insert at beginning :
node *insert_begin(node *p)
{
node *temp;
temp = (node *)malloc(sizeof(node));
printf(“nEnter the inserted data:”);
scanf(“%d”,temp-data);
temp-next = p;
p = temp;
return(p);
}
ii. Function to insert at end :
node *insert_end(node *p){
node *temp, *q;
q = p;
temp=(node*)malloc(sizeof(node));
printf(“nEnter the inserted data;”);
scanf(“%d”,temp-data);
while(p-next != NULL)
{
p = p-next;
}
p-next = temp;
temp-next = (node *)NULL;
return(q);
}
iii. Function to insert after element:
node *insert_after(node *p) {
node temp, *q;
int x;
q = p;
printf(“nEnter the data(after which you want to enter data):”);
scanf(“%d”,x);
while(p-data != x) {
p = p-next;
}
temp = (node *)malloc(sizeof(node));
printf(“nEnter the inserted data:”);
scanf(“%d”,temp-data);
temp-next = p-next;
p-next = temp;
return (q);
}
iv. Function to delete last node :
node *del end(node *p) {
38.
1–27 A (CS/IT-Sem-3)
DataStructure
node * q, *r;
r = p;
q = p;
if(p-next == NULL)
{
r = (node *)NULL;
}
else
{
while(p-next := NULL)
{
q = p;
p = p-next;
}
q-next = (node *)NULL;
}
free(p);
return(r);
}
v. Function to delete first node :
node *delete_begin(node *p) {
node *q;
q = p;
q = p-next;
free(q);
return(p);
}
vi. Function to delete node after element :
node “delete_after(node, *p)
{
node *temp, *q;
int x;
q = p;
printf(“nEnter the data(after which you want to delete):”);
scanf(“%d” ,x);
while(p-data != x) {
p = p-next;
}
temp = p-next;
p-next = temp-next;
free(temp);
return (q);
}
vii. Function to reverse the list :
node *reverse(node *p) {
node *q, *r;
39.
1–28 A (CS/IT-Sem-3)Array and Linked List
q = (node *)NULL;
while(p != NULL) {
r = q;
q = p;
p = p-next;
p-next = r;
}
return(q);
}
Que 1.29. What are the advantages and disadvantages of single
linked list ?
Answer
Advantages :
1. Linked lists are dynamic data structures as it can grow or shrink during
the execution of a program.
2. The size is not fixed.
3. Data can store non-continuous memory blocks.
4. Insertion and deletion of nodes are easier and efficient. Unlike array a
linked list provides flexibility in inserting a node at any specified position
and a node can be deleted from any position in the linked list.
5. Many more complex applications can be easily carried out with linked
lists.
Disadvantages :
1. More memory : In the linked list, there is a special field called link field
which holds address of the next node, so linked list requires extra space.
2. Accessing to arbitrary data item is complicated and time consuming
task.
Que 1.30. Write an algorithm that reverses order of all the
elements in a singly linked list.
Answer
1. To reverse a linear linked list, three pointer fields are used.
2. These are PREV, PTR, REV which hold the address of previous node,
current node and will maintain the linked list.
Algorithm :
1. PTR = FIRST
2. TPT = NULL
3. Repeat step 4 while PTR != NULL
4. REV = PREV
40.
1–29 A (CS/IT-Sem-3)
DataStructure
1. An array is a list of finite
number of elements of same
data type i.e., integer, real
or string etc.
2. Elements can be accessed
randomly.
3. Array is classified as :
a. 1-D array
b. 2-D array
c. n-D array
4. Each array element is
independent and does not
have a connection with
previous element or with its
location.
5. Array elements cannot be
added, deleted once it is
declared.
6. In array, elements can be
modified easily by
identifying the index value.
7. Pointer cannot be used in
array.
A linked list is a linear collection
of data elements called nodes
which are connected by links.
Elements cannot be accessed
randomly. It can be accessed only
sequentially.
A linked list can be linear, doubly
or circular linked list.
Location or address of element is
stored in the link part of previous
element or node.
The nodes in the linked list can be
added and deleted from the list.
In linked list, modifying the node
is a complex process.
Pointers are used in linked list.
5. PREV = PTR
6. PTR = PTR LINK
7. PREV LINK = REV
[End of while loop]
8. START = PREV
9. Exit
Que 1.31. Write difference between array and linked list.
AKTU 2014-15, Marks 05
Answer
S. No. Array Linked list
Time-Space Trade Off, Abstract Data Types (ADT).
41.
1–30 A (CS/IT-Sem-3)Array and Linked List
Questions-Answers
Long Answer Type and Medium Answer Type Questions
Que 1.32. Explain doubly linked list.
Answer
1. The doubly or two-way linked list uses double set of pointers, one pointing
to the next node and the other pointing to the preceding node.
2. In doubly linked list, all nodes are linked together by multiple links
which help in accessing both the successor and predecessor node for
any arbitrary node within the list.
3. Every node in the doubly linked list has three fields :
LPT INFO RPT
Fig. 1.32.1.
4. LPT will point to the node in the left side (or previous node) i.e., LPT will
hold the address of the previous node, RPT will point to the node in the
right side (or next node) i.e., RPT will hold the address of the next node.
5. INFO field store the information of the node.
6. A doubly linked list can be shown as follows :
LPT RPT
NULL INFO INFO INFO INFO NULL
Fig. 1.32.2. Doubly linked list.
7. The structure defined for doubly linked list is:
struct node
{
int info;
struct node *rpt;
struct node *lpt;
} node;
Que 1.33. What are doubly linked lists ? Write C program to create
doubly linked list. AKTU 2015-16, Marks 10
Answer
Doubly linked list : Refer Q. 1.32, Page 1–30A, Unit-1.
Program :
# includestdio.h
42.
1–31 A (CS/IT-Sem-3)
DataStructure
# includeconio.h
# includealloc.h
struct node
{
int info ;
struct node *lpt ;
struct node *rpt ;
} ;
struct node *first ;
void main ( )
{
create ( ) ;
getch ( ) ;
}
void create ( )
{
struct node *ptr, *cpt ;
char ch ;
ptr = (struct node *) malloc (size of (struct node)) ;
printf (“Input first node information”) ;
scanf (“%d”, ptr info) ;
ptr lpt = NULL ;
first = ptr ;
do
{
cpt = (struct node *) malloc (size of (struct node)) ;
printf (“Input next node information”);
scanf (“%d”, cpt info) ;
ptr rpt = cpt ;
cpt lpt = ptr ;
ptr = cpt ;
printf (“Press Y/N for more node”) ;
ch = getch ( );
}
while (ch == ‘Y’) ;
ptr rpt = NULL ;
}
Que 1.34. Implement doubly linked list using pointer for following
functions :
i. Insert at beginning
ii. Insert at end
iii. Searching an element
iv. Delete at beginning
v. Delete at end
vi. Delete entire list
43.
1–32 A (CS/IT-Sem-3)Array and Linked List
Answer
#includestdio.h
#includeconio.h
typedef struct n{
int data;
struct n *prev;
struct n *next;
}node;
node *head = NULL, *tail = NULL;
i. Function to insert at beginning :
void insert beg(node*h, int d) {
node *temp;
temp = (node *)malloc(sizeof(node));
temp-data = d;
temp-prev = NULL;
if(head == NULL)
{
temp-next = NULL;
head = tail = temp;
return;
}
temp-next = h;
h-prev = temp;
h = h-prev;
head = h;
}
ii. Function to insert at end :
void insert_end(node *t, int d) {
node *temp;
temp = (node*)malloc(sizeof(node));
temp-data = d;
temp-next = NULL;
if(head == NULL) {
temp-prev = NULL;
head = tail = temp;
return;
}
temp-prev = t;
t-next = temp;
t = t-next;
tail = t;
}
iii. Function to search an element :
node *find(node *h, int aft) {
while(h-next != head h-data != aft)
44.
1–33 A (CS/IT-Sem-3)
DataStructure
h = h-next;
if(h-next == head h-data != aft)
return (node*) NULL;
else
return h;
}
iv. Function to delete at beginning :
void delete_beg(node *h, node *t) {
if(head == (node*)NULL) {
printf(“nList is empty.”);
getch( );
return;
}
if(head == tail) {
free(h);
head = tail = (node *)NULL;
return;
}
if(h-next == t) {
tail-prev = NULL;
head = tail;
}
else {
head = head-next;
head-prev = NULL;
}
free(h);
}
v. Function to delete at end :
void delete_end(node *h, node *t) {
if(head == (node *)NULL) {
printf(“nList is empty.”);
getch( );
return;
}
if(head == tail) {
free(h);
head = tail = (node*)NULL;
return;
}
if(t-prev == h) {
head-next = NULL;
tail = head;
}
else {
tail = tail-prev;
tail-next = NULL;
45.
1–34 A (CS/IT-Sem-3)Array and Linked List
}
free(t);
}
void display(node *h) {
while(h != NULL) {
printf(n“/%d”, h-data);
h = h-next;
}
}
vi. Function to delete entire list :
void free_list(node *list) {
node *t;
while(list != NULL) {
t = list;
list = list-next;
free(t);
}
}
Que 1.35. Write algorithm of following operation for doubly linked
list :
i. Traversal
ii. Insertion at beginning
iii. Delete node at specific location
iv. Deletion from end.
OR
Write an algorithm or C code to insert a node in doubly link list in
beginning. AKTU 2014-15, Marks 05
Answer
i. Traversing of two-way linked list :
a. Forward Traversing :
1. PTR FIRST.
2. Repeat step 3 to 4 while PTR != NULL.
3. Process INFO (PTR).
4. PTR RPT (PTR).
5. STOP.
b. Backward Traversing :
1. PTR FIRST.
2. Repeat step (3) while RPT (PTR) != NULL.
3. PTR RPT (PTR)
4. Repeat step (5) to (6) while PTR != NULL.
5. Process INFO (PTR).
6. PTR LPT (PTR).
7. STOP.
46.
1–35 A (CS/IT-Sem-3)
DataStructure
ii. Insertion at beginning :
1. IF PTR = NULL then Write OVERFLOW
Go to Step 9
[END OF IF]
2. SET NEW_NODE = PTR
3. SET PTR = PTR - NEXT
4. SET NEW_NODE - DATA = VAL
5. SET NEW_NODE - PREV = NULL
6. SET NEW_NODE - NEXT = START
7. SET HEAD - PREV = NEW_NODE
8. SET HEAD = NEW_NODE
9. EXIT
iii. Delete node at specific location :
1. IF HEAD = NULL then Write UNDERFLOW
Go to Step 9
[END OF IF]
2. SET TEMP = HEAD
3. Repeat Step 4 while TEMP - DATA != ITEM
4. SET TEMP = TEMP - NEXT
[END OF LOOP]
5. SET PTR = TEMP - NEXT
6. SET TEMP - NEXT = PTR - NEXT
7. SET PTR - NEXT - PREV = TEMP
8. FREE PTR
9. EXIT
iv. Deletion from end :
1. IF HEAD = NULL
Write UNDERFLOW
Go to Step 7
[END OF IF]
2. SET TEMP = HEAD
3. Repeat Step 4 WHILE TEMP - NEXT != NULL
4. SET TEMP = TEMP - NEXT
[END OF LOOP]
5. SET TEMP - PREV - NEXT = NULL
6. FREE TEMP
7. EXIT
Que 1.36. Write a program in C to delete a specific element in
single linked list. Double linked list takes more space than single
linked list for sorting one extra address. Under what condition,
could a double linked list more beneficial than single linked list.
AKTU 2018-19, Marks 07
Answer
Program to delete a specific element from a single linked list :
#include stdio.h
47.
1–36 A (CS/IT-Sem-3)Array and Linked List
#include stdlib.h
// A linked list node
struct Node
{
int data;
struct Node *next;
};
/* Given a reference (pointer to pointer) to the head of a list
and an int, inserts a new node on the front of the list. */
void push(struct Node** head_ref, int new_data)
{
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
new_node-data = new_data;
new_node-next = (*head_ref);
(*head_ref) = new_node;
}
/* Given a reference (pointer to pointer) to the head of a list
and a position, deletes the node at the given position */
void deleteNode(struct Node **head_ref, int position)
{
// If linked list is empty
if (*head_ref == NULL)
return;
// Store head node
struct Node* temp = *head_ref;
// If head needs to be removed
if (position == 0)
{
*head_ref = temp-next; // Change head
free(temp); // free old head
return;
}
// Find previous node of the node to be deleted
for (int i = 0; temp != NULL i position – 1; i++)
temp = temp-next;
// If position is more than number of nodes
if (temp == NULL |
| temp-next == NULL)
return;
// Node temp-next is the node to be deleted
// Store pointer to the next of node to be deleted
struct Node *next = temp-next-next;
// Unlink the node from linked list
free(temp-next); // Free memory
temp-next = next; // Unlink the deleted node from list
}
// This function prints contents of linked list starting from
// the given node
48.
1–37 A (CS/IT-Sem-3)
DataStructure
void printList(struct Node *node)
{
while (node != NULL)
{
printf(“%d ”, node-data);
node = node-next;
}
}
/* Program to test above functions*/
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
push(head, 7);
push(head, 1);
push(head, 3);
push(head, 2);
push(head, 8);
puts(“Created Linked List: ”);
printList(head);
deleteNode(head, 4);
puts(“nLinked List after Deletion at position 4: ”);
printList(head);
return 0;
}
Double linked list is more beneficial than single linked list because :
1. A double linked list can be traversed in both forward and backward
direction.
2. The delete operation in double linked list is more efficient if pointer to
the node to be deleted is given.
3. In double linked list, we can quickly insert a new node before a given
node.
4. In double linked list, we can get the previous node using previous pointer
but in singly liked list we traverse the list to get the previous node.
Circular Linked List.
Questions-Answers
Long Answer Type and Medium Answer Type Questions
49.
1–38 A (CS/IT-Sem-3)Array and Linked List
Que 1.37. What is meant by circular linked list ? Write the
functions to perform the following operations in a doubly linked
list.
a. Creation of list of nodes.
b. Insertion after a specified node.
c. Delete the node at a given position.
d. Sort the list according to descending order
e. Display from the beginning to end.
AKTU 2016-17, Marks 15
Answer
Circular linked list : A circular list is a linear linked list, except that the last
element points to the first element, Fig. 1.37.1 shows a circular linked list
with 4 nodes for non-empty circular linked list, there are no NULL pointers.
start
Fig. 1.37.1.
Functions :
a. To create a list : Refer Q. 1.33, Page 1–30A, Unit-1.
b. To insert after a specific node :
void insert_given_node ( )
{
struct node *ptr, *cpt, *tpt, *rpt, *lpt;
int m;
ptr = (struct node *) malloc (size of (struct node));
if (ptr == NULL)
{
printf (“OVERFLOW”);
return;
}
printf (“input new node information”);
scanf (“%d”, ptr info);
printf (“input node information after which insertion”);
scanf (“%d”, m);
cpt = first;
while (cpt info != m)
cpt = cpt rpt;
tpt = cpt rpt;
cpt rpt = ptr;
To these Iventure to oppose a passage from an old historical ballad:
Go, little page, tell Hardiknute
That lives on hill so high[64],
To draw his sword, the dread of faes,
And haste to follow me.
The little page flew swift as dart
Flung by his master’s arm.
Come down, come down, Lord Hardiknute,
And rid your king from harm.
This rule is also applicable to other fine arts. In painting it is established,
that the principal figure must be put in the strongest light; that the beauty of
attitude consists in placing the nobler parts most in view, and in suppressing
the smaller parts as much as possible; that the folds of the drapery must be
few and large; that foreshortenings are bad, because they make the parts
appear little; and that the muscles ought to be kept as entire as possible,
without being divided into small sections. Every one at present is sensible
of the importance of this rule when applied to gardening, in opposition to
the antiquated taste of parterres split into a thousand small parts in the
strictest regularity of figure. Those who have succeeded best in architecture,
have governed themselves by this rule in all their models.
Another rule chiefly regards the sublime, though it may be applied to
every literary performance intended for amusement; and that is, to avoid as
much as possible abstract and general terms. Such terms, perfectly well
fitted for reasoning and for conveying instruction, serve but imperfectly the
ends of poetry. They stand upon the same footing with mathematical signs,
contrived to express our thoughts in a concise manner. But images, which
are the life of poetry, cannot be raised in any perfection, otherwise than by
introducing particular objects. General terms, that comprehend a number of
individuals, must be excepted from this rule. Our kindred, our clan, our
country, and words of the like import, though they scarce raise any image,
have notwithstanding a wonderful power over our passions. The greatness
of the complex object over-balances the obscurity of the image.
What I have further to say upon this subject, shall be comprehended in a
few observations. A man is capable of being raised so much above his
ordinary pitch by an emotion of grandeur, that it is extremely difficult by a
52.
single thought orexpression to produce that emotion in perfection. The rise
must be gradual and the result of reiterated impressions. The effect of a
single expression can be but momentary; and if one feel suddenly somewhat
like a swelling or exaltation of mind, the emotion vanisheth as soon as felt.
Single expressions, I know, are often justly cited as examples of the
sublime. But then their effect is nothing compared with a grand subject
displayed in its capital parts. I shall give a few examples, that the reader
may judge for himself. In the famous action of Thermopylæ, where
Leonidas the Spartan King with his chosen band fighting for their country,
were cut off to the last man, a saying is reported of Dieneces one of the
band, which, expressing chearful and undisturbed bravery, is well intitled to
the first place in examples of this kind. Talking of the number of their
enemies, it was observed, that the arrows shot by such a multitude would
intercept the light of the sun. So much the better, says he; for we shall then
fight in the shade[65].
Somerset. Ah! Warwick, Warwick, wert thou as we are,
We might recover all our loss again.
The Queen from France hath brought a puissant power,
Ev’n now we heard the news. Ah! couldst thou fly!
Warwick. Why, then I would not fly.
Third part, Henry VI. act 5. sc. 3.
Such a sentiment from a man expiring of his wounds, is truly heroic, and
must elevate the mind to the greatest height that can be done by a single
expression. It will not suffer in a comparison with the famous sentiment
Qu’il mourut in Corneille’s Horace. The latter is a sentiment of indignation
merely, the former of invincible fortitude.
In opposition to these examples, to cite many a sublime passage,
enriched with the finest images, and dressed in the most nervous
expressions, would scarce be fair. I shall produce but one instance from
Shakespear, which sets a few objects before the eye, without much pomp of
language. It works its effect, by representing these objects in a climax,
raising the mind higher and higher till it feel the emotion of grandeur in
perfection.
53.
The cloud-capt tow’rs,the gorgeous palaces,
The solemn temples, the great globe itself,
Yea all which it inherit, shall dissolve, c.
The cloud-capt tow’rs produce an elevating emotion, heightened by the
gorgeous palaces. And the mind is carried still higher and higher by the
images that follow. Successive images, making thus stronger and stronger
impressions, must elevate more than any single image can do.
I proceed to another observation. In the chapter of beauty it is remarked,
that regularity is required in small figures, and order in small groups; but
that in advancing gradually from small to great, regularity and order are less
and less required. This remark serves to explain the extreme delight we
have in viewing the face of nature, when sufficiently enriched and
diversified by objects. The bulk of the objects seen in a natural landscape
are beautiful, and some of them grand. A flowing river, a spreading oak, a
round hill, an extended plain, are delightful; and even a rugged rock or
barren heath, though in themselves disagreeable, contribute by contrast to
the beauty of the whole. Joining to these, the verdure of the fields, the
mixture of light and shade, and the sublime canopy spread over all; it will
not appear wonderful, that so extensive a group of glorious objects should
swell the heart to its utmost bounds, and raise the strongest emotion of
grandeur. The spectator is conscious of an enthusiasm, which cannot bear
confinement nor the strictness of regularity and order. He loves to range at
large; and is so inchanted with shining objects, as to neglect slight beauties
or defects. Thus it is, that the delightful emotion of grandeur, depends little
on order and regularity. And when the emotion is at its height by a survey of
the greatest objects, order and regularity are almost totally disregarded.
The same observation is applicable in some measure to works of art. In a
small building the slightest irregularity is disagreeable. In a magnificent
palace or a large Gothic church, irregularities are less regarded. In an epic
poem we pardon many negligences, which would be intolerable in a sonnet
or epigram. Notwithstanding such exceptions, it may be justly laid down for
a rule, That in all works of art, order and regularity ought to be governing
principles. And hence the observation of Longinus[66], “In works of art we
have regard to exact proportion; in those of nature, to grandeur and
magnificence.”
54.
I shall addbut one other observation, That no means can be more
successfully employed to sink and depress the mind than grandeur or
sublimity. By the artful introduction of an humbling object, the fall is great
in proportion to the former elevation. Of this doctrine Shakespear affords us
a beautiful illustration, in a passage part of which is cited above for another
purpose:
The cloud-capt tow’rs, the gorgeous palaces,
The solemn temples, the great globe itself,
Yea all which it inherit, shall dissolve,
And like the baseless fabric of a vision
Leave not a rack behind——
Tempest, act 4. sc. 4.
The elevation of the mind in the former part of this beautiful passage,
makes the fall great in proportion when the most humbling of all images is
introduced, that of an utter dissolution of the earth and its inhabitants. A
sentiment makes not the same impression in a cool state, that it does when
the mind is warmed; and a depressing or melancholy sentiment makes the
strongest impression, when it brings down the mind from its highest state of
elevation or chearfulness.
This indirect effect of elevation to sink the mind, is sometimes produced
without the intervention of any humbling image. There was occasion above
to remark, that in describing superior beings, the reader’s imagination,
unable to support itself in a strained elevation, falls often as from a height,
and sinks even below its ordinary tone. The following instance comes
luckily in view; for a better illustration cannot be given: “God said, Let
there be light, and there was light.” Longinus cites this passage from Moses
as a shining example of the sublime; and it is scarce possible in fewer
words, to convey so clear an image of the infinite power of the Deity. But
then it belongs to the present subject to remark, that the emotion of
sublimity raised by this image is but momentary; and that the mind, unable
to support itself in an elevation so much above nature, immediately sinks
down into humility and veneration for a being so far exalted above us
groveling mortals. Every one is acquainted with a dispute about this
passage betwixt two French critics[67], the one positively affirming, the
other as positively denying, it to be sublime. What I have opened, shows
55.
that both ofthem have reached the truth, but neither of them the whole
truth. Every one of taste must be sensible, that the primary effect of this
passage is an emotion of grandeur. This so far justifies Boileau. But then
every one of taste must be equally sensible, that the emotion is merely a
flash, which vanisheth instantly, and gives way to the deepest humility and
veneration. This indirect effect of sublimity, justifies Huet on the other
hand, who being a man of true piety, and perhaps of inferior imagination,
felt the humbling passions more sensibly than his antagonist. And even
laying aside any peculiarity of character, Huet’s opinion may I think be
defended as the more solid; upon the following account, that in such
images, the depressing emotions are the more sensibly felt, and have the
longer endurance.
The straining an elevated subject beyond due bounds and beyond the
reach of an ordinary conception, is not a vice so frequent as to require the
correction of criticism. But false sublime is a rock which writers of more
fire than judgement generally split on. And therefore a collection of
examples may be of use as a beacon to future adventurers. One species of
false sublime, known by the name of bon bast, is common among writers of
a mean genius. It is a serious endeavour, by strained description, to raise a
low or familiar subject above its rank; which instead of being sublime,
never fails to be ridiculous. I am extremely sensible how prone the mind is,
in some animating passions, to magnify its objects beyond natural bounds.
But such hyperbolical description has its limits. If carried beyond the
impulse of the propensity, the colouring no longer pleases: it degenerates
into the burlesque. Take the following examples.
Sejanus.———— Great and high
The world knows only two, that’s Rome and I.
My roof receives me not; ’tis air I tread,
And at each step I feel my advanc’d head
Knock out a star in heav’n.
Sejanus, Ben Johnson, act 5.
A writer who has no natural elevation of genius, is extremely apt to deviate
into bombast. He strains above his genius; and the violent effort he makes
carries him generally beyond the bounds of propriety. Boileau expresses
this happily:
56.
L’autre à peurde ramper, il se perd dans la nue[68].
The same author Ben Johnson abounds in the bombast:
—————— The mother,
Th’expulsed Apicata, finds them there;
Whom when she saw lie spread on the degrees,
After a world of fury on herself,
Tearing her hair, defacing of her face,
Beating her breasts and womb, kneeling amaz’d.
Crying to heav’n, then to them; at last
Her drowned voice got up above her woes:
And with such black and bitter execrations,
(As might affright the gods, and force the sun
Run backward to the east; nay, make the old
Deformed Chaos rise again t’ o’erwhelm
Them, us, and all the world) she fills the air,
Upbraids the heavens with their partial dooms,
Defies their tyrannous powers, and demands
What she and those poor innocents have transgress’d,
That they must suffer such a share in vengeance.
Sejanus, act 5. sc. last.
—————— Lentulus, the man,
If all our fire were out, would fetch down new,
Out of the hand of Jove; and rivet him
To Caucasus, should he but frown; and let
His own gaunt eagle fly at him to tire.
Catiline, act 3.
57.
Can these, orsuch, be any aids to us?
Look they as they were built to shake the world,
Or be a moment to our enterprise?
A thousand, such as they are, could not make
One atom of our souls. They should be men
Worth heaven’s fear, that looking up, but thus,
Would make Jove stand upon his guard, and draw
Himself within his thunder; which, amaz’d,
He should discharge in vain, and they unhurt.
Or, if they were, like Capaneus at Thebes,
They should hang dead upon the highest spires,
And ask the second bolt to be thrown down.
Why Lentulus talk you so long? This time
Had been enough t’ have scatter’d all the stars,
T’ have quench’d the sun and moon, and made the world
Despair of day, or any light but ours.
Catiline, act 4.
This is the language of a madman:
Guilford. Give way, and let the gushing torrent come,
Behold the tears we bring to swell the deluge,
Till the flood rise upon the guilty world
And make the ruin common.
Lady Jane Gray, act 4. near the end.
Another species of false sublime, is still more faulty than bombast; and
that is, to force an elevation by introducing imaginary beings without
preserving any propriety in their actions; as if it were lawful to ascribe
every extravagance and inconsistence to beings of the poet’s creation. No
writers are more licentious in this article than Johnson and Dryden.
58.
Methinks I seeDeath and the furies waiting
What we will do, and all the heaven at leisure
For the great spectacle. Draw then your swords:
And if our destiny envy our virtue
The honour of the day, yet let us care
To sell ourselves at such a price, as may
Undo the world to buy us, and make Fate,
While she tempts ours, to fear her own estate.
Catiline, act 5.
—————— The furies stood on hills
Circling the place, and trembled to see men
Do more than they: whilst Piety left the field,
Griev’d for that side, that in so bad a cause
They knew not what a crime their valour was.
The Sun stood still, and was, behind the cloud
The battle made, seen sweating to drive up
His frighted horse, whom still the noise drove backward.
Ibid. act. 5.
59.
Osmyn. While weindulge our common happiness,
He is forgot by whom we all possess,
The brave Almanzor, to whose arms we owe
All that we did, and all that we shall do;
Who like a tempest that outrides the wind,
Made a just battle ere the bodies join’d.
Abdalla. His victories we scarce could keep in view,
Or polish ’em so fast as he rough drew.
Abdemelech. Fate after him below with pain did move,
And Victory could scarce keep pace above.
Death did at length so many slain forget,
And lost the tale, and took ’em by the great.
Conquest of Granada, act. 2. at
beginning.
The gods of Rome fight for ye; loud Fame calls ye,
Pitch’d on the topless Apenine, and blows
To all the under world, all nations,
The seas and unfrequented deserts, where the snow dwells,
Wakens the ruin’d monuments, and there
Where nothing but eternal death and sleep is,
Informs again the dead bones.
Beaumont and Fletcher, Bonduca, act. 3.
sc. 3.
I close with the following observation, That an actor upon the stage may
be guilty of bombast as well as an author in his closet. A certain manner of
acting, which is grand when supported by dignity in the sentiment and force
in the expression, is ridiculous where the sentiment is mean, and the
expression flat.
60.
T
C H AP. V.
M o t i o n a n d F o r c e .
Hat motion is agreeable to the eye without relation to purpose or
design, may appear from the amusement it gives to infants. Juvenile
exercises are relished chiefly upon that account.
If to see a body in motion be agreeable, one will be apt to conclude, that
to see it at rest is disagreeable. But we learn from experience, that this
would be a rash conclusion. Rest is one of those circumstances that are
neither agreeable nor disagreeable. It is viewed with perfect indifferency.
And happy it is for mankind that the matter is so ordered. If rest were
agreeable, it would disincline us to motion, by which all things are
performed. If it were disagreeable, it would be a source of perpetual
uneasiness; for the bulk of the things we see appear to be at rest. A similar
instance of designing wisdom I have had occasion to explain, in opposing
grandeur to littleness, and elevation to lowness of place[69]. Even in the
simplest matters, the finger of God is conspicuous. The happy adjustment of
the internal nature of man to his external circumstances, displayed in the
instances here given, is indeed admirable.
Motion is certainly agreeable in all its varieties of quickness and
slowness. But motion long continued admits some exceptions. That degree
of continued motion which corresponds to the natural course of our
perceptions, is the most agreeable[70]. The quickest motion is for an instant
delightful. But it soon appears to be too rapid. It becomes painful, by
forcibly accelerating the course of our perceptions. Slow continued motion
becomes disagreeable for an opposite reason, that it retards the natural
course of our perceptions.
There are other varieties in motion, beside quickness and slowness, that
make it more or less agreeable. Regular motion is preferred before what is
irregular, witness the motion of the planets in orbits nearly circular. The
motion of the comets in orbits less regular, is less agreeable.
61.
Motion uniformly accelerated,resembling an ascending series of
numbers, is more agreeable than when uniformly retarded. Motion upward
is agreeable by the elevation of the moving body. What then shall we say of
downward motion regularly accelerated by the force of gravity, compared
with upward motion regularly retarded by the same force? Which of these is
the most agreeable? This question is not easily solved.
Motion in a straight line is no doubt agreeable. But we prefer undulating
motion, as of waves, of a flame, of a ship under sail. Such motion is more
free, and also more natural. Hence the beauty of a serpentine river.
The easy and sliding motion of fluids, from the lubricity and incoherence
of their parts, is agreeable upon that account. But the agreeableness chiefly
depends upon the following circumstance, that the motion is perceived, not
as of one body, but as of an endless number moving together with order and
regularity. Poets struck with this beauty, draw more images from fluids than
from solids.
Force is of two kinds; one quiescent, and one exerted by motion. The
former, dead weight for example, must be laid aside; for a body at rest is not
by that circumstance either agreeable or disagreeable. Moving force only
belongs to the present subject; and though it is not separable from motion,
yet by the power of abstraction, either of them may be considered
independent of the other. Both of them are agreeable, because both of them
include activity. It is agreeable to see a thing move: to see it moved, as
when it is dragged or pushed along, is neither agreeable nor disagreeable,
more than when at rest. It is agreeable to see a thing exert force; but it
makes not the thing either agreeable or disagreeable, to see force exerted
upon it.
Though motion and force are each of them agreeable, the impressions
they make are different. This difference, clearly felt, is not easily described.
All we can say is, that the emotion raised by a moving body, resembles its
cause: it feels as if the mind were carried along. The emotion raised by
force exerted, resembles also its cause: it feels as if force were exerted
within the mind.
To illustrate this difference, I give the following examples. It has been
explained why smoke ascending in a calm day, suppose from a cottage in a
wood, is an agreeable object[71]. Landscape-painters are fond of this object,
and introduce it upon all occasions. As the ascent is natural and without
62.
effort, it isdelightful in a calm state of mind. It makes an impression of the
same sort with that of a gently-flowing river, but more agreeable, because
ascent is more to our taste than descent. A fire-work or a jet d’eau rouses
the mind more; because the beauty of force visibly exerted, is superadded to
that of upward motion. To a man reclining indolently upon a bank of
flowers, ascending smoke in a still morning is delightful. But a fire-work or
a jet d’eau rouses him from this supine posture, and puts him in motion.
A jet d’eau makes an impression distinguishable from that of a water-
fall. Downward motion being natural and without effort, tends rather to
quiet the mind than to rouse it. Upward motion, on the contrary,
overcoming the resistance of gravity, makes an impression of a great effort,
and thereby rouses and enlivens the mind.
The public games of the Greeks and Romans, which gave so much
entertainment to the spectators, consisted chiefly in exerting force,
wrestling, leaping, throwing great stones, and such like trials of strength.
When great force is exerted, the effort felt within the mind produces great
life and vivacity. The effort may be such, as in some measure to overpower
the mind. Thus the explosion of gun-powder, the violence of a torrent, the
weight of a mountain, and the crush of an earthquake, create astonishment
rather than pleasure.
No quality nor circumstance contributes more to grandeur than force,
especially as exerted by sensible beings. I cannot make this more evident
than by the following citations.
—————— Him the almighty power
Hurl’d headlong flaming from th’ ethereal sky,
With hideous ruin and combustion, down
To bottomless perdition, there to dwell
In adamantine chains and penal fire,
Who durst defy th’ Omnipotent to arms.
Paradise Lost, book 1.
63.
—————— Now stormingfury rose,
And clamour such as heard in heaven till now
Was never; arms on armour clashing bray’d
Horrible discord, and the madding wheels
Of brazen chariots rag’d; dire was the noise
Of conflict; over head the dismal hiss
Of fiery darts in flaming vollies flew,
And flying vaulted either host with fire.
So under fiery cope together rush’d
Both battles main, with ruinous assault
And inextinguishable rage: all heav’n
Resounded; and had earth been then, all earth
Had to her centre shook.
Ibid, book 6.
64.
They ended parle,and both address’d for fight
Unspeakable; for who, though with the tongue
Of angels, can relate, or to what things
Liken on earth conspicuous, that may lift
Human imagination to such height
Of godlike pow’r? for likest gods they seem’d,
Stood they or mov’d, in stature, motion, arms,
Fit to decide the empire of great Heav’n.
Now wav’d their fiery swords, and in the air
Made horrid circles: two broad suns their shields
Blaz’d opposite, while Expectation stood
In horror: from each hand with speed retir’d,
Where erst was thickest fight, th’ angelic throng,
And left large field, unsafe within the wind
Of such commotion; such as, to set forth
Great things by small, if Nature’s concord broke,
Among the constellations war were sprung,
Two planets, rushing from aspéct malign
Of fiercest opposition, in mid sky,
Should combat, and their jarring spheres confound.
Ibid, book 6.
We shall now consider the effect of motion and force in conjunction. In
contemplating the planetary system, what strikes us the most, is the
spherical figures of the planets and their regular motions. The conception
we have of their activity and enormous bulk is more obscure. The beauty
accordingly of this system, raises a more lively emotion than its grandeur.
But if we could imagine ourselves spectators comprehending the whole
system at one view, the activity and irresistible force of these immense
bodies would fill us with amazement. Nature cannot furnish another scene
so grand.
Motion and force, agreeable in themselves, are also agreeable by their
utility when employed as means to accomplish some beneficial end. Hence
the superior beauty of some machines, where force and motion concur to
perform the work of numberless hands. Hence the beautiful motions, firm
and regular, of a horse trained for war. Every single step is the fittest that
65.
can be forobtaining the end proposed. But the grace of motion is visible
chiefly in man, not only for the reasons mentioned, but also because every
gesture is significant. The power however of agreeable motion is not a
common talent. Every limb of the human body has a good and a bad, an
agreeable and disagreeable action. Some motions are extremely graceful,
others are plain and vulgar: some express dignity, others meanness. But the
pleasure here, arising not singly from the beauty of motion, but from
indicating character and sentiment, belongs to a different chapter[72].
I should conclude with the final cause of the relish we have for motion
and force, were it not so evident as to require no explanation. We are placed
here in such circumstances as to make industry essential to our well-being;
for without industry the plainest necessaries of life are not to be obtained.
When our situation therefore in this world requires activity and a constant
exertion of motion and force, Providence indulgently provides for our
welfare in making these agreeable to us. It would be a blunder in our nature,
to make things disagreeable that we depend on for existence; and even to
make them indifferent, would tend to make us relax greatly from that
degree of activity which is indispensable.
66.
O
C H AP. V I .
N o v e l t y , a n d t h e u n e x p e c t e d
a p p e a r a n c e o f o b j e c t s .
F all the particulars that contribute to raise emotions, not excepting
beauty, or even greatness, novelty hath the most powerful influence. A
new spectacle attracts multitudes. It produceth instantaneously an
emotion which totally occupies the mind, and for a time excludes all other
objects. The soul seems to meet the strange appearance with a certain
elongation of itself; and all is hushed in close contemplation. In some
instances, there is perceived a degree of agony, attended with external
symptoms extremely expressive. Conversation among the vulgar never is
more interesting, than when it runs upon strange objects and extraordinary
events. Men tear themselves from their native country in search of things
rare and new; and curiosity converts into a pleasure, the fatigues, and even
perils of travelling. To what cause shall we ascribe these singular
appearances? The plain account of the matter follows. Curiosity is
implanted in human nature, for a purpose extremely beneficial, that of
acquiring knowledge. New and strange objects, above all others, excite our
curiosity; and its gratification is the emotion above described, known by the
name of wonder. This emotion is distinguished from admiration. Novelty
where-ever found, whether in a quality or action, is the cause of wonder:
admiration is directed upon the operator who performs any thing wonderful.
During infancy, every new object is probably the occasion of wonder, in
some degree; because, during infancy, every object at first is strange as well
as new. But as objects are rendered familiar by custom, we cease by degrees
to wonder at new appearances that have any resemblance to what we are
acquainted with. A thing must be singular as well as new, to excite our
curiosity and to raise our wonder. To save multiplying words, I would be
understood to comprehend both circumstances when I hereafter talk of
novelty.
67.
In an ordinarytrain of perceptions where one thing introduces another,
not a single object makes its appearance unexpectedly[73]. The mind thus
prepared for the reception of its objects, admits them one after another
without perturbation. But when a thing breaks in unexpectedly and without
the preparation of any connection, it raises a singular emotion known by the
name of surprise. This emotion may be produced by the most familiar
object, as when one accidentally meets a friend who was reported to be
dead; or a man in high life, lately a beggar. On the other hand, a new object,
however strange, will not produce this emotion if the spectator be prepared
for the fight. An elephant in India will not surprise a traveller who goes to
see one; and yet its novelty will raise his wonder. An Indian in Britain
would be much surprised to stumble upon an elephant feeding at large in
the open fields; but the creature itself, to which he was accustomed, would
not raise his wonder.
Surprise thus in several respects differs from wonder. Unexpedtedness is
the cause of the former emotion: novelty is the cause of the latter. Nor differ
they less in their nature and circumstances, as will be explained by and by.
With relation to one circumstance they perfectly agree, which is the
shortness of their duration. The instantaneous production of these emotions
in perfection, may contribute to this effect, in conformity to a general law,
That things soon decay which soon come to perfection. The violence of the
emotions may also contribute; for an ardent emotion, which is not
susceptible of increase, cannot have a long course. But their short duration
is occasioned chiefly by that of their causes. We are soon reconciled to an
object, however unexpected; and novelty soon degenerates into familiarity.
Whether these emotions be pleasant or painful, is not a clear point. It
may appear strange, that our own feelings and their capital qualities should
afford any matter for a doubt. But when we are ingrossed by any emotion,
there is no place for speculation; and when sufficiently calm for
speculation, it is not easy to recal the emotion with sufficient accuracy. New
objects are sometimes terrible, sometimes delightful. The terror which a
tyger inspires is greatest at first, and wears off gradually by familiarity. On
the other hand, even women will acknowledge, that it is novelty which
pleases the most in a new fashion. At this rate, it should be thought, that
wonder is not in itself pleasant or painful, but that it assumes either quality
according to circumstances. This doctrine, however plausible, must not pass
without examination. And when we reflect upon the principle of curiosity
68.
and its operations,a glimpse of light gives some faint view of a different
theory. Our curiosity is never more thoroughly gratified, than by new and
singular objects. That very gratification is the emotion of wonder, which
therefore, according to the analogy of nature, ought always to be
pleasant[74]. And indeed it would be a great defect in human nature, were
the gratification of so useful a principle unpleasant. But upon a more strict
scrutiny, we shall not have occasion to mark curiosity as an exception from
the general rule. A new object, it is true, that hath a threatening appearance,
adds to our terror by its novelty. But from this experiment it doth not follow,
that novelty is in itself disagreeable. It is perfectly consistent, that we
should be delighted with an object in one view, and terrified with it in
another. A river in flood swelling over its banks, is a grand and delightful
object; and yet it may produce no small degree of fear when we attempt to
cross it. Courage and magnanimity are agreeable; and yet when we view
these qualities in an enemy, they serve to increase our terror[75]. In the same
manner, novelty has two effects clearly distinguishable from each other. A
new object, by gratifying curiosity, must always be agreeable. It may, at the
same time, have an opposite effect indirectly, which is, to inspire terror. For
when a new object appears in any degree dangerous, our ignorance of its
powers and qualities affords ample scope for the imagination to dress it in
the most frightful colours[76]. Thus the first sight of a lion at some distance,
may at the same instant produce two opposite feelings, the pleasant emotion
of wonder, and the painful passion of terror. The novelty of the object,
produces the former directly, and contributes to the latter indirectly. Thus,
when the subject is analized, we find, that the power which novelty hath
indirectly to inflame terror, is perfectly consistent with its being in every
case agreeable. The matter may be put in a still clearer light by varying the
scene. If a lion be first seen from a place of safety, the spectacle is
altogether agreeable without the least mixture of terror. If again the first
sight put us within reach of this dangerous animal, our terror may be so
great as quite to exclude any sense of novelty. But this fact proves not that
wonder is painful: it proves only that wonder may be excluded by a more
powerful passion. And yet it is this fact, which, in superficial thinking, has
thrown the subject into obscurity. I presume we may now boldly affirm, that
wonder is in every case a pleasant emotion. This is acknowledged as to all
new objects that appear inoffensive. And even as to objects that appear
69.
offensive, I urgethat the same must hold so long as the spectator can attend
to the novelty.
Whether surprise be in itself pleasant or painful, is a question not less
intricate than the former. It is certain, that surprise inflames our joy when
unexpectedly we meet with an old friend: and not less our terror, when we
stumble upon any thing noxious. To clear this point, we must trace it step by
step. And the first thing to be remarked is, that in some instances an
unexpected object overpowers the mind so as to produce a momentary
stupefaction. An unexpected object, not less than one that is new, is apt to
sound an alarm and to raise terror. Man, naturally a defenceless being, is
happily so constituted as to apprehend danger in all doubtful cases.
Accordingly, where the object is dangerous, or appears so, the sudden alarm
it gives, without preparation, is apt totally to unhinge the mind, and for a
moment to suspend all the faculties, even thought itself[77]. In this state a
man is quite helpless; and if he move at all, is as likely to run upon the
danger as from it. Surprise carried to this height, cannot be either pleasant
or painful; because the mind, during such momentary stupefaction, is in a
good measure, if not totally, insensible.
If we then inquire for the character of this emotion, it must be where the
unexpected object or event produceth less violent effects. And while the
mind remains sensible of pleasure and pain, is it not natural to suppose, that
surprise, like wonder, should have an invariable character? I am inclined
however to think, that surprise has no invariable character, but assumes that
of the object which raises it. Wonder is the gratification of a natural
principle, and upon that account must be pleasant. There, novelty is the
capital circumstance, which, for a time, is intitled to possess the mind
entirely in one unvaried tone. The unexpected appearance of an object,
seems not equally intitled to produce an emotion distinguishable from the
emotion, pleasant or painful, that is produced by the object in its ordinary
appearance. It ought not naturally to have any effect, other than to swell that
emotion, by making it more pleasant or more painful than it commonly is.
And this conjecture is confirmed by experience, as well as by language,
which is built upon experience. When a man meets a friend unexpectedly,
he is said to be agreeably surprised; and when he meets an enemy
unexpectedly, he is said to be disagreeably surprised. It appears then, that
the sole effect of surprise is to swell the emotion raised by the object. And
this effect can be clearly explained. A tide of connected perceptions, glides
70.
gently into themind, and produceth no perturbation. An object on the other
hand breaking in unexpectedly, sounds an alarm, rouses the mind out of its
calm state, and directs its whole attention upon the object, which, if
agreeable, becomes doubly so. Several circumstances concur to produce
this effect. On the one hand, the agitation of the mind and its keen attention,
prepare it in the most effectual manner for receiving a deep impression. On
the other hand, the object by its sudden and unforeseen appearance, makes
an impression, not gradually as expected objects do, but as at one stroke
with its whole force. The circumstances are precisely similar, where the
object is in itself disagreeable.
The pleasure of novelty is easily distinguished from that of variety. To
produce the latter, a plurality of objects is necessary. The former arises from
a circumstance found in a single object. Again, where objects, whether
coexistent or in succession, are sufficiently diversified, the pleasure of
variety is complete, though every single object of the train be familiar. But
the pleasure of novelty, directly opposite to familiarity, requires no
diversification.
There are different degrees of novelty, and its effects are in proportion.
The lowest degree is found in objects that are surveyed a second time after
a long interval. That in this case an object takes on some appearance of
novelty, is certain from experience. A large building of many parts variously
adorned, or an extensive field embellished with trees, lakes, temples,
statues, and other ornaments, will appear new oftener than once. The
memory of an object so complex is soon lost; of its parts at least, or of their
arrangement. But experience teaches, that even without any decay of
remembrance, absence alone will give an air of novelty to a once familiar
object; which is not surprising, because familiarity wears off gradually by
absence. Thus a person with whom we have been intimate, returning after a
long interval, appears like a new acquaintance. Distance of place
contributes to this appearance, not less than distance of time. A friend after
a short absence in a remote country, has the same air of novelty as if he had
returned after a longer interval from a place nearer home. The mind forms a
connection betwixt him and the remote country, and bestows upon him the
singularity of the objects he has seen. When two things equally new and
singular are presented, the spectator balances betwixt them. But when told
that one of them is the product of a distant quarter of the world, he no
longer hesitates, but clings to this as the more singular. Hence the
71.
Welcome to ourwebsite – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!
ebooknice.com