Sunteți pe pagina 1din 28

J.

Pratheepan Data Structure and Algorithm ATI-Trincomalee


1

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 Nonlinear Data Structure
Data Organized Sequentially (one after the other) Data organized non sequentially
Easy to implement because the computer memory is also
organized as linear fashion
Difficult to implement
E.g: Array, Stack, Queue, Linked List 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
2

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(n
2
) quadratic
O(n
3
) cubic
O(2
n
) 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 n
3
+ 3n +
8,then the big O notation is O(n
3
).
Generally we can take O(1) is faster than
O(n) and O(n) is faster than O(n
3
).

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
3

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
4

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
5

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 1a5c c75c
int p; int* iptr; char* cptr; p iptr
1a5c
cptr
c75c


p = 9; *iptr = 5; *cptr=$; p 9 iptr 5 cptr $ t # /0

cout<<p; cout<<iptr; cout<<cptr; 9 1a5c $t#

cout<<&p; cout<<*iptr;cout<<*cptr; 2cdf 5 $
2cdf 1a5c
iptr = &p; p 9 iptr 2cdf 5 cptr $ t # /0

cout<<*iptr; 9

What is Structure (in C++)?

structemployee emp
{ empNo
Int empNo; salary
float salary;
}emp;
emp
emp.empNo=1005; empNo 1005
emp.salary=40000.00; salary 40000.00

cout<<emp.salary+1000.00; 41000.00


employee* eptr; eptr
eptr = new employee; empNo 1006
eptr->empNo=1006; salary 30000.00
eptr->salary=30000.00;
cout<<eptr->empNo; 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.

E.g1:

d
a
t
a

n
e
x
t

d
a
t
a

n
e
x
t

d
a
t
a

n
e
x
t

d
a
t
a

n
e
x
t


head 5 9 6 7 /

E.g2:
head

d
a
t
a

n
e
x
t

d
a
t
a

n
e
x
t

d
a
t
a

n
e
x
t

d
a
t
a

n
e
x
t


front 5 9 6 7 /
rear

J.Pratheepan Data Structure and Algorithm ATI-Trincomalee
6

E.g3:

p
r
e
v
i
o
u
s

d
a
t
a

n
e
x
t

p
r
e
v
i
o
u
s

d
a
t
a

n
e
x
t

p
r
e
v
i
o
u
s

d
a
t
a

n
e
x
t

p
r
e
v
i
o
u
s

d
a
t
a

n
e
x
t

head / 5 9 6 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:

1. initializeList() head /



3.insertAtFront(3)



d
a
t
a

n
e
x
t

head 5 /

d
a
t
a

n
e
x
t



newNode 3


4. insertAtEnd(8)

d
a
t
a

n
e
x
t

d
a
t
a

n
e
x
t

head 3 5

newNode 8 /


5. insertAfter(5,7)

d
a
t
a

n
e
x
t

d
a
t
a

n
e
x
t

d
a
t
a

n
e
x
t

head 3 5 8 /

newNode 7


2. insertFirstElt(5)

d
a
t
a

n
e
x
t

head 5 /
J.Pratheepan Data Structure and Algorithm ATI-Trincomalee
7

6. deleteElt(5):

d
a
t
a

n
e
x
t

d
a
t
a

n
e
x
t

d
a
t
a

n
e
x
t

d
a
t
a

n
e
x
t


head 3 5 7 8 /


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;
J.Pratheepan Data Structure and Algorithm ATI-Trincomalee
8

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;
}


J.Pratheepan Data Structure and Algorithm ATI-Trincomalee
9

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.

J.Pratheepan Data Structure and Algorithm ATI-Trincomalee
10

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)



5


4. push(7)


7
5


5. push(6)

6
7
5




J.Pratheepan Data Structure and Algorithm ATI-Trincomalee
11

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

6
7
q = false; r = false 5


7. x = pop()


7
x = 6 5


8. y = topElt()


7
y = 7 5

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

1. initializeStack() 4
3
2
1
top = -1 0

2. p =isEmpty() 4
3
2
1
p = true top = -1 0


3. push(5) 4
3
2
1
top = 0 5 0


4. push(7) 4
3
2
7 1
top = 1 5 0

J.Pratheepan Data Structure and Algorithm ATI-Trincomalee
12


