You are on page 1of 17

1) Implement QuickSort using Singly Linked List using Java.

public class QuickSortLinkedList {


static class Node {
int data;
Node next;
Node(int d)
{
this.data = d;
this.next = null;
}
}

Node head;

void addNode(int data)


{
if (head == null) {
head = new Node(data);
return;
}

Node curr = head;


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

Node newNode = new Node(data);


curr.next = newNode;
}

void printList(Node n)
{
while (n != null) {
System.out.print(n.data);
System.out.print(" ");
n = n.next;
}
}

// Takes first and last node, but do not break any links in the whole linked list
Node partitionLast(Node start, Node end)
{
if (start == end || start == null || end == null)
return start;

Node pivot_prev = start;


Node curr = start;
int pivot = end.data;

// iterate till one before the end, no need to iterate till the end because end is
pivot
while (start != end) {
if (start.data < pivot) {
// keep tracks of last modified item
pivot_prev = curr;
int temp = curr.data;
curr.data = start.data;
start.data = temp;
curr = curr.next;
}
start = start.next;
}

// Swap the position of curr i.e.next suitable index and pivot


int temp = curr.data;
curr.data = pivot;
end.data = temp;

// Return one previous to current // because current is now pointing to pivot


return pivot_prev;
}

void sort(Node start, Node end)


{
if (start == null || start == end || start == end.next)
return;

// Split list and partition recurse


Node pivot_prev = partitionLast(start, end);
sort(start, pivot_prev);

// If pivot is picked and moved to the start, that means start and pivot is same
// so pick from next of pivot
if (pivot_prev != null && pivot_prev == start)
sort(pivot_prev.next, end);

// If pivot is in between of the list, start from next of pivot,


// since we have pivot_prev, so we move two nodes
else if (pivot_prev != null && pivot_prev.next != null)
sort(pivot_prev.next.next, end);
}

// Driver's Code
public static void main(String[] args)
{
QuickSortLinkedList list = new QuickSortLinkedList();
list.addNode(30);
list.addNode(3);
list.addNode(4);
list.addNode(20);
list.addNode(5);

Node n = list.head;
while (n.next != null)
n = n.next;

System.out.println("Linked List before sorting");


list.printList(list.head);

// Function call
list.sort(list.head, n);

System.out.println("\nLinked List after sorting");


list.printList(list.head);
}
}
-------------------------------------------------------------------------------------------------------------

2) Write a Java program with following: Merge sort involves recursively splitting the array into
2 parts, sorting and finally merging them. A variant of merge sort is called 3-way merge sort
where instead of splitting the array into 2 parts we split it into 3 parts. Merge sort recursively
breaks down the arrays to subarrays of size half. Similarly, 3-way Merge sort breaks down the
arrays to subarrays of size one third.
Input : 45, -2, -45, 78, 30, -42, 10,19,73,93
Output : -45, -42, -2, 10, 19, 30, 45, 73, 78, 93
Input : 23, -19
Output : -19, 23
Program:
public class test3 {
public static void mergesort3way(Integer[] gArray) {
if(gArray==null)
return;
Integer[] fArray=new Integer[gArray.length];
for(int i=0;i<fArray.length;i++)
fArray[i]=gArray[i];
mergesort3wayrec(fArray,0,gArray.length,gArray);
for(int i=0;i<fArray.length;i++)
gArray[i]=fArray[i];
}
public static void mergesort3wayrec(Integer[] gArray, int low, int high, Integer[]
destArray) {
if(high-low<2)
return;
int mid1= low + ((high-low)/3);
int mid2 = low + 2*((high-low)/3)+1;
mergesort3wayrec(destArray,low,mid1,gArray);
mergesort3wayrec(destArray,mid1,mid2,gArray);
mergesort3wayrec(destArray,mid2,high,gArray);
merge(destArray,low,mid1,mid2,high,gArray);
}
public static void merge(Integer[] gArray, int low, int mid1, int mid2, int high,
Integer[] destArray) {
int i=low, j=mid1, k=mid2, l=low;
while((i<mid1)&& (j<mid2) && (k<high)) {
if(gArray[i].compareTo(gArray[j])<0) {
if(gArray[i].compareTo(gArray[k])<0)
destArray[l++]=gArray[i++];
else
destArray[l++]=gArray[k++];
}
else {
if(gArray[j].compareTo(gArray[k])<0)
destArray[l++]=gArray[j++];
else
destArray[l++]=gArray[k++];
}
}
while((i<mid1)&&(j<mid2)) {
if(gArray[i].compareTo(gArray[j])<0)
destArray[l++]=gArray[i++];
else
destArray[l++]=gArray[j++];
}
while((j<mid2)&&(k<high)) {
if(gArray[j].compareTo(gArray[k])<0)
destArray[l++]=gArray[j++];
else
destArray[l++]=gArray[k++];
}
while((i<mid1)&&(k<high)) {
if(gArray[i].compareTo(gArray[j])<0)
destArray[l++]=gArray[i++];
else
destArray[l++]=gArray[k++];
}
while(i<mid1)
destArray[l++]=gArray[i++];
while(j<mid2)
destArray[l++]=gArray[j++];
while(k<high)
destArray[l++]=gArray[k++];
}
public static void main(String args[]) {
Integer[] data = new Integer[] {45,-2,-45,78,30,-42,10,19, 73, 93};
mergesort3way(data);
System.out.println("After 3 way merge sort: ");
for(int i=0;i<data.length;i++)
System.out.println(data[i]+ " ");

}
}

