Linked List in Data Structure

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 57

Linked List in Data Structure

A linked list is consists sequence of nodes. Nodes are divided into parts,
first part is used for storing data and other part is for the node reference
which is link to next node. Linked list is linear data structure where each
node is link with other node in sequence.

As shown in above figure,


there are four nodes and each node linked with next node, as shown in
figure each node has two fields. One field stored data and other field used
as reference which use to link with next node.
A linked list is a dynamic data structure because the memory to store the
data is created at run time.

Types of Linked List


One way linked list
Two way or doubly linked list
Circular linked list
Header linked list
One Way Linked List

One way linked list is most simple list among all linked lists. It contains data
part or info part and address part or link field. Address part link to the next
node in sequence of nodes. It can be traversed only in one direction that is
forward direction. One way linked list takes less memory because it has
only one pointer or address part.

shown in above figure there are two parts in one way linked list.
The first part called data field. This part contains the information of
the element.
The second part called the address part, which lined to the next node,
contain the address of the next node in one way linked list.
Example

Above figure is example of one way linked list. In this example, each node is
linked with its next node, and has two parts.

Representation of Linked List in Memory

The elements in array are stored in contiguous memory locations. The


nodes of the linked list can be stored anywhere in memory. The address
part or link field that contains the address of its next node connects the
nodes of a linked list. To access the linked list, the address of a first node is
stored in a pointer which is the external pointer variable to the linked list.
START is an external pointer variable to the linked list and every other
node is accessed by the ADDRESS PART of its predecessor node. The last
node of address part is contains a NULL value to indicate the end of the list.

Linked list can be represented by following declarations.

Struct node
{
int data;
struct node*link;
}
Operations on One Way Linked List
Following are the operations on one way linked list.

Traversing
Inserting linked list
Inserting into a sorted linked list
Deleting operation
Searching a linked list
Reversing the direction of list

Traversing a Linked List

In this operation, processing of each node of the list exactly once. It


traverses the list starting from the first node to the end of the list.

ALGORITHM

STEP1 Set PTR = START


STEP2 Repeat while PTR (is not equal to) INFO
STEP3 Apply Process to INFO [PTR]
STEP4 PTR = PTR LINK
[End of step2 loop]
STEP5 Exit
For processing and accessing each node of the list we use a pointer variable
PTR.
Inserting into Linked List

Insertion operation adds a new node to the existing linked list. A new node
can be inserted in number of places in linked list.

FOLLOWING ARE THE CASES OF INSERTING INTO LINKED LIST

Insert at the beginning of the list


Inserting at the end
Insert a node after the given node
Inserting into a sorted linked list
Insert at the beginning of the list - ALGORITHM

STEP1 If (START == NULL) then


Set START == new node
START INFO = ITEM
START LINK = NULL
STEP2 else
STEP3 Set PTR = START
STEP4 START = New node [create new node]
STEP5 START INFO = ITEM
STEP6 START LINK = NULL
[End of if structure]
STEP7 Exit
Insertion at the End - ALGORITHM

STEP1 if (START == NULL) then


Set START = New node
START INFO = ITEM
START LINK= NULL
STEP2 Else
STEP3 Set PTR = START
STEP4 Repeat while (PTR LINK NULL)
PTR = PTR LINK
[End of while loop]
STEP5 PTR LINK = New node
STEP6 PTR = PTR LINK
STEP7 PTR INFO= ITEM
STEP8 PTR LINK = NULL
[End of If structure]
STEP9 Exit
Inserting a node after the given node - ALGORITHM

STEP1 If START = NULL then,


Print: OVERFLOW and Exit
STEP2 Set NEW = START and
START = LINK [START]
STEP3 Set Data [New] = Item
STEP4 If LOC = NULL then
LINK [NEW] = Head and Head = New
Else
LINK [New] = LINK [LOC] and LINK [LOC] = New
STEP5 Stop
Deletion from the Linked List

Deletion operation is to remove a node from the linked list. Following are
the cases of deletion from the linked list.

Deletion of first node of the linked list


Deletion of last node of the linked list
Deletion of node with given information
Deletion of first node of the linked list - ALGORITHM
START is pointer variable which contains the address of first node
STEP1 If (START == NULL) then
Print linked list does not exist and return
STEP2 Else
Set PTR = START
START = LINK [START]
DELETE PTR [End of If Structure]
STEP3 Exit
Deletion of Last Node of the Linked List - ALGORITHM
STEP1 If (START == NULL) then
Print linked list does not exist and return
STEP2 Set TEMP = START
STEP3 If (LINK [TEMP] == NULL) then
Set START = NULL
STEP4 Else
STEP5 Repeat while (LINK [TEMP] NULL)
STEP6 PREV = TEMP
TEMP = LINK [TEMP]
[End of If Structure]
STEP7 LINK [PREV] = NULL
[End of If Structure]
STEP8 Delete TEMP
STEP9 Print ITEM is deleted
STEP10 Exit
Deleting the node with given item of information - ALGORITHM

STEP1 If START = NULL then


