0% found this document useful (0 votes)
107 views15 pages

Merge Sort Using Divide and Conquer

The document discusses several algorithms: 1. Merge sort uses divide and conquer. It divides an array into halves, recursively sorts each half, and then merges the sorted halves into a single sorted array. 2. Binary search also uses divide and conquer to search for a target value in a sorted array. It repeatedly divides the search space in half and ignores halves that cannot contain the target. 3. Prim's algorithm finds the minimum spanning tree of a connected, undirected graph. It uses a greedy approach of building the spanning tree one edge at a time, always adding the lowest-cost edge that avoids cycles. 4. The 0-1 knapsack problem uses dynamic programming to determine

Uploaded by

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

Merge Sort Using Divide and Conquer

The document discusses several algorithms: 1. Merge sort uses divide and conquer. It divides an array into halves, recursively sorts each half, and then merges the sorted halves into a single sorted array. 2. Binary search also uses divide and conquer to search for a target value in a sorted array. It repeatedly divides the search space in half and ignores halves that cannot contain the target. 3. Prim's algorithm finds the minimum spanning tree of a connected, undirected graph. It uses a greedy approach of building the spanning tree one edge at a time, always adding the lowest-cost edge that avoids cycles. 4. The 0-1 knapsack problem uses dynamic programming to determine

Uploaded by

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

Merge sort using divide and conquer

/* Java program for Merge Sort */


class MergeSort
{
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;

/* Create temp arrays */


int L[] = new int [n1];
int R[] = new int [n2];

/*Copy data to temp arrays*/


for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];

/* Merge the temp arrays */

// Initial indexes of first and second subarrays


int i = 0, j = 0;

// Initial index of merged subarry array


int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}

/* Copy remaining elements of L[] if any */


while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}

/* Copy remaining elements of R[] if any */


while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}

// Main function that sorts arr[l..r] using


// merge()
void sort(int arr[], int l, int r)
{
if (l < r)
{
// Find the middle point
int m = (l+r)/2;

// Sort first and second halves


sort(arr, l, m);
sort(arr , m+1, r);

// Merge the sorted halves


merge(arr, l, m, r);
}
}

/* A utility function to print array of size n */


static void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}

// Driver method
public static void main(String args[])
{
int arr[] = {12, 11, 13, 5, 6, 7};

System.out.println("Given Array");
printArray(arr);

MergeSort ob = new MergeSort();


ob.sort(arr, 0, arr.length-1);

System.out.println("\nSorted array");
printArray(arr);
}
}

Binary search using divide and conquer

// Java implementation of iterative Binary Search


class BinarySearch {
// Returns index of x if it is present in arr[],
// else return -1
int binarySearch(int arr[], int x)
{
int l = 0, r = arr.length - 1;
while (l <= r) {
int m = l + (r - l) / 2;

// Check if x is present at mid


if (arr[m] == x)
return m;

// If x greater, ignore left half


if (arr[m] < x)
l = m + 1;

// If x is smaller, ignore right half


else
r = m - 1;
}

// if we reach here, then element was


// not present
return -1;
}

// Driver method to test above


public static void main(String args[])
{
BinarySearch ob = new BinarySearch();
int arr[] = { 2, 3, 4, 10, 40 };
int n = arr.length;
int x = 10;
int result = ob.binarySearch(arr, x);
if (result == -1)
System.out.println("Element not present");
else
System.out.println("Element found at "
+ "index " + result);
}
}

Prim's algorithm using greedy method


https://codispatch.blogspot.com/2015/12/java-program-implement-prims-minimum-spanning-
tree-algorithm.html

import java.util.*;

public class Prims

public int isVisited[] = new int[15];

public int cost[][] = new int[10][10];


public int minimum_cost;

public void calc(int n)

int flag[] = new int[n+1];

int i,j,min=999,num_edges=1,a=1,b=1,minpos_i=1,minpos_j=1;

while(num_edges < n)

for(i=1,min=999;i<=n;i++)

for(j=1;j<=n;j++)

if(this.cost[i][j]<min)

if(this.isVisited[i]!=0)

min=this.cost[i][j];

a=minpos_i=i;

b=minpos_j=j;

if(this.isVisited[minpos_i]==0 || this.isVisited[minpos_j]==0)

