Professional Documents
Culture Documents
Lecture 1
Introduction
DATA
• In programming, data represents the input needed for a certain program
to do his work.
VARIABLES
• Variables are memory containers for storing data values.
• It defines a way of organizing all data items that considers not only the
elements stored but also their relationship to each other.
INTRODUCTION-DATA
STRUCTURES
• The term data structure is used to describe the way data is stored.
Search
Insertion
Deletion
REAL EXAMPLES
+ Trees
a *
• Example: arrays, stacks, queues and linked lists organize data in linear order.
LINEAR AND NON-LINEAR
• Trees and Graphs are widely used non-linear data structures. Tree and graph
structures represents hierarchical relationship between individual data elements.
Data Types
Primitive Non-primitive
User-Defined Abstract
PRIMITIVE AND NON-PRIMITIVE
• Primitive Data Structures are the basic data structures that directly
operate upon the machine instructions.
• The collection of data you work with in a program have some kind of
structure or organization.
• No matter how complex your data structures are, they can be broken
down into two fundamental types:
✓ Contiguous
✓ Non-Contiguous.
CONTIGUOUS AND NON-CONTIGUOUS
• In contiguous structures, terms of data are kept together in memory
(either RAM or in a file).
• An array is an example of a contiguous structure. Since each element in
the array is located next to one or two other elements.
CONTIGUOUS AND NON-CONTIGUOUS
• In contrast, items in a non-contiguous structure are scattered in memory,
but we linked to each other in some way.
• A linked list is an example of a non-contiguous data structure. Here, the
nodes of the list are linked together using pointers stored in each node.
DATA STRUCTURES
Lecture 2
Pointers
MEMORY ALLOCATION
• Memory allocation is a process by which computer programs and
services are assigned with physical or virtual memory space.
• The memory allocation is done either before or at the time of program
execution.
• There are two types of memory allocations:
✓ Static memory allocation
✓ Dynamic memory allocation
STATIC MEMORY ALLOCATION
• Static Memory is allocated for declared variables by the compiler.
• The address can be found using the address of operator and can be assigned to
a pointer.
• The memory is allocated during compile time.
• It uses stack for managing the static allocation of memory.
• There is no memory re-usability.
• Once the memory is allocated, the memory size can not change.
• The allocated memory remains from the start to the end of the program.
DYNAMIC MEMORY ALLOCATION
• Memory allocation done at the time of execution (run time).
• It uses heap for managing the dynamic allocation of memory.
• Memory can be freed when not required.
• After memory is allocated, the memory size can be changed.
• The allocated memory can be released at any time during the program.
• Execution is slower than static memory allocation.
POINTERS
• Pointers are variables that hold the addresses of another variables.
• They have data type just like variables, for example an integer type pointer
can hold the address of an integer variable and an character type pointer can
hold the address of char variable.
• Pointers declarations
data_type *pointer_name;
• Ex:
int *p;
char *ch;
POINTERS
• Because the value of a pointer is a memory address, a pointer can store
the address of a memory space of the designated type.
• For example, if p is a pointer of type int, p can store the address of any
memory space of type int.
• C++ provides two operators — the address of operator (&) and the
dereferencing operator (*) — to work with pointers.
ADDRESS OF OPERATOR (&)
• Note that after the statement p = # executes, the value of *p is 78; after
the statement *p = 24; executes, the value of *p is 24.
POINTERS EXAMPLE 1
#include <iostream>
using namespace std;
int main(){
int *p, var=101; //Pointer declaration
p = &var; //Assignment
cout << "Address of var: " << &var << endl;
cout << "Address of var: " << p << endl;
cout << "Address of p: " << &p <<endl;
cout << "Value of var: " << *p <<endl;
return 0;
}
POINTERS EXAMPLE 1
• Output
int_var: 5
Address of int_var: 0x7fff6d7b1d58
f_var: 10.5
Address of f_var: 0x7fff6d7b1d5c
DYNAMIC VARIABLES
• Since a pointer can be used to refer to a variable, your program can
manipulate variables even if the variables have no identifiers to name them.
• The operator new can be used to create variables that have no identifiers to
serve as their names.
• Do it like this:
p = arr;
1
2
3
4
5
6
DELETE DYNAMIC VARIABLES
• A special area of memory, called the freestore (called heap) is reserved
for dynamic variables.
• Any new dynamic variable created by a program consumes some of the
memory in the freestore.
• If your program creates too many dynamic variables, it will consume all
of the memory in the freestore.
• If this happens, any additional calls to new will fail. The size of the
freestore varies from one implementation of C++ to another.
DELETE DYNAMIC VARIABLES
• It is typically large, and a modest program is not likely to use all the
memory in the freestore.
• It is a good practice to recycle any freestore memory that is no longer
needed.
• The delete operator eliminates a dynamic variable and returns the
memory that the dynamic variable occupied to the freestore so that the
memory can be reused.
delete p;
• After the above call to delete, the value of p is undefined and p should be
treated like an uninitialized variable.
DANGLING POINTERS
• When you apply delete to a pointer variable, the dynamic variable it is
pointing to is destroyed.
• At that point, the value of the pointer variable is undefined, which means
that you do not know where it is pointing, nor what the value is where it
is pointing.
• These undefined pointer variables are called dangling pointers.
• To produce the expression *p, the result is unpredictable and usually
disastrous.
• Before you apply the dereferencing operator * to a pointer variable, you
should be certain that the pointer variable points to some variable.
TYPE DEFINITION
• You can assign a name to a type definition and then use the type name to declare variables,
using the keyword typedef.
• These type definitions are normally placed outside of the body of the main part of your
program (and outside the body of other functions) in the same place as struct definitions.
• We will use type definitions to define names for pointer types.
• Syntax: typedef Known_Type_Definition New_Type_Name;
• Example: typedef int* IntPtr;
• The type name IntPtr can then be used to declare pointers to dynamic variables of
type int, as in the following:
IntPtr pointer1, pointer2;
DYNAMIC ARRAYS
• One problem with the kinds of arrays you have used thus far is that you must
specify the size of the array when you write the program.
• But for dynamic arrays, the size of the array can be entered as input to the
program and the dynamic array can be created to be exactly that size.
• Linked lists and arrays are similar since they both store collections of
data.
• Linked lists have their own strengths and weaknesses, but they happen
to be strong where arrays are weak.
ARRAYS DISADVANTAGES
• Arrays disadvantages are:
• The size of the array is fixed. Most often this size is specified at compile
time. This makes the programmers to allocate arrays, which seems "large
enough" than required.
• Generally arrays allocates the memory for all its elements in one block
• For every data item in a linked list, there is an associated pointer that
would give the memory location of the next data item in the linked list.
• The data items in the linked list are not in consecutive memory locations.
They may be anywhere, but the accessing of these data items is easier as
each data item contains the address of the next data item.
LINKED LISTS ADVANTAGES
• Linked lists advantages:
• They are dynamic data structures. i.e., they can grow or shrink during the
execution of a program.
• Many complex applications can be easily carried out with linked lists.
LINKED LISTS DISADVANTAGES
• A single linked list is one in which all nodes are linked together in some
sequential manner. Hence, it is also called as linear linked list.
LINKED LISTS TYPES
• A double linked list is one in which all nodes are linked together by
multiple links which helps in accessing both the successor node (next
node) and predecessor node (previous node) from any arbitrary node
within the list.
• Each node in a double linked list has two link fields (pointers) to point
to the left node (previous) and the right node (next).
• This helps to traverse in forward direction and backward direction.
LINKED LISTS TYPES
• A circular linked list is one, which has no beginning and no end.
• A single linked list can be made a circular linked list by simply storing
address of the very first node in the link field of the last node.
LINKED LISTS TYPES
• A circular double linked list is one, which has both the successor
pointer and predecessor pointer in the circular manner.
ARRAYS VS. LINKED LIST
Arrays Linked Lists
Size of an array is fixed Size of a list is not fixed
Memory is allocated from stack Memory is allocated from heap
It is necessary to specify the number of elements It is not necessary to specify the number of elements
during declaration (i.e., during compile time). during declaration (i.e., memory is allocated during
run time).
It occupies less memory than a linked list for the It occupies more memory.
same number of elements.
Inserting new elements at the front is potentially Inserting a new element at any position can be carried
expensive because existing elements need to be out easily.
shifted over to make room.
Deleting an element from an array is not possible. Deleting an element is possible.
LINKED LIST
• Linked List is called a dynamic data structure because each of the boxes
in the following figure is a variable of a struct or class type that has
been dynamically created with the new operator.
• In a dynamic data structure, these boxes, known as nodes, contain
pointers, diagrammed as arrows, that point to other nodes.
LINKED LIST
• We have pointers inside structs and have these pointers pointing to
structs that contain pointers.
• If you want to change the number in the first node from 17 to 12 .
• One way to accomplish this is with the following statement:
(*head).info = 12;
• The parentheses around *head are not optional.
• You want the dereferencing operation, * , to be performed before the dot
operation, and the dot operator has higher precedence than the
dereferencing one.
LINKED LIST
• C++ has an operator that can be used with a pointer to simplify the notation
for specifying the members of a struct or a class.
• The arrow operator -> combines the actions of a dereferencing operator, * ,
and a dot operator.
• For example, the previous assignment statement can be written more simply
as
head->info = 12;
THE ARROW OPERATOR, ->
• The arrow operator, ->, specifies a member of a struct or a member of a
class object that is pointed to by a pointer variable.
• The syntax is
Pointer_Variable->Member_Name
• This refers to a member of the struct or class object pointed to by the
Pointer_ Variable.
• Which member it refers to is given by the Member_Name.
• For example, Node *p;
p = new Node;
p->info = 30;
CONSTANT NULL
• In C++ programs we use the constant NULL as a marker to signal the end of a
linked list (or the end of any other kind of linked data structure).
• NULL is typically used for two purposes.
• First, it is used to give a value to a pointer variable that otherwise would not
have any value (this prevents an inadvertent reference to memory, since
NULL is not the address of any memory location.)
• The second category of use is that of an end marker (i.e. end of the list).
• It is actually the number 0.
• The definition of the identifier NULL is in a number of the standard libraries,
such as <iostream>.
• It can be assigned to a pointer variable of any pointer type.
LINKED LIST
First, build the node as a separate class:
class Node
{
int info;
Node* link;
};
Then, build the List class which contains the head pointer and the List
methods:
class List {
Node* head;
List() {
head = NULL;
}
};
OPERATIONS ON LINKED LISTS
• Linked list is a very important data structure, used as an abstract data structure ADT
• The basic operations on linked lists are as follows:
1. Display the list items.
2. Insert a node (first , last , certain position).
3. Delete a node.
4. Find the length of the list.
5. Search the list for a given item.
6. Check if the list is empty.
7. Destroy the list.
8. Make a copy of the linked list.
TRAVERSING A LINKED LIST
• We always want head to point to the first node.
• It now follows that we must traverse the list using another pointer of the same type.
• Suppose that current is a pointer of the same type as head. The following code
traverses the list:
Node* ptr;
ptr = head;
while (ptr != NULL) { //Process the current node
ptr = ptr>link; }
ptr
DISPLAYING LINKED LIST ITEMS
• The following code outputs the data stored in each node:
void print() {
if (head==NULL)
{ cout<<"The list is empty";
return; }
Node* ptr=head;
cout<<endl;
cout<<"List items : ";
while(ptr != NULL)
{ cout<<ptr->info<<" ";
ptr=ptr->link; }
}
NODE INSERTION
• Consider the following linked list, suppose we want to insert a node at the beginning
of the list:
5 10 15 20
info link
2
NODE INSERTION
• Consider the following linked list, suppose we want to insert a node at the beginning
of the list:
5 10 15 20
info link
ptr
25
NODE INSERTION
• Consider the following linked list, suppose we want to insert a node at the end of the list:
5 10 15 20
info link
ptr
12
NODE INSERTION
• Consider the following linked list, suppose we want to insert a node in an ordered list:
if (head->info > item) //item will be the first node
{ newnode->link=head;
head=newnode; }
else
{
While (ptr->link != NULL && ptr->link->info < item)
//traversing the list to find the order of the item
ptr=ptr->link;
newnode->link = ptr->link;
ptr->link = newnode;
}
FIND THE LENGTH OF THE LIST
• The following code outputs the count of list items:
int count()
{
Node* ptr = head;
int counter=0;
while (ptr != NULL)
{
counter++;
ptr = ptr -> link;
}
return counter;
}
SEARCH THE LIST
• The following method searches the list for a given item and retrieves its location,
outputs -1 if the item was not found:
int search(int item){
Node* ptr = head;
int loc=1;
while (ptr != NULL)
{ if (ptr->info==item)
return loc;
ptr=ptr->link;
loc++;
}
if (ptr == NULL)
return -1; }
CHECK IF THE LIST IS EMPTY
• The following method outputs true if the list is empty, otherwise it
outputs false:
bool is_empty()
{
return head==NULL;
}
NODE DELETION
• Consider the following linked list,
prev ptr
5 10 15 20
info link
• Suppose that the node with info 15 is to be deleted from the list. We need to do the
following steps:
• Because new items can be added to the stack, we can perform the add operation,
called push, to add an element onto the stack.
• Similarly, because the top item can be retrieved and/or removed from the stack, we
can perform the operation top to retrieve the top element of the stack.
• And the operation pop to remove the top element from the stack.
STACKS
• The push, top, and pop operations work as follows:
• Suppose there are boxes lying on the floor that need to be stacked on a table.
• Initially, all the boxes are on the floor and the stack is empty.
Stacks
Linked
Arrays
Lists
STACKS USING ARRAYS
• Implementation of Stacks as Arrays
• The first element of the stack can be put in the first array slot, the second
element of the stack in the second array slot, and so on.
• The top of the stack is the index of the last element added to the stack.
• An element can be removed from the stack only if there is something in the
stack.
• An element can be added to the stack only if there is room.
• Array is a random-access data structure. Thus, a stack element is accessed
only through the top, not through the bottom or middle. This feature of a stack
is extremely important and must be recognized in the beginning.
STACKS USING ARRAYS
• The push, top, and pop operations work as follows:
STACKS USING ARRAYS
Stack operations
isEmptyStack Determines whether the stack is empty. If it is empty, it returns the value true; otherwise, it
returns the value false.
isFullStack Determines whether the stack is full. If it is full, it returns the value true; otherwise, it returns
the value false.
push Adds a new element to the top of the stack. The input to this operation consists of the stack
and the new element. Prior to this operation, the stack must exist and must not be full.
top Returns the top element of the stack. Prior to this operation, the stack must exist and must
not be empty.
pop Removes the top element of the stack. Prior to this operation, the stack must exist and must
not be empty.
STACKS USING ARRAYS
• Taking into considerations the following global variables, for the stack
implementation to initialize the array.
• Global variables are defined outside of all functions, usually on top of the
program.
• They will hold their value throughout the lifetime of your program and can be
accessed by any function.
PUSH FUNCTION
• The following is the push function.
void pop() {
if (top <= -1)
cout << "Stack is EMPTY" << endl;
else {
cout << "The popped element is " << stack [top] << endl;
top--;
}
}
POP FUNCTION
• If we try to remove an item from an empty stack, the resulting condition is
called an underflow.
• Error checking for an underflow can be handled in different ways.
• One way is as shown previously, or,
• We can check for an underflow before calling the function pop
void pop () {
if (top == NULL)
cout << "Stack is EMPTY"<< endl;
else {
cout << "The popped element is "<< top->info<< endl;
top = top-> link;
}
}
DISPLAY STACK ELEMENTS
• The following is a function to display all elements in the stack.
void display() {
Node* ptr;
if (top == NULL)
cout << "stack is empty";
else {
ptr = top;
cout << "Stack elements are: ";
while (ptr != NULL) {
cout << ptr->info << " ";
ptr = ptr->link;
}
}
cout<<endl;
}
STACKS APPLICATIONS
➢ Runtime Stack
➢ Balanced Symbol checking
➢ Evaluating a postfix expression
➢ Infix to postfix conversion
STACKS APPLICATIONS
STACKS APPLICATIONS
➢ Balanced Symbol checking
CASE STUDY: BALANCED PARENTHESIS
CHECKING
POSTFIX EXPRESSIONS
• The usual notation for writing arithmetic expressions is called infix notation, in
which the operator is written between the operands. For example: a + b
• In infix notation, the operators have precedence. That is, we must evaluate
expressions from left to right, and multiplication and division have higher
precedence than addition and subtraction.
• If we want to evaluate the expression in a different order, we must include
parentheses. For example: a + b * c, we first evaluate * using the operands b and c,
and then we evaluate + using the operand a and the result of b * c.
• A discovered scheme, the postfix notation was used, in which the operators follow
the operands (postfix operators). This has the advantage that the operators appear in
the order required for computation.
POSTFIX EXPRESSIONS
• For example, the expression:
2*3–8/4
• A corresponding postfix expression is:
23*84/-
• The following example shows various infix expressions and their equivalent postfix
expressions.
EVALUATING POSTFIX EXPRESSIONS
• The operations for a queue are analogues to those for a stack, the difference is that
the insertions go at the end of the list, rather than the beginning.
• The rear of the queue is accessed whenever a new element is added to the queue, and
the front of the queue is accessed whenever an element is deleted from the queue.
QUEUE
STACKS VS. QUEUES
Stacks Queues
Uses LIFO (Last in, First out) approach. Uses FIFO (First in, First out) approach.
Items are added or deleted from only one end called Items are added from “Rear” end of the queue and are
“Top” of the stack. removed from the “front” of the queue.
The basic operations for the stack are “push” and The basic operations for a queue are “enqueue” and
“Pop”. “dequeue”.
We can do all operations on the stack by maintaining In queues, we need to maintain two pointers, one to
only one pointer to access the top of the stack. access the front of the queue and the second one to
access the rear of the queue.
The stack is mostly used to solve recursive problems. Queues are used to solve problems related to ordered
processing.
QUEUE APPLICATIONS
• The queue data structure is used in various CPU and disk scheduling. Here we have
multiple tasks requiring CPU or disk at the same time. The CPU or disk time is
scheduled for each task using a queue.
• The queue can also be used for print spooling wherein the number of print jobs is
placed in a queue.
• Call center phone systems use queues to hold the calls until they are answered by the
service representatives.
QUEUE OPERATIONS
• As in a stack, the middle elements of the queue are inaccessible, even if the queue
elements are stored in an array.
• The two key operations are add and delete. We call the add operation addQueue (or
enqueue) and the delete operation deleteQueue (or dequeue).
• Because elements can be neither deleted from an empty queue nor added to a full
queue, we need two more operations:
• isEmptyQueue (checks whether the queue is empty) and
• isFullQueue (checks whether a queue is full).
• We also need an operation, initializeQueue, to initialize the queue to an empty state.
• Moreover, to retrieve the first and last elements of the queue, we include the
operations front and back.
QUEUE OPERATIONS
isEmpty Determines whether the queue is empty. If the queue is empty, it returns the value true;
otherwise, it returns the value false.
isFull Determines whether the queue is full. If the queue is full, it returns the value true;
otherwise, it returns the value false.
front Returns the front, that is, the first element of the queue. Prior to this operation, the queue
must exist and must not be empty.
back Returns the last element of the queue. Prior to this operation, the queue must exist and must
not be empty.
enqueue Adds a new element to the rear of the queue. Prior to this operation, the queue must exist
and must not be full.
dequeue Removes the front element from the queue. Prior to this operation, the queue must exist and
must not be empty.
QUEUES
• As stacks, queues can be implemented as either an array or a linked structure.
Queues
Linked
Arrays
Lists
QUEUES USING ARRAYS
• We need to decide how many variables are needed to implement the queue
using arrays.
• Of course, we need
• an array to store the queue elements,
• the variable front and
• the variable rear
to keep track of the first and last elements of the queue,
and
• the variable MAX to specify the maximum size of the queue.
• Thus, we need at least four member variables.
QUEUES USING ARRAYS
• The following are the four variables needed for the implementation of the queue using an
array.
• Those variables will be either declared as global, or as member variables if we implement a
queue class.
front ++;
3 0
3 1
10 3
QUEUES USING ARRAYS
• One solution is to shift all elements after each dequeue operation but this solution too cost.
• A better solution is the CIRCULAR queue.
• The first array position immediately follows the last array position.
• A new variable queue_size is needed to keep track of the actual size
of the queue (the number of actual elements) and will be initialized by
0.
void dequeue()
{
if (isEmpty())
cout<<"queue is empty";
else
{
cout<<"item = "<< queue[front];
front = (front +1) % MAX;
queue_size --;
}
QUEUES USING ARRAYS
• The following is the print function to display the queue elements.
void printQueue()
{
if (isEmpty())
cout<<"Queue is empty";
else
{ cout<<“Queue elements : ";
int ptr=front;
while (ptr!=rear)
{ cout<<queue[ptr]<<" ";
ptr=(ptr + 1) % MAX;
}
cout<<queue[ptr]<<" ";
}
}
QUEUES USING LINKED LISTS
class Queue
{
public:
Node* front;
Node* rear;
Queue()
{
front = rear = NULL;
}
bool isEmpty()
{
return (front==NULL);
}
};
QUEUES USING LINKED LISTS
• The following is the enqueue (add in Queue) function
void enqueue(int item)
{
Node* newnode = new Node();
newnode->info = item;
newnode->link = NULL;
if (isEmpty())
front = rear = newnode;
else
{
rear -> link = newnode;
rear = newnode;
}
}
QUEUES USING LINKED LISTS
• The following is the dequeue (delete from Queue) function
void dequeue()
{
if (isEmpty())
cout<<"Queue is empty";
else if (front==rear)
{ delete front;
front = rear = NULL; }
else {
Node* ptr=front;
front = front->link;
delete ptr;
}
}
QUEUES USING LINKED LISTS
• The following is the print:
void printQueue()
{
if (isEmpty())
cout<<"Queue is empty";
else {
Node* ptr=front;
cout<<"Queue elements : ";
while (ptr!=NULL) {
cout<<ptr->info<<" ";
ptr=ptr->link;
}
}
}
DATA STRUCTURES
Lecture 8
TREES
• A data structure is said to be linear if its elements form a sequence or a linear
list. Previous linear data structures that we have studied like an array, stacks,
queues and linked lists organize data in linear order.
• A data structure is said to be nonlinear if its elements form a hierarchical
classification where, data items appear at various levels.
• Trees and Graphs are widely used non-linear data structures.
• Graphs are nothing but trees with certain restrictions removed.
TREES
TREES
• Tree and graph structures represents hierarchical
relationship that organizes data elements called nodes
by connecting them using links called edges.
a *
+ d
b c
• Depth : The number of edges from the node to the tree’s root node.
➢ Node C has a depth of 1.
• in-order (LVR):
17
41
6
41 9
17
81
9
6 81
TRAVERSAL EXAMPLE
Root
• pre-order (VLR): 17
17
41 41 9
6
9
6 81
81
TRAVERSAL EXAMPLE
Root
• post-order (LRV):
6 17
41
81 41 9
9
17 6 81
EXERCISE 1
– Pre-order: Root
42 15 27 48 9 86 12 5 3 39
42
– In-order:
15 9
15 48 27 42 86 5 12 9 3 39
27 86 3
– Post-order:
48 27 15 5 12 86 39 3 9 42 48 12 39
5
EXERCISE 2
EXAMPLE: EXPRESSION TREES
+
* +
a
a b
a++
a* b
EXAMPLE: C TREES
TREE IMPLEMENTATION
root
left A right
class Node
{
public:
int info;
Node* left;
Node* right;
};
TREE IMPLEMENTATION
class Tree
{
public:
Node* root;
Tree()
{
root=NULL;
}
};
TREE IMPLEMENTATION
• Find 6
• Find 9
• Find 12
• Insert 9
9
BINARY SEARCH TREE
• Delete 4
(leaf node)
BINARY SEARCH TREE
• Delete 10
(node with one child)
BINARY SEARCH TREE
• Delete 14
(node with one child)
BINARY SEARCH TREE
• Delete 8
7
(node with two children)
Find the
maximum
node in the left
subtree
BINARY SEARCH TREE
• Delete 8
10
(node with two children)
OR find the
minimum node
in the right
subtree
DELETING FROM A BINARY SEARCH TREE
• Item not present: do nothing
• Item present in leaf: remove leaf (change to null)
• Item is non-leaf with one child:
Replace current node with that child
• Item is non-leaf with two children:
• Find largest item in the left subtree
• Remove it
• Use it as the parent of the two subtrees
• (Could use smallest item in right subtree)
BINARY SEARCH TREE EXAMPLE
Given the following binary search tree:
• Delete 10
• Delete 22
• Delete 30
• Delete 25
BINARY SEARCH TREE INSERTION
void insert(int item)
{
Node* newnode = new Node;
newnode -> info = item;
newnode -> left = newnode -> right = NULL;
Node* ptr=root;
Node* prev=NULL;
if (root == NULL)
root = newnode;
// continued
BINARY SEARCH TREE INSERTION
else
{
while(ptr != NULL)
{
prev=ptr;
if(item<ptr->info)
ptr=ptr->left;
else
ptr=ptr->right;
}
//continued
BINARY SEARCH TREE INSERTION
if (item <prev->info)
prev->left= newnode;
else
prev->right=newnode;
}
}
BINARY SEARCH TREE
int tree_min()
{
Node* ptr=root;
If (ptr == NULL)
cout<<“The tree is empty”;
while(ptr->left!=NULL)
ptr = ptr->left;
return ptr->info;
}
BINARY SEARCH TREE
int tree_max()
{
Node* ptr=root;
If (ptr == NULL)
cout<<“The tree is empty”;
while(ptr->right!=NULL)
ptr = ptr->right;
return ptr->info;
}
BINARY SEARCH TREE
int Search(int item) {
int depth = -1;
Node* ptr = root;
while(ptr != NULL) {
depth++;
if(ptr->info == item)
return depth;
else if(item < ptr -> info)
ptr = ptr -> left;
else
ptr = ptr -> right; }
return depth;
}
DATA STRUCTURES
Lecture 7
LINEAR SEARCH
• After traversing the whole array, it is clear that 11 is the lowest value.
• Thus, replace 64 with 11. After one iteration 11, which happens to be the least value in the
array, tends to appear in the first position of the sorted list.
SELECTION SORT
• Second Pass:
• For the second position, where 25 is present, again traverse the rest of the array from index 2 to
index 4 in a sequential manner.
• After traversing, we found that 12 is the second lowest value in the array and it should appear
at the second place in the array, thus swap these values.
SELECTION SORT
• Third Pass:
• Now, for third place, where 25 is present again traverse the rest of the array and find the third
least value present in the array.
• While traversing, 22 came out to be the third least value and it should appear at the third place
in the array, thus swap 22 with element present at third position.
SELECTION SORT
• Fourth pass:
• Similarly, for fourth position traverse the rest of the array and find the fourth least element in
the array
• As 25 is the 4th lowest value hence, it will place at the fourth position.
• The largest value present in the array automatically get placed at the last position in the array
• The resulted array is the sorted array.
SELECTION SORT
void selection(int arr[], int n) //array and size of array
{
int min;
for (int i=0;i<n-1;i++)
{
min = i;
for (int j=i+1;j<n;j++)
if (arr[j]<arr[min])
min=j;
swap(arr[i],arr[min]);
}
}
BUBBLE SORT
• Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent
elements if they are in the wrong order.
• These passes through the list are repeated until no swaps had to be performed during a pass,
meaning that the list has become fully sorted.
• The algorithm is named for the way the larger elements "bubble" up to the top of the list.
• This algorithm is not suitable for large data sets as its average and worst-case time complexity is
quite high.
BUBBLE SORT
• Lets consider the following array as an example: arr[] = {5 , 1 , 4 , 2 , 8}
First pass:
BUBBLE SORT
Second pass:
Third pass:
BUBBLE SORT
Third pass:
BUBBLE SORT
void bubble_sort(int arr[],int n)
{
int temp;
for(int i=0;i<n-1;i++)
for (int j=0;j<n-i-1;j++)
if (arr[j]>arr[j+1])
swap(arr[j],arr[j+1]);
}
REFERENCES
• LECTURE NOTES ON DATA STRUCTURES USING C, L. V. NARASIMHA
PRASAD, E. KRISHNA RAO PATRO, INSTITUTE OF AERONAUTICAL
ENGINEERING DUNDIGAL – 500 043, HYDERABAD 2014-2015
• Tree Data Structure (programiz.com)
• DATA STRUCTURES USING C++, D.S. MALIK, SECOND EDITION
• Data Structures and Algorithm Analysis in C++, Mark Allen Weiss, Florida International
University, Fourth Edition
REFERENCES
• LECTURE NOTES ON DATA STRUCTURES USING C, L. V. NARASIMHA
PRASAD, E. KRISHNA RAO PATRO, INSTITUTE OF AERONAUTICAL
ENGINEERING DUNDIGAL – 500 043, HYDERABAD 2014-2015
• DATA STRUCTURES USING C++, D.S. MALIK, SECOND EDITION
• Queue Data Structure In C++ With Illustration (softwaretestinghelp.com)
REFERENCES
• Lecture Notes On Data Structures Using C, L. V. Narasimha Prasad, E.
Krishna Rao Patro, Institute of Aeronautical Engineering, 2014-2015
• C++ Programming: From Problem Analysis To Program Design, Fifth Edition,
D.S. Malik
• C++ Data Structures, Third Edition, N. Dale, University of Texas.
REFERENCES
• Lecture Notes On Data Structures Using C, L. V. Narasimha Prasad, E.
Krishna Rao Patro, Institute of Aeronautical Engineering, 2014-2015
• C++ Programming: From Problem Analysis To Program Design, Fifth
Edition, D.S. Malik
• https://beginnersbook.com/2017/08/cpp-pointers/
• Chapter 17: Linked Data Structures
REFERENCES
• Lecture Notes On Data Structures Using C, L. V. Narasimha Prasad, E.
Krishna Rao Patro, Institute Of Aeronautical Engineering, 2014-2015
• C++ Programming: From Problem Analysis To Program Design, Fifth
Edition, D.S. Malik
• https://beginnersbook.com/2017/08/cpp-pointers/
• Chapter 12: Pointers and Dynamic Arrays
REFERENCES
• LECTURE NOTES ON DATA STRUCTURES USING C, L. V. NARASIMHA PRASAD,
E. KRISHNA RAO PATRO, INSTITUTE OF AERONAUTICAL ENGINEERING, 2014-
2015
• https://www.w3schools.com/cpp/cpp_variables.asp