Unit - 1 - Part-1
Unit - 1 - Part-1
UNIT - I:
Presented By
Dr. M. Ambika
AP/CSE
DATA
Data is a collection of facts, such as numbers, words, measurements, observations or just descriptions of
things.
What is Information?
Information is organized or classified data, which has some meaningful values for the receiver.
Information is the processed data on which decisions and actions are based.
Example:
Say you are given a task to prepare a table that contains the height and weight of all the students in your class. It
would look something like this:
Ansh 4’ 10” 45
Becky 4’ 7” 42
Chotu 5’ 1” 52
Divya 4’ 9” 50
Emma 5’ 0” 49
Faiz 5’ 3” 52
Girish 5’ 2” 51
• Data presentation must be easy to understand so the developer, as well as the user, can make an
efficient implementation of the operation.
• Data structures provide an easy way of organizing, retrieving, managing, and storing data.
• Primitive Data Structure or Simple Data Structure- Primitive data structures are predefined types of
data, which are supported by the programming language. These are the basic data structures and are
directly operated upon by the machine instructions, which is in a primitive level.
• It is the predefined way of storing data of one type only.
• Eg: int, float, chat, so on
• Non-Primitive Data Structure or compound data structure - Non-primitive data structures are not
defined by the programming language, but are created by the programmer. It is a more sophisticated
data structure emphasizing on structuring of a group of homogeneous (same type) or heterogeneous
(different type) data items.
• Derived from primitive data structures.
• It is a user defined data structure that store the data of different types as a single entity with the
relationship between each data item.
Non-Primitive Data Structure
Non-Primitive Data Structure is of two types.
Linear data structure
Non-linear data structure
o Restricted list (Addition and deletion of data are restricted to the ends of the list)
✓ Stack (addition and deletion at top end)
✓ Queue (addition at rear end and deletion from front end)
o General list (Data can be inserted or deleted anywhere in the list: at the beginning, in the middle or at the end)
Non-Primitive Data Structure
Non-linear data structure-
• Data structures where data elements are not placed sequentially or linearly are called non-linear data
structures
• One element can be connected to more than two adjacent elements.(Each node/element can have more than
one successor)
o Tree (Each node could have multiple successors but just one predecessor)
o Graph (Each node may have multiple successors as well as multiple predecessors)
Basic Operations of Data Structures
• Traversing
• Searching
• Insertion
• Deletion
• Sorting
• Merging
Module- A module is a self-contained component of a larger software system. Each module is a logical unit and
does a specific job. Its size kept small by calling other modules.
Modularity is the degree to which a system's components may be separated and recombined. Modularity
refers to breaking down software into different parts called modules.
Advantages of modularity
o It is easier to debug small routines than large routines.
o Modules are easy to modify and to maintain.
o Modules can be tested independently.
o Modularity provides reusability.
o It is easier for several people to work on a modular program simultaneously.
ABSTRACT DATA TYPE
• ADT is a mathematical specification of the data, a list of operations that can be carried out on that data.
• It includes the specification of what it does, but excludes the specification of how it does.
• Operations on set ADT: Union, Intersection, Size and Complement.
• ADT is an extension of modular design.
• The primary objective is to separate the implementation of the abstract data types from their function. The
program must know what the operations do, but it is actually better off not knowing how it is done.
• Stack can be represented using one dimensional array and it is probably the more popular solution.
• Here the stack is of fixed size.
• That is maximum limit for storing elements is specified.
• Once the maximum limit is reached, it is not possible to store the elements into it.
• So array implementation is not flexible and not an efficient method when resource optimization is
concerned.
Push
Push - Inserts new item to the top of the stack. After the push, the new item becomes the top.
The process of putting a new data element onto stack is known as a Push Operation. Push operation involves a
series of steps −
Step 1 − Checks if the stack is full.
Step 2 − If the stack is full, produces an error and exit.
Step 3 − If the stack is not full, increments top to point next empty space.
Step 4 − Adds data element to the stack location, where top is pointing.
Step 5 − Returns success.
Function : PUSH(S,TOP,X)
1. If TOP ≥ N
then write (‘STACK OVERFLOW’)
return
2. TOP ←TOP + 1
3. S[TOP] ←X
4. return
Pop - Deletes top item from the stack. The next older item in the stack becomes the top.
Function : POP(S,TOP,X)
1. If TOP = 0
then Write (‘STACK UNDERFLOW ON POP’)
return
2. X=S [TOP]
3. TOP ← TOP – 1
3. return (X)
note: top = top+1 , since we have first decremented. Normal process is return and the decrement
Algorithm for Peep operation
Returns the value of the ith element from the top of the stack.
Function : PEEP(S,TOP,i)
1. If TOP – i +1<= 0
then Write (‘STACK UNDERFLOW ON PEEP’)
return
2. return (S [TOP – i + 1])
Algorithm for Change operation
Changes the value of the ith element from the top of the stack to the value contained in X.
Function : PUSH(S,TOP,X i)
1. If TOP – i +1<= 0
then Write (‘STACK UNDERFLOW ON CHANGE’)
return
2. S [TOP – i + 1]) ← X
3. return
C PROGRAM – ARRAY IMPLEMENTATION OF STACK OPERATION
Peek or Top - Returns a copy of the top item on the stack, but does not delete it.
int peek()
{
return stack[top];
}
Boolean IsEmpty - Determines whether the stack is empty. IsEmpty should compare top with -1.
bool isempty() {
if(top == -1)
return true;
else
return false;
}
Boolean IsFull - Determines whether the stack is full. IsFull should compare top with MAX_ITEMS - 1.
bool isfull()
{
if(top == MAXSIZE)
return true;
else
return false;
}
#include<stdio.h>
#include<conio.h>
#define MAX 5
void push();
void pop();
void display();
int stack[MAX], top=-1, item;
void push()
{
if(top == MAX-1)
printf("Stack is full");
else
{
printf("Enter item: ");
scanf("%d",&item);
top++;
stack[top] = item;
printf("Item pushed = %d", item);
}
}
void pop()
{
if(top == -1)
printf("Stack is empty");
else
{
item = stack[top];
top--;
printf("Item popped = %d", item);
}
}
void display()
{
int i;
if(top == -1)
printf("Stack is empty");
else
{
for(i=top; i>=0; i--)
printf("\n %d", stack[i]);
}
}
APPLICATIONS OF STACKS
Expression Types
Based on the operator position, expressions are divided into THREE types. They are as follows...
1. Infix Expression
2. Postfix Expression or Reverse Polish
3. Prefix Expression or Polish
Infix Expression
• In infix expression, operator is used in between the operands.
• An infix notation is a notation in which an expression is written in a usual or normal format.
Examples
Infix to prefix conversion
1. a + b => +ab
2. a+b-c => -+abc
3. a/b+c*d-e => -+/ab*cde
4. (A+B)/(C-D) => /+AB-CD
5. A+B*(C-D) =>?
6. A*B/C*E+D =>?
7. (3+6)*24+7 =>?
Infix to postfix conversion
1. a + b => ab+
2. a+b-c => ab+c-
3. a/b+c*d-e => ab/cd*+e-
4. (A+B)/(C-D) => /+AB-CD
5. A+B*(C-D) => ?
6. A*B/C*E+D =>?
7. (3+6)*24+7 =>?
(a+b)
Evaluating arithmetic expressions
To evaluate an arithmetic expressions,
1. Convert the given infix expression to postfix expression.
2. Then evaluate the postfix expression using stack.
Infix to Postfix Conversion
To convert any Infix expression into Postfix or Prefix expression we can use the following
procedure...
1. Find all the operators in the given Infix Expression.
2. Find the order of operators evaluated according to their Operator precedence.
3. Convert each operator into required type of expression (Postfix or Prefix) in the same order.
Example
Consider the following Infix Expression...
( A + B ) * ( C - D )$
The given infix expression can be converted into postfix expression using Stack data Structure as
follows...
AB+CD-*
Conversion of infix expression into postfix expression
1. Scan the infix expression from left to right. Repeat Steps 3 to 6 for each element of expression until the stack
is empty.
2. If an operand is encountered, add it to the postfix expression.
3. If an opening parenthesis is encountered, push it onto the stack and do not remove it until closing
parenthesis is encountered.
4. If an operator 'op' is encountered, then
a. Repeatedly pop from stack and add each operator (on the top of stack) to the postfix expression
which has the same precedence as, or higher precedence than 'op'.
b. Add 'op' to stack.
5. If a closing parenthesis is encountered, then
a. Repeatedly pop from stack and add to postfix expression (on the top of stack) until an opening
parenthesis is encountered.
b. Remove the opening parenthesis from the stack. [Do not add the opening parenthesis to postfix
expression.]
Infix to postfix conversion
1. A+B*C-D/E => ?
2. 10+3*5/(16-4) =?
3. 5 * 3 ** (4-2) =>5 3 4 2 - ** *
4. a+b*c+(d*e +f)*g =?
5. A * B +(C-D/E) =?
Postfix Expression Evaluation using Stack Data Structure
A postfix expression can be evaluated using the Stack data structure. To evaluate a postfix expression
using Stack data structure we can use the following steps...
1. Scan the postfix expression from left to right and repeat steps 2 & 3 for each element of postfix expression.
2. If an operand is encountered, push it onto the stack.
3. If an operator 'op' is encountered,
a. Pop two elements from the stack, where A is the top element and B is the next top element.
b. Evaluate B 'op' A.
c. Push the result onto stack.
4. The evaluated value is equal to the value at the top of the stack.
Postfix Evaluation
1. (5+3)*(8-2) => 5 3 + 8 2 - * = 48
2. 4 5 6 * + = 34
3. 2 * (5 *(3+6))/5-2 => 2 5 3 6 + * * 15 / 2- => 16
4. 17 10 + 3 * 9 / =?
Conditions
• Queue overflow - The condition resulting from trying to enqueue an element onto a full Queue.
• Queue underflow - The condition resulting from trying to dequeue an element from an empty Queue.
Implementation of Queue
1. Array implementation
2. Linked list implementation
Queue Animation
Array implementation of Linear Queue
Array implementation of Linear Queue
Enqueue Operation
Enqueue – Insert an item at the rear end of the queue.
The following steps should be taken to enqueue (insert) data into a queue −
Step 1 − Check if the queue is full.
Step 2 − If the queue is full, produce overflow error and exit.
Step 3 − If the queue is not full, increment rear pointer to point the next empty space.
Step 4 − Add data element to the queue location, where the rear is pointing.
Step 5 − return success.
Algorithm for Enqueue operation
Function : QINSERT(Q,FRONT,REAR,N,X)
1. If REAR ≥ N
then write (‘QUEUE OVERFLOW’)
return
2. REAR ←REAR + 1
3. Q[REAR] ←X
4. If FRONT=0
then FRONT ← 1
return
Note:
Q – Queue Q
FRONT – Front element of the queue
REAR – Rear element of the queue
N – Queue size
X – element to be inserted
Dequeue Operation
Dequeue- Delete an item at the front end of the queue and return.
The following steps are taken to perform dequeue operation −
Step 1 − Check if the queue is empty.
Step 2 − If the queue is empty, produce underflow error and exit.
Step 3 − If the queue is not empty, access the data where front is pointing.
Step 4 − Increment front pointer to point to the next available data element.
Step 5 − Return success.
Algorithm for Dequeue operation
Function : QDELETE(Q,FRONT,REAR,Y)
1. If FRONT=0
then write (‘QUEUE UNDERFLOW’)
return
2. Y ← Q[FRONT]
3. If FRONT = REAR
then FRONT ← REAR ← 0
else FRONT ← FRONT + 1
4. return (Y)
C PROGRAM – ARRAY IMPLEMENTATION OF QUEUE OPERATION
peek() − Gets the element at the front of the queue without removing it.
int peek()
{
return queue[front];
}
void enqueue();
void dequeue();
void display();
Now consider the following situation after deleting three elements from the queue...
• This situation also says that Queue is Full and we cannot insert the new element because 'rear' is still at last position.
• In the above situation, even though we have empty positions in the queue we can not make use of them to insert the new element.
• This is the major problem in a normal queue data structure.
• To overcome this problem we use a circular queue data structure.
Circular Queue
• Circular Queue is a linear data structure in which the operations are performed based on FIFO (First In First
Out) principle and the last position is connected back to the first position to make a circle. It is also
called ‘Ring Buffer’.
• In circular queues the elements Q[0],Q[1],Q[2] .... Q[n – 1] is represented in a circular fashion with Q[1]
following Q[n].
• A circular queue is one in which the insertion of a new element is done at the very first location of the queue
if the last location at the queue is full.
Circular Queue cont…
Initially Front = Rear = -1. That is, front and rear are at the same position.
At any time the position of the element to be inserted will be calculated by the relation:
Rear = (Rear + 1) % SIZE
After deleting an element from circular queue the position of the front end is calculated by the relation:
Front= (Front + 1) % SIZE.
After locating the position of the new element to be inserted, rear, compare it with front.
If Rear = Front, the queue is full and cannot be inserted anymore.
No of elements in a queue = (Rear – Front + 1) % N
Circular Queue Animation
Operations on Circular Queue:
enQueue(value) This function is used to insert an element into the circular queue.
In a circular queue, the new element is always inserted at Rear position.
• Check whether queue is Full – Check ((rear == SIZE-1 && front == 0) || (rear == front-1)).
• If it is full then display Queue is full.
• If queue is not full then, check if (rear == SIZE – 1 && front != 0) if it is true then set rear=0 and
insert element.
deQueue() This function is used to delete an element from the circular queue.
In a circular queue, the element is always deleted from front position.
• Check whether queue is Empty means check (front==-1).
• If it is empty then display Queue is empty. If queue is not empty then step 3
• Check if (front==rear) if it is true then set front=rear= -1 else check if (front==size-1), if it is true then
set front=0 and return the element.
Home work
• Write a C++ program to perform operations in the circular queue.
Deque - Double Ended QUEeue
Definition
• A deque is a homogeneous list in which inserted and deleted operations are performed at either ends of the
queue.
• That is, we can add a new element at the rear or front end and also we can remove an element from both
front and rear end.
• Hence it is called double ended queue.
• The most common ways of representing deque are: doubly linked list, circular list.
Types of deques
1. Input restricted deque
2. Output restricted deque
Deque - Double Ended QUEeue
• An input restricted deque is a deque, which allows insertion at only 1 end, rear end, but allows deletion at
both ends, rear and front end of the lists.
• An output-restricted deque is a deque, which allows deletion at only one end, front end, but allows
insertion at both ends, rear and front ends, of the lists.
Priority Queue
Definition
• Priority Queue is a queue where each element is assigned a priority. The priority may implicit (decided by its
value) or explicit (assigned). In priority queue, the elements are deleted and processed by following rules.
O An element of higher priority is processed before any element of lower priority.
o Two elements with the same priority are processed according to the order in which they were inserted to
the queue.