π Lecture 07 β Data Structures
π Overview: This lecture focuses on evaluating postfix expressions using a stack and converting infix expressions to postfix form. It introduces the stack-based algorithm for postfix evaluation and the conversion process using operator precedence and a stack data structure.
ποΈ Topics Covered
The lecture covers three main topics: evaluation of postfix expressions using a stack with a detailed algorithm and example, a comprehensive worked example of evaluating a long postfix expression step-by-step in tabular form, and infix to postfix conversion including the algorithm, operator precedence handling, and the role of parentheses.
π Lecture Summary
Evaluating postfix expressions
Postfix notation places operators after their operands and does not use parentheses. To evaluate a postfix expression, we use a stack. We read the expression from left to right. When we encounter an operand, we push it onto the stack. When we encounter an operator, we pop the top two operands from the stack (op2 first, then op1), apply the operator, and push the result back onto the stack. At the end, the stack will contain the final result.
π Definition β Postfix Expression: A mathematical expression where operators follow their operands (e.g., A B + instead of A + B). No parentheses are needed.
π Algorithm:
Stack s;
while( not end of input ) {
e = get next element of input
if( e is an operand )
s.push( e );
else {
op2 = s.pop();
op1 = s.pop();
value = result of applying operator 'e' to op1 and op2;
s.push( value );
}
}
finalresult = s.pop();
π Example: Evaluate postfix expression 432*+
- Push 4, 3, 2 onto stack (top to bottom: 2, 3, 4)
- Read
*: pop op2=2, op1=3 β 3*2=6 β push 6 (stack: 6, 4) - Read
+: pop op2=6, op1=4 β 4+6=10 β push 10 - Final result: 10
π‘ Why this matters: Stack-based evaluation is efficient because it eliminates the need for parentheses and precedence rules during evaluation.
An Example
We evaluate the long postfix expression 6 2 3 + - 3 8 2 / + * 2 ο 3 + step-by-step:
| Input | op1 | op2 | value | stack |
|---|---|---|---|---|
| 6 | 6 | |||
| 2 | 2,6 | |||
| 3 | 3,2,6 | |||
| + | 2 | 3 | 5 | 5,6 |
| - | 6 | 5 | 1 | 1 |
| 3 | 3,1 | |||
| 8 | 8,3,1 | |||
| 2 | 2,8,3,1 | |||
| / | 8 | 2 | 4 | 4,3,1 |
| + | 3 | 4 | 7 | 7,1 |
| * | 1 | 7 | 7 | 7 |
| 2 | 2,7 | |||
| ο | 7 | 2 | 49 | 49 |
| 3 | 3,49 | |||
| + | 49 | 3 | 52 | 52 |
Final result: 52
π Definition β Stack LIFO behavior: The last element pushed is the first popped, which is why op2 is popped first and op1 second when evaluating operators.
π Key rules: Always pop op2 first (top of stack), then op1. Apply operator as op1 op op2.
Infix to postfix Conversion
To convert an infix expression (with operators between operands like A+B) to postfix form, we use a stack for operators. The order of operands remains unchanged, but operators may be reordered based on precedence. We use a function prcd(op1, op2) that returns TRUE if op1 has precedence over op2.
π Definition β prcd function: A function that determines operator precedence. prcd(*, +) returns TRUE; prcd(+, *) returns FALSE.
π Algorithm:
Stack s;
while( not end of input ) {
c = next input character;
if( c is an operand )
add c to postfix string;
else {
while( !s.empty() && prcd(s.top(),c) ) {
op = s.pop();
add op to the postfix string;
}
s.push( c );
}
}
while( !s.empty() ) {
op = s.pop();
add op to postfix string;
}
π Example: Convert infix A+B*C to postfix
| Symbol | Postfix | Stack |
|---|---|---|
| A | A | |
| + | A | + |
| B | AB | + |
| * | AB | *,+ |
| C | ABC | *,+ |
| end | ABC*+ |
For parentheses in infix expressions:
- When
(is read, push it on the stack (prcd(op, '(') = FALSE) - When
)is read, pop all operators up to the first(and place them in postfix string - Both parentheses are discarded (not added to postfix string)
π Definition β Parenthesis handling in conversion: The open parenthesis is pushed as a marker; when closing parenthesis is encountered, all operators up to the open parenthesis are popped and added to postfix.
π Special prcd rules for parentheses:
prcd('(', op) = FALSEfor any operatorprcd(op, ')') = FALSEfor any operator other than ')'prcd(op, ')') = TRUEfor any operator other than '('
β Key Takeaways
Students must remember that stack is used both for evaluating postfix expressions and converting infix to postfix. For postfix evaluation, always push operands, and when encountering an operator, pop op2 first (top) then op1, apply the operator as op1 op op2, and push the result. For infix to postfix conversion, send operands directly to output, push operators on stack but before pushing, pop all operators with higher precedence from the stack to output. Parentheses require special handling β open parenthesis is pushed onto stack and acts as a lower precedence barrier, while closing parenthesis pops all operators until the matching open parenthesis, and both are discarded.
π§ Quick Revision Questions
- What are the steps to evaluate the postfix expression
5 3 + 2 *using a stack? - In postfix evaluation, why is op2 popped before op1, and what would happen if the order were reversed?
- Convert the infix expression
(A+B)*C-Dto postfix form using the algorithm. - When processing the infix expression
A+B*C, why is+not added to postfix immediately afterA? - How does the algorithm handle a closing parenthesis
)during infix to postfix conversion, and why are parentheses not included in the final postfix expression?
π Lecture 08 β Data Structures (CS301)
π Overview: This lecture focuses on the conversion of infix expressions with parentheses to postfix notation, details the evaluation process using a stack, and introduces the powerful C++ template mechanism for creating generic data structures. It also explores the fundamental role of the stack as the function call stack in program execution and memory management.
ποΈ Topics Covered
The lecture covers the conversion algorithm for infix to postfix expressions including parentheses handling, with a detailed step-by-step example. It then introduces C++ templates as a solution for writing generic code for data structures like Stack, providing a complete template class implementation and its usage. Finally, it explains the function call stack mechanism, including parameter passing, return addresses, and the runtime memory organization of a process.
π Lecture Summary
Conversion from infix to postfix
In the previous lecture, we discussed the way to convert an infix notation into a postfix notation. During the process of conversion, we saw that there may be a need for parentheses in the infix, especially when we want to give a higher precedence to an operator of lower precedence. For example, to force addition before multiplication in A + B * C, we write (A + B) * C. We have defined the return values for opening ( and closing ) parentheses in the precedence function.
The process of converting the infix expression (A + B) * C into a postfix expression is completed in eight steps, as shown in the following table. The symbol column has the input symbols, the postfix column has the postfix string after each step, and the stack is used to store operators.
| Step No. | Symbol | Postfix | Stack |
|---|---|---|---|
| 1 | ( | ( | |
| 2 | A | A | ( |
| 3 | + | A | (+ |
| 4 | B | AB | (+ |
| 5 | ) | AB+ | |
| 6 | * | AB+ | * |
| 7 | C | AB+C | * |
| 8 | AB+C* |
First, the opening parenthesis ( is put on the stack. The next symbol A is an operand, so it goes to the postfix string. The + operator is pushed onto the stack. Then operand B is placed in the postfix string. When the closing parenthesis ) appears, the operators (in this case +) are popped from the stack and put in the postfix string, and the opening parenthesis is also popped and discarded. The next operator * is pushed onto the stack. After operand C is placed in the postfix string, the input string ends. The remaining * operator is popped from the stack and put into the postfix string, yielding AB+C*.
π Definition β Conversion algorithm: A process that uses a stack to rearrange operators according to precedence and parentheses, producing a postfix expression where operators appear after their operands and parentheses are removed.
Now, we apply the evaluation algorithm on this postfix expression AB+C*. The two operands A and B go to the stack. The operator + pops these operands, adds them, and pushes the result back onto the stack. Next C goes to the stack, and then * operator pops the two operands (result of addition and C), and their multiplication leads to the final result. The postfix notation is simple to evaluate because operators are in the order of evaluation, unlike infix which requires parentheses to force precedence. With the help of a stack data structure, we can do the conversion and evaluation of expressions easily.
π‘ Why this matters: Understanding this conversion is crucial because computers evaluate postfix expressions much more efficiently than infix expressions, making this a fundamental algorithm for compilers and calculators.
C++ Templates
We can use C++ templates for stack and other data structures. When converting expressions, we use the stack for storing operators like +, *, -, and /, which are single characters. When evaluating expressions, we store operands (integers, floats, or variables). In both cases, the functionality is the same β we push and pop things, and check if the stack is empty. The only difference is the type of elements used.
Without templates, we would have to create separate classes like FloatStack and CharStack with identical code, just differing in data type. C++ provides templates to write the code for a stack once and then use it for different types of data. A template is a function or class written with a generic data type. When a programmer uses this function or class, the generic data type is replaced with the specific data type needed.
The lecture presents a template class for stack declared in the file Stack.h:
template <class T>
class Stack
{
public:
Stack();
int empty(void);
int push(T &);
T pop(void);
T peek(void);
~Stack();
private:
int top;
T* nodes;
};
The line template <class T> shows we are writing a template. Here T is a variable name for a generic data type. A data type will replace this T whenever the template is used. The peek function is similar to the top function β it returns the element from the top but does not remove it from the stack.
The implementation in Stack.cpp includes:
template <class T>
Stack<T>::Stack()
{
top = -1;
nodes = new T[MAXSTACKSIZE];
}
template <class T>
int Stack<T>::push(T& x)
{
if( top < MAXSTACKSIZE )
{
nodes[++top] = x;
return 1;
}
cout << "stack overflow in push.\n";
return 0;
}
template <class T>
T Stack<T>::pop(void)
{
T x;
if( !empty() )
{
x = nodes[top--];
return x;
}
cout << "stack underflow in pop.\n";
return x;
}
The main program in main.cpp demonstrates the usage:
Stack<int> intstack;
Stack<char> charstack;
int x=10, y=20;
char c='C', d='D';
intstack.push(x); intstack.push(y);
cout << "intstack: " << intstack.pop() << ", " << intstack.pop() << "\n";
charstack.push(c); charstack.push(d);
cout << "charstack: " << charstack.pop() << ", " << charstack.pop() << "\n";
The line Stack<int> intstack creates an object where the generic data type T is replaced by int, making it a stack for integers. Similarly, Stack<char> charstack creates a stack for characters. The compiler automatically provides two versions of the template code. This is possible only in C++ through the template utility. C++ also provides the Standard Template Library (STL), which is a tested code base containing common data structures like stack and queue as templates.
π‘ Why this matters: Templates enable code reuse and type safety without duplication, allowing us to define a data structure once and use it with any data type.
Function Call Stack
Whenever a programmer calls a function, they pass some arguments to the function, which does work on these arguments and returns a value. The function call stack is used by the compiler to fulfill this function call. The compiler puts entries on the stack in the following way: first (on the top) is the return address where control will go back after executing the function. After it, the next entries are the arguments of the function. The compiler pushes the last argument first (so it goes to the bottom), then the second last, and so on, making the first argument the first element on the stack.
top ------ > return address
first argument
second argument
.........
.........
last argument
Consider the function:
int i_avg (int a, int b)
{
return (a + b) / 2;
}
The assembly language code shows the use of the stack pointer %esp:
_i_avg:
movl 4(%esp), %eax # Gets first argument (offset 4 from top)
addl 8(%esp), %eax # Adds second argument (offset 8 from top)
sarl $1, %eax # Divide by 2
ret # Return value is in %eax
The esp register is the stack pointer (top). The movl takes offset 4 from top (4 bytes for an integer) to get the first argument. The addl takes offset 8 from the stack pointer for the second argument. The sarl divides by 2, and ret returns the value.
Different data structures are used in the run time environment of the computer. When an executable program runs, it is loaded in memory and becomes a process. This process is given a block of memory which it uses during its execution. The internal memory organization of a process includes:
- Code: The code generated by the compiler
- Static data: Holds global variables and different variables of objects
- Stack: Used in function calls
- Heap: Used for dynamic memory allocation
The task manager shows details of all running programs, including their Process ID (PID) and memory usage (Mem Usage). The whole process of using the stack in function calling is known as the run time environment.
π‘ Why this matters: Understanding the function call stack is fundamental for debugging, understanding recursion, and ultimately for writing compilers or understanding low-level program execution.
β Key Takeaways
This lecture provides the complete implementation of a generic stack using C++ templates, demonstrating how to write a single code base that works for any data type. The key skill is understanding the infix-to-postfix conversion algorithm with parentheses, which is essential for expression evaluation in compilers and calculators. The function call stack mechanism reveals how the computer actually passes arguments and returns control during function execution. Finally, the runtime memory organization (code, static data, stack, heap) is crucial for understanding program execution, memory management, and debugging.
π§ Quick Revision Questions
- In the conversion of
(A + B) * Cto postfix, what happens when the closing parenthesis)is encountered? - What is the purpose of the
template <class T>declaration in a C++ template class? - In the function call stack, what is stored at the top of the stack when a function is called?
- What are the four main sections of a process's memory organization, and which one is used for dynamic memory allocation?
- Why can't you push a character value onto a stack created as
Stack<int>?
π Lecture 09 β Data Structures
π Overview: This lecture explores memory organization in processes, including stack layout during function calls, and introduces the queue data structure. It covers queue implementation using both linked lists and arrays (including circular arrays), along with practical applications like simulation.
ποΈ Topics Covered
Memory organization in processes (code section, static data, stack, heap), stack layout during function calls, introduction to queues as FIFO data structures, queue operations (enqueue, dequeue, front, isEmpty), implementing queue using linked list with front and rear pointers, implementing queue using circular arrays with modulo arithmetic, and practical applications of queues in simulation.
π Lecture Summary
Memory Organization
When you run an executable, the operating system creates a process inside memory and constructs four main sections. A code section contains the binary version of the program's code. A section for static data includes global variables. The stack is used for function calling, while the heap area is utilized during dynamic memory allocation.
Stack Layout during a Function Call
The diagrams depict the layout of the stack when a function F calls function G. Here sp stands for stack pointer. Before function F calls function G, the parameters passed to function F are first inserted into the stack, followed by local variables of function F, and finally the memory address to return after function F finishes. Just before G is called, parameters being passed to G are inserted into the stack.
After the call to function G, local variables of function G are inserted into the stack after its parameters and return address. When function G finishes execution, its local variables and parameters are removed permanently from the stack. Thus, when a function call is made, all local variables and parameters of the called function are pushed onto the stack and destroyed soon after execution completes.
In C/C++, variables declared as static are not pushed on the stack. Rather, these are stored in a separate section allocated for static data of a program. This section is not destroyed till the end of the process's execution. If a variable x is declared as static inside function G, x will be stored in the static data section and its value is preserved across G function calls. The visibility of x is restricted to function G only.
π‘ Why this matters: Understanding stack layout is crucial for debugging, understanding recursion, and managing memory efficiently in programs.
Queues
A queue is a linear data structure into which items can only be inserted at one end and removed from the other. In contrast to the stack, which is a LIFO (Last In First Out) structure, a queue is a FIFO (First In First Out) structure. The usage of queue in daily life is common - we queue up while depositing a bill or purchasing a ticket, where the first person is served first.
Queue Operations
The queue data structure supports the following operations:
π Definition β enqueue(X): Place X at the rear of the queue π Definition β dequeue(): Remove the front element and return it π Definition β front(): Return front element without removing it π Definition β isEmpty(): Return TRUE if queue is empty, FALSE otherwise
Implementing Queue
Suppose we are implementing queue with the help of the linked list structure. Key points include: Insert works in constant time for either end of a linked list; Remove works in constant time only; Best that head of the linked list be the front of the queue so all removes will be from the front; Inserts will be at the end of the list.
The queue elements are shown with two pointers: front and rear. When dequeue() is called once, the front element is removed and the front pointer moves to the next element. When enqueue(9) is called, the new element is inserted at the rear end and the rear pointer points to this new node.
dequeue() code:
int dequeue() {
int x = front->get();
Node* p = front;
front = front->getNext();
delete p;
return x;
}
enqueue(int x) code:
void enqueue(int x) {
Node* newNode = new Node();
newNode->set(x);
newNode->setNext(NULL);
rear->setNext(newNode);
rear = newNode;
}
In dequeue(), the front element is retrieved and assigned to x. The front pointer is saved in p, then moved forward. The node pointed to by front is deleted, and the saved value is returned.
In enqueue(), a new Node object is created using new Node(). The value x is set in the new node, its next pointer is set to NULL. The new node is set as the next node of the node pointed by rear, and rear is updated to point to the new node.
front() and isEmpty() code:
int front() {
return front->get();
}
int isEmpty() {
return (front == NULL);
}
The front() method retrieves the oldest element inserted in the queue. The isEmpty() method checks if the front pointer is NULL, returning true if the queue is empty.
Queue using Array
Before implementing a queue with an array, consider: If we use an array to hold queue elements, both insertions and removal at the front (start) of the array are expensive due to shifting up to "n" elements. For a queue, both ends are required. To get around this, we will not shift upon removal of elements.
In array implementation, front and rear are not pointers but indexes of arrays. front contains the starting index (0) while rear comprises the last element's index. When an element is removed from the queue, we do not shift the array elements, as shifting might be expensive.
However, after insertions and removals, we create a new problem - we cannot insert new elements even though there are empty places at the start of the array.
π Definition β Circular Array: The solution lies in allowing the queue to wrap around by using a circular array to implement the queue.
The number of locations in the circular array are eight, starting from index 0 to 7, incremented in the clockwise direction. To insert an element, we insert it in the location next to the last used index.
enqueue() for circular array:
void enqueue(int x) {
rear = (rear + 1) % size;
array[rear] = x;
noElements = noElements + 1;
}
In line 1, 1 is added to rear and the mod operator (%) is applied with size variable. This expression can result from 0 to 7 as size is 8. This operator ensures the value will always be within range.
We also need to maintain four variables: front, rear, size, and noElements.
isFull() and isEmpty() methods:
int isFull() {
return noElements == size;
}
int isEmpty() {
return noElements == 0;
}
isFull() returns true if the number of elements equals the size of the array. isEmpty() returns true if noElements equals 0.
dequeue() for circular array:
int dequeue() {
int x = array[front];
front = (front + 1) % size;
noElements = noElements - 1;
return x;
}
In the first line, we take out an element from the array at front index and store it in x. In the second line, front is incremented by 1 but using modulo for circular behavior. In the third line, number of elements is reduced by 1 and the saved element is returned.
Use of Queues
Out of the numerous uses of queues, one of the most useful is simulation. A simulation program attempts to model a real-world phenomenon. Many popular video games are simulations, e.g., SimCity, Flight Simulator. Each object and action in the simulation has a counterpart in the real world.
Example: Suppose there is a bank with four tellers. A customer enters at time tβ desiring to conduct a transaction. Any teller can attend to the customer. The transaction will take time tβ. If a teller is free, the customer leaves at tβ+tβ. If no teller is free, the customer goes to the shortest line and waits. The customer leaves at tβ time units after reaching the front of the line. The time spent at the bank is tβ plus time waiting in line.
β Key Takeaways
The lecture covers two major topics: memory organization with stack layout during function calls, and the queue data structure. Understanding how the stack stores parameters, local variables, and return addresses during function calls is essential. Queues operate on FIFO principle, with enqueue at rear and dequeue from front. Queue can be implemented using linked lists (constant time operations) or circular arrays (using modulo arithmetic to wrap around). The circular array approach solves the problem of wasted space in regular array implementation. Queues are widely used in simulation applications for modeling real-world scenarios.
π§ Quick Revision Questions
- What four sections does the operating system create in memory when running an executable?
- What happens to static variables during function calls compared to local variables?
- What is the difference between stack (LIFO) and queue (FIFO) data structures?
- How does the modulo operator help in implementing a circular array for queues?
- In the bank simulation example, what determines the total time a customer spends at the bank?
π Lecture 10 β Queues, Simulation Models, Priority Queue & Code of the Bank Simulation
π Overview: This lecture extends the queue data structure by applying it to real-world simulation problems, specifically a bank teller simulation. It introduces two simulation modelsβtime-based and event-basedβand explains the priority queue data structure, which is essential for handling events in order of their occurrence rather than arrival order.
ποΈ Topics Covered
The lecture covers queue applications in bank simulation scenarios, two simulation models (time-based and event-based), the concept of priority queues as a generalization of FIFO queues, and the complete C++ code implementation of a bank simulation. The lecture also demonstrates how to calculate key performance metrics such as average customer wait time using simulation.
π Lecture Summary
Queues
The lecture begins by revisiting the queue data structure and demonstrating its usefulness in simulation, specifically a bank scenario. Customers enter a bank with four tellers and form queues. A person enters, analyzes the four queues, and joins the shortest one. The person cannot change queues once selected. The simulation tracks when customers arrive, how long they wait, and when they leave.
π Definition β Queue (from prior lecture): A FIFO (First In, First Out) data structure where elements are added at the rear and removed from the front.
π Example: A customer arrives at 10:00 AM with a 5-minute transaction time, waits 15 minutes in queue, is served for 5 minutes, and leaves at 10:20 AM. The total time in the bank is 20 minutes.
Simulation Models
Two common simulation models are discussed: time-based simulation and event-based simulation.
In time-based simulation, we maintain a timeline or clock. The clock ticks (e.g., every minute), and things happen when the time reaches the moment of an event.
π Example: Bank opens at 9:00 AM.
- Customer C1 arrives at 9:02 AM, needs 4 minutes β leaves at 9:06 AM
- Customer C2 arrives at 9:04 AM, needs 6 minutes β leaves at 9:10 AM
- Customer C3 arrives at 9:12 AM, needs 10 minutes
The pseudo code for time-based simulation:
clock = 0;
while ( clock <= 24*60 ) {
read new customer;
if customer.arrivaltime == clock
insert into shortest queue;
check the customer at head of all four queues.
if transaction is over
remove from queue.
clock = clock + 1;
}
The clock runs for 24 hours (1440 minutes). When the clock reaches a customer's arrival time, they are inserted into the shortest queue. When a transaction ends, the customer is removed. If no event occurs at a given minute, the loop simply increments the clock.
π‘ Why this matters: Time-based simulation is straightforward but inefficient because the program does nothing during idle clock ticks.
In event-based simulation, we don't wait for the clock to tick until the next event. Instead, we compute the time of the next event and maintain a list of events in increasing order of time. We remove an event from the list in a loop and process it.
π Example events for the same scenario:
- Event 1: 2 mins β C1 enters
- Event 2: 4 mins β C2 enters
- Event 3: 6 mins β C1 leaves
- Event 4: 10 mins β C2 leaves
- Event 5: 12 mins β C3 enters
These events are stored in a special queue where the earliest event is removed first, regardless of when it was added. This requires a priority queue.
Priority Queue
A priority queue is a data structure where the dequeue operation depends not on FIFO but on some priority. In a FIFO queue, priority is given to the time of arrival β the person who comes first has higher priority. In a priority queue, elements are removed based on their priority value, not their arrival order.
π Definition β Priority Queue: A data structure where each element has a priority, and elements are removed in order of their priority (highest priority first), not their insertion order. FIFO is a special case of priority queue where priority is given to arrival time.
π Example: In traffic, vehicles queue at a signal. When an ambulance comes from behind, it bypasses the queue and crosses the intersection first because it has higher priority.
π‘ Why this matters: Priority queues are used extensively in operating systems for process scheduling, where higher-priority processes run before lower-priority ones.
Code of the Bank Simulation
The lecture presents the complete C++ implementation of the bank simulation using event-based simulation with a priority queue.
Input File Format: Each line contains: arrival time (hours, minutes) and transaction duration.
00 30 10 <- customer 1 arrives 30 min after opening, needs 10 min
00 35 05 <- customer 2 arrives 35 min after opening, needs 5 min
00 40 08
00 45 02
00 50 05
00 55 12
01 00 13
01 01 09
Key Data Structures:
Queue q[4]; // four teller queues
PriorityQueue pq; // event list (priority queue)
int totalTime; // total wait time for all customers
int count; // number of customers served
int customerNo; // customer counter
Main Driver Loop:
main (int argc, char *argv[]) {
Customer* c;
Event* nextEvent;
ifstream data("customer.dat", ios::in);
ReadNewCustomer(data);
While( pq.length() > 0 ) {
nextEvent = pq.remove();
c = nextEvent->getCustomer();
if( c->getStatus() == -1 ) { // arrival event
int arrTime = nextEvent->getEventTime();
int duration = c->getTransactionDuration();
int customerNo = c->getCustomerNumber();
processArrival(data, customerNo, arrTime, duration, nextEvent);
}
else { // departure event
int qindex = c->getStatus();
int departTime = nextEvent->getEventTime();
processDeparture(qindex, departTime, nextEvent);
}
}
}
π Flow Explanation: The priority queue holds events. Events with status -1 are arrival events; otherwise they are departure events. Each iteration removes the earliest event (highest priority = smallest time) and processes it.
readNewCustomer Function:
void readNewCustomer(ifstream& data) {
int hour, min, duration;
if (data >> hour >> min >> duration) {
customerNo++;
Customer* c = new Customer(customerNo, hour*60+min, duration);
c->setStatus(-1); // mark as new arrival
Event* e = new Event(c, hour*60+min);
pq.insert(e); // insert arrival event into priority queue
}
else {
data.close();
}
}
processArrival Function:
int processArrival(ifstream &data, int customerNo, int arrTime, int duration, Event* event) {
int i, small, j = 0;
// find smallest teller queue
small = q[0].length();
for(i=1; i < 4; i++)
if( q[i].length() < small ) {
small = q[i].length();
j = i;
}
// put arriving customer in smallest queue
Customer* c = new Customer(customerNo, arrTime, duration);
c->setStatus(j); // remember which queue customer goes into
q[j].enqueue(c);
// if this is the only customer in queue, mark for departure
if( q[j].length() == 1 ) {
c->setDepartureTime(arrTime + duration);
Event* e = new Event(c, arrTime + duration);
pq.insert(e);
}
// get another customer from input
readNewCustomer(data);
}
π Key Logic: The customer is placed in the shortest queue. If the queue length is exactly 1 (customer is alone at teller), a departure event is created with time = arrival time + transaction duration. A new customer is then read from the file.
processDeparture Function:
int processDeparture(int qindex, int departTime, Event* event) {
Customer* cinq = q[qindex].dequeue();
int waitTime = departTime - cinq->getArrivalTime();
totalTime = totalTime + waitTime;
count = count + 1;
// if more customers on queue, mark next for departure
if( q[qindex].length() > 0 ) {
cinq = q[qindex].front();
int etime = departTime + cinq->getTransactionDuration();
Event* e = new Event(cinq, etime);
pq.insert(e);
}
}
Final Output Calculation:
double avgWait = (totalTime * 1.0) / count;
cout << "Total time: " << totalTime << endl;
cout << "Customer: " << count << endl;
cout << "Average wait: " << avgWait << endl;
π Example: The wait time for a customer = departure time - arrival time. The totalTime accumulates wait times for all customers. Average wait = totalTime / count. If totalTime = 1500 minutes and count = 300 customers, average wait = 5 minutes.
β Key Takeaways
The bank simulation demonstrates how queues and priority queues work together to model real-world systems. The priority queue is essential for event-based simulation because events must be processed in chronological order, not insertion order. The time-based simulation is simpler but inefficient as it wastes clock ticks, while event-based simulation jumps directly to the next event. The simulation code shows a practical pattern: arrival events create departure events, and each departure triggers the next customer at that teller queue to start service. Understanding these data structures and simulation techniques is critical for analyzing complex systems like bank queues, network traffic, and operating system process scheduling.
π§ Quick Revision Questions
- What is the key difference between time-based simulation and event-based simulation in terms of how the clock is handled?
- In the event-based bank simulation, what does a customer's status of -1 indicate versus status values 0-3?
- What happens in the processArrival function when the customer's queue length is exactly 1?
- How is the average wait time calculated in the bank simulation program?
- Why is a priority queue necessary for the event list rather than a regular FIFO queue?
π Lecture 11 β Implementation of Priority Queue & Tree
π Overview: This lecture continues the discussion of priority queue data structure, presenting its array-based implementation in C++. It then introduces tree data structures, focusing on binary trees, their mathematical definition, terminologies, and special types including strictly binary trees and complete binary trees. This knowledge is fundamental for understanding efficient searching and organization of hierarchical data.
ποΈ Topics Covered
The lecture covers the implementation of priority queue using arrays with insert, remove, and sorting operations. It then transitions to tree data structures, explaining why non-linear structures are needed. Binary trees are introduced with their recursive definition, terminologies (root, child, leaf, parent), and analysis through examples. Special types including strictly binary trees and complete binary trees are discussed with their properties, level calculations, and formulas for node counts.
π Lecture Summary
Implementation of Priority Queue
The priority queue is a variation of queue where elements are removed based on priority rather than FIFO order. In the banking simulation example, events were stored with their occurrence time, and the element with the earliest time was removed first. The implementation uses an array with a maximum size defined by PQMAX = 30. The class has private members for array storage, size counter, and rear index. The constructor initializes size to 0 and rear to -1. The full() method checks if size equals PQMAX and returns true if the queue is full.
π Definition β Priority Queue: A data structure where elements are added to a queue and removed based on a priority value assigned to each element, rather than following First-In-First-Out order.
The remove() method first checks if size > 0. If elements exist, it retrieves the event pointer from index 0 (the first position). A for loop shifts all remaining elements one position left (from index j to j-1) to fill the gap. Then size and rear are decremented. If size becomes 0, rear is set to -1. If the queue is empty, it returns NULL and displays a message. This method is inefficient because shifting elements is time-consuming.
π‘ Why this matters: The shifting operation in remove() makes this implementation slow for large queues. Better implementations using linked lists or heaps avoid this problem.
π Example: If the array contains events at indices 0, 1, 2 with priorities 10:00, 10:30, 11:00, removing the first event requires shifting the event at index 1 to index 0 and the event at index 2 to index 1.
The insert() method checks if the queue is not full using the full() function. If space is available, it increments rear, places the new event object at nodes[rear], increments size, then calls sortElements() to sort the array in ascending order based on event occurrence time. The method returns 1 for success or 0 for failure. The sorting ensures that the element at index 0 has the earliest (highest priority) time.
π Definition β sortElements(): A method called after each insertion to arrange the array elements in ascending order according to their priority (event time), ensuring the highest priority element is at index 0.
π Example: Inserting a departure event at 9:45 into a queue containing events at 10:00, 10:30, and 11:00 will result in the array being sorted to [9:45, 10:00, 10:30, 11:00], making the 9:45 event available for immediate removal.
Tree
Trees are non-linear data structures where elements are not arranged in a line like stacks, queues, or linked lists. Many applications require non-linear relationships between data. The genealogy tree example shows Muhammad Aslam Khan at the top (root) with children Sohail, Javed, and Yasmeen below him, and their children further below. Unlike real trees that grow upward, data structure trees are drawn top-down for easier understanding. Trees are essential when data has hierarchical relationships that cannot be captured by linear structures.
π Definition β Tree: A non-linear data structure consisting of nodes connected by edges, where data elements have parent-child relationships organized hierarchically.
π‘ Why this matters: Searching in linear structures with 100,000 entries requires traversing half the list on average. Tree structures enable much faster searching.
Binary Tree
The mathematical definition states: "A binary tree is a finite set of elements that is either empty or is partitioned into three disjoint subsets. The first subset contains a single element called the root of the tree. The other two subsets are themselves binary trees called the left and right sub-trees."
π Definition β Binary Tree: A tree data structure where each node has at most two subtrees, called left subtree and right subtree.
π Example: In the binary tree with root A, the left subtree contains nodes B, D, E, G and the right subtree contains nodes C, F, H, I. This recursive property applies at every level: node B becomes root of its subtree with left child D and right child E, while node E has left child G and empty right subtree.
A structure is NOT a tree if there are multiple paths to reach a node. For example, if node G can be reached via A-B-D-G and also via A-B-E-G, the structure becomes a graph, not a tree. Similarly, multiple links between nodes (like two connections between A and B) violate tree properties.
Terminologies of a Binary Tree
The root is the topmost node. Each node has a parent (the node above it) and children (nodes below it). Nodes can be left descendant or right descendant. Nodes with no children are called leaf nodes. The terms "descendant" and "child" are used interchangeably.
π Definition β Terminologies: Root (top node), parent (node above), child (node below), left descendant (child on left), right descendant (child on right), leaf node (node with no children).
Strictly Binary Tree
A binary tree is a strictly binary tree if every non-leaf node has non-empty left and right subtrees. In other words, every node that is not a leaf must have both a left child and a right child.
π Definition β Strictly Binary Tree: A binary tree where every non-leaf node has both non-empty left and right subtrees.
π Example: In the initial tree, node C has right child F but no left child, so it is NOT strictly binary. Adding node J as left child of C and node K as right child of E makes all non-leaf nodes (A, B, C, E, F) have both children, resulting in a strictly binary tree.
Level
The level of a node in a binary tree is defined as: root has level 0, and the level of any other node is one more than the level of its parent. The depth of a binary tree is the maximum level of any leaf in the tree.
π Definition β Level: Root is at level 0; each subsequent node's level is its parent's level plus one. Depth: The maximum level among all leaves in the tree.
π Example: In the tree with root A at level 0, nodes B and C are at level 1, nodes D, E, F are at level 2, and nodes G, H, I are at level 3. The depth of this tree is 3.
π Formula: Level of node = Level of parent + 1 (for all nodes except root which is 0)
Complete Binary Tree
A complete binary tree of depth d is a strictly binary tree where all leaves are at level d. This means every level from 0 to d-1 is completely filled with nodes, and all leaf nodes are on the deepest level.
π Definition β Complete Binary Tree: A strictly binary tree of depth d where all leaf nodes are at level d.
π Formula: Number of nodes at level k = 2α΅ π Formula: Total nodes in complete binary tree of depth d = 2α΅βΊΒΉ - 1 π Formula: Number of leaf nodes = 2α΅ π Formula: Number of non-leaf (inner) nodes = 2α΅ - 1
π Example: In a complete binary tree of depth 3, level 0 has 2β° = 1 node, level 1 has 2ΒΉ = 2 nodes, level 2 has 2Β² = 4 nodes, level 3 has 2Β³ = 8 nodes (all leaves). Total nodes = 2β΄ - 1 = 15. Leaf nodes = 2Β³ = 8. Non-leaf nodes = 2Β³ - 1 = 7.
Level of a Complete Binary Tree
If we know the total number of nodes (n) in a complete binary tree, we can calculate its depth (d).
π Formula: n = 2α΅βΊΒΉ - 1 β 2α΅βΊΒΉ = n + 1 β d + 1 = logβ(n + 1) β d = logβ(n + 1) - 1
π Example: With 100,000 nodes: d = logβ(100001) - 1 β 20. So the tree would be 20 levels deep.
Operations on Binary Tree
If p points to a node in an existing tree:
- left(p) returns pointer to the left subtree
- right(p) returns pointer to the right subtree
- parent(p) returns the father of p
- brother(p) returns brother of p
- info(p) returns content of the node
These operations will be discussed in detail in the next lecture.
β Key Takeaways
The priority queue does not follow FIFO rule; elements are removed based on their assigned priority values rather than insertion order. The array-based implementation of priority queue is inefficient for large datasets because removing an element requires shifting all remaining elements, and each insertion requires sorting the entire array. Trees are non-linear data structures essential for representing hierarchical relationships and enabling efficient searching operations. A binary tree's recursive nature means each node, when considered as a root, has its own left and right subtrees that are themselves binary trees. A complete binary tree of depth d has exactly 2α΅βΊΒΉ - 1 nodes with 2α΅ leaf nodes, and its depth can be calculated as logβ(n + 1) - 1 given n total nodes.
π§ Quick Revision Questions
- What makes a priority queue different from a regular queue, and how does the remove() method in the array-based implementation handle this difference?
- Why is the array-based implementation of priority queue inefficient, and what are the two specific operations that cause performance problems?
- What is the mathematical definition of a binary tree, and how does the recursive nature of this definition apply when analyzing any node in the tree?
- What is the difference between a strictly binary tree and a complete binary tree? Can a complete binary tree always be strictly binary, and vice versa?
- If a complete binary tree has 31 total nodes, what is its depth, how many leaf nodes does it have, and how many non-leaf nodes?