0% found this document useful (0 votes)
8 views

Implementation1

The document contains various implementations of sorting algorithms, graph representations, and traversal techniques in Java. It includes methods for Merge Sort, Quick Sort, and the Traveling Salesman problem, as well as data structures like heaps and binary trees. Additionally, it covers different traversal strategies such as Morris Inorder and iterative Preorder and Postorder traversals.

Uploaded by

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

Implementation1

The document contains various implementations of sorting algorithms, graph representations, and traversal techniques in Java. It includes methods for Merge Sort, Quick Sort, and the Traveling Salesman problem, as well as data structures like heaps and binary trees. Additionally, it covers different traversal strategies such as Morris Inorder and iterative Preorder and Postorder traversals.

Uploaded by

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

Implementation }

while (i < n1) {


Sort
arr[k++] = leftArray[i++];
Merge Sort }
while (j < n2) {
public void mergeSort(int[] arr, int left, int right) { arr[k++] = rightArray[j++];
if (left < right) { }
int mid = (left + right) / 2; }
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
Quick Sort
merge(arr, left, mid, right);
} public void quickSort(int[] arr, int low, int high) {
} if (low < high) {
int pivotIndex = partition(arr, low, high);
public void merge(int[] arr, int left, int mid, int right) { quickSort(arr, low, pivotIndex - 1);
int n1 = mid - left + 1; quickSort(arr, pivotIndex + 1, high);
int n2 = right - mid; }
}
int[] leftArray = new int[n1];
int[] rightArray = new int[n2];
public int partition(int[] arr, int low, int high) {
int pivot = arr[high];
for (int i = 0; i < n1; i++) {
int i = low - 1;
leftArray[i] = arr[left + i]; for (int j = low; j < high; j++) {
} if (arr[j] < pivot) {
for (int i = 0; i < n2; i++) { i++;
rightArray[i] = arr[mid + 1 + i]; int temp = arr[i];
}
arr[i] = arr[j];
arr[j] = temp;
int i = 0, j = 0, k = left;
}
while (i < n1 && j < n2) {
}
if (leftArray[i] <= rightArray[j]) { int temp = arr[i + 1];
arr[k++] = leftArray[i++]; arr[i + 1] = arr[high];
} else { arr[high] = temp;
arr[k++] = rightArray[j++];

Implementation 1 Implementation 2

return i + 1;
import java.util.Arrays;
}

public class GfG {


Graph
public static void main(String[] args) {
Adj List int V = 4;
int[][] mat = new int[V][V];
public class GfG {
public static void addEdge(List<List<Integer>> adj, int i, int j) { // Now add edges one by one
adj.get(i).add(j); addEdge(mat, 0, 1);
adj.get(j).add(i); // Undirected addEdge(mat, 0, 2);
} addEdge(mat, 1, 2);
public static void displayAdjList(List<List<Integer>> adj) { }
for (int i = 0; i < adj.size(); i++) { }
System.out.print(i + ": "); // Print the vertex
for (int j : adj.get(i)) {
System.out.print(j + " "); // Print its adjacent TRAVELLING SALESMAN
} class GfG {
System.out.println();
} static int totalCost(int mask, int curr, int n,
} int[][] cost, int[][] memo) {
public static void main(String[] args) {
// Base case: if all cities are visited, return the
// Create a graph with 4 vertices and no edges // cost to return to the starting city (0)
int V = 4; if (mask == (1 << n) - 1) {
List<List<Integer>> adj = new ArrayList<>(V); return cost[curr][0];
for (int i = 0; i < V; i++) { }
adj.add(new ArrayList<>());
} // If the value has already been computed, return it
addEdge(adj, 0, 1); addEdge(adj, 0, 2); // from the memo table
System.out.println("Adjacency List Representation:"); if (memo[curr][mask] != -1) {
displayAdjList(adj); return memo[curr][mask];
} }
}
int ans = Integer.MAX_VALUE;
Adj Mat

Implementation 3 Implementation 4
// Try visiting every city that has not been visited private static class HeapNode
// yet implements Comparable<HeapNode> {
for (int i = 0; i < n; i++) { int x;
if ((mask & (1 << i)) int y;
== 0) { int value;

// If city i is not visited HeapNode(int x, int y, int value)


// Visit city i and update the mask {
ans = Math.min( this.x = x;
ans, cost[curr][i] this.y = y;
+ totalCost(mask | (1 << i), i, this.value = value;
n, cost, memo)); }
}
} @Override public int compareTo(HeapNode hn)
{
// Memoize the result if (this.value <= hn.value) {
return memo[curr][mask] = ans; return -1;
} }
else {
BackTrack return 1;
}
N - Queen Problem
}
Lower diagonal formula row + col is same }
and other diagonal is row-col+N-1
public static ArrayList<Integer>
Heaps
mergeKArrays(int[][] arr, int K)
Maxheap {
ArrayList<Integer> result
PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>( = new ArrayList<Integer>();
Collections.reverseOrder()); PriorityQueue<HeapNode> heap
= new PriorityQueue<HeapNode>();
Merge k sorted arrays insert 1st in min heap then next during extract min
// Initially add only first column of elements. First
// element of every array
public class MergeKSortedArrays { for (int i = 0; i < arr.length; i++) {
heap.add(new HeapNode(i, 0, arr[i][0]));

Implementation 5 Implementation 6

} static int parent(int i) {


return (i - 1) / 2;
HeapNode curr = null; }
while (!heap.isEmpty()) { /*returns the left child of ith Node*/
curr = heap.poll(); static int left(int i) {
result.add(curr.value); return 2 * i + 1;
}
// Check if next element of curr min exists, /*Returns the right child of the ith Node*/
// then add that to heap. static int right(int i) {
if (curr.y < (arr[curr.x].length - 1)) { return 2 * i + 2;
heap.add( }
new HeapNode(curr.x, curr.y + 1,
arr[curr.x][curr.y + 1])); /*Insert a new key x*/
} static void Insert(int x) {
} if (size == capacity) {
System.out.println("Binary Heap Overflown");
return result; return;
} }
} arr[size] = x; /*Insert new element at end*/
int k = size; /*store the index ,for checking heap property*/
k largest(or smallest) elements in an array Largest use min heap store only size++; /*Increase the size*/
k elements then extract and heaping
/*Fix the min heap property*/
class BinaryHeap { while (k != 0 && arr[parent(k)] > arr[k]) {
static int capacity; /*Maximum elements that can be stored in heap*/ int temp = arr[parent(k)];
static int size; /*Current no of elements in heap*/ arr[parent(k)] = arr[k];
static int arr[]; /*array for storing the keys*/ arr[k] = temp;
k = parent(k);
BinaryHeap(int cap) { }
capacity = cap; /*Assigning the capacity*/ }
size = 0; /*Intailly size of hepa is zero*/
arr = new int[capacity]; /*Creating a array*/ static void Heapify(int ind) {
} int ri = right(ind); /*right child*/
int li = left(ind); /*left child*/
/*returns the parent of ith Node*/ int smallest = ind; /*intially assume violated value in Min value*/
if (li < size && arr[li] < arr[smallest])

Implementation 7 Implementation 8
smallest = li; }
if (ri < size && arr[ri] < arr[smallest]) }
smallest = ri; static void Delete(int i) {
/*smallest will store the minvalue index*/ Decreasekey(i, Integer.MIN_VALUE);
/*If the Minimum among the three nodes is the parent itself, ExtractMin();
that is Heap property satisfied so stop else call function recursively on Min }
if (smallest != ind) { static void print() {
int temp = arr[ind]; for (int i = 0; i < size; i++)
arr[ind] = arr[smallest]; System.out.print(arr[i] + " ");
arr[smallest] = temp; System.out.println();
Heapify(smallest); }
} }
}
static int getMin() { Sorting
return arr[0];
count inversions in array - for every 2 sorted arrays cout inversions using
}
merge sort
static int ExtractMin() {
if (size <= 0) median of 2 sorted arrays - how many from 1st array and second array
return Integer.MAX_VALUE; until n
if (size == 1) {
size--; static double medianOf2(int[] a, int[] b) {
return arr[0]; int n = a.length, m = b.length;
} int i = 0, j = 0;
int mini = arr[0];
arr[0] = arr[size - 1]; /*Copy last Node value to root Node value*/ // m1 to store the middle element
size--; // m2 to store the second middle element
Heapify(0); /*Call heapify on root node*/ int m1 = -1, m2 = -1;
return mini;
} // Loop till (m + n)/2
static void Decreasekey(int i, int val) { for (int count = 0; count <= (m + n) / 2; count++) {
arr[i] = val; /*Updating the new_val*/ m2 = m1;
while (i != 0 && arr[parent(i)] > arr[i]) /*Fixing the Min heap*/ {
int temp = arr[parent(i)]; // If both the arrays have remaining elements
arr[parent(i)] = arr[i]; if (i != n && j != m)
arr[i] = temp; m1 = (a[i] > b[j]) ? b[j++] : a[i++];
i = parent(i);

Implementation 9 Implementation 10

// If only a[] has remaining elements // inorder traversal of a binary tree


else if (i < n) public List<Integer> getInorder(TreeNode root) {
m1 = a[i++]; // List to store the
// inorder traversal result
// If only b[] has remaining elements List<Integer> inorder = new ArrayList<>();
else // Pointer to the current node,
m1 = b[j++]; // starting from the root
} TreeNode cur = root;

// Return median based on odd/even size // Loop until the current


if ((m + n) % 2 == 1) // node is not NULL
return m1; while (cur != null) {
else // If the current node's
return (m1 + m2) / 2.0; // left child is NULL
} if (cur.left == null) {
// Add the value of the current
Trees // node to the inorder list
inorder.add(cur.val);
Morris
// Move to the right child
cur = cur.right;
} else {
// TreeNode structure
// If the left child is not NULL,
class TreeNode {
// find the predecessor (rightmost node
int val;
// in the left subtree)
TreeNode left;
TreeNode prev = cur.left;
TreeNode right;
while (prev.right != null && prev.right != cur) {
prev = prev.right;
public TreeNode(int x) {
}
val = x;
left = null;
// If the predecessor's right child
right = null;
// is NULL, establish a temporary link
}
// and move to the left child
}
if (prev.right == null) {
prev.right = cur;
public class Solution {
cur = cur.left;
// Function to perform iterative Morris
} else {

Implementation 11 Implementation 12
// If the predecessor's right child PreOrder Stack
// is already linked, remove the link,
// add current node to inorder list, // Java program to implement iterative preorder traversal
// and move to the right child
prev.right = null; class BinaryTree {
inorder.add(cur.val);
cur = cur.right; Node root;
}
} void iterativePreorder()
} {
iterativePreorder(root);
// Return the inorder }
// traversal result void iterativePreorder(Node node)
return inorder; {
}
// Base Case
public static void main(String[] args) { if (node == null) {
TreeNode root = new TreeNode(1); return;
root.left = new TreeNode(2); }
root.right = new TreeNode(3);
root.left.left = new TreeNode(4); // Create an empty stack and push root to it
root.left.right = new TreeNode(5); Stack<Node> nodeStack = new Stack<Node>();
root.left.right.right = new TreeNode(6); nodeStack.push(root);

Solution sol = new Solution(); /* Pop all items one by one. Do following for every popped item
a) print it
List<Integer> inorder = sol.getInorder(root); b) push its right child
c) push its left child
System.out.print("Binary Tree Morris Inorder Traversal: "); Note that right child is pushed first so that left is processed first */
for (int i = 0; i < inorder.size(); i++) { }
System.out.print(inorder.get(i) + " ");
} PostOrder 2 stacks
System.out.println(); class GfG {
}
} // Function to do post-order traversal
// using two stacks

Implementation 13 Implementation 14

static ArrayList<Integer> postOrder(Node root) {


ArrayList<Integer> result = new ArrayList<>(); return result;
if (root == null) { }
return result;
} Postorder 1 stack

// Create two stacks static List<Integer> postOrder(Node root) {


Stack<Node> stk1 = new Stack<>(); // Check if the tree is empty
Stack<Node> stk2 = new Stack<>(); if (root == null)
return new ArrayList<>();
// Push root to first stack
stk1.push(root); Node curr = root;
Node curr; Stack<Node> stack = new Stack<>();
List<Integer> postorder = new ArrayList<>();
// Run while first stack is not empty
while (!stk1.isEmpty()) { // Traverse the tree until
// current node is not null
// Pop from stk1 and push it to stk2 // or the stack is not empty
curr = stk1.pop(); while (curr != null || !stack.isEmpty()) {
stk2.push(curr); // If current node is not null,
// push it onto the stack
// Push left and right children of // and move to its left child
// the popped node if (curr != null) {
if (curr.left != null) { stack.push(curr);
stk1.push(curr.left); curr = curr.left;
} } else {
if (curr.right != null) { // If current node is null,
stk1.push(curr.right); // check the right child of the
} // top node in the stack
} Node temp = stack.peek().right;

// Collect all elements from second stack // If right child is also null
while (!stk2.isEmpty()) { // or already visited, it means
curr = stk2.pop(); // we can process the top node now
result.add(curr.data); if (temp == null) {
} // Get the top node from stack

Implementation 15 Implementation 16
temp = stack.pop();
// Add the node's data to // Change the prev for subsequent node
// the postorder traversal list next = node;
postorder.add(temp.data);
// Finally, set the next pointer in left subtree
// Check if there are more populateNext(node.left);
// nodes to pop whose right }
// subtree is also processed }
while (!stack.isEmpty() && temp == stack.peek().right) {
temp = stack.pop();
postorder.add(temp.data); //min max tournament
} ```
} else { static Pair getMinMax(int arr[], int low, int high)
// If right child exists, {
// set current node to it Pair minmax =new Pair();
curr = temp; Pair mml =new Pair();
} Pair mmr =new Pair();
} int mid;
}
// Return the list containing the // If there is only one elementif (low == high) {
// Postorder Traversal Sequence minmax.max = arr[low];
return postorder; minmax.min = arr[low];
} return minmax;
}
// Java program to populate inorder successor of all nodes
void populateNext(Node node) /* If there are two elements */if (high == low + 1) {
{ if (arr[low] > arr[high]) {
// The first visited node will be the rightmost node minmax.max = arr[low];
// next of the rightmost node will be NULL minmax.min = arr[high];
if (node != null) { }
// First set the next pointer in right subtree else {
populateNext(node.right); minmax.max = arr[high];
minmax.min = arr[low];
// Set the next as previously visited node in }
// reverse Inorder return minmax;
node.next = next; }

Implementation 17 Implementation 18

Remove: remove(), removeFirst(), removeLast(), clear()


/* If there are more than 2 elements */ mid = (low + high) / 2; Access: get(), getFirst(), getLast(), peek(), peekFirst(), peekLast()
mml = getMinMax(arr, low, mid); Search: contains(), indexOf(), lastIndexOf()
mmr = getMinMax(arr, mid + 1, high); Queue/Deque: offer(), offerFirst(), offerLast(), poll(), pollFirst(), pollLast()
Utility: size(), isEmpty(), toArray(), iterator()
/* compare minimums of two parts*/if (mml.min < mmr.min) {
minmax.min = mml.min; LinkedList<String> list = new LinkedList<>();
} for (String element : list) {
else { System.out.println(element);
minmax.min = mmr.min; }
}
Iterator<String> iterator = list.iterator();
/* compare maximums of two parts*/if (mml.max > mmr.max) { while (iterator.hasNext()) {
minmax.max = mml.max; System.out.println(iterator.next());
} }
else {
minmax.max = mmr.max; Stacks/queue
}
Longest Valid Parentheses Substring

return minmax; Stack Methods in Java:


}
Stack<String> stack = new Stack<>();
BST
Push/Pop: push(E item) , pop() – Add and remove elements.
https://www.geeksforgeeks.org/print-common-nodes-in-two-binary-search-
trees/ Peek: peek() – View the top element without removing.

https://www.geeksforgeeks.org/construct-bst-from-given-preorder- Search: search(Object o) – Find the position of an element.


traversa/#efficient-pass-range-in-recursion
Queue Methods in Java:
https://www.geeksforgeeks.org/fix-two-swapped-nodes-of-bst/#expected-
Add/Remove: add(E e) , offer(E e) , poll() , remove() – Add and remove elements.
approach-using-one-traversal-on-time-and-oh-space
Peek/Element: peek() , element() – View the front element without removing.
Linked List
Size: size() , isEmpty() – Check the number of elements and if the queue is
LinkedList<String> l =new LinkedList<String>(); empty.

Deque Methods in Java:


Add/Update: add(), addFirst(), addLast(), set()

Implementation 19 Implementation 20
final K key;
Deque<String> deque = new LinkedList<>(); V value;
Node&lt;K, V&gt; next;
Add/Remove: addFirst(E e) , addLast(E e) , offerFirst(E e) , offerLast(E e) , removeFirst() ,
removeLast() , pollFirst() , pollLast() – Add or remove elements from both ends.
Node(K key, V value, Node&lt;K, V&gt; next) {
Peek: peekFirst() , peekLast() – View the first or last element without removing. this.key = key;
this.value = value;
Access: getFirst() , getLast() – Retrieve the first or last element.
this.next = next;
Size: size() , isEmpty() – Check the number of elements and if the deque is }
empty. }

Hashmap
private int hash(K key) {
Working return key.hashCode() % capacity;
}
public class MyHashMap<K, V> {
private static final int DEFAULT_CAPACITY = 16;
private static final float DEFAULT_LOAD_FACTOR = 0.75f; public void put(K key, V value) {
int index = hash(key);
Node<K, V> node = table[index];
private int capacity; while (node != null) {
private float loadFactor; if (node.key.equals(key)) {
private int size; node.value = value;
private Node&lt;K, V&gt;[] table; return;
}
public MyHashMap() { node = node.next;
this(DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR); }
} Node<K, V> newNode = new Node<>(key, value);
newNode.next = table[index];
table[index] = newNode;
public MyHashMap(int capacity, float loadFactor) { size++;
this.capacity = capacity; if (size > capacity * loadFactor) {
this.loadFactor = loadFactor; resize();
this.table = (Node&lt;K, V&gt;[]) new Node[capacity]; }
} }

private static class Node&lt;K, V&gt; {

Implementation 21 Implementation 22

public V get(K key) { while (node != null) {


int index = hash(key); Node<K, V> next = node.next;
Node&lt;K, V&gt; node = table[index]; int index = hash(node.key);
while (node != null) { node.next = newTable[index];
if (node.key.equals(key)) { newTable[index] = node;
return node.value; node = next;
} }
node = node.next; }
} table = newTable;
return null; capacity = newCapacity;
} }

public void remove(K key) { }


int index = hash(key);
Node&lt;K, V&gt; node = table[index]; Strings
Node&lt;K, V&gt; prev = null;
https://www.geeksforgeeks.org/longest-palindromic-substring/
while (node != null) {
if (node.key.equals(key)) { https://www.geeksforgeeks.org/find-the-smallest-window-in-a-string-
if (prev == null) { containing-all-characters-of-another-string/
table[index] = node.next; Arrays
} else {
https://www.geeksforgeeks.org/sort-an-array-of-0s-1s-and-2s/
prev.next = node.next;
} Find zeroes to be flipped so that no of 1 is maximum
size--;
return;
}
prev = node;
node = node.next;
}
}

private void resize() {


int newCapacity = capacity * 2;
Node<K, V>[] newTable = new Node[newCapacity];
for (int i = 0; i < capacity; i++) {
Node<K, V> node = table[i];

Implementation 23 Implementation 24

You might also like