Print: Underflow & Exit
STEP2 if ITEM = DATA [Head] then
Head = Link [Head] and Exit
STEP3 Save = Head, PTR = LINK [Head]
STEP4 Repeat STEP5 and STEP6 while PTR NULL
STEP5 IF Data [PTR] == ITEM then link [Save] = LINK [PTR] and Exit
STEP6 Save = PTR, PTR = LINK [PTR]
STEP7 Print: Item not found
STEP8 Stop
Two Way Linked List in Data Structure

A two way linked list is also known as doubly linked list. Each node in two
way linked list divided into three parts. Which is data part and two link
fields. Data part contains the info or data of the node. One link field is used
for forward direction which contains the address of its next node, and
second field is used for backward direction which contains the address of
its previous node.

First link field is link with the next node, and second link field is link with
the previous node. As compare to one way linked list, two way linked list
can traversed in reverse direction with help of backward link field. Sorting
data as two way link require more time and more time, and now we have
two pointer variables START and LAST, which contains the address of first
node and last node.

Representation of two way linked list


Declaration
Struct dnode
{
Struct dnode *back;
int data;
Struct dnode *forw;
}
In declaration data represent the data field and back and forw represent
the two
link fields which contain the address of forward and backward node.

Operations on Two Way Linked List


Following are operations on two way linked list.

Insertion onto a two way linked list


Deletion from two way linked list

Insertion onto a Two Way Linked List


Add a new node to the existing linked list.

Insert new node at the beginning of two way linked list


Insert new node at the end of the two way linked list
Insert new node into a sorted two way linked list
Difference between Single Linked list and Double
Linked List in Data Structure
Difference between Array and Linked List

Advantages and Disadvantages of Linked List

Following are the advantages and disadvantages of linked list

Advantages of Linked List

The link lists are dynamic data structure. So, their size need not be
defined in advance. It may be increased or decrease at any time.
A linked list can store large number of data items and can easily
change size to add more items.
A linked list way to store data when size is unsure and can be change
any time.
Insertion and deletion operations can be performed easily.
Link list are used to manipulate polynomials.
Disadvantages of Linked List

In linked list each node contains a pointer so we need extra space for
the pointer.
Insertion and deletion operations need more intention.
It does not allow random access.
It needs more space and more time.

Garbage Collection

Garbage collection is the collection of unused memory cells or all deleted


space on the list.
Garbage collection usually takes place in two ways- firstly, the computer
run through all the list tagging those cells which are currently in use.
Secondly, the computer runs through the memory collecting those cells
which are currently not in used into free storage list.

Need for garbage collection

Garbage collection is needed, when there is no space at all left in the free
storage list or when computer has no work to do.
Introduction of Stacks

Stack is an abstract data type (ADT), commonly used data structure, which
elements are added and removed from only one end. This end called a top
end.
Stacks follow LIFO (last in, first out) structure

To understand much better let takes example of plates in busy restaurant.


In restaurant, a waiter always take a plate from the top of the stack, and
after using plates waiter again returned plat at the top of the stack.
Let takes another example of shirts as stack. You have 4 different colors of
shirts in stack, and you want blue shirt from stack, which is at 2nd place
right after a green shirt. Then you have to remove red shirt first to pick a
blue shirt. After remove a green shirt top shirt is blue shirt, and after
remove blue shirt you can add green shirt again or throw it away. Similarly
happens in stacks.

Operations on Stack in Data Structure

Following are operations on Stack

Push
Pop
Peek
Push Operation

This operation is used to add the element in stack. In simple words, when
we insert a new element on the top of the stack is known as the push
operation. If have to check the stack before insert an element into the stack
whether it is full or not. We can check it by comparing the SIZE and the TOP
variable of the stack, if stack is full we cannot add new element.

As shown in above figure, before push operation we check the stack,


whether it is full or not. We can see that there is a space, so we perform the
push operation and insert c element into the stack.

Pop Operation

This operation is used to remove the element from stack. In simple words,
when we delete the top most element from the stack, this process known as
the pop operation. We should check the stack before delete element from
stack, whether it is empty or not. If stack is empty, then there no need for
pop operation.
As shown in above figure, there was c element on the top, and we perform
the pop operation, and delete c element from the top of the stack.

Peek Operation

This operation is used to check the top most element of the stack, which
making any change in the stack. We cannot perform any operation or we
cannot make any other modification in stack in this operation.

Representation of Stack in Memory

Following the ways to represent the stack in memory

Array representation of stack


Linked representation of stack
Array Representation of Stack

When implementing a stack of some simple type is most efficiently


implemented with an array.

Algorithm PUSH

This algorithm add a new item on the top of the stack using array
STEP1 [Check for overflow]
If TOP == MAX then
Print overflow and return [stack is full]
Exit
[End of If structure]
STEP2 Set TOP = TOP + 1 [Increment TOP by 1]
STEP3 Set STACK [TOP] = ITEM
STEP4 Print ITEM is inserted at TOP location
STEP5 Exit
STACK It is an array at MAX location
TOP Pointer variable contain the address of top most element
ITEM Inserted item
Algorithm POP