System.out.println("Edge Number \t"+num_edges+"\t from Vertex


\t"+a+"\t to Vertex \t"+b+"-mincost:"+min+" \n");
this.minimum_cost=this.minimum_cost+min;

num_edges=num_edges+1;

this.isVisited[b]=1;

this.cost[a][b]=this.cost[b][a]=999;

public static void main(String args[])

int nodes,i,j;

Scanner in = new Scanner(System.in);

System.out.println("Enter the Number of Nodes \n");

nodes = in.nextInt();

Prims p = new Prims();

System.out.println("Enter the Cost Matrix Weights : \n");

for(i=1;i<=nodes;i++)

for(j=1;j<=nodes;j++)

{
p.cost[i][j]=in.nextInt();

if(p.cost[i][j]==0)

p.cost[i][j]=999;

p.isVisited[1]=1; // Initialization

p.calc(nodes);

0/1 knapsack problem using dynamic programming


class Knapsack
{

// A utility function that returns maximum of two integers


static int max(int a, int b) { return (a > b)? a : b; }

// Returns the maximum value that can be put in a knapsack of capacity


W
static int knapSack(int W, int wt[], int val[], int n)
{
// Base Case
if (n == 0 || W == 0)
return 0;

// If weight of the nth item is more than Knapsack capacity W, then


// this item cannot be included in the optimal solution
if (wt[n-1] > W)
return knapSack(W, wt, val, n-1);

// Return the maximum of two cases:


// (1) nth item included
// (2) not included
else return max( val[n-1] + knapSack(W-wt[n-1], wt, val, n-1),
knapSack(W, wt, val, n-1)
);
}

// Driver program to test above function


public static void main(String args[])
{
int val[] = new int[]{60, 100, 120};
int wt[] = new int[]{10, 20, 30};
int W = 50;
int n = val.length;
System.out.println(knapSack(W, wt, val, n));
}
}
/*This code is contributed by Rajat Mishra */

Depth First Search

/ Java program to print DFS traversal from a given given graph


import java.io.*;
import java.util.*;

// This class represents a directed graph using adjacency list


// representation
class Graph
{
private int V; // No. of vertices

// Array of lists for Adjacency List Representation


private LinkedList<Integer> adj[];

// Constructor
Graph(int v)
{
V = v;
adj = new LinkedList[v];
for (int i=0; i<v; ++i)
adj[i] = new LinkedList();
}

//Function to add an edge into the graph


void addEdge(int v, int w)
{
adj[v].add(w); // Add w to v's list.
}

// A function used by DFS


void DFSUtil(int v,boolean visited[])
{
// Mark the current node as visited and print it
visited[v] = true;
System.out.print(v+" ");

// Recur for all the vertices adjacent to this vertex


Iterator<Integer> i = adj[v].listIterator();
while (i.hasNext())
{
int n = i.next();
if (!visited[n])
DFSUtil(n, visited);
}
}

// The function to do DFS traversal. It uses recursive DFSUtil()


void DFS(int v)
{
// Mark all the vertices as not visited(set as
// false by default in java)
boolean visited[] = new boolean[V];

// Call the recursive helper function to print DFS traversal


DFSUtil(v, visited);
}

public static void main(String args[])


{
Graph g = new Graph(4);

g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);

System.out.println("Following is Depth First Traversal "+


"(starting from vertex 2)");

g.DFS(2);
}
}
// This code is contributed by Aakash Hasija

Cyclic Redundancy Check


import java.util.Scanner;
class CRC
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int m,g[],n,d[],z[],r[],msb,i,j,k;
System.out.print(“Enter no. of data bits : “);
n=sc.nextInt();
System.out.print(“Enter no. of generator bits : “);
m=sc.nextInt();
d=new int[n+m];
g=new int[m];
System.out.print(“Enter data bits : “);
for(i=0;i<n;i++)
d[i]=sc.nextInt();
System.out.print(“Enter generator bits : “);
for(j=0;j<m;j++)
g[j]=sc.nextInt();
for(i=0;i<m-1;i++)
d[n+i]=0;
r=new int[m+n];
for(i=0;i<m;i++)
r[i]=d[i];
z=new int[m];
for(i=0;i<m;i++)
z[i]=0;
for(i=0;i<n;i++)
{
k=0;
msb=r[i];
for(j=i;j<m+i;j++)
{
if(msb==0)
r[j]=xor(r[j],z[k]);
else
r[j]=xor(r[j],g[k]);
k++;
}
r[m+i]=d[m+i];
}
System.out.print(“The code bits added are : “);
for(i=n;i<n+m-1;i++)
{
d[i]=r[i];
System.out.print(d[i]);
}
System.out.print(“\nThe code data is : “);
for(i=0;i<n+m-1;i++)
{
System.out.print(d[i]);
}
}
public static int xor(int x,int y)
{
if(x==y)
return(0);
else
return(1);
}
}

/*Output of crc cyclic redundancy check program:


Enter no. of data bits : 14
Enter no. of generator bits : 4
Enter data bits : 1
1
0
1
0
0
1
1
1
0
1
1
0
0

Enter generator bits :


1
0
1
1

The code bits added are : 100

The code data is : 11010011101100100


*/

Distance vector routing algorithm

http://campuscoke.blogspot.com/2015/01/distance-vector-
routing-dvr-algorithm.html

