Data Structure e Content 1
Data Structure e Content 1
Q.1
(i) What is data type?
Ans. A data type is a term, which is used to refer the kinds of data that variables may hold
in a programming language. The general form of a class of data items is also known as data
type.
(vi) List the four major operations performed on linear data structure.
Ans. There are four basic operations that are performed on data structures – traversing,
inserting, deleting and searching.
printf(“%u”, &p);
(xxii) Functions
Ans. Functions are self-code of statements which are written for performing a specific
given task. Each function performs a different function.
(xxiii) Parameters
Ans. Parameters are those entities that are used in function call as well as in function
definition. When we call a function we pass arguments to the called function. Such
arguments are called actual parameters. And calling function receives these actual arguments
in formal parameter (arguments).
Short answer type questions
Primary data type - The data types, which are not composed of other data types, are called as
primary data type. C names primary data types as standard data type. Primary data types are
integers, floats and characters data types. The primary data types could be of several types. For
example an integer could be a short integer or a ling integer. Or a character could be an unsigned
char or a signed char.
Secondary data type - The data types, which are composed of primary data types, are called as
secondary data type. Normally these are defined by the programmer that’s why these are sometimes
called user – defined data types. In C secondary data types are arrays, structures, pointers, unions,
enum etc.
What is data structure? Give difference between the data and information.
Ans. A data structure is defined as a specific way of arranging data and a set of operations performed
on the data that make it behave in a certain way. Information is a processed data and data is a
collection of values (raw data) from which no conclusion is made.
Another difference is that there are predefined set of operations on primitive data structures, whereas
on non-primitive data structure the user has to define the set of operations exclusively.
Global and local variables – The formal arguments and variables declared inside a function block
are local variables. These local variables are not seen by other function in the program. This type of
local variable is called as automatic local variable. On the other hand, if the variables are declared
anywhere outside all the functions, they can be accessible from any function in the program file.
Such variables are called as global variables. Global variables are usually declared in the beginning
of a program.
Write a program to swap the contents of two variables using pointers. Ans.
#include <stdio.h>
main()
{
int a, b;
printf(“\nEnter any two number –”);
scanf(“%d %d”, &a, &b);
printf(“\nTwo numbers before calling swap() function - %d %d”, a,
b); swap(&a, &b);
printf(“\nTwo numbers after calling swap() function - %d %d”, a, b);
}
swap(int *x, int *y)
{
int t;
t = (*x);
(*x) = (*y);
(*y) = t;
}
Ans. Programming can be defined as the development of a solution to an identified problem. There
are seven basic steps in the development of a program:
1. Define the problem - This step (often overlooked) involves the careful reading and re-reading
of the problem until the programmer understands completely what is required.
2. Outline the solution (analysis) - Once the problem has been defined, the programmer may
decide to break the problem up into smaller tasks or steps, and several solutions may be considered.
The solution outline often takes the shape of a hierarchy or structure chart.
3. Develop the outline into an algorithm (design) - Using the solution outline developed in step 2, the
programmer then expands this into a set of precise steps (algorithm) that describe exactly the tasks to
be performed and the order in which they are to be carried out. This step can use both structured
programming techniques and pseudocode (covered in more detail later).
4. Test the algorithm for correctness (desk check) - This step is one of the most important in the
development of a program as is often forgotten. Test data needs to be walked though each step in
the algorithm to check that the instructions described in the algorithm will actually do what they are
supposed to. If logic errors are discovered then they can be easily corrected.
5. Code the algorithm into a specific programming language (coding) - It is only after all design
considerations have been met that a programmer should actually start to code the program. In
preceding analysis it may have been necessary to consider which language should be used, as each
has its own peculiarities (advantages and disadvantages).
6. Run the program on the computer (testing) - This step uses a program compiler and test data to
test the code for both syntax and logic errors. If the program is well designed then the usual time-
wasting frustration and despair often associated with program testing are reduced to a minimum. This
step will often need to be done several times until the programmer is satisfied that the program is
running as required.
7. Document and maintain the program (documentation) - Program documentation should not be
just listed as the last step in the development process, as it is an ongoing task from the initial
definition of the problem to the final test results. Documentation also involves maintenance - the
changes that are made to a program, often by another programmer, during the life of that program.
The better a program has been documented and the logic understood, the easier it is for another
to make changes. The whole process of defining problems to providing the coded solution are an
ongoing process that is circular in nature and can be called the System Development Life Cycle
(SDLC).
What are linear and non-linear data structures? Explain with example.
Ans. Linear data structures - The data structures whose components are processed sequentially,
one by one, are referred as linear data structures. Generally we have following types of linear data
structures:
1. Stack - A stack is a data structure in which insertions and deletions are made at one end, called top
of the stack. A stack is called as LIFO (Last–In First –Out) structure. The plate holder in a cafeteria
has this property. We can take only the top plate. When we do this, the only below it rises to the top
so that the next person can take one.
2. Queue - A queue is a data structure in which insertions are made at one end and deletions are made
at other end. A queue is also called as FIFO (First–In First–Out) structure. A waiting line in a bank or
for a bus is suitable example of a queue.
3. Linked List - A linked list is a data structure in which the components are logically ordered by
their pointer fields rather than physically ordered. Each component of the linked list, called a node,
has two fields – data field and link field. The data field stores the information and the link field points
to the next component.
Non–linear data structures – In non–linear data structures, elements are not processed linearly. In
these insertion and deletion can take place anywhere in the data structure. Non–linear data structures
are of two main types:
1. Tree – Tree is a non–linear data structure and is defined as a finite set of one or more nodes such
that
(i) there is a specially designated node, called the root node of the tree
(ii) the remaining nodes are partitioned into n ≥ 0 disjoint sets T 1, T2, …, Tn are called the
subtree of root node
Topmost node of a tree is called the root of the tree and remaining nodes are called leaves
(children) of the tree.
2. Graph – Graph is another important non-linear data structure, which is represented by a 2-tuple
(V,E) such that V is a set of vertices and E is a set of edges. We write it as:
Here ‘E’ is a set of pairs of vertices and these pairs are called edges.
What is structured programming? Explain top- down and bottom-up design for solvingany
problem. Illustrates with examples.
Ans. Structured programming is a computer programming technique in which the statements are
organized in a specific manner to minimize error or misinterpretation. Structured programming is an
organized programming approach that involve the use of four basic control structures, - Sequential,
Conditional, Repetition and Procedures.
The sequential structure is composed of statements executed one after another. In this all the
statements are executed in the order in which they are written. The conditional structure (also know
as selection structure) executes different set of statements depending upon certain condition. The
repetitive structures repeat a set of statements while certain conditions are met. The procedure
enables us to replace a set of statements with a single statement. Following figure shows these basic
structures of programming languages.
Sequence Selection
Statement
Condition
Procedure1
Condition
Statement
Procedure2
A procedure is a combination of the basic structures that is considered as a single statement in the
program. In C language procedures are called as functions. They allow you to write parts of your
programs separately, then assemble into final form. In other words you can say that structured
programming approach uses the top-down approach to decompose main functions into lower level
components for modular coding process. This technique improves the programming process through
better organization of programs and better programming notations to facilitates, correct, and clear
description of data in control structures.
Top-down and Bottom-up design – The top-down approach divides the large problem into smaller
problems (subproblems) that can be handled more easily. However if the subproblem is still complex
then it must be further divided into subsubproblems. This process goes on until each subproblem can
not be further divided. Each subproblem can be easily solved independently of the others. These
subproblems are also called as modules. That’s why the top-down approach is also called as modular
programming. Following figure shows top-down methodology.
Large and
Complex Problem
SubSubProblem SubSubProblem
1. Problem Definition - Understand the problem statement, that is one must very clear about
what is given (input) and what is required (output)
2. Naming the Modules and Submodules – Write the naming module and name the lower
level modules
3. Algorithms and their Implementations - Write the remaining submodules
4. Analyze – Resequence and revise, if necessary
Another interesting approach is bottom-up approach. This approach works inversely of top-down. In
bottom-up approach the programmer might choose to solve different parts of the problem directly in
his programming language and then combine these pieces into a complete program. Experience
suggests that the top-down approach should be followed when creating a program.
Chapter-2 Arrays
Very Short Answer Type Questions
Q.1
(i) What do you mean by an array?
Ans. An array is a collection of similar data items which are stored in memory contiguously.
datatype arrayname[Size];
Here arrayname is the name of array, Size is the number of elements in the array and datatype
specifies the type of elements stored in array.
(vii) Given a linear array A(5:50) B(18). Find the number of elements in each
array. Ans. The length of array A = (50-5+1)
= 46
Row major Order - The basic formula for calculating the address of element A[I, J] in row
major order of an array of (M x N) elements is as:
Column major Order - The basic formula for calculating the address of element A[I, J] in
an array of (M x N) elements in column major order as :
Here M is total number of columns (M2 - M1+1), M1 is starting row number, M2 is last row
number and N1 is starting column number.
Memory representation of a linear array – The elements of a linear array are stored in contiguous
memory locations. It means that if there is an integer array of 10 elements starting from the address
6000, then the next element would be stored at address 6002, and the third element would be stored at
6004, and so on. Figure shows this:
A[]
Consider the one dimensional float array LA. Base address is 2000,
w = 4, LB = 1 and UB = 8. Calculate the address of LA[4] and LA[6].
Ans. The formula Address of finding the address of Ith data is as:
LA[I] = BaseAddress + w * (I – LB)
1. Set I = 0
2. Repeat through step-4 while (I< N)
3. Process element A[I]
4. Increment I as I = I+1
5. Exit
1. Reset Flag = 0
2. Initialize I = 0
3. Repeat through step-6 while (I< N)
4. If Item = A[I] then go to step 5; otherwise go to step 6
5. Set Flag = 1 and go to step-7
6. Increment the value of I as I = I+1
7. If Flag = 1 then print the message – “Item found”; otherwise print the message – “Item not
found”
8. Exit
Row major order - In this the elements of two-dimensional array are stored row by row, that is first
row of two-dimensional array is stored first, then second, third, fourth. And so on. Let we have a
matrix of (3x4) dimension:
4 9 7 8
2 5 0 8
1 6 1 3 3x4
4 9 7 8 2 5 0 8 1 6 1 3
The computer stored the base address of the array and using this base address we can find out the
address of other elements. The basic formula for calculating the address of element A[I, J] in an array
of (M x N) elements is as:
Here Base is the base address of a two dimensional array, Size specifies the size of element in bytes,
N is total number of columns (N2 - N1+ 1), N1 is starting column number, N2 is last column
number and M1 is first row number.
Column major order - In this the elements of two-dimensional array are stored column by column,
that is first column of two-dimensional array is stored first, then second, third, fourth. And so on.
Let we have a matrix of (3x4) dimension:
4 9 7 8
2 5 0 8
1 6 1 3 3x4
4 2 1 9 5 6 7 0 1 8 8 3
Here M is total number of columns (M2 - M1+1), M1 is starting row number, M2 is last row
number and N1 is starting column number.
Addition of Matrices – Two matrices are added only when their dimensions are exactly same.
The algorithm of performing addition operation on matrixes A & B is as:
Multiplication of Matrices – Two matrices are multiplied only when number of columsn of first
matrix is equal to number of rows of first second matrix. The algorithm of performing multiplication
operation on matrixes A & B is as:
Bij = Aji
1. Initialize I = 0
2. Repeat through step-7 while (I < Row1)
3. Initialize J = 0
4. Repeat through step-6 while (J < Col1)
5. Assign B[I][J] = A[J]I]
6. Increment of J as J = J + 1
7. Increment of I as I = I +1
8. Exit
#include <stdio.h>
main()
{
int a[10][10], b[10][10], c[10][10];
int i, j, row1, row2, col1, col2;
#include <stdio.h>
main()
{
int a[3][3], b[3][3], c[3][3];
int i, j, k, r1, r2, c1, c2;
#include <stdio.h>
#include <alloc.h>
main()
{
int i, j, r1, c1, r2, c2, *a, *b, *c;
printf("\nEnter number of rows and columns of first matrix -
"); scanf("%d %d", &r1, &c1);
printf("\nEnter number of rows and columns of second matrix - ");
scanf("%d %d", &r2, &c2);
if ((r1 == r2) && (c1 == c2))
{
a = (int *)malloc(r1*c1*2);
b = (int *)malloc(r2*c2*2);
c = (int *)malloc(r1*c1*2);
printf("\nEnter elements of first matrix - ");
for(i=0; i<r1; i++)
{
for(j=0; j<c1; j++)
scanf("%d", &a[i*r1+j]);
}
printf("\nEnter elements of first matrix - ");
for(i=0; i<r1; i++)
{
for(j=0; j<c1; j++)
scanf("%d", &b[i*r1+j]);
}
printf("\nAddition of two matrices is \n");
for(i=0; i<r1; i++)
{
for(j=0; j<c1; j++)
c[i*r1+j] = a[i*r1+j] + b[i*r1+j];
}
for(i=0; i<r1; i++)
{
printf("\n");
for(j=0; j<c1; j++)
printf("%d\t", c[i*r1+j]);
}
}
else
printf("\n The Dimensions of both matrices do not match.");
}
Chapter-3 Linked Lists
Very Short Answer Type Questions
Q.1
(i) What is linked list?
Ans. A linked list is a linear data structure in which each component (node) has at least two
fields – data (information of component) and link (information about the location of next
component. The end of the list is indicated by the special pointer constant NULL.
(ix) Write the difference between singly lined list and doubly linked list.
Ans. In a singly linked list, each node consists of an address of its next node; therefore
traversing is done in one direction only. On the other hand, in a doubly linked list, each
node consists of an address of its next node as well as its previous node, therefore traversing
is done in both directions (forward as well as backward).
A linked list can be represented in memory – either by using an array or by using pointers. Array
is static in nature. Therefore pointers are frequently used in the implementation of a linked list.
Insertion into a Linked List – Here is the algorithm that inserts an item in a linear linked list.
Here ‘First’ contains either a NULL value or the address of first node of the linked list.
Write down the algorithm that deletes an element from the linked list.
Ans. DeleteList(First, item)
Here ‘First’ contains either a NULL value or the address of first node of the linked list. Perform the
following steps if the list is not empty:
What is Doubly linked list? How an element is inserted in a doubly linked list?
Ans. A linked list in which each node contains two links, one for the next node and another for the
previous one, is called as a doubly linked list. Following figure shows a doubly linked list of 4 nodes.
FIRST 38 18 29 62
NULL NULL
Insertion of an element at any specific position - When we insert a new element (node) at any
position in the doubly linked list we need to specify the position of the inserted node. If the position of
new element is within the limitation then it is inserted at that specific position; otherwise this element
is inserted at the end of the doubly linked list.
Let we have a linked list of three nodes as shown in following figure and we want to insert a new
node ‘t’ after the node ‘p’ .
FIRST 38 18 62
NULL
NULL p
When a new node ‘t’ is inserted after ‘p’ node then the following link fields are changed accordingly:
data(t) = 29
rlink(t) = rlink(p)
llink(t) = p
llink(rlink(p) = t
rlink(p) = t
After using these statements, the doubly linked list might look like this:
FIRST 38 18 29 62
NULL p t NULL
struct node
{
int data;
struct node *link;
};
struct node *temp = (struct node *)malloc(sizeof(struct node));
struct dnode
{
struct dnode *next;
int data;
struct dnode *next;
};
struct dnode *temp = (struct dnode *)malloc(sizeof(struct dnode));
What is a linked list? Explain representation of linked list in memory. Give its applications. Ans.
A linked list is a linear data structure in which each element contains two pieces of information -first
part holds the data (information) of item and second part holds the address (link) of next element in
the list. The entire list is accessed from an external pointer, start, that points (contains the address of)
the first node in the list. The link field of last node in the list contains a special value, known as null,
which is not a valid address; rather it just signifies the end of the list. Following figure shows this.
start 46 78 90 13 NULL
Representation of linked list in memory - A linked list can be represented in memory in two ways -
using arrays and using dynamic variables (Pointers)
Array Representation of Linked Lists – As stated earlier, a linked list is basically a collection of
elements and each element is also referred to as a node. Each array node consists an item of
information, say ‘data’ item, and an integer variable, say link, containing the index of its
successor node.
The declaration of an array node in a simple linked list is as follows:
struct ArrayNode
{
int data;
int link;
};
Here a pointer to a node is represented by an array index and a group of 10 nodes might be declared,
globally, as:
#define n 100
struct ArrayNode node[n];
Here a pointer ‘link’ is an integer value between 0 and n-1, that references a particular element of the
array node[]. In array implementation, node[i] refers to ith node, node[i].data is used to refer the data
of node ‘i’ and node[i].link to next node of the linked list. The link field of last node contains a null
pointer represented by the integer –1.
However, it is not necessary that the linked list from node[0], rather it can be started from any node
number, say node[3]. Since a variable ‘start’ represents a pointer to the list, therefore ‘start’ points
to node[3] as it is the first node on the list. The node[3].data references the information of the
current node and node[3].link contains the index value of second node. Let node[3].link is 8 then
node[8] is the second node of the list. The node[8].link will contain the index of value of third node.
This process goes on until the linked list is completed. The index value of last node of the list is
represented by the integer –1. The value –1 is just used to represent the end of the list. However we
can also used any unusual values, such as -9999 or -11111 etc, for representing the end of the list.
As stated earlier each node of a linked list has two fields – the data (information) field and a link field
pointing to the next node in the list. Nodes are created dynamically using dynamic memory allocation
function malloc(), when needed, and destroyed using free() function, when no longer needed. The link
field contains the memory address of the next node in the list. Such a node can be declared in C using
self-referential structure.
Here the link field of each node, except last node, contains the memory address of its successor node.
The link field of the last node contains sentinel value, defined as NULL in C.
struct node
{
int data;
struct node *link;
};
typedef struct node node;
data link
A node of this type is identical to the nodes of the array implementation except that the link field is a
pointer (containing the address of the next node in the list) rather than an integer containing the index
within an array where the next node in the list is kept.
To maintain a linear linked list we use a pointer variable ‘first’, also known as an external pointer
variable. The ‘first’ pointer contains an address of first node in the list. Here the name ‘first’ is just an
user-defined identifier. You can also use other names, such as start, or head etc. if the list is empty
then the value of this external pointer variable must contain a NULL value.
When a linked list is implemented using pointers, nodes are allocated and free as necessary. Thus
there is no need to declare a collection of nodes. A new node is created dynamically as:
This statement places the address of an available node into ‘p’. Here the malloc() function is used to
create memory dynamically. Similarly the memory allocated to ‘p’ node is released by using free()
function as:
free(p);
Write a program which a singly (linear) linked list of ‘n’ number of nodes and traverses it.
#include <stdio.h>
#include <alloc.h>
struct node
{
int data;
struct node *link;
};
typedef struct node node;
main()
{
int i,n, item;
node *t, *current;
node *first = NULL;
t = (node *)malloc(sizeof(node));
t->data = item;
t->link = NULL;
if (first == NULL)
first = t;
else
current->link = t;
current = t;
}
printf(“\nLinked list is as... \n\n”);
while (first != NULL)
{
printf(“%d —> “, first->data);
first = first->link;
}
printf(“Null”);
}
Ans. Here is the algorithm for searching an element in sorted linked list:
Search(First, Item)
Here ‘First’ contains the address of first node and Item is the element to be searched in it.
Write a program which a doubly (linear) linked list of ‘n’ number of nodes and traverses it.
Ans. Here is a program which a doubly (linear) linked list of ‘n’ number of nodes and traverses it.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
struct dnode
{
struct dnode *left;
int data;
struct dnode *right;
};
typedef struct dnode dnode;
main()
{
if (first == NULL)
{
first = temp;
temp->left = NULL;
}
else
{
current->right = temp;
temp->left = current;
}
current = temp;
}
if (first = = NULL)
printf(“\nList is empty.\n”);
else
{
printf(“\nTraversing in forward direction.\n\n”);
while (first->right != NULL)
{
printf(“%d<—>”, first ->data);
first = first ->right;
}
printf(“%d <—> Null”, first ->data);
printf(“\n\nTraversing in backward direction.\n\n”);
while (first->left != NULL) {
Ans.
(a) Circular linked list – Circular linked list is a special type of singly linked list in which each
node has two fields – data and link. The data field contains the information of the node and the link
field contains the information of the next node in the list. The special thing about it is that the link
field of last node contains the address of first node rather than a NULL value like in a linear linked
list. Following figure shows this:
21 37 16 72 44
First
Circular linked queues have two basic operations – Insertion and Deletion and four other important
operations, such as InitializeQueue, FrontElement, IsQueueFull and IsQueueEmpty. Here we will
only discuss insertion and deletion operations. Rest are left for the readers.
(b) Header linked list – A header linked list is also a special type of linked list in which there is
always a special designated first node, called a header node, at the front of the list. This header node
contains some special and important information of list. For example, a header node usually contains
information such as the total number of nodes in the list or whether the list is sorted or not.
67 90 17
# 45
First
Generally we have two types of header linked lists:
(i) Grounded Header Linked Lists - A grounded header linked list is one whose last node
contains a NULL value
(ii) Circular Header Linked Lists - A circular leader linked list is one whose last node points to
the header node; rather than containing a NULL value.
Chapter-4 Stacks, Queues and Recursion
Very Short Answer Type Questions
Q.1
(i) What is stack? Give example.
Ans. A stack is a linear data structure in which insertions and deletions are made at one
end, called top of the stack. A stack is called as LIFO (Last–In First –Out) structure
because the item that is inserted in last will be the first item to be removed from the stack.
Section-B
XX YY ZZ
1 2 3 4 5 6 7 8
Top = 3 MAXSTK = 8
Ans. Push(Stack, WWW) – In this first the value of TOP is increased and then the item ‘WWW’ is
pushed as:
Top = Top + 1
STACK[Top] = WWW
XX YY ZZ WWW
1 2 3 4 5 6 7 8
Top = 4 MAXSTK = 8
What are infix, postfix and prefix notations for an arithmetic expression? Explainwith
suitable examples.
Ans. A notation in which operators comes between its operands in an arithmetic expression is
called infix notation. When an operator comes after its operands, it is called as postfix notation.
And when an operator comes before its operands, it is called as prefix notation Here are examples
of infix, postfix and prefix notation for an arithmetic expression (infix) a + b:
a b + is postfix notation of a + b .
+ a b is prefix notation of a + b
A * ( B + D ) / E – F *( G + H / K )
Ans. Firstly we will parenthesize this expression according to the operator priority precedence as:
( ( ( A * ( B + D ) ) / E ) – ( F *( G + ( H / K ) ) ) )
Now for the post fix expression shift all the operators to their respective ending brackets and remove
all the parenthesis as:
( ( ( A * ( B + D ) ) / E ) – ( F *( G + ( H / K ) ) ) )
Postfix expression : A B D + * E / F G H K / + * –
For prefix expression shift all the operators to their respective opening brackets and remove all
the parenthesis as:
( ( ( A * ( B + D ) ) / E ) – ( F *( G + ( H / K ) ) ) )
Prefix expression : – / * A + B D E * F + G / H K
Traverse(Stack)
Here ‘Stack’ contains the base address of the array ‘Stack’.
Perform the following steps if the stack is not empty:
1. Set I = Top
2. Repeat through step-4 while (I>=0)
3. Process the element Stack[I]
4. Decrement I as I = I – 1
5. Exit
Ans. Infix notation – If an operator is placed between its two operands in an expression, it is said to be
an ‘infix’ expression and this notation is called as infix notation. For example: a+b, a*b etc.
Prefix notation – If an operator is placed just before its operands, it is said to be a prefix notation. For
example +a b, *a b etc.
Postfix notation – If the operator is placed after its two operands, it is said to be a postfix notation.
For example a b +, a b * etc.
Explain Queues. How you will present and implement the queue in memory.
Ans. A queue is linear data structure in which all insertion to the list are made at one end, called the
rear, and all deletions from the list are made at the other end, called the front. Following figure shows
a queue of 8 elements.
4 9 1 5 6 3 8 2
front rear
The queue is also known as FIFO (First In First Out) data structure because the first element that is
inserted into the queue would be the first one to be removed.
In C, a queue is implemented either by using an array or by using a linked list (pointers).
Insert Operation – An item is inserted into the queue only when the queue is not full. Insert
operation is implemented as:
Insert(Queue, item)
Here ‘Queue’ contains the base address of the array and ‘item’ be the element to be inserted.
Delete (Queue)
Here ‘Queue’ contains the base address of the array Queue.
rear = (rear+1)%Size;
front = (front+1)%Size;
Write a program that finds the factorial of any given number using recursion.
Ans. Here is a program that finds the factorial of any given number using recursion.
#include <stdio.h>
main()
{
int num , n ;
printf("\nEnter the number : ") ;
scanf("%d",&n);
num = factorial(n);
printf("\nThe factorial of a given number %d = %d", num , number ) ;
}
factorial(int n)
{
if ( n = = 0 )
return (1) ;
else
return (n * factorial (n-1)) ;
}
#include <stdio.h>
main ()
{
int n;
printf (“\n Enter the number of terms to be generated?”);
scanf (“%d”, &n);
printf (“\n Fibonacci series upto %d terms \n”,
number); fib (n);
}
fib (int n)
{
if ((n= =0) || (n= =1))
return 0;
else
{
if (n= =2)
return (1);
else
{
f = fib (n-1)+fib (n-2);
printf (“%d”,f);
}
}
}
1. for loop
2. while loop
3. do-while loop
On the other hand, recursion is a process in which a function calls itself directly or indirectly.
Recursion is a fast process as compare to iterations.
Recursion is preferred over iteration when the problem is naturally recursive. For example, finding a
factorial of a given number is naturally recursive. On the other hand, iteration is not always
overshadow by recursion. Recursion becomes very dangerous if it is used improperly.
Ans. Stack is a data structure in which all insertion and deletion are made at only one end, called
the top of the stack. When a new item is inserted into the stack it is said to be PUSH operation. And
when an item is deleted from the stack it is said to be POP operation.
Let we have a stack ‘S’ of 8 cells, which is initially empty and we want to insert the following
sequence of characters - ‘M’, ‘N’, ‘P’, ‘G’, ‘H’. Here ‘M’ is the first character to put on the stack and
‘H’ is the last character as shown in following figure.
H Top
G G
Top
P Top P P
N Top N N N
M Top M M M M
If we want to delete an item from stack then the first element to be deleted would be ‘H’. You can
also say that the element, which is most recently put on the stack, will be the first one to be
removed. That’s why Stack is also known as LIFO, which stands for Last In First Out.
Push Operation - When we insert an item onto a stack, we say that we push it onto the stack. A new
item is inserted into a stack only when the stack is not full; otherwise it displays an error message –
“Stack Overflow”. Therefore when a new item is inserted, we will firstly check, whether the stack is
full or not. If the value of top is equal to (MAXSTK-1) then our stack is overflow; otherwise the top is
incremented by one and the item is inserted at current top position of the stack.
Pop Operation - When we delete an item from stack, it is said to be pop operation. An item is
deleted from the stack only when the stack is not empty. If the stack is empty then it displays an error
message – “Stack Underflow”; otherwise the top element of the stack is removed and the value of
TOP is decremented.
Algorithm - POP(STACK)
Here STACK is an array of items
Q.14 What do you understand by Precedence of arithmetic operators. Convert the following
expression into Postfix form using Stack:
A/B+C/D*(E+F)/H
Ans. When we convert an infix expression into postfix expression, we scan each symbol from left to
right. If an operand is encountered then it is appended to postfix expression. If a left parenthesis is
encountered then it is pushed into stack and when right parenthesis is encountered then all operators
upto the first left parenthesis are popped from the stack. However if an operator is scanned then it
follows the rule:
(i) If the scanned operator has lower or equal priority as compared to the top of the operators
on stack then the operator on top of the stack is popped from the stack and is appended to
the postfix expression and then the new scanned character is pushed on to the stack
(ii) If the scanned operator has higher priority as compared to the top of the operator on
stack then the scanned operator is pushed on top of the stack.
( (
A ( A
/ (/ A
B (/ AB
+ (+ AB/
C (+ AB/C
/ (+/ AB/C
D (+/ AB/CD
* (+* AB/CD/
( (+*( AB/CD/
E (+*( AB/CD/E
+ (+*(+ AB/CD/E
F (+*(+ AB/CD/EF
) (+* AB/CD/EF+
/ (+/ AB/CD/EF+*
H (+/ AB/CD/EF+*H
None Empty AB/CD/EF+*H/+
Ans. (a) POP(STACK, ITEM) – removes the topmost item BBB from the stack and store it in
ITEM and the STACK looks
STACK: AAA, , ,
(b) POP(STACK, ITEM) – removes the topmost item AAA from the stack and store it in ITEM
and the STACK looks
STACK: , , ,
(c) PUSH(STACK, HHH) – inserts new item HHH on top of the stack and the STACK looks
STACK: HHH, , ,
(d) POP(STACK, ITEM) – removes the topmost item HHH from the stack and store it in ITEM
and the STACK looks
STACK: , , ,
(e) POP(STACK, ITEM) – displays an error message – “STACK UNDERFLOW” because there is
no item in the stack to be removed
(f) PUSH(STACK, GGG) – inserts new item GGG on top of the stack and the STACK looks
STACK: GGG, , ,
Consider the following queue of characters where QUEUE is a circular array whichis
allocated 6 memory cells:
FRONT = 2, REAR = 4
QUEUE = , A, C, D, ,
QUEUE= _, A, C, D, ,
(i) When F is added to the queue, the rear changes to 5 and the Queue is
(ii) When two letters are deleted, the front changes to 4 and the Queue is
(iii) When K, L and M are added to the queue, the rear changes to 2 and the Queue is
(iv) When two letters are deleted, the front changes to 6 and the Queue is
(v) When R is added to the queue, the rear changes to 3 and the Queue is
Consider the following circular queue capable of accommodating maximum Six elements
FRONT = 2, REAR = 4
QUEUE = , A, B, C, ,
QUEUE= ,A, B, C, , .
(i) When N is added to the queue, the rear changes to 5 and the Queue is
(ii) When Z is added to the queue, the rear changes to 6 and the Queue
(iii) When two letters are deleted, the front changes to 4 and the Queue is
(iv) When M, H and I are added, the rear again changes to 3 and the Queue is
(e) When one letter is deleted , the front changes to 5 and the Queue is
Ans. (a) Stack - A stack is a basic data structure, where insertion and deletion of items takes place at
one end called top of the stack. The basic concept can be illustrated by thinking of your data as a stack
of plates or books where you can only take the top item off the stack in order to remove things from it.
A stack is also called a LIFO (Last In First Out) to demonstrate the way it accesses data. There are
basically three operations that can be performed on stacks . They are 1) inserting an item into a
stack (push). 2) deleting an item from the stack (pop). 3) displaying the contents of the stack(pip).
(ii) Priority Queue - A priority queue is a data structure in which elements are inserted arbitrarily but
deleted according to their priority. If elements have an equal priority, then the usual rule applies, that
is first element inserted should be removed first. Priority queues are of two types:
(a) Ascending Priority Queues - In ascending priority queues, the elements are inserted
arbitrarily at any position depending upon their priority but delete the element having
smallest priority.
(b) Descending Priority Queues - In descending priority queues, the elements are inserted
arbitrarily at any position depending upon their priority but delete the element having largest
priority.
(iii) De-Queues – The Deque stands for Double Ended Queue. A deque is an ordered collection of
elements from which new elements can be added or deleted from either end of the queue but not in
the middle, as shown in following figure
Deletion Deletion
45 50 61 70 13 27 96 56
Insertion Insertion
Front Rear
In this figure, there are 8 elements in the deque. Here the new element can be inserted
at either end of the queue. Similarly the elements can be removed from the either end of the
queue. Deques are of two special types -
1. Input Restricted Deque – a deque in which items may be deleted at either end, i.e. front as
well as rear, but insertion of items is restricted at only one end, say rear, of the queue.
2. Output Restricted Deque – a deque in which items may be inserted at either end, i.e. front as
well as rear, but deletion of items is restricted at only one end, say front, of the queue.
(iv) Recursion – Recursion is a process in which a functions calls itself directly or indirectly.
While using recursion one should remember that there should be at least one if statement used to
terminaterecursion. It does not contain any looping statements. For example:
Recursion()
{
printf(“\n Recursion….!”);
Recursion();
}
(a) Stacks are more commonly used within the computer system when functions are called. A
function may be called either by itself or by other function. When a function is called within
another function then the system should remember the location from where the call was
made, additionally the parameters and local variables of the calling function so that their
values will not be lost while its execution resumes.
(b) Stacks are also used in evaluating of postfix expressions.
Chapter-5 Trees
Very Short Answer Type Questions
Q.1
(i) Define a tree.
Ans. A tree, ‘T’, may be defined as a finite set of one or more nodes such that
a) there is a specially designated node, called the root, ‘R’, of the tree
b) the remaining nodes (excluding the root node) are partitioned into n 0 disjoint sets
T1, T2, …., Tn and each of these sets is a tree in turn. The trees T1, T2, …., Tn are
called the subtrees of the root.
What do you mean by binary search tree (BST) ? Explain it with example.
Ans. A binary search tree (BST) is a special binary tree and is defined as:
(i) every node has a key and no two nodes have the same key value
(ii) all left subtree’s keys (if any) are smaller than the root’s key
(iii) all right subtree’s keys (if any) are larger than the root’s key
(iv) the left and right subtrees of a binary search tree are itself binary search trees
62 95
51 79 73 98
38 55 83 96 99
(a) (b)
Ans. A binary tree is a specific type of tree in which each node can have a maximum of two children.
These child nodes are typically distinguished as the left and the right child. The tree made up of a left
child (of a node x) and all its descendents is called the left subtree of x. Similarly we can define right
subtrees.
B C
D E F
Figure-3
In the above binary tree, node B is the left child of node 'A', and node C is the right child of node 'A'.
Similarly D and E are the left and right child's of node B.
In this method, the nodes of a binary tree are represented as elements in an array. The node started in
array are accessible sequentially. The root node always lies at index '0'. For example:
The array representation of a binary tree is represented in an array by storing each element at the
array position corresponding to the number assigned to it.
A B C D E F G
0 1 2 3 4 5 6
The binary tree to be represented is regarded as a complete binary tree with some missing elements.
example:
Figure-4
A B C
0123456
Syntax:
struct tnode
{
struct tnode *lchild;
int info;
struct tnode *rchild;
};
B C
D E F G
What do you mean by traversing a binary tree? Explain various types of traversing
techniques and write algorithm for preorder traversal and implement the same using ‘C’.
Ans. Traversal is the process of visiting every node in a tree data structure, exactly once, in a
systematic way. Such traversals are classified by the order in which the nodes are visited. If there are
‘n’ nodes in a binary tree then there are n! different orders in which they could be visited. However a
good traversal technique visits the nodes of a tree in some linear sequence. When a node is picked
then there are three tasks to do at a given node - visit the node itself (V), traverse its left subtree (L)
or traverse its right subtree (R).
Generally the left subtree always precedes visiting the right subtree, thus there are three possible
traversal techniques known as inorder (LVR), postorder (LRV) and preorder (VLR)
respectively. Consider a simple expression tree.
+ D
A *
B C
As discussed earlier, there are three ways in which you can traverse a binary tree. They are:
a) Preorder - In Preorder, the root is visited before (pre) the subtrees traversals.
Algorithm: Preorder(Root)
Here ‘Root’ contains the address of the root node. Perform these steps if Root is
not equal to Null.
‘C’ Implementation:
Preorder(TreeNode *Root)
{
if (Root != NULL)
{
printf(“\n%c”, Root->data);
Preorder(Root->lchild);
Preorder(Root->rchild);
}
}
If this function is executed on the tree of shown in above figure then the following
output would be printed:
/ +A*BCD
b) Inorder - In Inorder, the root is visited in-between left and right subtree traversal.
Algorithm: Inorder(Root)
Here ‘Root’ contains the address of the root node. Perform these steps if Root
is not equal to Null.
1. Call Inorder(lchild(Root))
2. Print the value of data of Root node
3. Call Inorder(rchild(Root))
4. Exit
‘C’ Implementation:
Inorder(TreeNode *Root)
{
if (Root != NULL)
{
Inorder(Root->lchild);
printf(“\n%c”, Root->data);
Inorder(Root->rchild);
}
}
A+B*C/D
c) Postorder - In Postorder, the root is visited after (pre) the subtrees traversals.
Algorithm: Postorder(Root)
Here ‘Root’ contains the address of the root node. Perform these steps if Root
is not equal to Null.
1. Call Postorder(lchild(Root))
2. Call Postorder (rchild(Root))
3. Print the value of data of Root node
‘C’ Implementation:
Inorder(TreeNode *Root)
{
if (Root != NULL)
{
Inorder(Root->lchild);
printf(“\n%c”, Root->data);
Inorder(Root->rchild);
}
}
If this function is executed on the tree shown earlier then the following output would be printed:
ABC*D/+
Q. 6 Consider the given tree and write its preorder, inorder and postorder
A
B C
D E F
Ans.
Inorder Traversal – D B E A C F
Preorder Traversal – A B D E C F
Postorder Traversal – D E B F C A
Q. 7 Construct a binary tree with the following inorder and preorder traversal.
Inorder Traversal : D B A F E G C
Preorder Traversal : A B D C E F G
Ans. We know that in preorder traversal of a binary tree, the root node is visited first, therefore the
preorder sequence is looked for the node to be visited. And as far as the inorder traversal is concerned,
the root node is visited after traversing the left sub-tree. Therefore the inorder sequence is looked for
those node who are in the left subtree of the visited node and who are in the right subtree of the
visited node.
And since ‘A’ is the first node in the preorder sequence, therefore ‘A’ becomes the root node of the
binary tree. And as far as the inorder traversal is concerned, the root node is visited after traversing
the left sub-tree. Therefore all the nodes which are on the left side of ‘A’ in the given inorder
sequence belong to the left subtree and the nodes to the right of ‘A’ belong to the right subtree of the
tree as shown below:
Again if there are ‘n’ number of nodes after ‘A’ in inorder sequence then the first ‘n’ nodes after ‘A’
in preorder sequence become the preorder sequence of the left subtree. This process is applied to both
the left and right subtrees once again. Let we consider the left subtree. The preorder sequence of this
subtree suggests that ‘B’ is the root node of this left subtree. The position of ‘B’ in the inorder
sequence determines the inorder sequence of the left and the right subtree as shown below:
B Inorder: FEGC
Preorder: CEFG
D
And this process continues for the remaining set of subtrees, as follows.
B C
D
Inorder: FEG
Preorder: EFG
A
B C
D
E
F G
Chapter-6 Sorting and Searching
Q.1
(i) Define searching.
Ans. Searching is a process in which an item is searched from a set of numbers.
Ans. Identifying a particular item or a record among a set of elements or records is called as
searching. Here is the algorithm of linear searching.
SequentialSearch(A, N, Item)
Here ‘A’ is an array of ‘N’ number of elements and ‘Item’ represents the item to be searched in array
‘A’
1. Set Flag = 0
2. Initialize I = 0
3. Repeat through step-4 while (I < N)
4. Compare A[I] and item
A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9]
28 24 36 29 14 75 80 31 60 49
Then after each insertion we have the following array as shown in figure-6.5.
Passes pass-1 pass-2 pass-3 Pass-4 PASS-5 Pass-6 Pass-7 Pass-8 Pass-9
A[0] 24 24 24 14 14 14 14 14 14
A[1] 28 28 28 24 24 24 24 24 24
A[2] 36 36 29 28 28 28 28 28 28
A[3] 29 29 36 29 29 29 29 29 29
A[4] 14 14 14 36 36 36 31 31 31
A[5] 75 75 75 75 75 75 36 36 36
A[6] 80 80 80 80 80 80 75 60 49
A[7] 31 31 31 31 31 31 80 75 60
A[8] 60 60 60 60 60 60 60 80 75
A[9] 49 49 49 49 49 49 49 49 80
Long Answer Type Questions
Q. 5. Explain binary search with suitable example.
Ans. Searching is a process in which an item is searched from a set of numbers. There are basically
two searching techniques - Linear searching and Binary searching
Binary searching – In Binary Searching, searching begins from the middle of array. If the item is less
than the item which is at the mid of array then it must be searched in the top half of array, that is 0 to
mid-1. If the item is greater than the item which is at the mid of array then it must be searched in the
second half of array that is mid+1 to n-1. If both are equal then no need to search further more. This
process continues until the entire list is not further subdivided or item is found.
We perform binary searching by keeping two counter variables lower and upper. Two variables lower
and upper are used to contain the lower value and upper value of the set of elements not yet searched.
At each stage the number of elements in the remaining set is decreased by about one half. Initially we
have following values:
lower = 0;
upper = n -1;
mid = (lower + upper)/2;
otherwise
lower = 0
upper = mid-1
Here are the steps to search 34 using Binary Search in the following array:
Number 60 53 49 40 37 34 21
Index 0 1 2 3 4 5 6
(i) Initially -
low = 0 and upper = 6
mid = (low + upper)/2 = (0+6)/2 = 3
a [mid] = a [3] = 40
Here item = 34 is less than a [mid], so we will update the value of lower to mid+1. Figure (a)
shows this.
Number 60 53 49 40 37 34 21
Index 0 1 2 3 4 5 6
Low Mid Upper
(a)
Number 60 53 49 40 37 34 21
Index 0 1 2 3 4 5 6
Low Mid Upper
(b)Fi
gure - 2
Here item = 34 is equal to a [mid] as shown in figure 2(b), so the process of searching ends.
if (flag == -1)
printf("\nItem not found.");
else
printf("\nItem found at %dth position.", flag);
}
BinarySearch(int a[], int n, int item)
{
int mid, lower, upper;
lower=0;
upper=n-1;
while (lower <= upper)
{
mid = (lower+upper)/2;
if (a[mid] == item)
return (mid+1);
else if (a[mid] > item)
upper = mid-1;
else
lower = mid+1;
}
return (-1);
}
24 31 13 20 36 9 16 48 37 10 58 28
Ans. Quick sorting is a very fast method of internal sorting developed by C.A.B. Hoare in 1962. In
this an element Ai is placed in such a way that all the elements from (A0 A1 A2 A3 ....... Ai-1) are less
than Ai and all the elements from (Ai+1, Ai+2, Ai+3 ..... An-1) are equal to or greater than Ai. And this
process is called recursively for (A0 A1 A2 A3 ..... Ai-1) and (Ai+1, Ai+2, Ai+3 ...... An-1) respectively. Each
time the quick sorting function is invoked, it further divides the elements into smaller lists.
In Quick sorting, let A[First : Last] be an array to be sorted. Here we will assume two counter
variables I and J in such a way that ‘I’ refers to ‘First’ and ‘J’ refers to ‘Last’. Here ‘First’ indicates
the lower bound of an array and ‘Last’ indicates upper bound of an array. The counter variable ‘I’
moves right searching for an element, which is greater than A[I] and the counter variable ‘J’ moves
towards left for an element, which is smaller than A[I]. This process ends whenever the counter
variable “I” and “J” meet or cross over. For example, consider an array of 10 elements as shown
below:
Item 24 31 13 20 36 9 16 48 37 10 58 28
0 1 2 3 4 5 6 7 8 9 10 11
Index
Here First = 0, Last = 11 and now we have to place the first element A[First] = 24 at its proper
location. Initially ‘I’ is set to second and ‘J’ to last element of the array respectively as:
24 31 13 20 36 9 16 48 37 10 58 28
First I J
Element
Now we move ‘I’ towards right until A[I] > 24. Since A[I] > 24, therefore ‘I’ does not move further to
the right and stops immediately. Now we move ‘J’ towards left until A[J] < 22. Here ‘J moves 2 units
to the left and the scene may be as shown below:
24 31 13 20 36 9 16 48 37 10 58 28
I J
At this point, we exchange A[I] and A[J] and the movement of ‘I’ and ‘J’ resume. Now ‘I’ moves 3
units to the right and ‘J’ moves 3 units to left ass shown below:
24 10 13 20 36 9 16 48 37 31 58 28
I J
Once again A[I] and A[J] are exchanged and movement of ‘I’ and ‘J’ resume.
24 10 13 20 16 9 36 48 37 31 58 28
J I
Since the index of ‘I’ becomes greater than ‘J’, the process ends after exchanging A[J] and A[First].
The resultant array looks like the following:
9 10 13 20 16 24 36 48 37 31 58 28
Now the element 24 is placed at index ‘5’. This latest scenario of array ‘A’ clearly shows that
elements of array A[ ], which are left to ‘5’ are less than 24 and all elements which are right to
index‘5’ are greater than 24. Thus the element 22 is placed correctly. Now the above procedure is
applied on these two subarrays A[First : J-1] and A[J+1 : Last] and this process continues till the array
id not further subdivided.
Ans. Bubble sorting compares the adjacent elements and moves the largest element to the bottom of
the list. This process continues till the entire list is sorted.
Algorithm:
1. Iterates through every element of the array, starting with the first 2 elements.
2. If left element is bigger than right element, swap them.
3. Repeat step #1 and #2 until there are no more swaps.
First Pass:
29 36 11 24 55 22 no interchange
29 11 24 36 55 22 no interchange
29 11 24 36 22 55
Second Pass:
11 24 29 36 22 55 no interchange
11 24 29 22 36 55
Third Pass:
11 24 29 22 36 55 no interchange
11 24 29 22 36 55 no interchange
11 24 22 29 36 55
Fourth Pass
11 24 22 29 36 55 no interchange
11 22 24 29 36 55
Fifth Pass
11 22 24 29 36 55 no interchange
11 22 24 29 36 55
Following numbers
89, 20, 31, 56, 25, 64, 48
are to be sorted using selection sort. Show the list appear at the end of each pass.
Ans.
First Pass:
89, 20, 31, 56, 25, 64, 48 * Interchange these two number
Second Pass:
89, 20, 31, 56, 25, 64, 48 * Interchange these two number
20, 31, 89, 56, 25, 64, 48 * Interchange these two number
Third Pass:
20, 25, 89, 56, 31, 64, 48 * Interchange these two number
20, 25, 31, 56, 89, 64, 48 * Interchange these two number
Fifth Pass:
20, 25, 31, 48, 89, 64, 56 * Interchange these two number
20, 25, 31, 48, 64, 89, 56 * Interchange these two number
Sixth Pass:
20, 25, 31, 48, 56, 89, 64 * Interchange these two number
33, 40, 22, 55, 88, 60, 11, 80, 20, 50, 44, 77, 30
Ans. Merging is a process of combining two or more sorted lists into a third sorted list. Merge sort
algorithm is based on ‘divide-and-conquer’ technique in which a list is divided into sublists. This
technique may be used effectively sort a list of numbers. In merge sorting, an unsorted array A[lower
: upper] is split around its middle element , mid such that mid = (lower + upper) / 2, into two unsorted
arrays A[lower : mid] and A[mid+1 : upper]. The same procedure is applied recursively on two
unsorted arrays A[lower : mid] and A[mid+1 : upper] and finally when there are only one element left
in the array, they are merged.
66, 33, 40, 22, 55, 88, 60, 11, 80, 20, 50, 44, 77, 30
(66, 33, 40, 22, 55, 88, 60), (11, 80, 20, 50, 44, 77, 30)
((66, 33, 40, 22) , (55, 88, 60)) , ((11 ,80 ,20 ,50 ) , (44 , 77, 30))
(((66, 33) , (40, 22)) , ((55, 88) , (60))) , (((11, 80) , (20, 50)) , ((44, 77) , (30)))
(((33, 66) , (22, 40)) , ((55, 88) , (60))) , (((11, 80) , (20, 50)) , ((44, 77) , (30)))
((22, 33, 40, 66) , (55, 60, 88)) , ((11, 20, 50, 80)) , (30, 44, 77))
(22, 33, 40, 55, 60, 66, 88) , (11, 20, 30, 44, 50, 77, 80)
(11, 20, 22, 30, 33, 40, 44, 50, 55, 60, 66, 77, 80, 88)
Write Merge sort algorithm. Describe the steps to sort the following list of elements using
merge sort.
First List: 7, 15, 38, 41, 49, 53, 68, 71, 82, 90
Second List: 3, 6, 9, 14, 45, 60, 65, 70, 85
Ans. Let the name of first list is A and the second list is B. For list ‘A’, we consider the counter
variable ‘I’ and for list ‘B’ we take ‘J’. When we merge these two lists we will store it into a third list
‘C’. For list ‘C’ we take the counter variable ‘K’. Initially all these three counter variables are set to 0.
Rule: Both A[I] and B[J] are compared and smallest of these two is stored in third list and
their respective counter variables are incremented.
7 15 38 41 49 53 68 71 80 83
First List ‘A’
I=0
0 1 2 3 4 5 6 7 8 9
3 6 9 14 45 60 65 70 85
Second List ‘B’
J=0
0 1 2 3 4 5 6 7 8
Here B[J] is smaller than A[I] therefore B[J] is stored at C[K] and both ‘J’ and ‘K’ are incremented
as:
3
Third List ‘C’
K=1
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
3 6 9 14 45 60 65 70 85
Second List ‘B’
J=1
0 1 2 3 4 5 6 7 8
Again B[J] is smaller than A[I] therefore B[J] is stored at C[K] and both ‘J’ and ‘K’ are
incremented as:
3 6
Third List ‘C’
K=2
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
First List ‘A’ 7 15 38 41 49 53 68 71 80 83
I=0
0 1 2 3 4 5 6 7 8 9
In third case B[J] is larger than A[I] therefore A[I] is stored at C[K] and both ‘I’ and ‘K’
are incremented as:
3 6 7
Third List ‘C’
K=3
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
7 15 38 41 49 53 68 71 80 83
First List ‘A’
I=1 0 1 2 3 4 5 6 7 8 9
3 6 9 14 45 60 65 70 85
Second List ‘B’
J=2 0 1 2 3 4 5 6 7 8
Next B[J] is smaller than A[I] therefore B[J] is stored at C[K] and both ‘J’ and ‘K’ are incremented
as:
7 15 38 41 49 53 68 71 80 83
First List ‘A’
I=1 0 1 2 3 4 5 6 7 8 9
7 15 38 41 49 53 68 71 80 83
First List ‘A’
I=1 0 1 2 3 4 5 6 7 8 9
3 6 9 14 45 60 65 70 85
0 1 2 3 4 5 6 7 8
Second List ‘B’
J=4
7 15 38 41 49 53 68 71 80 83
First List ‘A’
I=2 0 1 2 3 4 5 6 7 8 9
7 15 38 41 49 53 68 71 80 83
First List ‘A’
I=3 5 6 7 8 9
0 1 2 3 4
7 15 38 41 49 53 68 71 80 83
First List ‘A’
I=4 0 1 2 3 4 5 6 7 8 9
And this process continues and finally we get the sorted merged list as:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18