-----------------------------------------------------------------------------------------

3) Write a program to implement Travelling Sales Person problem using Dynamic


programming.

Algorithm:

Program:
import java.util.*;
public class test9 {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int c[][]=new int[10][10], tour[]=new int[10];
int cost, i,j;
System.out.println("enter no of nodes: ");
int n=sc.nextInt();
if(n==1) {
System.out.println("Path not possible");

}
System.out.println("Enter cost matrix: ");
for(i=1;i<=n;i++) {
for(j=1;j<=n;j++) {
c[i][j]=sc.nextInt();
}
}
for(i=1;i<=n;i++) {
tour[i]=i;
}
cost=tspdp(c,tour, 1,n);
System.out.println("The accurate path is: ");
for(i=1;i<=n;i++) {
System.out.print(tour[i]+"-->");
}
System.out.println("1");
System.out.println("Min cost: "+cost);
}
static int tspdp(int c[][], int tour[], int start, int n) {
int mintour[]=new int[10], temp[]= new int[10];
int mincost=999,ccost,i,j,k;
if(start==n-1)
return (c[tour[n-1]][tour[n]]+c[tour[n]][1]);
for(i=start+1;i<=n;i++) {
for(j=1;j<=n;j++) {
temp[j]=tour[j];
}
temp[start+1]=tour[i];
temp[i]=tour[start+1];
if((c[tour[start]][tour[i]] + (ccost=tspdp(c,temp,start+1,n)))<mincost) {
mincost=c[tour[start]][tour[i]] + ccost;
for(k=1;k<=n;k++)
mintour[k]=temp[k];
}

}
for(i=1;i<=n;i++) {
tour[i]=mintour[i];
}
return mincost;
}
}

-----------------------------------------------------------------------------------

4) Write a program to find shortest path from source to destination using Bellman-ford
algorithm. The graph may contain negative weight edges

Algorithm:

Program:
import java.util.*;
public class test10 {
private int n;
private int distances[];
public static final int MAX_VALUE =999;
public test10(int n) {
this.n=n;
distances =new int[n+1];

}
public void bellmanfordeval(int source, int c[][]) {
for(int node=1;node<=n;node++) {
distances[node]=MAX_VALUE;
}
distances[source]=0;
for(int node=1;node<=n-1;node++) {
for(int sn=1;sn<=n;sn++) {
for(int dn=1;dn<=n;dn++) {
if(c[sn][dn]!=MAX_VALUE) {
if(distances[dn] > distances[sn]+c[sn][dn]) {
distances[dn] = distances[sn]+c[sn][dn];
}
}
}
}
}
for(int sn=1;sn<=n;sn++) {
for(int dn=1;dn<=n;dn++) {
if(c[sn][dn]!=MAX_VALUE) {
if(distances[dn] > distances[sn]+c[sn][dn]) {
System.out.println("The graph contains negative
edge cycle ");
}
}
}
}
for(int vertex=1;vertex<=n;vertex++) {
System.out.println("Distance from source "+ source + "to vertex "+
vertex + " is "+distances[vertex]);
}

}
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int n=0;
int source;
System.out.println("enter no of nodes: ");
n=sc.nextInt();
int c[][]=new int[n+1][n+1];
System.out.println("Enter adjacency matrix: ");
for(int sn=1;sn<=n;sn++) {
for(int dn=1;dn<=n;dn++) {
c[sn][dn]=sc.nextInt();
if(sn==dn)
c[sn][dn]=0;
if(c[sn][dn]==0)
c[sn][dn]=MAX_VALUE;
}
}
System.out.println("enter source vertex: ");
source=sc.nextInt();
test10 bf = new test10(n);
bf.bellmanfordeval(source, c);
sc.close();

}
}

