CS301 IMP Short Notes
CS301 IMP Short Notes
(IT OF VU)
We provide all categories of final year project (CS619) and short notes
Definition
Deferent B/W Mergesort and Linked Lists?
Define mergeArrays?
What is Bubble Sort?
Insertion Sort?
Hashing is Suitable?
Applications of Hashing?
Linear Probing and Collision?
What is lvalue?
In an assignment statement, lvalue refers to some memory location where some value can be stored. Lvalue
variable is written on left hand side of an assignment statement. For example, in the following statement,
variable ‘var’ is lvalue variable and value 7 will be stored in it. int var= 7;
What is algorithem?
Algorithm is a finite sequence of steps for the solution of a problem.
What is chunk?
Chunk means "a piece of reasonable size". Computer memory is divide into small parts.
Combination (allocation in sum) of these parts constitutes and can be called as chunk.
If we use the “current” marker, the following four methods would be useful:
Functions Description
Short Notes of CS301 By Muhammad Usman
(IT OF VU)
We provide all categories of final year project (CS619) and short notes
int x;
Here x is a integer type variable we can assign any integer value to x like x = 10 or x = 2
In the following code statement y is an array which can hold 10
values. int y[10];
In this scenario y is not lvalue, the reason is we cannot assign a single integer value to y like y = 10
Lets we elaborate it with diagram.
Suppose the box given below is int variable x. we can easily assign (save) 10 or 2 to it.Assume 10 boxes given
below are representing an array y. We cannot assign single value 10 or 2 to y. The problem is, if we will assign
10 to y then which box (place) in array it will save. This is the reason array is not lvalue.
Data structure concept in easy wording?
A data structure is a group of data elements grouped together under one name. Data structure
helps to store the data in computer in an organized and efficient way. Data structures are used
to efficiently utilize the memory of computer. Data structures not only consider the items
stored but also the relationship to each other.
What is Difference b/w arrays and linked list?
i. The difference between arrays and linked lists are:
ii. Arrays are linear data structures. Linked lists are linear and non-linear data structures.
iii. Linked lists are linear for accessing, and non-linear for storing in memory
iv. Array has homogenous values. And each element is independent of
each other positions.
v. Each node in the linked list is connected with its previous node
which is a pointer to the node.
vi. Array elements can be modified easily by identifying the index value. It
is a complex process for modifying the node in a linked list.
vii. Array elements cannot be added, deleted once it is declared. The nodes in
the linked list can be added and deleted from the list.
Using linked memory method is the other way of implementing the list. We have
to implement a list of elements, so this implementation can be done in 2 ways.
First is array implementation in which the elements will be stored in contiguous
memory locations. There are certain limitations of this type of implementation of
list i.e. the size is fixed. So to avoid these limitations, we can implement list by
other method. That method is implementing via linked memory locations which do
not restrict the list items to be stored contiguously.
what is the difference b/w array that is dynamic allocated and that is simple ?
Simple array (Static) is created in stack and dynamic is created in heap area of
the memory. In static array you have to tell the size before program runs but in
dynamic you can take input from user and then make array of that size.
Example static: int array[6];
Example dynamic: int *array; cout > size;
array = new int[size];
What is the difference b/w array and list data structure?
Array is collection of homogeneous elements. List is collection of heterogeneous elements. For
Array memory allocated is static and continuous while for List memory allocated is dynamic and
Random.
In array, user need not have to keep in track of next memory allocation while in list user has to
keep in Track of next location where memory is allocated.
Array size should be specified but the list size can be determined at run time also.
coutendl;
// after shifting
int first = a[0]; // Save 1st element or delete for(int i =0;i<4;i++)
{
a[i] = a[i+1]; // Real shifting statement. couta[i] '\t' ;
}
getche(); return 0;
}
Following is the list of operations and their description:
Operation Name Description
createList() Create a new list (presumably empty)
copy() Set one list to be a copy of another
clear(); Clear a list (remove all elements)
insert(X, ?) Insert element X at a particular position in the list
remove(?) Remove element at some position in the list
get(?) Get element at a given position
update(X, ?) Replace the element at a given position with X
find(X) Determine if the element X is in the list
length() Returns the length of the list.
runtime of that program. It can be seen also as a way of distributing ownership of limited
memory resources among many pieces of data and code.Dynamically allocated memory
exists until it is released either explicitly by the programmer, or by the garbage collector. This
is in contrast to static memory allocation, which has a fixed duration. It is said that an object
so allocated has a dynamic lifetime.
what is the main difference between list implementation and add method?
Suppose we want to create a list of integers. For this purpose, the methods of the list can
be implemented with the use of an array inside. For example, the list of integers (2, 6, 8,
7, 1) can be represented in the following manner where the current position is 3.
A 2 6 8 7 1 Current Size
1 2 3 4 5 3 5
In this case, we start the index of the array from 1 just for simplification against the usual
practice in which the index of an array starts from zero in C++. It is not necessary to always
start the indexing from zero. Sometimes, it is required to start the indexing from 1.
Add Method
Suppose there is a call to add an element in the list i.e. add(9). As we said earlier that the
current position is 3, so by adding the element 9 to the list, the new list will be (2, 6, 8,
9, 7, 1).
To add the new element (9) to the list at the current position, at first, we have to make space
for this element. For this purpose, we shift every element on the right of 8 (the current
position) to one place on the right. Thus after creating the space for new element at position
4, the array can be represented as
A 2 6 8 7 1 Current Size
1 2 3 4 5 6 4 6
Now in the second step, we put the element 9 at the empty space i.e. position 4. Thus the array will
attain the following shape. The figure shows the elements in the array in the same order as
stored in the list.
A 2 6 8 9 7 1 Current Size
1 2 3 4 5 6 4 6
We have moved the current position to 4 while increasing the size to 6. The size shows that
the elements in the list. Where as the size of the array is different that we have defined
already to a fixed length, which may be 100, 200 or even greater.
An array is a data structure in which identical data types are stored. Every array has a data type i.e. name and
size. Data type can be any valid data type. The size of the array tells how many elements are there in the array.
The arrays occupy the memory depending upon their size and have contiguous area of memory. We can access
the arrays using the array index.
Difference between Programming and Data Structure?
Programming is very wide topic and covers lots of computer science concepts. In simple words programming
is developing software to automate or solve a problem, with the help of different data structures and
algorithms.
While data structure is a part of programming. Data structures are instructions to solve a problem by using
computer resources efficiently.
What are LValues Variables?
Lvalue variables are those variables that can used on left side to save a value.
Variables are labels of memory locations that we want to use in our program. Assigning a value to variable is
saving value on a memory location.
In following example int x = 10;
Here x is Lvalue and holding a value 10.
int y[10];
Here y is not Lvalue and we cannot write y = 20;
Because y is an array and can be used to hold 10 values. In above line out program will not know on which
location it should save value 20.
What is Index?
Index is location of element in an array. With the help of index we can reach to any element in the array. Here
is example of using index
int grades[10]; // declaring an integer array to store 10 integer values
grades[4] = 3; // assigning integer 3 to 5th location of array. here 4 is index of element.
What is Node?
These are the elements that make it possible to have a linked list. Without them, there would be no listing.
Each node contains two parts; a part for the data and a part for the address of the next element. As you can see,
this will use pointers.
that accepts a pointer of type Node, further assigned to nextNode data member of the object. This method is
used to connect the next node of the linked list with the current object. It is passed an address of the next node
in the linked list.
In this case, we start the index of the array from 1 just for simplification against the usual practice in which the
index of an array starts from zero in C++. It is not necessary to always start the indexing from zero.
Short Notes of CS301 By Muhammad Usman
(IT OF VU)
We provide all categories of final year project (CS619) and short notes
Sometimes, it is required to start the indexing from 1. For this, we leave the zeroth position and start using the
array from index 1 that is actually the second position. Suppose we have to store the numbers from 1 to 6 in
the array. We take an array of 7 elements and put the numbers from the index 1. Thus there is a
correspondence between index and the numbers stored in it. This is not very useful. So, it does not justify the
non-use of zeroth position of the array out-rightly. However for simplification purposes, it is good to use the
index from 1.
There are number of limitations of array data structure. Most common are as follows:-
1O.nce an array is created, its size cannot be altered
Array provides inadequate support for inserting and deleting operations.
A linked list is a popular data structure to store data in sequential order. Meanwhile, linked list structure allow
following operations which overcomes limitation of array: for example
1. Retrieve an element from list.
2. Insert a new element to the list.
3. Delete an element from the list.
4. Find how many elements are in the list.
5. Find a specific element is in the list.
6. Find if this list is empty.
Example:
if we are executing our program Test.exe we will use this command in cmd. Test.exe
If we want to pass arguments while executing our program, we can write this command. Test.exe abc def gh i 1
5 xyz
Here Test.exe is our program executable file and others are command line arguments we are passing during
execution.
C++ will consider Test.exe as command line argument too. Now argc variable will hold 7 as it is number of
command line arguments and argv will hold all command line arguments we passed.
What is the Josephus problem (or Josephus permutation) ?
In computer science and mathematics, the Josephus problem (or Josephus permutation) is a theoretical problem
related to a certain counting-out game.
There are people standing in a circle waiting to be executed. After the first man is executed, certain number of
people are skipped and one man is executed. Then again, people are skipped and a man is executed. The
elimination proceeds around the circle (which is becoming smaller and smaller as the executed people are
removed), until only the last man remains, who is given freedom.
What is the difference between doubly link list and single link list?
If you look at single link list, the chain is seen formed in a way that every node has a field next that point to the
next node. This continues till the last node where we set the next to NULL i.e. the end of the list. There is a
headNode pointer that points to the start of the list. We have seen that moving forward is easy in single link list
but going back is difficult. For moving backward, we have to go at the start of the list and begin from there. Do
you need a list in which one has to move back or forward or at the start or in the end very often? If so, we have
to use double link list.
In doubly-link list, a programmer uses two pointers in the node, i.e. one to point to next node and the other to
point to the previous node. Now our node factory will create a node with three parts. First part is prev i.e. the
pointer pointing to the previous node, second part is element, containing the data to be inserted in the list. The
third part is next pointer that points to the next node of the list. The objective of prev is to store the address of
the previous node.
Now in the start, when our list is empty, the current has value 0 i.e; current is pointing to the 0th location of
array which is empty.
When we want to insert first item into the list, we first increment value in the current, so now current has value
1 i.e; current is pointing to the 1st location of array. So here we insert the first item.
That is how we keep track of the current item in the array list.
Consider the following example to understand the current position.
Suppose you are reading a page and using your finger to point at the word you are reading. As you read the
next word in the line, you move your finger towards next. Now at any time, if you or someone wants to check
which word you are reading, simply check which word your finger is pointing at.
What are Arrays advantages over Linked list? Arrays advantages over Linked list:
Arrays allow random access to its elements and thus the complexity is order of O(1).
Linked lists allow only sequential access to elements. Thus the algorithmic complexity is order of O(n).
Arrays do not need an extra storage to point to next data item. Each element can be accessed via indexes.
Linked lists require an extra storage for references. This makes them impractical for lists of small data items
such as characters or Boolean values.
What is Node?
We form a link list by joining nodes, a node consists of two fields first is used to store the actual object value
and second is used to store a reference to the next node. infect a linked list is a chain of these nodes and each
node have a pointer or reference to the next node while the last node have a null pointer.
difference between Find and back in linked list.?
Find() method uses to find an element in a data structure whereas Back() function of the list will move the
current pointer one item back, for example, if the current pointer point to item no 3 of the list and we call the
back() function of this list, after this call the current pointer (means current item) will be item no. 2. Find() and
Back are not one step operations, it is because sometimes during Find() operation we may have to search the
entire list in order to find some particular element say x whereas in the back() method, we move the current
pointer one position back. Moving the current pointer back, one requires traversing the list from the start until
a node reach, whose next pointer points to current node.
Short Notes of CS301 By Muhammad Usman
(IT OF VU)
We provide all categories of final year project (CS619) and short notes
Write a function that takes as an input a pointer to the head of a linked list and determines whether the list is
circular or if the list has an ending node. If the linked list is circular then your function should return true,
otherwise your function should return false if the linked list is not circular. You can not modify the linked list
in any way.
This is an acyclic (non-circular) linked list:
You should start out this problem by taking a close look at the pictures of a circular linked list and a singly
linked list so that you can understand the difference between the 2 types of lists.
The difference between the 2 types of linked lists is at the very last node of the list. In the circular linked list,
you can see that the very last node (37) links right back to the first node in the list – which makes it circular.
However, in the acyclic or non-circular linked list you can see that the end node does not point to another node
in the linked list and just ends.
It is easy enough to know when you are in an acyclic linked list – the pointer in the end node will just be
pointing to NULL. However, knowing when you are in a circularly linked list is more difficult because there is
no end node, so your function would wind up in an infinite loop if it just searches for an end node. So, there
has to be a solution other than just looking for a node that points to NULL, since that clearly will not work.
Diffrence between josephus problem and circularly linked?
In circularly link list, the last node is connected to the head node. Joseph problem is an application of circularly
link list. We use circular link list to solve the Joseph problem.
Analysis of Linked List
§add
we simply insert the new node after the current node. So add is a one-step operation.
§remove
§remove is also a one-step operation
§find
§worst-case: may have to search the entire list
Short Notes of CS301 By Muhammad Usman
(IT OF VU)
We provide all categories of final year project (CS619) and short notes
§back
§moving the current pointer back one node requires traversing the list from the start until the node
Doubly-linked List
§Moving forward in a singly-linked list is easy; moving backwards is not so easy.
§To move back one node, we have to start at the head of the singly-linked list and move forward
until the node before the current.
§To avoid this we can use two pointers in a node: one to point to next node and another to point to the previous
node:
isEmpty() is a Boolean function which will return true if stack is empty and return false if it is not empty;
means there may be one or more elements in the stack.
isFull() is also a Boolean function which will return a Boolean value. If it returns true, it means that the stack is
full and no more elements can be inserted and if it returns false, it means stack is not full and an element can
be inserted into it.
What are stacks and how are they affected in Data Structure?
A stack is a list with the restriction that inserts and deletes can be performed in only one position, namely the
end of the list called the top.
Stack is used in infix to postfix conversion, function calls.
The difference between an array pointer and an ordinary pointer is that the array name is a constant pointer. It
always contains the memory address of the first element of the array. As value of constant can never be
changed or reassigned any other address so you can not perform an increment operator on an array pointer.
Hence, you can not use (*Y)++ and so, in case Y is the name of an array.
What are stacks and how are they affected in Data Structure?
A stack is a list with the restriction that inserts and deletes can be performed in only one position, namely the
end of the list called the top.
Stack is used in infix to postfix conversion, function calls.
Dynamic data:
Dynamic data or transactional data denotes information that is asynchronously changed as further updates to
the information become available.The opposite of this is persistent data, which is data that is infrequently
accessed and not likely to be modified. Dynamic data is also different from streaming data, in that there is no
constant flow of information. Rather, updates may come at any time, with periods of inactivity in between.
Stack:
in computer science, a stack is a last in, first out (LIFO) abstract data type and data structure. A stack can have
any abstract data type as an element, but is characterized by only two fundamental operations: push and pop.
The push operation adds to the top of the list, hiding any items already on the stack, or initializing the stack if
it is empty. The pop operation removes an item from the top of the list, and returns this value to the caller. A
pop either reveals previously concealed items, or results in an empty list. Stacks have many applications. For
example, as processor executes a program, when a function call is made, the called function must know how to
return back to the program, so the current address of program execution is pushed onto a stack. Once the
function is finished, the address that was saved is removed from the stack, and execution of the program
resumes. If a series of function calls occur, the successive return values are pushed onto the stack in LIFO
order so that each function can return back to calling program. Stacks support recursive function calls in the
same manner as conventional non recursive calls.
ADTs allows the creation of instances with well-defined properties and behaviour. In object- orientation ADTs
are referred to as classes. Therefore a class defines properties of objects which are the instances in an object-
oriented environment.
ADTs define functionality by putting main emphasis on the involved data, their structure, operations as well as
axioms and preconditions. Consequently, object-oriented programming is ``programming with ADTs'':
combining functionality of different ADTs to solve a problem. Therefore instances (objects) of ADTs (classes)
are dynamically created, destroyed and used.
What is the difference between A[current++] and A[++current] please Explain because they
are totally different when implemented it in the stack?
To understand the difference between above mentioned statements, you have to understand the difference
between pre and post increment operator. Let me explain you with an example.
Suppose we have a variable x int x=10;
Now we will apply pre and post increment operator over it.
cout”x= “x++;
Short Notes of CS301 By Muhammad Usman
(IT OF VU)
We provide all categories of final year project (CS619) and short notes
Now in the above statement, I have used post increment operator with x. The result of the above statement will
be 10. As in post increment operator, the value is used first and then the increment is applied. So firstly the
value is printed and then it is incremented.
What is the difference between A[current++] and A[++current] please Explain because
they are totally different when implemented it in the stack?
To understand the difference between above mentioned statements, you have to understand the difference
between pre and post increment operator. Let me explain you with an example.
Suppose we have a variable x int x=10;
Now we will apply pre and post increment operator over it. cout”x= “x++;
Now in the above statement, I have used post increment operator with x. The result of the above statement will
be 10. As in post increment operator, the value is used first and then the increment is applied. So firstly the
value is printed and then it is incremented.
int isEmpty(){return ( current == -1 );} // Will return true when stack is empty int isFull(){ return ( current ==
size-1);}
In the constructor of the class stack, the member variable current is initialized to -1. When an element is
inserted in the stack, current is incremented by 1. Now in isEmpty method we check whether the value of
current is -1 or not. If the value is -1 the return statement will return true. If stack even has one element, the
function will return false.
Stack can only hold elements equal to the size of stack. If the size is 10 then stack can only have 10 elements
in it. As we are incrementing the value of current during insertion, so when the value of current reaches the
value of size, it means that now there is no more capacity in the stack. isFull method compare the value of
current with the value of size. If both are equal it returns true otherwise false.
int pop(){ return A[current--];} // The pop function void push(int x){A[++current] = x;}
will pop and push?
During the push function, if the stack is not full yet than the value is inserted in the stack. Before the value is
inserted the value of current is incremented first because its value is one less than the current empty space.
As stack follow LIFO method to pop the value. So the pop will return the value at the index current.
when we write the method: int *y = new int[10]
Does the new method in this command returns the address of the 1st location to a pointer *y? int *y = new
int[10] line is reserving the memory for 10 integer elements and giving address of first element to integer point
y.
Let us consider that you declare an array size 3 to store 3 elements of stack in the following way int a[2];
In the above case, size 3 refers to the numbers of elements of stack in the array. But the array starts from index
0, so 2 will be the last index of array which is one less than size. So that’s why we use
int isFull()
{ return ( current==size-1); }
this pointer is used to access data member and function of current object. It is not necessary to use this pointer.
Compiler uses it implicitly. Here we are using this pointer to differentiate between local variable Object and
Node class data member Object. When we want to access any data member or function using pointer then we
use arrow sign. When we want to access data member or function using object of class then we use dot sign.
and associativities is just one way. However, it is not the most general way: this model cannot give an operator
more precedence when competing with '−' than it can when competing with '+', while still giving '+' and '−'
equivalent precedences and associativities.
INFIX,POSTFIX,PREFIX?
A major application that illustrates the different types of stacks and the various operations and functions
defined upon them.
A + B à Infix
+ AB à prefix AB+ à postfix
A + (B * C) A + (BC*) A(BC*)+ ABC * +
The following is the order of precedence (highest to lowest)
Exponentiation
Multiplication / division Addition / subtraction
Infix
A+B
A+B–C
(A+B) * (C – D)
Short Notes of CS301 By Muhammad Usman
(IT OF VU)
We provide all categories of final year project (CS619) and short notes
A $ B * C – D + E / F / (G + H)
postfix
AB+
AB + C – AB+ CD- *
AB$C*D-EF / GH + / +
Prefix
+AB
- + ABC
* + AB – CD
+ - * $ ABCD / / EF + GH
What is the benefit writing implementation separately ,if we can write it in same program.?
Public member functions exposed by a class are called interface. Purpose of writing interface in a different file
with .h extension and writing implementation in different file with .cpp extension is to separate interface and
implementation details of your program. Separation of implementation from the interface is good software
engineering.
Separating interface and implementation allows you to change the implementation independently of the
interface. This helps to deal with changing requirements.
For example, let us consider that one year ago, you developed an application by separating interface and
implementation. You developed that application in which data processing capability was not so fast. But with
the passage of time you come to know that you should change the implementation of your application so that
data processing capability may become fast. For this purpose you replaced old implementation with the some
new better and faster implementation without having to change the interface of the system.
User is only concerned about ways of accessing data (interface)
Advantages
User has no concern about the internal representation and implementation of the class
For example, when we say that insertion in a linked list is a constant time operation, then it means that
process of inserting a node in a linked list will take a particular amount of time i.e. 5 milliseconds. And if we
change the value to be inserted then the time will not exceed more than 5 milliseconds.
What is Traversing?
Traversing means visiting each and every element in a data structure, at least once. Traversing is used in
searching and printing elements from a data structure.
What is the postfix expression.
Postfix expression is in the form of ABO where, A and B are numbers or also postfix expression
and O is operator (+, -, *, /).e.g. AB+.
The reason to convert infix to postfix expression is that postfix expression evaluation is easier by using a stack.
In postfix expression evaluation, maintain a stack and scan the postfix expression from left to right. If the
element is a number, push it into the stack and if the element is an operator O, pop twice and get A and B
respectively. Calculate BOA and push it back to the stack. When the expression is ended, the number in the
stack is the final answer.
For example, for given 3 6 9*+ 3- expression, start scanning from left. Follow the following given steps;
i. First, push(3) into the Stack
ii. Then, push(6) into the Stack
iii. Push(9) into the stack
iv. Now we see an operator *, that means we can get an new number by calculation
v. Pop the first two numbers and perform calculations on these numbersi.e.6*9=54
vi. Push the new number back into the stack
vii. Then we see the next operator +, pop the top two values and perform the calculation
3+54=57
viii. Push the new number back
ix. We see the next number 3, Push (3) into the stack
x. Then we see the next operator -, pop the top two values and perform the calculation
57-3= 54
54 is the required result.
Examples:
evaluated and then its result will be added to other operand. If there are * and / operators in
an expression (both have the same precedence) then the operator which occurs first from left
will be evaluated first and then the next, except you force any operator to evaluate by putting
parentheses around it.
The following table explains the precedence of the arithmetic operators:
OPERATORS OPERATIONS PRECEDENCE (ORDER OF EVALUATION)
() Parentheses Evaluated first
Multiplication, Division, Evaluated second. If there are several, they are
*, /, or % Modulus evaluated from left to right
Evaluated last. If there are several, they are
+ or - Addition, Subtraction evaluated from left to right
in the postfix form, parentheses are not used. Consider the infix expressions as ‘4+3*5’ and ‘(4+3)*5’. The
parentheses are not needed in the first but
are necessary in the second expression. The position of operators and operands in the expression makes it clear
in which order we have to do the multiplication and addition.
Short Notes of CS301 By Muhammad Usman
(IT OF VU)
We provide all categories of final year project (CS619) and short notes
A fatal error usually occurs due to many reasons; some are given below:
User may have tried to access an illegal memory location
Invalid data or code has been accessed
A Program attempts to divide an integer by zero.
Short Notes of CS301 By Muhammad Usman
(IT OF VU)
We provide all categories of final year project (CS619) and short notes
getche(); return 0;
}
What is the purpose of using(*)?
With reference to pointers, * can be used to declare a pointer, like char * aName; (aName is a pointer of type
char)
Pointers are special type of variables in which a memory address is stored. They contain a memory address,
not value of the variable.
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 pretty common. For example, we queue up while depositing a utility bill or
purchasing a ticket. The objective of that queue is to serve persons in their arrival order; the first coming
Short Notes of CS301 By Muhammad Usman
(IT OF VU)
We provide all categories of final year project (CS619) and short notes
person is served first. The person, who comes first, stands at the start followed by the person coming after him
and so on. At the serving side, the person who has joined the queue first is served first.
what are Templates?
Through templates we can create generic functions and classes. In a generic function or class, the type of data
upon which the function or class operates is specified as a parameter.
Thus, you can use one function or class with several different types of data without having to explicitly re-code
specific versions for each data type.
The syntax of the template class is:
template <class T> class class-name()
{
//definition of class
};
In the definition of the class where the generic data type is required, we write T. For example, there is a class
in which we want to write int data type. The int is the data type that may be a float or double at different times.
For this, T is written wherever we are using int in the class definition.
What are the local, global variables in the function and the stack in the function?
These variables only exist inside the specific function that creates them. They are unknown to other functions
and to the main program. As such, they are normally implemented using a stack. Local variables cease to exist
once the function that created them is completed. They are recreated each time a function is executed or called.
Global:
global variables are declared outside the boundary of the function. These variables can be accessed by any
function comprising the program. They are implemented by associating memory locations with
variable names. They do not get recreated if the function is recalled.
stack in function:
Short Notes of CS301 By Muhammad Usman
(IT OF VU)
We provide all categories of final year project (CS619) and short notes
tack is a data structure that stores information about the active subroutines of a computer program. This kind of
stack is also known as an execution stack, control stack, function stack, or run-time stack, and is often
shortened to just "the stack". Although maintenance of the call stack is important for the proper functioning of
most software. Whenever we call a function then compiler will create a stack for the function and first of all it
places the return address of the function where the control will go back after executing the function. After this
it place the arguments of the function on the stack. After the execution of the function called the programs start
its execution from the next line after the function call by taking return address from the stack.
peek() returns the top item from the stack but does not remove it. It needs no parameters. The stack is not
modified.
isEmpty() tests to see whether the stack is empty. It needs no parameters and returns a boolean value. size()
returns the number of items on the stack. It needs no parameters and returns an integer.
C++ Templates
§We need a stack of operands and a stack of operators.
§Operands can be integers and floating point numbers, even variables.
§Operators are single characters.
§We would have to create classes FloatStack and CharStack.
§Yet the internal workings of both classes is the same.
§We can use C++ Templates to create a “template” of a stack class.
§Instantiate float stack, char stack, or stack for any type of element we want.
Use of Queues??
§Out of the numerous uses of the 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, FlightSimulator
§Each object and action in the simulation has a counterpart in real world.
§If the simulation is accurate, the result of the program should mirror the results of the real-world event.
§Thus it is possible to understand what occurs in the real-world without actually observing its occurrence.
§Let us look at an example. Suppose there is a bank with four tellers.
Short Notes of CS301 By Muhammad Usman
(IT OF VU)
We provide all categories of final year project (CS619) and short notes
Out of the numerous uses of the 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 etc.
modification that we do to the local variables will have an effect in their counterpart variables passed as
arguments in the call to the function.
Example
Queue Operations
Enqueue(X) – place X at the rear of the queue. Dequeue() -- remove the front element and return it. Front() --
return front element without removing it.
IsEmpty() -- return TRUE if queue is empty, FALSE otherwise
Implementing Queue
§Using linked List: Recall
§If we use an array to hold queue elements, both insertions and removal at the front (start) of the array are
expensive.
§For the stack, we needed only one end; for queue we need both.
Short Notes of CS301 By Muhammad Usman
(IT OF VU)
We provide all categories of final year project (CS619) and short notes
§To get around this, we will not shift upon removal of an element.
§We have inserts and removal running in constant time but we created a new problem.
§Cannot insert new elements even though there are two places available at the start of the array.
Complete Binary Tree: If every non-leaf node has non-empty left and right subtrees and all leaf nodes are at
the same level.
So, complete binary tree is a strict binary tree with the restriction that all leaf nodes must be at the same level.
Implementation of Priority Queues?
There are a variety of simple, usually inefficient, ways to implement a priority queue. They provide an analogy
to help one understand what a priority queue is. For instance, one can keep all the elements in an unsorted list.
Whenever the highest-priority element is requested, search through all elements for the one with the highest
priority. (In big O notation: O(1) insertion time, O(n) pull time due to search.)
Full binary tree are a complete binary tree but reverse is not possible, and if the depth of the binary is n the no.
of nodes in the full binary tree is ( 2^n-1 ). It is not necessary in the binary tree that it have two child but in the
full binary it every node have no or two child.
A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and
all nodes are as far left as possible.
Short Notes of CS301 By Muhammad Usman
(IT OF VU)
We provide all categories of final year project (CS619) and short notes
A complete binary tree can be used to represent a heap. It can be easily represented in contiguous memory with
no gaps (i.e. all array elements are used save for any space that may exist at the end)
What is Level?
Level
The level of a node in a binary tree is defined as follows:
Root has level 0,
Level of any other node is one more than the level its parent (father).
The depth of a binary tree is the maximum level of any leaf in the tree.
A binary tree is heap-ordered if the key in each node is larger than (or equal to) the keys in that nodes two
children (if any)
Uses and Properties of Binary tree ? Uses for Binary Trees…
Use for storing and retrieving information
Insert, delete, and search faster than with a linked list
Take advantage of logn height
Idea: Store information in an ordered way (keys)
A Property of Binary Search Trees
The key of the root is larger than any key in the left subtree
The key of the root is smaller than any key in the right subtree
Note: Duplicated keys are not allowed
How to insert some new numbers in the tree?
Binary tree is a tree like (means hierarchical) data structure in which each node has at most two child nodes,
these child nodes are called left child (or left subtree) and right child (or right subtree), while binary search tree
(BST) is a special binary tree with the following properties,
The left child (left subtree) of a node contains only those nodes which have values less than the value of this
node.
The right child (right subtree) of a node contains only those nodes which have values greater than the value of
this node.
Both the left and right subtrees must also be binary search trees.
So inorder to insert elements in binary search tree, you should have to keep in mind the properties of BST that
has been discussed above. Now let us consider a string
14, 15, 4
Now 14 i.e. first elements will be root node of BST. As 15 is greater than 14 so 15 will become right child of
14. Similarly as 4 is less than 14 so 4 will become left child of node 14.
– Inorder: We visit the left subtree then we visit the node, then we visit the right subtree void
inOrder(BinaryTreeNode t)
{
if (t != null)
{
inOrder(t.leftChild); visit(t); inOrder(t.rightChild);
}
}
Short Notes of CS301 By Muhammad Usman
(IT OF VU)
We provide all categories of final year project (CS619) and short notes
– Postorder: We visit the left and right subtree and then we visit the node. This is what normally authors mean
if they mention just depth -first traversal
void postOrder(BinaryTreeNode t)
{
if (t != null)
{
postOrder(t.leftChild); postOrder(t.rightChild); visit(t);
}
}
How can we determine, whether data structure is recursive or not?
Recursive data structures are used for recursive problems, where Recursive problems are those problems in
which the solution depends on the solution to smaller instances (occurrences) of the same problem.
For example, we need to find the sum of first 100 numbers (i.e. sum of 1-100). Now,
Sum of 1-100 = 1+ (Sum of 2-100)
Sum of 2-100 = 2+ (Sum of 3-100)
Sum of 3-100 = 3+ (Sum of 4-100)
Sum of 4-100 = 4+ (Sum of 5-100)
The (Sum of 2-100), (Sum of 3-100), (Sum of 4-100) etc are the smaller instances of the main problem.
When a data structure solves a problem which is recursive in nature, then the data structure may be called
recursive data structure.
Preorder Traversal (cont.)
Visit the root of the tree first, then visit the nodes in the left subtree, then visit the nodes in the right subtree
Preorder(tree)
If tree is not NULL { Visit Info(tree) Preorder(Left(tree)) Pre Order(Right(tree)
}
Inorder Traversal (cont.)
Visit the nodes in the left subtree, then visit the root of the tree, then visit the nodes in the right subtree
Inorder(tree)
If tree is not NULL { Inorder(Left(tree)) Visit Info(tree) Inorder(Right(tree))
}
Postorder Traversal
Visit the nodes in the left subtree first, then visit the nodes in the right subtree, then visit the root of the tree
Postorder(tree)
If tree is not NULL { Postorder(Left(tree)) Postorder(Right(tree)) Visit Info(tree)
}
A breadth-first traversal consists of visiting the nodes based on their level in the tree. It visits all nodes with
level
depth 0, then depth 1, then depth 2, and so on. Use a queue to implement breadth first traversal
Binary tree is a tree like (means hierarchical) data structure in which each node has at most two child nodes,
these child nodes are called left child (or left subtree) and right child (or right subtree), while binary search tree
(BST) is a special binary tree with the following properties,
The left child (left subtree) of a node contains only those nodes which have values less than the value of this
node.
The right child (right subtree) of a node contains only those nodes which have values greater than the value of
this node.
Both the left and right subtrees must also be binary search trees.
When a function calls itself then it is called recursion or recursive call.
want the objects created in a function to be destroyed. The answer to this is dynamic memory allocation. All
the variables or objects created in a function that we want to access later are created on memory heap
(sometimes called free store) using the dynamic memory allocation functions or operators like new. Heap is an
area in computer memory that is allocated dynamically. You should remember that all the objects created using
new operator have to be explicitly destroyed using the delete operator.
So now, we understand that we cannot pass references to transient objects. If we want to use the
objects later we create them on heap and keep the address
}
int main() { programming x; x.output();
return 0;
}
If make a class for Node and have a method as void set(int object); what does the int object here means?
In method
void set(int object);
A variable of type int is passed by value. Here object is simply a variable name of type int. You can also use
any other variable name instead of object like data e.g.
void set(int data);
2: (14, 4, 15)
3: (15, 4, 14)
5: (14, 15, 4)
6: (15, 14, 4)
When we apply permutation then these 6 are the possible ways in which the above mentioned tree can be
traversed. Root, left and right child will remain the same only the sequence of their traversal from the tree will
be change.
The left child (left subtree) of a node contains only those nodes which have values less than the value of this
node.The right child (right subtree) of a node contains only those nodes which have values greater than the
value of this node.
Both the left and right subtrees must also be binary search trees.
AVL tree is just like binary search tree. But difference between BST and AVL tree is that, during insertion of
nodes, AVL tree re-balances itself when the balance factor of any node becomes more than -1 or 0 or 1. AVL
tree re-balances itself by applying either single or double rotation on unbalanced node in such away that
balance factor again becomes either -1 or 0 or 1.
What is balance AVL Tree?
The balance of a node in a binary tree is defined as the height of its left subtree minus height of its right
subtree.
On the basis of this definition, a Balanced AVL tree will be a an AVL tree whose each node has a balance of
either 1, 0 or -1, while the balance of an empty tree is -1.
Statement Event* e=node[0]; is incorrect and it will given an error. It is because in order to save the first
address of array in pointer of type Event, you should use new operator for dynamic memory allocation in the
following way
Event* e=new Event[10]
Or in case of primitive data type like int, you should write the statement in the following way int* e= new
int[10];
Explain the difference of a binary tree and binary search tree?
Binary tree is a tree in which a node can only have two children at most. The order of insertion of nodes in the
tree does not matter in case of binary tree.
Binary search tree is a type of binary tree. It is like binary tree except, the left child
contains only nodes with values less than the parent node and the right child only contains nodes with values
greater than the parent.
Cases of Rotation
The single rotation does not seem to restore the balance. We will re-visit the tree and rotations to
identify the problem area. We will call the node that is to be rotated
as a (node requires to be re-balanced). Since any node has at the most two children, and a height
imbalance requires that a ’s two sub-trees differ by two (or –2), the violation will occur in four cases:
Once we insert a node in the tree, it is necessary to check its balance to see whether it is within AVL
defined balance. If it is not so, then we have to rotate a node. The balance factor of the node containing number
4 is zero due to the absence of any left or right subtrees. Now, we see the balance factor of the node containing
number 3. As it has no left child, but only right subtree, thebalance factor is –1. The balance factor of the node
containing number 1 is 0. For the node containing number 2, the height of the left subtree is 1 while that of the
right subtree is 2. Therefore, the balance factor of the node containing number 2 is 1 – 2 = -1. So every node in
the tree in fig. 21.3 has balance factor either 1 or less than that. You must be remembering that the condition
for a tree to be an AVL tree, every node’s balance needs not to be zero necessarily. Rather, the tree will be
called AVL tree, if
the balance factor of each node in a tree is 0, 1 oer –1. By th inside the tree is 0, it will be a perfectly balanced
tree.
way, if the balance factor of each node
Here k1 is the root of the tree while k3 is the right child of the k1. k2 is the inner child. It is
the Y tree expanded again here and the new node will be inserted in the k2’s right subtree C or left subtree B.
As we have to transform the k2 into the root of the tree, so the right rotation between the link k2 and k3 will be
carried out. As a result of this rotation, k2 will come up
and k3 will go down. The subtree B has gone up with the k2 while subtree C is now attached with the k3. To
make the k2 root of the tree, we will perform the left rotation between
then k1 and k2.
At the right side, we have the final shape of the tree. You can see that k2 has become the root of the tree. k1
and k3 are its left and right children respectively. While performing the inorder traversal, you will see that we
have preserved our inorder traversal.
•
Concepts of Single rotation and Double rotation?
Single rotation can restore the balance of the tree if the new inserted node has inserted as per the following
conditions,
Double rotations can restore the balance of the tree if the new inserted node has inserted as per the following
conditions,
α is a node that requires to be re-balanced. In order to know that which node should rotate left or right
in balancing the AVL tree, you need to study the topic “Cases of Rotation” in lecture no. 21 of handouts.
This topic has already been discussed in very deep detail by using graphical trees that which node (or
sub tree) should go left or right during rotations.