Vous êtes sur la page 1sur 28

J.

Pratheepan

Data Structure and Algorithm

ATI-Trincomalee

1. Introduction to Data Structure and Algorithm


Primitive Data Types:
Primitive Data Types are basic data types of a programming language.
These refer to two things: a data item with certain characteristics and the permissible operations on
that data.
For example,
The operations + (addition), - (subtraction), * (multiplication), / (division) can be applied to the
primitive data types integer and float.
The operations && (and), || (or), ! (not) can be applied to the primitive data type boolean.
Abstract Data Types (ADT):
ADT is a specification of a mathematical set of data and the set of operations that can be performed
on the data.
The set of operations that define an ADT is referred to as its interface.
ADTfocuses on what it does and ignores how it does its job.That is,ADT is independent of any
particular implementation.
Eg:
1. stack (last-in-first-out)
Push(5)
Pop()

5
2. queue (first-in-first-out)
6
enQueue(6)

deQueue()

Data Structures:
Data structure is the arrangement of data in a computer memory/storage.
Data structure is the implementation of ADT such as stack, queue, linked list, tree, graph.
When working with certain data structures we need to know how to insert new data, how to search
for a specific item, and how to delete a specific item.
Data structure helps for efficient programming.
Data structure reduces complexity of the program and its calculations.
There are two types of data structures: Linear data structure and Nonlinear data structure
Linear and Nonlinear Data Structures:
Linear Data Structure
Data Organized Sequentially (one after the other)
Easy to implement because the computer memory is also
organized as linear fashion
E.g: Array, Stack, Queue, Linked List

Nonlinear Data Structure


Data organized non sequentially
Difficult to implement
E.g: Tree, Graph

What is Algorithm?
An algorithm is a step by step procedure for solving a problem in a finite amount of time.
Many algorithms apply directly to a specific data structures.
Efficiency of an Algorithm:
Some algorithms are more efficient than others. We would prefer to choose an efficient algorithm.
Running time of algorithms typically depends on the input set, and its size(n).

J.Pratheepan

Data Structure and Algorithm

ATI-Trincomalee

Big O Notation:
We can say that a function is of the order of n", which can be written as O(n) to describe the upper
bound on the number of operations. This is called Big-Oh notation.
Some common orders are:
O(1) constant (the size of n has no
effect)
O(log n) logarithmic
O(n log n)
O(n)
O(n2) quadratic
O(n3) cubic
O(2n) exponential
If the number of operations is 500, then the
big O notation is O(1).
If the number of operations is 9n + 200,
then the big O notation is O(n).
If the number of operations is n3 + 3n +
8,then the big O notation is O(n3).
Generally we can take O(1) is faster than
O(n) and O(n) is faster than O(n3).
Best, Worst and Average Cases:
Best case efficiency is the minimum number
of steps that an algorithm can take any
collection of data values.
Worst case efficiency is the maximum
number of steps that an algorithm can take for any collection of data values.
Average case efficiency
is the efficiency averaged on all possible inputs
must assume a distribution of the input
is normally assumed for uniform distribution (all keys are equally probable)
For example, when we search for an element in a list sequentially,
In best case, the cost is 1 compare. That is O(1).
In worst case, the cost is n compares. That is O(n).
In the average case, the cost may be (n+1)/2. That is O(n).

J.Pratheepan

Data Structure and Algorithm

ATI-Trincomalee

2. Array Data Structure