This algorithm use to delete the item from the stack using array
STEP1 [Check for underflow of stack]
If (TOP == 0) then
Print underflow and return [Stack is empty]
Exit
[End of If structure]
STEP2 Set ITEM = STACK [TOP]
STEP3 Set TOP = TOP 1
[Decrement TOP by 1]
STEP4 Exit
Algorithm 3 PEEK

This algorithm use to check or view the top most item of the stack.
STEP1 [Check for underflow of stack]
If (TOP == 0) then
Print underflow and return [Stack is empty]
Exit
[End of If structure]
STEP2 STACK [TOP] ! ITEM
STEP3 Return (ITEM)
STEP4 Exit
Linked Representation of Stack

There are some drawbacks to represent a stack using array. We have to


specify the size of array before compilation. So, the space is totally wastage
if there is less items in stack than given size of array. Similarly, if we give
less memory to the stack, and we want to push more items, then there is
shortage of space.

That is way representation of stack using linked list is more beneficial. In


linked list each node contains two parts, one is DATA part which contains
the data of element, and other is LINK part which contains the address of
next node, link with next node.

Algorithm PUSH

This operation is use to insert a new element in the stack using link list
STEP1 [check for over flow]
If AVAIL == NULL then
Print overflow and return [list is empty]
Exit
[End of If structure]
STEP2 [Create new node]
AVAIL NEW
STEP3 [Modify AVAIL pointer]
LINK (AVAIL) AVAIL
STEP4 [Copy ITEM into new node INFO part]
ITEM INFO (NEW)
STEP5 [Set link part of new node to top]
TOP LINK (NEW)
STEP6 [TOP points to new node]
NEW TOP
STEP7 Exit
AVIAL Pointer, points to first node of the availability
TOP Pointer variable, holds the address of the first node
ITEM New item
Algorithm POP

STEP1 [Check for underflow]


If TOP = NULL then
Print underflow and return
Exit
STEP2 [Copy to element of stack into ITEM]
INFO (TOP) ITEM
STEP3 TOP TEMP
STEP4 [Modify TOP pointer to point to the node in linked list]
STEP5 AVAIL LINK (STORE)
STEP6 STORE AVIAL
STEP7 Exit
AVIAL Pointer, points to first node of the availability
TEMP Local pointer variable, points to the deleted node
Applications of Stacks in Data Structure

Evaluation of Arithmetic Expressions


Recursion
Reversing the String
Quick Sort
Evaluation of Arithmetic Expressions

Stacks are used for evaluation of arithmetic expressions. Following are the
three notations in which we can write arithmetic expressions.

Infix notation
Prefix or polish notation
Postfix or reverse polish notation
Infix Notation

In infix notation, operator must be placed between two operands.


Example D + E, B E * C
Prefix Notation

In prefix notation, operator must be placed before its operands.


Example: +DC
Postfix Notation

In postfix notation, operator must be placed after its operands.


Example DC +
Recursion

Recursion is defined as the process of repeating itself again and again till a
specific condition is met. This condition is called the base condition.
Recursion can be direct or indirect. In direct recursion algorithm calls itself
and in indirect recursion one algorithm calls another algorithm.

Advantages of Recursion

It uses top down approach for problem solving


Factorial, Fibonacci series generation can be easily implemented
using recursion
Recursion functions are easy to understand, and easy to implement.
Disadvantages of Recursion

Most of the programming languages do not support recursion.


It need more storage.
It takes more time
Reversing a String

The stack can be used for reversing a string. Reversing operation reverse
the characters of a string. We can reverse a string using stack by pushing
each character of the string on the stack one by one. After pushing the
characters of the string on the stack, pop the characters from stack which
reverses the order of characters in the string.

Quick Sort

Stacks can be used for sorting data. Sorting is the process of arranging the
elements in some logical order. This logical order may be ascending or
descending in case numeric values or dictionary order in case
alphanumeric values.

Queues in Data Structure

Queue is also linear data structure, which has two ends. One end is used to
insert a element which is known as the rear, and other end is used to
remove the element which is known as front. It follows first in first out
(FIFO) structure.
Means, which element inserted first will remove first.

Example

Let takes example of Queue at ticket counter, in this queue, which person
enter first will leave first. Every person enter from one end which is known
as rear end in queue and leave from other end which is known as front end.
Operations on the Queue

ENQUEUE or Insertion into queue


DEQUEUE or Deletion from queue
PEEK

ENQUEUE (Insertion)

This operation is used to insert the element at the end of the queue. First
thing we have to check the space of the queue, if there is no space then we
cannot insert any element in the queue. If queue has a space then we can
add new element. The new element only can be insert from rear end.

DEQUEUE (Deletion)

This operation is used to delete the element from the front of the queue.
Before using DEQUEUE operation, we have check the queue, whether it is
empty or not. If queue is empty, there is no need of DEQUEUE operation. If
queue is not full, we delete the element using this operation, we delete the
element only from front end.
Peek Operation

