DSNotes Using Java
DSNotes Using Java
Data structures are essential in almost every aspect where data is involved. In
general, algorithms that involve efficient data structure is applied in the following
areas:
Numerical analysis, Operating system, Statistical analysis, Compiler
Design, Operating System, Database Management System, Statistical analysis
package, Numerical Analysis, Graphics, Artificial Intelligence, Simulation
Arrays
Array is a container which can hold a fix number of items and these items
should be of the same type. Most of the data structures make use of arrays
to implement their algorithms. Following are the important terms to
understand the concept of Array.
• Element − Each item stored in an array is called an element.
• Index − Each location of an element in an array has a numerical index,
which is used to identify the element.
As per the above illustration, following are the important points to be considered.
• Index starts with 0.
• Array length is 10 which means it can store 10 elements.
• Each element can be accessed via its index. For example, we can fetch an
element at index 6 as 9.
Basic Operations
Following are the basic operations supported by an array.
Traverse − print all the array elements one by one.
Insertion − Adds an element at the given index.
Deletion − Deletes an element at the given index.
Search − Searches an element using the given index or by the value.
Update − Updates an element at the given index.
Singly Linked List
Limitations of array over linked list:
Array does not grow dynamically (i.e length has to be known) Inefficient
memory management.
In ordered array insertion is slow.
In both ordered and unordered array deletion is slow.
Large number of data movements for insertion & deletion
Which is very expensive in case of array with large number of elements.
Linked List:
We can overcome the drawbacks of the sequential storage.
If the items are explicitly ordered, that is each item contained within itself the
address of the next Item.
In Linked Lists elements are logically adjacent, need not be physically adjacent.
Node is divide into two part.
//--------------------------------Node Class-----------------//
public class Node {
private int data;
private Node next;
@Override
public String toString() {
return data + "";
}
}
public LinkedList() {
head = null;
}
return true;
}
if(position <= 0) {
return false;
}
if(position == 1) {
newNode.setNext(head);
head = newNode;
return true;
}
//2
newNode.setNext(prev.getNext());
//3
prev.setNext(newNode);
return true;
}
if(position == 1) {
head = head.getNext();
return true;
}
prev.setNext(del.getNext());
return true;
}
if(head == null) {
return false;
}
if(head.getData() == data) {
head = head.getNext();
return true;
}
prev.setNext(del.getNext());
return true;
}
void displayRev() {
Node temp = head;
Node [] stack = new Node[100];
int top = -1;
while(temp != null) {
stack[++top] = temp;
temp = temp.getNext();
}
while(top != -1) {
System.out.print(stack[top--] + " ");
}
System.out.println();
}
displayRev( node.getNext() );
System.out.print(node.getData() + " ");
}
void reverse() {
while(n2 != null) {
n3 = n2.getNext();
n2.setNext(n1);
n1 = n2;
n2 = n3;
}
head.setNext(null);
head = n1;
}
Node getHead() {
return head;
}
}
//--------------------------------TesterSLL Class--------------------------------/
public class Main {
public static void main(String [] args) {
l1.reverse();
l1.display();
l1.insert(10);
l1.insert(20);
l1.insert(30);
l1.insert(40);
l1.display();
l1.insert(50, 1);
l1.display();
l1.insert(60, 4);
l1.display();
l1.insert(70, 7);
l1.display();
l1.insert(80, -1);
l1.display();
l1.insert(90, 9);
l1.display();
l1.insert(20);
l1.insert(20, 5);
l1.display();
l1.displayRev();
l1.displayRev( l1.getHead() );
//l1.reverse();
//l1.display();
//l1.displayRev();
/*
while(l1.deleteByVal(20))
;
l1.display();
*/
/*l1.deleteByVal(50);
l1.display();
l1.deleteByVal(60);
l1.display();
l1.deleteByVal(70);
l1.display();
l1.deleteByVal(70);
l1.display();*/
/*
l1.deleteByPosition(1);
l1.display();
l1.deleteByPosition(3);
l1.display();
l1.deleteByPosition(5);
l1.display();
l1.deleteByPosition(5);
l1.display();
l1.deleteByPosition(10);
l1.display();*/
}
}
//----------------------------------Node Class------------------------//
public class Node {
private int data;
private Node next;
public SCLL()
{
this.head=null;//empty list creation
}
public Node getHead()
{
return this.head;
}
public void setHead(Node head)
{
this.head=head;
}
void display() {
Node temp=head;
System.out.println();
do
{
System.out.print(temp.getData()+ " ");
temp=temp.getNext();
} while(temp!=head);
if(pos==1) {
//chk if list is empty
if(this.head==null)//list is empty ...so new node becomes head
{
head=newNode;
head.setNext(head);
return true;
}
else //non empty list
{
newNode.setNext(head);
Node temp=head;
while(temp.getNext()!=head)
{
temp=temp.getNext();
}
temp.setNext(newNode);
head=newNode;
return true;
}
}
else //pos other than first
{
Node prev=head;
for(int i=1;i<pos-1;i++)
{
if(prev.getNext()==head)//out of bound pos
return false;
prev=prev.getNext();
}
newNode.setNext(prev.getNext());
prev.setNext(newNode);
return true;
}
}
if(pos==1)
{
if(head.getNext()==head)//only one node in list
{
head=null;
return true;
}
//non empty list
//locate last node
while(temp.getNext()!=head)
{
temp=temp.getNext();
}
// connect last n second node
temp.setNext(head.getNext());
head=head.getNext();//update head
return true;
}
else //other than first pos
{
//set prev to pos-1
for(int i=1;i<pos-1;i++)
{
if(prev.getNext()==head)//out of bound
{
return false;
}
prev=prev.getNext();
}
del=prev.getNext();
prev.setNext(del.getNext());
return true;
}
}
}
}
A doubly linked list is a linked list data structure that includes a link back to
the previous node in each node in the structure. This is contrasted with a singly
linked list where each node only has a link to the next node in the list. Doubly
linked lists also include a field and a link to the next node in the list.
public DoublyLinkedList() {
head = null;
}
//list is empty
if(head == null) {
head = newNode;
return true;
}
last.setNext(newNode);
newNode.setPrev(last);
return true;
}
public boolean insert(int data, int position) {
if(position <= 0) {
return false;
}
if(position == 1) {
if(head != null ) {
newNode.setNext(head);
head.setPrev(newNode);
}
head = newNode;
return true;
}
return true;
}
while(temp != null) {
System.out.print(temp.getData() + " ");
temp = temp.getNext();
}
System.out.println();
}
if( (head == null || position <= 0 ) || ( head == null && position > 1))
{
return false;
}
if(position == 1) {
head = head.getNext();
if(head != null) {
head.setPrev(null);
}
return true;
}
del.getPrev().setNext(del.getNext());
if(del.getNext() != null) {
del.getNext().setPrev(del.getPrev());
}
return true;
}
return true;
}
}
//-------------------------Tester DLL Class------------------//
public class TesterDLL {
dll.insert(10);
dll.insert(20);
dll.insert(30);
dll.insert(40);
dll.display();
dll.insert(50, 1);
dll.display();
dll.insert(60, 4);
dll.display();
dll.insert(70, 7);
dll.display();
dll.insert(50, 9);
dll.display();
dll.deleteByPosition(1);
dll.display();
dll.deleteByPosition(3);
dll.display();
dll.deleteByPosition(5);
dll.display();
dll.deleteByPosition(5);
dll.display();
}
}
Stack
Stack is a linear data structure which follows a particular order in which the
operations are performed. It is an ordered list in which insertion and deletion
are done at one end, called a top. The last element inserted is the first one to
be deleted. Hence, it is called the Last in First out (LIFO) or First in Last out
(FILO) list.
Applications of Stack:
Direct applications
• Balancing of symbols
• Infix-to-postfix conversion
• Evaluation of postfix expression
• Implementing function calls (including recursion)
• Finding of spans (finding spans in stock markets)
• Page-visited history in a Web browser [Back Buttons]
• Undo sequence in a text editor
• Matching Tags in HTML and XML implemented
Indirect applications
• Auxiliary data structure for other algorithms (Example: Tree traversal s)
• Component of other data structures
(Example: Simulating queues, Queues)
Push Operation
The process of putting a new data element onto the stack is known as a Push
Operation.
Push operation involves a series of steps −
Step 1 − Checks if the stack is full.
Step 2 − If the stack is full, produces an error and exit.
Step 3 − If the stack is not full, increments top to a point next empty space.
Step 4 − Adds data element to the stack location, where the top is pointing.
Step 5 − Returns success.
If the linked list is used to implement the stack, then in step 3, we need to
allocate space dynamically.
Pop Operation
Accessing the content while removing it from the stack, is known as a Pop
Operation. In an array implementation of pop() operation, the data element
is not actually removed, instead top is decremented to a lower position in the
stack to point to the next value. But in linked-list implementation, pop()
actually removes data element and deallocates memory space.
A Pop operation may involve the following steps −
Step 1 − Checks if the stack is empty.
Step 2 − If the stack is empty, produces an error and exit.
Step 3 − If the stack is not empty, accesses the data element at which top is
pointing.
Step 4 − Decreases the value of top by 1.
Step 5 − Returns success.
Push Operation
In a push operation, we add an element into the top of the stack.
Increment the variable Top so that it can now refer to the next memory
location.
Add an element at the position of the incremented top. This is referred
to as adding a new element at the top of the stack.
Throw an exception if Stack is full.
Pop Operation
Remove the top element from the stack and decrease the size of a top
by 1.
Throw an exception if Stack is empty.
In the array, we add elements from left to right and use a variable to
keep track of the index of the top element. The array storing the stack
elements may become full. A push operation will then throw a full stack
exception. Similarly, if we try deleting an element from an empty stack it will
throw a stack empty exception.
//*--------------Stack Class-----------------------*/
public class Stack {
private int [] arr;
private int size;
private int top;
public Stack() {
size = 5;
arr = new int[5];
top = -1;
}
arr[++top] = data;
return true;
}
return arr[top--];
}
return arr[top];
}
//*----------------------TesterMain Class------------------*/
public class Main {
public static void main(String [] args) {
Stack s = new Stack(4);
System.out.println("Pop: " + s.pop());
System.out.println("Push: " + s.push(0) );
System.out.println("Push: " + s.push(20) );
System.out.println("Push: " + s.push(30) );
System.out.println("Push: " + s.push(40) );
System.out.println("Push: " + s.push(50) );
}
}
Stack implementation using Linked List in Java. Instead of using an array, we can
also use a linked list to implement a Stack. Linked list allocates the memory
dynamically. However, time complexity in both the scenario is the same for all the
operations i.e. push, pop and peek.
In the linked list implementation of a Stack, the nodes are maintained non-
contiguously in the memory. Each node contains a pointer to its immediate
successor node in the Stack. A Stack is said to be overflown if the space left in the
memory heap is not enough to create a node.
A push operation is implemented by inserting an element at the
beginning of the list.
A pop operation is implemented by deleting the node from the
beginning (the header/top node).
public Node()//def
{
this.data=0;
this.next=null;
}
public Node(int data)//param.
{
this.data=data;
this.next=null;
}
int getData()
{
return this.data;
}
Node getNext()
{
return this.next;
}
public StackLiLi()
{
this.top=null;
}
int pop()
{
if(top==null) //empty stack
return -999;
//non empty stack
int val=top.getData();
top=top.getNext();
return val;
}
int peek()
{
if(top==null) //empty stack
return -999;
//non empty stack
int val=top.getData();
return val;
}
void display()
{
Node temp=top;
System.out.println();
while(temp!=null)
{
System.out.print(temp.getData()+ " " );
temp=temp.getNext();
}
}
}
//*-------------------------Tester Main ---------------------*/
package com.stklili;
s1.push(10);
s1.push(20);
s1.push(30);
System.out.println("peek : "+s1.peek());
s1.push(40);
s1.push(50);
s1.display();
s1.push(60);
System.out.println("popped: "+s1.pop());
System.out.println("popped: "+s1.pop());
System.out.println("popped: "+s1.pop());
System.out.println("popped: "+s1.pop());
System.out.println("popped: "+s1.pop());
System.out.println("popped: "+s1.pop());
s1.display();
}
}
Polish Notation:
These are notations to represent math equations.
• Infix Notation: A+B
• Prefix Notation: +AB
• Postfix Notation: AB+
To convert infix to prefix /postfix considers the priorities:
Ex: A+ (B*C-(D/E^F)*G)*H
Check chart below as an example.
Infix to prefix Evaluation rules:
1. Reserve the input string or start from right of the infix expression
2. Examine the next element in the input.
3. If it is operand , add it to output string .
4. If it is closing parenthesis ,push it on to stack.
5. If it is an operator ,then
6. If stack is empty , push operator on stack.
7.
same or higher priority then the top of stack push operator on stack
8. If it has lower priority the top, the pop stack and add it to post fix
expression and push operator into stack
9. Else pop the operator from the stack and add it to output string If it is an
opening parenthesis, pop operators from stack and ass them to output
string until a closing parenthesis is encountered. pop and discard the
closing parenthesis.
10. If there is more input go to step 2.
11. If there is no more input , unstack the remaining operators and them to
output string.
12. Reserve the output string.
Queue
A Queue is an ordered collection of items into which new items may be
inserted at rear end and items are deleted at one end called front.
Which is exactly how queue system works in real world. If you go to a ticket
counter to buy movie tickets, and are first in the queue, then you will be the
first one to get the tickets. Right? Same is the case with Queue data structure.
Data inserted first, will leave the queue first.
The process to add an element into queue is called Enqueue and the process
of removal of an element from queue is called Dequeue.
Types of Queue:
1. Linear Queue
2. Circular Queue
3. Priority Queue
4. Dequeue (Double Ended Queue)
Operations performed on Queue
ENQUEUE operation
1. Check if the queue is full or not.
2. If the queue is full, then print overflow error and exit the program.
3. If the queue is not full, then increment the rear and add the element.
DEQUEUE operation
1. Check if the queue is empty or not.
2. If the queue is empty, then print underflow error and exit the program.
3. If the queue is not empty, then print the element at the front and increment
the front.
Applications of Queue
//*----------------------------------Queue Class--------------------*/
public class Queue {
private int [] arr;
private int front, rear;
private int size;
arr[++rear] = data;
if(front == -1) {
front = 0;
}
return arr[front++];
}
Q1.insert(10);
Q1.insert(20);
Q1.insert(30);
//System.out.println(Q1.peek());
Q1.insert(40);
Q1.insert(50);
Q1.display();
System.out.println();
System.out.println("deleted :"+Q1.delete());
System.out.println("deleted :"+Q1.delete());
Q1.insert(60);
Q1.insert(70);//bubble prob
Q1.display();
System.out.println("deleted :"+Q1.delete());
Q1.insert(70);
Q1.display();
}
}
Difference between Stack and Queue:
Trees
A tree consists of nodes connected by edges, which do not form cycle.
For collection of nodes & edges to define as tree, there must be one &
only one path from the root to any other node.
A tree is a connected graph of N vertices with N-1 Edges.
Tree Terminologies:
1. Node: A node stands for the item of information plus the branches of other
items.
3. Degree: The number of sub trees of a node is called degree. The degree of a
tree is the maximum degree of the nodes in the tree.
4. Leaf Nodes: Nodes that have the degree as zero are called leaf nodes or
terminal nodes. Other nodes are called non terminal nodes.
5. Ancestor: The ancestor of a node are all the nodes along the path from the
root to that node.
6. Level: The level of a node is defined by first letting the root of the tree to
be level = 1or level=0.
A Binary Search Tree (BST) is a tree in which all the nodes follow the below
mentioned properties –
The left sub-tree of a node has a key less than or equal to its parent node's
key.
The right sub-tree of a node has a key greater than to its parent node's
key.
Tree traversals:
Traversal is a process to visit all the nodes of a tree and may print their values
too. Because, all nodes are connected via edges (links) we always start from the
root (head) node. That is, we cannot randomly access a node in a tree. There are
three ways which we use to traverse a tree ,
In-order Traversal
Pre-order Traversal
Post-order Traversal
e.g.
Preorder:
In this traversal method, the root node is visited first, then the left subtree
and finally the right subtree.
Algorithm
1. Visit the root.
2. Traverse the left subtree, i.e., call Preorder(left-subtree)
3. Traverse the right subtree, i.e., call Preorder(right-subtree)
Inorder:
In this traversal method, the left subtree is visited first, then the root and
later the right sub-tree. We should always remember that every node may
represent a subtree itself.
If a binary tree is traversed in-order, the output will produce sorted key
values in an ascending order.
Algorithm
1. Traverse the left subtree, i.e., call Inorder (left-subtree)
2. Visit the root.
3. Traverse the right subtree, i.e., call Inorder (right-subtree)
Postorder:
In this traversal method, the root node is visited first, then the left subtree
and finally the right subtree.
Algorithm
1. Traverse the left subtree, i.e., call Postorder(left-subtree)
2. Traverse the right subtree, i.e., call Postorder(right-subtree)
3. Visit the root.
//*----------------------------BST Node Class----------------------------*/
public BinarySearchTree() {
root = null;
}
if (root == null) {
root = newNode;
return true;
}
while (true) {
if (data == temp.getData()) {
return false;
}
if (data < temp.getData()) {
//insert to left
if (temp.getLeft() == null) {
//newnode will become left child of temp
temp.setLeft(newNode);
return true;
}
temp = temp.getLeft();
} else {
//insert to right
if (temp.getRight() == null) {
//newnode will become right child of temp
temp.setRight(newNode);
return true;
}
temp = temp.getRight();
}
}
System.out.print("PreOrder : ");
temp = stack[top--];
temp = temp.getRight();
}
System.out.println();
}
System.out.print("InOrder : ");
temp = stack[top--];
System.out.print(temp.getData() + " ");
temp = temp.getRight();
}
System.out.println();
}
System.out.print("PostOrder: ");
class Pair {
public Node node;
public char flag;
}
while(temp != null) {
Pair pair = new Pair();
pair.node = temp;
pair.flag = 'L';
stack[++top] = pair;
temp = temp.getLeft();
}
}
System.out.println();
}
inOrder(root.getLeft());
System.out.print(root.getData() + " ");
inOrder(root.getRight());
}
postOrder(root.getLeft());
postOrder(root.getRight());
System.out.print(root.getData() + " ");
}
while (true) {
//2. check if the del node is terminal node, if it is unlink it from the parent
if (del.getLeft() == null && del.getRight() == null) {
if (del == root) {
root = null;
return true;
}
if (parent.getLeft() == del) {
parent.setLeft(null);
} else {
parent.setRight(null);
}
return true;
}
del = max;
} else {
//find min from right
Node min = del.getRight();
parent = del;
while(min.getLeft() != null) {
parent = min;
min = min.getLeft();
}
del = min;
}
}
}
bst.preOrder();
bst.inOrder();
bst.postOrder();
System.out.println( bst.insert(50) );
System.out.println( bst.insert(20) );
System.out.println( bst.insert(28) );
System.out.println( bst.insert(80) );
System.out.println( bst.insert(10) );
System.out.println( bst.insert(60) );
System.out.println( bst.insert(100) );
System.out.println( bst.insert(15) );
System.out.println( bst.insert(55) );
System.out.println( bst.insert(70) );
System.out.println( bst.insert(15) );
System.out.println( bst.insert(12) );
System.out.println( bst.insert(18) );
System.out.println("count = " + bst.count(bst.getRoot()));
bst.preOrder();
bst.preOrder(bst.getRoot());
System.out.println();
bst.inOrder();
bst.inOrder(bst.getRoot());
System.out.println();
bst.postOrder();
bst.postOrder(bst.getRoot());
System.out.println();
System.out.println();
Threaded Binary Tree is also a binary tree in which all left child pointers that are
NULL (in Linked list representation) points to its in-order predecessor, and all
right child pointers that are NULL (in Linked list representation) points to its in-
order successor.
super();
this.data = data;
this.left=null;
this.right=null;
this.Lflag='T';
this.Rflag='T';
return data;
this.data = data;
}
public Node getLeft() {
return left;
this.left = left;
return right;
this.right = right;
return Lflag;
Lflag = lflag;
return Rflag;
}
public void setRflag(char rflag) {
Rflag = rflag;
public TBST() {
super();
this.root=null;
return root;
this.root = root;
if(root==null){
root=newnode;
return true;
Node temp=root;
while(temp.getData()!=data){
if(data<temp.getData()){
//insert left
if(temp.getLflag()=='T'){
newnode.setRight(temp);
newnode.setLeft(temp.getLeft());
temp.setLeft(newnode);
temp.setLflag('L');
return true;
temp=temp.getLeft();
else{
//insert right
if(temp.getRflag()=='T'){
//parent will become inorder predecessor of newnode
newnode.setLeft(temp);
newnode.setRight(temp.getRight());
temp.setRight(newnode);
temp.setRflag('L');
return true;
temp=temp.getRight();
return false;
Node temp=root;
char flag='L';
while(temp!=null){
temp=temp.getLeft();
if(flag=='L'){
System.out.print(" "+temp.getData());
flag=temp.getRflag();
temp=temp.getRight();
Node temp=root;
char flag='L';
while(temp!=null){
temp=temp.getLeft();
System.out.print(" "+temp.getData());
flag=temp.getRflag();
temp=temp.getRight();
}
if(node==root){
return false;
Node temp=root;
while(true){
if(node.getData()<temp.getData()){
temp=temp.getLeft();
if(temp==node){
return false;
else{
temp=temp.getRight();
if(temp==node){
return true;
}
}
Node temp=root;
char flag='L';
while(temp!=null){
temp=temp.getLeft();
flag=temp.getRflag();
if(flag=='L'){
temp=temp.getRight();
else{
while(true){
System.out.print(" "+temp.getData());
boolean isRight=isRight(temp);
if(isRight){
while(temp.getLflag()=='L'){
temp=temp.getLeft();
}
temp=temp.getLeft();
else{
while(temp.getRflag()=='L'){
temp=temp.getRight();
temp=temp.getRight();
break;
Node del=root,parent=root;
if(root==null){
return false;
}
while(true){
while(del.getData()!=data){
if(data<del.getData()){
//left
if(del.getLflag()=='T'){
return false;
parent=del;
del=del.getLeft();
else{
//right
if(del.getRflag()=='T'){
return false;
parent=del;
del=del.getRight();
}
//check for terminal node
if(del==root){
root=null;
return true;
if(parent.getLeft()==del){
parent.setLeft(del.getLeft());
parent.setLflag('T');
else{
//right child
parent.setRight(del.getRight());
parent.setRflag('T');
}
return true;
if(del.getLflag()=='L'){
Node max=del.getLeft();
parent=del;
while(max.getRflag()=='L'){
parent=max;
max=max.getRight();
//swap
int temp=max.getData();
max.setData(del.getData());
del.setData(temp);
del=max;
else{
Node min=del.getRight();
parent=del;
while(min.getLflag()=='L'){
parent=min;
min=min.getLeft();
int temp=min.getData();
min.setData(del.getData());
del.setData(temp);
del=min;
t.insert(50);
t.insert(30);
t.insert(90);
t.insert(40);
t.insert(60);
t.insert(20);
t.insert(100);
t.insert(25);
/*t.inOrder();
System.out.println("\n\n-----------------\n\n");
//t.preOrder();
t.deleteData(50);
t.inOrder();
System.out.println("\n\n-----------------\n\n");
t.deleteData(30);*/
t.postOrder();
System.out.println("\n\n-----------------\n\n");
}
Graph
Graphs provide the ultimate in data structure flexibility. A graph consists of a set
of nodes, and a set of edges where an edge connects two nodes. Trees and lists
can be viewed as special cases of graphs.
Graphs are used to model both real-world systems and abstract problems, and
are the data structure of choice in many applications.
Here is a small sampling of the types of problems that graphs are routinely used
for.
Definition
A Graph is a collection of nodes, which are called vertices ‘V’, connected in
pairs by line segments, called Edges E.
Sets of vertices are represented as V(G) and sets of edges are represented as
E(G).
So a graph is represented as G = (V, E).
There are two types of Graphs
- Undirected Graph
- Directed Graph
Graph traversal
Many graph applications need to visit the vertices of a graph in some specific order
based on the graph's topology. This is known as a graph traversal and is similar in
concept to a tree traversal. Standard graph traversal orders also exist. Each is
appropriate for solving certain problems.
//*--------------------Graph class-------------*/
//Adjacency Matrix representation
init();
}
int curVertex;
while( front <= rear) {
curVertex = queue[front++];
if(visited[curVertex] == 0) {
System.out.print( vertices[curVertex] + " ");
visited[curVertex] = 1;
while(top != -1) {
curVertex = stack[top];
for(int i = 0; i < noOfVertices; i++) {
if(adjMat[curVertex][i] == 1 && visited[i] == 0) {
System.out.print( vertices[i] + " ");
visited[i] = 1;
stack[++top] = i;
curVertex = i;
i = -1;
}
}
top--;
}
System.out.println();
}
}
//*--------------------------Tester Main ---------------------*/
public class Main {
public static void main(String [] args) {
Graph g = new Graph(9);
g.display();
g.bfs(0);
g.bfs(5);
g.dfs(0);
g.dfs(3);
}
}
Searching & Sorting Algorithms
Searching means finding out an element in array that meet some specified criteria.
Sorting means rearranging all the items in array in increasing or decreasing order.
Sequential Search: This is simplest type of searching. The search starts at first
record and move through each record until match is made or not.
The best case for sequential search is that it does one comparison, and matches X
right away. In the worst case, sequential search does n comparisons, and either
matches the last item in the list or doesn't match anything. The average case is
harder to do.
Binary search is the search technique which works efficiently on the sorted lists.
Hence, in order to search an element into some list by using binary search
technique, we must ensure that the list is sorted.
Binary search follows divide and conquer approach in which, the list is divided
into two halves and the item is compared with the middle element of the list. If
the match is found then, the location of middle element is returned otherwise, we
search into either of the halves depending upon the result produced through the
match.
In the base case, the algorithm will end up either finding the element or just
failing and returning false. In both cases, the algorithm is going to take a
constant time because only comparison and return statements are going to be
executed.
import java.util.*;
public class BinarySearch {
public static void main(String[] args) {
int[] arr = {16, 19, 20, 23, 45, 56, 78, 90, 96, 100};
int item, location = -1;
System.out.println("Enter the item which you want to search");
Scanner sc = new Scanner(System.in);
item = sc.nextInt();
location = binarySearch(arr,0,9,item);
if(location != -1)
System.out.println("the location of the item is "+location);
else
System.out.println("Item not found");
}
public static int binarySearch(int[] a, int beg, int end, int item)
{
int mid;
if(end >= beg)
{
mid = (beg + end)/2;
if(a[mid] == item)
{
return mid+1;
}
else if(a[mid] < item)
{
return binarySearch(a,mid+1,end,item);
}
else
{ return binarySearch(a,beg,mid-1,item);
}
}
return -1; } }
Introduction To Sorting
Sorting Algorithm is used to rearrange a given array or list elements according to a
comparison operator on the elements. The
comparison operator is used to decide the new order of element in the respective
data structure.
Sorting arranges data in a sequence which makes searching easier. Every record
which is going to be sorted will contain one key. Based on the key the record will
be sorted.
Type of Sorting
Bubble Sort
Selection Sort
Insertion Sort
Quick Sort
Merge Sort
Heap Sort
Shell Sort
Bubble Sort
We can create a java program to sort array elements using bubble sort. Bubble
sort algorithm is known as the simplest sorting algorithm.
In bubble sort algorithm, array is traversed from first element to last element.
Here, current element is compared with the next element. If current element is
greater than the next element, it is swapped.
Selection sort is an algorithm that selects the smallest element from an unsorted
list in each iteration and places that element at the beginning of the unsorted
list.
Selection Sort Applications
Insertion Sort
Insertion sort is the sorting mechanism where the sorted array is built having
one item at a time. The array elements are compared with each other
sequentially and then arranged simultaneously in some particular order. The
analogy can be understood from the style we arrange a deck of cards. This sort
works on the principle of inserting an element at a particular position, hence the
name Insertion Sort.
Shell Sort
Shell sort is an algorithm that first sorts the elements far apart from each
other and successively reduces the interval between the elements to be
sorted. It is a generalized version of insertion sort.In shell sort, elements at a
specific interval are sorted. The interval between the elements is gradually
decreased based on the sequence used. The performance of the shell sort
depends on the type of sequence used for a given input array.
Heap Sort is one of the best sorting methods being in-place and with no quadratic
worst-case running time. Heap sort involves building a Heap data structure from
the given array and then utilizing the Heap to sort the array.
You must be wondering, how converting an array of numbers into a heap data
structure will help in sorting the array.
Heap sort algorithm is divided into two basic parts:
Initially on receiving an unsorted list, the first step in heap sort is to create a
Heap data structure(Max-Heap or Min-Heap). Once heap is built, the first
element of the Heap is either largest or smallest(depending upon Max-Heap
or Min-Heap), so we put the first element of the heap in our array. Then we
again make heap using the remaining elements, to again pick the first
element of the heap and put it into the array. We keep on doing the same
repeatedly untill we have the complete sorted list in our array.
// Java program for implementation of Heap Sort