What is an array?
Arrays are a group of continuous similar type of variables referred by a common name.
In C++, array can be declared and used as follows:
0 1 2 3 4
intnum[5];
num
0 1 2 3 4
num[2]=3;
num
3
0 1 2 3 4
num[4]=2*num[2];
num
6
cout<<num[4]+num[2]; 9
A program to store and print elements in an array:
#include<iostream.h>
#include<conio.h>
void main()
{
int i;
char keys[6]={'Q','W','E','R','T','Y'};
cout<<"The first 6 keys of a keyboard are ";
for (i=0; i<=5; i++)
cout<<keys[i]<<" ";
}
A program to search and replace an element in an array:
#include<iostream.h>
#include<conio.h>
void main()
{
int i;
char s,r;
int found=0; //found=false
char keys[6]={'Q','W','E','R','T','Y'};
cout<<"Enter a character to be searched: "; cin>>s;
cout<<"Enter a character to replace: "; cin>>r;
i= (-1);
while (i<5 && found==0)
if (keys[++i]==s) found=1;
if (found==1)
keys[i]=r;
else
cout<<"No such element.";
}
A program to delete an elementfrom an array:
Actually we cant delete an element from an array.
If we want to delete an element, we have to move all the subsequent elements forward.
Or otherwise we can replace the element with invalid values (e.g.: 0 or NULL).
#include<iostream.h>
#include<conio.h>
void main()
{
int i;
char d;

J.Pratheepan

Data Structure and Algorithm

ATI-Trincomalee

int found=0; //found=false


char keys[6]={'Q','W','E','R','T','Y'};
cout<<"Enter a character to be deleted: "; cin>>d;
i= (-1);
while (i<5 && found==0)
if (keys[++i]==d) found=1;
if (found==1)
keys[i]=NULL;
else
cout<<"No such element."
}
Multi-Dimensional Array:
Multi-dimensional array can be considered as an array of arrays.
For example a two dimensional array may look like as follows:
table
0 1 2 3 4 5 6
0
0 1 2 3 4 5 6
1
This location can be referred to as table[1][5]
0 1 2 3 4 5 6
2
Or simply we can imagine a two dimensional array as follows:
table 0 1 2 3 4 5 6
0
1
This location can be referred to as table[1][5]
2
A program to store and print elements in a two dimensional array:
#include<iostream.h>
#include<conio.h>
void main()
{
Int i,j;
clrscr();
int matrix[3][4]={{5,3,6,4},{2,5,3,7},{3,6,5,8}};
cout<<"The elements of the array are";
for (i=0; i<3; i++)
{
for (j=0; j<4; j++)
cout<<matrix[i][j]<<"\t";
cout<<"\n";
}
}
Advantages of arrays:
Fast access if index is known
Easy to add an element in a particular location.
Disadvantages of arrays:
Fixed size
Same data type
Slow in searching an element
Slow in inserting/deleting an element

J.Pratheepan

Data Structure and Algorithm

ATI-Trincomalee

3. Linked List Data Structure


What is Pointer?
Pointer contains memory address of a particular type of data.
In C++, we use * to declare a pointer.
2cdf

int p; int* iptr; char* cptr;

p = 9; *iptr = 5; *cptr=$;

cout<<p; cout<<iptr; cout<<cptr;

cout<<&p; cout<<*iptr;cout<<*cptr;

2cdf

1a5c

iptr
9

1a5c

iptr

1a5c

$t#

2cdf

iptr = &p;

cout<<*iptr;

c75c

cptr

c75c

cptr

/0

cptr

/0

1a5c

iptr

2cdf

What is Structure (in C++)?


structemployee
{
Int empNo;
float salary;
}emp;

emp
empNo
salary

emp
empNo 1005
salary 40000.00

emp.empNo=1005;
emp.salary=40000.00;
cout<<emp.salary+1000.00;

employee* eptr;
eptr = new employee;
eptr->empNo=1006;
eptr->salary=30000.00;
cout<<eptr->empNo;

41000.00

eptr
empNo 1006
salary 30000.00
1006

What is Linked List?


A linked list consists of nodes of data which are connected to other nodes. There are several types
of linked lists.

head

next

data

next

data

next

data

next

data

E.g1:

7 /

next

data

next

data

next

data

next

head
front
rear

data

E.g2:

7 /

head

next

data

ATI-Trincomalee
previous

next

data

previous

next

data

previous

next

data

E.g3:

Data Structure and Algorithm


previous

J.Pratheepan

7 /

Common operations of Linked List are:


initializeList() - initializes the list as empty list.
insertFirstElt(int elt) - inserts a new element into an empty list.
insertAtFront(int elt) - inserts an element at the beginning of the list.
insertAtEnd(int elt) - inserts an element at the end of the list (appendElt or appendNode).
insertAfter(int oldElt, int newElt) - inserts an element after a specified element.
deleteElt(int elt) - deletes a specified element.
displayList() - displays all the elements in the list
isEmpty() - returns true if the list has no elements, false otherwise.
isFull() - returns false if the list is full, false otherwise.
Structural Diagramsof Linked List Operations:
/
data