This operation is used to check or view the element of the queue without
making any change in the queue. Peek operation has two types. First type is
FRONTPEEK, which use to view the front end of the queue, and second type
is REARPEEK, which use to view the rear end of the queue

Memory Representation of Queues in Data Structure

Following the two ways to represented queues in memory.

Array representation of queue


Linked representation of queue
Array Representation of Queue

We represent queue with the help of an array to hold the items and two
variables- FRONT and REAR.

ENQUEUE (Insertion of Element)

We are going to insert a element in queue.

ALGORITHM

STEP1 [Check for queue overflow]


If (REAR = MAX) then
Print Queue is full
And return
[End of If Structure]
STEP2 If (FRONT = 0 and REAR = 0) then
Set FRONT = 1
Set REAR = 1
Else
STEP3 [Increment REAR]
REAR = REAR + 1
[End of If Structure]
STEP4 [Insert new element]
Queue [REAR] = ITEM
STEP5 Exit
Queue One dimensional array representing queue containing
FRONT REAR pointer variable represent the front and rear end
ITEM New item
Max size of array
DEQUEUE (Deletion of Element)

STEP1 [Check for queue underflow]


If (REAR = 0) then
Print underflow
Return
[End of If Structure]
STEP2 ITEM = QUEUE (FRONT)
STEP3 If (FRINT = REAR)
[Queue contains single element]
FRONT = 0
REAR = 0
[Queue becomes empty]
Else if FRONT < REAR then
FRONT = FRONT + 1
[Increment FRONT by 1]
[End of If Structure]
STEP4 Print the ITEM
STEP5 Exit
Linked Representation of Queue

It is a second method to represent a queue in memory. Linked list


representation of queue is more efficient representation of queues. A linked
list allocates memory to elements at run time.

We use two pointer variable FRONT and REAR which used to store the
address of first node and second node. The value of FRONT pointer is
changed when we delete or remove the element from the queue, and the
value of REAR pointer is change when we insert the element in queue.

EQUEUE (Insert a Element)

STEP1 [Check for overflow]


If (AVAIL = NULL) [Availability list is empty]
Print Overflow
Return
[End of If Structure]
STEP2 [Create new node]
Set NEW = AVAIL
STEP3 [update AVAIL pointer]
AVAIL = AVAIL LINK
STEP4 Set NEW INFO = ITEM [copy ITEM into info part]
STEP5 [Check whether queue is empty or not]
IF FRONT = NULL then [queue is empty]
Set FRONT = NEW
REAR = NEW
Else [queue is not empty]
Set REAR LINK = NEW and REAR = NEW
[End of If Structure]
STEP6 Set NEW LINK = NULL [Set link part of new node to null]
STEP7 Exit
FRONT REAR pointer variables, contains the address of first node and
last node
ITEM New element
AVIAL Pointer Points to the first node
DEQUEUE ( Deletion of Element)

STEP1 [Check for underflow]


If (FRONT = NULL) then
Print Overflow
Return
[End of If Structure]
STEP2 Set ITEM = FRONT INFO
STEP3 If FRONT = REAR then
Set FRONT = NULL
REAR = NULL
Else
Set FRONT = FRONT NEXT
[End of If Structure]
STEP4 Exit
Circular Queue

Circular queue is a linear data structure, where insert element from REAR
end and remove the element form FRONT end. In circular queue, FRONT
end will meet to the REAR end, if circular queue is full. Circular queue
follows First in First Out (FIFO).

In simple words, we can say that a queue is called circular when the last
element comes just before the first element.

Operations on Circular Queue

Insertion into the circular queue


Deletion from the circular queue
Insertion into Circular Queue

QUEUE circular queue


FRONT REAR Pointer variables, store the address of first and rear
element
ITEM is the value to be inserted
Algorithm

STEP1 [Check for overflow]


If (FRONT = 1 and REAR = N) or
(FRONT = REAR + 1) then
Print Overflow
Return
[End of If Structure]
STEP2 If (REAR = 0) then
Set FRONT = 1 and REAR = 1
Else If (REAR = N) then
Set REAR = 1
Else
Set REAR = REAR + 1
[End of If structure]
STEP3 [Insert new data element]
Set QIEIE [REAR] = ITEM
STEP4 EXIT
Deletion from the Circular Queue

STEP1 [Check for underflow]


If (Rear = 0) then
Print underflow
Return
[End of If Structure]
STEP2 Set ITEM = QUEUE [FRONT]
STEP3 If (FRONT = REAR) then
Set FRONT = 0 and REAR = 0
Else If (FRONT = N)
Set FRONT = 1
Else
Set FRONT = FRONT + 1
[End of If Structure]
STEP4 Exit
Sorting
When we sort any type of data in logical order is known as sorting, it can be
in any form such as ascending or descending, alphabetically or in numeric
values. We can see it everywhere in our daily routine, for example, contacts
stored in our mobile phones in alphabetically order, or we search any files
in our office, these files are also stored in alphabetically or numeric values.
So, sorting is comes with searching, we always do sorting, because it make
searching easier.

Sorting is classified into following categories.