import java.io.*;
public class DVR
{
static int graph[][];
static int via[][];
static int rt[][];
static int v;
static int e;

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


{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Please enter the number of Vertices: ");


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

System.out.println("Please enter the number of Edges: ");


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

graph = new int[v][v];


via = new int[v][v];
rt = new int[v][v];
for(int i = 0; i < v; i++)
for(int j = 0; j < v; j++)
{
if(i == j)
graph[i][j] = 0;
else
graph[i][j] = 9999;
}

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


{
System.out.println("Please enter data for Edge " + (i + 1) + ":");
System.out.print("Source: ");
int s = Integer.parseInt(br.readLine());
s--;
System.out.print("Destination: ");
int d = Integer.parseInt(br.readLine());
d--;
System.out.print("Cost: ");
int c = Integer.parseInt(br.readLine());
graph[s][d] = c;
graph[d][s] = c;
}

dvr_calc_disp("The initial Routing Tables are: ");

System.out.print("Please enter the Source Node for the edge whose cost has
changed: ");
int s = Integer.parseInt(br.readLine());
s--;
System.out.print("Please enter the Destination Node for the edge whose cost
has changed: ");
int d = Integer.parseInt(br.readLine());
d--;
System.out.print("Please enter the new cost: ");
int c = Integer.parseInt(br.readLine());
graph[s][d] = c;
graph[d][s] = c;

dvr_calc_disp("The new Routing Tables are: ");


}

static void dvr_calc_disp(String message)


{
System.out.println();
init_tables();
update_tables();
System.out.println(message);
print_tables();
System.out.println();
}

static void update_table(int source)


{
for(int i = 0; i < v; i++)
{
if(graph[source][i] != 9999)
{
int dist = graph[source][i];
for(int j = 0; j < v; j++)
{
int inter_dist = rt[i][j];
if(via[i][j] == source)
inter_dist = 9999;
if(dist + inter_dist < rt[source][j])
{
rt[source][j] = dist + inter_dist;
via[source][j] = i;
}
}
}
}
}

static void update_tables()


{
int k = 0;
for(int i = 0; i < 4*v; i++)
{
update_table(k);
k++;
if(k == v)
k = 0;
}
}

static void init_tables()


{
for(int i = 0; i < v; i++)
{
for(int j = 0; j < v; j++)
{
if(i == j)
{
rt[i][j] = 0;
via[i][j] = i;
}
else
{
rt[i][j] = 9999;
via[i][j] = 100;
}
}
}
}

static void print_tables()


{
for(int i = 0; i < v; i++)
{
for(int j = 0; j < v; j++)
{
System.out.print("Dist: " + rt[i][j] + " ");
}
System.out.println();
}
}

}
output:-

Please enter the number of Vertices:


4
Please enter the number of Edges:
5
Please enter data for Edge 1:
Source: 1
Destination: 2
Cost: 1
Please enter data for Edge 2:
Source: 1
Destination: 3
Cost: 3
Please enter data for Edge 3:
Source: 2
Destination: 3
Cost: 1
Please enter data for Edge 4:
Source: 2
Destination: 4
Cost: 1
Please enter data for Edge 5:
Source: 3
Destination: 4
Cost: 4

The initial Routing Tables are:


Dist: 0 Dist: 1 Dist: 2 Dist: 2
Dist: 1 Dist: 0 Dist: 1 Dist: 1
Dist: 2 Dist: 1 Dist: 0 Dist: 2
Dist: 2 Dist: 1 Dist: 2 Dist: 0

Please enter the Source Node for the edge whose cost has changed: 2
Please enter the Destination Node for the edge whose cost has changed: 4
Please enter the new cost: 10

The new Routing Tables are:


Dist: 0 Dist: 1 Dist: 2 Dist: 6
Dist: 1 Dist: 0 Dist: 1 Dist: 5
Dist: 2 Dist: 1 Dist: 0 Dist: 4
Dist: 6 Dist: 5 Dist: 4 Dist: 0
--------------------------------

Dijkstra's algorithm
import java.util.Scanner; //Scanner Function to take in the Input Values

public class Dijkstra


{
static Scanner scan; // scan is a Scanner Object

public static void main(String[] args)


{
int[] preD = new int[5];
int min = 999, nextNode = 0; // min holds the minimum value,
nextNode holds the value for the next node.
scan = new Scanner(System.in);
int[] distance = new int[5]; // the distance matrix
int[][] matrix = new int[5][5]; // the actual matrix
int[] visited = new int[5]; // the visited array

System.out.println("Enter the cost matrix");

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


{
visited[i] = 0; //initialize visited array to zeros
preD[i] = 0;

for (int j = 0; j < distance.length; j++)


{
matrix[i][j] = scan.nextInt(); //fill the matrix
if (matrix[i][j]==0)
matrix[i][j] = 999; // make the zeros as 999
}
}

distance = matrix[0]; //initialize the distance array


visited[0] = 1; //set the source node as visited
distance[0] = 0; //set the distance from source to source to zero
which is the starting point

for (int counter = 0; counter < 5; counter++)


{
min = 999;
for (int i = 0; i < 5; i++)
{
if (min > distance[i] && visited[i]!=1)
{
min = distance[i];
nextNode = i;
}
}

visited[nextNode] = 1;
for (int i = 0; i < 5; i++)
{
if (visited[i]!=1)
{
if (min+matrix[nextNode][i] < distance[i])
{
distance[i] = min+matrix[nextNode][i];
preD[i] = nextNode;
}

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


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

System.out.println("|");

int j;
for (int i = 0; i < 5; i++)
{
if (i!=0)
{

System.out.print("Path = " + i);


j = i;
do
{
j = preD[j];
System.out.print(" <- " + j);
}
while(j != 0);
}
System.out.println();
}
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy