unit1
unit1
unit1
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 areto be given and
results to be obtained. The data and actions of the functions are specified
precisely. Similarly, the purpose of studying Abstract data types is to find out
some general principles that will help in designing efficient programs. There
exists a similarity between the process of top down refinement of algorithms and
the top-down specification of the data structures. In algorithm design, we
begin with the problem and slowlyspecify more details until we develop a
complete program. In data specification, we begin with the selection of
mathematical concepts and abstract data types required for our problem, and
slowly specify more details until finally we can describe our data structures in
terms of programming language.
The application 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:
Conceptual or abstract level
Algorithmic or data structures
Programming or implementation
Applications
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
The first two levels are often called conceptual. The middle two levels can be
called algorithmic as they are concerned with representing data and the
operations performed on the same. Last level is basically concerned with
programming
at the conceptual level, the queue has been selected as an abstract data type
and further at the next level circular queue has been selected, as this could
provide the best solution. Last level shows the operations which can be
performed on the data, for the Airport simulation,
Example: “Arrays, Stacks, Queues and linked lists” are the examples
for linear data structures.
Example: “Trees & Graphs” are the examples for the non-linear data
structures.
Linear Data Structures: The data structure where data items are organized
sequentially or linearly where data elements attached one after another is
called linear data structure. Data elements in a liner data structure are
traversed one after the other and only one element can be directly reached
while traversing. All the data items in linear data structure can be traversed
in single run.
These kind of data structures are very easy to implement because memory of
computer is also organized in linear fashion.
Examples of linear data structures are:
Arrays,
Stack,
Queue
Linked List.
An arrays is a collection of data items having the same data types.
A Stack is a LIFO (Last In First Out) data structure where element that
added last will be deleted first. All operations on stack areperformed from
on end called TOP. A Queue is a FIFO (First In First Out) data structure
where element that added first will be deleted first.
In queue, insertion is performed from one end called REAR anddeletion
is performed from another end called FRONT.
A Linked list is a collection of nodes, where each node is made up of a data
element and a reference to the next node in the sequence.
Non Linear Data Structures: The data structure where data items are not
organized sequentially is called non linear data structure. In other words, A
data elements of the non linear data structure could be connected to more
than one elements to reflect a special relationship among them. All the data
elements in non linear data structure can not be traversed in single run.
Examples of non linear data structures are:
Trees
Graphs
A tree is collection of nodes where these nodes are arranged
hierarchically and form a parent child relationships.
A Graph is a collection of a finite number of vertices and an edges that
connect these vertices. Edges represent relationships among vertices
that stores data elements.
Difference Between Linear and Non Linear Data Structure:
Every item is related to its previous Every item is attached with many
and next item. other items.
Declaration of Arrays:
Syntax:
datatype array_name [no. of items];
OR
datatype array_name [index];
Ex:
int a [10]; // integer array
Note:
11 33 22 55 44 88 66 55 77 99 100 101
0 1 2 3 0 1 2 3 0 1 2 3
Initialization of array:
int a[5]={11,12,13,14,15};
int a[]={11,22,33};
char a[7]={“sairam”};
float b[4]={1.2,3.5,7};
For example, some of the valid double dimensional arrays are written as
below:
int a[10][10];
float b[50][50];
char name[10][20];
Also you can declare two-dimensional array in static form i.e. these type of array
declarations have fixed value or constant value. The syntax used for static two
dimensional array is as follows:
For example, suppose you want to assign some fixed value to a variable
array named table by using the static two-dimensional array as.
Eg:
int a[3][2][4];
Operations on Arrays:
1. Creation of array
2. Initialization of array
3. Accepting data into array
4. Displaying contents of array
5. Insertions
6. Deletions
7. Search
8. Sort
Advantages of arrays:
As arrays store all the elements in continuous locations, it becomes
easy to access all the elements.
Arrays allow the user to store elements of same type in sequential
manner.
Array elements can be accessed randomly (need not to follow any
order).
Arrays avoid no. of variables & their naming.
Disadvantages of arrays:
Array size is fixed. The user cannot grew or shrink the size
dynamically.
Optimum utilization of memory may not be achieved (i.e., there is a
scope for wasting the memory).
Arrays allow only similar kind of items as data.
Characteristics of a Data Structure
Correctness:
Data structure implementation should implement its interface correctly.
Time Complexity:
Running time or the execution time of operations of data structure must be
as small as possible.
Space Complexity:
Memory usage of a data structure operation should be as little as possible.
Operations on Data Structures: The operations involve in data
structure are as follows.
Create: Used to allocate/reserve memory for the data element(s).
Destroy: This operation de allocate /destroy the memory space
assigned to the specified data structure.
Selection: Accessing a particular data within a data structure.
Update: For updating (insertion or deletion) of data in the data
structure.
Searching: Used to find out the presence of the specified data item in
the list of data
Sorting: Process of arranging all data items either in ascending or in
descending order.
Merging: Process of combining data items of two different sorted lists
of data items into a single list.
A stack is a linear list in which insertions & deletions are made at one end
called top. Stack follows LIFO manner in order to store data. LIFO means Last
In First Out. As an example to stack, consider a set of plates placed one over
the other or a pile of books.
Operations on Stack:
Push
Pop
Show
Is empty
Is Full
4 4 4 4 4 50 4
3 3 3 3 40 3 40 3
2 2 2 30 2 30 2 30 2
1 1 20 1 20 1 20 1 20 1
0 10 0 10 0 10 0 10 0 10 0
For each insertion, we check out whether the stack is full or not. If it is
FULL stop the process otherwise continue pushing items.
Procedure to perform push operation:
Note: Here ‘MAX’ is the value of maximum number of items that can be
stored in a stack.
POP:
In pop operation, the elements of stack are removed one after other by
decrementing the value of top. Once after removing the last item from the stack,
pop operation is terminated. For each deletion, we check out whether the
stack is empty or not.
50 4 4 4 4 4 4
40 3 40 3 3 3 3 3
30 2 30 2 30 2 2 2 2
20 1 20 1 20 1 20 1 1 1
10 0 10 0 10 0 10 0 10 0 0
The stack allows display from top to bottom i.e., from top pointer only the
user can list the items.
Applications of Stack:
Used in operating systems, compilers other system software
Processor itself maintains a stack in order to execute applications.
Used for expression evaluations.
Used in regular function calls, nested function calls and recursive
function calls.
Q)Write an algorithm for infix to Postfix expression?
Step 1: start
Step 2: Initially push a left parenthesis ‘(‘ into the stack and ‘)’ added to
the given expression.
Step 3: Repeat the following procedure while the stack is not empty.
Step 4: If an operand is encountered added to the postfix expression.
Step 5: If a ‘(‘ is encountered, pushes onto the stack.
Step 6: If an operator is encountered, Repeatedly pop from the stack and
each operator is added to the postfix expression until the same
precedence operator occur on the stack.
(the operator is less than in the stack)
Step 7: If ‘)’ is encountered repeatedly pop from the stack and added to the
postfix expression until ‘(‘ and next remove the ‘(‘.
Step 8: stop.
To convert infix to post fix expression
1) (a+(b*c-(d/e^f)*g)*h)
ans) abc*def^/g*-h*+
2) 5,6,2,+,*,12,4,/,-
ans) 5 5
6 5,6
2 5,6,2
+ 5,8
* 40
12 40,12
4 40,12,4
/ 40,3
- 37
To convert Infix to Postfix
((A+B)*(D^(E-F)))
( (
(( ((
A (( A
+ ((+ A
B ((+ AB
) ( AB+
* (* AB+
( (*( AB+
D (*( AB+D
^ (*(^ AB+D
( (*(^( AB+D
E (*(^( AB+DE
- (*(^(- AB+DE
F (*(^(- AB+DEF
) (* AB+DEF-
(^
) AB+DEF-^
(*
) AB+DEF-^*
.
Example
Infix to prefix
6+9+(4*2+4^2)
Reverse Infix Expression:
)2^4+2*4(+9+6
)D+C(*)B+A(
Types of Queues:
Queues
Circular Queues
Double Ended Queues (De-Queues)
Priority Queues
Queues
A queue is a linear list where items may be inserted or deleted in FIFO manner.
FIFO means First In First Out. That is, the item placed in the first, will be accessed
and removed first from the queue. Similarly the item placed last will be accessed
and removed last. A queue uses two pointers called front, rear to perform
storage & retrieval operations.
In other words, queue has two ends: front and rear. All the insertions into queue
are made at ‘rear’ end and all the deletions are done at ‘front’ end.
Operations on Queues:
Create or Initialize a queue.
Insert an item into a queue (Insertq () or Enqueue())
Delete an item from a queue (Deleteq()).
Display all the items (show ()).
Check whether Queue is empty or not (isempty())
Check whether Queue is full or not (isfull())
Initially declaration & initializing the front and rear pointers is to be done.
Enqueue:(Insertq) Storing elements one after the other into the queue is possible
at this level of operation using the rear pointer. Increment each time an item is
placed in the queue.
Show: Displaying elements of the queue are performed in this operation because
unless the user doesn’t know what is the content of the queue, he is unable to
process other operations.
The process of adding an element into the queue is known as Enqueue. The
following steps should be taken to enqueue (insert) data into a queue .
0 1 2 3 4 0 1 2 3 4
10
r =-1 f = 0 f=r=0
10 20 10 20 30
f r f r
10 20 30 40 10 20 30 40 50
Dequeue Operation(Deletions):
This operation allows removing of elements from the queue one by one. Here we use
front end (or pointer) to remove each item. For each removal front is incremented
by 1. The process of removing items from the queue is done untilthe queue
becomes EMPTY. That is, when the queue becomes empty, the deletion process
is terminated.
f r f r
0 1 2 3 4 0 1 2 3 4
30 40 50 40 50
f r f r
0 1 2 3 4 0 1 2 3 4
50
if(front==rear)
BEGIN
front=0;rear=-1;
END
else
front=front+1;
End.
Applications of queue
There are various applications of computer science, which are performed using data
structure queue. This data structure is usually used in simulation, various
features of operating system, multiprogramming platform systems and different
type of scheduling algorithm are implemented using queues. Round robin
technique is implemented using queues. Printer server routines, various
applications software are also based on queue data structure.
The operating system itself uses a queue called an Instruction Queue & a Message
Queue.
In a network, there will be a print queue that manages the documents to be printed
Circular Queues( It is also called as “Ring buffer”.)
In regular queues, there is a situation where the user cannot insert items through
the positions are free. That is, for example, consider a queue with full of data.
f r
10 20 30 40 50 60 70
Perform Deletion operation on the above queue for 3 times. The following is the
resultant queue.
40 50 60 70
f r
Now there are 3 empty locations, but still the user cannot store any more items
because the rear pointer cannot be incremented further.
In order to overcome the above problem and to reutilize the empty locations,
circular queues have come into picture.
So that in CIRCULAR QUEUE we can again insert new values at the deleted
positions
Algorithm to insert an element in a circular queue
Step 1: IF (REAR+1)%MAX = FRONT
Write " OVERFLOW "
Goto step 4
[End OF IF]
Step 4: EXIT
Dequeue Operation
The steps of dequeue operation are given below:
First, we check whether the Queue is empty or not. If the queue is empty, we cannot perform
the dequeue operation.
When the element is deleted, the value of front gets decremented by 1.
If there is only one element left which is to be deleted, then the front and rear are reset to -1.
Algorithm to delete an element from the circular queue
Step 1: IF FRONT = -1
Write " UNDERFLOW "
Goto Step 4
[END of IF]
Step 4: EXIT
Double Ended Queue
A double-ended queue is a queue where items can be inserted & deleted at either
end. That is, we can insert elements from both rear & front ends. Again there are
2 types of double-ended queues. They are:
Applications:
Band width management : pq can be used to manage the limited resources
such as band width on transmission line from a network router
Discrete event simulation: pq is to manage events in a discrete event
simulation . The events are added to the queue with their simulation
time used as priority
Relationship to store the algorithms: the semantics of pq naturally suggested
to storing methods (heap sort)
LINKED LIST:-
DEF:-”Linked list is a dynamic and linear data structure”. A linked list is a list of
elements in which the elements of the list can be placed anywhere in memory, and these
elements are linked with each other using an explicit link field, that is, by storing the
address of the next element in the link field of the previous element.
Dynamic Allocation:-
3. Circular linked list :-Circular linked list is one which has no beginning and no end.
A single linked list can be made a circular linked list by simply storing the address of
last node to the first node of the list.
The diagrammatic representation of this list is as follows.
1) It occupy more space because every node contain a pointer to share the
address ofnext node
2) Searching a particular element in a list is a time consuming one.
Applications of linked list:-
1) Linked list are used to implement data structures such as stacks, queues, trees and
graphs
2) Linked list are used to represent very large numbers and operations of large number.
3) Linked list are used to represent to represent manipulate polynomial.
The operations that are performing on a single linked list are in the following ways.
1 .Create a list
2 .Insert an element into the list
3 .Delete an element from the list
4 .Traverse a list
1) Create a list: -To create a linked list first of all we have to check whether the list is
emptyor not. Initially the value of a header will be null. If the header is null then create
new node andassign the address of the node to header. If the header is not null then
established the links between last existing and the new node.
Algorithm:-
Step 1:- start
Newnode->data=element
Newnode->link=null
Header=new
node else
Step 6:-p=p->link
Newnode->data=element
Newnode->link=null
Head=newnode
else
Step 5:-Head=newnode
Algorithm:-
New node->data=element
New node->link=null
Head=newn
ode else
8:- End
iii) Insertion of the node middle position:-
Inserting an element in a list after a specified position of a node then we have
to findout the location of the specified node or element. If the node which you are
going to place isat the beginning then header points to the new node or if the position
you specified is the lastnode then place new node and it becomes last node. If not,
place it at the middle of the list. Algorithm:- Step 1:- start
Step 2:- Create a newnode
Newnode-
>data=element
Newnode->link=null
else
newnode->link=p-> link
Step 1: Start
Step 5:-p=p->link
Step 7:-free p;
Step 8:-stop
Step 5:-p=p->link
Step 6:-free p
Step 8:-Stop
3) Traversing of a linked list:-
Traversing a node in the list is possible only in one direction. Traversing of a linked list begins at the
first node of the list. To traverse a linked list we have to create a temporary variable of type node to
hold the address of the first node after compilation of the node it points to next node. It will be
continued until the address of the last node becomes null
The operations that are performing on a double linked list are in the following
ways.
1. . Create a list
2. Insert an element into
the list 3 . Delete an element
from the list4 . Traverse a list
1) Creation of a node:-
To create a double linked list first of all we have to check whether the list is
empty or not, if it is empty assign a new node to the header otherwise establish the links
between existing and the new node.
Algorithm:-
New node->data=num;
Return;
New node->data=num;
head=New node;
New node->data=num;
Header=new node
else
In this we first search element is there or not. It is Found then insert a new node and
assignthat address to the previous node and next node. Otherwise to display element
not found.
New node->data=element
New node->left link=null
newnode->leftlink =p
newnode->rightlink->leftlink=newnode
Step 8:- End
4) Deletion:-
Node can be deleted from the front. Replace the START pointer to next node
andrelease the links from the first node.
Algorithm :-
1. Start
2. If (head==null)
print “no nodes in doubly linked list”
3. p=head
4. head =head->rightlink
5. free p
6. head ->leftlink=NULL
7. Stop
b Deleting from End of the list:Node can be deleted at the end of the list. Make lastnode
left link as NULL
Algorithm:-
1. Start
2. if(head == null)
print “ D.L.L is empty”
else
3.p=head
4.repeat steps 5 until ( p->rightlink !=null)
5.p=p->rightlink
6.p->rightlink->leftlink=null
7.free p
8. Stop
4. Traversing:- In this we visit each and every element from first element to last
element
Algorithm: - Step 1:- START
Advantages:
1. We can traverse in both directions i.e. from starting to end and as well as
from end tostarting.
2. It is easy to reverse the linked list.
3. If we are at a node, then we can go to any node. But in linear linked list, it
is notpossible to reach the previous node.
Disadvantages:
1. It requires more space per space per node because one extra field is
required forpointer to previous node.
2. Insertion and deletion take more time than linear linked list because more
pointeroperations are required than linear linked list.
Example:-
o Else
§ Invalid POS. Node can’t be inserted
o
· Else if (POS == 1) (Now list is not empty also)
o Set PTR->NEXT = TAIL->NEXT
o Set TAIL->NEXT = PTR
· Else
1) Deletion:-
Elements can be deleted in the following ways. First of all we have to check
whetherthe given element is existed or not. There are Three positions to delete an
element.
i. Deletion at beginning of the Circular linked list.
ii. Deletion at the middle of the Circular linked list.
iii. Deletion at the end of the Circular linked list.
i. Deletion at beginning of the Circular linked list:- Element can be deleted
at thebeginning
Algorithm:-
Declare TEMP
If list have only one node
o FREE (TAIL)
TAIL = NULL
else
TEMP = TAIL->NEXT [TEMP will point to first node]
TAIL->NEXT = TAIL->NEXT->NEXT [TAIL’s next will now pointto second node]
Free (TEMP) [free the first node]
§ FREE (TEMP1)
o Else
§ Traverse the list so that TEMP1 points to last node
andTEMP2 points second last node
§ TEMP2->NEXT = NULL
§ FREE (TEMP1)
o End If;