Internal Sorting

An internal sort is any data sorting process that takes place entirely within
the main memory of a computer. Internal sorting deals with sorting the
data held in memory of the computer. The internal sorting can reside in
main memory. It is independent of time to read and write a record. The
internal sorting takes input only which can be fit into its memory, so it takes
small input.

External Sorting

External sorting uses secondary memory. External sorting can take large
input and deals with sorting the data stored in data files. When the volume
of data to be sort is very large and cannot be held in computer main
memory then external sorting is used.

Sorting Techniques

Bubble Sort
Insertion Sort
Selection Sort
Quick Sort
Merge Sort
Heap Sort

Bubble Sort

In bubble sort to sort a list, we compare each element in the list with its
successes and interchange them if they are not in proper order such as
ascending or descending order. In the first scanning of the list the largest
element is arranged at its proper place. We repeat the whole process with
one less element each time until or unless we got the sorted list.
Bubble sort is the simplest sort technique among all the sorting techniques.
But this sorting technique is not efficient in comparison to other sorting
techniques.

Example

Suppose we have a array list is A1, A2An which has 6 elements


20, 50, 9, 14, 19, 12.

PASS 1
Compare A1 and A2, which are 20 and 50. 20 < 50 so it remain at
same position.

Compare A2 and A3, which is 50 and 9. 50 > 9 so it will interchange


with each other.
Compare A3 and A4, which is 50 and 14. 50 > 14 so it will interchange
with each other.

Compare A4 and A5, which is 50 and 19. 50 > 19 so it will interchange


with each other.

Compare A5 and A6, which is 50 and 12. 50 > 12 so it will interchange


with each other.

At the end of Pass 1 the largest number 50 has moved to the last position.
Note that the rest of the numbers are not sorted, even though some of them
have changed their positions.

PASS 2
Compare A1 and A2, which is 9 and 20. 9 > 20 so it will interchange
with each other.

Compare A2 and A3, which is 20 and 14. 20 > 14 so it will interchange


with each other.
Compare A3 and A4, which is 20 and 19. 20 > 19 so it will interchange
with each other.

Compare A4 and A5, which is 20 and 12. 20 > 12 so it will interchange


with each other.

Compare A5 and A6, which is 20 and 50. 20 < 50 so it will remain at


same place.

Now we have last element of array is sorted, as shown in following


figure

PHASE 3
Compare A1 and A2, which is 9 and 14. 9 < 14 so it will remain at
same place.

Compare A2 and A3, which is 14 and 19. 14 < 19 so it will remain at


same place.

Compare A3 and A4, which is 19 and 12. 19 > 12 so it will interchange


with each other.
Compare A4 and A5, which is 19 and 20. 19 < 20 so it will remain at
same place, and element A_5 is already sorted.

PHASE 4
Compare A1 and A2, which is 9 and 14. 9 < 14 so it will remain at
same place.

Compare A2 and A3, which is 14 and 12. 14 > 12 so it will interchange


with each other.

Compare A3 and A4, which is 14 and 19. 14 < 19 so it will remain at


same place.

We have Sorted List in Following Figure

Selection Sort

In the selection sort first we find the smallest element in the list and put it
in the first position. Then find the second smallest element in the list and
put it in the second position, this process will go on till the last element of
the list.

Example

Suppose we have a list A= A1, A2 An 45, 54, 34, 43, 10, 8, 4


STEP1 The smallest element in the entire list is 4, which is located at A6, so
it will interchange with A1, which is 45.

STEP2 Now the second smallest element in the list is 10, which located at
A5, so it will interchange by the second element of the list. A5 interchange
with A2.

STEP3 Afterwards, we will find the smallest element of the remaining


unsorted list, the smallest element of the unsorted list is 25. So it will
interchange with A3, which has the value of 34. A3 interchange with A4

STEP4 After that we can see it the smallest element of the unsorted list is
34, which placed at right location, so we will not take any actions.
STEP5 Now we have the sorted list till A4. Lets find next smallest element
from remaining unsorted list, which is 45, then it will interchange with 54.
A6 interchange with A5.

STEP6 Now compare the last two element of list, if the smallest element
placed at the end of the list then it will interchange, otherwise it will remain
at same place. Our given list, last element of the list is larger than other
elements so it will remain at same place.

And now we have sorted list, through selection sort.

Heap Sort

Heap sort is a sorting algorithm that sorts by building a priority queue and
then repeatedly extracting the maximum of the queue until it is empty. The
priority queue used is a heap that shares the space in the array to be sorted.
The heap is constructed using all the elements in the array and is located in
the lower part of the array. The sorted array is constructed from top to
bottom using the locations vacated by the heap as it shrinks.

There are two steps to sort a list by heap sorting

Consider the values of the elements as priorities and build the heap
tree.
Start delete operation of heap sort, by storing each deleted element at
the end of the heap array. In this step we delete the largest element
and place it in the last position in the array
Example
Suppose we have a list A= 45, 23, 20, 10, 40, 30
We have an array list which represent by tree, but it is not a heap.

BUILD THE HEAP TREE