-------------------------------------------------------------------------------------
5) Design and implement in Java to find a subset of a given set S = {Sl, S2,.....,Sn} of n
positive integers whose SUM is equal to a given positive integer d. For example, if S ={1, 2,
5, 6, 8} and d= 9, there are two solutions {1,2,6}and {1,8}. Display a suitable message, if the
given problem instance doesn't have a solution.

Algorithm:
ALGORITHM :
void SumOfSub (float s, int k, float r)
// Find all subsets of w[1:n] that sum to m. The values of x[j], 1<=j<k, have already
// Generate left child. Note that s+w[k] <=m because Bk-1 is true.
x[k] =1;
if (s+w[k] == m)
{// Subset found
for (int j=1; j<=k; j++) Print x[j] ;
}
// There is no recursive call here as w[j] > 0, 1 <= j <= n.
else if (s+w[k]+w[k+1] <= m)
SumOfSub(s+w[k], k+1, r-w[k]);
// Generate right child and evaluate Bk .
if ((s+r-w[k] >= m) && (s+w[k+1] <= m))
{ x[k] = 0;
SumOfSub(s, k+1, r-w[k]);
}
}

Program:
import java.util.*;
public class test11 {
static int c=0;
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int n,d,i,sum=0;
int x[]=new int[10];
int w[]=new int[10];
System.out.println("Enter no of elements: ");
n=sc.nextInt();
System.out.println("enter elements in increasing order: ");
for(i=0;i<n;i++) {
w[i]=sc.nextInt();
}
System.out.println("Enter value of d: ");
d=sc.nextInt();
for(i=0;i<n;i++) {
sum=sum+w[i];
}
System.out.println("sum is: "+sum);
if(sum<d || w[0]>d) {
System.out.println("Path not possible.");
System.exit(0);
}
finalsubset(0,0,sum,x,w,d);
if(c==0) {
System.out.println("Path not possible.");
}
}
static void finalsubset(int cs, int k, int r, int x[], int w[], int d) {
x[k]=1;
if(cs+w[k]==d) {
c++;
System.out.print("\nSolution "+c+ " is {");
for(int i=0;i<=k;i++) {
if(x[i]==1) {
System.out.print(w[i]+" ");
}
}
System.out.print("}");
}
else if(cs+w[k]+w[k+1]<=d) {
finalsubset(cs+w[k],k+1,r-w[k],x,w,d);
}
if(cs+r-w[k]>=d && cs+w[k+1]<=d) {
x[k]=0;
finalsubset(cs,k+1,r-w[k],x,w,d);
}
}

-------------------------------------------------------------------------------------------
6) Design and implement the presence of Hamiltonian Cycle in an undirected Graph G of n
vertices.

Algorithm:
Program:
import java.util.*;
public class test12 {
static int x[]=new int[10];
static void NextVertex(int g[][], int n, int k) {
int j;
while(true) {
x[k]=(x[k]+1)%(n+1);
if(x[k]==0)
return;
if(g[x[k-1]][x[k]]!=0) {
for(j=1;j<=k-1;j++) {
if(x[j]==x[k])
break;

}
if(j==k) {
if((k<n) || ((k==n)&& (g[x[n]][x[1]]!=0)))
return;
}
}
}
}
static void hcycle(int g[][], int n, int k) {
int i;
while(true) {
NextVertex(g,n,k);
if(x[k]==0)
return;
if(k==n) {
System.out.println("\n");
for(i=1;i<=n;i++) {
System.out.print(x[i]+"-->");
}
System.out.println(x[1]);
}
else{
hcycle(g,n,k+1);
}
}
}
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int i,j,n;
int g[][]=new int[10][10];
System.out.println("Enter no of nodes: ");
n=sc.nextInt();
System.out.println("Enter adjacency matrix: ");
for(i=1;i<=n;i++) {
for(j=1;j<=n;j++) {
g[i][j]=sc.nextInt();
x[i]=0;
}
}
x[1]=1;
System.out.println("Hcycles are: ");
hcycle(g,n,2);
}
}

-------------------------------------------------------------------------------------

You might also like