5. push(6) 4
3
6 2
7 1
top = 2 5 0


6. q = isEmpty(); r = isFull(); 4
3
6 2
7 1
q = false; r = false top = 2 5 0


7. x = pop() 4
3
2
7 1
x = 6 top = 1 5 0


8. y = topElt() 4
3
2
7 1
y = 7 top = 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();
}

J.Pratheepan Data Structure and Algorithm ATI-Trincomalee
13

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);
J.Pratheepan Data Structure and Algorithm ATI-Trincomalee
14

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
J.Pratheepan Data Structure and Algorithm ATI-Trincomalee
15

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) 5

4. enQueue(9)
enQueue(7) 5 9 7

5. x=deQueue() 9 7
x = 5

6. enQueue(2)
enQueue(6) 9 7 2 6

7. q = isFull() 9 7 2 6
q = false

8. enQueue(3) 9 7 2 6 3

9. r = isFull()
y = deQueue() 7 2 6 3
r = true
y = 9

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

0 1 2 3 4
1. initializeQueue()

front -1
rear -1
size 0

J.Pratheepan Data Structure and Algorithm ATI-Trincomalee
16

0 1 2 3 4
2. p=isEmpty()

front -1
rear -1
p = true size 0

0 1 2 3 4
3. enQueue(5) 5

front -1
rear 0
size 1

0 1 2 3 4
4. enQueue(9) 5 9 7
enQueue(7)
front -1
rear 2
size 3

0 1 2 3 4
5. x=deQueue() 9 7

front 0
rear 2
x = 5 size 2

0 1 2 3 4
6. enQueue(2) 9 7 2 6
enQueue(6)
front 0
rear 4
size 4

0 1 2 3 4
7. q = isFull() 9 7 2 6

front 0
rear 4
q = false size 4

0 1 2 3 4
8. enQueue(3) 3 9 7 2 6

front 0
rear 0
J.Pratheepan Data Structure and Algorithm ATI-Trincomalee
17

size 5

0 1 2 3 4
9. r = isFull() 3 7 2 6
y = deQueue()
front 1
r = true rear 0
y = 9 size 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
}
J.Pratheepan Data Structure and Algorithm ATI-Trincomalee
18

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
J.Pratheepan Data Structure and Algorithm ATI-Trincomalee
19


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

J.Pratheepan Data Structure and Algorithm ATI-Trincomalee
20

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.



J.Pratheepan Data Structure and Algorithm ATI-Trincomalee
21

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.


J.Pratheepan Data Structure and Algorithm ATI-Trincomalee
22

Implementation of Binary Tree:
6

4 8

/ 2 / 5 / / 7 / / 9 /

/ 3 /


Advantages of Binary Tree:
Quick search, Quick inserts, Quick deletes (If the tree remains balanced)

Disadvantages of Binary Tree:
Deletion algorithm is complex
J.Pratheepan Data Structure and Algorithm ATI-Trincomalee
23

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

Pass0 6 7 72 4 32 65 9 56
Original


Pass1 4 7 72 6 32 65 9 56



Pass2 4 6 72 7 32 65 9 56



Pass3 4 6 7 72 32 65 9 56



Pass4 4 6 7 9 32 65 72 56



Pass5 4 6 7 9 32 65 72 56



Pass6 4 6 7 9 32 56 72 65



Pass7 4 6 7 9 32 56 65 72
Sorted

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]<<" ";
}

J.Pratheepan Data Structure and Algorithm ATI-Trincomalee
24

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 6 7 72 4 32 65 9 56
Original


Pass1 6 7 4 32 65 9 56 72



Pass2 6 4 7 32 9 56 65 72



Pass3 4 6 7 9 32 56 65 72



Pass4 4 6 7 9 32 56 65 72



Pass5 4 6 7 9 32 56 65 72
Sorted

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
J.Pratheepan Data Structure and Algorithm ATI-Trincomalee
25

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):


J.Pratheepan Data Structure and Algorithm ATI-Trincomalee
26

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

J.Pratheepan Data Structure and Algorithm ATI-Trincomalee
27

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);
J.Pratheepan Data Structure and Algorithm ATI-Trincomalee
28

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!

S-ar putea să vă placă și