To build a heap, firstly we have to change the elements with each others. So,
firstly start with right child node of root node. Right child nodes child node
is greater than its parent node, then we will interchange both nodes with
each other.

Now we have a tree in below figure

Afterwards come to left child of root node. It right child is greater than its
value, so we going to interchange right child node 40 with its parent node
23.
Now we have heap tree, in which value of every parent node is greater than
its child node.

Sorting a list by Heap Sorting

STEP1 Delete root node of the heap tree, and store it in temporary place.

Now swap 45 with last element of the list

Afterwards greater child will take place the root node of the tree, which
means left node of the tree will be the root node.
Same step implement again, and 23 will make child node of the root node.

Now 20 can be inserted in the remaining place.

STEP2 Delete 40, and store it in temporary place.

Now Swap 40 with second last element of the list, which is 20. Store node
20 in temporary place.

Afterwards greater value of the child node will take place of root node, so
30 will make the root node of the tree.
In the last 20 will be inserted into the blank node

STEP3 Delete root node, store it in temporary place

Now Swap 30 with third last element of the list, and store node 10 in
temporary place

Afterwards greater value of child node is take place of root node, so 23 will
make the root node of the tree.
Now insert 10 in blank space

STEP4 Delete the root node, and store it in temporary place.

Now Swap 23 with last element of unsorted list which is 20.

Afterwards greater value of node will be the root node of the tree. And
insert 20 in first element.

STEP5 Delete root node of the tree, and store it in temporary place

Now swap 20 with last element of unsorted list before 23.

Now 10 will make root node of tree, because this only node of the tree
Now insert 10 in the hole

Finally we a sorted list, sorted by Heap Sorting

Merge Sort

Divide and conquer method applied on this merge sorting technique. It is


a natural way of sorting lists by repeated merging of sub-lists. At the
deepest level of the recursion, single element lists are merged together to
form two element lists, afterwards every two element list will merge
another two element list.

First the list is to be decomposed into two halves and then each half is
sorted independently. Then these two sorted halves are merged to get a
sorted sequence.

Following are three steps two sort a list by merge sorting

Divide the unsorted list into two sub-lists


Sort each sub-list
Merge the two sorted sub-lists back into one sorted list.
EXAMPLE

Suppose we have list A= {50, 45, 35, 23, 18, 11}


Quick Sort

Quick sort is sorting algorithm that uses the idea of divide and conquer.
This is basically a recursive technique developed by C.A.B. Hoare. The
algorithm, find the element called pivot that partition the array into two
haves in such a way that the elements in left sub-array are less than the
element in right sub array are greater than the partitioned element
(PIVOT).

Example
Suppose we a list of array A = {15, 18, 5, 10, 50, 60}
In first step we use the first element of the list as the PIVOT, first element of
the list is 15. At the outset, we will compare first element of the list with
each element of the list from right to left until we will find the element
which has less value than 15.

Firstly we compare first element (15) with the last element of the list. Last
element of the list is greater than first element so we dont take any action,
afterwards we compare 15 with second last Now we come at A4 which is
10, and it is less than 15, so it will interchange with each other, and 15 will
be A4 element of the list.

After interchange A1 with A4, the location of the 15 element has been
changed. Now we compare elements on the lest with 15, and we these
elements by left to right.

A1 is already less than 15, so we come to A2. The value of A2 is greater than
15, so we will interchange both elements with each other. A4 A2
After interchange 15 and 18 elements, again we compare 15 element with
each element of the list from right to left.

Afterwards we find a less value element from 15, which is 5 located at A3,
so we will interchange both elements with each other. A2 A3

Now 15 is correctly placed in its final position, and elements in the left sub-
array are smaller than 15 and elements in the right sub-array are greater
than 15. This algorithm finds final position of one of the elements in the left
sub-array less than the elements in the right sub-array are greater than the
dividing element. The quick sort algorithm is recursive with the base
criteria that the number of elements in the array are not more than 1.
Suppose BEG and END represents the lower and upper bound of the array
respectively then the quick sort algorithm can be defined recursively as

If (BEG < END) then


Find element that divides the array into two parts
Quicksort left half
Quicksort right half
Trees

Trees are very commonly used non-linear data structure. Trees are used to
store the data in a hierarchical manner. A tree consists of nodes connected
by edges.

As, shown in figure, the top node is called a root node, it is connected with
other nodes with the help of lines which is known as the edges. A node can
have multiple relations among its nodes.

Example

The best example of tree is corporate organization. In corporate


organization, the root node is CEO of a company, it has further nodes as
directors and mangers of different departments, then they connect with
employers.

Trees Aspects
ROOTS
The node at the top of tree is known as the root node of the tree. The root
node is connected to other nodes with help of edges (lines). There is only
root node in tree.

LEAVES
At the end of the tree, which branches are not connected to other node is
known as the leaves, which node has not connected with further node is
known as leaf node. In above figure, I, D, E, F, D, and H are the leaf node in
tree.

BRANCHES
Which edges or lines use to connect two nodes is known as the branches of
trees.