2. insertFirstElt(5)

5 /
data

3.insertAtFront(3)

data

4. insertAtEnd(8)

head

data

next

newNode

next

5 /
data

head

next

head

newNode

next

head

next

1. initializeList()

8 /

head

newNode

next

8 /
7

data

next

data

next

data

5. insertAfter(5,7)

J.Pratheepan

Data Structure and Algorithm

ATI-Trincomalee

head

Implementation of Linked List Operations:


#include<iostream.h>
#include<conio.h>
class LinkedList
{
private:
struct listNode
{
int data;
listNode* next;
};
listNode* head;
public:
LinkedList();
void initializeList();
void insertFirstElt(int elt);
void insertAtFront(int elt);
void insertAtEnd(int elt);
void insertAfter(int oldElt, int newElt);
void deleteElt(int elt);
void displayList();
int isEmpty();
int isFull();
}
LinkedList::LinkedList() //Constructor
{
head=NULL;
}
void LinkedList::initializeList()
{
head=NULL;
}
void LinkedList::insertFirstElt(int elt)
{
head=new listNode;
head->data=elt;
head->next=NULL;
}
void LinkedList::insertAtFront(int elt)
{
listNode *newNode;
newNode=new listNode;
newNode->data=elt;

next

data

next

data

next

data

next

data

6. deleteElt(5):

8 /

J.Pratheepan

Data Structure and Algorithm

newNode->next=head;
head=newNode;
}
void LinkedList::insertAtEnd(int elt)
{
listNode *newNode, *curNode;
newNode=new listNode;
newNode->data=elt;
newNode->next=NULL;
if (!head)
head=newNode;
else
{
curNode=head;
while (curNode->next != NULL)
curNode = curNode->next;
curNode->next = newNode;
}
}

void LinkedList::insertAfter(int oldElt, int newElt)


{

}
void LinkedList::deleteElt(int elt)
{

}
void LinkedList::displayList()
{
listNode* curNode;
curNode=head;
while (curNode)
{
cout<<curNode->data<<" ";
curNode=curNode->next;
}
}
int LinkedList::isEmpty()
{
if (head== NULL)
return 1;
else
return 0;
}

ATI-Trincomalee

J.Pratheepan

Data Structure and Algorithm

int LinkedList::isFull() //It always returns false.


{
return 0;
}
void main()
{
clrscr();
LinkedList lst;
lst.insertAtEnd(4);
lst.insertAtEnd(6);
lst.insertAtEnd(5);
lst.displayList();
}
Advantages of Linked List:
Easy to insert and delete elements.
Unlike array, memory space is not wasted in linked list.
Disadvantages of Linked List:
Slow in searching.

ATI-Trincomalee

J.Pratheepan

Data Structure and Algorithm

ATI-Trincomalee

4. Stack Data Structure


What is Stack?
Stack is a data structure which is used to handle data in a last-in-first-out (LIFO) method. That is we
can remove the most recently added element from the stack first.
Common operations of Stack are:
initializeStack() initializes the stack as empty stack.
push()- adds an element on top of the stack.
pop()-removes and returns the top most element from the stack.
topElt()-returns the top element without removing it.
isEmpty() - returns true if the stack has no elements and false otherwise.
isFull() - returns true if the stack is full of elements and false otherwise.
displayStack() - displays all elements from top to bottom.
Graphical Representation of Stack Operation:
1. initializeStack()

2. p =isEmpty()

p = true

3. push(5)

4. push(7)

7
5

5. push(6)
6
7
5

10

J.Pratheepan

Data Structure and Algorithm

ATI-Trincomalee

6. q = isEmpty(); r = isFull();
6
7
5

q = false; r = false

7. x = pop()

x=6

7
5

8. y = topElt()

y=7

7
5

Static (Array based) Implementation of Stack Operations [Graphical Representation]:


1. initializeStack()

top = -1

4
3
2
1
0

top = -1

4
3
2
1
0

top = 0

4
3
2
1
5 0

top = 1

4
3
2
7 1
5 0

2. p =isEmpty()

p = true

3. push(5)

4. push(7)

11

J.Pratheepan

Data Structure and Algorithm

