Module 2
Module 2
Structures
Module:2
Content
• Computer programming language & types,
• machine and assembly languages, high-level language.
Data Structures:
• Introduction to Data Structures,
• Arrays,
• Stacks,
• Queues.
Computer programming language & types
• The languages that are used to write a program or set of instructions are called "Programming
languages".
• Programming languages are broadly categorized into three types − Machine level language(Low
level). Assembly level language(Middle level). High-level language.
• Computer programming language, any of various languages for expressing a set of detailed
instructions for a digital computer.
• Such instructions can be executed directly when they are in the computer manufacturer-specific
numerical form known as machine language, after a simple substitution process when expressed
in a corresponding assembly language, or after translation from some “higher-level” language.
• Although there are many computer languages, relatively few are widely used.
• Machine and assembly languages are “low-level,” requiring a programmer to manage explicitly all
of a computer’s features of data storage and operation.
• In contrast, high-level languages shield a programmer from worrying about such considerations
and provide a notation that is more easily written and read by programmers.
Types of computer programming languages
There are basically three types of computer programming languages, they are
• These are the machine independent programming languages, which are easy to
write, read, edit and understand.
• The languages like Java, .Net, Pascal, COBOL, C++, C, C# and other (which are
very popular now to develop user end applications). These languages come under
the high level programming language category.
• High level programming languages have some special keywords, functions and
class libraries by using them we can easily build a program for the computer.
• Computer does not understand program written in such languages directly, as I
have written above that computer understands only Machine code. So, here
programming translators are required to convert a high level program to its
equivalent Machine code.
• Programming translators such as Compilers and Interpreters are the system
software’s which converts a program written in particular programming
languages to its equivalent Machine code.
FEATURES OF HIGH LEVEL PROGRAMMING
LANGUAGES
• The programs are written in High Level programming languages and are
independent that means a program written on a system can be run on
another system.
• Easy to understand - Since these programming languages have keywords,
functions, class libraries (which are similar to English words) we can
easily understand the meaning of particular term related to that
programming language.
• Easy to code, read and edit - The programs written in High Level
programming languages are easy to code, read and edit. Even we can
edit programs written by other programmers easily by having little
knowledge of that programming language.
• Since, High Level language programs are slower than Low level language
programs; still these programming languages are popular to develop
Various - High Level languages
Algorithmic languages
• Algorithmic languages are designed to express mathematical or
symbolic computations.
• They can express algebraic operations in notation similar to
mathematics and allow the use of subprograms that package
commonly used operations for reuse. They were the first high-level
languages.
FORTRAN
• COBOL
• COBOL (common business oriented language) has been heavily used by businesses since its
inception in 1959.
• A committee of computer manufacturers and users and U.S. government organizations established
CODASYL (Committee on Data Systems and Languages) to develop and oversee the language
standard in order to ensure its portability across diverse systems.
• COBOL uses an English-like notation—novel when introduced.
• Business computations organize and manipulate large quantities of data, and COBOL introduced
the record data structure for such tasks.
• A record clusters heterogeneous data—such as a name, an ID number, an age, and an address—
into a single unit.
• This contrasts with scientific languages, in which homogeneous arrays of numbers are common.
Records are an important example of “chunking” data into a single object, and they appear in
nearly all modern languages.
SQL
• As we have discussed above, anything that can store data can be called as a data
structure, hence Integer, Float, Boolean, Char etc, all are data structures. They
are known as Primitive Data Structures.
• Then we also have some complex Data Structures, which are used to store large
and connected data. Some example of Abstract Data Structure are :
• Linked List
• Tree
• Graph
• Stack, Queue etc.
• All these data structures allow us to perform different operations on data. We
select these data structures based on which type of operation is required.
The data structures can also be classified on
the basis of the following characteristics:
Characterstic Description
Linear In Linear data structures,the data items are arranged
in a linear sequence. Example: Array
Non-Linear In Non-Linear data structures,the data items are not
in sequence. Example: Tree, Graph
Homogeneous In homogeneous data structures,all the elements are
of same type. Example: Array
Non-Homogeneous In Non-Homogeneous data structure, the elements
may or may not be of the same type.
Example: Structures
Static Static data structures are those whose sizes and
structures associated memory locations are fixed, at
compile time. Example: Array
Dynamic Dynamic structures are those which expands or
shrinks depending upon the program need and its
execution. Also, their associated memory locations
changes. Example: Linked List created using
pointers
Data Structure vs Storage Structure
21
Classification
• Data Structure
• Linear
• Non-Linear
22
Representation in Memory
• Two basic representation in memory
• Have a linear relationship between the elements represented by means of
sequential memory locations [ Arrays]
23
Operation on Linear Structure
• Traversal : Processing each element in the list
• Search : Finding the location of the element with a given value or the
record with a given key
• Insertion: Adding a new element to the list
• Deletion: Removing an elements from the list
• Sorting : Arranging the elements in some type of order
• Merging : Combining two list into a single list
24
Array
25
Linear Arrays
• A linear array is a list of a finite number of n homogeneous data
elements ( that is data elements of the same type) such that
• The elements are of the arrays are referenced respectively by an index set
consisting of n consecutive numbers
• The elements of the arrays are stored respectively in successive memory
locations
26
Linear Arrays
• The number n of elements is called the length or size of the array.
• The index set consists of the integer 1, 2, … n
• Length or the number of data elements of the array can be obtained
from the index set by
Length = UB – LB + 1 where UB is the largest index called the upper
bound and LB is the smallest index called the lower bound of the
arrays
27
Linear Arrays
• Element of an array A may be denoted by
• Subscript notation A1, A2, , …. , An
• Parenthesis notation A(1), A(2), …. , A(n)
• Bracket notation A[1], A[2], ….. , A[n]
28
Representation of Linear Array in Memory
1000
1001
1002
1003
1004
1005
:
Computer Memory
29
Representation of Linear Array in Memory
• Let LA be a linear array in the memory of the computer
• LOC(LA[K]) = address of the element LA[K] of the array LA
• The element of LA are stored in the successive memory cells
• Computer does not need to keep track of the address of every
element of LA, but need to track only the address of the first element
of the array denoted by Base(LA) called the base address of LA
30
Representation of Linear Array in Memory
• LOC(LA[K]) = Base(LA) + w(K – lower bound) where w is the number
of words per memory cell of the array LA [w is aka size of the data
type]
31
Example 1
200 LA[1]
Find the address for LA[6] 201 LA[2]
Each element of the array occupy
202 LA[3]
1 byte
203 LA[4]
204 LA[5]
205 LA[6]
206 LA[7]
207 LA[8]
34
Traversing Linear Arrays
• Traversing is accessing and processing (aka visiting ) each element of
the data structure exactly ones
Linear Array
•••
35
Traversing Linear Arrays
• Traversing is accessing and processing (aka visiting ) each element of
the data structure exactly ones
Linear Array
•••
36
Traversing Linear Arrays
• Traversing is accessing and processing (aka visiting ) each element of
the data structure exactly ones
Linear Array
•••
37
Traversing Linear Arrays
• Traversing is accessing and processing (aka visiting ) each element of
the data structure exactly ones
Linear Array
•••
38
Traversing Linear Arrays
• Traversing is accessing and processing (aka visiting ) each element of
the data structure exactly ones
Linear Array
•••
39
Traversing Linear Arrays
• Traversing is accessing and processing (aka visiting ) each element of
the data structure exactly ones
Linear Array
•••
40
Traversing Linear Arrays
• Traversing is accessing and processing (aka visiting ) each element of
the data structure exactly ones
Linear Array
•••
1. Repeat for K = LB to UB
Apply PROCESS to LA[K]
[End of Loop]
2. Exit 41
Inserting and Deleting
• Insertion: Adding an element
• Beginning
• Middle
• End
42
Insertion
1 Brown 1 Brown
2 Davis 2 Davis
3 Johnson 3 Johnson
4 Smith 4 Smith
5 Wagner 5 Wagner
6 6 Ford
7 7
8 8
43
Insertion
1 Brown 1 Brown 1 Brown 1 Brown
2 Davis 2 Davis 2 Davis 2 Davis
3 Johnson 3 Johnson 3 Johnson 3 Ford
4 Smith 4 Smith 4 4 Johnson
5 Wagner 5 5 Smith 5 Smith
6 6 Wagner 6 Wagner 6 Wagner
7 7 7 7
8 8 8 8
45
Deletion
1 Brown 1 Brown 1 Brown
1 Brown
2 Davis 2 2 Ford
2 Ford
3 Ford 3 Ford 3
3 Johnson
4 Johnson 4 Johnson 4 Johnson
4
5 Smith 5 Smith 5 Smith
5 Smith
6 Taylor 6 Taylor 6 Taylor
6 Taylor
7 Wagner 7 Wagner 7 Wagner
7 Wagner
8 8 8
8
46
Deletion
1 Brown
2 Ford
3 Johnson
4 Smith
5 Taylor
6 Wagner
7
8
47
Insertion Algorithm
• INSERT (LA, N , K , ITEM) [LA is a linear array with N
elements and K is a positive integers such that K ≤ N. This
algorithm insert an element ITEM into the Kth position in LA ]
1. [Initialize Counter] Set J := N
2. Repeat Steps 3 and 4 while J ≥ K
3. [Move the Jth element downward ] Set LA[J + 1] :=
LA[J]
4. [Decrease Counter] Set J := J -1
5 [Insert Element] Set LA[K] := ITEM
6. [Reset N] Set N := N +1;
7. Exit
48
Deletion Algorithm
• DELETE (LA, N , K , ITEM) [LA is a linear array with N
elements and K is a positive integers such that K ≤ N. This
algorithm deletes Kth element from LA ]
1. Set ITEM := LA[K]
2. Repeat for J = K to N -1:
[Move the J + 1st element upward] Set LA[J] := LA[J + 1]
3. [Reset the number N of elements] Set N := N - 1;
4. Exit
49
Multidimensional Array
• One-Dimensional Array
• Two-Dimensional Array
• Three-Dimensional Array
• Some programming Language allows as many as 7 dimension
50
Two-Dimensional Array
• A Two-Dimensional m x n array A is a collection of m .
n data elements such that each element is specified
by a pair of integer (such as J, K) called subscript with
property that
1 ≤ J ≤ m and 1 ≤ K ≤ n
51
2D Arrays
The elements of a 2-dimensional array a is shown as below
55
2D Array in Memory
A Subscript A Subscript
(1,1) (1,1)
(2,1) (1,2)
Column 1 Row 1
(3,1) (1,3)
(1,2) (1,4)
(2,2) Column 2 (2,1)
(3,2) (2,2)
(1,3) Row 2
(2,3)
(2,3) Column 3 (2,4)
(3,3) (3,1)
(1,4) (3,2) Row 3
(2,4) Column 4 (3,3)
(3,4) (3,4)
• LOC(A[J,K]) of A[m,n]
Column-Major Order
LOC(A[J,K]) = Base(A) + w[m(K-1) + (J-1)]
Row-Major Order
LOC(A[J,K]) = Base(A) + w[n(J-1) + (K-1)]
57
Stack
58
Basic Idea
• A stack is an Abstract Data Type (ADT), commonly
used in most programming languages. It is named stack
as it behaves like a real-world stack, for example – a
deck of cards or a pile of plates, etc.
59
Stack Representation
pop
create
STACK
isempty
isfull
61
STACK: Last-In-First-Out (LIFO)
• void push (stack *s, int element);
/* Insert an element in the stack */
• int pop (stack *s);
/* Remove and return the top
element */
• void create (stack *s);
/* Create a new stack */
• int isempty (stack *s);
/* Check if stack is empty */
• int isfull (stack *s);
Assumption: stack contains integer elements!
/* Check if stack is full */
62
Stack using Array
63
Push using Stack
PUSH
top
top
64
Pop using Stack
POP
top
top
65
Stack using Linked List
66
Push using Linked List
PUSH OPERATION
top
67
Pop using Linked List
POP OPERATION
top
68
Basic Idea
• In the array implementation, we would:
• Declare an array of fixed size (which determines the maximum
size of the stack).
69
Declaration
70
Stack Creation
71
Pushing an element into stack
void push (stack *s, int element) void push (stack **top, int element)
{ {
stack *new;
if (s->top == (MAXSIZE-1))
{ new = (stack *)malloc (sizeof(stack));
printf (“\n Stack overflow”); if (new == NULL)
exit(-1); {
} printf (“\n Stack is full”);
exit(-1);
else
}
{
s->top++; new->value = element;
s->st[s->top] = element; new->next = *top;
} *top = new;
}
}
72
Popping an element from stack
int pop (stack **top)
{
int pop (stack *s) int t;
{ stack *p;
if (s->top == -1) if (*top == NULL)
{ {
printf (“\n Stack underflow”); printf (“\n Stack is empty”);
exit(-1);
exit(-1); }
} else
else {
{ t = (*top)->value;
p = *top;
return (s->st[s->top--]); *top = (*top)->next;
} free (p);
} return t;
}
}
73
Checking for stack empty
74
Checking for Stack Full
75
Example: A Stack using an Array
#include <stdio.h>
#define MAXSIZE 100
struct lifo
{
int st[MAXSIZE];
int top;
};
typedef struct lifo stack;
main() {
stack A, B;
create(&A);
create(&B);
push(&A,10);
push(&A,20);
push(&A,30);
push(&B,100);
push(&B,5);
printf (“%d %d”, pop(&A), pop(&B));
push (&A, pop(&B));
if (isempty(&B))
printf (“\n B is empty”);
return;
}
76
Example: A Stack using Linked List
#include <stdio.h>
struct lifo
{
int value;
struct lifo *next;
};
typedef struct lifo stack;
main() {
stack *A, *B;
create(&A);
create(&B);
push(&A,10);
push(&A,20);
push(&A,30);
push(&B,100);
push(&B,5);
printf (“%d %d”, pop(&A), pop(&B));
push (&A, pop(&B));
if (isempty(B))
printf (“\n B is empty”);
return;
}
77
Applications of Stacks
• Direct applications:
• Page-visited history in a Web browser
• Undo sequence in a text editor
• Chain of method calls in the Java Virtual Machine
• Validate XML
• Indirect applications:
• Auxiliary data structure for algorithms
• Component of other data structures
78
Infix and Postfix Notations
• Infix: operators placed between operands:
A+B*C
• Postfix: operands appear before their operators:-
ABC*+
• There are no precedence rules to learn in postfix
notation, and parentheses are never needed
79
Infix to Postfix
Infix Postfix
A+B AB+
A+B*C ABC*+
(A + B) * C AB+C*
A+B*C+D ABC*+D+
(A + B) * (C + D) AB+CD+*
A*B+C*D AB*CD*+
A+B* C 🡪 (A + (B * C)) 🡪 (A + (B C *) ) 🡪 A B C * +
80
Infix to postfix conversion
• Use a stack for processing operators (push and pop
operations).
• Scan the sequence of operators and operands from left
to right and perform one of the following:
• output the operand,
• push an operator of higher precedence,
• pop an operator and output, till the stack top contains
operator of a lower precedence and push the present
operator.
81
The algorithm steps
1. Print operands as they arrive.
2. If the stack is empty or contains a left parenthesis on top, push the incoming operator onto the
stack.
3. If the incoming symbol is a left parenthesis, push it on the stack.
4. If the incoming symbol is a right parenthesis, pop the stack and print the operators until you
see a left parenthesis. Discard the pair of parentheses.
5. If the incoming symbol has higher precedence than the top of the stack, push it on the stack.
6. If the incoming symbol has equal precedence with the top of the stack, use association. If the
association is left to right, pop and print the top of the stack and then push the incoming
operator. If the association is right to left, push the incoming operator.
7. If the incoming symbol has lower precedence than the symbol on the top of the stack, pop the
stack and print the top operator. Then test the incoming operator against the new top of stack.
8. At the end of the expression, pop and print all operators on the stack. (No parentheses should
remain.)
82
Infix to Postfix Conversion
Requires operator precedence information
Operands:
Add to postfix expression.
Close parenthesis:
pop stack symbols until an open parenthesis appears.
Operators:
Pop all stack symbols until a symbol of lower precedence appears. Then push
the operator.
End of input:
Pop all remaining stack symbols and add to the expression.
83
Infix to Postfix Rules
Current Operator Postfix string
Expression: symbol Stack
1 A A
A * (B + C * D) + E 2 * * A
3 ( *( A
becomes
4 B *( AB
ABC D * +* E+ 5 + *(+ AB
6 C *(+ ABC
7 * *(+* ABC
8 D *(+* ABCD
Postfix notation 9 ) * ABCD*+
is also called as
10 + + ABCD*+*
Reverse Polish
Notation (RPN) 11 E + ABCD*+*E
12 ABCD*+*E+
84
Queue
85
Basic Idea
• Queue is an abstract data structure, somewhat similar to
Stacks. Unlike stacks, a queue is open at both its ends.
One end is always used to insert data (enqueue) and the
other is used to remove data (dequeue).
86
Queue Representation
dequeue
create
QUEUE
isempty
size
88
QUEUE: First-In-First-Out (FIFO)
void enqueue (queue *q, int element);
/* Insert an element in the queue */
int dequeue (queue *q);
/* Remove an element from the queue */
queue *create();
/* Create a new queue */
int isempty (queue *q);
/* Check if queue is empty */
int size (queue *q);
/* Return the no. of elements in queue */
89
Queue using Linked List
90
Basic Idea
• Basic idea:
• Create a linked list to which items would be added to one end
and deleted from the other end.
• Two pointers will be maintained:
• One pointing to the beginning of the list (point from where
elements will be deleted).
• Another pointing to the end of the list (point where new
elements will be inserted).
Rear
ENQUEUE
front rear
92
Queue: Linked List Structure
DEQUEUE
front rear
93
Example :Queue using Linked List
struct qnode
{
int val;
struct qnode *next;
};
struct queue
{
struct qnode *qfront, *qrear;
};
typedef struct queue QUEUE;
94
Example :Queue using Linked List
int size (queue *q)
{
queue *q1;
int count=0;
q1=q;
while(q1!=NULL) int dequeue (queue *q)
{ {
q1=q1->next; int val;
count++; queue *q1,*prev;
} q1=q;
return count; while(q1->next!=NULL)
} {
prev=q1;
q1=q1->next;
}
val=q1->val;
int peek (queue *q) prev->next=NULL;
{ free(q1);
queue *q1; return (val);
q1=q; }
while(q1->next!=NULL)
q1=q1->next;
return (q1->val);
}
95
Problem With Array Implementation
• The size of the queue depends on the number and
order of enqueue and dequeue.
• It may be situation where memory is available but
enqueue is not possible.
ENQUEUE DEQUEUE
Effective queuing storage area of array gets reduced.
0 N
front
front rearrear
• Indirect applications:-
• Auxiliary data structure for algorithms
• Component of other data structures
97