PATH

Passing a data or information from root node or any node to any node in
tree with the help of branches or edges, is known as the path of the tree.

PARENT
Any node which connected with other node in upward direction is known
as the parent node of that node.

CHILD
Any node connected to other node toward downward direction, all nodes
on downward is known as the child nodes.

Binary Tree in Data Structure

In binary tree every node can have maximum two children node. Two node
of the binary tree is called left node and right node. And in further every
node of binary tree can have only two nodes as shown in figure. However, it
is not necessary that a node of binary tree should have two node, it can
have one node or leaf node.

Representation of Binary Trees

There are two ways to represent a binary tree.


Sequential representation
Linked representation
Sequential Representation

The other name of sequential representation is array representation. Array


is used to store the nodes of binary tree.
A binary tree can be represented using array in memory as follows:

Root node is stored at index 1


Left child of root stored at index 2k (k = index number of parent
node) and right child of root node stored at index 2K + 1 (K = index
number of parent node)

As shown in figure, A is stored at 1, and left stored at the index 2 (2K = 2 * 1


= 2), and right child stored at index 2K + 1 (2K + 1= 2 *1 + 1 = 3). As of, D is
left child node of B node, so it stored at index 4 (2K = 2 * 2 = 4).

Linked Representation

Each node of the binary tree is represented as having three parts in linked
representation.

First part of the node contains the information of the left child node.
Second part of the node contains the data of the node
Third part of the node contains the information of the right node.
Linked three may be declared as
typedef struct node
{
struct node *1child
int data;
struct node *rchild;
}
Struct node*root

Binary Search Tree in Data Structure

A binary search tree is also a ordered tree just link a ordinary binary tree,
in which the value of all nodes in the left subtree of the binary tree is less
than value of root node, and value of all these left subtrees nodes less than
all values of the nodes in the right subtree.

Algorithm to Find the Maximum Elements in Increasing


Order in a Binary Search Tree
STEP1 Set PTR = Root
STEP2 If (PTR RCHILD == NULL) then
Return PTR
Else
STEP3 Return (BST_MAXI (PTR RCHILD))
[End of if structure]
STEP4 Exit
Root Pointer variable contain the address of the root node
Algorithm to Find the Minimum Elements in Increasing
Order in a Binary Search Tree

STEP1 Set PTR = Root


STEP2 If (PTR LCHILD == NULL) then
Return PTR
Else
STEP3 Return (BST_MINI (PTR LCHILD))
[End of if structure]
STEP4 Exit
Operations on Binary Search Tree
Insertion
Deletion
Searching
Find the total number of nodes
Insertion

This operation is used to insert the new element in binary search tree, but
firstly, we have to whether the binary search tree is empty or not, if binary
search tree is empty, we have to insert a node in root node. Otherwise, if
binary search tree is not empty we have to find the location of the new
node.
ALGORITHM

STEP1 If (ROOT == NULL) then


ROOT = New node
ROOT LCHILD = NULL
ROOT INFO = ITEM
ROOT RCHILD = NULL
Else
STEP2 Set PTR = ROOT
STEP3 If (ITEM < PTR INFO) then
BST_INS (PTR LCHILD, ITEM)
Else
STEP4 BST_INS (PTR RCHILD, ITEM)
[End of if structure]
[End of step1 if structure]
STEP5 Exit
ROOT pointer variable, contain the address of the root node
ITEM New element

Deletion

This operation is used to delete the node from the binary search tree.
However to delete the node from binary search tree is more difficult to
insert into the tree.
Following are some cases of deletion operation.

Case 1 A node with no child

A node with no child can be deleted, with help of pointing a parent to NULL.
A Node with One Child

If we want to delete a node with one child, we have to adjust its parent
pointer, and connect to the child node of the deleted node.

As shown in figure, if we want to delete node which contain the value of 35,
then we have to make a change of its parent node which contain the value
of 40. Afterward, the node of 35 is deleted and its child node connect with
its parent node.

A node with two children

If we want to delete a node with two children, then we have to replace it


with another node.
We have two choices to do it

Element in the left subtree with the largest key value


Element in the right subtree with the smallest key value.
Searching in Binary Search Tree
This operation is used to search the node in binary search tree. Following is
the algorithm to search element in binary search tree.

Algorithm
STEP1 Set PTR = ROOT
STEP2 If (CPTR INFO == ITEM) then
Return
Else if (ITEM < PTR INFO) then
BST_SEARCH (PTR LCHILD, ITEM)
Else
BST_SEARCH (PTR RCHILD, ITEM)
[End of if structure]
STEP3 Exit
Root Pointer variable, contains address of the root node
ITEM Value of searched item
Find the Total number of Nodes

To find the total numbers of nodes in binary search, we have to traverse


(visit) the all nodes of the binary search tree. Following is the algorithm to
find the total number of nodes.

Algorithm
STEP1 If (ROOT == NULL) then
Return 0
Else
STEP2
Return(BST_COUNT(ROOTLCHILD) + BST_COUNT(ROOT RCHILD) + 1)
[End of if structure]
STEP3 Exit
Heap in Data Structure