5. push(6)

top = 2

4
3
6 2
7 1
5 0

6. q = isEmpty(); r = isFull();

q = false; r = false

top = 2

7. x = pop()

x=6

top = 1

4
3
2
7 1
5 0

top = 1

4
3
2
7 1
5 0

8. y = topElt()

y=7

4
3
6 2
7 1
5 0

Static (Array based) Implementation of Stack Operations [C++ Code]:


#include<iostream.h>
#include<conio.h>
const STK_SIZE=5;
class Stack
{
private:
int top;
int stk[STK_SIZE];
public:
Stack();
void initializeStack();
void push(int);
int pop();
int topElt();
int isEmpty();
int isFull();
void displayStack();
}

12

ATI-Trincomalee

J.Pratheepan

Data Structure and Algorithm

Stack::Stack()
{
top=(-1);
}
void Stack::initializeStack()
{
top=(-1);
}
void Stack::push(int elt)
{
if (top < STK_SIZE-1) stk[++top]=elt;
}
int Stack::pop()
{
if (top > -1)
return stk[top--];
else
return 999; //Some invalid integer should be returned
}
int Stack::topElt()
{
if (top > -1)
return stk[top];
else
return 999; //Some invalid integer should be returned
}
int Stack::isEmpty()
{
return (top == (-1));
}
int Stack::isFull()
{
return (top == (STK_SIZE-1));
}
void Stack::displayStack()
{
int i=top;
while (i>-1)
{
cout<<stk[i]<<endl;
i--;
}
}
void main()
{
clrscr();
Stack s;
s.push(5);
s.push(7);
s.push(6);

13

ATI-Trincomalee

J.Pratheepan

Data Structure and Algorithm

ATI-Trincomalee

int x=s.pop();
s.push(9);
s.displayStack();
}
Output:
9
7
5
Dynamic (Linked List based) Implementation of Stack Operations:
initializeStack() - top=NULL; //Similar to initialzeList() and it is better to use top instead of head.
push() - newNode->next=top; top=newNode; //Similar to insertAtFront()
pop() - x=top->data; top=top->next; return x;
topElt() - return top->data
isEmpty() - if (top==NULL) return 1 else return 0
isFull() - return 0; //Always return false
displayStack() - Similar to displayList()
Advantages of Stack:
Last-in-first-out access
Disadvantages of Stack:
Difficult to access other items

14

J.Pratheepan

Data Structure and Algorithm

ATI-Trincomalee

5. Queue Data Structure


What is Queue?
Queue is a data structure which is used to handle data in a first-in-first-out (FIFO) method. That is
we can remove the element which has been added earlier from the queue first.
Common operations of Queue are:
initializeQueue() initializes the queue as empty queue.
enQueue()- adds an element at the rear of the queue.
deQueue()-removes and returns the front element from the queue.
frontElt()-returns the front element without removing it.
isEmpty() - returns true if the queue has no elements and false otherwise.
isFull() - returns true if the queue is full of elements and false otherwise.
displayQueue() - displays all elements from front to rear.
Graphical Representation of Queue Operation:
1. initializeQueue()
2. p=isEmpty()
p = true
3. enQueue(5)

4. enQueue(9)
enQueue(7)

7. q = isFull()
q = false

8. enQueue(3)

5. x=deQueue()
x=5
6. enQueue(2)
enQueue(6)

9. r = isFull()
y = deQueue()
r = true
y=9

Static (Array based) Implementation of Queue Operations [Graphical Representation]:


0

1. initializeQueue()
front
rear
size

-1
-1
0

15

J.Pratheepan

Data Structure and Algorithm


0

ATI-Trincomalee

1
9

2
7

1
9

2
7

1
9

2
7

3
2

4
6

1
9

2
7

3
2

4
6

1
9

2
7

3
2

4
6

2. p=isEmpty()

p = true

front
rear
size

-1
-1
0
0
5

3. enQueue(5)
front
rear
size

-1
0
1
0
5

4. enQueue(9)
enQueue(7)
front
rear
size

-1
2
3
0

5. x=deQueue()

x=5

front
rear
size

0
2
2
0

6. enQueue(2)
enQueue(6)
front
rear
size

0
4
4
0

7. q = isFull()

q = false

