Date post: | 14-Dec-2015 |
Category: |
Documents |
Upload: | allyson-simpson |
View: | 215 times |
Download: | 1 times |
Stacks• Stack is a data structure that can be
used to store data which can later be retrieved in the reverse or last in first out (LIFO) order.
• Stack is an ordered-list in which all the insertions and deletions are made at one end to maintain the LIFO order. (Stack is LIFO data structure)
Race([email protected])
Race([email protected])
Stacks• The operations defined on a stack are:
• Push - Store onto a stack• Pop - retrieve from stack• Top - examine the top element in
the stack• Is_empty - check if the stack is empty• Is_Full - check if the stack is full
• A stack can be very easily implemented using arrays.
• Can also be implemented using linked list • Stack is implemented by maintaining a pointer
to the top element in the stack. This pointer is called the stack pointer.
• Linked implementation will be discussed later.Race([email protected])
Stacks – Array Implementation
If a stack is implemented using arrays, the following two conventions can be used:
• A stack can grow upwards, i.e., from index 0 to the maximum index, or it can grow downwards, i.e., from the maximum index to index 0.
• Stack pointer can point to the last element inserted into the stack or it can point to the next available position.
Race([email protected])
6
8
3
12
6
5
4
3
2
1
0
7
8
9
Growing Downwards Initial state: stk_ptr = MAX - 1
• stk_ptr points to the next empty location
• Pop – first increment stk_ptr and then take data out
• Push – first add data to the stack, then decrement stk_ptr
Race([email protected])
6
8
3
12
6
5
4
3
2
1
0
7
8
9
Growing Downwards Initial state: stk_ptr = MAX
• stk_ptr points to the last element added to the stack
• Pop – first take data out and then increment stk_ptr
• Push – first decrement the stk_ptr and then add data
Race([email protected])
6
4
5
2
7
6
5
4
3
2
1
0
7
8
9
Growing Upwards Initial state: stk_ptr = 0
• Push – first add data to the stack then increment stk_ptr
• Pop – first decrement stk_ptr and then take data out
• stk_ptr points to the next empty location
Race([email protected])
6
4
5
2
7
6
5
4
3
2
1
0
7
8
9
Growing Upwards Initial state: stk_ptr = -1
• Push – first increment the stk_ptr and then add data
• Pop – first take data out and then decrement stk_ptr
• stk_ptr points to the last element added to the stack
Race([email protected])
Stacks – Array Implementation
class Stack {
private:
int maxSize; // maximum storage
capacity
int stk_ptr; // stack pointer
int *stackArray; // array used to implement stack
public:
Stack(int s ); // constructor
~Stack() {delete [ ] stackArray; } // destructor
bool push (int); // add an element to the stack
bool pop(int &); // remove an element from stack
bool isFull(); // check if the stack is full
bool isEmpty(); // check if the stack is empty
};
Race([email protected])
bool Stack::push(int n)
{
if (! isFull() ) {
stackArray[stk_ptr] = n;
stk_ptr = stk_ptr + 1;
return true;
}
else return false;
}
bool Stack::pop(int &n)
{
if (! IsEmpty ()) {
stk_ptr = stk_ptr – 1;
n = stackArray[stk_ptr];
return true;
}
else return false;
}
bool Stack::isEmpty()
{
return (stk_ptr == 0);
}
Stack::Stack(int s)
{
maxSize = s;
stk_ptr = 0;
stackArray = new int[maxSize];
}bool Stack::isFull()
{
return (stk_ptr == maxSize);
}
Race([email protected])
Applications of stack
• Is used in recursion
• Used in expression evaluation
• Used for string comparisons
• Used in function calling
• Used in memory manipulation to store addresses
• Used in tree manipulation
• etc. Race([email protected])
Multiple Stack
• More than one stacks can be implemented on a single one dimensional array
• Size of each array can be equal or different
• Number of arrays can be fixed or varying
• Simple implementation consists of two arrays of . Size of each array can not be predicted
Race([email protected])
Queues• Queue is a data structure that can be used to store data which can
later be retrieved in the first in first out (FIFO) order.
• Queue is an ordered-list in which all the insertions and deletions are made at two different ends to maintain the FIFO order.
• The operations defined on a Queue are:
• Add/ Insert - Store onto a Queue
• Remove/ Delete - retrieve (delete) from Queue
• isEmpty - check if the Queue is empty
• isFull - check if the Queue is full
• A Queue can be very easily implemented using arrays.
• Queue is implemented by maintaining one pointer to the front element in the Queue and another pointer pointing to the rear of the Queue.
• Insertions are made at the rear and deletions are made from the front.
Race([email protected])
Uses of Queue
• Many real life applications (banks, bill paying in
shopping malls, etc)
• Process Scheduling
• Memory Management
• Trees traversing
• etc
Race([email protected])
Queues – Array Implementation
class Queue {public:
Queue(int s = 10); // constructor - default size = 10~Queue() {delete [ ] QueueArray; } // destructorbool add (int n);bool remove (int &n);bool isFull() {return size == MaxSize;}bool isEmpty() {return size == 0; }
private:int maxSize; // max Queue sizeint front, rear;int *QueueArray;int size; // no. of elements in the Queue
};Race([email protected])
Queue::Queue(int s)
{
if (s <= 0) maxSize = 10; else maxSize = s;
QueueArray = new int[maxSize];
size = 0;
rear = 0; // points to the last element
front = 0; // points to first element
}
Race([email protected])
bool Queue::add(int n)
{
if (! isFull() ) {
QueueArray[rear] = n;
rear++;
size++;
return true;
}
else return false;
}
Race([email protected])
bool Queue::remove(int &n)
{
if (! isEmpty() {
n = QueueArray[front];
front++;
size--;
return true;
}
else return false;
}
Race([email protected])
• Assume maxSize = 5
• Initial conditionsize = 0; front = 0; rear = 0;
• Add 3, remove 1size = 2; front = 1; rear = 3;
Race([email protected])
• Add 2 more, remove 1 moresize = 3; front = 2; rear = 5;
• Question: Is the Queue Full?
• Where to add the next element?
• Push everything backsize = 3; front = 0; rear = 3;
• Cost? • O (size)
Race([email protected])
Circular Implementation
bool Queue::add(int n){
if (! isFull() ) { QueueArray[rear] =
n; rear++;if (rear == maxSize)
rear = 0; size++;return true;
}else return false;
}
01
2
3
MS-1
Race([email protected])
Circular Implementation
bool Queue::remove(int &n){
if (! isEmpty() { n =
QueueArray[front]; front++;if (front == maxSize)
front = 0;size--;return true;
}else return false;
}
01
2
3
MS-1
Race([email protected])
bool Queue::add(int n){
if (! isFull() ) { QueueArray[rear] = n; rear++;if (rear == maxSize)
rear = 0; size++;return true;
}else return false;
}
01
2
3
MS-1
bool Queue::isFull() {return size == MaxSize;}bool Queue::isEmpty() {return size == 0; }
Queue::Queue(int s){
if (s <= 0) MaxSize = 10; else MaxSize = s;QueueArray = new int[MaxSize];size = 0; rear = 0; front = 0;
}
bool Queue::remove(int &n){
if (! isEmpty() ) { n = QueueArray[rear]; front++;if (front == maxSize)
front = 0; size--;return true;
}else return false;
}
Race([email protected])
bool Queue::add(int n){
if (! isFull() ) { QueueArray[rear] = n; rear++;if (rear == maxSize)
rear = 0; size++;return true;
}else return false;
}
bool Queue::remove(int &n){
if (! isEmpty() { n = QueueArray[front]; front++;if (front == maxSize)
front = 0;size--;return true;
}else return false;
}
01
2
3
MS-1
Add: rear = (rear + 1) % maxSize; Remove: front = (front + 1) % maxSize;
What happens if we try to do it clockwise?
Race([email protected])
Double Ended Queue (Dequeue)
• We can insert at or delete from queue at either end
• Can be used as queue as well as stack
• Two types - Input restricted dequeue
- output restricted dequeue
Race([email protected])
Input restricted dequeue (algorithm)
remove (queue, n, f, r, side)
1. If (f= -1 or r= -1) then
print (“queue is empty”)
return (dummy value)
2. If (f = r) then
n = queue [f]
f = -1, r = -1
3. If (side = ‘front) then
n = queue [f]
f = f + 1
4. If (side = ‘rear’) then
n = queue [r]
r = r – 1
5. Return (n)
Race([email protected])
Output restricted dequeue (algorithm)
Add( queue, f, r, n, size, side)
1. If (side = ‘front’ and f = 0) or (side = ‘rear’ and r = size-1)
print (“ queue full”)
return
2. If (side = ‘front’) then
if ( f = -1) then
f = 0, r = 0
else
f = f – 1
queue [f] = n
3. If (side = ‘rear’) then
r = r + 1
queue [r] = n
if (f = -1) then
f = 0, r = 0
4. return
Race([email protected])
Priority Queue
• Items are inserted according to priority• Priority determines the order in which items exists in the
queue• Simple example is mail sorting, process control systems• Ascending Priority Queue ( queue which remove lowest
priority item first)• Descending priority Queue (queue which remove highest
priority item first)• Implementation is like multiple stack i.e more than one
queues can exist on a single one dimensional array
Race([email protected])
Use of Stack in the Implementation of
Subprograms • In a typical program, the subprogram
calls are nested.• Some of these subprogram calls may be
recursive.• Address of the next instruction in the
calling program must be saved in order to resume the execution from the point of subprogram call.
• Since the subprogram calls are nested to an arbitrary depth, use of stack is a natural choice to preserve the return address.
Race([email protected])
Activation Records
• An activation record is a data structure which keeps important information about a sub program.
• In modern languages, whenever a subprogram is called, a new activation record corresponding to the subprogram call is created, and pushed into the stack.
• The information stored in an activation record includes the address of the next instruction to be executed, and current value of all the local variables and parameters. i.e. the context of a subprogram is stored in the activation record.
• When the subprogram finishes its execution and returns back to the calling function, its activation record is popped from the stack and destroyed-restoring the context of the calling function.
Race([email protected])
Recursive Functions• Recursion is a very powerful algorithm design tool.• A subprogram is called recursive if it directly or
indirectly calls itself.
• A recursive program has two parts:• The End Condition.• The Recursive Step.
• The end condition specifies where to stop.
• With each recursive step you should come closer to the end condition.
• In other words, with a recursive step, you apply the same algorithm on a scaled down problem and its process is repeated until the end of condition is reached.
Race([email protected])
Recursion – Some Examples
int linear_search (int a[], int from, int to, int key){
if (from <= to) { //end conditionif (key == a[from]) return from;
//end conditionelse
return linear_search(a, from+1, to, key)//recursive step
}else
return -1;}
Race([email protected])
int binary_search (int a[], int high, int low, int key){
int mid = (high + low)/2;if (high >=low) {
if (key == a[mid]) return mid; //end conditionelse if (key < a[mid])
return binary_search(a, mid -1, low, key); //recursive step
elsereturn binary_search(a, high, mid + 1,
key); //recursive step}else
return-1; // end condition
}
Race([email protected])
How Does Recursion WorkSome More Recursive Functions
and Their Simulation
int factorial (int n){
int temp;
if (n<0) return 0; //end conditionelse if (n <=1) return 1; //end conditionelse {
temp = factorial(n-1); //recursive step
return n*temp;}
}
Race([email protected])
Simulation of factorial(4)
• if (n<0) return 0;• else if (n <=1) return 1;• else {• temp = factorial (n-1);• return n*temp;
}
n = 4
1.2.3.4.
n = 3
1.2.3.4.
n = 2
1.2.3.4.
n = 1
1.2. return 1
temp = 15. return 2*1
1.2. return 1
temp = 25. return 3*2
1.2. return 1
temp = 65. return 4*6
1.2. return 1
Race([email protected])
Fibonacci Sequence0,1,1,2,3,5,8,13,…
int fibonacci (int n){
int temp1, temp2;if (n<=0) return 0; //end conditionelse if (n<=2) return 1; //end conditionelse{
temp1 = fibonacci(n - 1); // recursive step temp2 = fibonacci(n - 2); //recursive step return temp1 + temp2; //same as return fib(N-
1)+fib(N-2)
}}
Race([email protected])
Simulation of fibonacci(4)
1. if (n<=0) return 0;• else if (n<=2) return 1;
else {• temp1 = fibonacci(n - 1);• temp2 = fibonacci(n - 2);
• return temp1 + temp2;
}
n = 21.1. return 1
n = 41.2.3.
n = 31.2.3. temp1 = 14.
1.2. return 1
n = 11.2. return 1
temp2 = 15. return 2
1.2. return 1
temp1 = 24.
1.2. return 1
n = 21.2. return 1
temp2 = 15. return 3
1.2. return 1
Race([email protected])
Tower of Honoi• Invented by French mathematician Lucas in 1880s.• In the town of Honoi, monks are playing a game with:
– 3 diamond needles fixed on a brass plate.– One needle contains 64 pure gold disks of different
diameters. – Plates are put on top of each other in the order of
their diameters with the largest plate lying at the bottom on the brass plate.
• Priests are supposed to transfer all the disks from one needle to the other such that:– Only one disk can be moved at a time.– At no time a disk of larger diameter should be put on
a disk of smaller diameter.
Race([email protected])
From Using To
3 Disks
• How much time would it take? Estimate…..• According to the legend, that will mark the end of time!
Race([email protected])
Tower of Honoivoid TOH (int from, int to, int using, int n){
if (n>0) // end condition – stop when there is // nothing to be moved
{TOH (from, using, to, n-1);
// recursive step// move n-1 plates from the starting// disk to the auxiliary disk
move (to, from);// move the nth disk to the
destination
TOH (using, to, from, n-1);// recursive step// move n-1 plates from the auxiliary// disk to the destination disk
}}
Race([email protected])
1. if (n>0) 2. {• TOH (from, using, to, n-1);• move (to, from);• TOH (using, to, from, n-1);1. }
Simulation of TOH(1, 2, 3, 3)
1 2
3
from:1, to:2, using:3, n:3
f = 1, t = 2, u = 3, n = 3
statement: 3
f = 1, t = 2, u = 3, n = 1
statement: 3f = 1, t = 3, u = 2,
n = 2statement: 3
f = 1, t = 3, u = 2, n = 0
statement: 1f = 1, t = 2, u = 3,
n = 1statement: 4
f = 1, t = 2, u = 3, n = 1
statement: 5
f = 3, t = 2, u = 1, n = 0
statement: 1
f = 1, t = 3, u = 2, n = 2
statement: 4
f = 1, t = 3, u = 2, n = 2
statement: 5
f = 2, t = 3, u = 1, n = 1
statement: 3
f = 2, t = 1, u = 3, n = 0
statement: 1f = 2, t = 3, u = 1,
n = 1statement: 4
f = 2, t = 3, u = 1, n = 1
statement: 5
f = 1, t = 3, u = 2, n = 0
statement: 1
f = 1, t = 2, u = 3, n = 3
statement: 4
f = 1, t = 2, u = 3, n = 3
statement: 5
f = 3, t = 2, u = 1, n = 2
statement: 3
f = 3, t = 1, u = 2, n = 1
statement: 3
f = 3, t = 2, u = 1, n = 0
statement: 3f = 3, t = 1, u = 2,
n = 1statement: 4
f = 3, t = 1, u = 2, n = 1
statement: 5
f = 2, t = 1, u = 3, n = 0
statement: 1
f = 3, t = 2, u = 1, n = 2
statement: 4
f = 3, t = 2, u = 1, n = 2
statement: 5
f = 1, t = 2, u = 3, n = 1
statement: 3
f = 1, t = 3, u = 2, n = 0
statement: 1f = 1, t = 2, u = 3,
n = 1statement: 4
f = 3, t = 2, u = 1, n = 1
statement: 5
f = 1, t = 2, u = 3, n = 0
statement: 5
Race([email protected])