Escolar Documentos
Profissional Documentos
Cultura Documentos
16.Counting Sort
1. SORTING
import java.io.*;
class Array
{
private int[] a;
private int nElems;
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(" ");
}
}
O/P:
Polynomial Addition
Enter 1 polynomial
Enter no. of terms:3
Enter the coeff and exponent of 3term:4
3
Enter 2 polynomial
Enter no. of terms:2
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;
}
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
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
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 {
}
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):
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];
}
}
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;
}
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;
}
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
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&¤t.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
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];
int column = 1;
while(column < nVerts)
{
if( vertexList[column].isInTree )
{
column++;
continue;
}
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 n;
static int mincost = 0;
static int k, l, num_ed=0;
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);
}
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!");
}
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;
}
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;
G = new int[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++)
{
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(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)
{
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