Skip to content

Commit

Permalink
until heap
Browse files Browse the repository at this point in the history
  • Loading branch information
mitibirru committed Jul 10, 2024
0 parents commit 4e38e1b
Show file tree
Hide file tree
Showing 13 changed files with 614 additions and 0 deletions.
67 changes: 67 additions & 0 deletions divide-conquer/Inversioncount.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import java.util.Scanner;;

public class Inversioncount {
private static long count;

// Function to count inversions in the array.
static long inversionCount(long arr[], int n) {
count = 0; // Reset count before starting
mergeSort(arr, 0, n - 1);
return count;
}

// Helper function for merge sort.
private static void mergeSort(long[] arr, int lo, int hi) {
if (lo < hi) {
int mid = lo + (hi - lo) / 2;
mergeSort(arr, lo, mid);
mergeSort(arr, mid + 1, hi);
merge(arr, lo, mid, hi);
}
}

// Function to merge two sorted halves and count inversions.
private static void merge(long[] arr, int lo, int mid, int hi) {
int n1 = mid - lo + 1;
int n2 = hi - mid;

long[] left = new long[n1];
long[] right = new long[n2];

System.arraycopy(arr, lo, left, 0, n1);
System.arraycopy(arr, mid + 1, right, 0, n2);

int i = 0, j = 0, k = lo;

while (i < n1 && j < n2) {
if (left[i] <= right[j]) {
arr[k++] = left[i++];
} else {
arr[k++] = right[j++];
count += (n1 - i); // Count inversions
}
}

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

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

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long[] arr = new long[n];

for (int i = 0; i < n; i++) {
arr[i] = sc.nextLong();
}

inversionCount(arr, n);
System.out.println(count);
sc.close();
}
}
69 changes: 69 additions & 0 deletions divide-conquer/MaximumSubArray.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class MaximumSubArray {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
System.out.print("Enter the number of elements: ");
int n = sc.nextInt();

if (n <= 0) {
System.out.println("The number of elements must be positive.");
return;
}

int[] arr = new int[n];
System.out.println("Enter the elements:");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}

List<Integer> result = findMaximumSubArray(arr);
if (result.isEmpty()) {
System.out.println("No positive subarray found.");
} else {
System.out.println("Maximum subarray:");
for (int num : result) {
System.out.println(num);
}
}
} catch (Exception e) {
System.out.println("Invalid input. Please enter integers only.");
} finally {
sc.close();
}
}

static List<Integer> findMaximumSubArray(int[] arr) {
List<Integer> res = new ArrayList<>();
int currentSum = 0, maxSum = Integer.MIN_VALUE;
int maxStart = -1, maxEnd = -1;
int currentStart = 0;

for (int i = 0; i < arr.length; i++) {
if (arr[i] >= 0) {
currentSum += arr[i];
if (currentSum > maxSum || (currentSum == maxSum && (i - currentStart > maxEnd - maxStart))) {
maxSum = currentSum;
maxStart = currentStart;
maxEnd = i;
}
} else {
currentSum = 0;
currentStart = i + 1;
}
}

if (maxStart == -1 || maxEnd == -1) {
return res; // Return an empty list if no positive subarray is found
}

for (int i = maxStart; i <= maxEnd; i++) {
res.add(arr[i]);
}

return res;
}
}
91 changes: 91 additions & 0 deletions graph/Bipartite.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
package graph;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;

