0% found this document useful (0 votes)
2 views31 pages

algorithm and problems

The document contains multiple Java programs demonstrating various algorithms and data structures, including factorial calculation, Fibonacci series, GCD computation, bubble sort, palindrome checking, binary search, cycle detection in graphs, depth-first search, binary tree implementation, queue using stacks, and multithreading concepts like Singleton pattern, producer-consumer problem, and readers-writers problem. Each program is structured with a main method and relevant class definitions. The examples provide practical implementations of fundamental programming concepts.

Uploaded by

REVATHI
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
Download as txt, pdf, or txt
0% found this document useful (0 votes)
2 views31 pages

algorithm and problems

The document contains multiple Java programs demonstrating various algorithms and data structures, including factorial calculation, Fibonacci series, GCD computation, bubble sort, palindrome checking, binary search, cycle detection in graphs, depth-first search, binary tree implementation, queue using stacks, and multithreading concepts like Singleton pattern, producer-consumer problem, and readers-writers problem. Each program is structured with a main method and relevant class definitions. The examples provide practical implementations of fundamental programming concepts.

Uploaded by

REVATHI
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1/ 31

1.

factorial number:

public class Factorial1 {

public static void main(String[] args) {

int num = 10;


long factorial = 1;
for(int i = 1; i <= num; ++i)
{
// factorial = factorial * i;
factorial *= i;
}
System.out.printf("Factorial of %d = %d", num, factorial);
}
}

2. fibonacci number.
class fibonacci {
public static void main(String[] args) {

int n = 10, firstTerm = 0, secondTerm = 1;


System.out.println("Fibonacci Series till " + n + " terms:");

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


System.out.print(firstTerm + ", ");

// compute the next term


int nextTerm = firstTerm + secondTerm;
firstTerm = secondTerm;
secondTerm = nextTerm;
}
}
}

3.GCD of two numbers.


class gcd {
public static void main(String[] args) {

// find GCD between n1 and n2


int n1 = 81, n2 = 153;

// initially set to gcd


int gcd = 1;

for (int i = 1; i <= n1 && i <= n2; ++i) {

// check if i perfectly divides both n1 and n2


if (n1 % i == 0 && n2 % i == 0)
gcd = i;
}

System.out.println("GCD of " + n1 +" and " + n2 + " is " + gcd);


}
}

4.array bubble sort


class BubbleSort {
void bubbleSort(int arr[])
{
int n = arr.length;

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


for (int j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1]) {

// swap temp and arr[i]


int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}

// Driver method to test above


public static void main(String args[])
{
BubbleSort ob = new BubbleSort();
int a[] = { 64, 34, 25, 12 };

ob.bubbleSort(a);

int n = a.length;

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


System.out.print(a[i] + " ");
System.out.println();
}
}

5.palindrome in string .

class palindrome{
public static void main(String args[]){
String s = "ARORA";
String rev = "";
for(int i=s.length()-1;i>=0;i--){
rev = rev+s.charAt(i);
}
if(s.toLowerCase().equals(rev.toLowerCase())){
System.out.println(s + " is a palindrome");
}
else{
System.out.println(s + "is not a palindrome");
}
}
}

6.binaer search

class BinarySearch {
// Binary Search Function (Iterative)
public static int binarySearch(int[] arr, int target) {
int left = 0, right = arr.length - 1;

while (left <= right) {


int mid = left + (right - left) / 2;
// Check if target is at mid
if (arr[mid] == target)
return mid;

// If target is greater, ignore left half


if (arr[mid] < target)
left = mid + 1;
else // If target is smaller, ignore right half
right = mid - 1;
}
return -1; // Element not found
}

public static void main(String[] args) {


int[] sortedArray = {10, 20, 30, 40, 50, 60, 70};
int target = 40;

int result = binarySearch(sortedArray, target);


if (result != -1)
System.out.println("Element found at index: " + result);
else
System.out.println("Element not found.");
}
}

7.Write a program to detect a cycle in a graph

import java.util.ArrayList;
import java.util.List;

public class SimpleCycleDetection {

static class Graph {


int vertices;
List<List<Integer>> adjList;

// Constructor
public Graph(int vertices) {
this.vertices = vertices;
adjList = new ArrayList<>();
for (int i = 0; i < vertices; i++) {
adjList.add(new ArrayList<>());
}
}

// Add edge to the graph


public void addEdge(int source, int destination) {
adjList.get(source).add(destination);
}

// Detect cycle
public boolean hasCycle() {
boolean[] visited = new boolean[vertices];
boolean[] recStack = new boolean[vertices];

for (int i = 0; i < vertices; i++) {


if (dfs(i, visited, recStack)) {
return true;
}
}
return false;
}

// DFS helper
private boolean dfs(int node, boolean[] visited, boolean[] recStack) {
if (recStack[node]) return true;
if (visited[node]) return false;

visited[node] = true;
recStack[node] = true;

for (int neighbor : adjList.get(node)) {


if (dfs(neighbor, visited, recStack)) {
return true;
}
}

recStack[node] = false;
return false;
}
}

public static void main(String[] args) {


Graph graph = new Graph(3);
graph.addEdge(0, 1);
graph.addEdge(1, 2);
graph.addEdge(2, 0);

if (graph.hasCycle()) {
System.out.println("Cycle detected.");
} else {
System.out.println("No cycle detected.");
}
}
}

