Data Structures and Algorithms
Data Structures and Algorithms
Algorithms
Contents:
Records, Arrays, Stacks,
Queues, Priority Queues
(Heaps), Deque and
Evaluation of expressions
Terminology
Data Types
Refer to the different kinds of data that
a variable may hold in a programming
language.
Examples: integer, real, float, char,
string
Data Objects
2-dimensional arrays:
A[i][j] = + [(i) * (N2) + (j)] * esize
where: N2 = number of columns
3-dimensional arrays:
A[i][j][k] = + [(i) * (N2) *(N3) + (j)*(N3)
+ (k)] * esize
where: N2 = num of elems in 2nd dimension;
N3 = num of elems in 3rd dimension
esize = element size in bytes
•one-dimensional array
•singly linked-list
a b a c d e a
top
a b c e
top
Declaration
#define n <constant value>;
typedef <data type> elementtype;
typedef elementtype Stack[n];
Example:
Processing of procedure calls and their
terminations
Procedures for Stack
Operations:
void create(int *top)
{ *top = -1;}
Expression: (A + B * C) / D
Prefix: /+A*BC D
Postfix: ABC*+ D/
Conversion from infix to postfix
using stacks
IN-Stack Priority (ISP) - the priority of the
operator as an element of the stack
IN-Coming Priority (ICP) - the priority of
the operator as current token.
SYMBOL ISP ICP
) ----- -----
^ 3 4
*, / 2 2
+, - 1 1
( 0 4
RULE:
in the queue.
Initial value: Front = Rear = -1
Operations:
Createq(Front, Rear) - creates an
empty queue
Insert(Queue, Rear, Item) - inserts the
one-dimensional array
singly linked-list
a b a c d e a
front rear
a b c e
rear front
Declaration
Notes:
QUEUEFULL signal does not necessary
imply that there are N elements in the
queue.
To solve this, move the entire queue to
the left so that the first element is again
at Q[0] and front = -1.
Circular Queues
.. n-1
.. 0
4 1
3 2
Int cquempty()
{ if front== rear return 1
else return 0
}
Priority Queues (Heaps)
A special kind of queue in which deletion
of items from any position of the queue is
based on some conditions.
For instance, given a line printer, jobs are
sent to the printer queue. If a particular
job has a higher priority, then it is
reasonably to execute this job first than
other jobs in the queue.
If there are several one-page jobs and one
hundred-page job, it might be reasonable to
make the long job go last, even it is not the
last job submitted.
Deque
Double-ended queue is a linear list in which insertions and
deletions are made to or from either end of the structure.
deletion insertion
insertion deletion
Exercises
Convert the following infix expressions to
postfix and prefix.
1. A+B*C/D
2. A/B^C+D*E-A* C
3. (A+B)*D+E/(F+A*D)+C
4. A+B*D^E^F^G/H^J*K-L
5. !(A&&!(B<C)||(C>D))||(C<E)
Prefix to infix
1. - + - ^ A B C * D ^ E F G
2. ^ + - A B C + D - E F
3. || || && A B C ! <= E F
Postfix to Infix
1. A B + C D E - F + * G - /
2. A B - C + D E F - + ^
3. A B && C || E F <= ! ||
Infix to Postfix use of Stack
1. B+C^(E+F*G^H)/(K-L/M)+N
2. B+C/D^(E+F*G^H)+Z
3. A+B-C*D*(E+F-G*H^I^J) + L/M+
(N*O/P+(Q^R^S^T))+U