front
rear
size

0
4
4
0
3

8. enQueue(3)
front
rear

0
0

16

J.Pratheepan

Data Structure and Algorithm


size

r = true
y=9

5
0
3

9. r = isFull()
y = deQueue()
front
rear
size

ATI-Trincomalee

2
7

3
2

1
0
4

Static (Array based) Implementation of Stack Operations [C++ Code]:


#include<iostream.h>
#include<conio.h>
const Q_SIZE=5;
class Queue
{
private:
int front, rear, size;
int que[Q_SIZE];
public:
Queue();
void initializeQueue();
void enQueue(int);
int deQueue();
int frontElt();
int isEmpty();
int isFull();
void displayQueue();
}
Queue::Queue()
{
front=(-1);
rear=(-1);
size=0;
}
void Queue::initializeQueue()
{
front=(-1);
rear=(-1);
size=0;
}
void Queue::enQueue(int elt)
{
if (size < Q_SIZE)
{
rear=(rear+1)%Q_SIZE;
que[rear]=elt;
size++;
}
//Else cout<<Queue is full
}

17

4
6

J.Pratheepan

Data Structure and Algorithm

ATI-Trincomalee

int Queue::deQueue()
{
if (size > 0)
{
front=(front+1)%Q_SIZE;
size--;
return que[front];
}
else
return 999; //Some invalid integer should be returned or cout<<Queue is empty
}
int Queue::frontElt()
{
if (size>0)
{
return que[(front+1)%Q_SIZE];
}
else
return 999; //Some invalid integer should be returned or cout<<Queue is empty
}
int Queue::isEmpty()
{
return (size == 0);
}
int Queue::isFull()
{
return (size == Q_SIZE);
}
void Queue::displayQueue()
{
int i=front;
for (int j=1;j<=size;j++)
{
i=(i+1)%Q_SIZE;
cout<<que[i]<<endl;
}
}
void main()
{
clrscr();
Queue q;
q.enQueue(5);
q.enQueue(9);
q.enQueue(7);
int x=q.deQueue();
q.enQueue(2);
q.enQueue(6);
q.enQueue(3);
int y=q.deQueue();
q.displayQueue();
}
Output: 7 2 6 3

18

J.Pratheepan

Data Structure and Algorithm

ATI-Trincomalee

Dynamic (Linked List based) Implementation of Queue Operations:


initializeQueue() - front=NULL; //Similar to initialzeList() and it is better to use front instead of head.
enQueue() - newNode->next=front; front=newNode; //Similar to insertAtFront()
deQueue() - Move to the last node, get the data, remove the last node, return the data.
frontElt() - Move to the last node, get the data, remove the last node, return the data.
isEmpty() - if (front==NULL) return 1 else return 0
isFull() - return 0; //Always return false
displayQueue() - Similar to displayList()
Advantages of Queue:
First-in-first-out access
Disadvantages of Queue:
Difficult to access other items

19

J.Pratheepan

Data Structure and Algorithm

ATI-Trincomalee

6. Tree Data Structure


What is Tree?
A tree is a widely-used data structure that emulates a hierarchical tree structure with a set of linked
nodes.
A rooted tree has a distinguished node called root.

Some Terms related to Trees:


1. Root, parent, child, sibling, leaf
Every child node has a unique parent.
Every parent node can have any number of children (including none).
There is one unique node in every tree which has no parent and is called the root of the tree.
An internal node has one or more children.
A leaf node has no children.
Nodes with the same parent are called siblings.

2. Size, depth, height and level


The size of a tree is the number of nodes that it contains.
The depth of a node is the number of edges from the root to the node.
The height of a tree is the largest depth of any of its nodes.

Size=9 Height=4

3. Degree
The degree of a node is the number of its children.
The degree of a tree is the maximum degree of any of its nodes.

20

J.Pratheepan

Data Structure and Algorithm

ATI-Trincomalee

4. Path
Path between two nodes in a tree is a sequence of edges which connect those nodes.

Path from F to C is (FB, BD, DC)

Special Types of Trees:


1. Binary Tree:
A binary tree is a rooted tree in which no node can have more than two children, and the children
are distinguished as left and right.
A full binary tree is a tree in which every node other than the leaves has two children.
A complete binary tree is a binary tree, which is completely filled, with the possible exception of the
bottom level, which is filled from left to right.
A perfect binary tree is a binary tree with all leaf nodes at the same depth. All internal nodes have
degree 2.

2. Binary Search Tree:


It is a binary tree such that for every node N in the tree:
All keys in N's left sub tree are less than the key in N, and
All keys in N's right sub tree are greater than the key in N.
Note: if duplicate keys are allowed, then nodes with values that are equal to the key in node N
can be either in N's left sub tree or in its right sub tree (but not both). In these notes, we will
assume that duplicates are not allowed.
Example: Inserting 21, 6, 41, 45, 50, 55, 57, 40, 50, 15, 20, 30 in a BST.

3. AVL (Adelson Velsky Landis) Tree:


It is a binary search tree such that no node that has sub trees differing in height by more than 1.
Example: Inserting 21, 6, 41, 45, 50, 55, 57, 40, 50, 15, 20, 30 in an AVL tree.

21

J.Pratheepan

Data Structure and Algorithm

Implementation of Binary Tree:


6
4
/

8
/

Advantages of Binary Tree:


Quick search, Quick inserts, Quick deletes (If the tree remains balanced)
Disadvantages of Binary Tree:
Deletion algorithm is complex

22

ATI-Trincomalee

J.Pratheepan

Data Structure and Algorithm

ATI-Trincomalee

7. Sorting Algorithms
What is sorting?
Arranging items in ascending or descending order is called as sorting.
There are different types of sorting techniques each of which is good for some cases such as nearly
sorted, reversed, random, etc.
Selection Sort Algorithm:
Here we repeatedly find the next largest (or smallest) element in the array and move it to its final
position in the sorted array.
Example: Sort the numbers 6, 7,72, 4, 32, 65, 9, 56 using selection sort.
0
1
2
3
4
5
6
7
Original
Pass0
7
72
4
32
65
9
56
6
Pass1

72

32

65

56

Pass2

72

32

65

56

Pass3

72

32

65

56

Pass4

32

65

72

56

Pass5

32

65

72

56

Pass6

32

56

72

65

Pass7

32

56

65

72

Pseudo Code:
swap(x, y)
t=x
x=y
y=t
selectionSort (a[],n) //Let a be an array containing n items
for i = 0 to n-2
m=i
for j = i+1 to n-1
if (a[j] < a[m]) m = j
next j
swap(a[i],a[m])
next i
C++ Code:
#include<iostream.h>
#include<conio.h>
void displayArray(int *a, int n)
{
int i;
for (i=0; i<n; i++)
cout<<a[i]<<" ";
}

23

Sorted

J.Pratheepan

Data Structure and Algorithm

ATI-Trincomalee

void swap(int *x,int *y)


{
int t;
t=(*x);
*x=(*y);
*y=t;
}
void selectionSort (int *a, int n)
{
int i, j, m, t;
for (i = 0; i < n-1; i++)
{
m = i;
for (j = i+1; j < n; j++)
if (a[j] < a[m]) m = j;
swap(&a[i],&a[m]);
}
}
void main ()
{
clrscr();
int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};
int n = 10;
displayArray(a,n);cout<<endl;
selectionSort(a, n);
displayArray(a,n);
}
Output:
4 65 2 -31 0 99 2 83 782 1
-31 0 1 2 2 4 65 83 99 782
Bubble Sort Algorithm:
Here we repeatedly move the largest element to the highest index position of the array.
Example: Sort the numbers 6, 7,72, 4, 32, 65, 9, 56 using bubble sort.
0
1
2
3
4
5
6
7
Pass0
7
72
4
32
65
9
56
6
Pass1

32

65

56

72

Pass2

32

56

65

72

Pass3

32

56

65

72

Pass4

32

56

65

72

Pass5

32

56

65

72

Pseudo Code:
bubbleSort(a[],n) //Let a be an array containing n items
max = n-2
swapped = true
while (max>0 AND swapped=true)
swapped = false
for j = 0 to max

24

Original

Sorted

J.Pratheepan

Data Structure and Algorithm

ATI-Trincomalee

if (a[j] > a[j + 1])