8.Write a program to perform depth-first search (DFS).

import java.util.ArrayList;
import java.util.List;

public class DepthFirstSearch {

static class Graph {


private int vertices; // Number of vertices
private List<List<Integer>> adjList; // Adjacency list

// Constructor
public Graph(int vertices) {
this.vertices = vertices;
adjList = new ArrayList<>();
for (int i = 0; i < vertices; i++) {
adjList.add(new ArrayList<>());
}
}

// Add an edge to the graph


public void addEdge(int source, int destination) {
adjList.get(source).add(destination);
}

// Perform DFS
public void dfs(int start) {
boolean[] visited = new boolean[vertices];
System.out.println("Depth-First Search starting from vertex " + start +
":");
dfsUtil(start, visited);
}

// Recursive DFS utility function


private void dfsUtil(int vertex, boolean[] visited) {
visited[vertex] = true;
System.out.print(vertex + " ");

for (int neighbor : adjList.get(vertex)) {


if (!visited[neighbor]) {
dfsUtil(neighbor, visited);
}
}
}
}

public static void main(String[] args) {


Graph graph = new Graph(6);

// Add edges to the graph


graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 3);
graph.addEdge(1, 4);
graph.addEdge(2, 5);

// Perform DFS starting from vertex 0


graph.dfs(0);
}
}

9.Implement a binary tree in Java.

// Binary Tree Implementation in Java


class BinaryTree {

// Node class representing a single node in the tree


static class Node {
int value;
Node left;
Node right;

Node(int value) {
this.value = value;
left = null;
right = null;
}
}

// Root of the binary tree


Node root;

// Constructor
public BinaryTree() {
root = null;
}

// Insert a new value into the binary tree


public void insert(int value) {
root = insertRec(root, value);
}

// Recursive helper function for insertion


private Node insertRec(Node root, int value) {
if (root == null) {
root = new Node(value);
return root;
}
if (value < root.value) {
root.left = insertRec(root.left, value);
} else if (value > root.value) {
root.right = insertRec(root.right, value);
}
return root;
}

// Inorder traversal of the tree


public void inorder() {
inorderRec(root);
}

// Recursive helper function for inorder traversal


private void inorderRec(Node root) {
if (root != null) {
inorderRec(root.left);
System.out.print(root.value + " ");
inorderRec(root.right);
}
}

public static void main(String[] args) {


BinaryTree tree = new BinaryTree();

// Insert nodes
tree.insert(50);
tree.insert(30);
tree.insert(70);
tree.insert(20);
tree.insert(40);
tree.insert(60);
tree.insert(80);

// Print inorder traversal


System.out.println("Inorder traversal of the binary tree:");
tree.inorder();
}
}

10.Implement a queue using two stacks


import java.util.Stack;

