├── .gitignore ├── Algorithms ├── Factorial.java ├── LeapYear.java ├── SubsetsOfArray.java ├── PascalTriangle.java ├── SeiveOfEratosthenes.java ├── number_swapping.java ├── Gcd.java ├── Anagram.java ├── BubbleSort.java ├── recursiveBinarysearch.java ├── Pattern Search Algorithm( Naive algorithm) ├── Kernighan'sAlgorithm_22.java ├── KadaneAlgorithm.java ├── ArrayRotation.java ├── LongestPallindromicSubsequenc.java ├── Huffman.java ├── BalancedBrackets.java ├── PrimsAlgorithm.java ├── EqualSumPartition.java ├── SuffixArray.java └── matrixProblems.java ├── Tree ├── binarySearchTree │ ├── TreeNode.java │ └── Bst.java ├── Second_Minimum_In_Binary_Tree.java ├── BFSTree.java ├── Lowest Common Ancestor.java └── AVLtree.java ├── Graph ├── Description ├── Graph.java ├── DFSgraph.java ├── BFSgraph.java ├── DFS │ └── DFS.java ├── BFS │ └── BFS.java ├── Single_source_Shortest Path ├── Cyclic_detection └── k_cores.java ├── Sorting ├── Insertion.java ├── Bubble.java ├── Selection.java ├── BubbleSort.java ├── selectionSort.java ├── CocktailSort.java ├── CountingSort.java ├── Frequency_Sort.java ├── InsertionSort.java ├── RadixSort.java ├── heap sort.java ├── quick sort.java ├── IterativeMergeSort.java ├── merge sort.java ├── TopologicalSort.java ├── shellSort.java ├── Randomized_Quick_Sort.java └── partition.java ├── linkedList ├── ListNode.java ├── LinkedListasQueue.java ├── removeNthNodeFromEnd.java ├── SinglyLinkedList.java ├── CircularLinkedList.java └── DoubleLinkedList ├── maximumsumsubbarray.java ├── Searching ├── BinarySearch.java ├── recursiveBinarysearch.java ├── Exponential Search ├── linearSearch.java └── JumpSearch.java ├── binaryPalindrome.java ├── EulerTour.java ├── README.md ├── Stack └── Stack.java ├── Bipartite.java ├── KMP_String_Matching.java ├── Queue └── Queue.java ├── Boggle.java ├── AESencryption.java ├── Backtracking.java ├── Interview Questions └── Questions.md └── Minimum_spanning_tree.java /.gitignore: -------------------------------------------------------------------------------- 1 | tmp 2 | dist 3 | dump.rdb 4 | .idea 5 | /.idea 6 | /.idea_modules 7 | /.classpath 8 | /.project 9 | /.settings 10 | /RUNNING_PID 11 | /.DS_Store 12 | 13 | /coverage -------------------------------------------------------------------------------- /Algorithms/Factorial.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class Factorial{ 3 | 4 | public static void main(String args[]) 5 | { 6 | Scanner s=new Scanner(System.in); 7 | int n=s.nextInt(); 8 | long f=1; 9 | 10 | for(int i=1;i<=n;i++) 11 | f=f*i; 12 | System.out.println(f); 13 | 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /Tree/binarySearchTree/TreeNode.java: -------------------------------------------------------------------------------- 1 | public class TreeNode { 2 | int val; 3 | TreeNode left; 4 | TreeNode right; 5 | 6 | TreeNode() { 7 | } 8 | 9 | TreeNode(int val) { 10 | this.val = val; 11 | } 12 | 13 | TreeNode(int val, TreeNode left, TreeNode right) { 14 | this.val = val; 15 | this.left = left; 16 | this.right = right; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Algorithms/LeapYear.java: -------------------------------------------------------------------------------- 1 | package Algorithms; 2 | 3 | import java.util.Scanner; 4 | 5 | public class LeapYear { 6 | 7 | public static void main(String[] args){ 8 | 9 | Scanner scan = new Scanner(System.in); 10 | int year = scan.nextInt(); 11 | 12 | if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) { 13 | System.out.println("Leap"); 14 | } else { 15 | System.out.println("Regular"); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Graph/Description: -------------------------------------------------------------------------------- 1 | 1) Find k-cores of an undirected graph 2 | 3 | Given a graph G and an integer K, K-cores of the graph are connected components that are left after all vertices of degree less than k have been removed. 4 | 5 | 2) Count all possible paths between two vertices 6 | 7 | Count the total number of ways or paths that exist between two vertices in a directed graph. 8 | These paths don’t contain a cycle, the simple enough reason is that a cycle contains an infinite number of paths and hence they create a problem 9 | -------------------------------------------------------------------------------- /Algorithms/SubsetsOfArray.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | import java.io.*; 4 | 5 | public class SubsetsOfArray 6 | { 7 | public static void main (String[] args) throws java.lang.Exception 8 | { 9 | Scanner sc = new Scanner(System.in); 10 | int n = sc.nextInt(); 11 | int arr[] = new int[n]; 12 | for(int i=0;i0){ 19 | System.out.print(arr[j]+" "); 20 | } 21 | } 22 | System.out.println("}"); 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /Sorting/Insertion.java: -------------------------------------------------------------------------------- 1 | package Sorting; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Insertion { 6 | static Scanner sc=new Scanner(System.in); 7 | public static void sort(int [] array) { 8 | int n=array.length,j; 9 | for(int i=1;i=0 && temp=1;k--){ 16 | System.out.print(" "); 17 | } 18 | for(int j=0;j<=i;j++){ 19 | System.out.print(m[j]+" "); 20 | } 21 | System.out.println(); 22 | p--; 23 | for(int j=i+1;j>0;j--){ 24 | m[j] = m[j] + m[j-1]; 25 | } 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /Algorithms/SeiveOfEratosthenes.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | import java.io.*; 4 | 5 | public class SeiveOfEratosthenes 6 | { 7 | public static void main (String[] args) throws java.lang.Exception 8 | { 9 | Scanner sc = new Scanner(System.in); 10 | int n = sc.nextInt(); 11 | boolean prime[] = new boolean[n+1]; 12 | for(int i=0;i[] adj; 7 | 8 | public Graph(int V) { 9 | this.V = V; 10 | this.E = 0; 11 | 12 | this.adj = new LinkedList[this.V]; 13 | for(int i = 0; i < V; i++) { 14 | this.adj[i] = new LinkedList<>(); 15 | } 16 | } 17 | 18 | public void addEdge(int s, int d) { 19 | this.adj[s].add(d); 20 | this.adj[d].add(s); 21 | this.E++; 22 | } 23 | 24 | public LinkedList adj(int v) { 25 | return this.adj[v]; 26 | } 27 | 28 | public int V() { 29 | return this.V; 30 | } 31 | 32 | public int E() { 33 | return this.E; 34 | } 35 | } -------------------------------------------------------------------------------- /Algorithms/Anagram.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | import java.io.*; 4 | 5 | public class Anagram 6 | { 7 | public static void main (String[] args) throws java.lang.Exception 8 | { 9 | Scanner sc = new Scanner(System.in); 10 | String a = sc.next(); 11 | String b = sc.next(); 12 | boolean isAnagram = true; 13 | int al[] = new int[256]; 14 | for(char c:a.toCharArray()){ 15 | int index = (int)c; 16 | al[index]++; 17 | } 18 | for(char c:b.toCharArray()){ 19 | int index = (int)c; 20 | al[index]--; 21 | } 22 | for(int i=0;i<256;i++){ 23 | if(al[i]!=0){ 24 | isAnagram=false; 25 | break; 26 | } 27 | } 28 | if (isAnagram){ 29 | System.out.println("Anagram"); 30 | } 31 | else{ 32 | System.out.println("Not Anagram"); 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /linkedList/ListNode.java: -------------------------------------------------------------------------------- 1 | public class ListNode { 2 | int val; 3 | ListNode next; 4 | 5 | ListNode() { 6 | } 7 | 8 | ListNode(int val) { 9 | this.val = val; 10 | this.next = null; 11 | } 12 | 13 | ListNode(int val, ListNode next) { 14 | this.val = val; 15 | this.next = next; 16 | } 17 | 18 | 19 | public static ListNode createArray(int[] a) { 20 | 21 | if (a.length == 0) { 22 | return null; 23 | } 24 | 25 | ListNode root = new ListNode(a[0]); 26 | ListNode cur = root; 27 | 28 | for (int j = 1; j < a.length; j++) { 29 | ListNode temp = new ListNode(a[j]); 30 | cur.next = temp; 31 | cur = cur.next; 32 | } 33 | 34 | return root; 35 | } 36 | } -------------------------------------------------------------------------------- /Algorithms/BubbleSort.java: -------------------------------------------------------------------------------- 1 | 2 | public class BubbleSorting{ 3 | 4 | 5 | 6 | public static void main(String[] args) { 7 | int arr[] ={3,60,35,2,45,320,5}; 8 | 9 | int n = arr.length; 10 | int temp = 0; 11 | for(int i=0; i < n; i++){ 12 | for(int j=1; j < (n-i); j++){ 13 | if(arr[j-1] > arr[j]){ 14 | //swap elements 15 | temp = arr[j-1]; 16 | arr[j-1] = arr[j]; 17 | arr[j] = temp; 18 | } 19 | } 20 | 21 | } 22 | 23 | for(int i=0; i < arr.length; i++){ 24 | System.out.print(arr[i] + " "); 25 | } 26 | 27 | 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /maximumsumsubbarray.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | class maximumsumsubbarray{ 3 | public static void main(String[] args){ 4 | Scanner sc=new Scanner(System.in); 5 | int T=sc.nextInt(); 6 | for(int t=1;t<=T;t++){ 7 | int N=sc.nextInt(); 8 | int A[]=new int[N]; 9 | for(int i=0;i languages = new LinkedList<>(); 7 | 8 | // add elements 9 | languages.add("Python"); 10 | languages.add("Java"); 11 | languages.add("C"); 12 | System.out.println("LinkedList: " + languages); 13 | 14 | // access the first element 15 | String str1 = languages.peek(); 16 | System.out.println("Accessed Element: " + str1); 17 | 18 | // access and remove the first element 19 | String str2 = languages.poll(); 20 | System.out.println("Removed Element: " + str2); 21 | System.out.println("LinkedList after poll(): " + languages); 22 | 23 | // add element at the end 24 | languages.offer("Swift"); 25 | System.out.println("LinkedList after offer(): " + languages); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Searching/BinarySearch.java: -------------------------------------------------------------------------------- 1 | package Searching; 2 | import java.util.Arrays; 3 | import java.util.Scanner; 4 | public class BinarySearch { 5 | static Scanner sc=new Scanner(System.in); 6 | public static void main(String[] args) { 7 | // TODO Auto-generated method stub 8 | int n=sc.nextInt();//size of array 9 | int array[]=new int[n];//array declaration 10 | for(int i=0;iui)break; 23 | else if(search>array[curin]) 24 | li=curin+1; 25 | else 26 | ui=curin-1; 27 | } 28 | if(found)System.out.println("Yes"); 29 | else 30 | System.out.println("No"); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /Algorithms/recursiveBinarysearch.java: -------------------------------------------------------------------------------- 1 | package Searching; 2 | import Sorting.Selection; 3 | import java.util.Scanner; 4 | 5 | public class recursiveBinarysearch { 6 | static Scanner sc=new Scanner(System.in); 7 | public static int search(int array[],int key,int li,int ui) { 8 | int curindex=(li+ui)/2; 9 | if(li>ui)return -1; 10 | if(array[curindex]==key)return key; 11 | else if(key>array[curindex])return search(array,key,curindex+1,ui); 12 | else 13 | return search(array,key,li,curindex-1); 14 | } 15 | public static void main(String[] args) { 16 | // TODO Auto-generated method stub 17 | int n=sc.nextInt(); 18 | int array[]=new int[n]; 19 | for(int i=0;iui)return -1; 10 | if(array[curindex]==key)return key; 11 | else if(key>array[curindex])return search(array,key,curindex+1,ui); 12 | else 13 | return search(array,key,li,curindex-1); 14 | } 15 | public static void main(String[] args) { 16 | // TODO Auto-generated method stub 17 | int n=sc.nextInt(); 18 | int array[]=new int[n]; 19 | for(int i=0;i 0, subtract by 1 and do bitwise & with (9-1) 34 | n = 9&8 (1001 & 1000) 35 | n = 8 36 | count = 1 37 | 38 | Since 8 > 0, subtract by 1 and do bitwise & with (8-1) 39 | n = 8&7 (1000 & 0111) 40 | n = 0 41 | count = 2 42 | 43 | Since n = 0, return count which is 2 now. 44 | */ 45 | -------------------------------------------------------------------------------- /Sorting/BubbleSort.java: -------------------------------------------------------------------------------- 1 | // Java program for implementation of Bubble Sort 2 | 3 | public class BubbleSort 4 | { 5 | void bubbleSort(int arr[]) 6 | { 7 | int n = arr.length; 8 | boolean swapped; 9 | for (int i = 0; i < n-1; i++){ 10 | swapped=false; 11 | for (int j = 0; j < n-i-1; j++) 12 | if (arr[j] > arr[j+1]) 13 | { 14 | // swap temp and arr[i] 15 | int temp = arr[j]; 16 | arr[j] = arr[j+1]; 17 | arr[j+1] = temp; 18 | swapped=true; 19 | } 20 | if(!swapped){ 21 | break; 22 | } 23 | } 24 | } 25 | 26 | /* Prints the array */ 27 | void printArray(int arr[]) 28 | { 29 | int n = arr.length; 30 | for (int i=0; i arr) 9 | { 10 | int n = arr.size(); 11 | for (int i = 0; i < n-1; i++) 12 | { 13 | int min_idx = i; 14 | for (int j = i+1; j < n; j++) 15 | if (arr.get(j) < arr.get(min_idx)) 16 | min_idx = j; 17 | 18 | int temp = arr.get(min_idx); 19 | arr.set(min_idx, arr.get(i)); 20 | arr.set(i,temp); 21 | } 22 | } 23 | 24 | public static void main(String args[]) throws IOException 25 | { 26 | SelectionSort obj = new SelectionSort(); 27 | String pathToFile = "./Sorting/unsorted.txt"; 28 | File unsorted = new File(pathToFile); 29 | Scanner sc = new Scanner(unsorted); 30 | sc.useDelimiter(","); 31 | ArrayList arr = new ArrayList(); 32 | while(sc.hasNext()){ 33 | arr.add(sc.nextInt()); 34 | } 35 | obj.sorting(arr); 36 | System.out.println("Sorted array"); 37 | 38 | System.out.println( arr); 39 | sc.close(); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Algorithms/KadaneAlgorithm.java: -------------------------------------------------------------------------------- 1 | //task of finding the largest possible sum of a contiguous subarray, within a given one-dimensional array A[1…n] of numbers. 2 | 3 | class KadaneAlgorithm { 4 | 5 | static void maxSubArraySum(int a[], int size) 6 | { 7 | int max_so_far = Integer.MIN_VALUE, 8 | max_ending_here = 0,start = 0, 9 | end = 0, s = 0; 10 | 11 | for (int i = 0; i < size; i++) 12 | { 13 | max_ending_here += a[i]; 14 | 15 | if (max_so_far < max_ending_here) 16 | { 17 | max_so_far = max_ending_here; 18 | start = s; 19 | end = i; 20 | } 21 | 22 | if (max_ending_here < 0) 23 | { 24 | max_ending_here = 0; 25 | s = i + 1; 26 | } 27 | } 28 | System.out.println("Maximum contiguous sum is " 29 | + max_so_far); 30 | System.out.println("Starting index " + start); 31 | System.out.println("Ending index " + end); 32 | } 33 | 34 | // Driver code 35 | public static void main(String[] args) 36 | { 37 | int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 }; 38 | int n = a.length; 39 | maxSubArraySum(a, n); 40 | } 41 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Java Algorithms ☕ 2 | 3 | ![](https://img.shields.io/badge/Java-Algos-red) ![](https://img.shields.io/badge/Hacktoberfest-2020-brightgreen) ![](https://img.shields.io/github/issues/anku580/Java-Algorithms) ![](https://img.shields.io/github/issues-pr-closed/anku580/Java-Algorithms)![](https://img.shields.io/github/stars/anku580/Java-Algorithms?style=social) ![](https://img.shields.io/github/forks/anku580/Java-Algorithms?style=social) 4 | 5 | ### 👋 Hi coders !!! 6 | 7 | This Hactoberfest, we have brought you this repo where you can contribute your Java Algorithms. So, contribute here and get a chance to win Hacktoberfest Tees. 👕 8 |
9 | 10 | ### Algos added till now.. 11 | 12 | * [Binary Search Tree](/binarySearchTree/TreeNode.java) 13 | * [Linked List](/linkedList/ListNode.java) 14 | * [BFS Graph](/BFSgraph.java) 15 | * [Bipartite](/Bipartite.java) 16 | * [Bubble Sort](/BubbleSort.java) 17 | * [DFS Graph](/DFSgraph.java) 18 | * [Euler Tour](/EulerTour.java) 19 | * [Factorial](/Factorial.java) 20 | * [Greates Common Divisor](Gcd.java) 21 | * [Graph](Graph.java) 22 | * [Insertion Sort](InsertionSort.java) 23 | * [Prims Algo](/PrimsAlgorithm.java) 24 | * [Randomised Quick Sort](/Randomized_Quick_Sort.java) 25 | * [Selection Sort](selectionSort.java) 26 | 27 | 28 | ### Happy Coding 👩‍💻👨‍💻 -------------------------------------------------------------------------------- /Sorting/CocktailSort.java: -------------------------------------------------------------------------------- 1 | public class CocktailSort 2 | { 3 | 4 | public static void cocktailSort(Integer[] inputArrays, 5 | Integer n) 6 | { 7 | Boolean swapped = Boolean.TRUE; 8 | Integer start = 0; 9 | Integer end = inputArrays.length; 10 | 11 | while (swapped) { 12 | swapped = Boolean.FALSE; 13 | 14 | for (int i = start; i < end - 1; ++i) { 15 | if (inputArrays[i] > inputArrays[i + 1]) { 16 | int temp = inputArrays[i]; 17 | inputArrays[i] = inputArrays[i + 1]; 18 | inputArrays[i + 1] = temp; 19 | swapped = Boolean.TRUE; 20 | } 21 | } 22 | 23 | if (!swapped) { 24 | break; 25 | } 26 | 27 | swapped = Boolean.FALSE; 28 | end--; 29 | 30 | for (int i = end - 1; i >= start; i--) { 31 | if (inputArrays[i] > inputArrays[i + 1]) { 32 | int temp = inputArrays[i]; 33 | inputArrays[i] = inputArrays[i + 1]; 34 | inputArrays[i + 1] = temp; 35 | swapped = Boolean.TRUE; 36 | } 37 | } 38 | 39 | start++; 40 | } 41 | } 42 | 43 | } -------------------------------------------------------------------------------- /Stack/Stack.java: -------------------------------------------------------------------------------- 1 | // Java code for stack implementation 2 | 3 | import java.io.*; 4 | import java.util.*; 5 | 6 | class Test 7 | { 8 | 9 | static void stack_push(Stack stack) 10 | { 11 | for(int i = 0; i < 5; i++) 12 | { 13 | stack.push(i); 14 | } 15 | } 16 | 17 | 18 | static void stack_pop(Stack stack) 19 | { 20 | System.out.println("Pop Operation:"); 21 | 22 | for(int i = 0; i < 5; i++) 23 | { 24 | Integer y = (Integer) stack.pop(); 25 | System.out.println(y); 26 | } 27 | } 28 | 29 | 30 | static void stack_peek(Stack stack) 31 | { 32 | Integer element = (Integer) stack.peek(); 33 | System.out.println("Element on stack top: " + element); 34 | } 35 | 36 | 37 | static void stack_search(Stack stack, int element) 38 | { 39 | Integer pos = (Integer) stack.search(element); 40 | 41 | if(pos == -1) 42 | System.out.println("Element not found"); 43 | else 44 | System.out.println("Element is found at position: " + pos); 45 | } 46 | 47 | 48 | public static void main (String[] args) 49 | { 50 | Stack stack = new Stack(); 51 | 52 | stack_push(stack); 53 | stack_pop(stack); 54 | stack_push(stack); 55 | stack_peek(stack); 56 | stack_search(stack, 2); 57 | stack_search(stack, 6); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /Sorting/CountingSort.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.InputStreamReader; 3 | import java.util.Arrays; 4 | 5 | class CountSort{ 6 | public static void main(String[] args) throws Exception { 7 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 8 | System.out.println("Enter the size of Array to be sorted"); 9 | int n = Integer.parseInt(br.readLine()); 10 | System.out.println("Enter the Array to be sorted"); 11 | int[] arr = new int[n]; 12 | String[] integerStrings = br.readLine().split(" "); 13 | for (int i = 0; i < arr.length; i++) { 14 | arr[i] = Integer.parseInt(integerStrings[i]); 15 | } 16 | int k = 60; 17 | 18 | countingSort(arr, k); 19 | 20 | System.out.println("Sorted Array :- "); 21 | System.out.println(Arrays.toString(arr)); 22 | 23 | } 24 | 25 | static void countingSort(int[] input, int k) { 26 | // create buckets 27 | int count[] = new int[k + 1]; 28 | 29 | for (int i : input) { 30 | count[i]++; 31 | } 32 | 33 | int ndx = 0; 34 | for (int i = 0; i < count.length; i++) { 35 | while (0 < count[i]) { 36 | input[ndx++] = i; 37 | count[i]--; 38 | } 39 | } 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /Sorting/Frequency_Sort.java: -------------------------------------------------------------------------------- 1 | /* 2 | This class implements sorting Strings based on their frequency. 3 | The frequency is stored in the HashMap> 4 | Where the ArrayList contains three items - Scores, Id, Correction 5 | */ 6 | import java.io.*; 7 | import java.util.HashMap; 8 | import java.util.Comparator; 9 | import java.util.ArrayList; 10 | public class PlaylistSort implements Comparator{ 11 | int SCORES_INDEX = 0; 12 | int TIE_INDEX = 2; 13 | private HashMap> frequency = new HashMap>(); 14 | public PlaylistSort(HashMap> arr) { 15 | frequency = arr; 16 | } 17 | public int compare(String s1, String s2) { 18 | if(frequency.get(s1).get(SCORES_INDEX) < frequency.get(s2).get(SCORES_INDEX)) { 19 | return 1; 20 | } 21 | else if(frequency.get(s1).get(SCORES_INDEX) > frequency.get(s2).get(SCORES_INDEX)) { 22 | return -1; 23 | } 24 | else { 25 | //If two playlists have the same score, we need to break the tie..so we compare the tie scores.. 26 | if((frequency.get(s1).get(TIE_INDEX)) < (frequency.get(s2).get(TIE_INDEX))) { 27 | return 1; 28 | } 29 | else if((frequency.get(s1).get(TIE_INDEX)) > (frequency.get(s2).get(TIE_INDEX))) { 30 | return -1; 31 | } 32 | else { 33 | return 0; 34 | } 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Sorting/InsertionSort.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Scanner; 3 | 4 | 5 | public class InsertionSort 6 | { 7 | public static void sort( int arr[] ) 8 | { 9 | int N = arr.length; 10 | int i, j, temp; 11 | for (i = 1; i< N; i++) 12 | { 13 | j = i; 14 | temp = arr[i]; 15 | while (j > 0 && temp < arr[j-1]) 16 | { 17 | arr[j] = arr[j-1]; 18 | j = j-1; 19 | } 20 | arr[j] = temp; 21 | } 22 | } 23 | 24 | public static void main(String[] args) 25 | { 26 | Scanner scan = new Scanner( System.in ); 27 | System.out.println("Insertion Sort Test\n"); 28 | int n, i; 29 | 30 | System.out.println("Enter number of integer elements"); 31 | n = scan.nextInt(); 32 | 33 | int arr[] = new int[ n ]; 34 | 35 | System.out.println("\nEnter "+ n +" integer elements"); 36 | for (i = 0; i < n; i++) 37 | arr[i] = scan.nextInt(); 38 | 39 | sort(arr); 40 | 41 | System.out.println("\nElements after sorting "); 42 | for (i = 0; i < n; i++) 43 | System.out.print(arr[i]+" "); 44 | System.out.println(); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Algorithms/ArrayRotation.java: -------------------------------------------------------------------------------- 1 | class ArrayRotation { 2 | public static void main(String[] args) { 3 | 4 | //Making scanner class for user input 5 | Scanner sc = new Scanner(System.in); 6 | 7 | //Taking user input for n that determine the number of times an array should be rotated. 8 | int n = sc.nextInt(); 9 | 10 | //Taking user input for d that is the size of the array. 11 | int d = sc.nextInt(); 12 | 13 | //Taking array by user of size d 14 | int [] arr = new int [d]; 15 | for(int i = 0;i < d; i++) { 16 | arr[i] = sc.nextInt(); 17 | } 18 | 19 | 20 | //Rotate the given array by n times 21 | for(int i = 0; i < n; i++){ 22 | int j, temp; 23 | //Stores the last element of array in temp 24 | temp = arr[arr.length-1]; 25 | 26 | for(j = arr.length-1; j > 0; j--){ 27 | //Shifting element of the array by one position 28 | arr[j] = arr[j-1]; 29 | } 30 | //storing temp in last of array 31 | arr[0] = temp; 32 | } 33 | 34 | System.out.println(); 35 | 36 | //Displays array after rotation 37 | for(int e: arr){ 38 | System.out.print(e); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Graph/DFSgraph.java: -------------------------------------------------------------------------------- 1 | import java.util.LinkedList; 2 | import java.util.Stack; 3 | 4 | public class DFSgraph { 5 | 6 | private boolean[] marked; 7 | private int[] edgeTo; 8 | private int s; 9 | public Stack stk = new Stack<>(); 10 | 11 | DFSgraph(Graph g, int s) { 12 | marked = new boolean[g.V()]; 13 | edgeTo = new int[g.V()]; 14 | this.s = s; 15 | 16 | dfs(g, s); 17 | } 18 | 19 | public void dfs(Graph g, int v) { 20 | marked[v] = true; 21 | for (int w : g.adj(v)) { 22 | if (!marked[w]) { 23 | dfs(g, w); 24 | edgeTo[w] = v; 25 | } 26 | } 27 | } 28 | 29 | public void printEle(int d) { 30 | stk.push(d); 31 | do { 32 | stk.push(edgeTo[d]); 33 | d = edgeTo[d]; 34 | } while (d != s); 35 | 36 | while (!stk.isEmpty()) { 37 | System.out.println(stk.pop()); 38 | } 39 | 40 | } 41 | 42 | public static void main(String args[]) { 43 | Graph g = new Graph(7); 44 | g.addEdge(0, 1); 45 | g.addEdge(0, 2); 46 | g.addEdge(0, 5); 47 | g.addEdge(0, 6); 48 | g.addEdge(5, 3); 49 | g.addEdge(5, 4); 50 | g.addEdge(3, 4); 51 | g.addEdge(4, 6); 52 | 53 | DFSgraph d = new DFSgraph(g, 0); 54 | d.printEle(3); 55 | } 56 | } -------------------------------------------------------------------------------- /Tree/Second_Minimum_In_Binary_Tree.java: -------------------------------------------------------------------------------- 1 | /* 2 | This code has been written by - Amrit Raj 3 | 4 | This is a functional code with the following specifications:- 5 | Arguments - Root node of the Tree defined by class TreeNode 6 | Return - An int signifying the second minimum node in the given tree. In case 7 | it is not found, it returns -1 8 | */ 9 | 10 | public int findSecondMinimumValue(TreeNode root) { 11 | //A queue to store the nodes.. 12 | Queue q = new ArrayDeque<>(); 13 | if (root == null) 14 | return -1; 15 | int min = root.val; 16 | int secondMin = Integer.MAX_VALUE; 17 | boolean found = false; 18 | 19 | q.add(root); 20 | while (!q.isEmpty()) { 21 | int size = q.size(); 22 | for (int i = 0; i < size; i++) { 23 | TreeNode node = q.poll(); 24 | if (node.val > min) { 25 | secondMin = Math.min(node.val, secondMin); 26 | found = true; 27 | continue; 28 | } 29 | //Left subtree.. 30 | if (node.left != null && node.left.val <= secondMin) 31 | q.add(node.left); 32 | //Right Subtree 33 | if (node.right != null && node.right.val <= secondMin) 34 | q.add(node.right); 35 | } 36 | } 37 | //Returning second min, else -1... 38 | return found? secondMin : -1; 39 | } 40 | -------------------------------------------------------------------------------- /Graph/BFSgraph.java: -------------------------------------------------------------------------------- 1 | import java.util.LinkedList; 2 | import java.util.Stack; 3 | 4 | import sun.misc.Queue; 5 | 6 | public class BFSgraph { 7 | 8 | private boolean[] marked; 9 | private int[] edgeTo; 10 | private int s; 11 | public Queueque = new Queue<>(); 12 | 13 | DFSgraph(Graph g, int s) { 14 | marked = new boolean[g.V()]; 15 | edgeTo = new int[g.V()]; 16 | this.s = s; 17 | 18 | bfs(g, s); 19 | } 20 | 21 | public void bfs(Graph g, int v) { 22 | que.push(v); 23 | 24 | while(que.isEmpty()) 25 | { 26 | int vert = que.pop(); 27 | marked[vert] = true; 28 | for(int w : g.adj(vert)) 29 | { 30 | if(!marked[w]) { 31 | que.push(w); 32 | edgeTo[w] = v; 33 | } 34 | } 35 | } 36 | } 37 | 38 | public void printEle(int d) { 39 | int i = d; 40 | while(i != s) { 41 | System.out.println(i); 42 | i = edgeTo[i]; 43 | } 44 | } 45 | 46 | 47 | public static void main(String args[]) { 48 | Graph g = new Graph(7); 49 | g.addEdge(0, 1); 50 | g.addEdge(0, 2); 51 | g.addEdge(0, 5); 52 | g.addEdge(0, 6); 53 | g.addEdge(5, 3); 54 | g.addEdge(5, 4); 55 | g.addEdge(3, 4); 56 | g.addEdge(4, 6); 57 | 58 | BFSgraph d = new BFSgraph(g, 0); 59 | d.printEle(3); 60 | } 61 | } -------------------------------------------------------------------------------- /linkedList/SinglyLinkedList.java: -------------------------------------------------------------------------------- 1 | public class SinglyLinkedList 2 | { 3 | class Node 4 | { 5 | int data; 6 | Node next; 7 | 8 | public Node(int data) 9 | { 10 | this.data=data; 11 | this.next=null; 12 | size++; 13 | } 14 | } 15 | 16 | Node head; 17 | Node tail; 18 | int size; 19 | 20 | public SinglyLinkedList() 21 | { 22 | head=null; 23 | tail=null; 24 | size=0; 25 | } 26 | 27 | public void InsertAtTail(int data) 28 | { 29 | Node node =new Node(data); 30 | if(this.head==null) 31 | { 32 | this.head=node; 33 | this.tail=node; 34 | } 35 | else 36 | this.tail.next=node; 37 | this.tail=node; 38 | } 39 | 40 | public void InstertAtHead(int data) 41 | { 42 | Node node=new Node(data); 43 | node.next=head; 44 | head=node; 45 | if(this.tail==null) 46 | this.tail=node; 47 | } 48 | 49 | Boolean isEmpty() 50 | { 51 | return head==null; 52 | } 53 | 54 | public void displayNodes() 55 | { 56 | if(this.isEmpty()) 57 | System.out.println("The list is empty"); 58 | Node temp=this.head; 59 | while(temp.next!=null) 60 | { 61 | System.out.print(temp.data+"->"); 62 | temp=temp.next; 63 | } 64 | System.out.print("end"); 65 | } 66 | public static void main(String[] args) 67 | { 68 | SinglyLinkedList l =new SinglyLinkedList(); 69 | l.InstertAtHead(5); 70 | l.InsertAtTail(6); 71 | l.InstertAtHead(4); 72 | System.out.println("Size of Linked List is: "+l.size); 73 | l.InsertAtTail(3); 74 | l.displayNodes(); 75 | } 76 | 77 | } -------------------------------------------------------------------------------- /Algorithms/LongestPallindromicSubsequenc.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | import java.io.*; 4 | 5 | class LongestPallindromicSubsequenc{ 6 | 7 | int max(int a, int b) 8 | { 9 | return (a>b ? a:b); 10 | } 11 | 12 | int LCS(int n, char[] arr, char[] b){ 13 | 14 | int[][] dp=new int[n+1][n+1]; 15 | 16 | for(int i=0;i0){ 41 | String str=sc.next(); 42 | int n=str.length(); 43 | char[] arr=str.toCharArray(); 44 | char[] b=new char[n]; 45 | 46 | for(int i=0;iqueue = new LinkedList(); 8 | 9 | Bipartite(Graph g,int s) { 10 | 11 | color = new int[g.V()]; 12 | marked = new boolean[g.V()]; 13 | 14 | for ( int i = 0 ; i BFStraversal(TreeNode tree) 21 | { 22 | Queue queue = new LinkedList<>(); 23 | 24 | List list = new ArrayList<>(); 25 | 26 | if(tree == null) 27 | { 28 | return list; 29 | } 30 | 31 | queue.add(tree); 32 | 33 | while(!queue.isEmpty()) 34 | { 35 | TreeNode t = queue.poll(); 36 | list.add(t.val); 37 | 38 | if(t.left != null) 39 | { 40 | queue.add(t.left); 41 | } 42 | if(t.right != null) 43 | { 44 | queue.add(t.right); 45 | } 46 | } 47 | 48 | return list; 49 | 50 | } 51 | } 52 | 53 | class BFSTreeDemo 54 | { 55 | public static void main(String[] args) { 56 | 57 | 58 | BFSTree b = new BFSTree(); 59 | TreeNode tree = null; 60 | tree = new TreeNode(10); 61 | tree.left = new TreeNode(11); 62 | tree.right = new TreeNode(15); 63 | tree.left.left = new TreeNode(16); 64 | tree.right.right = new TreeNode(17); 65 | tree.left.right= new TreeNode(19); 66 | tree.right.left = new TreeNode(20); 67 | System.out.println(b.BFStraversal(tree)); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /KMP_String_Matching.java: -------------------------------------------------------------------------------- 1 | public class KMP_String_Matching { 2 | public static void KMPSearch(String pat, String txt) 3 | { 4 | int M = pat.length(); 5 | int N = txt.length(); 6 | 7 | 8 | int lps[] = new int[M]; 9 | int j = 0; // index for pat[] 10 | 11 | 12 | computeLPSArray(pat, M, lps); 13 | 14 | int i = 0; // index for txt[] 15 | while (i < N) { 16 | if (pat.charAt(j) == txt.charAt(i)) { 17 | j++; 18 | i++; 19 | } 20 | if (j == M) { 21 | System.out.println("Found pattern " 22 | + "at index " + (i - j)); 23 | j = lps[j - 1]; 24 | } 25 | 26 | 27 | else if (i < N && pat.charAt(j) != txt.charAt(i)) { 28 | // Do not match lps[0..lps[j-1]] characters, 29 | // they will match anyway 30 | if (j != 0) 31 | j = lps[j - 1]; 32 | else 33 | i = i + 1; 34 | } 35 | } 36 | } 37 | 38 | void computeLPSArray(String pat, int M, int lps[]) 39 | { 40 | 41 | int len = 0; 42 | int i = 1; 43 | lps[0] = 0; // lps[0] is always 0 44 | 45 | 46 | while (i < M) { 47 | if (pat.charAt(i) == pat.charAt(len)) { 48 | len++; 49 | lps[i] = len; 50 | i++; 51 | } 52 | else // (pat[i] != pat[len]) 53 | { 54 | 55 | if (len != 0) { 56 | len = lps[len - 1]; 57 | 58 | 59 | } 60 | else // if (len == 0) 61 | { 62 | lps[i] = len; 63 | i++; 64 | } 65 | } 66 | } 67 | } 68 | 69 | 70 | public static void main(String args[]) 71 | { 72 | String txt = "ABABDABACDABABCABAB"; 73 | String pat = "ABABCABAB"; 74 | new KMP_String_Matching().KMPSearch(pat, txt); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /Tree/Lowest Common Ancestor.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | 4 | class Node { 5 | Node left; 6 | Node right; 7 | int data; 8 | 9 | Node(int data) { 10 | this.data = data; 11 | left = null; 12 | right = null; 13 | } 14 | } 15 | 16 | class Solution { 17 | 18 | /* 19 | class Node 20 | int data; 21 | Node left; 22 | Node right; 23 | */ 24 | public static Node lca(Node root, int v1, int v2) { 25 | // Write your code here. 26 | if(root == null) return null; 27 | 28 | if(root.data > v1 && root.data > v2) return lca(root.left, v1, v2); 29 | if(root.data < v1 && root.data < v2) return lca(root.right, v1, v2); 30 | 31 | return root; 32 | } 33 | 34 | public static Node insert(Node root, int data) { 35 | if(root == null) { 36 | return new Node(data); 37 | } else { 38 | Node cur; 39 | if(data <= root.data) { 40 | cur = insert(root.left, data); 41 | root.left = cur; 42 | } else { 43 | cur = insert(root.right, data); 44 | root.right = cur; 45 | } 46 | return root; 47 | } 48 | } 49 | 50 | public static void main(String[] args) { 51 | Scanner scan = new Scanner(System.in); 52 | int t = scan.nextInt(); 53 | Node root = null; 54 | while(t-- > 0) { 55 | int data = scan.nextInt(); 56 | root = insert(root, data); 57 | } 58 | int v1 = scan.nextInt(); 59 | int v2 = scan.nextInt(); 60 | scan.close(); 61 | Node ans = lca(root,v1,v2); 62 | System.out.println(ans.data); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /Sorting/RadixSort.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.InputStreamReader; 3 | import java.util.*; 4 | 5 | class Radix { 6 | 7 | static int getMax(int arr[], int n) 8 | { 9 | int mx = arr[0]; 10 | for (int i = 1; i < n; i++) 11 | if (arr[i] > mx) 12 | mx = arr[i]; 13 | return mx; 14 | } 15 | 16 | static void countSort(int arr[], int n, int exp) 17 | { 18 | int output[] = new int[n]; // output array 19 | int i; 20 | int count[] = new int[10]; 21 | Arrays.fill(count, 0); 22 | 23 | for (i = 0; i < n; i++) 24 | count[(arr[i] / exp) % 10]++; 25 | 26 | for (i = 1; i < 10; i++) 27 | count[i] += count[i - 1]; 28 | 29 | for (i = n - 1; i >= 0; i--) { 30 | output[count[(arr[i] / exp) % 10] - 1] = arr[i]; 31 | count[(arr[i] / exp) % 10]--; 32 | } 33 | 34 | for (i = 0; i < n; i++) 35 | arr[i] = output[i]; 36 | } 37 | 38 | static void radixSort(int arr[], int n) { 39 | int m = getMax(arr, n); 40 | 41 | for (int exp = 1; m / exp > 0; exp *= 10) 42 | countSort(arr, n, exp); 43 | } 44 | 45 | 46 | public static void main(String[] args) throws Exception { 47 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 48 | int n = Integer.parseInt(br.readLine()); 49 | int arr[] = new int[n]; 50 | String[] integerStrings = br.readLine().split(" "); 51 | for (int i = 0; i < arr.length; i++) { 52 | arr[i] = Integer.parseInt(integerStrings[i]); 53 | } 54 | radixSort(arr, n); 55 | for (int i = 0; i < n; i++) 56 | System.out.print(arr[i] + " "); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Algorithms/Huffman.java: -------------------------------------------------------------------------------- 1 | // Huffman Coding Algorithm 2 | 3 | import java.util.*; //importing all the classes from the "utility" at a time 4 | 5 | class Node { 6 | int element; 7 | char c; 8 | Node left; 9 | Node right; 10 | } 11 | 12 | class ImplementComparator implements Comparator { 13 | public int compare(Node x, Node y) { 14 | return x.element - y.element; 15 | } 16 | } 17 | 18 | // class implementing the Huffman Algorithm 19 | public class Huffman { 20 | 21 | public static void outCode(Node r, String s) { 22 | if (r.left == null && r.right == null && Character.isLetter(r.c)) { 23 | 24 | System.out.println(r.c + " | " + s); 25 | 26 | return; 27 | } 28 | outCode(r.left, s + "0"); 29 | outCode(r.right, s + "1"); 30 | } 31 | 32 | public static void main(String[] args) { // main method: the execution of the program starts from here 33 | 34 | int n = 4; 35 | char[] cArray = { 'A', 'B', 'C', 'D' }; 36 | int[] cf = { 5, 1, 6, 3 }; 37 | 38 | PriorityQueue k = new PriorityQueue(n, new ImplementComparator()); 39 | 40 | for (int i = 0; i < n; i++) { 41 | Node t = new Node(); 42 | 43 | t.c = cArray[i]; 44 | t.element = cf[i]; 45 | 46 | t.left = null; 47 | t.right = null; 48 | 49 | k.add(t); 50 | } 51 | 52 | Node r = null; 53 | 54 | while (k.size() > 1) { 55 | 56 | Node x = k.peek(); 57 | k.poll(); 58 | 59 | Node y = k.peek(); 60 | k.poll(); 61 | 62 | Node f = new Node(); 63 | 64 | f.element = x.element + y.element; 65 | f.c = '-'; 66 | f.left = x; 67 | f.right = y; 68 | r = f; 69 | 70 | k.add(f); 71 | } 72 | System.out.println(" Char|Huffman code "); 73 | System.out.println("--------------------"); 74 | outCode(r, ""); 75 | } 76 | } -------------------------------------------------------------------------------- /Queue/Queue.java: -------------------------------------------------------------------------------- 1 | class Queue 2 | { 3 | int front, rear, size; 4 | int capacity; 5 | int array[]; 6 | 7 | public Queue(int capacity) { 8 | this.capacity = capacity; 9 | front = this.size = 0; 10 | rear = capacity - 1; 11 | array = new int[this.capacity]; 12 | 13 | } 14 | 15 | 16 | boolean isFull(Queue queue) 17 | { return (queue.size == queue.capacity); 18 | } 19 | 20 | 21 | boolean isEmpty(Queue queue) 22 | { return (queue.size == 0); } 23 | 24 | 25 | void enqueue( int item) 26 | { 27 | if (isFull(this)) 28 | System.out.println("Queue capacity reached"); 29 | this.rear = (this.rear + 1)%this.capacity; 30 | this.array[this.rear] = item; 31 | this.size = this.size + 1; 32 | } 33 | 34 | 35 | void dequeue() 36 | { 37 | if (isEmpty(this)) 38 | System.out.println("The queue is empty"); 39 | this.front = (this.front + 1)%this.capacity; 40 | this.size = this.size - 1; 41 | } 42 | 43 | 44 | int front() 45 | { 46 | if (isEmpty(this)) 47 | return Integer.MIN_VALUE; 48 | 49 | return this.array[this.front]; 50 | } 51 | 52 | 53 | int rear() 54 | { 55 | if (isEmpty(this)) 56 | return Integer.MIN_VALUE; 57 | 58 | return this.array[this.rear]; 59 | } 60 | 61 | public static void main(String[] args) 62 | { 63 | Queue q=new Queue(10); 64 | q.enqueue(5); 65 | q.enqueue(7); 66 | q.enqueue(4); 67 | q.enqueue(3); 68 | System.out.println("front is "+q.front()); 69 | q.dequeue(); 70 | q.dequeue(); 71 | q.dequeue(); 72 | q.dequeue(); 73 | q.dequeue(); 74 | } 75 | } -------------------------------------------------------------------------------- /Searching/JumpSearch.java: -------------------------------------------------------------------------------- 1 | package searching; 2 | import java.util.*; 3 | public class JumpSearch 4 | { 5 | public static void main( String args[]) 6 | { 7 | Scanner sc = new Scanner(System.in); 8 | System.out.println("Enter the size of the array"); 9 | int n = sc.nextInt(); 10 | int[] a = new int[n]; 11 | System.out.println("Enter the elements of the sorted array"); 12 | for(int i=0; i root.val) 40 | root.right=insertnode(root.right, data); 41 | return root; 42 | } 43 | 44 | public Boolean search(int data) 45 | { 46 | TreeNode node=searchnode(this.root,data); 47 | return node!=null; 48 | } 49 | 50 | private TreeNode searchnode(TreeNode root,int data) 51 | { 52 | if (root==null || root.val==data) 53 | return root; 54 | if (root.val>data) 55 | return searchnode(root.left,data); 56 | return searchnode(root.right, data); 57 | } 58 | 59 | public static void main(String[] args) 60 | { 61 | Bst bst=new Bst(); 62 | bst.insert(8); 63 | bst.insert(3); 64 | bst.insert(10); 65 | bst.insert(1); 66 | bst.insert(14); 67 | bst.insert(6); 68 | bst.insert(4); 69 | System.out.println(bst.search(14)?"Found":"Not Found"); 70 | } 71 | } -------------------------------------------------------------------------------- /Boggle.java: -------------------------------------------------------------------------------- 1 | // Java program for Boggle game 2 | class Boggle { 3 | // Let the given dictionary be following 4 | static final String[] dictionary = { "GEEKS", "FOR", "QUIZ", "GUQ", "EE" }; 5 | static final int n = dictionary.length; 6 | static final int M = 3, N = 3; 7 | 8 | // A given function to check if a given string is present in 9 | // dictionary. The implementation is naive for simplicity. As 10 | // per the question dictionary is given to us. 11 | static boolean isWord(String str) 12 | { 13 | // Linearly search all words 14 | for (int i = 0; i < n; i++) 15 | if (str.equals(dictionary[i])) 16 | return true; 17 | return false; 18 | } 19 | 20 | // A recursive function to print all words present on boggle 21 | static void findWordsUtil(char[][] boggle, boolean[][] visited, int i, int j, String str) { 22 | visited[i][j] = true; 23 | str = str + boggle[i][j]; 24 | 25 | if (isWord(str)) 26 | System.out.println(str); 27 | 28 | for (int row = i - 1; row <= i + 1 && row < M; row++) 29 | for (int col = j - 1; col <= j + 1 && col < N; col++) 30 | if (row >= 0 && col >= 0 && !visited[row][col]) 31 | findWordsUtil(boggle, visited, row, col, str); 32 | 33 | str = "" + str.charAt(str.length() - 1); 34 | visited[i][j] = false; 35 | } 36 | 37 | static void findWords(char[][] boggle) 38 | { 39 | boolean[][] visited = new boolean[M][N]; 40 | String str = ""; 41 | 42 | for (int i = 0; i < M; i++) 43 | for (int j = 0; j < N; j++) 44 | findWordsUtil(boggle, visited, i, j, str); 45 | } 46 | 47 | // Driver program to test above function 48 | public static void main(String[] args) 49 | { 50 | char[][] boggle = { { 'G', 'I', 'Z' }, 51 | { 'U', 'E', 'K' }, 52 | { 'Q', 'S', 'E' } }; 53 | 54 | System.out.println("Following words of dictionary are present"); 55 | findWords(boggle); 56 | } 57 | } -------------------------------------------------------------------------------- /Sorting/heap sort.java: -------------------------------------------------------------------------------- 1 | // Implementation of Heap Sort 2 | public class HeapSort 3 | { 4 | public void sort(int arr[]) 5 | { 6 | int n = arr.length; 7 | 8 | // Build heap (rearrange array) 9 | for (int i = n / 2 - 1; i >= 0; i--) 10 | heapify(arr, n, i); 11 | 12 | // One by one extract an element from heap 13 | for (int i=n-1; i>0; i--) 14 | { 15 | // Move current root to end 16 | int temp = arr[0]; 17 | arr[0] = arr[i]; 18 | arr[i] = temp; 19 | 20 | // call max heapify on the reduced heap 21 | heapify(arr, i, 0); 22 | } 23 | } 24 | 25 | // To heapify a subtree rooted with node i which is 26 | // an index in arr[]. n is size of heap 27 | void heapify(int arr[], int n, int i) 28 | { 29 | int largest = i; // Initialize largest as root 30 | int l = 2*i + 1; // left = 2*i + 1 31 | int r = 2*i + 2; // right = 2*i + 2 32 | 33 | // If left child is larger than root 34 | if (l < n && arr[l] > arr[largest]) 35 | largest = l; 36 | 37 | // If right child is larger than largest so far 38 | if (r < n && arr[r] > arr[largest]) 39 | largest = r; 40 | 41 | // If largest is not root 42 | if (largest != i) 43 | { 44 | int swap = arr[i]; 45 | arr[i] = arr[largest]; 46 | arr[largest] = swap; 47 | 48 | // Recursively heapify the affected sub-tree 49 | heapify(arr, n, largest); 50 | } 51 | } 52 | // Driver program 53 | public static void main(String args[]) 54 | { 55 | int arr[] = {12, 11, 13, 5, 6, 7}; 56 | int n = arr.length; 57 | int i; 58 | HeapSort ob = new HeapSort(); 59 | ob.sort(arr); 60 | 61 | System.out.println("Sorted array is"); 62 | for (i=0; i s = new Stack(); 8 | int flag =0; 9 | 10 | for(int i=0; i adj[]; 16 | 17 | // Constructor 18 | Graph(int v) 19 | { 20 | V = v; 21 | adj = new LinkedList[v]; 22 | for (int i=0; i i = adj[v].listIterator(); 41 | while (i.hasNext()) 42 | { 43 | int n = i.next(); 44 | if (!visited[n]) 45 | DFSUtil(n, visited); 46 | } 47 | } 48 | 49 | // The function to do DFS traversal. It uses recursive DFSUtil() 50 | void DFS(int v) 51 | { 52 | // Mark all the vertices as not visited(set as 53 | // false by default in java) 54 | boolean visited[] = new boolean[V]; 55 | 56 | // Call the recursive helper function to print DFS traversal 57 | DFSUtil(v, visited); 58 | } 59 | 60 | public static void main(String args[]) 61 | { 62 | Graph g = new Graph(4); 63 | 64 | g.addEdge(0, 1); 65 | g.addEdge(0, 2); 66 | g.addEdge(1, 2); 67 | g.addEdge(2, 0); 68 | g.addEdge(2, 3); 69 | g.addEdge(3, 3); 70 | 71 | System.out.println("Following is Depth First Traversal "+ 72 | "(starting from vertex 2)"); 73 | 74 | g.DFS(2); 75 | } 76 | } -------------------------------------------------------------------------------- /Backtracking.java: -------------------------------------------------------------------------------- 1 | 2 | public class RatMaze { 3 | 4 | 5 | static int N; 6 | 7 | 8 | void printSolution(int sol[][]) 9 | { 10 | for (int i = 0; i < N; i++) { 11 | for (int j = 0; j < N; j++) 12 | System.out.print( 13 | " " + sol[i][j] + " "); 14 | System.out.println(); 15 | } 16 | } 17 | 18 | /* A utility function to check 19 | if x, y is valid index for N*N maze */ 20 | boolean isSafe( 21 | int maze[][], int x, int y) 22 | { 23 | // if (x, y outside maze) return false 24 | return (x >= 0 && x < N && y >= 0 25 | && y < N && maze[x][y] == 1); 26 | } 27 | 28 | 29 | boolean solveMaze(int maze[][]) 30 | { 31 | int sol[][] = new int[N][N]; 32 | 33 | if (solveMazeUtil(maze, 0, 0, sol) == false) { 34 | System.out.print("Solution doesn't exist"); 35 | return false; 36 | } 37 | 38 | printSolution(sol); 39 | return true; 40 | } 41 | 42 | boolean solveMazeUtil(int maze[][], int x, int y, 43 | int sol[][]) 44 | { 45 | // if (x, y is goal) return true 46 | if (x == N - 1 && y == N - 1 47 | && maze[x][y] == 1) { 48 | sol[x][y] = 1; 49 | return true; 50 | } 51 | 52 | 53 | if (isSafe(maze, x, y) == true) { 54 | / 55 | sol[x][y] = 1; 56 | 57 | 58 | if (solveMazeUtil(maze, x + 1, y, sol)) 59 | return true; 60 | 61 | if (solveMazeUtil(maze, x, y + 1, sol)) 62 | return true; 63 | 64 | 65 | sol[x][y] = 0; 66 | return false; 67 | } 68 | 69 | return false; 70 | } 71 | 72 | public static void main(String args[]) 73 | { 74 | RatMaze rat = new RatMaze(); 75 | int maze[][] = { { 1, 0, 0, 0 }, 76 | { 1, 1, 0, 1 }, 77 | { 0, 1, 0, 0 }, 78 | { 1, 1, 1, 1 } }; 79 | 80 | N = maze.length; 81 | rat.solveMaze(maze); 82 | } 83 | } -------------------------------------------------------------------------------- /Sorting/quick sort.java: -------------------------------------------------------------------------------- 1 | // Implementation of QuickSort 2 | class QuickSort 3 | { 4 | /* This function takes last element as pivot, 5 | places the pivot element at its correct 6 | position in sorted array, and places all 7 | smaller (smaller than pivot) to left of 8 | pivot and all greater elements to right 9 | of pivot */ 10 | int partition(int arr[], int low, int high) 11 | { 12 | int pivot = arr[high]; 13 | int i = (low-1); // index of smaller element 14 | for (int j=low; j Array to be sorted, 39 | low --> Starting index, 40 | high --> Ending index */ 41 | void sort(int arr[], int low, int high) 42 | { 43 | if (low < high) 44 | { 45 | /* pi is partitioning index, arr[pi] is 46 | now at right place */ 47 | int pi = partition(arr, low, high); 48 | 49 | // Recursively sort elements before 50 | // partition and after partition 51 | sort(arr, low, pi-1); 52 | sort(arr, pi+1, high); 53 | } 54 | } 55 | 56 | /* A utility function to print array of size n */ 57 | static void printArray(int arr[]) 58 | { 59 | int n = arr.length; 60 | for (int i=0; i adj[]; //Adjacency Lists 15 | 16 | // Constructor 17 | Graph(int v) 18 | { 19 | V = v; 20 | adj = new LinkedList[v]; 21 | for (int i=0; i queue = new LinkedList(); 40 | 41 | // Mark the current node as visited and enqueue it 42 | visited[s]=true; 43 | queue.add(s); 44 | 45 | while (queue.size() != 0) 46 | { 47 | // Dequeue a vertex from queue and print it 48 | s = queue.poll(); 49 | System.out.print(s+" "); 50 | 51 | // Get all adjacent vertices of the dequeued vertex s 52 | // If a adjacent has not been visited, then mark it 53 | // visited and enqueue it 54 | Iterator i = adj[s].listIterator(); 55 | while (i.hasNext()) 56 | { 57 | int n = i.next(); 58 | if (!visited[n]) 59 | { 60 | visited[n] = true; 61 | queue.add(n); 62 | } 63 | } 64 | } 65 | } 66 | 67 | // Driver method to 68 | public static void main(String args[]) 69 | { 70 | Graph g = new Graph(4); 71 | 72 | g.addEdge(0, 1); 73 | g.addEdge(0, 2); 74 | g.addEdge(1, 2); 75 | g.addEdge(2, 0); 76 | g.addEdge(2, 3); 77 | g.addEdge(3, 3); 78 | 79 | System.out.println("Following is Breadth First Traversal "+ 80 | "(starting from vertex 2)"); 81 | 82 | g.BFS(2); 83 | } 84 | } -------------------------------------------------------------------------------- /Sorting/merge sort.java: -------------------------------------------------------------------------------- 1 | /* Java program for Merge Sort */ 2 | class MergeSort { 3 | // Merges two subarrays of arr[] where the first subarray is arr[l...m] and other array is arr[m+1...r] 4 | void merge(int arr[], int l, int m, int r) 5 | { 6 | // Find sizes of two subarrays to be merged 7 | int n1 = m - l + 1; 8 | int n2 = r - m; 9 | 10 | /* Create temp arrays */ 11 | int L[] = new int[n1]; 12 | int R[] = new int[n2]; 13 | 14 | /*Copy data to temp arrays*/ 15 | for (int i = 0; i < n1; ++i) 16 | L[i] = arr[l + i]; 17 | for (int j = 0; j < n2; ++j) 18 | R[j] = arr[m + 1 + j]; 19 | 20 | /* Merge the temp arrays */ 21 | 22 | // Initial indexes of first and second subarrays 23 | int i = 0, j = 0; 24 | 25 | // Initial index of merged subarry array 26 | int k = l; 27 | while (i < n1 && j < n2) { 28 | if (L[i] <= R[j]) { 29 | arr[k] = L[i]; 30 | i++; 31 | } 32 | else { 33 | arr[k] = R[j]; 34 | j++; 35 | } 36 | k++; 37 | } 38 | 39 | /* Copy remaining elements of L[] if any */ 40 | while (i < n1) { 41 | arr[k] = L[i]; 42 | i++; 43 | k++; 44 | } 45 | 46 | /* Copy remaining elements of R[] if any */ 47 | while (j < n2) { 48 | arr[k] = R[j]; 49 | j++; 50 | k++; 51 | } 52 | } 53 | 54 | // Main function that sorts arr[l..r] using 55 | // merge() 56 | void sort(int arr[], int l, int r) 57 | { 58 | if (l < r) { 59 | // Find the middle point 60 | int m = (l + r) / 2; 61 | 62 | // Sort first and second halves 63 | sort(arr, l, m); 64 | sort(arr, m + 1, r); 65 | 66 | // Merge the sorted halves 67 | merge(arr, l, m, r); 68 | } 69 | } 70 | // Driver method 71 | public static void main(String args[]) 72 | { 73 | int arr[] = { 12, 11, 13, 5, 6, 7 }; 74 | int n = arr.length; 75 | System.out.println("Given Array"); 76 | 77 | for (int i = 0; i < n; ++i) 78 | System.out.print(arr[i] + " "); 79 | System.out.println(); 80 | 81 | MergeSort ob = new MergeSort(); 82 | ob.sort(arr, 0, arr.length - 1); 83 | 84 | System.out.println("\nSorted array"); 85 | 86 | for (int j = 0; j < n; ++j) 87 | System.out.print(arr[j] + " "); 88 | System.out.println(); 89 | } 90 | } 91 | 92 | // By ANKITAKHAN -------------------------------------------------------------------------------- /Sorting/TopologicalSort.java: -------------------------------------------------------------------------------- 1 | import java.lang.*; 2 | import java.io.*; 3 | import java.util.*; 4 | 5 | class TopologicalSort { 6 | public static void main(String[] args) throws IOException { 7 | BufferedReader read = 8 | new BufferedReader(new InputStreamReader(System.in)); 9 | int t = Integer.parseInt(read.readLine()); 10 | 11 | while (t-- > 0) { 12 | ArrayList> list = new ArrayList<>(); 13 | String st[] = read.readLine().trim().split("\\s+"); 14 | int edg = Integer.parseInt(st[0]); 15 | int nov = Integer.parseInt(st[1]); 16 | 17 | for (int i = 0; i < nov + 1; i++) 18 | list.add(i, new ArrayList()); 19 | 20 | String s[] = read.readLine().trim().split("\\s+"); 21 | int p = 0; 22 | for (int i = 1; i <= edg; i++) { 23 | int u = Integer.parseInt(s[p++]); 24 | int v = Integer.parseInt(s[p++]); 25 | list.get(u).add(v); 26 | } 27 | 28 | int[] res = new TopologicalSortUtil().topoSort(list, nov); 29 | 30 | if (check(list, nov, res) == true) 31 | System.out.println("1"); 32 | else 33 | System.out.println("0"); 34 | } 35 | } 36 | static boolean check(ArrayList> list, int V, int[] res) { 37 | int[] map = new int[V]; 38 | for (int i = 0; i < V; i++) { 39 | map[res[i]] = i; 40 | } 41 | for (int i = 0; i < V; i++) { 42 | for (int v : list.get(i)) { 43 | if (map[i] > map[v]) return false; 44 | } 45 | } 46 | return true; 47 | } 48 | } 49 | 50 | class TopologicalSortUtil { 51 | static int[] topoSort(ArrayList> adj, int N) { 52 | int[] indegree = new int[N]; 53 | for(int i=0; i temp = adj.get(i); 55 | for(int node : temp) { 56 | indegree[node]++; 57 | } 58 | } 59 | Queue q = new LinkedList<>(); 60 | for(int i=0; i result = new ArrayList<>(); 67 | while(!q.isEmpty()) { 68 | int u = q.poll(); 69 | result.add(u); 70 | for(int node : adj.get(u)) { 71 | if(--indegree[node] == 0) { 72 | q.add(node); 73 | } 74 | } 75 | visited++; 76 | } 77 | int[] arr = new int[result.size()]; 78 | for(int i=0; i> l,int u,int v,boolean bi) 13 | { 14 | l.get(u).add(v); 15 | if(bi) 16 | { 17 | l.get(v).add(u); 18 | } 19 | } 20 | 21 | void sssp(ArrayList> l,int n,int s,int destination) 22 | { 23 | boolean visit[]=new boolean[n]; 24 | LinkedList que=new LinkedList(); 25 | int dist[]=new int [n]; 26 | for(int i=0;i i=l.Iterator(); 41 | for (int j = 0; j < l.get(s).size(); j++) { 42 | //while(i.hasNext()) 43 | //{ 44 | int nn=l.get(s).get(j); 45 | if(!visit[nn]){ 46 | visit[nn]=true; 47 | dist[nn]=dist[s]+1; 48 | que.add(nn);} 49 | } 50 | 51 | } 52 | System.out.println(dist[destination]); 53 | } 54 | 55 | 56 | void print(List> l) 57 | { 58 | 59 | for (int i = 0; i < l.size(); i++) { 60 | System.out.print(i+"-->"); 61 | // System.out.print("head"); 62 | for (int j = 0; j < l.get(i).size(); j++) { 63 | System.out.print(" "+l.get(i).get(j)); 64 | } 65 | System.out.println(); 66 | } 67 | } 68 | public static void main (String[] args) throws java.lang.Exception 69 | { 70 | // your code goes here 71 | Scanner sc=new Scanner(System.in); 72 | int v; 73 | v=sc.nextInt(); 74 | ArrayList> l=new ArrayList>(v); 75 | 76 | for(int i=0;i()); 79 | } 80 | Codechef ob=new Codechef(); 81 | ob.add(l,1,2,true); 82 | ob.add(l,1,3,true); 83 | ob.add(l,1,7,true); 84 | 85 | ob.add(l,2,5,true); 86 | ob.add(l,3,5,true); 87 | 88 | ob.add(l,7,6,true); 89 | ob.add(l,6,5,true); 90 | 91 | ob.print(l); 92 | System.out.println(" SSP "); 93 | ob.sssp(l,v,0,5); 94 | //System.out.println(" BFS "); 95 | // ob.bfs(l,v,1); 96 | //System.out.println(" DFS "); 97 | //ob.dfs(l,v,1); 98 | 99 | //System.out.println(ob.isCyclic(l,v,1)); 100 | 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /Sorting/shellSort.java: -------------------------------------------------------------------------------- 1 | // shellSort.java 2 | // demonstrates shell sort 3 | // to run this program: C>java ShellSortApp 4 | //-------------------------------------------------------------- 5 | class ArraySh 6 | { 7 | private long[] theArray; // ref to array theArray 8 | private int nElems; // number of data items 9 | //-------------------------------------------------------------- 10 | public ArraySh(int max) // constructor 11 | { 12 | theArray = new long[max]; // create the array 13 | nElems = 0; // no items yet 14 | } 15 | //-------------------------------------------------------------- 16 | public void insert(long value) // put element into array 17 | { 18 | theArray[nElems] = value; // insert it 19 | nElems++; // increment size 20 | } 21 | //-------------------------------------------------------------- 22 | public void display() // displays array contents 23 | { 24 | System.out.print("A="); 25 | for(int j=0; j0) // decreasing h, until h=1 40 | { 41 | // h-sort the file 42 | for(outer=h; outer h-1 && theArray[inner-h] >= temp) 48 | { 49 | theArray[inner] = theArray[inner-h]; 50 | inner -= h; 51 | } 52 | theArray[inner] = temp; 53 | } // end for 54 | h = (h-1) / 3; // decrease h 55 | } // end while(h>0) 56 | } // end shellSort() 57 | //-------------------------------------------------------------- 58 | } // end class ArraySh 59 | //////////////////////////////////////////////////////////////// 60 | class ShellSortApp 61 | { 62 | public static void main(String[] args) 63 | { 64 | int maxSize = 10; // array size 65 | ArraySh arr; 66 | arr = new ArraySh(maxSize); // create the array 67 | 68 | for(int j=0; j= end){ 15 | return; 16 | } 17 | 18 | //Partation index ind.. 19 | int ind = partation(arr, beg, end); 20 | //Calling the left sub - sort space.. 21 | sort(arr, beg, ind-1); 22 | //Calling the right sub - sort space.. 23 | sort(arr, ind+1, end); 24 | } 25 | /* 26 | This method is used to find the partation index based on the assumption 27 | that last element is the pivot.. 28 | Arguments - int array for which the index is to be found, int beginning of 29 | the array, int end - Last index of the passed array.. 30 | Returns - an int denoting the point of paration.. 31 | */ 32 | public int partation(int arr[], int beg, int end){ 33 | //If the array has only one element.. 34 | if(beg == end){ 35 | return end; 36 | } 37 | else{ 38 | //Finding the random index in range.. 39 | int tempInd = rand(beg, end); 40 | //Swapping the element at the random index with the last element.. 41 | swap(arr, tempInd, end); 42 | //Making the new last element as the pivot.. 43 | int pivot = arr[end]; 44 | //Current index to swap values.. 45 | int ind = beg - 1; 46 | //Finding all the elements smaller than the pivot.. 47 | for(int i = beg; i < end; i++){ 48 | if(arr[i] < pivot){ 49 | //Swapping the elements smaller than pivot to left of 50 | //pivot.. 51 | ind++; 52 | swap(arr, ind, i); 53 | } 54 | } 55 | //Swapping the pivot to it's correct place 56 | ind++; 57 | 58 | swap(arr, ind, end); 59 | return ind; 60 | } 61 | } 62 | /* 63 | This method generates a random number in a given range 64 | Arguments - int beg, int end 65 | Returns - a random int in the range of end - beg + 1 66 | */ 67 | public int rand(int beg, int end){ 68 | int range = end - beg + 1; 69 | int show = (int)(Math.random() * range) + beg; 70 | return show; 71 | } 72 | /* 73 | This method is used as a utility function to swap two numbers in an array.. 74 | Arguments - int array of elements, int index1, int index2 75 | Returns - Nothing, inplace swapping.. 76 | */ 77 | public void swap(int arr[], int a, int b){ 78 | int temp = arr[a]; 79 | arr[a] = arr[b]; 80 | arr[b] = temp; 81 | } 82 | } 83 | /* 84 | This class is used to check the QuickSort class. 85 | */ 86 | class Demo{ 87 | public static void main(String args[]){ 88 | //A dummy array to be sorted.. 89 | int sampleArray[] = {10, 7, 8, 9, 5, 1, 5}; 90 | QuickSort sorter = new QuickSort(); 91 | //Printing the original array.. 92 | System.out.println("Array before sorting:- "); 93 | printer(sampleArray, sampleArray.length); 94 | //Sorting the array using quicksort.. 95 | sorter.sort(sampleArray, 0, sampleArray.length-1); 96 | 97 | //Printing the sorted array.. 98 | System.out.println("Array after sorting:- "); 99 | printer(sampleArray, sampleArray.length); 100 | } 101 | /* 102 | A utility function to print the array linearly.. 103 | Arguments - An array to be printed, and an int with length of array 104 | Return - Nothing.. 105 | */ 106 | public static void printer(int arr[], int n){ 107 | StringBuffer br = new StringBuffer(); 108 | for(int i = 0; i < n; i++){ 109 | br.append(arr[i]+" "); 110 | } 111 | System.out.println(br); 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /Algorithms/EqualSumPartition.java: -------------------------------------------------------------------------------- 1 | /* PROBLEM STATEMENT : DIVIDE THE ARRAY INTO TWO PARTITION OF EQUAL SUM. 2 | //Key Points : 3 | 1 : THE PROBLEM IS SIMILAR TO THE SUBSET SUM PROBLEM WITH A LIITLE MODIFICATION 4 | ARRAY ARR(2s) 5 | / \ 6 | / \ 7 | / \ 8 | Partition 1 Partition 2 9 | Sum : s Sum : s 10 | 2 : WE CONCLUDE THAT THE SUM OF ARRAY SHOULD BE EVEN TO BE ABLE TO PARTIONED. 11 | 3 : IT IS SIMILAR TO SUBSET SUM PROBLEM AS WE NEED TO FIND A SUBSET OF SUM sum/2. 12 | */ 13 | public class EqualSumPartition { 14 | 15 | //***********************************************Recursive Approach********************************************************** 16 | private static boolean solveRecursively(int arr[], int i, int sum) { 17 | //If at some point we have (sum == 0) it means we have found a subset of given sum in the array.So we return true 18 | if (sum == 0) { 19 | return true; 20 | } 21 | //The i == 0 will get executed only when we have no more elements left in the array and we couldnt find the required sum. So we return false; 22 | if (i == 0) { 23 | return false; 24 | } 25 | //If the given element is valid i.e it is less than our required sum. We solve the problem recursively. We have two possible choice: 26 | //Include the element OR exclude it. 27 | if (arr[i - 1] <= sum) { 28 | return solveRecursively(arr, i - 1, sum - arr[i - 1]) | solveRecursively(arr, i - 1, sum); 29 | } else { 30 | return solveRecursively(arr, i - 1, sum); //As the element is invalid we do not include 31 | } 32 | } 33 | 34 | //***********************************************Dynamic Programming Approach********************************************************** 35 | private static boolean solveUsingDp(int arr[], int sum) { 36 | //The bottom up dynamic programming approach is similar to the subset sum problem. 37 | //The state dp[i][j] will be true if there a subset of first i items with sum value = j. 38 | boolean dp[][] = new boolean[arr.length + 1][sum + 1]; 39 | for (int i = 0; i < arr.length + 1; i++) { 40 | for (int j = 0; j < sum + 1; j++) { 41 | if (i == 0 || j == 0) //base case. Evident from our recurive approah 42 | { 43 | if (i == 0) // the case when there are no it 44 | { 45 | dp[i][j] = false; 46 | } 47 | if (j == 0) { 48 | dp[i][j] = true; //The case when sum = 0. We always have a empty subset {} with sum 0. 49 | } 50 | } else { 51 | if (arr[i - 1] <= j) //If the element is valid. We will find subset of sum j by including or excluding the ith item 52 | { 53 | dp[i][j] = dp[i - 1][j - arr[i - 1]] | dp[i - 1][j]; 54 | } else { 55 | dp[i][j] = dp[i - 1][j]; //We dont include the ith item as its invalid 56 | } 57 | } 58 | 59 | } 60 | } 61 | return dp[arr.length][sum]; 62 | } 63 | 64 | public static void main(String[] args) { 65 | 66 | int arr[] = {1, 2, 3, 6}, sum = 0; 67 | 68 | //We find the sum of each element of array. 69 | for (int i = 0; i < arr.length; i++) { 70 | sum += arr[i]; 71 | } 72 | //As explained at top : A partition with equal sum would only exist when the sum is an even number 73 | if (sum % 2 != 0) { 74 | System.out.println(0); 75 | } else { 76 | System.out.println(solveRecursively(arr, arr.length, sum / 2)); //Recursive Approach 77 | System.out.println(solveUsingDp(arr, sum / 2)); //Bottom up dynamic programming approach. 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /Sorting/partition.java: -------------------------------------------------------------------------------- 1 | // partition.java 2 | // demonstrates partitioning an array 3 | // to run this program: C>java PartitionApp 4 | //////////////////////////////////////////////////////////////// 5 | class ArrayPar 6 | { 7 | private long[] theArray; // ref to array theArray 8 | private int nElems; // number of data items 9 | //-------------------------------------------------------------- 10 | public ArrayPar(int max) // constructor 11 | { 12 | theArray = new long[max]; // create the array 13 | nElems = 0; // no items yet 14 | } 15 | //-------------------------------------------------------------- 16 | public void insert(long value) // put element into array 17 | { 18 | theArray[nElems] = value; // insert it 19 | nElems++; // increment size 20 | } 21 | //-------------------------------------------------------------- 22 | public int size() // return number of items 23 | { return nElems; } 24 | //-------------------------------------------------------------- 25 | public void display() // displays array contents 26 | { 27 | System.out.print("A="); 28 | for(int j=0; j left && // find smaller item 44 | theArray[--rightPtr] > pivot) 45 | ; // (nop) 46 | if(leftPtr >= rightPtr) // if pointers cross, 47 | break; // partition done 48 | else // not crossed, so 49 | swap(leftPtr, rightPtr); // swap elements 50 | } // end while(true) 51 | return leftPtr; // return partition 52 | } // end partitionIt() 53 | //-------------------------------------------------------------- 54 | public void swap(int dex1, int dex2) // swap two elements 55 | { 56 | long temp; 57 | temp = theArray[dex1]; // A into temp 58 | theArray[dex1] = theArray[dex2]; // B into A 59 | theArray[dex2] = temp; // temp into B 60 | } // end swap() 61 | //-------------------------------------------------------------- 62 | } // end class ArrayPar 63 | //////////////////////////////////////////////////////////////// 64 | class PartitionApp 65 | { 66 | public static void main(String[] args) 67 | { 68 | int maxSize = 16; // array size 69 | ArrayPar arr; // reference to array 70 | arr = new ArrayPar(maxSize); // create the array 71 | 72 | for(int j=0; jNULL 122 | dll.append(6); 123 | 124 | // Insert 7 at the beginning. So linked list becomes 7->6->NULL 125 | dll.push(7); 126 | 127 | // Insert 1 at the beginning. So linked list becomes 1->7->6->NULL 128 | dll.push(1); 129 | 130 | // Insert 4 at the end. So linked list becomes 1->7->6->4->NULL 131 | dll.append(4); 132 | 133 | // Insert 8, after 7. So linked list becomes 1->7->8->6->4->NULL 134 | dll.InsertAfter(dll.head.next, 8); 135 | 136 | System.out.println("Created DLL is: "); 137 | dll.printlist(dll.head); 138 | } 139 | } 140 | 141 | -------------------------------------------------------------------------------- /Graph/Cyclic_detection: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | import java.io.*; 4 | 5 | /* Name of the class has to be "Main" only if the class is public. */ 6 | class Codechef 7 | { 8 | 9 | void add(List> l,int u,int v,boolean bi) 10 | { 11 | l.get(u).add(v); 12 | if(bi) 13 | { 14 | l.get(v).add(u); 15 | } 16 | } 17 | 18 | void dfs(ArrayList> l,int n,int s) 19 | { 20 | boolean visit[]=new boolean [n]; 21 | Stack st= new Stack<>(); 22 | Arrays.fill(visit,false); 23 | visit[s]=true; 24 | st.push(s); 25 | 26 | while(!st.empty()) 27 | { 28 | int nn=st.peek(); 29 | System.out.print(nn+" "); 30 | st.pop(); 31 | for(int i=0;i> l,int n,int s) 43 | { 44 | boolean visit[]=new boolean[n]; 45 | LinkedList que=new LinkedList(); 46 | for(int i=0;i i=l.Iterator(); 60 | for (int j = 0; j < l.get(s).size(); j++) { 61 | //while(i.hasNext()) 62 | //{ 63 | int nn=l.get(s).get(j); 64 | if(!visit[nn]){ 65 | visit[nn]=true; 66 | que.add(nn);} 67 | } 68 | 69 | } 70 | } 71 | 72 | 73 | boolean isCyclic(ArrayList> l,int n,int s) 74 | { 75 | boolean visit[]=new boolean[n]; 76 | int parent[]=new int [n]; 77 | LinkedList que=new LinkedList(); 78 | for(int i=0;i i=l.Iterator(); 92 | for (int j = 0; j < l.get(s).size(); j++) { 93 | //while(i.hasNext()) 94 | //{ 95 | int nn=l.get(s).get(j); 96 | if (visit[nn]==true && parent[s]!=nn) 97 | { 98 | return true; 99 | } 100 | else if(!visit[nn]){ 101 | visit[nn]=true; 102 | parent[nn]=s; 103 | que.add(nn);} 104 | } 105 | 106 | } 107 | return false; 108 | } 109 | 110 | void print(List> l) 111 | { 112 | 113 | for (int i = 0; i < l.size(); i++) { 114 | System.out.print(i+"-->"); 115 | // System.out.print("head"); 116 | for (int j = 0; j < l.get(i).size(); j++) { 117 | System.out.print(" "+l.get(i).get(j)); 118 | } 119 | System.out.println(); 120 | } 121 | } 122 | public static void main (String[] args) throws java.lang.Exception 123 | { 124 | // your code goes here 125 | Scanner sc=new Scanner(System.in); 126 | int v; 127 | v=sc.nextInt(); 128 | ArrayList> l=new ArrayList>(v); 129 | 130 | for(int i=0;i()); 133 | } 134 | Codechef ob=new Codechef(); 135 | ob.add(l,1,2,true); 136 | ob.add(l,1,3,true); 137 | ob.add(l,1,7,true); 138 | 139 | ob.add(l,2,5,true); 140 | ob.add(l,3,5,true); 141 | 142 | ob.add(l,7,6,true); 143 | ob.add(l,6,5,true); 144 | 145 | ob.print(l); 146 | System.out.println(" BFS "); 147 | ob.bfs(l,v,1); 148 | System.out.println(" DFS "); 149 | ob.dfs(l,v,1); 150 | 151 | System.out.println(ob.isCyclic(l,v,1)); 152 | 153 | } 154 | } 155 | -------------------------------------------------------------------------------- /Interview Questions/Questions.md: -------------------------------------------------------------------------------- 1 | # This file is all about the interview question asked in java. 2 | Keep on adding the interview questions. 3 | 4 | 5 | ### Q1 - Explain public static void main(String args[]) in Java. 6 | A1- 7 | > main() in Java is the entry point for any Java program. It is always written as public static void main(String[] args). 8 | * public: Public is an access modifier, which is used to specify who can access this method. Public means that this Method will be accessible by any Class. 9 | * static: It is a keyword in java which identifies it is class-based. main() is made static in Java so that it can be accessed without creating the instance of a Class. In case, main is not made static then the compiler will throw an error as main() is called by the JVM before any objects are made and only static methods can be directly invoked via the class. 10 | * void: It is the return type of the method. Void defines the method which will not returnss any value. 11 | * main: It is the name of the method which is searched by JVM as a starting point for an application with a particular signature only. It is the method where the main execution occurs. 12 | * String args[]: It is the parameter passed to the main method. 13 | 14 | ### Q2 - Is java Pass by value or Pass by reference? 15 | A2- 16 | > Java is strictly Pass by Value. This can be best explained by a swap() function in java. 17 | ```java 18 | public static void swap(int n1, int n2) 19 | { 20 | int temp=n1; 21 | n1=n2; 22 | n2=temp; 23 | } 24 | 25 | public static void main(String[] args) 26 | { 27 | int a = 10; 28 | int b = 20; 29 | swap(a,b); 30 | System.out.print(a,b); 31 | 32 | //output will be 10 20 33 | } 34 | ``` 35 | 36 | ### Q3- Can we declare the main method of our class as private? 37 | 38 | A3- 39 | > In java, main method must be public static in order to run any application correctly. If main method is declared as private, developer won't get any compilation error however, it will not get executed and will give a runtime error. 40 | 41 | ### Q4- Is there any way to skip Finally block of exception even if some exception occurs in the exception block? 42 | 43 | A4- 44 | > If an exception is raised in `Try` block, control passes to `catch` block if it exists otherwise to finally block. `Finally` block is always executed when an exception occurs and the only way to avoid execution of any statements in Finally block is by aborting the code forcibly by writing following line of code at the end of try block: 45 | 46 | ```System.exit(0);``` 47 | 48 | ### Q5- What is System class? 49 | 50 | A5- 51 | > System.class is a final class provided by java.lang package. It contains several useful class fields and methods. The purpose of System class is to provide access to system 52 | resources. 53 | 54 | ### Q6- What is the difference between Singleton class and Static class? 55 | 56 | A6- 57 | * A static class in Java has only static methods. It is a container of functions. It is created based on procedural programming design. Singleton class is a pattern in Object Oriented Design. 58 | * A Singletonclass has only one instance of an object in JVM. This pattern is 59 | implemented in such a way that there is always only one instance of 60 | that class present in JVM. 61 | 62 | ### Q7 - What are Wrapper classes in Java? 63 | A7- 64 | > Java has concept of Wrapper classes to allow primitive types to be 65 | accessed as objects. Primitive types like boolean, int, double, float 66 | etc. have corresponding Wrappers classes – Boolean, Integer, 67 | Double, Float etc. 68 | Many of these Wrapper classes are in java.lang package. 69 | Java 5.0 has launched the concept of Autoboxing and Unboxing in 70 | Java for Wrapper classes. 71 | ```java 72 | public class WrapperTest { 73 | public static void main(String args[]) { 74 | 75 | int count=50; //Converting int into Integer 76 | Integer i=Integer.valueOf(count);//converting int into Integer 77 | Integer j=a;//autoboxing, now compiler will write 78 | Integer.valueOf(count) internally 79 | System.out.println(count+" "+i+" "+j); 80 | } 81 | } 82 | 83 | 84 | ### Q7- You have 10 balls and a scale, find the heaviest ball in the least interations. 85 | 86 | A6- 87 | > Seperate the balls into two groups of 5 and place each group on the scale. Take balls from the heaviest side, put 1 on the side and weigh two on each side. If even, heaviest one is on the side. If the scale dips weigh those balls. Least amount of iterations is 3. 88 | > It's a logic puzzle to see how you willl troubleshoot through a problem. 89 | 90 | -------------------------------------------------------------------------------- /Graph/k_cores.java: -------------------------------------------------------------------------------- 1 | // Java program to find K-Cores of a graph 2 | import java.util.*; 3 | 4 | class k_cores 5 | { 6 | 7 | // This class represents a undirected graph using adjacency 8 | // list representation 9 | static class Graph 10 | { 11 | int V; // No. of vertices 12 | 13 | // Pointer to an array containing adjacency lists 14 | Vector[] adj; 15 | 16 | @SuppressWarnings("unchecked") 17 | Graph(int V) 18 | { 19 | this.V = V; 20 | this.adj = new Vector[V]; 21 | 22 | for (int i = 0; i < V; i++) 23 | adj[i] = new Vector<>(); 24 | } 25 | 26 | // function to add an edge to graph 27 | void addEdge(int u, int v) 28 | { 29 | this.adj[u].add(v); 30 | this.adj[v].add(u); 31 | } 32 | 33 | // A recursive function to print DFS starting from v. 34 | // It returns true if degree of v after processing is less 35 | // than k else false 36 | // It also updates degree of adjacent if degree of v 37 | // is less than k. And if degree of a processed adjacent 38 | // becomes less than k, then it reduces of degree of v also, 39 | boolean DFSUtil(int v, boolean[] visited, int[] vDegree, int k) 40 | { 41 | 42 | // Mark the current node as visited and print it 43 | visited[v] = true; 44 | 45 | // Recur for all the vertices adjacent to this vertex 46 | for (int i : adj[v]) 47 | { 48 | 49 | // degree of v is less than k, then degree of adjacent 50 | // must be reduced 51 | if (vDegree[v] < k) 52 | vDegree[i]--; 53 | 54 | // If adjacent is not processed, process it 55 | if (!visited[i]) 56 | { 57 | 58 | // If degree of adjacent after processing becomes 59 | // less than k, then reduce degree of v also. 60 | if (DFSUtil(i, visited, vDegree, k)) 61 | vDegree[v]--; 62 | } 63 | } 64 | 65 | // Return true if degree of v is less than k 66 | return (vDegree[v] < k); 67 | } 68 | 69 | // Prints k cores of an undirected graph 70 | void printKCores(int k) 71 | { 72 | 73 | // INITIALIZATION 74 | // Mark all the vertices as not visited and not 75 | // processed. 76 | boolean[] visited = new boolean[V]; 77 | boolean[] processed = new boolean[V]; 78 | Arrays.fill(visited, false); 79 | Arrays.fill(processed, false); 80 | 81 | int mindeg = Integer.MAX_VALUE; 82 | int startvertex = 0; 83 | 84 | // Store degrees of all vertices 85 | int[] vDegree = new int[V]; 86 | for (int i = 0; i < V; i++) 87 | { 88 | vDegree[i] = adj[i].size(); 89 | 90 | if (vDegree[i] < mindeg) 91 | { 92 | mindeg = vDegree[i]; 93 | startvertex = i; 94 | } 95 | } 96 | DFSUtil(startvertex, visited, vDegree, k); 97 | 98 | // DFS traversal to update degrees of all 99 | // vertices. 100 | for (int i = 0; i < V; i++) 101 | if (!visited[i]) 102 | DFSUtil(i, visited, vDegree, k); 103 | 104 | // PRINTING K CORES 105 | System.out.println("K-Cores : "); 106 | for (int v = 0; v < V; v++) 107 | { 108 | 109 | // Only considering those vertices which have degree 110 | // >= K after BFS 111 | if (vDegree[v] >= k) 112 | { 113 | System.out.printf("\n[%d]", v); 114 | 115 | // Traverse adjacency list of v and print only 116 | // those adjacent which have vDegree >= k after 117 | // BFS. 118 | for (int i : adj[v]) 119 | if (vDegree[i] >= k) 120 | System.out.printf(" -> %d", i); 121 | } 122 | } 123 | } 124 | } 125 | 126 | // Driver Code 127 | public static void main(String[] args) 128 | { 129 | 130 | // Create a graph given in the above diagram 131 | int k = 3; 132 | Graph g1 = new Graph(9); 133 | g1.addEdge(0, 1); 134 | g1.addEdge(0, 2); 135 | g1.addEdge(1, 2); 136 | g1.addEdge(1, 5); 137 | g1.addEdge(2, 3); 138 | g1.addEdge(2, 4); 139 | g1.addEdge(2, 5); 140 | g1.addEdge(2, 6); 141 | g1.addEdge(3, 4); 142 | g1.addEdge(3, 6); 143 | g1.addEdge(3, 7); 144 | g1.addEdge(4, 6); 145 | g1.addEdge(4, 7); 146 | g1.addEdge(5, 6); 147 | g1.addEdge(5, 8); 148 | g1.addEdge(6, 7); 149 | g1.addEdge(6, 8); 150 | g1.printKCores(k); 151 | 152 | System.out.println(); 153 | 154 | Graph g2 = new Graph(13); 155 | g2.addEdge(0, 1); 156 | g2.addEdge(0, 2); 157 | g2.addEdge(0, 3); 158 | g2.addEdge(1, 4); 159 | g2.addEdge(1, 5); 160 | g2.addEdge(1, 6); 161 | g2.addEdge(2, 7); 162 | g2.addEdge(2, 8); 163 | g2.addEdge(2, 9); 164 | g2.addEdge(3, 10); 165 | g2.addEdge(3, 11); 166 | g2.addEdge(3, 12); 167 | g2.printKCores(k); 168 | } 169 | } 170 | 171 | -------------------------------------------------------------------------------- /Algorithms/SuffixArray.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Collections; 3 | import java.util.Comparator; 4 | public class SuffixArray { 5 | private static final StringBuilder STRING_BUILDER = new StringBuilder(); 6 | private static final char DEFAULT_END_SEQ_CHAR = '$'; 7 | private final char endSeqChar; 8 | private String string; 9 | private ArrayList suffixArray; 10 | private ArrayList KMRarray; 11 | public SuffixArray(CharSequence sequence) { 12 | this(sequence, DEFAULT_END_SEQ_CHAR); 13 | } 14 | public SuffixArray(CharSequence sequence, char endChar) { 15 | endSeqChar = endChar; 16 | string = buildStringWithEndChar(sequence); 17 | } 18 | public ArrayList getSuffixArray() { 19 | if (suffixArray == null) 20 | KMRalgorithm(); 21 | return suffixArray; 22 | } 23 | public ArrayList getKMRarray() { 24 | if (KMRarray == null) 25 | KMRalgorithm(); 26 | return KMRarray; 27 | } 28 | public String getString(){ 29 | return string; 30 | } 31 | private void KMRalgorithm() { 32 | final int length = string.length(); 33 | ArrayList KMRinvertedList = new ArrayList(); 34 | ArrayList KMR = getBasicKMR(length); 35 | int radius = 1; 36 | while (radius < length) { 37 | KMRinvertedList = getKMRinvertedList(KMR, radius, length); 38 | KMR = getKMR(KMRinvertedList, length); 39 | radius *= 2; 40 | } 41 | KMRarray = new ArrayList(KMR.subList(0, length)); 42 | suffixArray = new ArrayList(); 43 | for (KMRsWithIndex kmr : KMRinvertedList) { 44 | suffixArray.add(new Integer(kmr.index)); 45 | } 46 | } 47 | private ArrayList getKMR(ArrayList KMRinvertedList, int length) { 48 | final ArrayList KMR = new ArrayList(length*2); 49 | for (int i=0; i<2*length; i++) 50 | KMR.add(new Integer(-1)); 51 | int counter = 0; 52 | for (int i=0; i0 && substringsAreEqual(KMRinvertedList, i)) 54 | counter++; 55 | KMR.set(KMRinvertedList.get(i).index, new Integer(counter)); 56 | } 57 | return KMR; 58 | } 59 | private boolean substringsAreEqual(ArrayList KMRinvertedList, int i) { 60 | return (KMRinvertedList.get(i-1).beginKMR.equals(KMRinvertedList.get(i).beginKMR) == false) || 61 | (KMRinvertedList.get(i-1).endKMR.equals(KMRinvertedList.get(i).endKMR) == false); 62 | } 63 | private ArrayList getKMRinvertedList(ArrayList KMR, int radius, int length) { 64 | final ArrayList KMRinvertedList = new ArrayList(); 65 | for (int i=0; i() { 69 | @Override 70 | public int compare(KMRsWithIndex A, KMRsWithIndex B) { 71 | if (A.beginKMR.equals(B.beginKMR) == false) 72 | return A.beginKMR.compareTo(B.beginKMR); 73 | if (A.endKMR.equals(B.endKMR) == false) 74 | return A.endKMR.compareTo(B.endKMR); 75 | return A.index.compareTo(B.index); 76 | } 77 | } 78 | ); 79 | return KMRinvertedList; 80 | } 81 | private ArrayList getBasicKMR(int length) { 82 | final ArrayList result = new ArrayList(length*2); 83 | final char[] characters = string.toCharArray(); 84 | for (int i=0; i b) ? a : b; 27 | } 28 | 29 | // A utility function to right rotate subtree rooted with y 30 | // See the diagram given above. 31 | Node rightRotate(Node y) { 32 | Node x = y.left; 33 | Node T2 = x.right; 34 | 35 | // Perform rotation 36 | x.right = y; 37 | y.left = T2; 38 | 39 | // Update heights 40 | y.height = max(height(y.left), height(y.right)) + 1; 41 | x.height = max(height(x.left), height(x.right)) + 1; 42 | 43 | // Return new root 44 | return x; 45 | } 46 | 47 | // A utility function to left rotate subtree rooted with x 48 | // See the diagram given above. 49 | Node leftRotate(Node x) { 50 | Node y = x.right; 51 | Node T2 = y.left; 52 | 53 | // Perform rotation 54 | y.left = x; 55 | x.right = T2; 56 | 57 | // Update heights 58 | x.height = max(height(x.left), height(x.right)) + 1; 59 | y.height = max(height(y.left), height(y.right)) + 1; 60 | 61 | // Return new root 62 | return y; 63 | } 64 | 65 | // Get Balance factor of node N 66 | int getBalance(Node N) { 67 | if (N == null) 68 | return 0; 69 | 70 | return height(N.left) - height(N.right); 71 | } 72 | 73 | Node insert(Node node, int key) { 74 | 75 | /* 1. Perform the normal BST insertion */ 76 | if (node == null) 77 | return (new Node(key)); 78 | 79 | if (key < node.key) 80 | node.left = insert(node.left, key); 81 | else if (key > node.key) 82 | node.right = insert(node.right, key); 83 | else // Duplicate keys not allowed 84 | return node; 85 | 86 | /* 2. Update height of this ancestor node */ 87 | node.height = 1 + max(height(node.left), 88 | height(node.right)); 89 | 90 | /* 3. Get the balance factor of this ancestor 91 | node to check whether this node became 92 | unbalanced */ 93 | int balance = getBalance(node); 94 | 95 | // If this node becomes unbalanced, then there 96 | // are 4 cases Left Left Case 97 | if (balance > 1 && key < node.left.key) 98 | return rightRotate(node); 99 | 100 | // Right Right Case 101 | if (balance < -1 && key > node.right.key) 102 | return leftRotate(node); 103 | 104 | // Left Right Case 105 | if (balance > 1 && key > node.left.key) { 106 | node.left = leftRotate(node.left); 107 | return rightRotate(node); 108 | } 109 | 110 | // Right Left Case 111 | if (balance < -1 && key < node.right.key) { 112 | node.right = rightRotate(node.right); 113 | return leftRotate(node); 114 | } 115 | 116 | /* return the (unchanged) node pointer */ 117 | return node; 118 | } 119 | 120 | // A utility function to print preorder traversal 121 | // of the tree. 122 | // The function also prints height of every node 123 | void preOrder(Node node) { 124 | if (node != null) { 125 | System.out.print(node.key + " "); 126 | preOrder(node.left); 127 | preOrder(node.right); 128 | } 129 | } 130 | 131 | public static void main(String[] args) { 132 | AVLTree tree = new AVLTree(); 133 | 134 | /* Constructing tree given in the above figure */ 135 | tree.root = tree.insert(tree.root, 10); 136 | tree.root = tree.insert(tree.root, 20); 137 | tree.root = tree.insert(tree.root, 30); 138 | tree.root = tree.insert(tree.root, 40); 139 | tree.root = tree.insert(tree.root, 50); 140 | tree.root = tree.insert(tree.root, 25); 141 | 142 | /* The constructed AVL Tree would be 143 | 30 144 | / \ 145 | 20 40 146 | / \ \ 147 | 10 25 50 148 | */ 149 | System.out.println("Preorder traversal" + 150 | " of constructed tree is : "); 151 | tree.preOrder(tree.root); 152 | } 153 | } 154 | -------------------------------------------------------------------------------- /Minimum_spanning_tree.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.LinkedList; 3 | import java.util.TreeSet; 4 | import java.util.Comparator; 5 | 6 | public class Minimum_spanning_tree { 7 | class node1 { 8 | 9 | // Stores destination vertex in adjacency list 10 | int dest; 11 | 12 | // Stores weight of a vertex in the adjacency list 13 | int weight; 14 | 15 | // Constructor 16 | node1(int a, int b) 17 | { 18 | dest = a; 19 | weight = b; 20 | } 21 | } 22 | static class Graph { 23 | 24 | // Number of vertices in the graph 25 | int V; 26 | 27 | // List of adjacent nodes of a given vertex 28 | LinkedList[] adj; 29 | 30 | // Constructor 31 | Graph(int e) 32 | { 33 | V = e; 34 | adj = new LinkedList[V]; 35 | for (int o = 0; o < V; o++) 36 | adj[o] = new LinkedList<>(); 37 | } 38 | } 39 | 40 | // class to represent a node in PriorityQueue 41 | // Stores a vertex and its corresponding 42 | // key value 43 | class node { 44 | int vertex; 45 | int key; 46 | } 47 | 48 | // Comparator class created for PriorityQueue 49 | // returns 1 if node0.key > node1.key 50 | // returns 0 if node0.key < node1.key and 51 | // returns -1 otherwise 52 | class comparator implements Comparator { 53 | 54 | @Override 55 | public int compare(node node0, node node1) 56 | { 57 | return node0.key - node1.key; 58 | } 59 | } 60 | 61 | // method to add an edge 62 | // between two vertices 63 | void addEdge(Graph graph, int src, int dest, int weight) 64 | { 65 | 66 | node1 node0 = new node1(dest, weight); 67 | node1 node = new node1(src, weight); 68 | graph.adj[src].addLast(node0); 69 | graph.adj[dest].addLast(node); 70 | } 71 | 72 | // method used to find the mst 73 | void prims_mst(Graph graph) 74 | { 75 | 76 | // Whether a vertex is in PriorityQueue or not 77 | Boolean[] mstset = new Boolean[graph.V]; 78 | node[] e = new node[graph.V]; 79 | 80 | // Stores the parents of a vertex 81 | int[] parent = new int[graph.V]; 82 | 83 | for (int o = 0; o < graph.V; o++) 84 | e[o] = new node(); 85 | 86 | for (int o = 0; o < graph.V; o++) { 87 | 88 | // Initialize to false 89 | mstset[o] = false; 90 | 91 | // Initialize key values to infinity 92 | e[o].key = Integer.MAX_VALUE; 93 | e[o].vertex = o; 94 | parent[o] = -1; 95 | } 96 | 97 | // Include the source vertex in mstset 98 | mstset[0] = true; 99 | 100 | // Set key value to 0 101 | // so that it is extracted first 102 | // out of PriorityQueue 103 | e[0].key = 0; 104 | 105 | // Use TreeSet instead of PriorityQueue as the remove function of the PQ is O(n) in java. 106 | TreeSet queue = new TreeSet(new comparator()); 107 | 108 | for (int o = 0; o < graph.V; o++) 109 | queue.add(e[o]); 110 | 111 | // Loops until the queue is not empty 112 | while (!queue.isEmpty()) { 113 | 114 | // Extracts a node with min key value 115 | node node0 = queue.pollFirst(); 116 | 117 | // Include that node into mstset 118 | mstset[node0.vertex] = true; 119 | 120 | // For all adjacent vertex of the extracted vertex V 121 | for (node1 iterator : graph.adj[node0.vertex]) { 122 | 123 | // If V is in queue 124 | if (mstset[iterator.dest] == false) { 125 | // If the key value of the adjacent vertex is 126 | // more than the extracted key 127 | // update the key value of adjacent vertex 128 | // to update first remove and add the updated vertex 129 | if (e[iterator.dest].key > iterator.weight) { 130 | queue.remove(e[iterator.dest]); 131 | e[iterator.dest].key = iterator.weight; 132 | queue.add(e[iterator.dest]); 133 | parent[iterator.dest] = node0.vertex; 134 | } 135 | } 136 | } 137 | } 138 | 139 | // Prints the vertex pair of mst 140 | for (int o = 1; o < graph.V; o++) 141 | System.out.println(parent[o] + " " 142 | + "-" 143 | + " " + o); 144 | } 145 | 146 | public static void main(String[] args) 147 | { 148 | int V = 9; 149 | 150 | Graph graph = new Graph(V); 151 | 152 | prims e = new prims(); 153 | 154 | e.addEdge(graph, 0, 1, 4); 155 | e.addEdge(graph, 0, 7, 8); 156 | e.addEdge(graph, 1, 2, 8); 157 | e.addEdge(graph, 1, 7, 11); 158 | e.addEdge(graph, 2, 3, 7); 159 | e.addEdge(graph, 2, 8, 2); 160 | e.addEdge(graph, 2, 5, 4); 161 | e.addEdge(graph, 3, 4, 9); 162 | e.addEdge(graph, 3, 5, 14); 163 | e.addEdge(graph, 4, 5, 10); 164 | e.addEdge(graph, 5, 6, 2); 165 | e.addEdge(graph, 6, 7, 1); 166 | e.addEdge(graph, 6, 8, 6); 167 | e.addEdge(graph, 7, 8, 7); 168 | 169 | // Method invoked 170 | e.prims_mst(graph); 171 | } 172 | } 173 | -------------------------------------------------------------------------------- /Algorithms/matrixProblems.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | public class Main { 3 | public static void main(String[] args) { 4 | Scanner sc=new Scanner(System.in); 5 | System.out.println("1. Add matrices\n" + "2. Multiply matrix by a constant\n" + "3. Multiply matrices\n" +"4. Transpose matrix\n"+ "0. Exit"); 6 | while(true) 7 | { 8 | switch(sc.nextInt()) 9 | { 10 | case 1: addition(); 11 | break; 12 | case 2: multiplyConstant(); 13 | break; 14 | case 3: multiplyMatrix(); 15 | break; 16 | case 4: transposeMatrix(); 17 | break; 18 | case 0:return; 19 | } 20 | } 21 | } 22 | public static void addition() 23 | { 24 | Scanner sc=new Scanner(System.in); 25 | System.out.println("Enter size of first matrix:"); 26 | int n1=sc.nextInt(); 27 | int m1=sc.nextInt(); 28 | double[][] one=new double[n1][m1]; 29 | int i,j; 30 | System.out.println("Enter first matrix:"); 31 | for( i=0;i-1;i--) 158 | { 159 | for(j=col-1;j>-1;j--) 160 | System.out.print(arr[j][i]+" "); 161 | System.out.println(); 162 | } 163 | } 164 | public static void vertD(double[][] arr,int row,int col) 165 | { 166 | int i,j; 167 | for(i=0;i-1;j--) 170 | System.out.print(arr[i][j]+" "); 171 | System.out.println(); 172 | } 173 | } 174 | public static void horiD(double[][] arr,int row,int col) 175 | { 176 | int i,j; 177 | for(i=row-1;i>-1;i--) 178 | { 179 | for(j=0;j