swap(&a[j],&a[j+1])
swapped = true
end if
next j
max=max-1
end while
C++ Code:
void bubbleSort(int *a, int n)
{
int j;
int max = n-2;
int swapped = 1;
while (max>0 && swapped)
{
swapped = 0;
for (j = 0; j <= max; j++)
{
if (a[j] > a[j + 1])
{
swap(&a[j],&a[j+1]);
swapped = 1;
}
}
max--;
}
}
Efficiency of the Sort Algorithms (Best, Worst and Average Case Comparison):

25

J.Pratheepan

Data Structure and Algorithm

ATI-Trincomalee

8. Searching Algorithm
What is search algorithm?
A search algorithm is an algorithm for finding an item among a collection of items.
Sequential/Linear Search Algorithm:
It examines the first element in the list and then second element and so on until a much is found.
Pseudo code:
int sequentialSearch(a[],n,t) //It returns the location of the target t in the array a[] with n elements.
for i = 0 to n-1
if (a[i]=t) return i;
next i
return -1;
C++ Implementation:
#include<iostream.h>
#include<conio.h>
int sequentialSearch(int *a, int n, int t)
{
int i;
for (i = 0; i < n; i++)
if (a[i]==t) return i;
return (-1);
}
void main ()
{
clrscr();
int num[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};
int n = 10;
int t = 99;
cout<<t<<" is found at "<<sequentialSearch(num, n, t)<<".";
}
Output: 99 is found at 5.
Binary Search Algorithm:
Here the elements should be in (ascending) order and the elements should be saved in a randomly
accessible data structure like array.
The basic algorithm is to find the middle element of the list, compare it against the key/target, decide
which half of the list must contain the key, and repeat with that half.
Pseudo code:
int binarySearch(a[],l,u,t) //It returns the location of t in the array a[] from the index l to u.
p = ( l + u) / 2;
while(a[p] t AND l<=u)
if (a[p] > t)
u=p-1
else
l=p+1
p = (l + u) / 2
end while
if (l <= u)
return p
else
return -1

26

J.Pratheepan

Data Structure and Algorithm

ATI-Trincomalee

C++ Implementation:
int binarySearch(int* a, int l, int u, int t)
{
int p;
p = ( l + u) / 2;
while((a[p] != t) && (l<=u))
{
if (a[p] > t)
u = p - 1;
else
l = p + 1;
p = (l + u) / 2;
}
if (l <= u)
return p;
else
return (-1);
}
void main ()
{
clrscr();
int num[] = {1, 2, 7, 9, 50, 99, 100, 150, 190, 200};
int n = 10;
int t = 99;
cout<<t<<" is found at "<<binarySearch(num, 0, n-1, t)<<".";
}
Output: 99 is found at 5.
Recursive Pseudo Code:
int recBinarySearch(a[],l,u,t) //It returns the location of t in the array a[] from the index l to u.
if l>u then
return -1
else
mid=(l+u)/2
if t=a[mid] then
return mid
else if t<a[mid] then
return recBinarySearch(a[],l,mid-1,t)
else
return recBinarySearch(a[],mid+1,u,t)
end if
end if
Recursive C++ Code:
int recBinarySearch(int* a, int l, int u, int t)
{
int mid;
if (l>u)
return (-1);
else
{
mid=(l+u)/2;
if (t==a[mid])
return mid;
else if (t<a[mid])
return recBinarySearch(a,l,mid-1,t);

27

J.Pratheepan

Data Structure and Algorithm

ATI-Trincomalee

else
return recBinarySearch(a,mid+1,u,t);
}
}
void main ()
{
clrscr();
int a[] = {1, 2, 7, 9, 50, 99, 100, 150, 190, 200};
int n = 10;
int t = 99;
cout<<t<<" is found at "<<recBinarySearch(a, 0, n-1, t)<<".";
}
Output: 99 is found at 5.
Efficiency of the Search Algorithms (Best, Worst and Average Cases):
Searching Technique Best case Average Case Worst Case
Sequential Search
O(1)
O(n)
O(n)
Binary Search
O(1)
O (log n)
O(log n)
The difference between O(log(N)) and O(N) is extremely significant when N is large.
For example, suppose your array contains 2 billion values, the sequential search would involve
about a billion comparisons; binary search would require only 32 comparisons!

28