public class QueueStacks {


static class Queue {
Stack<Integer> stack1; // Primary stack
Stack<Integer> stack2; // Auxiliary stack

// Constructor
public Queue() {
stack1 = new Stack<>();
stack2 = new Stack<>();
}

// Enqueue operation
public void enqueue(int value) {
stack1.push(value);
}

// Dequeue operation
public int dequeue() {
if (stack2.isEmpty()) {
if (stack1.isEmpty()) {
throw new RuntimeException("Queue is empty");
}
// Transfer all elements from stack1 to stack2
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
}

// Check if the queue is empty


public boolean isEmpty() {
return stack1.isEmpty() && stack2.isEmpty();
}

// Peek the front element


public int peek() {
if (stack2.isEmpty()) {
if (stack1.isEmpty()) {
throw new RuntimeException("Queue is empty");
}
// Transfer all elements from stack1 to stack2
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.peek();
}
}

public static void main(String[] args) {


Queue queue = new Queue();

// Enqueue elements
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
// Dequeue and display elements
System.out.println("Dequeued: " + queue.dequeue()); // 1
System.out.println("Peek: " + queue.peek()); // 2
System.out.println("Dequeued: " + queue.dequeue()); // 2

// Enqueue more elements


queue.enqueue(4);
queue.enqueue(5);

// Dequeue remaining elements


while (!queue.isEmpty()) {
System.out.println("Dequeued: " + queue.dequeue());
}
}
}

___________________________________________________________________________________

------- multi threading---------------


11. Implement a thread-safe Singleton design pattern

class Singleton {
// Volatile keyword ensures visibility of changes to variables across threads
private static volatile Singleton instance;

// Private constructor to prevent instantiation from outside


private Singleton() {
// Prevent instantiation via reflection
if (instance != null) {
throw new IllegalStateException("Instance already created");
}
}

// Public method to provide access to the Singleton instance


public static Singleton getInstance() {
if (instance == null) { // First check (no locking)
synchronized (Singleton.class) {
if (instance == null) { // Second check (with locking)
instance = new Singleton();
}
}
}
return instance;
}
}
public class Singleton1 {
public static void main(String[] args) {
Singleton singleton1 = Singleton.getInstance();
Singleton singleton2 = Singleton.getInstance();

System.out.println(singleton1 == singleton2); // true


}
}

12. Write a program to implement a producer-consumer problem using semaphores.

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.Semaphore;

public class ProducerConsumer {

// Shared buffer
private static final int BUFFER_SIZE = 5;
private static final Queue<Integer> buffer = new LinkedList<>();

// Semaphores
private static final Semaphore empty = new Semaphore(BUFFER_SIZE); // Tracks
empty slots
private static final Semaphore full = new Semaphore(0); // Tracks
filled slots
private static final Semaphore mutex = new Semaphore(1); // Mutual
exclusion

public static void main(String[] args) throws InterruptedException {


Thread producerThread = new Thread(new Producer());
Thread consumerThread = new Thread(new Consumer());

// Start threads
producerThread.start();
consumerThread.start();

// Keep main thread alive


producerThread.join();
consumerThread.join();
}

static class Producer implements Runnable {


@Override
public void run() {
while (true) {
produce();
}
}

private void produce() {


try {
int item = (int) (Math.random() * 100); // Produce an item
empty.acquire(); // Wait if no empty slots
mutex.acquire(); // Enter critical section
buffer.add(item); // Add item to buffer
System.out.println("Producer produced: " + item + ", Buffer: " +
buffer);
mutex.release(); // Exit critical section
full.release(); // Signal that a slot is filled
Thread.sleep((int) (Math.random() * 1000)); // Simulate time to
produce
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}

static class Consumer implements Runnable {


@Override
public void run() {
while (true) {
consume();
}
}

private void consume() {


try {
full.acquire(); // Wait if buffer is empty
mutex.acquire(); // Enter critical section
int item = buffer.poll(); // Remove item from buffer
System.out.println("Consumer consumed: " + item + ", Buffer: " +
buffer);
mutex.release(); // Exit critical section
empty.release(); // Signal that a slot is empty
Thread.sleep((int) (Math.random() * 1000)); // Simulate time to
consume
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}

13. Implement the Readers-Writers problem

import java.util.concurrent.Semaphore;

public class ReadersWriters {

// Semaphores
private static final Semaphore mutex = new Semaphore(1); // For reader count
access
private static final Semaphore rwMutex = new Semaphore(1); // For resource
access
private static int readerCount = 0; // Tracks the number of readers

public static void main(String[] args) {


// Create multiple readers and writers
Thread reader1 = new Thread(new Reader(), "Reader 1");
Thread reader2 = new Thread(new Reader(), "Reader 2");
Thread writer1 = new Thread(new Writer(), "Writer 1");
Thread writer2 = new Thread(new Writer(), "Writer 2");

// Start threads
reader1.start();
reader2.start();
writer1.start();
writer2.start();
}

static class Reader implements Runnable {


@Override
public void run() {
while (true) {
try {
// Entering critical section to update readerCount
mutex.acquire();
readerCount++;
if (readerCount == 1) {
rwMutex.acquire(); // First reader locks the resource
}
mutex.release();

// Reading (non-critical section)


System.out.println(Thread.currentThread().getName() + " is
reading...");
Thread.sleep((int) (Math.random() * 1000)); // Simulate reading
time

// Leaving critical section


mutex.acquire();
readerCount--;
if (readerCount == 0) {
rwMutex.release(); // Last reader unlocks the resource
}
mutex.release();

// Simulate delay between reads


Thread.sleep((int) (Math.random() * 1000));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}

static class Writer implements Runnable {


@Override
public void run() {
while (true) {
try {
rwMutex.acquire(); // Lock resource for writing
// Writing (critical section)
System.out.println(Thread.currentThread().getName() + " is
writing...");
Thread.sleep((int) (Math.random() * 1000)); // Simulate writing
time
rwMutex.release(); // Unlock resource

// Simulate delay between writes


Thread.sleep((int) (Math.random() * 1000));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
}

14. Design a thread-safe bounded blocking queue

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.Semaphore;

public class BoundedBlockingQueue<T> {


private final Queue<T> queue;
private final int capacity;
private final Semaphore enqueueSemaphore; // Tracks available space
private final Semaphore dequeueSemaphore; // Tracks available items
private final Semaphore mutex; // Mutual exclusion for queue
operations

public BoundedBlockingQueue(int capacity) {


this.capacity = capacity;
this.queue = new LinkedList<>();
this.enqueueSemaphore = new Semaphore(capacity); // Initially, the queue
has all slots available
this.dequeueSemaphore = new Semaphore(0); // Initially, no items in
the queue
this.mutex = new Semaphore(1); // Ensures thread-safe
operations
}

public void enqueue(T item) throws InterruptedException {


enqueueSemaphore.acquire(); // Wait if the queue is full
mutex.acquire(); // Enter critical section
try {
queue.add(item);
System.out.println("Enqueued: " + item);
} finally {
mutex.release(); // Exit critical section
}
dequeueSemaphore.release(); // Signal that an item is available
}

public T dequeue() throws InterruptedException {


dequeueSemaphore.acquire(); // Wait if the queue is empty
mutex.acquire(); // Enter critical section
try {
T item = queue.poll();
System.out.println("Dequeued: " + item);
return item;
} finally {
mutex.release(); // Exit critical section
}
enqueueSemaphore.release(); // Signal that space is available
}

public int size() {


mutex.acquireUninterruptibly();
try {
return queue.size();
} finally {
mutex.release();
}
}

public static void main(String[] args) {


BoundedBlockingQueue<Integer> queue = new BoundedBlockingQueue<>(5);

// Producer thread
Thread producer = new Thread(() -> {
try {
for (int i = 1; i <= 10; i++) {
queue.enqueue(i);
Thread.sleep((int) (Math.random() * 500)); // Simulate work
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});

// Consumer thread
Thread consumer = new Thread(() -> {
try {
for (int i = 1; i <= 10; i++) {
queue.dequeue();
Thread.sleep((int) (Math.random() * 500)); // Simulate work
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});

producer.start();
consumer.start();
}
}

15. Write a program to solve the dining philosophers problem

import java.util.concurrent.Semaphore;

public class DiningPhilosophers {

// Number of philosophers
private static final int NUM_PHILOSOPHERS = 5;

// Array of semaphores, one for each fork


private static final Semaphore[] forks = new Semaphore[NUM_PHILOSOPHERS];

// Semaphore to limit the number of philosophers trying to eat (prevent


deadlock)
private static final Semaphore table = new Semaphore(NUM_PHILOSOPHERS - 1);

public static void main(String[] args) {


// Initialize fork semaphores
for (int i = 0; i < NUM_PHILOSOPHERS; i++) {
forks[i] = new Semaphore(1);
}

// Create and start philosopher threads


for (int i = 0; i < NUM_PHILOSOPHERS; i++) {
new Thread(new Philosopher(i)).start();
}
}

static class Philosopher implements Runnable {


private final int id;
private final int leftFork;
private final int rightFork;
public Philosopher(int id) {
this.id = id;
this.leftFork = id;
this.rightFork = (id + 1) % NUM_PHILOSOPHERS;
}

@Override
public void run() {
try {
while (true) {
think();
pickUpForks();
eat();
putDownForks();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}

private void think() throws InterruptedException {


System.out.println("Philosopher " + id + " is thinking...");
Thread.sleep((int) (Math.random() * 1000)); // Simulate thinking time
}

private void pickUpForks() throws InterruptedException {


table.acquire(); // Limit the number of philosophers trying to eat
forks[leftFork].acquire(); // Pick up the left fork
System.out.println("Philosopher " + id + " picked up left fork " +
leftFork);
forks[rightFork].acquire(); // Pick up the right fork
System.out.println("Philosopher " + id + " picked up right fork " +
rightFork);
}

private void eat() throws InterruptedException {


System.out.println("Philosopher " + id + " is eating...");
Thread.sleep((int) (Math.random() * 1000)); // Simulate eating time
}

private void putDownForks() {


forks[leftFork].release(); // Put down the left fork
System.out.println("Philosopher " + id + " put down left fork " +
leftFork);
forks[rightFork].release(); // Put down the right fork
System.out.println("Philosopher " + id + " put down right fork " +
rightFork);
table.release(); // Allow another philosopher to try eating
}
}
}

16. Implement a cyclic barrier.

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class CyclicBarrier {


private final int parties; // Total number of threads to wait for
private int count; // Tracks the current number of waiting threads
private final Runnable barrierAction; // Optional action to execute when
barrier is tripped

private final Lock lock = new ReentrantLock();


private final Condition condition = lock.newCondition();

public CyclicBarrier(int parties, Runnable barrierAction) {


if (parties <= 0) {
throw new IllegalArgumentException("Number of parties must be greater
than 0");
}
this.parties = parties;
this.count = parties;
this.barrierAction = barrierAction;
}

public CyclicBarrier(int parties) {


this(parties, null);
}

public void await() throws InterruptedException {


lock.lock();
try {
count--;

if (count == 0) {
// All threads have reached the barrier
if (barrierAction != null) {
barrierAction.run(); // Execute the optional barrier action
}
// Reset the barrier for reuse
count = parties;
condition.signalAll(); // Wake up all waiting threads
} else {
// Wait for other threads to reach the barrier
while (count > 0) {
condition.await();
}
}
} finally {
lock.unlock();
}
}
}

//example of cyclic barrier

public class CyclicBarrierExample {

public static void main(String[] args) {


final int NUM_THREADS = 3;

// CyclicBarrier with an action to execute when the barrier is tripped


CyclicBarrier barrier = new CyclicBarrier(NUM_THREADS,
() -> System.out.println("All threads reached the barrier. Barrier
tripped!"));
Runnable task = () -> {
try {
System.out.println(Thread.currentThread().getName() + " is
performing work...");
Thread.sleep((int) (Math.random() * 1000)); // Simulate work
System.out.println(Thread.currentThread().getName() + " is waiting
at the barrier...");
barrier.await();
System.out.println(Thread.currentThread().getName() + " has crossed
the barrier.");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
};

// Create and start threads


for (int i = 0; i < NUM_THREADS; i++) {
new Thread(task).start();
}
}
}

17. Write a program to implement a custom thread pool.

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class CustomThreadPool {

private final int poolSize;


private final WorkerThread[] workers;
private final BlockingQueue<Runnable> taskQueue;
private volatile boolean isShutdown = false;

public CustomThreadPool(int poolSize) {


this.poolSize = poolSize;
this.taskQueue = new LinkedBlockingQueue<>();
this.workers = new WorkerThread[poolSize];

// Initialize and start worker threads


for (int i = 0; i < poolSize; i++) {
workers[i] = new WorkerThread();
workers[i].start();
}
}

public void submit(Runnable task) {


if (isShutdown) {
throw new IllegalStateException("Thread pool is shutting down, cannot
accept new tasks.");
}
taskQueue.offer(task); // Add task to the queue
}

public void shutdown() {


isShutdown = true; // Mark the thread pool for shutdown
for (WorkerThread worker : workers) {
worker.interrupt(); // Interrupt each worker thread
}
}

private class WorkerThread extends Thread {


@Override
public void run() {
while (!isShutdown || !taskQueue.isEmpty()) {
try {
Runnable task = taskQueue.take(); // Take task from the queue
task.run(); // Execute the task
} catch (InterruptedException e) {
// Allow thread to exit if interrupted during shutdown
if (isShutdown) {
break;
}
}
}
}
}

public static void main(String[] args) {


CustomThreadPool threadPool = new CustomThreadPool(3); // Create a pool of
3 threads

// Submit tasks to the thread pool


for (int i = 1; i <= 10; i++) {
final int taskId = i;
threadPool.submit(() -> {
System.out.println("Task " + taskId + " is being executed by " +
Thread.currentThread().getName());
try {
Thread.sleep(500); // Simulate task execution time
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}

threadPool.shutdown(); // Shut down the thread pool


}
}

18. Implement a parallel merge sort algorithm

import java.util.concurrent.RecursiveAction;
import java.util.concurrent.ForkJoinPool;

public class ParallelMergeSort {

public static void parallelMergeSort(int[] array) {


if (array == null || array.length <= 1) {
return; // Already sorted or empty
}
ForkJoinPool pool = new ForkJoinPool(); // Create ForkJoinPool
pool.invoke(new MergeSortTask(array, 0, array.length - 1));
}
private static class MergeSortTask extends RecursiveAction {
private final int[] array;
private final int left;
private final int right;

public MergeSortTask(int[] array, int left, int right) {


this.array = array;
this.left = left;
this.right = right;
}

@Override
protected void compute() {
if (left < right) {
int mid = left + (right - left) / 2;

// Split the task into two subtasks


MergeSortTask leftTask = new MergeSortTask(array, left, mid);
MergeSortTask rightTask = new MergeSortTask(array, mid + 1, right);

// Invoke the subtasks in parallel


invokeAll(leftTask, rightTask);

// Merge the results


merge(array, left, mid, right);
}
}

private void merge(int[] array, int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;

// Create temporary arrays


int[] leftArray = new int[n1];
int[] rightArray = new int[n2];

// Copy data into temporary arrays


System.arraycopy(array, left, leftArray, 0, n1);
System.arraycopy(array, mid + 1, rightArray, 0, n2);

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

// Merge the temporary arrays


while (i < n1 && j < n2) {
if (leftArray[i] <= rightArray[j]) {
array[k++] = leftArray[i++];
} else {
array[k++] = rightArray[j++];
}
}

// Copy any remaining elements from leftArray


while (i < n1) {
array[k++] = leftArray[i++];
}

// Copy any remaining elements from rightArray


while (j < n2) {
array[k++] = rightArray[j++];
}
}
}

public static void main(String[] args) {


int[] array = {38, 27, 43, 3, 9, 82, 10};
System.out.println("Original array:");
printArray(array);

parallelMergeSort(array);

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

private static void printArray(int[] array) {


for (int num : array) {
System.out.print(num + " ");
}
System.out.println();
}
}

//Input: {38, 27, 43, 3, 9, 82, 10}


//Output: {3, 9, 10, 27, 38, 43, 82}

19. Write a program to simulate a bank transaction system with multiple threads.

class BankAccount {
private int balance;

public BankAccount(int initialBalance) {


this.balance = initialBalance;
}

// Synchronized deposit method


public synchronized void deposit(int amount) {
balance += amount;
System.out.println(Thread.currentThread().getName() + " deposited $" +
amount + ". Current balance: $" + balance);
notifyAll(); // Notify waiting threads
}

// Synchronized withdraw method


public synchronized void withdraw(int amount) {
while (balance < amount) {
System.out.println(Thread.currentThread().getName() + " wants to
withdraw $" + amount + " but only $" + balance + " is available. Waiting...");
try {
wait(); // Wait until there is enough balance
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
balance -= amount;
System.out.println(Thread.currentThread().getName() + " withdrew $" +
amount + ". Current balance: $" + balance);
}
public synchronized int getBalance() {
return balance;
}
}

public class BankTransactionSystem {

public static void main(String[] args) {


BankAccount account = new BankAccount(100); // Initial balance is $100

// Runnable for deposit transactions


Runnable depositTask = () -> {
for (int i = 0; i < 5; i++) {
account.deposit((int) (Math.random() * 100) + 1); // Deposit a
random amount
try {
Thread.sleep(500); // Simulate processing time
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
};

// Runnable for withdrawal transactions


Runnable withdrawTask = () -> {
for (int i = 0; i < 5; i++) {
account.withdraw((int) (Math.random() * 100) + 1); // Withdraw a
random amount
try {
Thread.sleep(700); // Simulate processing time
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
};

// Create threads for deposit and withdrawal


Thread depositor1 = new Thread(depositTask, "Depositor-1");
Thread depositor2 = new Thread(depositTask, "Depositor-2");
Thread withdrawer1 = new Thread(withdrawTask, "Withdrawer-1");
Thread withdrawer2 = new Thread(withdrawTask, "Withdrawer-2");

// Start all threads


depositor1.start();
depositor2.start();
withdrawer1.start();
withdrawer2.start();

// Wait for all threads to finish


try {
depositor1.join();
depositor2.join();
withdrawer1.join();
withdrawer2.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}

// Final balance
System.out.println("Final balance: $" + account.getBalance());
}
}

20. Design a concurrent cache using ConcurrentHashMap.

import java.util.concurrent.*;

public class ConcurrentCache<K, V> {

private final ConcurrentHashMap<K, V> cache;


private final int cacheSize;

// Constructor for cache with a specified maximum size


public ConcurrentCache(int cacheSize) {
this.cacheSize = cacheSize;
this.cache = new ConcurrentHashMap<>();
}

// Add or update an item in the cache


public void put(K key, V value) {
if (cache.size() >= cacheSize) {
evictCache(); // Evict an item if cache exceeds size
}
cache.put(key, value);
}

// Get an item from the cache


public V get(K key) {
return cache.get(key);
}

// Remove an item from the cache


public void remove(K key) {
cache.remove(key);
}

// Evict an item from the cache (simple approach: remove first item)
private void evictCache() {
// For simplicity, we just remove one entry. A better strategy could be an
LRU (Least Recently Used) eviction policy.
for (K key : cache.keySet()) {
cache.remove(key);
break; // Evict only one element for this simple example
}
}

// Print the cache (just for demonstration)


public void printCache() {
System.out.println(cache);
}

// Test the cache with concurrent threads


public static void main(String[] args) {
ConcurrentCache<Integer, String> cache = new ConcurrentCache<>(5);

// Runnable to simulate cache operations


Runnable cacheTask = () -> {
for (int i = 0; i < 10; i++) {
int key = (int) (Math.random() * 10); // Random key
String value = "Value-" + key;
cache.put(key, value); // Put new value in cache
System.out.println(Thread.currentThread().getName() + " put " + key
+ ": " + value);

// Randomly get value


String retrievedValue = cache.get(key);
System.out.println(Thread.currentThread().getName() + " got " + key
+ ": " + retrievedValue);
}
};

// Create multiple threads to access the cache concurrently


Thread thread1 = new Thread(cacheTask, "Thread-1");
Thread thread2 = new Thread(cacheTask, "Thread-2");
Thread thread3 = new Thread(cacheTask, "Thread-3");

thread1.start();
thread2.start();
thread3.start();

// Wait for threads to finish


try {
thread1.join();
thread2.join();
thread3.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}

// Final cache state


System.out.println("Final Cache State:");
cache.printCache();
}
}

_________________________________________________________________________________

--------------data structure and algorithms------------

1. Implement a Trie data structure with insert, search, and delete operations.

class Trie {

// TrieNode definition
static class TrieNode {
TrieNode[] children = new TrieNode[26]; // Array for 26 lowercase letters
boolean isEndOfWord = false; // Flag to mark the end of a word
}

private final TrieNode root;

// Constructor to initialize the Trie


public Trie() {
root = new TrieNode();
}

// Insert a word into the Trie


public void insert(String word) {
TrieNode node = root;
for (char ch : word.toCharArray()) {
int index = ch - 'a'; // Find index of the character
if (node.children[index] == null) {
node.children[index] = new TrieNode(); // Create a new TrieNode if
not already present
}
node = node.children[index];
}
node.isEndOfWord = true; // Mark the end of the word
}

// Search for a word in the Trie


public boolean search(String word) {
TrieNode node = root;
for (char ch : word.toCharArray()) {
int index = ch - 'a';
if (node.children[index] == null) {
return false; // Word not found
}
node = node.children[index];
}
return node.isEndOfWord; // Check if the word ends correctly
}

// Delete a word from the Trie


public boolean delete(String word) {
return delete(root, word, 0);
}

private boolean delete(TrieNode node, String word, int depth) {


if (node == null) {
return false; // Word not found
}

if (depth == word.length()) {
if (!node.isEndOfWord) {
return false; // Word not found
}
node.isEndOfWord = false; // Unmark the end of the word
return isEmpty(node); // Check if node has no children
}

int index = word.charAt(depth) - 'a';


if (delete(node.children[index], word, depth + 1)) {
node.children[index] = null; // Remove the child reference
return !node.isEndOfWord && isEmpty(node); // Check if the current node
can be deleted
}
return false;
}

// Helper method to check if a node has any children


private boolean isEmpty(TrieNode node) {
for (TrieNode child : node.children) {
if (child != null) {
return false; // Node has children
}
}
return true; // Node has no children
}

// Main method for testing


public static void main(String[] args) {
Trie trie = new Trie();

// Insert words
trie.insert("hello");
trie.insert("world");
trie.insert("help");
trie.insert("heap");

// Search for words


System.out.println(trie.search("hello")); // true
System.out.println(trie.search("hell")); // false
System.out.println(trie.search("heap")); // true

// Delete words
System.out.println(trie.delete("heap")); // true
System.out.println(trie.search("heap")); // false
System.out.println(trie.search("help")); // true
}
}

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

------ string manipulation -----------

31. Write a program to find all permutations of a string.

public class StringPermutations {

// Method to generate permutations


public static void generatePermutations(String str, int left, int right) {
if (left == right) {
System.out.println(str);
} else {
for (int i = left; i <= right; i++) {
str = swap(str, left, i); // Swap characters
generatePermutations(str, left + 1, right); // Recursive call
str = swap(str, left, i); // Backtrack
}
}
}

// Utility method to swap characters in a string


private static String swap(String str, int i, int j) {
char[] charArray = str.toCharArray();
char temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
return String.valueOf(charArray);
}

public static void main(String[] args) {


String input = "ABC";
System.out.println("All permutations of the string: " + input);
generatePermutations(input, 0, input.length() - 1);
}
}

32. Implement a program to find the longest palindromic substring.

public class LongestPalindromicSubstring {

// Method to expand around center and find longest palindrome


private static String expandAroundCenter(String s, int left, int right) {
while (left >= 0 && right < s.length() && s.charAt(left) ==
s.charAt(right)) {
left--;
right++;
}
return s.substring(left + 1, right); // Extract palindromic substring
}

// Main method to find the longest palindromic substring


public static String findLongestPalindrome(String s) {
if (s == null || s.length() < 1) return "";

String longestPalindrome = "";

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


// Check for odd-length palindrome (single center)
String oddPalindrome = expandAroundCenter(s, i, i);
// Check for even-length palindrome (two-character center)
String evenPalindrome = expandAroundCenter(s, i, i + 1);

// Update the longest palindrome found


if (oddPalindrome.length() > longestPalindrome.length()) {
longestPalindrome = oddPalindrome;
}
if (evenPalindrome.length() > longestPalindrome.length()) {
longestPalindrome = evenPalindrome;
}
}
return longestPalindrome;
}

public static void main(String[] args) {


String input = "babad";
System.out.println("Longest Palindromic Substring: " +
findLongestPalindrome(input));
}
}

33. Write a program to perform wildcard pattern matching.

public class WildcardMatching {

// Function to check if text matches pattern


public static boolean isMatch(String text, String pattern) {
int m = pattern.length();
int n = text.length();
boolean[][] dp = new boolean[m + 1][n + 1];
// Base case: Empty pattern and empty text match
dp[0][0] = true;

// Handle patterns with '*' at the start (can match empty text)
for (int i = 1; i <= m; i++) {
if (pattern.charAt(i - 1) == '*') {
dp[i][0] = dp[i - 1][0]; // '*' can represent empty sequence
}
}

// Fill DP table
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (pattern.charAt(i - 1) == text.charAt(j - 1) || pattern.charAt(i
- 1) == '?') {
dp[i][j] = dp[i - 1][j - 1]; // Match character or '?'
} else if (pattern.charAt(i - 1) == '*') {
dp[i][j] = dp[i - 1][j] || dp[i][j - 1]; // '*' matches empty
or any char
}
}
}

return dp[m][n];
}

public static void main(String[] args) {


String text = "abcd";
String pattern = "a*d";

System.out.println("Pattern matches string: " + isMatch(text, pattern)); //


Output: true
}
}

________________________________________________________________________

file handling

import java.io.File;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.BufferdReader;
import java.io.IOException;

public class file{


public static void main(String args[]){
File newFile = new File("ex.txt");
System.out.println("file created...");
try(FileWriter myWrite = new FileWriter(newFile)){
myWrite.write("hello file\n");
myWrite.write("adding extra information...");
System.out.println("file have some content");
}
catch(IOException e){
System.out.println("error occured");
e.printStackTrace();
}
try(FileReader myRead = new FileReader(newFile);
BufferedReader buff = new BufferedReader(myRead)){
String line;
while(line = buff.readLine() != null);
System.out.println("read the data" +line);
}
catch(IOException e){
System.out.println("error occured");
e.printStackTrace();
}
}
}

111. reader writer in mutlithreading .

class SharedResource {
private int data = 0; // Shared variable

// Writer Method
public synchronized void write(int value) {
System.out.println(Thread.currentThread().getName() + " is Writing: " +
value);
data = value;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
System.out.println(Thread.currentThread().getName() + " finished
Writing.");
}

// Reader Method
public synchronized void read() {
System.out.println(Thread.currentThread().getName() + " is Reading: " +
data);
try { Thread.sleep(500); } catch (InterruptedException e) {}
}
}

// Reader Thread using Runnable


class Reader implements Runnable {
private SharedResource resource;

public Reader(SharedResource resource) {


this.resource = resource;
}

public void run() {


for (int i = 0; i < 3; i++) {
resource.read();
}
}
}

// Writer Thread using Runnable


class Writer implements Runnable {
private SharedResource resource;

public Writer(SharedResource resource) {


this.resource = resource;
}

public void run() {


for (int i = 1; i <= 2; i++) {
resource.write(i * 10);
}
}
}

// Main Class
public class ReaderWriterRunnable {
public static void main(String[] args) {
SharedResource resource = new SharedResource();

Thread reader1 = new Thread(new Reader(resource), "Reader-1");


Thread reader2 = new Thread(new Reader(resource), "Reader-2");
Thread writer = new Thread(new Writer(resource), "Writer");

reader1.start();
reader2.start();
writer.start();
}
}

112.producer consumer in multithread

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

class Producer implements Runnable {


private BlockingQueue<Integer> queue;

public Producer(BlockingQueue<Integer> queue) {


this.queue = queue;
}

@Override
public void run() {
for (int i = 1; i <= 5; i++) {
try {
System.out.println("Produced: " + i);
queue.put(i); // Put item in the queue
Thread.sleep(1000); // Simulate time-consuming task
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}

class Consumer implements Runnable {


private BlockingQueue<Integer> queue;

public Consumer(BlockingQueue<Integer> queue) {


this.queue = queue;
}

@Override
public void run() {
while (true) {
try {
Integer item = queue.take(); // Take item from queue
System.out.println("Consumed: " + item);
Thread.sleep(1500); // Simulate processing time
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
}
}

public class ProducerConsumerExample {


public static void main(String[] args) {
BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(3); // Max size 3

Thread producerThread = new Thread(new Producer(queue));


Thread consumerThread = new Thread(new Consumer(queue));

producerThread.start();
consumerThread.start();
}
}

-----------------------------------------
bank details

import java.util.Scanner;
class BankAcc{
private String name;
private double accno;
private double balance;

public BankAcc(String name, double accno, double balance){


this.name = name;
this.accno = accno;
this.balance = balance;
}
public void deposit(double amount){
if(amount>0){
balance = balance + amount;
System.out.println("after deposit the balance is:" +balance);
}
else{
System.out.println("invalid deposit:");
}
}
public void withdraw(double amount){
if(amount>0 && amount<=balance){
balance = balance - amount;
System.out.println("balance after withdraw:" +balance);
}
else{
System.out.println("insufient amount you eneter:");
}
}
public void display(){
System.out.println("account holde name:" +name);
System.out.println("account number:" +accno);
System.out.println("balance is:" +balance);
}
}
public class BankDetails{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("enter the account holder name:");
String accName = sc.nextLine();
System.out.println("enter the account number:");
double accNo = sc.nextDouble();
System.out.println("enter initial balance:");
double initialBalance = sc.nextDouble();

BankAcc account = new BankAcc(accName, accNo, initialBalance);


int choice;
do{
System.out.println("\n1. Deposit");
System.out.println("2. Withdraw");
System.out.println("3. Display Account Details");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
choice = sc.nextInt();
switch(choice){
case 1:
System.out.println("enter the amount of deposit:");
double depositAmount = sc.nextDouble();
account.deposit(depositAmount);
break;

case 2:
System.out.println("enter amount you withdraw:");
double withdrawAmount = sc.nextDouble();
account.withdraw(withdrawAmount);
break;

case 3:
account.display();
break;

case 4:
System.out.println("exit.. Thank u");
break;
default:
System.out.println(" invalid choice");
}
}
while(choice != 4);
sc.close();
}
}

You might also like