0% found this document useful (0 votes)
13 views

DSA-Notes [JUMAIL]

Uploaded by

mmhalith3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

DSA-Notes [JUMAIL]

Uploaded by

mmhalith3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

JUMAIL.

WM Data Structure and Algorithm

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

2. queue (first-in-f irst-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 Difficult to implement
organized as linear fashion
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).

1
JUMAIL.WM Data Structure and Algorithm

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

2
JUMAIL.WM Data Structure and Algorithm

2. Array Data Structure

What is an array?
Arrays are a group of continuous similar type of variables referred by a common name.
In Java, 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

A program to store and print elements in an array java:

public class Main {

public static void main(String[] args) {

// Declare and initialize an array

int[] array = {1, 2, 3, 4, 5};

// Print the elements of the array

for (int i = 0; i < array.length; i++) {

System.out.println("Element at index " + i + ": " + array[i]);

A program to search and replace an element in an array java:

public class Main {


public static void main(String[] args) {
// Declare and initialize an array
int[] array = {1, 2, 3, 4, 5};

// Element to search for


int searchElement = 3;

// Element to replace with


int replaceElement = 10;

// Search and replace


for (int i = 0; i < array.length; i++) {
if (array[i] == searchElement) {
array[i] = replaceElement;
}
}

// Print the modified array


for (int i = 0; i < array.length; i++) {

3
JUMAIL.WM Data Structure and Algorithm

System.out.println("Element at index " + i + ": " + array[i]);


}
}
}

A program to delete an elementfrom an array java:

Actually we can’t 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).

public class Main {


public static void main(String[] args) {
// Declare and initialize an array
int[] array = {1, 2, 3, 4, 5};

// Element to delete
int deleteElement = 3;

// Find the index of the element to delete


int deleteIndex = -1;
for (int i = 0; i < array.length; i++) {
if (array[i] == deleteElement) {
deleteIndex = i;
break;
}
}

// If the element was found, delete it


if (deleteIndex != -1) {
// Shift all elements after the deleted element one position to the left
for (int i = deleteIndex; i < array.length - 1; i++) {
array[i] = array[i + 1];
}

// The last element is now a duplicate of the second-to-last element, so we can delete it
array[array.length - 1] = 0;
}

// Print the modified array


for (int i = 0; i < array.length; i++) {
System.out.println("Element at index " + i + ": " + array[i]);
}
}
}

4
JUMAIL.WM Data Structure and Algorithm

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

public class Main {


public static void main(String[] args) {
// Declare and initialize a two-dimensional array
int[][] array = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

// Print the elements of the array


for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.println("Element at index (" + i + ", " + j + "): " + array[i][j]);
}
}
}
}

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

5
JUMAIL.WM Data Structure and Algorithm

3. Linked List Data Structure

What is Pointer?
Pointer contains memory address of a particular type of data.
In java, we use * to declare a pointer.
2cdf 1a5c c75c
p iptr 1a5c cptr c75c

p 9 iptr 5 cptr $ t # /0

9 1a5c $t#

2cdf 5 $
2cdf 1a5c
p 9 iptr 2cdf 5 cptr $ t # /0

What is Structure (in Java)?

In Java, a structure is not a built-in data type like int, float, or String. However, you can create your own
custom data types using classes and objects.

A class in Java is a blueprint for creating objects (a particular data structure), providing initial values for
state (member variables or attributes), and implementations of behavior (member functions or
methods).

Here is an example of a simple class in Java:

public class Car {


// Attributes
private String color;
private String model;
private int year;

// Constructor
public Car(String color, String model, int year) {
this.color = color;
this.model = model;
this.year = year;
}

// Methods
public String getColor() {
return color;
}

public String getModel() {


return model;
}

public int getYear() {


return year;
}

6
JUMAIL.WM Data Structure and Algorithm

public void setColor(String color) {


this.color = color;
}

public void setModel(String model) {


this.model = model;
}

public void setYear(int year) {


this.year = year;
}
}

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

data

data

data
next

next

next

next

head 5 9 6 7 /

E.g2:
data

data

data

data
next

next

next

next

head
front 5 9 6 7 /
rear

7
JUMAIL.WM Data Structure and Algorithm

E.g3:

previous

previous

previous

previous
data

data

data

data
next

next

next

next
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 /

2. insertFirstElt(5)
data
next

head 5 /

3.insertAtFront(3)
data
next

head 5 /
data
next

newNode 3

4. insertAtEnd(8)
data

data
next

next

head 3 5

newNode 8 /

5. insertAfter(5,7)
data

data

data
next

next

next

head 3 5 8 /

newNode 7

8
JUMAIL.WM Data Structure and Algorithm

6. deleteElt(5):

data

data

data

data
next

next

next

next
head 3 5 7 8 /

Implementation of Linked List Operations:

public class Node {


int data;
Node next;

// Constructor to create a new node


Node(int d) {
data = d;
next = null;
}
}

public class LinkedList {


Node head; // head of list

// Insert a new node at the end of the list


public void insert(int data) {
Node new_node = new Node(data);
if (head == null) {
head = new Node(data);
return;
}
new_node.next = null;

Node last = head;


while (last.next != null)
last = last.next;

last.next = new_node;
return;
}

// Delete a node with a given key


void delete(int key) {
Node temp = head, prev = null;

if (temp != null && temp.data == key) {


head = temp.next;
return;
}

while (temp != null && temp.data != key) {


prev = temp;
temp = temp.next;
}

if (temp == null) return;

prev.next = temp.next;
}
9
JUMAIL.WM Data Structure and Algorithm

// Print the linked list


public void printList() {
Node tnode = head;
while (tnode != null) {
System.out.print(tnode.data+" ");
tnode = tnode.next;
}
}

public static void main(String[] args) {


LinkedList llist = new LinkedList();

llist.insert(1);
llist.insert(2);
llist.insert(3);
llist.insert(4);
llist.insert(5);
llist.insert(6);
llist.insert(7);
llist.insert(8);

System.out.println("\nCreated Linked list is: ");


llist.printList();

llist.delete(1); // Delete node at position 4

System.out.println("\nLinked List after Deletion at position 1: ");


llist.printList();
}
}

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.

10
JUMAIL.WM Data Structure and Algorithm

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

11
JUMAIL.WM Data Structure and Algorithm
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

12
JUMAIL.WM Data Structure and Algorithm

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 [Java Code]:

public class Stack {

private int maxSize;

private int top;

private int[] stackArray;

// Constructor to initialize the stack

public Stack(int size) {

maxSize = size;

stackArray = new int[maxSize];

top = -1;

13
JUMAIL.WM Data Structure and Algorithm

// Method to add an element to the stack

public void push(int value) {

if(top < maxSize - 1) {

stackArray[++top] = value;

System.out.println(value + " pushed to stack");

} else {

System.out.println("Stack is full. Can't push " + value);

// Method to remove an element from the stack

public int pop() {

if(top >= 0) {

System.out.println(stackArray[top] + " popped from stack");

return stackArray[top--];

} else {

System.out.println("Stack is empty");

return -1;

// Method to check the top element of the stack

public int peek() {

if(top >= 0) {

System.out.println("Top element is " + stackArray[top]);

return stackArray[top];

} else {

System.out.println("Stack is empty");

return -1;

}
14
JUMAIL.WM Data Structure and Algorithm
}

// Method to check if the stack is empty

public boolean isEmpty() {

return (top == -1);

// Method to check if the stack is full

public boolean isFull() {

return (top == maxSize - 1);

public static void main(String[] args) {

Stack stack = new Stack(5);

stack.push(1);

stack.push(2);

stack.push(3);

stack.push(4);

stack.push(5);

stack.peek();

stack.pop();

stack.pop();

stack.peek();

System.out.println("Is stack empty? " + stack.isEmpty());

System.out.println("Is stack full? " + stack.isFull());

15
JUMAIL.WM Data Structure and Algorithm

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

16
JUMAIL.WM Data Structure and Algorithm

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

17
JUMAIL.WM Data Structure and Algorithm

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

18
JUMAIL.WM Data Structure and Algorithm

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 [Java Code]:

public class Stack {


private int maxSize;
private int top;
private int[] stackArray;

// Constructor to initialize the stack


public Stack(int size) {
maxSize = size;
stackArray = new int[maxSize];
top = -1;
}

// Method to add an element to the stack


public void push(int value) {
if(top < maxSize - 1) {
stackArray[++top] = value;
System.out.println(value + " pushed to stack");
} else {
System.out.println("Stack is full. Can't push " + value);
}
}

// Method to remove an element from the stack


public int pop() {
if(top >= 0) {
System.out.println(stackArray[top] + " popped from stack");
return stackArray[top--];
} else {
System.out.println("Stack is empty");
return -1;
}
}

// Method to check the top element of the stack


public int peek() {
if(top >= 0) {
System.out.println("Top element is " + stackArray[top]);
return stackArray[top];
} else {
System.out.println("Stack is empty");
return -1;
}
}

19
JUMAIL.WM Data Structure and Algorithm

// Method to check if the stack is empty


public boolean isEmpty() {
return (top == -1);
}

// Method to check if the stack is full


public boolean isFull() {
return (top == maxSize - 1);
}

public static void main(String[] args) {


Stack stack = new Stack(5);

stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);

stack.peek();

stack.pop();
stack.pop();

stack.peek();

System.out.println("Is stack empty? " + stack.isEmpty());


System.out.println("Is stack full? " + stack.isFull());
}
}

20
JUMAIL.WM Data Structure and Algorithm

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

21
JUMAIL.WM Data Structure and Algorithm

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.

22
JUMAIL.WM Data Structure and Algorithm

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.

23
JUMAIL.WM Data Structure and Algorithm

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

24
JUMAIL.WM Data Structure and Algorithm

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

Java Code:

public class Stack {


private int maxSize;
private int top;
private int[] stackArray;

// Constructor to initialize the stack


public Stack(int size) {
maxSize = size;
stackArray = new int[maxSize];
top = -1;

25
JUMAIL.WM Data Structure and Algorithm

// Method to add an element to the stack


public void push(int value) {
if(top < maxSize - 1) {
stackArray[++top] = value;
System.out.println(value + " pushed to stack");
} else {
System.out.println("Stack is full. Can't push " + value);
}
}

// Method to remove an element from the stack


public int pop() {
if(top >= 0) {
System.out.println(stackArray[top] + " popped from stack");
return stackArray[top--];
} else {
System.out.println("Stack is empty");
return -1;
}
}

// Method to check the top element of the stack


public int peek() {
if(top >= 0) {
System.out.println("Top element is " + stackArray[top]);
return stackArray[top];
} else {
System.out.println("Stack is empty");
return -1;
}
}

// Method to check if the stack is empty


public boolean isEmpty() {
return (top == -1);
}

// Method to check if the stack is full


public boolean isFull() {
return (top == maxSize - 1);
}

public static void main(String[] args) {


Stack stack = new Stack(5);

stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);

stack.peek();

stack.pop();
stack.pop();

stack.peek();

26
JUMAIL.WM Data Structure and Algorithm

System.out.println("Is stack empty? " + stack.isEmpty());


System.out.println("Is stack full? " + stack.isFull());
}
}

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

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


swap(&a[j],&a[j+1])
swapped = true
end if
next j
max=max-1
end while

27
JUMAIL.WM Data Structure and Algorithm

Java Code:

public class BubbleSort {

void bubbleSort(int arr[]) {

int n = arr.length;

for (int i = 0; i < n-1; i++)

for (int j = 0; j < n-i-1; j++)

if (arr[j] > arr[j+1]) {

// swap arr[j+1] and arr[j]

int temp = arr[j];

arr[j] = arr[j+1];

arr[j+1] = temp;

/* Prints the array */

void printArray(int arr[]) {

int n = arr.length;

for (int i=0; i<n; ++i)

System.out.print(arr[i] + " ");

System.out.println();

// Driver method to test above

public static void main(String args[]) {

BubbleSort ob = new BubbleSort();

int arr[] = {6, 7, 72, 4, 32, 65, 9, 56};

ob.bubbleSort(arr);

System.out.println("Sorted array");

ob.printArray(arr);

28
JUMAIL.WM Data Structure and Algorithm

Efficiency of the Sort Algorithms (Best, Worst and Average Case Comparison):

29
JUMAIL.WM Data Structure and Algorithm

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;

Java Implementation:

public class LinearSearch {


public static int search(int arr[], int x) {
int n = arr.length;
for (int i = 0; i < n; i++) {
if (arr[i] == x)
return i;
}
return -1;
}

public static void main(String args[]) {


int arr[] = {10, 20, 80, 30, 60, 50, 110, 100, 130, 170};
int x = 110;

int result = search(arr, x);


if (result == -1)
System.out.print("Element is not present in array");
else
System.out.print("Element is present at index " + result);
}
}

30
JUMAIL.WM Data Structure and Algorithm

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

31
JUMAIL.WM Data Structure and Algorithm

Java Implementation:

public class BinarySearch {

int binarySearch(int arr[], int x) {

int l = 0, r = arr.length - 1;

while (l <= r) {

int m = l + (r - l) / 2;

// Check if x is present at mid

if (arr[m] == x)

return m;

// If x greater, ignore left half

if (arr[m] < x)

l = m + 1;

// If x is smaller, ignore right half

else

r = m - 1;

// if we reach here, then element was not present

return -1;

public static void main(String args[]) {

BinarySearch ob = new BinarySearch();

int arr[] = {2, 3, 4, 10, 40};

int n = arr.length;

int x = 10;

int result = ob.binarySearch(arr, x);

if (result == -1)

System.out.println("Element not present");

else

System.out.println("Element found at index " + result);

}
32
JUMAIL.WM Data Structure and Algorithm
}

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 Java Code:

public class RecursiveExample {


public static void main(String[] args) {
int number = 5;
long factorial = factorial(number);
System.out.println("Factorial of " + number + " = " + factorial);
}

public static long factorial(int n) {


if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
}

33
JUMAIL.WM Data Structure and Algorithm

Output: Factorial of 5 = 120

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!

34

You might also like