Você está na página 1de 51

CONTENT

1. Sorting Algorithms-Insertion sort, Selection sort, Bubble sort.


2. Fibonacci series
3. Reverse a string
4. Palindrome checking
5. Stack Application( Implement simple Stack also)
a. Infix to Postfix conversion
b. Postfix Evaluation
6. Queue Application (Implement simple Queue also)
7. Linklist Application(Implement simple link list also)
a. Polynomial Addition
b. Sparse Matrix
8. Breadth First Search
9. Depth First Search
10.Quicksort
11.Heapsort
12.Mergesort
13.Binary Search Tree with tree traversals-pre-order, in-order, post-order
14.Dijikstra’s (shortest path algorithm)
15.Minimum Spanning Tree
a. Kruskals
b. Prims

16.Counting Sort
1. SORTING
import java.io.*;
class Array
{
private int[] a;
private int nElems;

public Array(int max)


{
a = new int[max];
nElems = 0;
}

public void insert(int value)


{
a[nElems] = value;
nElems++;
}

public void display()


{
for(int j=0; j<nElems; j++)
System.out.print(a[j] + " ");
System.out.println("");
}

public void bubbleSort()


{
int out, in;
for(out=nElems-1;out>=0;out--)
for(in=0; in<out; in++)
if( a[in] > a[in+1] )
swap(in, in+1);
}
public void selectionSort()
{
int out, in, min;
for(out=0;out<nElems;out++)
{
min = out;
for(in=out+1; in<nElems; in++)
if(a[in] < a[min] )
min = in;
swap(out, min);
}
}
public void insertionSort()
{
int in, out;

for(out=1; out<nElems; out++)


{
int temp = a[out];
in = out;
while(in>0&&a[in-1]>=temp)
{
a[in]=a[in-1];
--in;
}
a[in] = temp;
}
}

private void swap(int one, int two)


{
int temp = a[one];
a[one] = a[two];
a[two] = temp;
}

class Main
{
public static void main(String[] args) throws Exception
{
Array arr;
int ch;
BufferedReader b= new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the size of array:");
int maxSize=Integer.parseInt(b.readLine());
arr = new Array(maxSize);
System.out.println("Enter the array:");
for(int i=0;i<maxSize;i++)
arr.insert(Integer.parseInt(b.readLine()));
System.out.println("Array before sortin:");
arr.display();
start:
System.out.println("Sorting:");
System.out.println("1.Bubble sort ");
System.out.println("2.Insertion Sort");
System.out.println("3.Selection Sort");
System.out.println("Enter your choice:");
ch=Integer.parseInt(b.readLine());
switch(ch)
{
case 1:arr.bubbleSort();
break;
case 2:arr.insertionSort();
break;
case 3:arr.selectionSort();
break;
}
System.out.println("Array after sortin:");
arr.display();
}
}

O/P:
Enter the size of array:
7
Enter the array:
22 19 7 5 15 2 1
Array before sortin:
22 19 7 5 15 2 1
Sorting:
1.Bubble sort
2.Insertion Sort
3.Selection Sort
Enter your choice:
2
Array after sortin:
1 2 5 7 15 19 22

2. FIBONACCI
import java.io.*;
class fibonacci
{
private int first;
private int second;
private int third;
public fibonacci()
{
first=0;
second=1;
third=0;
}
public void getfibo(int n)
{
if(n==1)
System.out.print(first);
else if(n==2)
System.out.print(first+" "+second);
else
{
System.out.print(first+" "+second);
for(int i=1;i<=n-2;i++)
{
third=first+second;
System.out.print(" "+third);
first=second;
second=third;
}
}
}
}
class Main
{
public static void main(String[] args) throws Exception
{
fibonacci f=new fibonacci();
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the no. of 'fibonacci no.s' u want: ");
int n=Integer.parseInt(b.readLine());
f.getfibo(n);
}
}
O/P:
Enter the no. of 'fibonacci no.s' u want:
7
0 1 1 2 3 5 8

3. REVERSING A STRING:
import java.io.*;
class Reverse
{
private String str;
public Reverse(String s)
{
str=s;
}
public void stringRev()
{
for(int i=str.length()-1;i>=0;i--)
{
System.out.print(str.charAt(i));
}
}
}
public class Main
{
public static void main(String[] args) throws Exception
{
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the string:");
Reverse s=new Reverse(b.readLine());
s.stringRev();
}
}
O/P:
Enter the string:
INFORMATION TECHNOLOGY
YGOLONHCET NOITAMROFNI

4. PALINDROME:

import java.io.*;
class Pallindrome
{
private String str;
public Pallindrome(String s)
{
str=s;
}
public void checkPallindrome()
{
int i, f=0;
for(i=0; i<=str.length()/2;i++)
{
if(str.charAt(i)!=str.charAt(str.length()-i-1))
f=1;
}
if(f==1)
System.out.println("its not a pallindrome");
else
System.out.println("its a pallindrome");
}
}
public class Main
{
public static void main(String[] args) throws Exception
{
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the string:");
Pallindrome p=new Pallindrome(b.readLine());
p.checkPallindrome();
}
}
O/P:
Enter the string:
MALAYALAM
its a pallindrome

5. POLYNOMIAL ADDITION
import java.io.*;
class Link
{
int coef,exp;
Link next;
public Link(int a,int b)
{
coef=a;
exp=b;
}
public void display()
{
System.out.print(" "+coef+"xe "+exp);
}
}
class LinkedList
{
Link p,q,d;
Link first;
public LinkedList()
{
first=null;
}
public void create(int a,int b)
{
Link node=new Link(a,b);
node.next=first;
first=node;
}
public void padd(LinkedList c,LinkedList d)
{
int x;
p=c.first;
q=d.first;
this.d=first;
while((p!=null)&&(q!=null))
{
if(p.exp==q.exp)
{
x=p.coef+q.coef;
if(x!=0)
{
Link node=new Link(x,p.exp);
node.next=this.d;
this.d=node;
}
p=p.next;
q=q.next;
}
else if(p.exp>q.exp)
{
Link node=new Link(p.coef,p.exp);
node.next=this.d;
this.d=node;
p=p.next;
}
else
{
Link node=new Link(q.coef,q.exp);
node.next=this.d;
this.d=node;
q=q.next;
}
}
while(p!=null)
{
Link node=new Link(p.coef,p.exp);
node.next=this.d;
this.d=node;
p=p.next;
}
while(q!=null)
{
Link node=new Link(q.coef,q.exp);
node.next=this.d;
this.d=node;
q=q.next;
}
first=this.d;
}
public void display()
{
Link current=first;
while(current!=null)
{
current.display();
if(current.next!=null)
System.out.print("+");
else
System.out.print(" ");
current=current.next;
}
System.out.print(" ");
}
}

public class Main {


public static void main(String[] args) throws Exception {
int l=0,n,x,y;
System.out.print("Polynomial Addition");
LinkedList a=new LinkedList();
LinkedList b=new LinkedList();
LinkedList c=new LinkedList();
BufferedReader b1=new BufferedReader(new InputStreamReader(System.in));
for(int j=1;j<=2;j++)
{
System.out.print("\nEnter "+j+" polynomial");
System.out.print("\nEnter no. of terms:");
n=Integer.parseInt(b1.readLine());
for(int i=n;i>0;i--)
{
System.out.print("\nEnter the coeff and exponent of "+i+"term:");
x=Integer.parseInt(b1.readLine());
y=Integer.parseInt(b1.readLine());
if(j==1)
a.create(x,y);
else
b.create(x,y);
}
}
System.out.print("\nFirst polynomial is:");
a.display();
System.out.print("Second polynomial is:");
b.display();
c.padd(a,b);
System.out.print("Sym of polynomial is:");
c.display();
}

O/P:
Polynomial Addition
Enter 1 polynomial
Enter no. of terms:3
Enter the coeff and exponent of 3term:4
3

Enter the coeff and exponent of 2term:3


2

Enter the coeff and exponent of 1term:9


0

Enter 2 polynomial
Enter no. of terms:2

Enter the coeff and exponent of 2term:1


2

Enter the coeff and exponent of 1term:1


0

First polynomial is: 9xe 0+ 3xe 2+ 4xe 3 Second polynomial is: 1xe 0+ 1xe 2 Sym of
polynomial is: 4xe 3+ 4xe 2+ 10xe 0

6. SPARSE MATRIX:
import java.io.*;
class node
{
int data;
int row;
int column;
node next;
node prev;

public node(int d,int r,int c)


{
data=d;
row=r;
column=c;
}
}
class LinkedList
{

private node first;


private node current;
public boolean isEmpty()
{
return(first==null);
}
public void insert(int x,int y,int z)
{
node newnode=new node(x,y,z);
if(isEmpty())
{first=newnode;
current=newnode;}
else
{ current.next=newnode;
current=newnode;}
}
public void display()
{
while(first!=null)
{ System.out.println("The term is "+first.data+" in row "+first.row+" and column
"+first.column);
first=first.next;}
}
}
class Main
{

public static void main(String args[])throws IOException


{
LinkedList o=new LinkedList();
int m,n,i,j;
int a[][]=new int[10][10];
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the no of rows and column");
m=Integer.parseInt(b.readLine());
n=Integer.parseInt(b.readLine());
System.out.println("Enter the matrix terms");
for(i=0;i<m;i++)
{ for(j=0;j<n;j++)
{ a[i][j]=Integer.parseInt(b.readLine());
}}
for(i=0;i<m;i++)
{ for(j=0;j<n;j++)
{
if(a[i][j]!=0)
o.insert(a[i][j], i+1, j+1);
}
}
o.display();
}

}
O/P:
Enter the no of rows and column
3
3
Enter the matrix terms
0
0
7
0
2
0
5
0
6
The term is 7 in row 1 and column 3
The term is 2 in row 2 and column 2
The term is 5 in row 3 and column 1
The term is 6 in row 3 and column 3

7. STACK APPLICATION: (CONCATENATION OF


2 STRINGS):
import java.io.*;
class stack
{
private int maxSize;
private char [] stackArray;
private int top;
public stack(int s)
{
maxSize = s;
stackArray = new char[maxSize];
top = -1;
}
public void push(char j)
{
stackArray[++top] = j;
}
public char pop()
{
return stackArray[top--];
}
public char peek()
{
return stackArray[top];
}
public boolean isEmpty()
{
return (top == -1);
}
public boolean isFull()
{
return (top == maxSize - 1);
}
}
class concatstack
{
public static void main(String[]arg)throws Exception
{
String str1,str2,str3="";
int i; char k;
BufferedReader b= new BufferedReader(new
InputStreamReader(System.in));
System.out.println("enter the first string");
str1=b.readLine();
System.out.println("enter the second string");
str2=b.readLine();
stack s1= new stack(str1.length());
stack s2= new stack(str2.length());
stack s3= new stack(str1.length()+str2.length());
for(i=0;i<str1.length();i++)
s1.push(str1.charAt(i));
for(i=0;i<str2.length();i++)
s2.push(str2.charAt(i));
while(!s2.isEmpty())
{
k=s2.pop();
s3.push(k);
}
while(!s1.isEmpty())
{
k=s1.pop();
s3.push(k);
}
while(!s3.isEmpty())
str3+= s3.pop();
System.out.println("concatenated string is:");
System.out.print(str3);
}
}
O/P:
enter the first string
abcdef
enter the second string
ghijkl
concatenated string is:
abcdefghijkl

8. INFIX TO POSTFIX:
import java.io.*;
class stack
{
private int maxsize;
private char[]stackarray;
private int top;
public stack(int s)
{
maxsize=s;
stackarray = new char[maxsize];
top=-1;
}
public void push(char j)
{
stackarray[++top]=j;
}
public char pop()
{
return stackarray[top--];
}
public char peek()
{
return stackarray[top];
}
public boolean isEmpty()
{
return top==-1;
}
}
class postevaln
{
public static void main(String[]args)throws Exception
{
int i,c=0;
String str,str2="";
char k,j;
k='+';
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the infix exp");
str=b.readLine();
stack s1=new stack(str.length());
for (i=0;i<str.length();i++)
{
if(!s1.isEmpty())
k=s1.peek();
switch(str.charAt(i))
{
default:str2+=str.charAt(i);
break;
case'-':
case'+': if(!(k=='*'||k=='/'))
s1.push(str.charAt(i));
else
{
if(c==0)
{
while((k!='+'&&k!='-
')&&(!s1.isEmpty()))
str2+= s1.pop();
s1.push(str.charAt(i));
}
}break;
case'/':
case'*':s1.push(str.charAt(i));
break;
case'(':c++;
s1.push(str.charAt(i));
break;
case')':while(k!='('&&!s1.isEmpty())
{
str2+=s1.pop();
k=s1.peek();
}
if(!s1.isEmpty())
{
j=s1.pop();
break;
}
}
}
while(!s1.isEmpty())
str2+=s1.pop();
System.out.println(str2);
}
}
O/P:
Enter the infix exp:
a+b*(c+d/(e+f))
Postfix exp:
abcdef+/+*+

9. POSTFIX EVALUATION:
import java.io.*;
class stack
{
private int maxsize;
private double[]stackarray;
private int top;
public stack(int s)
{
maxsize=s;
stackarray = new double[maxsize];
top=-1;
}
public void push(double j)
{
stackarray[++top]=j;
}
public double pop()
{
return stackarray[top--];
}
public double peek()
{
return stackarray[top];
}
public boolean isEmpty()
{
return top==-1;
}
}
class postfix
{
public static void main(String[]args)throws Exception
{
int i;
String str;
char ch;
double res=0,op1,op2,j;
BufferedReader b= new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the postfix expression");
str= b.readLine();
stack s= new stack(str.length());
for(i=0;i<str.length();i++)
{
ch=str.charAt(i);
switch(ch)
{
default: System.out.println("enter the value of"+ch+":");
j=Double.parseDouble(b.readLine());
s.push(j);
break;
case'+': op1=s.pop();
op2=s.pop();
res=op1+op2;
s.push(res);
break;
case'-': op1=s.pop();
op2=s.pop();
res=op1-op2;
s.push(res);
break;
case'*': op1=s.pop();
op2=s.pop();
res=op1*op2;
s.push(res);
break;
case'/': op1=s.pop();
op2=s.pop();
res=op1/op2;
s.push(res);
break;
}
}
System.out.println("The value of the exp is:"+res);
}
}

O/P:
Enter the postfix expression
abcdef+/+*+
Enter the value ofa:
6
Enter the value ofb:
5
Enter the value ofc:
4
Enter the value ofd:
3
Enter the value ofe:
2
Enter the value off:
1
The value of the exp is:31.0

10. QUEUE APPLICATION: (CONCATENATION


OF 2 STRINGS) :
package concatqueue;
import java.io.*;
class Queue
{
private int maxSize;
private char[] queArray;
private int front;
private int rear;
private int nItems;
public Queue(int s)
{
maxSize = s;
queArray = new char[maxSize];
front = 0;
rear = -1;
nItems = 0;
}
public void insert(char j)
{
if (rear == maxSize - 1)
rear = -1;
queArray[++rear] = j;
nItems++;
}
public char remove()
{
char temp = queArray[front++];
if (front == maxSize)
front = 0;
nItems--;
return temp;
}
public char peekFront()
{
return queArray[front];
}
public boolean isEmpty()
{
return (nItems == 0);
}
public boolean isFull()
{
return (nItems == maxSize);
}
public int size()
{
return nItems;
}
}
class Main
{
public static void main(String[]args)throws Exception
{
String str1,str2,str3="";
int i;
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the first String");
str1= b.readLine();
System.out.println("Enter the second string");
str2= b.readLine();
Queue q1= new Queue(str1.length()+str2.length());
Queue q2= new Queue(str2.length());
for(i=0;i<str1.length();i++)
q1.insert(str1.charAt(i));
for(i=0;i<str2.length();i++)
q2.insert(str2.charAt(i));
while(!q2.isEmpty())
q1.insert(q2.remove());
while(!q1.isEmpty())
str3+=q1.remove();
System.out.println("Concatenated String");
System.out.print(str3);
}
}
O/P:
Enter the first String
ABCD
Enter the second string
EFGH
Concatenated String
ABCDEFGH

11. DFS:
import java.io.*;
class node
{
public int data;
public node next;
public node previous;
node(int d)
{
data=d;
next=previous=null;
}
}
class stack
{
node start;
node end;
stack()
{
start=end=null;
}
public void push(int d)
{
node newNode=new node(d);
if(start==null)
start=end=newNode;
else
{
newNode.next=start;
start.previous=newNode;
start=newNode;
}
}
public int pop()
{
node current=end;
if(end.previous==null)
end=start=null;
else
end=end.next;

return current.data;
}
public boolean isEmpty()
{
return end==null;
}
public int peek()
{
return start.data;
}
}
class vertex
{
public char label;
public boolean wasVisited;
public vertex(char lab)
{
label=lab;
wasVisited=false;
}
}
class graph
{
private final int max_verts=20;
private vertex vertexList[];
private int adjMat[][];
private int nVerts;
private stack theStack;
public graph()
{
vertexList=new vertex[max_verts];
adjMat=new int[max_verts][max_verts];
nVerts=0;
for(int j=0;j<max_verts;j++)
for(int i=0;i<max_verts;i++)
adjMat[j][i]=0;
theStack=new stack();
}
public void addVertex(char lab)
{
vertexList[nVerts++]=new vertex(lab);
}
public void addEdge(int start, int end)
{
adjMat[start][end]=1;
adjMat[end][start]=1;
}
public int getAdjUnvisitedVertex(int v)
{
for(int i=0;i<nVerts;i++)
if((adjMat[v][i]==1)&&(vertexList[i].wasVisited==false))
return i;
return -1;

}
public void displayVertex(int v)
{
System.out.println(vertexList[v].label);
}
public void dfs()
{
int v2;
vertexList[0].wasVisited=true;
theStack.push(0);
displayVertex(0);
while(!theStack.isEmpty())
{
int v1=theStack.pop();
while(( v2=getAdjUnvisitedVertex(v1))!=-1)
{
vertexList[v2].wasVisited=true;
displayVertex(v2);
theStack.push(v2);
}

}
for(int j=0;j<nVerts;j++)
vertexList[j].wasVisited=false;

}
}
public class Main {

public static void main(String[] args) throws Exception


{
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
graph G=new graph();
String ch;
while(true)
{
System.out.println("Enter the vertex:");
ch=b.readLine();
char c=ch.charAt(0);
G.addVertex(c);
System.out.println("want to enter more(y/n):");
ch=b.readLine();
c=ch.charAt(0);
if(c=='n'||c=='N')
break;

}
while(true)
{
System.out.println("Enter the adjacency:");
System.out.println("Enter the first vertex no.:");
int x=Integer.parseInt(b.readLine());
System.out.println("Enter the adjacent vertex:");
int y=Integer.parseInt(b.readLine());
G.addEdge(x, y);
System.out.println("want to enter more(y/n):");
ch=b.readLine();
char c=ch.charAt(0);
if(c=='n'||c=='N')
break;
}
G.dfs();
}
}

O/P:
Enter the vertex:
A
want to enter more(y/n):

Enter the vertex:


B
want to enter more(y/n):
Y
Enter the vertex:
C
want to enter more(y/n):
Y
Enter the vertex:
D
want to enter more(y/n):
n
Enter the adjacency:
Enter the first vertex no.:
0
Enter the adjacent vertex:
1
want to enter more(y/n):
y
Enter the adjacency:
Enter the first vertex no.:
1
Enter the adjacent vertex:
3
want to enter more(y/n):
y
Enter the adjacency:
Enter the first vertex no.:
0
Enter the adjacent vertex:
2
want to enter more(y/n):
n

A
B
C
D

12. BFS:
import java.io.*;
class node
{
public int data;
public node next;
public node previous;
node(int d)
{
data=d;
next=previous=null;
}
}
class queue
{
node start;
node end;
queue()
{
start=end=null;
}
public void push(int d)
{
node newNode=new node(d);
if(start==null)
start=end=newNode;
else
{
newNode.next=start;
start.previous=newNode;
start=newNode;
}

}
public int pop()
{
node current=end;
if(end.previous==null)
end=start=null;
else
end=end.next;
return current.data;
}
public boolean isEmpty()
{
return end==null;
}
public int peek()
{
return start.data;
}
}
class vertex
{
public char label;
public boolean wasVisited;
public vertex(char lab)
{
label=lab;
wasVisited=false;
}
}
class graph
{
private final int max_verts=20;
private vertex vertexList[];
private int adjMat[][];
private int nVerts;
private queue theQueue;
public graph()
{
vertexList=new vertex[max_verts];
adjMat=new int[max_verts][max_verts];
nVerts=0;
for(int j=0;j<max_verts;j++)
for(int i=0;i<max_verts;i++)
adjMat[j][i]=0;
theQueue=new queue();
}
public void addVertex(char lab)
{
vertexList[nVerts++]=new vertex(lab);
}
public void addEdge(int start, int end)
{
adjMat[start][end]=1;
adjMat[end][start]=1;
}
public int getAdjUnvisitedVertex(int v)
{
for(int i=0;i<nVerts;i++)
if((adjMat[v][i]==1)&&(vertexList[i].wasVisited==false))
return i;
return -1;

}
public void displayVertex(int v)
{
System.out.println(vertexList[v].label);
}
public void dfs()
{
int v2;
vertexList[0].wasVisited=true;
theQueue.push(0);
displayVertex(0);
while(!theQueue.isEmpty())
{
int v1=theQueue.pop();
while(( v2=getAdjUnvisitedVertex(v1))!=-1)
{
vertexList[v2].wasVisited=true;
displayVertex(v2);
theQueue.push(v2);
}
}
for(int j=0;j<nVerts;j++)
vertexList[j].wasVisited=false;

}
}
public class Main {
public static void main(String[] args) throws Exception
{
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
graph G=new graph();
String ch;
while(true)
{
System.out.println("Enter the vertex:");
ch=b.readLine();
char c=ch.charAt(0);
G.addVertex(c);
System.out.println("want to enter more(y/n):");
ch=b.readLine();
c=ch.charAt(0);
if(c=='n'||c=='N')
break;

}
while(true)
{
System.out.println("Enter the adjacency:");
System.out.println("Enter the first vertex no.:");
int x=Integer.parseInt(b.readLine());
System.out.println("Enter the adjacent vertex:");
int y=Integer.parseInt(b.readLine());
G.addEdge(x, y);
System.out.println("want to enter more(y/n):");
ch=b.readLine();
char c=ch.charAt(0);
if(c=='n'||c=='N')
break;
}
G.dfs();
}
}

O/P:
Enter the vertex:a
want to enter more(y/n):y
Enter the vertex:b
want to enter more(y/n):y
Enter the vertex:c
want to enter more(y/n):y
Enter the vertex:d
want to enter more(y/n):n
Enter the adjacency:
Enter the first vertex no.:0
Enter the adjacent vertex:1
want to enter more(y/n):y
Enter the adjacency:
Enter the first vertex no.:1
Enter the adjacent vertex:2
want to enter more(y/n):y
Enter the adjacency:
Enter the first vertex no.:0
Enter the adjacent vertex:3
want to enter more(y/n):y
Enter the adjacency:
Enter the first vertex no.:3
Enter the adjacent vertex:1
want to enter more(y/n):n
a
b
d
c

13. QUICKSORT:

import java.io.*;
class quickSort
{
public int theArray[];
quickSort(int s)
{
theArray=new int[s];
}

public int partition(int left, int right, long pivot)


{
int leftPtr=left-1;
int rightPtr=right+1;
while(true)
{
while(theArray[++leftPtr]<pivot&&leftPtr<rightPtr);
while(theArray[--rightPtr]>pivot&&rightPtr>leftPtr);
if(leftPtr>=rightPtr)
break;
else
{
int temp;
temp=leftPtr;
leftPtr=rightPtr;
rightPtr=temp;
}

}
return leftPtr;

}
public void recQuickSort(int left, int right)
{
if(right-left<=0)
return;
else
{
int pivot=theArray[right];
int partition=partition(left, right, pivot);
recQuickSort(left,partition-1);
recQuickSort(partition+1, right);
}
}

}
public class Main {
public static void main(String[] args) throws Exception
{
int k;
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the size of array:");
k=Integer.parseInt(b.readLine());
quickSort a=new quickSort(k);
System.out.println("enter the array:");
for(int i=0;i<k;i++)
{
a.theArray[i]=Integer.parseInt(b.readLine());
}
a.recQuickSort(0, k-1);
for(int i=0;i<k;i++)
System.out.print(a.theArray[i]+" ");
}

O/P:
Enter the size of array:
5
Enter the array:
7
4
9
6
3
Sorted array:
3 4 6 7 9

14. HEAPSORT:

import java.io.*;
class Node
{
int idata;
Node lchild;
Node rchild;
public Node(int i)
{
idata=i;
lchild = null;
rchild=null;
}
}
class Heap
{
int heapsize;
Heap(int n)
{
heapsize=n;
}
void Max_Heapify(int A[],int i)
{
int r=0,l=0;
int largest;
l = left(i);
r=right(i);
if(l!=-1)
{
if(l<heapsize&&A[l]>A[i])
largest=l;
else
largest=i;
if(r<heapsize&&A[r]>A[largest])
largest=r;
if(largest!=i&&largest<heapsize)
{
swap(A,i,largest);
Max_Heapify(A,largest);
}}
}
int right(int i)
{
if((left(i)+1)>(2*i))
return (left(i)+1);
return -1;
}
int left(int i)
{
if(heapsize>((2*i)+1))
return((2*i)+1);
return -1;
}

void swap(int A[],int dex1,int dex2)


{
if(dex1<A.length&&dex2<A.length)
{
int temp=A[dex1];
A[dex1]=A[dex2];
A[dex2]=temp;
}}

void Build_MaxHeap(int A[])


{
heapsize=A.length;
for(int j=(A.length/2);j>=0;j--)
Max_Heapify(A,j);
}

void Heap_Sort(int A[])


{

Build_MaxHeap(A);
for(int j=A.length-1;j>=1;j--)
{
swap(A,0,j);
heapsize=heapsize-1;
Max_Heapify(A,0);
}
}
}
class Main
{
public static void main(String args[]) throws Exception
{
System.out.print("\nEnter the size of the array:");
BufferedReader b= new BufferedReader(new InputStreamReader(System.in));
int size=0;
size=Integer.parseInt(b.readLine());
System.out.print("\nEnter the elements:");
int thearray[]= new int[size];
for(int j=0;j<size;j++)
thearray[j]=Integer.parseInt(b.readLine());
Heap h= new Heap(size);
h.Heap_Sort(thearray);
System.out.print("\nSorted array:");
for(int j=0;j<size;j++)
System.out.print(thearray[j]+" ");
}
}

O/P:
Enter the size of the array:5
Enter the elements:9
3
6
7
4
Original array:9 3 6 7 4
Sorted array:3 4 6 7 9

15. MERGESORT:

import java.io.*;
public class merge
{
public static void main(String args[]) throws Exception
{
int i,n;
BufferedReader b=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the size of array:");
n=Integer.parseInt(b.readLine());
int data[]=new int[n];
System.out.println("Enter the array:");
for(i=0;i<n;i++)
data[i]=Integer.parseInt(b.readLine());
System.out.println("original array:");
for(i=0;i<n;i++)
System.out.println(data[i]+" ");
System.out.println();
mergeSort_srt(data,0,n-1);
System.out.println("The array after sorting:");
for(i=0;i<n;i++)
System.out.print(data[i]+"");
System.out.println();
}
public static void mergeSort_srt(int array[],int lo, int n){
int low = lo;
int high = n;
if (low >= high) {
return;
}

int middle = (low + high) / 2;


mergeSort_srt(array, low, middle);
mergeSort_srt(array, middle + 1, high);
int end_low = middle;
int start_high = middle + 1;
while ((lo <= end_low) && (start_high <= high)) {
if (array[low] < array[start_high]) {
low++;
} else {
int Temp = array[start_high];
for (int k = start_high- 1; k >= low; k--) {
array[k+1] = array[k];
}
array[low] = Temp;
low++;
end_low++;
start_high++;
}
}
}
}

O/P:
Enter the size of array:
5
Enter the array:
5
4
3
2
1
original array:
5 4 3 2 1
The array after sorting:
1 2 3 4 5

16. BINARY SEARCH TREE:


import java.io.*;
{
int idata;
Node leftChild;
Node rightChild;
Node(int id)
{
idata=id;
leftChild=rightChild=null;
}
}
class tree
{
private Node root;
private boolean isLeftChild;
tree()
{
root=null;
}
public Node find(int key)
{
Node current=root;
while(current.idata!=key)
{
if(key<current.idata)
current=current.leftChild;
else
current=current.rightChild;
if(current==null)
return null;
}
return current;
}
public void insert(int id)
{
Node newNode=new Node(id);
if(root==null)
root=newNode;
else
{
Node current=root;
while(current!=null)
{
if(newNode.idata<current.idata)
{

if(current.leftChild==null)
{
current.leftChild=newNode;
break;
}
else
current=current.leftChild;

}
else
{

if(current.rightChild==null)
{
current.rightChild=newNode;
break;
}
else
current=current.rightChild;
}
}
System.out.print("Inorder traversal: ");
inOrder(root);
System.out.print("Preorder traversal: ");
preOrder(root);
System.out.print("Postorder traversal: ");
postOrder(root);
}
}
public boolean delete(int key)
{
Node current= root;
Node parent= root;
while(current.idata!=key)
{
parent= current;
if(key<current.idata)
{
isLeftChild=true;
current=current.leftChild;
}
else
{
isLeftChild=false;
current=current.rightChild;
}
if(current==null)
return false;
}
if(current.leftChild==null&&current.rightChild==null)
{
if(current==root)
root=null;
else if(isLeftChild)
parent.leftChild=null;
else
parent.rightChild=null;

}
else if(current.rightChild==null)
{
if(current==root)
root=current.leftChild;
else if(isLeftChild)
parent.leftChild=current.leftChild;
else
parent.rightChild=current.leftChild;
}
else if(current.leftChild==null)
{
if(current==root)
root=current.rightChild;
else if(isLeftChild)
parent.leftChild=current.rightChild;
else
parent.rightChild=current.rightChild;
}
else
{
Node successor=getSuccessor(current);
parent.rightChild=successor;
successor.leftChild=current.leftChild;
}
System.out.print("Inorder traversal: ");
inOrder(root);
System.out.print("Preorder traversal: ");
preOrder(root);
System.out.print("Postorder traversal: ");
postOrder(root);
return true;
}
public Node getSuccessor(Node delNode)
{
Node successorParent=delNode;
Node successor=delNode;
Node current=delNode.rightChild;
while(current!=null)
{
successorParent=successor;
successor=current;
current=current.leftChild;
}
if(successor!=delNode.rightChild)
{
successorParent.leftChild=successor.rightChild;
successor.rightChild=delNode.rightChild;
}
return successor;
}
public void inOrder(Node localRoot)
{

if(localRoot!=null)
{
inOrder(localRoot.leftChild);
System.out.print(localRoot.idata+" ");
inOrder(localRoot.rightChild);
}
}
public void preOrder(Node localRoot ){
if(localRoot!=null)
{
System.out.print(localRoot.idata+" ");
inOrder(localRoot.leftChild);
inOrder(localRoot.rightChild);
}
}
public void postOrder(Node localRoot){
if(localRoot!=null)
{
inOrder(localRoot.leftChild);
inOrder(localRoot.rightChild);
System.out.print(localRoot.idata+" ");
}
}

}
public class Main {
public static void main(String[] args)throws Exception
{
boolean f;
int k;
String str;
char ch;
tree mytree= new tree();
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
while(true)
{
System.out.println("enter the node:");
k=Integer.parseInt(b.readLine());
mytree.insert(k);
System.out.println("want to enter more:(y/n)");
str=b.readLine();
ch=str.charAt(0);
if(ch=='n'||ch=='N')
break;
}
System.out.println("enter the element to be deleted:");
k=Integer.parseInt(b.readLine());
f=mytree.delete(k);
if(f)
System.out.println("deleted");
else
System.out.println("element not found!!!");
}
}

O/P:
enter the node:
8
want to enter more:(y/n)
y
enter the node:
12
Inorder traversal: 8 12 Preorder traversal: 8 12 Postorder traversal: 12 8 want to enter
more:(y/n)
y
enter the node:
3
Inorder traversal: 3 8 12 Preorder traversal: 8 3 12 Postorder traversal: 3 12 8 want to enter
more:(y/n)
y
enter the node:
100
Inorder traversal: 3 8 12 100 Preorder traversal: 8 3 12 100 Postorder traversal: 3 12 100 8
want to enter more:(y/n)
y
enter the node:
9
Inorder traversal: 3 8 9 12 100 Preorder traversal: 8 3 9 12 100 Postorder traversal: 3 9 12
100 8 want to enter more:(y/n)
n
enter the element to be deleted:
12
Inorder traversal: 3 8 9 100 Preorder traversal: 8 3 9 100 Postorder traversal: 3 9 100 8
deleted

17. DIJIKSTRA’S(SHORTEST PATH


ALGORITHM) :

package dijikstra;
import java.io.*;
class DistPar
{
public int distance;
public int parentVert;
public DistPar(int pv, int d)
{
distance = d;
parentVert = pv;
}
}

class Vertex
{
public char label;
public boolean isInTree;
public Vertex(char lab)
{
label = lab;
isInTree = false;
}

class Graph
{
private final int MAX_VERTS = 20;
private final int INFINITY = 1000000;
private Vertex vertexList[];
private int adjMat[][];
private int nVerts;
private int nTree;
private DistPar sPath[];
private int currentVert;
private int startToCurrent;

public Graph()
{
vertexList = new Vertex[MAX_VERTS];

adjMat = new int[MAX_VERTS][MAX_VERTS];


nVerts = 0;
nTree = 0;
for(int j=0; j<MAX_VERTS; j++)
for(int k=0; k<MAX_VERTS; k++)
adjMat[j][k] = INFINITY;
sPath = new DistPar[MAX_VERTS];
}

public void addVertex(char lab)


{
vertexList[nVerts++] = new Vertex(lab);
}

public void addEdge(int start, int end, int weight)


{
adjMat[start][end] = weight;
}

public void path()


{
int startTree = 0;
vertexList[startTree].isInTree = true;
nTree = 1;
for(int j=0; j<nVerts; j++)
{

int tempDist = adjMat[startTree][j];


sPath[j] = new DistPar(startTree, tempDist);
}

while(nTree < nVerts)


{
int indexMin = getMin();
int minDist = sPath[indexMin].distance;
if(minDist == INFINITY)
{
System.out.println("There are unreachable vertices");
break;
}
else
{
currentVert = indexMin;
startToCurrent = sPath[indexMin].distance;
}
vertexList[currentVert].isInTree = true;
nTree++;
adjust_sPath();
}
displayPaths();
nTree = 0;
for(int j=0; j<nVerts; j++)
vertexList[j].isInTree = false;
}

public int getMin()


{
int minDist = INFINITY;
int indexMin = 0;
for(int j=1; j<nVerts; j++)
{
if( !vertexList[j].isInTree &&
sPath[j].distance < minDist )
{
minDist = sPath[j].distance;
indexMin = j;
}
}
return indexMin;
}
public void adjust_sPath()
{

int column = 1;
while(column < nVerts)
{
if( vertexList[column].isInTree )
{
column++;
continue;
}

int currentToFringe = adjMat[currentVert][column];


int startToFringe = startToCurrent + currentToFringe;
int sPathDist = sPath[column].distance;
if(startToFringe < sPathDist)
{
sPath[column].parentVert = currentVert;
sPath[column].distance = startToFringe;
}
column++;
}
}
public void displayPaths()
{
for(int j=0; j<nVerts; j++)
{
System.out.print(vertexList[j].label + "=");
if(sPath[j].distance == INFINITY)
System.out.print("inf");
else
System.out.print(sPath[j].distance);
char parent = vertexList[ sPath[j].parentVert ].label;
System.out.print("(" + parent + ") ");
}
System.out.println("");
}
}
class Main
{
public static void main(String[] args) throws Exception
{
Graph theGraph = new Graph();
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
int v,e,f,l,w;
System.out.print("\nEnter the no. of vertices and edges:");
v=Integer.parseInt(b.readLine());
e=Integer.parseInt(b.readLine());
System.out.print("\nEnter the vertices:");
for(int i=0;i<v;i++)
theGraph.addVertex(b.readLine().charAt(0));
System.out.print("\nEnter the edges and its weight:");
for(int i=0;i<e;i++)
{
f=Integer.parseInt(b.readLine());
l=Integer.parseInt(b.readLine());
w=Integer.parseInt(b.readLine());
theGraph.addEdge(f,l,w);
}
System.out.println("Shortest paths");
theGraph.path();
System.out.println();
}
}

O/P:
Enter the no. of vertices and edges:4
4
Enter the vertices:a
b
c
d
Enter the edges and its weight:
1 2 5
2 3 2
1 4 1
4 2 3
Shortest paths
There are unreachable vertices
a=inf(a) b=inf(a) c=inf(a) d=inf(a)
18. KRUSKAL’S (SPANNING TREE
ALGORITHM):

import java.io.*;
class Main
{
public static BufferedReader br =new BufferedReader(new
InputStreamReader(System.in));

static int [][] G;


static int [][] t;
static boolean [][] in;
static boolean [][] temp;

static int n;
static int mincost = 0;
static int k, l, num_ed=0;

public static void main (String[] args) throws IOException


{
System.out.println("\t\t\t\tKruskal's Algorithm");
System.out.print("\nEnter the number of the vertices: ");
n = Integer.parseInt(br.readLine());

G = new int[n+1][n+1];
in = new boolean[n+1][n+1];
t = new int[n+1][3];

System.out.print("\nIf edge between the following vertices enter its cost (not
more than 7000) else 0:\n");
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{
in[i][j] = in[j][i] = false;
if((i!=j)&&(i<j))
{
System.out.print(i+" and "+j+": ");
G[j][i] = G[i][j] = Integer.parseInt(br.readLine());
if(G[i][j] == 0 )
G[j][i] = G[i][j] = 7001;
}
if(i==j)
G[i][j]=7001;
}

System.out.println("\n\nSolution : \n\n");
Kruskals();
System.out.println("\n\n\n\ncost incured is: "+ mincost);
}

static void Kruskals()


{
for (int i = 1; i<=n; i++)
{
getMinKL();
if(k==l)
break;
System.out.print(l + "-" +k);
if(formscycle(i-1))
{
System.out.println(" --> Forms cycle, hence rejected!");
i--;
continue;
}
else
System.out.println();

mincost = mincost + G[k][l];


num_ed = (isPresent(i, k))?num_ed:num_ed+1;
num_ed = (isPresent(i, l))?num_ed:num_ed+1;

t[i][1] = l;
t[i][2] = k;
if(num_ed >= n)
{
if(allconnect(i)) //not a forest
return;
}

}
System.out.println("\nNo Solution Available!");
}

static boolean allconnect(int i)


{
for(int c=2;c<=n;c++)
{
temp = new boolean[n+1][n+1];
for(int a=1;a<=n;a++)
for(int b=1;b<=n;b++)
temp[a][b] = temp[b][a] = false;

if(can_reach(1, c, i) == false)
return false;
}
return true;
}
static boolean formscycle(int i)
{
if(isPresent(i, k) && isPresent(i, l))
{
temp = new boolean[n+1][n+1];
for(int a=1;a<=n;a++)
for(int b=1;b<=n;b++)
temp[a][b] = temp[b][a] = false;

if(can_reach(k, l, i) )
return true;
}
return false;
}

static boolean can_reach(int k, int l, int i)


{
temp[k][l] = temp[l][k] = true;
for(int o=1; o<=i; o++)
{
if(((k == t[o][1]) && (l == t[o][2])) || ((l == t[o][1]) && (k ==
t[o][2])))
return true;
if((k == t[o][1]) && !(temp[t[o][2]][l]) )
{
if(can_reach(t[o][2], l, i) == true)
return true;
}
else if((k == t[o][2]) && !(temp[t[o][1]][l]))
{
if(can_reach(t[o][1], l, i) == true)
return true;
}
}
return false;
}

static boolean isPresent(int i, int val)


{
for(int o=1; o<=i; o++)
if((val == t[o][1]) || ((val == t[o][2]) ))
return true;
return false;
}

static void getMinKL()


{
int k1 = 1, l1 = 1;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{
if((i!=j)&&(i<j))
{
if((G[i][j] < G[k1][l1]) && G[i][j] !=0 &&
in[j][i]==false)
{
k1 = i;
l1 = j;
}
}
}
if(G[k1][l1] !=0 )
{
k =k1; l=l1;
in[k][l] = in[l][k] = true;
}
}
}

O/P:
Enter the number of the vertices: 4
If edge between the following vertices enter its weight (not more than 7000) else 0:
1 and 2: 5
1 and 3: 0
1 and 4: 1
2 and 3: 2
2 and 4: 0
3 and 4: 3
Solution :
4-1
3-2
4-3
weight incured is: 6
19. PRIMS (SPANNING TREE ALGORITHM):

import java.io.*;
class Main
{
public static BufferedReader br =new BufferedReader(new
InputStreamReader(System.in)); static int [][] G;
static int [][] t;
static int [] near;
static int n;
static int mincost = 0;
static int k, l;

public static void main (String[] args) throws IOException


{
System.out.println("\t\t\t\tImplementation of Prim's Algorithm");

System.out.print("\nEnter the number of the vertices: ");


n = Integer.parseInt(br.readLine());

G = new int[n+1][n+1];
t = new int[n+1][3];

near = new int[n+1];

System.out.print("\nIf edge between the following vertices enter its cost (not more than
7000) else 0:\n");
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{
if((i!=j)&&(i<j))
{
System.out.print(i+" and "+j+": ");
G[j][i] = G[i][j] = Integer.parseInt(br.readLine());
if(G[i][j] == 0 )
G[j][i] = G[i][j] = 7001;
}
if(i==j)
G[i][j]=7001;
}
prims();
System.out.println("\n\nSolution : \n\n");

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


{
if( (t[i][1]!=0) && (t[i][2] !=0) )
System.out.println(t[i][1] + "-" +t[i][2]);
}
System.out.println("\n\n\n\n Minimum is "+ mincost);
}

static void prims()


{
getMinKL();
mincost = G[k][l];
t[1][1] = l;
t[1][2] = k;
for(int i=1; i<=n; i++)
near[i] = (G[i][l]<G[i][k])?l:k;
near[k] = near[l] = 0;
for(int i=2; i<n; i++)
{
int j = getMin();
t[i][1] = j; t[i][2] = near[j];
mincost = mincost+G[j][near[j]];
near[j] =0;
for (int k=1; k<=n; k++)
if( (near[k] !=0) && G[k][ near[k] ]> G[k][j] )
near[k] =j;
}
}

static int getMin()


{
int j=1;
for(int i=1;i<=n;i++)
if(near[i] !=0)
{
j = i;
break;
}

for(int i=1;i<=n;i++)
if(near[i] !=0)
if(G[j][near[j]]> G[i][near[i]])
j =i;
return j;
}
static void getMinKL()
{
int k1 = 1, l1 = 2;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{
if((i!=j)&&(i<j))
{
if((G[i][j] < G[k1][l1]) && G[i][j] !=0 )
{
k1 = i;
l1 = j;
}
}
}
if(G[k1][l1] !=0 )
{
k =k1; l=l1;
}
}
}

O/P:
Enter the number of the vertices: 4
If edge between the following vertices enter its cost (not more than 7000) else 0:
1 and 2: 5
1 and 3: 0
1 and 4: 1
2 and 3: 2
2 and 4: 0
3 and 4: 3
Solution :
4-1
3-4
2-3
Minimum is 6
20. COUNTING SORT:
import java.io.*;
class Main
{
public static int s;
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the number of elements");
s=Integer.parseInt(br.readLine());
int array[]=new int[s+1];
System.out.println("enter elements");
for(int i=1; i<=s; i++)
{
array[i]=Integer.parseInt(br.readLine());
}
System.out.println("input array");
for(int i=1;i<=s;i++)
System.out.print(array[i]+" ");
System.out.println();
int max=array[1];
for(int j=1;j<=s;j++)
{
if(array[j]>=max)
max=array[j];
}
int B[]=new int[s+1];
int k=max;
csort(array,B,k);
for(int i=1;i<=s;i++)
System.out.print(B[i]+" ");
}
public static void csort(int A[],int B[], int k)
{

int C[]=new int[k+1];


for(int i=0;i<k+1;i++)
C[i]=0;
for(int j=1;j<=s;j++)
C[A[j]]=C[A[j]]+1;
for(int i=1;i<=k;i++)
C[i]=C[i]+C[i-1];
for(int i=s;i>=1;i--)
{
B[C[A[i]]]=A[i];
C[A[i]]=C[A[i]]-1;
}
}}

O/P:
Enter the number of elements
5
Enter elements
7
2
9
6
4
input array
7 2 9 6 4
2 4 6 7 9

Você também pode gostar