Heap is also a binary tree, in which the value of each node is less than or
equal to the value of father node. If root value of heap is always a largest
value in tree, this type of heap known as max-heap. If root value of heap is
always the smallest value of tree, this type of heap is known as min-heap.

Operations on Heap

Insertion into a Heap

STEP1: Add a new element at the end of heap H

STEP2: Compare the new element with its parent element, if value of new
element is more than the value of father element, then it will interchange
with each other, otherwise, it will remain at same place.
As shown in figure, the value of the new element is 70 and its father nodes
value is 65, that is why, both nodes interchange with each other
STEP 3: After that, again compare the new element, with its new parent
node, as similar to step 2, if value of parent node is more than new element,
then it remains at same place, if it is less, then again it interchange with its
parent node.

As shown in figure, new element remains at same place, because the value
of new element is less than its parent node.

Creating a Heap

Create a heap given numbers


58, 59, 65, 10, 85, 20, 45
STEP1: Now just add a node with given number at first.

STEP2: Now add second number to the heap at left side, which is 59
Then compare both node with each other, as shown in figure, 59 is more
than 58.
So it will interchange with each other.

STEP3: Then add the third element to the right side of the heap, the value
of this element is 65.

Next step is to compare the new element with its parent node, as shown in
figure, the new element 65 is more than its parent node which is 59, so both
node interchange with each other.

STEP 4: Now, add the fourth element into the left side of 58s node in the
left of the heap which is 10.

As shown in figure, we insert a new node 10 into the heap. Afterwards, we


compare the new node with its parent node. The value of new node is less
than its parent node, then it remains at same place.
STEP 5: Afterwards, add the fifth element into the right side of 58s node of
the heap. Which is 85.

Now compare the new node to its parent node. As shown in figure, the
value of new node 85 which is more than its parent node, then it will
replace the parent node.

Again we have to compare the value of new node with its parent node, we
can see that, the value of new node 85 is more than its parent node value
which is 65, so it will interchange with each other, and new node will make
the root node.

STEP 6: Now add the sixth value which is 20 to the left side of 59s node of
the heap.
Compare the value of new node with its parent node. In this step the value
of new node is less than its parent node, so it will remains at same place.
STEP 7: Now insert the seventh value in the right side of 59s node in the
heap, the value of seventh is 45.

ALGORITHM
STEP1 Input n elements in the heap H
STEP2 By incrementing the size of the heap H, add new node:
N = n + 1 and LOC = n
STEP3 Repeat step 4 and 7 while (LOC < 1)
STEP4 PR = LOC/2
STEP5 If (ITEM <= A[PR])
A [LOC] = ITEM
Exit
STEP6 A [LOC] = A [PR]
STEP7 LOC = PR
STEP8 A [1] = ITEM
STEP9 Exit
H Heap with n number of elements
A Array
ITEM New element
LOC Present location of new element
PR The location of the parent of new element
Deletion from a Heap

STEP1: Delete the root node from the heap, the root value of heap is 85.

STEP2: Afterwards, we replace deleted root node with last node of the
heap. As shown in figure, 50 is the last node of the heap, then 50s node is
replaced with deleted node.

STEP3: Now we compare the value of the root node with its child nodes. As
shown in figure, the value of root node which is 50 is less its child nodes,
then root node is replaced by the greatest value among children nodes.
ALGORITHM

STEP1 Input n elements in the heap H


STEP2 ITEM = A [1];
LAST = A [n] and n = n 1
STEP3 LOC = 1, LEFT = 2 and RIGHT = 3
STEP4 Repeat the steps 5, 6 and 7 while (RIGHT <= n)
STEP5 If (LAST => A [LEFT]) and (LAST => A [RIGHT])
A [LOC] = LAST
Exit
STEP6 If (A [RIGHT] <= A[LEFT])
A [LOC] = A [LEFT]
LOC = LEFT
Else
STEP7 LEFT = 2 * LOC
RIGHT = LEFT + 1
STEP8 If (LEFT = n) and (LAST < A[LEFT])
LOC = LEFT
STEP9 A[LOC] = LAST
STEP10 Exit

Graphs
Graphs are most used structure in computer programming. A graph consist
edges and vertices. Vertices represent the nodes of graphs, and which line
connect one node to other node known as the edges of the graph.

In above diagram vertices are V = A, B, C, D, E and Edges are


E = (AD, DC, BC, ED)
V represents the vertices of the graphs
E represents the Edges of the graphs
G = (V, E)

Some Aspects of Graphs

Vertices: Vertices are the also known as the nodes, which contain the data. In
above example A, B, C, D, E are the vertices.
Edges: Edges are the lines which help to connect one node to other node,
E = (AD, DC, BC, ED) are the edges of the graph in above example.
Adjacency: Which two vertices are connected with edge known as adjacent.
A vertices and B vertices are two adjacent.
Incidence: Which edge help to connect two vertices known as incidence.
For example- (A, B)
Loops: Which vertex connected with itself with help of edge known as loop.

You might also like