public class Bipartite {
/**
* Function to check if graph is bipartite.
*
* @param v the number of vertices in the graph
* @param adj the adjacency list representing the graph
* @return true if the graph is bipartite, false otherwise
*/

/**
* Helper function to perform BFS and check for bipartiteness.
*
* @param start the source vertex to start BFS
* @param color the array to store colors of vertices
* @param adj the adjacency list representing the graph
* @param n the number of vertices in the graph
* @return true if the component is bipartite, false otherwise
*/
private boolean check(int start, ArrayList<ArrayList<Integer>> adj, int[] color, int n) {
Queue<Integer> q = new LinkedList<>();
q.add(start);
color[start] = 0;

while (!q.isEmpty()) {
int curr = q.poll();

for (int nei : adj.get(curr)) {
// If the neighbor is not colored, color it with the opposite color
if (color[nei] == -1) {
color[nei] = 1 - color[curr];
q.add(nei);
}
// If the neighbor has the same color as the current node, it's not bipartite
else if (color[nei] == color[curr])
return false;
}
}

return true;
}

public boolean isBipartite(int v, ArrayList<ArrayList<Integer>> adj) {
int color[] = new int[v];

Arrays.fill(color, -1); // Initialize all vertices as uncolored

for (int i = 0; i < v; i++) {
if (color[i] == -1) {
// If the vertex is not colored, perform BFS
if (!check(i, adj, color, v))
return false;
}
}

return true;
}

public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine().trim());
while (T-- > 0) {
String[] input = br.readLine().trim().split(" ");
int V = Integer.parseInt(input[0]);
int E = Integer.parseInt(input[1]);
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
for (int i = 0; i < V; i++) {
adj.add(new ArrayList<>());
}
for (int i = 0; i < E; i++) {
String[] edge = br.readLine().trim().split(" ");
int u = Integer.parseInt(edge[0]);
int v = Integer.parseInt(edge[1]);
adj.get(u).add(v);
adj.get(v).add(u);
}
Bipartite obj = new Bipartite();
boolean ans = obj.isBipartite(V, adj);
System.out.println(ans ? "1" : "0");
}
}
}
50 changes: 50 additions & 0 deletions graph/Dijkstras.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package graph;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;

public class Dijkstras {
private int v;
private List<List<Pair>> adj;

Dijkstras(int v) {
this.v = v;

adj = new ArrayList<>();
for (int i = 0; i < v; i++) {
adj.add(new ArrayList<>());
}
}

public int[] shortestPath(int src) {
int[] dist = new int[v];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[src] = 0;

PriorityQueue<Pair> pq = new PriorityQueue<>(v, (a, b) -> a.dist - b.dist); //minheap
pq.add(new Pair(src, 0));

while(!pq.isEmpty()) {
int currNode = pq.poll().node;

for (Pair p : adj.get(currNode)) {
if (dist[p.node] > dist[currNode] + p.dist) {
dist[p.node] = dist[currNode] + p.dist;
pq.add(new Pair(p.node, dist[currNode] + p.dist));
}
}
}
return dist;
}
}

class Pair {
int dist;
int node;

Pair(int node, int dist) {
this.dist = dist;
this.node = node;
}
}
67 changes: 67 additions & 0 deletions graph/IsCycleDirected.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package graph;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

public class IsCycleDirected {
public static void main(String[] args) {
IsCycleDirected solution = new IsCycleDirected();
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();

// Example graph with 4 vertices
int V = 4;
for (int i = 0; i < V; i++) {
adj.add(new ArrayList<>());
}

// Adding edges to the graph
adj.get(0).add(1);
adj.get(1).add(2);
adj.get(2).add(3);
adj.get(3).add(1); // This creates a cycle

boolean hasCycle = solution.isCyclic(V, adj);
System.out.println("Graph has cycle: " + hasCycle);
}

// Function to detect cycle in a directed graph.
public boolean isCyclic(int V, ArrayList<ArrayList<Integer>> adj) {
// Step 1: Calculate in-degree of each vertex
int[] indegree = new int[V];
for (ArrayList<Integer> list : adj) {
for (int nei : list) {
indegree[nei]++;
}
}

// Step 2: Initialize a queue and enqueue all vertices with in-degree 0
Queue<Integer> queue = new LinkedList<>();
for (int i = 0; i < V; i++) {
if (indegree[i] == 0) {
queue.offer(i);
}
}

// Step 3: Initialize count of visited vertices
int count = 0;

// Step 4: Process vertices in queue
while (!queue.isEmpty()) {
int node = queue.poll();
count++;

// Decrease in-degree for all adjacent vertices
for (int nei : adj.get(node)) {
indegree[nei]--;
// If in-degree becomes zero, add it to the queue
if (indegree[nei] == 0) {
queue.offer(nei);
}
}
}

// Step 5: Check if topological sort included all vertices
return count != V;
}
}
Loading

0 comments on commit 4e38e1b

Please sign in to comment.