B.SC - C & DS 2023 Final
B.SC - C & DS 2023 Final
UNIT-II
Linked List: Concept of Linked Lists, Representation of linked lists in Memory, Comparison between Linked List
and Array, Types of Linked Lists - Singly Linked list, Doubly Linked list, Circularly Singly Linked list, Circularly
Doubly Linked list; Implementation of Linked List ADT: Creating a List, Traversing a linked list, Searching
linkedlist, Insertion and deletion into linked list (At first Node, Specified Position, Last node), Application of
linked lists
UNIT-III
Stacks: Introduction to stack ADT, Representation of stacks with array and Linked List, Implementation of
stacks, Application of stacks - Polish Notations - Converting Infix to Post Fix Notation - Evaluation of Post Fix
Notation - Tower of Hanoi, Recursion: Concept and Comparison between recursion and Iteration Queues:
Introduction to Queue ADT, Representation of Queues with array and Linked List, Implementation of Queues,
Application of Queues Types of Queues- Circular Queues, De-queues, Priority Queue
UNIT-IV
Searching: Linear or Sequential Search, Binary Search and Indexed Sequential Search Sorting: Selection Sort,
Bubble Sort, Insertion Sort, Quick Sort and Merge Sort
UNIT-V
Binary Trees: Concept of Non- Linear Data Structures, Introduction Binary Trees, Types of Trees, Basic
Definition of Binary Trees, Properties of Binary Trees, Representation of Binary Trees, Operations on a Binary
Search Tree, Binary Tree Traversal, Applications of Binary Tree. Graphs: Introduction to Graphs, Terms
Associated with Graphs, Sequential Representation of Graphs, Linked Representation of Graphs, Traversal of
Graphs (DFS, BFS), Application of Graphs.
BOOKS:
1. “Data Structures using C”, ISRD group Second Edition, TMH
2. “Data Structures through C”, Yashavant Kanetkar, BPB Publications
3. “Data Structures Using C” Balagurusamy E. TMH
1 B.Sc(cs)
UNIT – I
Introduction to Data Structures : Data Structure is a way of organizing the data, not only stored
items and also stores its relationship. (or) A data may be organized in many ways such as the Logical
(or) mathematical representation of given data is called as "data structure". (or) The method to store
the information and computes the memory is collectively known as Data structure. Data Structure can
be defined as the group of data elements which provides an efficient way of storing and organising
data in the computer, so that it can be used efficiently. Some examples of Data Structures are arrays,
Linked List, Stack, Queue, etc. Data Structure plays a very important role in various algorithms, it
allows the programmer to handle the data efficiently.
NEED OF THE DATA STRUCTURE :
1. A data structure helps us to understand the relationship of one data element With other.
2. Data structure helps us to analyze the data in a logical or mathematical manner.
3. Data structure helps us to store the data and organize in logical or mathematical manner
4. Modern day computing problems are complex and large. So, there is a need to handle large
amount of data which is overcome using data structure.
5. The collecting of data and link dynamically over time is organized by using various efficient
algorithms in data structure.
OPERATIONS ON DATA STRUCTURES
Traversing: It means to access each data item exactly once so that it can be processed. For example,
to print the names of all the students in a class.
Searching : It is used to find the location of one or more data items that satisfy the given constraint.
Such a data item may or may not be present in the given collection of data items. For example, to find
the names of all the students who secured 100 marks in Computers.
Inserting: It is used to add new data items to the given list of data items. For example, to add the
details of a new student who has recently joined the course.
Deleting:It means to remove (delete) a particular data item from the given collection of data items.
For example, to delete the name of a student who has left the course.
Sorting:Data items can be arranged in some order like ascending order or descending order
depending on the type of application. For example, arranging the names of students in a class in an
alphabetical order.
Merging: Lists of two sorted data items can be combined to form a single list of sorted data items.
2 B.Sc(cs)
ADVANTAGES OF DATA STRUCTURES: We need data structures because there are several advantages
of using them, few of them are as follows:
1. Data Organization: We need a proper way of organizing the data so that it can accessed efficiently
when we need that particular data. DS provides different ways of data organization so we have
options to store the data in different data structures based on the requirement.
2. Efficiency The main reason we organize the data is to improve the efficiency. We can store the data
in arrays then why do we need linked lists and other data structures? because when we need to
perform several operation such as add, delete update and search on arrays , it takes more time in
arrays than some of the other data structures. So the fact that we are interested in other data
structures is because of the efficiency.
3. Reusability Data structure can be reused. Once we have implemented a data structure, the same
data structure can be used later.
4. Abstraction Data structure hides (abstracts) the implementation details from the user. The user
access the data through an interface and enjoys the benefits of data structures, the important
complex implementation details are hidden from the user.
Data Representation:
Data Representation refers to the form in which data is stored, processed, and transmitted. Devices
such as smart phones, iPods, and computers store data in digital formats. Digitization is the process of
converting information, such as text, numbers, photo, or music, into digital data that can be
manipulated by electronic devices. The 0s and 1s used to represent digital data are referred to as
binary digits — from this term we get the word bit that stands for binary digit. A bit is a 0 or 1 used in
the digital representation of data.
Representing Numbers Numeric data consists of numbers that can be used in arithmetic operations.
Digital devices represent numeric data using the binary number system, also called base 2. The binary
number system only has two digits: 0 and 1. No numeral like 2 exists in the system, so the number
“two” is represented in binary as 10 (pronounced “one zero”).
3 B.Sc(cs)
Representing Text Character data is composed of letters, symbols, and numerals that are not used in
calculations. Examples of character data include your name, address, and hair colour. Character data
is commonly referred to as “text.”Digital devices employ several types of codes to represent
character data, including ASCII, Unicode, and their variants. ASCII (American Standard Code for
Information Interchange, pronounced “ASK ee”) requires seven bits for each character. The ASCII
code for an uppercase A is 1000001.
: Abstract Datatypes:
The abstract datatype is special kind of datatype, whose behaviour is defined by a set of
values and set of operations. The word ‘abstract’ in the context of data structures means considered
apart from the detailed specifications or implementation. The keyword “Abstract” is used as we can
use these datatypes, we can perform different operations. But how those operations are working that
is totally hidden from the user. The ADT is made of with primitive datatypes, but operation logics are
hidden. It does not specify how data will be organized in memory and what algorithms will be used
for implementing the operations.
For example, when we use a stack or a queue, the user is concerned only with the type of data
and the operations that can be performed on it. Therefore, the fundamentals of how the data is
stored should be invisible to the user.
For example, if you want to add a new field to a student’s record to keep track of more information
about each student, then it will be better to replace an array with a linked structure to improve the
program’s efficiency. In such a scenario, rewriting every procedure that uses the changed structure is
not desirable. Therefore, a better alternative is to separate the use of a data structure from the
details of its implementation. This is the principle underlying the use of abstract data types.
DATA TYPE
A data type is a set of data values having predefined characteristics. You will have encountered data
types during computer programming. In sense, it describes which type of data is stored in the
variable. Ex: integer, float, character and Boolean. Generally in all programming languages we have a
limited number of such data types. The range of values that can be stored in each of these data types
is defined by the languages and the computer hardware that the high level language is used.
4 B.Sc(cs)
Data types can be broken up to two types
I. Scalar or primitive data types
II. Structured or non- primitive data types.
I. Scalar or primitive data type A simple (scalar) data type consists of a collection of or ordered values
and set of operations that can be performed on those values. The C,C++, and Java programming
languages refers to scalar types primitive data types. A scalar variable can hold only one piece of data
at a time. So in C, C++ , and java scalar data type include int , char , float, and double , along with
others. Scalar variable of the same type can be arranged into ascending or descending order based on
the value.
A. Integer Types Integer types can hold whole numbers as 286,-32…. The size of the values that can
be stored depends on the integer data type. Java supports four types of integer as shown below.
These can be positive or negative.
Integer
-
Long 8 9,223,372,036,854,775,8 9,223,372,036,854,775,80
08 8
Floating point types can hold numbers containing fractional parts such as 7.5, 9.04, etc..
Floating point
C. Character type Java provide a character data type called char to store character constants .The
char type assumes a size of 2 bytes but it can hold only a single characters.
D. Boolean type Boolean type is used when we want to test a particular condition during the
execution of the program. There are only 2 values that Boolean type can take: true or false. Only one
bit is required to store Boolean values.
5 B.Sc(cs)
II. Structured or non- primitive data types :Non - primitive data types hold a collection of data values.
This collection will generally consists of the primitive data types. Example of this would include
ARRAYS, RECORDS (STRUCTURES), CLASSES AND FILES. These data types, which are created by
programmers, are extremely important and are the building block of data structures. Non-primitive
data types in java languages are arrays, classes, interface etc. These are also examples of reference
data types.
Primitive Data Structures are the basic data structures that directly operate upon the machine
instructions.
Non-primitive data structures are more complicated data structures and are derived from primitive
data structures.
Linear Data Structures: A data structure is called linear if all of its elements are arranged in the linear
order. In linear data structures, the elements are stored in non-hierarchical way.
Arrays: An array is a collection of similar type of data items and each data item is called an element of
the array. The data type of the element may be any valid data type like char, int, float or double.
Linked List: Linked list is a linear data structure which is used to maintain a list in the memory.
Stack: Stack is a linear list in which insertion and deletions are allowed only at one end, called top.
6 B.Sc(cs)
Queue: Queue is a linear list in which elements can be inserted only at one end called rear and
deleted only at the other end called front.
Non Linear Data Structures: This data structure does not form a sequence i.e. each item or element is
connected with two or more other items in a non-linear arrangement. The data elements are not
arranged in sequential structure.
Trees: Trees are multilevel data structures with a hierarchical relationship among its elements known
as nodes.
Graphs: Graphs can be defined as the pictorial representation of the set of elements (represented by
vertices) connected by the links known as edges.
Atomic Type
Generally, a data structure is represented by a memory block, which has two parts:
1.Data storage
2.Address storage
This facilitates in storing the data and relating it to some other data by means of storing pointers in
the address part.
An atomic type data is a data structure that contains only the data items and not the pointers. Thus,
for a list of data items, several atomic type nodes may exist each with a single data item
corresponding to one of the legal data types. The list is maintained using a list node which contains
pointers to these atomic nodes and a type indicator indicating the type of atomic node to which it
points. Whenever a test node is inserted in the list, its address is stored in the next free element of
the list of pointers.
Difference between Abstract Data types, Data types and Data Structures
To avoid the confusion between abstract data types, data types and data structures, it is relevant to
understand the relationship between the three.
7 B.Sc(cs)
An abstract data type is the specification of the data type which specifies the logical and
mathematical model of the data type.
Data structure refers to the collection of computer variables that are connected in some
specific manner.
Thus, there seems to be an open relationship between the three, i.e., a data type has its root in
the abstract data type and a data structure comprises a set of computer variables of some or
different data types.
Refinement Stages:
The best approach to solve a complex problem is to divide it into smaller parts such that each part
becomes an independent module which is easy to manage. An example of this approach is the System
Development Life Cycle (SDLC) methodology. This helps in understanding the problem, analyzing
solutions, and handling the problems efficiently.
The principle underlying writing large programs is the top-down refinement. While writing the
main program, we decide exactly how the work will be divided into various functions and then in the
refinement process, it is further decided what will be the task of each function, and what inputs are
to be given and results to be obtained. The data and actions of the functions are specified precisely.
The applications or the nature of problem determines the number of refinement stages
required in the specification process. Different problems have different number of refinement stages,
but in general, there are four levels of refinement processes:
Application level
Conceptual Level
At this level we decide how the data is related to each other, and what operations are needed. Details
about how to store data and how various operations are performed on that data are not decided at
this level.
At data structure level we decide about the operations on the data as needed by our problem.
At implementation level, we decide the details of how the data structures will be represented in the
computer memory.
8 B.Sc(cs)
Application Level
This level determines all details required for particular application such as names for variables or
special requirements for the operations imposed by applications.
Software Engineering is the theory and practice of methods helpful for the construction and
maintenance of large software systems. Development of a good software is a complicated process
which continues for long time before the software or program takes the final shape and is put into
use. There are many stages in software development cycle. The process is often referred to as
Software Development Life Cycle (SDLC). In SDLC, the output from one stage becomes the input to
the next stage.
In the simplified version, the software development life cycle may contain requirement analysis,
design, implementation and maintenance phases which are implemented in sequence over a period
of time.
2. Build a prototype and experiment with it until all specifications are finalized.
9 B.Sc(cs)
8. Refine and repeat the foregoing steps until the software is complete.
10. Maintain the program so that it meets the changing needs of its users.
Program Design
Program design can be considered as an important phase of the software development life cycle. In
this phase that the algorithms and data structures to solve a problem are proposed. Some of the
various points that can help us to evaluate the proposed program designs are as follows:
As the design stage involves taking the specification and designing solutions to the problems,
the designer needs to adopt a design strategy. The strategy adopted while designing should be
according to the given specifications.
Another important point which should be kept in mind while developing a solution strategy is
that it should work correctly in all conditions.
Generally, the people who use the system are not aware of program design you have adopted.
thus, there is a system manual which is a detailed guide to how the design was achieved. In
addition a user manual serves as a reference for the users who are not familiar with the
system or machines.
A large program should be divided into small modules and submodules by following one of the
two decomposition approaches-top down approach or bottom-up approach.
Othe important criteria by which a program can be judged are execution time and storage
requirement.
Algorithms
The term ‘algorithm’ refers to the sequence of instructions that must be followed to solve a problem.
In other words, an algorithm is a logical representation of the instructions which should be executed
to perform a meaningful task.
Each instruction should be relative in nature and should not be repeated infinitely.
The result should be available to the user after the algorithm terminates.
10 B.Sc(cs)
Thus, an algorithm is any well defined computational procedure, along with a specified set of
allowable inputs, that produce some value or set of values as output.
After an algorithm has been designed, its efficiency must be analyzed. This involves determining
whether the algorithm is economical in the use of computer resources i.e., CPU time and memory.
The importance of efficiency of an algorithm is in the correctness- i.e., does it always produce the
correct result.
A complex system may be divided into smaller units called modules. Modularity enhances design
clarity, which in turn eases implementation, debugging, testing, documenting, and maintenance of
the product. A system consists of components. Indeed a system is a hierarchy of components. The
highest level component corresponds to the total system. To design such a hierarchy there are two
possible approaches:
1. Top-down approach
2. Bottom-up approach
Top-down Approach
A top-down approach starts by identifying the major components of the system or program,
decomposing them into their lower-level components and iterating until the desired level of module
complexity is achieved.
Top-down design method takes the form of stepwise refinement. Thus, in top-down approach
we start from an abstract design. In each step, design is refined into most concrete level until we
reach the level where no more refinement is needed and the design can be implemented directly.
Stepwise refinement is “top-down” method for decomposing a system from high level specifications
into more elementary levels. The top-down approach, however is often useful way to better
document a design.
Bottom-Up Approach
A bottom-up design approach starts with designing the most basic or primitive components and
proceeds to higher-level components. Bottom-up method works with layers of abstraction. Starting
from the very bottom, the operations that provide a layer of abstraction are implemented. Bottom-up
approach follows information hiding.
The design activity should not be constrained to proceed according to a fixed pattern but
should be a blend of top-down and bottom-up approaches.
Complexity
11 B.Sc(cs)
When we talk of complexity in context of computers, we call it as computational complexity.
Computational complexity is a characterization of the time or space requirements for solving a
problem by a particular algorithm. These requirements are expressed in terms of a single parameter
that represents the size of the problem.
1. Time complexity
2. Space complexity
1. Time Complexity: The time complexity of a program / algorithm is the amount of computer time
that it needs to run to completion. While measuring the time complexity of an algorithm, we
concentrate on developing only the frequency count for all key statements. This is because, it is often
difficult to get reliable timing figure because of clock limitations and the multiprogramming or the
sharing environment.
1. Algorithm A a=a+1
2. Algorithm B for x=1 to n step 1
a=a+1
loop
In the algorithm A we may find that the statement a=a+1 is independent and is not contained within
any loop. Therefore, the number of times this shall be executed is 1. We can say that the frequency
count of algorithm A is 1.
In the second algorithm, i.e., B, the key statement out of three statements is the assignment
operation a=a+1. Because this statement is contained within a loop, the number of times it is
executed is n, as the loop runs for n times. The frequency count for this algorithm is n.
2.Space Complexity: The space complexity of a program / algorithm is the amount of memory that it
needs to run to completion. The space needed by the program is the sum of the following
components:
Fixed space requirements: This includes the instructions space, for simple variables, fixed size
structured variables, and constants.
Variable space requirements: This consists of space needed by structured variables whose size
depends on particular instance of variables. It also includes the additional space required when the
function uses recursion.
Asymptotic Analysis
As we know that data structure is a way of organizing the data efficiently and that efficiency is
measured either in terms of time or space. So, the ideal data structure is a structure that occupies the
least possible time to perform all its operation and the memory space. Our focus would be on finding
12 B.Sc(cs)
the time complexity rather than space complexity, and by finding the time complexity, we can decide
which data structure is the best for an algorithm.
The main question arises in our mind that on what basis should we compare the time complexity of
data structures?. The time complexity can be compared based on operations performed on them.
Let's consider a simple example.
Suppose we have an array of 100 elements, and we want to insert a new element at the beginning of
the array. This becomes a very tedious task as we first need to shift the elements towards the right,
and we will add new element at the starting of the array.
Suppose we consider the linked list as a data structure to add the element at the beginning. The
linked list contains two parts, i.e., data and address of the next node. We simply add the address of
the first node in the new node, and head pointer will now point to the newly added node. Therefore,
we conclude that adding the data at the beginning of the linked list is faster than the arrays. In this
way, we can compare the data structures and select the best possible data structure for performing
the operations.
It is used to mathematically calculate the running time of any operation inside an algorithm.
Example: Running time of one operation is x(n) and for another operation, it is calculated as f(n2). It
refers to running time will increase linearly with an increase in 'n' for the first operation, and running
time will increase exponentially for the second operation. Similarly, the running time of both
operations will be the same if n is significantly small.
Worst case: It defines the input for which the algorithm takes a huge time.
Best case: It defines the input for which the algorithm takes the lowest time
Asymptotic Notations
The commonly used asymptotic notations used for calculating the running time complexity of an
algorithm is given below:
13 B.Sc(cs)
constant time g(n). n is the parameter which characterizes the inputs and/ or outputs. For ex: n might
be the number of inputs or the number of outputs or their sum or the magnitude of one of them.
For example:
If f(n) and g(n) are the two functions defined for positive integers,
then f(n) = O(g(n)) as f(n) is big oh of g(n) or f(n) is on the order of g(n)) if there exists constants c
and no such that:
This implies that f(n) does not grow faster than g(n), or g(n) is an upper bound on the function
f(n). In this case, we are calculating the growth rate of the function which eventually calculates
the worst time complexity of a function, i.e., how worst an algorithm can perform.
14 B.Sc(cs)
Omega Notation (Ω)
o It basically describes the best-case scenario which is opposite to the big o notation.
o It is the formal way to represent the lower bound of an algorithm's running time. It measures
the best amount of time an algorithm can possibly take to complete or the best-case time
complexity.
o It determines what the fastest time that an algorithm can run is.
If we required that an algorithm takes at least certain amount of time without using an upper bound,
we use big- Ω notation i.e. the Greek letter "omega". It is used to bound the growth of running time
for large input size.
If f(n) and g(n) are the two functions defined for positive integers,
then f(n) = Ω (g(n)) as f(n) is Omega of g(n) or f(n) is on the order of g(n)) if there exists constants c
and no such that:
As we can see in the above figure that g(n) function is the lower bound of the f(n) function when the
value of c is equal to 1. Therefore, this notation gives the fastest running time. But, we are not more
interested in finding the fastest running time, we are interested in calculating the worst-case
15 B.Sc(cs)
scenarios because we want to check our algorithm for larger input that what is the worst time that it
will take so that we can take further decision in the further process.
As c1.g(n) should be less than f(n) so c1 has to be 1 whereas c2.g(n) should be greater than f(n) so c2
is equal to 5. The c1.g(n) is the lower limit of the of the f(n) while c2.g(n) is the upper limit of the f(n).
c1.g(n)<=f(n)<=c2.g(n)
Replace g(n) by n and f(n) by 2n+3
c1.n <=2n+3<=c2.n
if c1=1, c2=2, n=1
1*1 <=2*1+3 <=2*1
1 <= 5 <= 2 // for n=1, it satisfies the condition c1.g(n)<=f(n)<=c2.g(n)
If n=2
1*2<=2*2+3<=2*2
2<=7<=4 // for n=2, it satisfies the condition c1.g(n)<=f(n)<=c2.g(n)
16 B.Sc(cs)
Therefore, we can say that for any value of n, it satisfies the condition c1.g(n)<=f(n)<=c2.g(n). Hence,
it is proved that f(n) is big theta of g(n). So, this is the average-case scenario which provides the
realistic time complexity.
Some of the control structures which can be used for structured programming are as follows:
Structured Programming emphasises functional specialization and tries to ensure that only one
primary function is allocated to any module.
Recursion:
A recursive routine is one whose design includes a call to itself. In design phase of software
development we use various problem solving methods in which recursion can be one of the powerful
tools.
A common example which can explain the concept of recursion is to find out the factorial of any
number.
A ‘C’ function declaration for factorial is:
Factorial(a)
17 B.Sc(cs)
Int a:
{
Int fact=1
If(a>1)
Fact=a*Factorial(a-1); /* recursive function call*/
Return(fact);
}
A program in any language is a collection of one or more functions. Every function is a collection of
statements which performs a specific task. For example, a program written in ‘C’ can have the
following format:
Comments
Preprocessor directives
Global_variables
Main()
{
Local variables
Statements
--------------
--------------
Func1()
{
Local variables
Statements
-----------
-----------
}
Func2()
{
Local variables
Statements
-------------
-------------
}
A program starts with comments enclosed between /* and */. Comments can be given anywhere in
the program.
The pre-processor directives are executed before C program code passes through the compiler. These
pre-processor directives make programs more efficient. Most commonly used directives are #include
which includes files, # define which defines the macro name and macro expansion.
Then there are declarations for global variables, which have same data type and same name
throughput the function and are defined outside the main() function. But the declaration of too many
global variables is not advisable. To make the program more efficient constants are used.
‘C’ program contains the main() function but a program should be divided into functions. A function is
a self-contained subprogram which performs some specific, well defined task.
18 B.Sc(cs)
ARRAYS
we have seen different types of variables which holds only one value. There are many applications
which require to process a group of data item that are of same type such as int, float, char,double.
“An array is a collection of variables of the same type , referred to by a common name ,items stored
at contiguous memory locations .
We can define an array to represent set of 5 elements . A particular value is indicated by writing a
number called index number or subscript in square brockets after an array name. The individual
values of an array referred as elements of array.
Eg: salary [5] => represents 5 employee salary.
Array Operations :
Traverse − print all the array elements one by one.
Insertion − Adds an element at the given index.
Deletion − Deletes an element at the given index.
Search − Searches an element using the given index or by the value.
Update − Updates an element at the given index.
Arrays are generally categorized into following types
1. One-dimensional arrays
2. Two-dimensional arrays
3. Multi dimensional arrays
1. One-dimensional arrays:”A list of items can be given one variable name using only one subscript
and such a variable called single-subscripted variable or a one-dimensional array”. It represents only
one row or column of elements.
Here datatype may be int, float, or char and size indicates the maximum number of elements that
can be stored inside the array.
Eg: int marks[10]
19 B.Sc(cs)
In above example, declares the marks to be an array containing 10 real elements.
Initialization of values into one dimensional array:-
We can assign the values into one dimensional array at the time of
declaration of an array or after the declaration of array.
Example : int a[5];
a[0]=1, a[1]=2 , a[2]=4, a[3]=8, a[4]=16;
OR
int a[5]={ 1,2,4,8,16};
2. Two Dimensional Array :- A list of items can be given to one variable name using two subscripts
and such a variable is called a two subscripted variable or two dimensional array..
type – data type, variable_name – name of the array, row_size – no of rows, column_size – no of
columns of an array.
Example:-
Int a[3][3];
3. Three Dimensional Array :- A list of items can be given to one variable name using more than two
subscripts and such a variable is called a three dimensional array..
Declaration :-
type variable _name[s1][s2]… [sn];
Example:-
20 B.Sc(cs)
Int a[2][2][2];
Unit – II
LINKED LISTS
LINKED LISTS
A linked list or one way list is a liner collection of data elements, called nodes where the linear
order is given by means of references. That is each node is divided into to parts the first part
contains the information of the element and the second part called the link field or next reference
field, contains the address of the next node in the list.
Node
The reference of the last node contains a special value called “NULL” reference denoted
by “ X ” in the diagram signals the end of the list. The linked list also contains a pointer variable
called “START” which refer to the first or head node in the list .
A special case is the list that has no nodes, such list is called the “NULL” list or empty list
and is denoted by null reference in the start variable.
21 B.Sc(cs)
Advantages of linked lists
1) The primary advantage of linked list over arrays is that linked list can increase and
decrease in size. That means their maximum size need not be mentioned inadvance. This
is a very good advantage in practicalapplications.
2) The second advantage of linked list is the flexibility in allowing the items to the
rearranged efficiently. This flexibility is gained at the experience of quick access toany
item inthis.
3) The insertion and deletion of an element takes one time. Unlike array implementationin
which they taken-times.
1.Singly linkedlist
Here in this type of list the node has only one reference variable apart from the
information part which always refers to the next node. In singly linked list we can perform
only forward traversing. This type of lists is also known as one way list.
2. Doubly linkedlist
These types of lists are also known as two way list, which can be traversed in two
directions forward and backward directions. A two list is a collection of data elements
called nodes where each node is divided into three parts
a. An information field INFO which contains thedata
b. A reference field “NEXT” which contains the location of the next node in thelist.
c. A reference field “PREV” which contains the location of the preceding node in the
list
22 B.Sc(cs)
4. Circularly doubly linkedlist:
In a double linked list, the end node refer back to the header node and the header node
refers tothe end node, it forms a circle then it is called as Circular Double linked list.
Linked
ListRepresentation:
Linked list can be visualized as a chain of nodes, where every node points to the next node.
As per the above illustration, following are the important points to be considered.
Linked List contains a link element called first.
Each link carries a data field(s) and a link field called next.
Each link is linked with its next link using its next link.
Last link carries a link as null to mark the end of the list.
Basic Operations:
Following are the basic operations supported by a list.
Insertion − Adds an element in the list.
Deletion − Deletes an element in the list.
Display − Displays the complete list.
Insertion Operation
Adding a new node in linked list is a more than one step activity. We shall learn this with
diagrams here. First, create a node using the same structure and find the location where it has to be
inserted.
23 B.Sc(cs)
Imagine that we are inserting a node B (NewNode), between A (LeftNode) and C (RightNode). Then
point B.next to C − NewNode.next −> RightNode; It should look like this −
Now, the next node at the left should point to the new node.
LeftNode.next −> NewNode;
This will put the new node in the middle of the two. The new list should look like this −
Similar steps should be taken if the node is being inserted at the beginning of the list. While inserting
it at the end, the second last node of the list should point to the new node and the new node will
point to NULL.
Deletion Operation
Deletion is also a more than one step process. We shall learn with pictorial representation. First,
locate the target node to be removed, by using searching algorithms.
24 B.Sc(cs)
The left (previous) node of the target node now should point to the next node of the target node −
LeftNode.next −> TargetNode.next;
This will remove the link that was pointing to the target node. Now, using the following code, we will
remove what the target node is pointing at.
TargetNode.next −> NULL;
We need to use the deleted node. We can keep that in memory otherwise we can simply deallocate
memory and wipe off the target node completely.
As per the above illustration, following are the important points to be considered.
Doubly Linked List contains a link element called first and last.
Each link carries a data field(s) and two link fields called next and prev.
25 B.Sc(cs)
Each link is linked with its next link using its next link.
Each link is linked with its previous link using its previous link.
The last link carries a link as null to mark the end of the list.
Basic Operations:
Insertion − Adds an element at the beginning of the list.
Deletion − Deletes an element at the beginning of the list.
Insert Last − Adds an element at the end of the list.
Delete Last − Deletes an element from the end of the list.
Insert After − Adds an element after an item of the list.
Delete − Deletes an element from the list using the key.
Insertion Operation
Following code demonstrates the insertion operation at the beginning of a doubly linked list.
Example
//insert link at the first location
void insertFirst(int key,int data){
//create a link
struct node *link =(struct node*) malloc(sizeof(struct node));
link->key = key;
link->data = data;
if(isEmpty()){
//make it the last link
last= link;
}else{
//update first prev link
head->prev = link;
}
26 B.Sc(cs)
head->next->prev = NULL;
}
head = head->next;
//create a link
struct node *link =(struct node*) malloc(sizeof(struct node));
link->key = key;
link->data = data;
if(isEmpty()){
//make it the last link
last= link;
}else{
//make link a new last link
last->next= link;
Circular Linked List is a variation of Linked list in which the first element points to the last
element and the last element points to the first element. Both Singly Linked List and Doubly Linked
List can be made into a circular linked list.
Singly Linked List as Circular
In singly linked list, the next pointer of the last node points to the first node.
27 B.Sc(cs)
As per the above illustration, following are the important points to be considered.
The last link's next points to the first link of the list in both cases of singly as well as doubly linked list.
The first link's previous points to the last of the list in case of doubly linked list.
Basic Operations
Following are the important operations supported by a circular list.
insert − Inserts an element at the start of the list.
delete − Deletes an element from the start of the list.
display − Displays the list.
Insertion Operation
Following code demonstrates the insertion operation in a circular linked list based on single linked
list.
Example
//insert link at the first location
void insertFirst(int key,int data){
//create a link
struct node *link =(struct node*) malloc(sizeof(struct node));
link->key = key;
link->data= data;
if(isEmpty()){
head = link;
head->next= head;
}else{
//point it to old first node
link->next= head;
if(head->next== head){
head = NULL;
return tempLink;
}
28 B.Sc(cs)
//return the deleted link
return tempLink;
}
Display List Operation
Following code demonstrates the display list operation in a circular linked list.
//display the list
void printList(){
struct node *ptr = head;
printf("\n[ ");
printf(" ]");
}
29 B.Sc(cs)
no need of extra space in memory for pointer. extra memory space is needed.
30 B.Sc(cs)
Unit – III
Stacks
Stack is a linear data structure that follows the LIFO (Last-In-First-Out) principle. Stack has one
end, whereas the Queue has two ends (front and rear). It contains only one pointer top pointer
pointing to the topmost element of the stack. Whenever an element is added in the stack, it is added
on the top of the stack, and the element can be deleted only from the stack.
A stack can be defined as “a container in which insertion and deletion can be done from the
one end known as the top of the stack”.
Somekey points
It is called as stack because it behaves like a real-world stack, piles of books, etc.
A Stack is an abstract data type with a pre-defined capacity, which means that it can store the
elements of a limited size.
It is a data structure that follows some order to insert and delete the elements, and that order
can be LIFO
Stack operations
31 B.Sc(cs)
Representation of Stack using Array
A stack is a data structure that can be represented as an array.
An array is used to store an ordered list of elements. Using an array for representation of stack is one
of the easy techniques to manage the data. But there is a major difference between an array and a
stack.
Size of an array is fixed. While, in a stack, there is no fixed size since the size of stack changed with the
number of elements inserted or deleted to and from it.
Despite the difference, an array can be used to represent a stack by taking an array of maximum size;
big enough to manage a stack.
32 B.Sc(cs)
Step 2 - If it is FULL, then display "Stack is FULL!!! Insertion is not possible!!!" and terminate the
function.
Step 3 - If it is NOT FULL, then increment top value by one (top++) and set stack[top] to value
(stack[top] = value).
pop() - Delete a value from the Stack. In a stack, pop() is a function used to delete an element from
the stack. In a stack, the element is always deleted from top position. Pop function does not take any
value as parameter. We can use the following steps to pop an element from the stack...
Step 1 - Check whether stack is EMPTY. (top == -1)
Step 2 - If it is EMPTY, then display "Stack is EMPTY!!! Deletion is not possible!!!" and terminate the
function.
Step 3 - If it is NOT EMPTY, then delete stack[top] and decrement top value by one (top--).
display() - Displays the elements of a Stack. We can use the following steps to display the elements of
a stack...
Step 1 - Check whether stack is EMPTY. (top == -1)
Step 2 - If it is EMPTY, then display "Stack is EMPTY!!!" and terminate the function.
Step 3 - If it is NOT EMPTY, then define a variable 'i' and initialize with top. Display stack[i] value and
decrement i value by one (i--).
Step 3 - Repeat above step until i value becomes '0'.
Implementation of a stack using an Array
#include <stdio.h>
int stack[20],top;
void main()
{
top=-1;
push(100);
push(500);
push(600);
display();
pop();
display();
}
33 B.Sc(cs)
push(int num)
{
top++;
stack[top]=num;
printf("item pushed =%d\n",num);
}
pop()
{
int d;
d=stack[top];
top--;
printf("Element deleted: %d \n",d);
}
display()
{
int i=0;
for(i = top ; i >=0 ; i--)
{
printf(" %d \n",stack[i]);
}
}
34 B.Sc(cs)
Stack Operations using Linked List
To implement a stack using a linked list, we need to set the following things before
implementing actual operations.
Step 1- Include all the header files which are used in the program. And declare all the user defined
functions.
Step 2 - Define a 'Node' structure with two members data and next.
Step 3 - Define a Node pointer 'top' and set it to NULL.
Step 4 - Implement the main method by displaying Menu with list of operations and make suitable
function calls in the main method.
push(value) - Inserting an element into the Stack. We can use the following steps to insert a new
node into the stack...
Step 1 - Create a newNode with given value.
Step 2 - Check whether stack is Empty (top == NULL)
Step 3 - If it is Empty, then set newNode → next = NULL.
Step 4 - If it is Not Empty, then set newNode → next = top.
Step 5 - Finally, set top = newNode.
pop() - Deleting an Element from a Stack. We can use the following steps to delete a node from the
stack...
Step 1 - Check whether stack is Empty (top == NULL).
Step 2 - If it is Empty, then display "Stack is Empty!!! Deletion is not possible!!!" and terminate the
function
Step 3 - If it is Not Empty, then define a Node pointer 'temp' and set it to 'top'.
Step 4 - Then set 'top = top → next'.
Step 5 - Finally, delete 'temp'. (free(temp)).
display() - Displaying stack of elements. We can use the following steps to display the elements
(nodes) of a stack...
Step 1 - Check whether stack is Empty (top == NULL).
Step 2 - If it is Empty, then display 'Stack is Empty!!!' and terminate the function.
35 B.Sc(cs)
Step 3 - If it is Not Empty, then define a Node pointer 'temp' and initialize with top.
Step 4 - Display 'temp → data --->' and move it to the next node. Repeat the same until temp reaches
to the first node in the stack. (temp → next != NULL).
Step 5 - Finally! Display 'temp → data ---> NULL'.
36 B.Sc(cs)
ptr -> next = NULL;
head=ptr;
}
else
{
ptr->val = val;
ptr->next = head;
head=ptr;
}
printf("Item pushed : %d\n",val);
}
pop()
{
int item;
struct node *ptr;
item = head->val;
ptr = head;
head = head->next;
free(ptr);
printf("Item popped : %d\n",item);
}
display()
{
int i;
struct node *ptr;
ptr=head;
printf("Printing Stack elements \n");
while(ptr!=NULL)
{
printf("%d\n",ptr->val);
ptr = ptr->next;
}}
37 B.Sc(cs)
QUEUE
A Queue is a linear data structure which follows FIFO mechanism, which means the element which
was inserted first in to the Queue will be the first one to go out. The insertion in Queue will be done
at one end and deletion will be done at another end. The place where insertions are made is called
“rear” of the Queue. The place where deletions are made is called “front” of the Queue. In a Queue,
the elements are inserted from rear end and deleted from front end.
The following are the list of operations that can be performed on Queue.
EnQueue: The insertion operation is called EnQueue(ENQ).
DeQueue: The deletion operation is called DeQueue(DNQ).
Traverse( Display ): Visiting each and every element of a Queue is called “Traversing”.
OVERFLOW: Inserting an extra element in an already filled Queue is called Overflow. Before inserting
an element into a Queue, we need to take care about the overflow.
UNDERFLOW: The deletion operation with an empty Queue is called Underflow. So, before deleting
an element from the Queue, we need to take care about the underflow situation.
Algorithm: InsertionOperation:
Initially front = rear = -1
Step-1: [ check for Overflow ] If( rear + 1 >= maxsize)
Display “Queue Overflow” Else
Read an element into item. if(rear = = -1) then
Rear = front = 0 Else
Rear = rear + 1 a[rear] = item
Step-2: Exit
Algorithm: DeletionOperation:
Step-1: [ check for underflow ]
If( front = -1 or front > rear ) Display “ Queue is underflow”
Else item=Q[front] front=front+1
Display :Deleted item is” + item
Step-2: Exit
Algorithm:Traversing
Step-1: set i = front
Step-2:while(i<=rear)
display Q[ i ] i=i+1
Step-3:Exit
38 B.Sc(cs)
Types of Queues:
There are several types of Queues, each one is used in different type of application. The
following are thedifferent types ofQueues.
1. CircularQueues
2. PriorityQueues
3. Double Ended Queues(DEQueues)
1. CIRCULARQUEUES:
Let us consider a situation in ordinary Queue that the max-size of the Queue is 5 and
5 insertions arealready performed and 2 deletions are performed. After performing
1. Insertion( ) 2. Insertion( )
Item=10 Item=20
3. Insertion( ) 4. Insertion( )
Item=30 Item=40
39 B.Sc(cs)
5. Insertion( )
Item=50 6. Deletion( )
7. Deletion( ) 8. Deletion( )
9. Insertion( ) 10.Insertion(
Item=60 )Item=70
Algorithm: Insertion()
40 B.Sc(cs)
Step-1: [ check for overflow ]
If((rear+1) % max-size = = front) then Display “ Queue is
Overflow”
Else
read a value into item if( rear = = -1)
then
rare=front=0
else
rear = ( rear + 1 ) % max-size ;
Q[rear] = item;
Step 2 : Exit
(A) Algorithm: Deletion()
A dequeue is a double-ended queue. You can insert items at either end and delete them
from either end. The methods might be called insertLeft() and insertRight(), and removeLeft() and
removeRight(). If you restrict yourself to insertLeft() and removeLeft() (or their equivalents on the
41 B.Sc(cs)
right), then the deque acts like a stack. If you restrict yourself to insertLeft() and removeRight() (or
the opposite pair), then it acts like aqueue.
A dequeue provides a more versatile data structure than either a stack or a queue, and is
sometimes used in container class libraries to serve both purposes. However, it's not used as often
as stacks and queues, so we won't explore it further here.
PRIORITY QUEUES
A priority queue is a more specialized data structure than a stack or a queue. However, it's a useful
tool in a surprising number of situations. Like an ordinary queue, a priority queue has a front and a
rear, and items are removed from the front. However, in a priority queue, items are ordered by key
value, so that the item with the lowest key (or in some implementations the highest key) is always
at the front. Items are inserted in the proper position to maintain theorder.
Here's how the mail sorting analogy applies to a priority queue. Every time the postman
hands you a letter, you insert it into your pile of pending letters according to its priority. If it must
be answered immediately (the phone company is about to disconnect your modem line), it goes on
top, while if it can wait for a leisurely answer (a letter from your Aunt Mabel), it goes on the
bottom. When you have time to answer your mail, you start by taking the letter off the top (the
front of the queue), thus ensuring that the most important letters are answered first.
42 B.Sc(cs)
UNIT – VI
Searching and sorting:
SORTING
Sorting refers to the technique of arranging and rearranging of data in some specific order. A
collection of recordscalledalistwhereeveryrecordhasoneormorefields.The records are then
arranged inascending or descending order depending on the numerical value of the key.
Sorting is the process of arranging data into meaningful order, so that we can analyze it more
effectively and efficiently. Sorting can be done for text data into alphabetical order, and numeric
data into numerical order both are from ascending or descending.
Sorting refers to arrangement of data items either in ascending order or in descending order.
Sorting is the most primitive operation in data organization.
1. BUBBLESORT
It is the most easiest sorting algorithms used with small number of elements.
In bubble sort technique, each time the consecutive elements are compared and swapping takes
place if necessary
i.e., a[0] is compared with a[1], a[1] is compared with a[2] and so on.
At the end of pass-1(iteration) the highest element of the list will be in its proper position
i.e., a[n-1] is filled with highest element, again we have to repeat the same procedure for
remaining n-1 elements. At the end of each iteration we found that the consecutive highest
element will get their properplace.
Let us consider the following example to implement bubble sort with an array a of 5 elements.
PASS-1:
In this pass a[0] is compared with a[1], a[1] is compared with a[2], a[2] is compared with a[3], a[3]
is compared with a[4]. Whenever greater than condition is true then swapping of those two
elements willbe performed.
43 B.Sc(cs)
PASS-2:
In this pass a[0] is compared with a[1], a[1] is compared with a[2], a[2] is compared with
a[3].Whenever greater than condition is true then swapping of those two elements will be
performed.
PASS-3:
In this pass a[0] is compared with a[1], a[1] is compared with a[2]. Whenever greater than
condition istrue then swapping of those two elements will be performed.
PASS-4:
In this pass a[0] is compared with a[1]. Whenever greater than condition is true then swapping
ofthose two elements will beperformed.
As the end of pass-4 the 4th highest element is in a[1] position. The number of comparisons
in pass-4 is 1. Thetotal number of passes is 4 and total number of comparisons in all the passes is
10.
If there are n elements in the array then the total number of comparisons requiredfor
bubble sort isn(n-1)/2.
ALGORITHM:
44 B.Sc(cs)
Program to sort an array using Bubble Sort Algorithm.
#include <stdio.h>
#include <conio.h>
void main()
{
int a[15],i,j,n,temp; clrscr();
printf("\nENTER THE SIZE OF ARRAY:");
scanf("%d",&n);
printf("\nENTER VALUES FOR THE ARRAY:\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]); for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i]; a[i]=a[j]; a[j]=temp;
}
}
}
printf("\nTHE SORTED ARRAY IS:\n"); for(i=0;i<n;i++)
printf("%d ",a[i]); getch();
}
2. SELECTIONSORT
It is the most easiest sorting algorithm used with small number of elements. In selection sort
techniques, each time one element is compared with all the remaining elements and swapping
takes place if necessary,
i.e., a[0] iscompared with a[1],a[2],..a[n-1] and
45 B.Sc(cs)
a[1] is compared with a[2],a[3]… and so on…. At the end of pass-1, the lowest element of the list
will be in its proper position i.e., a[0].
Again we have to repeat the same process with a[1] for remaining elements. At the end of
each iteration we findthat the consecutive lowest element will be placed in their proper places.
Let us consider the following example to implement selection sort with an array of 5
elements.
PASS-1:
In this pass a[0] is compared with a[1],a[2],a[3] and a[4]. If a[0] greater than any of the element
then swapping will be takes place.
PASS-2:
In this pass a[1] is compared with a[2],a[3] and a[4]. If a[1] greater than any of the element then
swapping will be takes place.
PASS-3:
In this pass a[2] is compared with a[3] and a[4]. If a[2] is greater than any of the element then
swapping will be takes place.
PASS-4:
In this pass a[3] is compared with a[4]. If a[3] is greater than a[4] then
swapping will be done.
46 B.Sc(cs)
Algorithm:
Step-1: Read a list of elements into an array of size n. Step-2: loop i=0 to n-1 each time increment i
by 1 Step-3: loop j=i+1 to n-1 each time increment j by 1
Step-4: if a[i] > a[j] then
temp=a[i] a[i]=a[j] a[j]=temp
Step-5: Exit
47 B.Sc(cs)
{
int max=0,j;
for (j = 1; j <= k;j++)
{
if ( b[j] >b[max])
{
max = j;
}
}
return(max);
}
void exchang(int b[10],int k)
{
int temp, big, j;
for ( j=k-1; j>=1; j--)
{
big = findmax(b,j); temp = b[big]; b[big] = b[j];
b[j] = temp;
}
return;
}
3. INSERTIONSORT:
It is another kind of most efficient sorting algorithm. This algorithm begins with taking first
element of the listas in its proper place i.e, in sorted list and the remaining all elements will be
considered as unsorted list.
Then first element of the unsorted list will be compared with sorted list and if it is less than
the value in sorted list then swapping will be performed. This process will be continued until
unsorted list will become empty.
Let us consider the following list in to an array of size 5.
48 B.Sc(cs)
First element will be considered as sorted list and all the remaining will be
considered as unsorted list.
PASS-1:
In this pass a[1] will be a[0]. Since a[0] < a[1] then a[1] will be taken into sorted list without
swapping.
PASS-2:
In this pass a[2] is compared with a[1]. Since a[1] > a[2] then swapping will be performed.
After swapping a[1] and a[0] are compared. Since a[0] > a[1] then again swapping will be
performed.
PASS-3
In this pass a[3] is compared with a[2]. Since a[2] > a[3] then swapping will be performed. After
swapping a[2] is compared with a[1]. Since a[1] < a[2] then this will be completed.
PASS-4
In this pass a[4] is compared with a[3]. Since a[3] > a[4] swapping will be performed.
After swapping a[3] is compared with a[2]. Since a[2] >a[3] again these two elements will be
swapped.
After swapping a[2] is compared with a[1]. Since a[1] >a[2] again these two elements will be
swapped.
After swapping a[1] is compared with a[0]. Since a[0] >a[1] again these two elements will be
swapped.
Algorithm:
49 B.Sc(cs)
Step-1: Read a list values into an array of size n. Step-2: loop for i=1 to n-1 each time increment i
by 1. Step-3: set value=a[i] and place =i
Step-4: Repeat step-5
until place > 0 and a[place-1] > value
Step-5: a[place]=a[place-1]
Place=place-1 Step-6: a[place]=value Step-7: Exit
4. QUICKSORT:
This is the most efficient and fastest sorting procedure when compared to all other sorting
algorithms. This sorting algorithm uses divide and conquer approach of the elements of the array
to arrange them either in ascending order or in descendingorder.
50 B.Sc(cs)
In this algorithm the array will be portioned into two parts based on pivotelement.
On each step the pivot element will be placed in correct location and hence the array will be divided into
two parts. Those are before pivot element and after the pivotelement.
The same process is repeated for both parts and therefore again these two parts will be divided and same
process is repeated for these subparts until the size of the sub part become1.
It is very clear that the algorithm is completely based on portioning approach for the pivot element.
Algorithm:
Step-1 : Read a list of values into an array of sizen.
Step-2 : set i=low andj=high+1
Step-3 : if low <high
Set pivot=a[low]
Step-3.1: Repeat
while a[i] < pivot and i<hight, i++ Step-3.2 : Repeat while a[j]>pivot and j>=high,
j --
Step-3.3 : if(i<j) then
temp=a[i] a[i]=a[j] a[j]=Temp
Repeat until 3.1, 3.2, 3.3 otherwise stop the loop
Step-3.4 : swap pivot and a[j]
Quick(a, low, j-1) Quick(a, j+1, high)
Step-4 : Exit
51 B.Sc(cs)
{
printf("%5d",a[i]);
} l=0;
r=n-1;
qsort(a,l,r);
printf("\nTHE ARRAY ELEMENTS AFTER SORTING: \n");
for(i=0;i<n;i++)
printf("%5d",a[i]); getch();
}
void qsort(int b[],int left,int right)
{
int i,j,p,tmp,finished,k; if(right>left)
{
i=left; j=right; p=b[left]; finished=0;
while (!finished)
{
do
{
++i;
}
while ((b[i]<=p) && (i<=right));
while ((b[j]>=p) && (j>left))
{
}
if(j<i)
else
{--j;
finished=1;
tmp=b[i]; b[i]=b[j]
52 B.Sc(cs)
b[j]=tmp;
}
}
tmp=b[left]; b[left]=b[j]; b[j]=tmp; qsort(b,left,j-1); qsort(b,i,right);
}
return;
}
MERGESORT
Merge sort technique can be implemented in two ways.
1. We can take two sorted lists and then form a new sorted list by arranging the two sorted lists
intoonelist.
2. We will divide the list into two parts until the sub-list contains single values and then merging
them in a sorted order. While merging place lower values in left hand side and larger values in
right handside.
53 B.Sc(cs)
Algorithm:
Step-1: Read a list of elements into an array of size n
Step-2: Divide the unsorted list into two sub-lists of about half the size until the sub-list contains
single element.
Step-3: Sort each sub-list recursively by reapplying merge sort
Step-4: Merge the two lists into one sorted list until the final list contains n elements.
Step-5: Exit
54 B.Sc(cs)
for (j = 0; j < size;j++)
executing[j] = x[end + j]; mrg1 = 0;
mrg2 = mid - end + 1;
for (j = 0; j < size; j++) {
if(mrg2 <= start - end) if(mrg1 <= mid - end)
if(executing[mrg1] > executing[mrg2]) x[j + end] = executing[mrg2++];
else x[j + end] = executing[mrg1++];
else x[j + end] = executing[mrg2++];
else x[j + end] = executing[mrg1++];
}} }
SEARCHING:
Finding the element whether the given element is present in the list or not is called searching.
It is the most important operation in the field of computer science. Searching means finding the
required element from a group of elements. The searching element is used as a key element.
There are two types of searching mechanisms. They are
1. Linear/ SequentialSearch
2. BinarySearch
1. LINEAR or SEQUENTIALSEARCH
As the name implies, the linear search works in a sequential order from the first element to the
required element found or till to the end of the list. The linear search compares the key element
with the group elements one by one until either a match has been found or the list becomesend.
Let us consider the following example.
Let, Searchkey=29.
1. The search process starts at a[0], which is compared with key. Since a[0]≠ key we move to
thenextelement.
2. Now a[1] is compared with key element. Since a[1] ≠ key we move on to thenext element.
3. Now a[2] is compared with key element. Since a[2] = key we stop thesearch process.
Algorithm:
Step-1: Read list of element into array a with size n.
Step-2: set i = 0 , flag = 0
Step-3: Repeat
while(i<n)
if(a[i] = key) then
55 B.Sc(cs)
set flag=1 and break the loop. set i=i+1
Step-4: if flag= = 1 then
Display “element found” else
Display “element not found”
Step-5: Exit
Output :
2. BINARYSEARCH
It is a divide and conquer technique. In binary search, the search process always focused on
middleelement of the list. In-order to perform binary search, the elements of the list should be
arranged in a sortedorder.
In binary search, first we calculate the location of the middle element. Then that element is
comparedwith key element. Then any one of the following three cases may occur.
1.If the key element is equal to the middle element, then we conclude that the element was found
and willstop the searchingprocess.
2.If the key element is less than middle element then we divide the array from the first element to
middle element and repeat the same process by calculating middleelement.
3.If the key element is greater than middle element, then we divide the array from middle
element to last element and repeat the same process by calculating middleelement.
56 B.Sc(cs)
Algorithm:
Step-1: Read list of elements into array a with size n in sorted order.
Step-2: set start=0, end=n-1, flag=0
Step-3: Repeat
while (start<=end)
Calculate mid=(start+end)/2 If(a[mid]>key) then end=mid-1 If(a[mid]<key) then start mid+1
If(a[mid])==key then
set flag=1 and break the loop
Step-4: if(flag==1) then
Display” element found” else
Display “element not found”
Step-5 : Exit
57 B.Sc(cs)
for(j=i+1;j<10;j++)
{
if(x[i]>x[j])
{
temp=x[i]; x[i]=x[j]; x[j]=temp;
} } } }
int search(int *x,int k)
{
int low=0,high=10,mid,res=0; while(high>=low)
{
mid=(high+low)/2; if(k==x[mid])
{
res=1; break;
}
else
{
if(k>x[mid]) low=mid+1; else high=mid-1;
}}return res;}
58 B.Sc(cs)
UNIT – IV
Trees
A tree is a non-linear data structure and is generally defined as a nonempty finite set of
elements, called nodes such that:
1. Itcontainsaspecialnodecalledrootofthetree.
2. Others all nodes are partitioned under root, and should exist one path between any pairs of
nodes. (It doesn’t form anycycle).
Tree Terminologies:
1. Root:
In a tree data structure, the first
node is called as Root Node. Every
tree must have root node. We can
say that root node is the origin of
tree data structure. In any tree,
there must be only one root node.
We never have multiple root
nodes in atree.
2. Edge:
In a tree data structure, the connecting link
between any two nodes is called as EDGE. In a
tree with 'N' number of nodes there will be a
maximum of 'N-1' number of edges.
59 B.Sc(cs)
3. Parent:
In a tree data structure, the
node which is predecessor of
any node is called as PARENT
NODE. In simple words, the
node which has branch from it
to any other node is called as
parent node. Parent node can
also be defined as "The node
which has child / children".
4. Child:
In a tree data structure, the node which
is descendant of any node is called
as CHILD Node. In simple words, the
node which has a link from its parent
node is called as child node. In a tree,
any parent node can have any number
of child nodes. In a tree, all the nodes
except root are childnodes.
5. Siblings:
In a tree data structure, nodes which
belong to same Parent are called as
SIBLINGS. In simple words, the nodes
with same parent are called as
Siblingnodes.
6. Leaf:
In a tree data structure, the node which
does not have a child is called as
LEAFNode. In simple words, a leaf is a
node with no child.
In a tree data structure, the
leaf nodes are also called as External
Nodes. External node is also a node
with no child. In a tree, leaf node is also
called as 'Terminal' node.
7. InternalNodes:
In a tree data structure, the node
which has atleast one child is called
as INTERNAL Node. In simple words,
an internal node is a node with
atleast one child. In a tree data
structure, nodes other than leaf
nodes are called as Internal Nodes.
The root node is also said to be Internal Node, if the tree has more than one node. Internal
60 B.Sc(cs)
nodes are also called as 'Non-Terminal'nodes.
8. Degree:
In a tree data structure, the
total number of children of
a node is called as DEGREE
of that Node. In simple
words, the Degree of a node
is total number of children it
has. The highest degree of a
node among all the nodes in
a tree is called as 'Degree of
Tree'
9. Level:
In a tree data structure, the
root node is said to be at Level
0 and the children of root node
are at Level 1 and the children
of the nodes which are at Level
1 will be at Level 2 and soon...In
simple words, in a tree each
step from top to bottom is
called as a Level and the Level count starts with '0' and incremented by one at each level
(Step).
10. Height:
In a tree data structure, the
total number of edges from
leaf node to a particular node
in the longest path is called as
HEIGHT of that Node. In a
tree, height of the root node
is said to be height of the
tree. In a tree, height of all
leaf nodes is '0'.
11. Depth:
In a tree data structure, the
total number of edges from
root node to a particular
node is called as DEPTH of
that Node. In a tree, the total
number of edges from root
node to a leaf node in the
longest path is said to be Depth of the tree. In simple words, the highest depth of any leaf
node in a tree is said to be depth of that tree. In a tree, depth of the root node is'0'.
61 B.Sc(cs)
12. Path:
In a tree data
structure, the
sequence of Nodes and
Edges from one node
to another node is
called as PATH
between that two
Nodes. Length of a
Path is total number of
nodes in that path. In
below example the
path A - B - E - J has
length 4.
13. SubTree:
In a tree data structure, each
child from a node forms a
subtree recursively.Every child
node will form a subtree on its
parent node.
BINARY TREE
A binary tree is a tree-type non-linear data structure with a maximum of two children for each
parent. Every node in a binary tree has a left and right reference along with the data element. The
node at the top of the hierarchy of a tree is called the root node. The nodes that hold other sub-
nodes are the parent nodes.
62 B.Sc(cs)
TYPES OF TREES
1. Complete BinaryTree:
A binary tree is said to be complete if all its level except possibly the
last, have maximum number of possible nodes, and if all the nodes at
the last level appear as far left as possible.
2. Full binarytree:
A Binary Tree is a full binary tree if every node has 0 or 2 children.
The following are the examples of a full binary tree. We can also
say a full binary tree is a binary tree in which all nodes except leaf
nodes have two children.
4. SkewedTree:
A tree is called Skew if all the nodes of a tree are attached to one
side only. i.e A left skew will not have any right children in its each
node and right skew will not have any left child in its each node.
BINARY-TREE REPRESENTATION
A binary tree data structure is represented in two ways.
A. Arrayrepresentation
B. Linked listrepresentation
A. ARRAYREPRESENTATION:
In array representation of binary tree, we
use one-dimensional array. Let’s consider
the followingtree.
63 B.Sc(cs)
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
A B C D E F G H I - - - J - - -
Advantages:
• This method benefits from more compact storage and better locality of reference,
particularly during a preordertraversal.
Limitations:
Wastage of space for some types of binarytree.
Insertion and deletions require potential changes in thearray.
B. LINKEDREPRESENTATION:
We use double linked list to represent binary tree. In a double linked list, every node
consists of three fields. First field is used to store the left child address, second field is used
to store data, third field is used tostore right child address.
Advantages:
Insertion and deletion involve no data movement and no movement of nodes except the
rearrangement ofpointers.
Limitations:
Given a node structure, it is difficult to determine its parentnode.
Memory spaces are wasted for storing NULL pointers for the nodes, which have nosubtrees.
BINARY TREE TRAVERSAL
There are three different types of traversing techniques to traverse a binary tree. Traversing
means visiting each and every node of a tree. The following are the different traversingtechniques.
1. Pre-ordertraversal
2. In-ordertraversal
3. Post-ordertraversal
1. Pre-OrderTraversal:
In this traversing technique, the root of the tree is visited first and followed by left sub- tree
and then right sub-tree is visited. The following is the sequence of visiting order of pre-
ordertraversal.
Leftsub- Rightsub
Root
tree -tree
64 B.Sc(cs)
Algorithm for Pre-Order Traversal:
Step-1: (check if the tree is empty by
verifying root pointer) If (p==NULL)
Print tree is empty
Step-2: visit root (root.data)
Step-3: visit left sub-tree (root.lchild) Step-4: visit right sub-tree (root.rchild) Step-5: exit.
Implementation:
2. In-OrderTraversal
In this traversing technique the left sub-tree visited first followed by its root and then the
right sub-tree is visited. The following is the sequence of visiting order for an in-order
traversal.
Left Right
sub-tree Root sub-tree
65 B.Sc(cs)
Algorithm for In-Order Traversal:
Step-1: (check if the tree is empty by
verifying root pointer) void inorder(node root)
If (p==NULL) { if(root != NULL)
Print tree is empty
{
Step-2: visit left sub-tree (root.lchild)
Step-3: visit root (root.data) inorder(root . lchild);
Step-4: visit right sub-tree (root.rchild) print root . data;
Step-5: exit
inorder(root . rchild);
Implementation: }
}
3. Post-OrderTraversal:
In this traversing technique, the left sub-tree is visited first and then right sub-tree is visited and
then root is visited. The following is the sequence of visiting order of post order.
Left Right
sub-tree sub-tree Root
66 B.Sc(cs)
Algorithm for Post-Order Traversal:
Step-1: (check if the tree is empty byverifying
root pointer) If (p==NULL)
Print tree is empty
Step-2: visit left sub-tree (root.lchild) Step-3: visit right sub-tree (root.rchild) Step-4:
visit root (root.data)
Step-5: exit
Implementation:
First of all, binary search tree (BST) is a dynamic data structure, which means, that its size is only
limited by amount of free memory in the operating system and number of elements may vary during
the program run.
67 B.Sc(cs)
A Binary tree is said to be binary search tree if the nodes of the left sub- tree of
the root node are less than root node and the nodes of the right sub-tree of the root node are
greater than or equal to the root node.
Binary search tree is a data structure, which meets the following requirements:
• It is a binarytree;
• Each node contains avalue/key;
• Every element has a value and no two elements have the samevalue
• The keys in the left subtree are smaller than the key in theroot.
• The keys in the right subtree are larger than the key in theroot.
• Notice, that definition above doesn't allowduplicates.
Let us consider the following numbers to be stored into a binary search tree.
35, 14, 10, 25, 40, 50, 45, 65
The binary search tree of above data is as follows:
1. Pre ordertraversal
Algorithm for Pre-Order traversal:
Step-1: visit root node (display root.data) Step-2:
visit left sub-tree preorder(root.lchild) Step-3:
visit right sub-tree preorder(root.rchild)
Pre-Order : 3514102540504565
2. In ordertraversal
Algorithm for In-order traversal:
Step-1: visit left sub-tree inorder(root.lchild)
Step-2: visit root node ( display root.data) Step-
3: visit right sub-tree inorder(root.rchild)
In-Order :1014253540455065
68 B.Sc(cs)
3. Post order traversal
Algorithm for Post-Order traversal:
Step-1: visit left sub-tree postorder(root.lchild)
Step-2: visit right sub-tree postorder(root.rchild)
Step-3: visit root node (display root.data)
Post-Order :1025144565504035
OPERATIONS ON BST
In order of this binary search tree gives ascending order of the list. Operations that can be
performed on binary search tree are:
1) Searching
2) Inserting anydata
3) Deleting any data fromBST
69 B.Sc(cs)
9. Check the flagstatus
if (flag = = TRUE) then
print “Data item found at
“, p else
print “search
unsuccess” end if
10. Finish
STOP
2. Inserting in to binary searchtree:-
This is very simple and is extension of searching in binary search tree. To insert “ITEM” in to
binary search tree “T”. We start searching in “T” for “ITEM” from the root node. If “ITEM” is found
in binary search tree there is no insertion. If “ITEM” is not found then we insert it at the dead-end
where the search stops.
Algorithm:-
1. Access root
node P=ROOT;
2. Read the data ITEM
ITEM=Get value ();
3. Search for correct dead-end
node while (p!=NULL){
4. If the ITEM is less than node data, then move to left
child if (ITEM <Data(p))
p=Left child (p);
5. If the ITEM is greater than node data, then move to right
child else if(ITEM >Data(p))
p=Right child (p);
6. If the data ITEM is available in BST then STOP the process.
else if (ITEM = =Data(p))
{
print “The node already
exist”; EXIT;
}
} // End while
7. Insert new node at END. If ITEM is less than node data then create left
child. if (ITEM <Data(p))
Left child (p) = ITEM;
8. Otherwise the ITEM stores as a right child of the
node. else if (ITEM >Data(p))
Right child (p) = ITEM;
70 B.Sc(cs)
9. Finish
STOP
3. Deleting a node from binary searchtree:-
Another important function for maintaining BST is to delete a specific node form the tree. The
method to delete a node depends on the specific position of the node in the tree.
AVL Trees
A binary search tree can be maintained equal sized left and right sub trees, it is correctly suitable to
efficient searching operation. Such a binary search tree is called as balanced binary tree or AVL tree.
It was developed in the year 1962 by Adelson, Velskii and Landis.
Threaded Binary Tree (TBT):We know that a binary tree is represented either by using arrays or by using
linked list. When a binary tree is represented is by using linked list, if any node is not having a child, we
use null reference in thatposition.In any binary tree there are more number of null references than actual
references, it wastes lot of storagespace.
Heap Tree:
Heap data structure is a specialized binary tree based data structure. Hence it is a binary tree with
specialcharacteristics. In a heap data structure, nodes are arranged based on their values.
2. Max-heap
The value of each node is less than or equal to the value of its parent, with the maximum- value
element at the root.
71 B.Sc(cs)
GRAPHS
Graph is a non-linear data structure mainly used in the applications for finding shortest path root. This
data structure consists of number of non-empty set of vertices as well as edges.
(OR)
A graph can be defined as group of vertices and edges that are used to connect these vertices. A graph
can be seen as a cyclic tree, where the vertices (Nodes) maintain any complex relationship among
them instead of having parent child relationship.
Definition
A graph G can be defined as an ordered set G(V, E) where V(G) represents the set of vertices and E(G)
represents the set of edges which are used to connect these vertices.
A graph ‘G’ consists of a set of ‘V’ vertices (nodes) and set of ‘E’ edges (arcs)
To represent a graph G= {V, E}, here V is a non-empty set of vertices, E is a set of pairs of vertices called
edges.
Where V = {v1, v2,………vi};
E = {e1, e2,e3….ej}
TERMINOLOGY:
72 B.Sc(cs)
Let us take a graph
1. Path:
The edges involved in connection between any pair of vertices is called path. In the above
example the edges AB,BD forms a path between the vertices A and D.
start vertex
End vertex
2. IsolatedVertex:
A vertex which does not have any edges connect to it os called isolated vertex. In the below
5 In-degree of agraph:
For a directed graph, the number of edges incident with vertex is called its in-degree. The in-
degrees of vertices of the above graph is shown below.
In-Degree of
A is 0
B is2
C is 1
73 B.Sc(cs)
D is 2
E is 2
6.Out-degree of agraph:
For a directed graph, the number of edges eliminating from a vertex is called out-degree. The
out-degree of vertices of the above graph is shown below.
Out-Degreeof A is 2
B is2
C is 1
D is 1
E is 1
5. Loop (or)Cycle:
A path which starts from a vertex and ends with the same vertex forms a cycle.
6. Self-Loop:
A vertex which has an edge with itself is called as self loop.
7. WeightedGraph:
A graph G(V,E) is called a weighted graph, if there is a positive
integer assigned to each and every edges of a graph.
APPLICATIONS OF GRAPHS
Since they are powerful abstractions, graphs can be very important in
modelingdata.
Social network graphs: Graphs that represent who knows whom, who communicates with
whom or other relationships in socialstructures
Transportation networks: Graph networks are used by many map programs such as Google
maps, Bing maps and now Apple IOS 6 maps to find the best routes betweenlocations.
Utility graphs. The power grid, the Internet, and the water network are all examples of graphs
where vertices represent connection points, and edges the wires or pipes betweenthem.
Document link graphs. The best known example is the link graph of the web, where each web
page is a vertex, and each hyperlink a directededge.
Network packet traffic graphs. Vertices are IP (Internet protocol) addresses and edges are the
packets that flow betweenthem.
Robot planning. Vertices represent states the robot can be in and the edges the possible
transitions between thestates.
74 B.Sc(cs)
Neural networks. Vertices represent neurons and edges the synapses between them. Neural
networks are used to understand how our brain works and how connections change when
welearn.
Semantic networks. Vertices represent words or concepts and edges represent the
relationships among the words orconcepts.
Graphs in compilers. Graphs are used extensively in compilers. They can be used for type
inference, for so called data flow analysis, register allocation and many otherpurposes.
TRAVERSAL OF A GRAPH
A graph traversal means, visiting all the nodes of the graph. Graph traversal may be needed in many
of application areas and there may be many methods for visiting the vertices of the graph. Many
graph applications required to one to systematically examining the nodes and edges of a graph.
There are two standard ways ie., is done
1) Breadth first search(BFS)
2) Depth first search(DFS)
Here, The breadth – first search will use a queue as an auxiliary structure to hold nodes
forfutureprocessingThe depth – first search will use a stack.
The general idea behind a breadth – first search beginning at a starting node A is
asfollows.
First we examine the starting nodeA.
Then we examine all the neighbors ofA.
After then we examine all the neighbors of the neighbors ofA.
And soon.
During the execution of our algorithm each node of a graph will be in one of 3
statuses called “STATUS” of the node.
75 B.Sc(cs)
Algorithm:
This algorithm executes a breadth – first search on a graph G beginning at a starting node A.
1. Initialize all nodes to the ready state (STATUS =1)
2. Put the starting node A in QUEUE and change its status to the waiting state(STATUS =2).
3. Repeat the steps 4 & 5until the queue isempty.
4. Remove the front node N of QUEUE. Process N and change the status of N
to the processed state(STATUS =3).
5. Add to the rear of QUEUE all the neighbors of N that are in the steady state
(STATUS = 1), and change their status to the waiting state (STATUS =2).
[End of Step3 loop.]
6. Exit.
The above algorithm will process only those nodes which are reachable from the starting
node A. Suppose one wants to examine all the nodes in the graph G. then the algorithm must be
modified so that it begins again with another node (which we will call B) that is still in the ready
state. This node B can be obtained by traversing the list of nodes.
Example:
Consider the graph G In fig. Suppose G represents the daily flights between cities some airline, and
suppose we want to fly from city A to city J with the minimum number of stops. In other words, we
want the minimum path P from A to J (where each edge has length 1).
The minimum path P can be found by using a breadth – first search beginning at city A and
ending when J is encountered. During the execution of the search, we will also keep track of the
origin of each edge by using an array ORIG together with the array QUEUE.
Adjacency Lists
A: F, C, B
F C B B: G, C
C:F
D:C
E:D,C,J
D G F:D
E
G:C,E
J:D,K
K:E,G
J K
Fig.a. Fig.b
76 B.Sc(cs)
REAR=1 ORIG:Ø
b. Remove the front element A from QUEUE by setting FRONT:=FRONT + 1. and add to QUEUE
the neighbors of A asfollows:
FRONT = 2 QUEUE: A, F, C,B
REAR=4 ORIG: Ø, A, A,A
Note that the original A of each of the three edges is added to ORIG.
c. Remove the front element F from QUEUE by setting FRONT := FRONT +1, and add to QUEUE
the neighbors of F asfollows:
FRONT = 3 QUEUE: A, F, C, B,D
REAR=5 ORIG: Ø, A, A, A,F
d. Remove the front element C from QUEUE, and add to QUEUE the neighborsof C(which
are in the ready state) asfollows:
FRONT = 4 QUEUE: A, F, C, B,D
REAR=5 ORIG: Ø, A, A, A,F
Note that the neighbor F of C is not added to QUEUE, since F is not in the ready state
(because F has already been added to QUEUE).
e. Remove the front element B from QUEUE, and add to QUEUE the neighborsof B(the
ones in the ready state) asfollows:
FRONT = 5 QUEUE: A, F, C, B, D,G
REAR=6 ORIG: Ø, A, A, A, F,B
Note that only G is added to QUEUE, since the other neighbor, C is not in the ready state.
f. Remove the front element D from QUEUE, and add to QUEUE the neighborsof
D(the ones in the ready state) as follows:
FRONT =6 QUEUE: A, F, C, B, D,G
REAR=6 ORIG: Ø, A, A, A, F,B
g. Remove the front element G from QUEUE, and add to QUEUE the neighborsof G(the
ones in the ready state) asfollows:
FRONT =7 QUEUE: A, F, C, B, D, G,E
REAR=7 ORIG: Ø, A, A, A, F, B,G
h. Remove the front element E from QUEUE, and add to QUEUE the neighbors of E(the
ones in the ready state) asfollows:
FRONT = 4 QUEUE: A, F, C, B, D, G, E, J
REAR=5 ORIG: Ø, A, A, A, F, B, G,E
We stop as soon as J is added to QUEUE, since J is our final destination. We now backtrack
from J, using the array ORIG to find the path P.Thus
77 B.Sc(cs)
J E G B A
(This algorithm is similar to the inorder traversal of a binary tree, and the algorithm is also similar
to the way one might travel through a maze.)
The algorithm is very similar to the breadth – first search except now we use a stack instead of
the queue.
During the execution of our algorithm each node of a graph will be in one of three statuses
called “STATUS” of the node.
Algorithm:
This algorithm executes a Depth – first search on a graph G beginning at a starting node A.
1: Initialize all nodes to the ready state (STATUS 1)
2: Put the starting node ‘A’ in STACK and change its status to the waiting state (STATUS 2)
3: Repeat steps 4 & 5 until STACK is empty.
4: Remove the front node ‘A’ of STACK. Process ‘A’ and change the status of ‘A’ to the
processed state (STATUS 3).
5: Add to the STACK of all the neighbors of node ‘A’ that are in the ready state and change
their status to the waiting state (STATUS 2).
6:Exist.
78 B.Sc(cs)
Again, the above algorithm will process only those nodes which are reachable from the starting
node A. Suppose one wants to examine all the nodes in G. Then the algorithm must be modified so
that it begins again with another node which we will call
B – that is still in the ready state. This node B can be obtain by traversing the list of nodes.
Example:
Consider the graph G in Fig. Suppose we want to find and print all the node reachable from the
node J (including J itself). One way to do this is to use a depth – first search of G starting at the
node J. the steps of our searchfollow.
79 B.Sc(cs)
The stack is now empty, so the depth – first search of G starting at J is now complete.
SPANNING TREE
Spanning tree of the graph is an undirected graph consisting of only those edges that are necessary to
connect all the vertices in the original graph.
A spanning tree has a property that any pair of vertices they exists only one path
between them, in spanning tree travers from any edge make a unique cycle.
80 B.Sc(cs)
The spanning trees for the above graph are
Prim's Algorithm
Prim's Algorithm is used to find the minimum spanning tree from a graph. Prim's algorithm finds the
subset of edges that includes every vertex of the graph such that the sum of the weights of the edges can
be minimized.
Prim's algorithm starts with the single node and explore all the adjacent nodes with all the connecting
edges at every step. The edges with the minimal weights causing no cycles in the graph got selected.
81 B.Sc(cs)
Algorithm
o Step 1: Select a starting vertex
o Step 2: Repeat Steps 3 and 4 until there are fringe vertices
o Step 3: Select an edge e connecting the tree vertex and fringe vertex that has minimum weight
o Step 4: Add the selected edge and the vertex to the minimum spanning tree T
[END OF LOOP]
o Step 5: EXIT
82 B.Sc(cs)
Unit Wise Important Questions
Unit-I :
Unit-II:
Unit - III:
Unit-IV:
Unit-V:
83 B.Sc(cs)