├── .bin ├── install_apt.sh ├── install_go.sh ├── install_npm.sh ├── install_pip2.sh ├── install_pip3.sh └── test_running.sh ├── .coafile ├── .codeclimate.yml ├── .editorconfig ├── .gitignore ├── .travis.yml ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── Disjoint_union_set └── Disjoint_union_set.c ├── ISSUE_TEMPLATE.md ├── LICENSE ├── PULL_REQUEST_TEMPLATE.md ├── README.md ├── Soundex Algorithm └── Soundex.java ├── apt-requirements.txt ├── avl_tree ├── AvlTree.java └── avl_tree.c ├── bin_sort ├── BinSort.java ├── bin_sort.c ├── bin_sort.go └── bin_sort.py ├── binary_search ├── BinarySearch.cs ├── BinarySearch.java ├── binarySearch.js ├── binary_search.c ├── binary_search.cpp ├── binary_search.go └── binary_search.py ├── binary_search_tree ├── BinarySearchTree.java ├── BinarySearchTree.py ├── Mirror_of_Binary_Search_Tree.java └── binary_search_tree.go ├── breadth_first_search ├── BreadthFirstSearch.cpp ├── BreadthFirstSearch.java └── breadth_first_search.py ├── breadth_first_traversal ├── breadthFirstTraversal.java ├── breadth_first_traversal.cpp └── breadth_first_traversal.py ├── coin_change_problem ├── CoinChangeProblem.java ├── coinChangeProblem.js ├── coin_change_problem.c ├── coin_change_problem.go └── coin_change_problem.py ├── counting_sort ├── CountingSort.cs ├── CountingSort.java ├── countingSort.js ├── counting_sort.c ├── counting_sort.go └── counting_sort.py ├── depth_first_traversal ├── DepthFirstTraversal.java └── DepthFirstTraversal.py ├── dijkstra ├── Dijkstra.java ├── dijkstra.c ├── dijkstra.js └── dijkstra.py ├── double_ended_queue └── doubleEndedQueue.c ├── doubly_linked_list └── doublyLinkedList.c ├── euclidean_gcd ├── EuclideanGCD.cpp ├── EuclideanGCD.cs ├── EuclideanGCD.java ├── euclideanGCD.js ├── euclidean_gcd.c ├── euclidean_gcd.go └── euclidean_gcd.py ├── exponentiation_by_squaring ├── ExponentiationBySquaring.java ├── exponentiationBySquaring.js ├── exponentiation_by_squaring.c ├── exponentiation_by_squaring.go └── exponentiation_by_squaring.py ├── fibonacci_number ├── FibonacciNumber.c ├── FibonacciNumber.java ├── FibonacciNumber.js └── FibonacciNumber.py ├── heap_sort ├── HeapSort.java ├── heapSort.js ├── heap_sort.c ├── heap_sort.py └── heapsort.cpp ├── insertion_sort ├── InsertionSort.cs ├── InsertionSort.java ├── insertionSort.js ├── insertion_sort.c ├── insertion_sort.cpp ├── insertion_sort.go └── insertion_sort.py ├── k_nn └── k_nn.py ├── largest_sum_contiguous_subarray ├── LargestSumContiguousSubarray.java ├── largestSumContiguousSubarray.c ├── largestSumContiguousSubarray.go ├── largestSumContiguousSubarray.js └── largest_sum_contiguous_subarray.py ├── linear_regression └── linear_regression.py ├── linear_search ├── LinearSearch.cs ├── LinearSearch.java ├── Linear_Search.cpp ├── linear-search.go ├── linearSearch.js ├── linear_search.c └── linear_search.py ├── linked_list ├── LinkedList.cs ├── LinkedList.java ├── linkedList.c ├── linkedList.js ├── linked_list.go └── linked_list.py ├── longest_common_subsequence ├── LongestCommonSubsequence.java ├── longestCommonSubsequence.c ├── longestCommonSubsequence.go ├── longestCommonSubsequence.js └── longest_common_subsequence.py ├── longest_palindromic_substring ├── LongestPalindromicSubstring.java ├── longestPalindromicSubstring.js ├── longest_palindromic_substring.cpp ├── longest_palindromic_substring.go └── longest_palindromic_substring.py ├── merge_sort ├── MergeSort.cs ├── MergeSort.java ├── mergeSort.js ├── merge_sort.c ├── merge_sort.go └── merge_sort.py ├── modular_exponential ├── ModularExponential.java ├── modularExponential.js ├── modular_exponential.c ├── modular_exponential.go └── modular_exponential.py ├── n_queen_problem ├── NQueenProblem.cpp ├── NQueenProblem.java ├── n_queen_problem.go └── n_queen_problem.py ├── npm-requirements.txt ├── pip2-requirements.txt ├── pip3-requirements.txt ├── prime_factor ├── PrimeFactor.java ├── primeFactor.js ├── prime_factor.c ├── prime_factor.go └── prime_factor.py ├── prims ├── Prims.java ├── prims.c ├── prims.go └── prims.js ├── queue ├── Queue.java ├── queue.cpp └── queue.py ├── quick_select ├── QuickSelect.java ├── quick_select.c └── quick_select.py ├── quick_sort ├── QuickSort.cs ├── QuickSort.java ├── quickSort.js ├── quick_sort.go ├── quick_sort.py └── quicksort.c ├── radix_sort ├── RadixSort.java ├── radix_sort.c ├── radix_sort.cs └── radix_sort.py ├── rod_cutting_problem ├── RodCutting.java ├── rodCuttingProblem.js ├── rod_cutting.c ├── rod_cutting.go └── rod_cutting.py ├── shell_sort ├── ShellSort.cpp ├── ShellSort.cs ├── ShellSort.java ├── shellSort.js ├── shell_sort.go └── shell_sort.py ├── sieve_of_eratosthenes ├── SieveOfEratosthenes.java ├── sieveOfEratosthenes.c ├── sieveOfEratosthenes.js ├── sieve_of_eratosthenes.go └── sieve_of_eratosthenes.py ├── sleep_sort ├── SleepSort.java ├── sleep_sort.cpp ├── sleep_sort.go └── sleep_sort.py ├── stack ├── Stack.cs ├── Stack.java ├── stack.c ├── stack.go ├── stack.js └── stack.py └── trie ├── Trie.cs ├── Trie.java ├── trie.cpp └── trie.go /.bin/install_apt.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # PPA for latest go 4 | sudo add-apt-repository -y ppa:longsleep/golang-backports 5 | 6 | sudo apt-get update 7 | sudo apt-get install -y $(grep -vE "^\s*#" apt-requirements.txt | tr "\n" " ") 8 | -------------------------------------------------------------------------------- /.bin/install_go.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | go get -u golang.org/x/lint/golint 3 | cd $GOPATH/src/golang.org/x/lint 4 | go install . 5 | -------------------------------------------------------------------------------- /.bin/install_npm.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | npm install -g $(grep -vE "^\s*#" npm-requirements.txt | tr "\n" " ") 3 | -------------------------------------------------------------------------------- /.bin/install_pip2.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | sudo -H pip2 install --upgrade pip 3 | sudo -H pip2 install --ignore-installed -Ur pip2-requirements.txt 4 | -------------------------------------------------------------------------------- /.bin/install_pip3.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | sudo -H python3 -m pip install --upgrade pip 3 | sudo -H python3 -m pip install --ignore-installed -Ur pip3-requirements.txt 4 | -------------------------------------------------------------------------------- /.bin/test_running.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | 4 | echo "Testing C files..." 5 | for i in $(ls -1 **/*.c); do 6 | echo " Compiling $i - gcc $i -lm -std=c11" 7 | gcc $i -lm -std=c11 8 | echo " Running $i - ./a.out > /dev/null" 9 | ./a.out > /dev/null 10 | rm -f a.out 11 | echo "" 12 | done 13 | 14 | echo "" 15 | echo "Testing C++ files..." 16 | for i in $(ls -1 **/*.cpp); do 17 | echo " Compiling $i - g++ $i -lm -pthread -std=c++11" 18 | g++ $i -lm -pthread -std=c++11 19 | echo " Running $i - ./a.out > /dev/null" 20 | ./a.out > /dev/null 21 | rm -f a.out 22 | echo "" 23 | done 24 | 25 | echo "" 26 | echo "Testing Java files..." 27 | for i in $(ls -1 **/*.java); do 28 | echo " Compiling $i - javac -Werror -Xlint:all $i -d ." 29 | javac -Werror -Xlint:all $i -d . 30 | filename="${i##*/}" 31 | classname="${filename%.*}" 32 | echo " Running $i - java $classname > /dev/null" 33 | java $classname > /dev/null 34 | echo "" 35 | done 36 | rm -f *.class 37 | 38 | echo "Testing Python files..." 39 | for i in $(ls -1 **/*.py); do 40 | echo " Running $i - python2 $i > /dev/null" 41 | python2 $i > /dev/null 42 | echo " Running $i - python3 $i > /dev/null" 43 | python3 $i > /dev/null 44 | echo "" 45 | done 46 | 47 | echo "" 48 | echo "Running Go files..." 49 | for i in $(ls -1 **/*.go); do 50 | echo " Running $i - go run $i > /dev/null" 51 | go run $i > /dev/null 52 | echo "" 53 | done 54 | 55 | echo "" 56 | echo "Running JavaScript files..." 57 | for i in $(ls -1 **/*.js); do 58 | echo " Running $i - node --use-strict --harmony $i > /dev/null" 59 | node --use-strict --harmony $i > /dev/null 60 | echo "" 61 | done 62 | 63 | echo "" 64 | echo "Running C# files..." 65 | for i in $(ls -1 **/*.cs); do 66 | echo " Compiling $i - mcs $i" 67 | mcs $i 68 | excname="${i%.*}".exe 69 | echo " Running $i - mono $excname > /dev/null" 70 | mono $excname > /dev/null 71 | echo "" 72 | done 73 | -------------------------------------------------------------------------------- /.coafile: -------------------------------------------------------------------------------- 1 | # coafile for this project 2 | # please add more settings beneath 3 | # Local fixing 4 | # coala --apply-patches -n 5 | 6 | # python files should only use spaces 7 | [Python Spacing] 8 | files = **/*.py 9 | bears = SpaceConsistencyBear 10 | use_spaces = True 11 | 12 | # golint 13 | # [Golint] 14 | # files = **/*.go 15 | # bears = GoLintBear 16 | 17 | # gofmt 18 | [Gofmt] 19 | files = **/*.go 20 | bears = GofmtBear 21 | 22 | # python lint 23 | [pep8] 24 | files = **/*.py 25 | bears = PEP8Bear 26 | 27 | # Haskell 28 | [haskell] 29 | files = **/*.hs 30 | bears = HaskellLintBear 31 | 32 | # hlint 33 | [hlint] 34 | files = **/*.hs 35 | bears = GhcModBear 36 | 37 | # JavaScript 38 | [happiness] 39 | files = **/*.js 40 | bears = HappinessLintBear 41 | 42 | # CSharp 43 | [csharp] 44 | files = **/*.cs 45 | bears = CSharpLintBear 46 | -------------------------------------------------------------------------------- /.codeclimate.yml: -------------------------------------------------------------------------------- 1 | --- 2 | engines: 3 | duplication: 4 | enabled: true 5 | checks: 6 | Similar code: 7 | enabled: false # matches in different files 8 | config: 9 | languages: 10 | - javascript 11 | - python 12 | fixme: 13 | enabled: true 14 | radon: 15 | enabled: true 16 | checks: 17 | Complexity: 18 | enabled: false 19 | ratings: 20 | paths: 21 | - "**.js" 22 | - "**.py" 23 | exclude_paths: [] 24 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | end_of_line = lf 6 | insert_final_newline = true 7 | 8 | [*.{go,c,cpp}] 9 | indent_style = tab 10 | tab_width = 4 11 | trim_trailing_whitespace = true 12 | 13 | [*.js] 14 | indent_style = tab 15 | tab_width = 2 16 | trim_trailing_whitespace = true 17 | 18 | [*.{py,java,cs}] 19 | indent_style = space 20 | indent_size = 4 21 | trim_trailing_whitespace = true 22 | 23 | [*.{c,cpp,java,js}] 24 | block_comment_start = /* 25 | block_comment = * 26 | block_comment_end = */ 27 | 28 | [*.yml] 29 | indent_style = space 30 | indent_size = 2 31 | trim_trailing_whitespace = true 32 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # python 2 | *.pyc 3 | # C/CPP 4 | *.exe 5 | *.out 6 | # Java 7 | *.class 8 | # MacOS 9 | .DS_Store 10 | # coala 11 | *.orig 12 | 13 | # Jetbrains 14 | .idea/ 15 | # vscode project files 16 | .vscode/ 17 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | dist: xenial 2 | sudo: required 3 | language: node_js 4 | node_js: 5 | "7" 6 | 7 | env: 8 | GOPATH: $HOME/go 9 | PATH: $GOPATH/bin:$PATH 10 | 11 | install: 12 | - ./.bin/install_apt.sh 13 | - ./.bin/install_go.sh 14 | - ./.bin/install_npm.sh 15 | - ./.bin/install_pip2.sh 16 | - ./.bin/install_pip3.sh 17 | 18 | script: 19 | - ./.bin/test_running.sh 20 | - coala --ci 21 | - eclint check "**/*.{java,c,cpp,js,cs}" 22 | -------------------------------------------------------------------------------- /Disjoint_union_set/Disjoint_union_set.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int find(int a, int parent[]) // recursive function to find parent of a 4 | { 5 | if (parent[a] == a) // if root itself is a parent 6 | return a; 7 | else 8 | return find(parent[a], parent); // to find the parent of the parent 9 | } 10 | 11 | void unionn(int a, int b, int parent[], int rank[]) // function to do unionn of a and b 12 | { 13 | int a1 = find(a, parent); // to find parent of a 14 | int b1 = find(b, parent); // to find parent of b 15 | if (a1 == b1) // if both have same parent that is both are in same set 16 | { 17 | printf("both the elements are in same set\n"); 18 | return; 19 | } 20 | if (rank[a1] > rank[b1]) // if height of parent of a is greater than height of parent of b 21 | { 22 | parent[b1] = a1; 23 | } 24 | else if (rank[a1] < rank[b1]) // if height of parent of b is greater than height of parent of a 25 | { 26 | parent[a1] = b1; 27 | } 28 | else // if height of both parent is same 29 | { 30 | parent[a1] = b1; 31 | rank[b1]++; 32 | } 33 | } 34 | int main() 35 | { 36 | int n = 10; 37 | int parent[n]; 38 | int rank[n]; 39 | 40 | for (int i = 0; i < 10; i++) 41 | parent[i] = i; // in starting the node is itself the parent 42 | for (int i = 0; i < 10; i++) 43 | rank[i] = 1; // by default the rank of all nodes is 1 44 | 45 | unionn(3, 8, parent, rank); // 3 is friend of 8 46 | unionn(3, 6, parent, rank); // 3 is friend of 6 47 | printf("the parent of 8 is %d\n", find(8, parent)); 48 | 49 | unionn(1, 9, parent, rank); // 1 is friend of 9 50 | unionn(2, 8, parent, rank); // 2 is friend of 8 51 | unionn(5, 8, parent, rank); // 5 is friend of 8 52 | 53 | unionn(2, 9, parent, rank); // 2 is friend of 9 54 | printf("the parent of 2 is %d\n", find(2, parent)); 55 | printf("the parent of 8 is%d\n", find(8, parent)); 56 | 57 | if (find(5, parent) == find(7, parent)) // to check whether 5 is friend of 7 or not 58 | printf("5 is a friend of 7\n"); 59 | else 60 | printf("5 is not a friend of 7\n"); 61 | if (find(3, parent) == find(1, parent)) // to check whether 3 is friend of 1 or not 62 | printf("3 is a friend of 1\n"); 63 | else 64 | printf("3 is not a friend of 1\n"); 65 | 66 | return 0; 67 | } 68 | -------------------------------------------------------------------------------- /ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 2 | #### This issue is about [Algo/DS Name](link to resource for the Algo/DS). 3 | 4 | - [ ] Issue Title is in form `Algo/DS Name [Language]`. 5 | - [ ] I searched or browsed the repo’s other issues to ensure this is not a duplicate. 6 | - [ ] This Algo/DS is worth adding to this repository. 7 | - [ ] Assign this issue to me (I want to work on this). 8 | - [ ] I ensure that I am not already assigned to 2 or more issues. 9 | - [ ] I will send my PR only after I'm assigned to this issue by any maintainer. 10 | - [ ] I understand that I will be unassigned from this issue if I fail to send a PR for this within a week. 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2017 IIITV GitHub Group 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 9 | 10 | Fixes #{ISSUE_NUMBER} 11 | 12 | 13 | #### By submitting this pull request I confirm I've read and complied with the below declarations. 14 | 15 | - [ ] I have read the [Contribution guidelines](https://github.com/iiitv/algos/blob/master/CONTRIBUTING.md) and I am confident that my PR reflects them. 16 | - [ ] I have followed the [coding guidelines](https://github.com/iiitv/algos/blob/master/CONTRIBUTING.md#cs) for this project. 17 | - [ ] My code follows the [skeleton code structure](https://github.com/iiitv/algos/blob/master/CONTRIBUTING.md#sample). 18 | - [ ] This pull request has a descriptive title. For example, `Added {Algorithm/DS name} [{Language}]`, not `Update README.md` or `Added new code`. 19 | - [ ] This pull request will be closed if I fail to update it even once in a continuous time span of 7 days. 20 | - [ ] This pull request shall only be reviewed and merged once the Travis build passes. No maintainer or supporter shall be obliged to review it before this condition is met. 21 | - [ ] I have mentioned the issue number correctly (with hyperlink) in this pull request description. 22 | -------------------------------------------------------------------------------- /Soundex Algorithm/Soundex.java: -------------------------------------------------------------------------------- 1 | public class Soundex { 2 | 3 | public static void soundex(String str) { 4 | 5 | char[] s = str.toUpperCase().toCharArray(); 6 | //retaining first letter 7 | String output = s[0] + ""; 8 | 9 | //replacing consonants with digits 10 | for(int i = 0; i avg case and O(n^2)-> Worst Case 14 | // constraints:- 0<=A[i]<1 15 | public class BinSort { 16 | public static void binSort(Node[] b, double[] a) { 17 | for (int i = 0; i < a.length; i++) { 18 | int ins = (int) (a[i] * b.length); 19 | if (b[ins] == null) { 20 | b[ins] = new Node(a[i]); 21 | } else { 22 | boolean check = true; 23 | Node temp = b[ins]; 24 | while (temp.next != null) { 25 | if (a[i] > temp.next.data) { 26 | temp = temp.next; 27 | } else { 28 | if (a[i] < temp.data) 29 | break; 30 | Node newNode = new Node(a[i]); 31 | newNode.next = temp.next; 32 | temp.next = newNode; 33 | check = false; 34 | break; 35 | } 36 | } 37 | if (check) { 38 | if (a[i] >= temp.data) { 39 | Node newNode = new Node(a[i]); 40 | temp.next = newNode; 41 | } else { 42 | double loc = temp.data; 43 | temp.data = a[i]; 44 | Node newNode = new Node(loc); 45 | newNode.next = temp.next; 46 | temp.next = newNode; 47 | } 48 | } 49 | } 50 | } 51 | int j = 0; 52 | for (int i = 0; i < b.length; i++) { 53 | while (b[i] != null) { 54 | a[j++] = b[i].data; 55 | b[i] = b[i].next; 56 | } 57 | } 58 | } 59 | 60 | public static void main(String[] args) { 61 | Node[] b = new Node[10]; 62 | Random ran = new Random(); 63 | int n = 100; 64 | double[] a = new double[n]; 65 | for (int i = 0; i < n; i++) { 66 | a[i] = ran.nextDouble(); 67 | } 68 | binSort(b, a); 69 | for (int i = 0; i < n; i++) { 70 | System.out.print(a[i] + " "); 71 | } 72 | System.out.println(" "); 73 | } 74 | } 75 | 76 | -------------------------------------------------------------------------------- /bin_sort/bin_sort.c: -------------------------------------------------------------------------------- 1 | /* Following algorithm sorts the input array in ascending order 2 | * Time Complexity : O(n)-> Avg case and O(n^2)-> Worst Case 3 | */ 4 | #include 5 | #include 6 | 7 | struct bucket { 8 | int count; 9 | float* value; 10 | }; 11 | 12 | int comparator(const void* first, const void* second) { 13 | float a = *((int*)first), b = *((int*)second); 14 | int result = a - b; 15 | return (0 < result) - (result < 0); 16 | } 17 | 18 | void bucket_sort(float array[], int n) { 19 | struct bucket buckets[n]; 20 | int a, b, c; 21 | for (a = 0; a < n; a++) { 22 | buckets[a].count = 0; 23 | buckets[a].value = malloc(sizeof(int) * n); 24 | } 25 | for (a = 0; a < n; a++) { 26 | int bi; 27 | bi = n * array[a]; 28 | buckets[bi].value[buckets[bi].count++] = array[a]; 29 | } 30 | for (c = 0, a = 0; a < n; a++) { 31 | qsort(buckets[a].value, buckets[a].count, sizeof(int), &comparator); 32 | for (b = 0; b < buckets[a].count; b++) { 33 | array[c + b] = buckets[a].value[b]; 34 | } 35 | c += buckets[a].count; 36 | free(buckets[a].value); 37 | } 38 | } 39 | 40 | int main() { 41 | float array[100]; 42 | int n = 100; 43 | int j, k; 44 | for (k = 0; k < n; k++) { 45 | array[k] = (double)(rand() % 1000) / 1000; 46 | } 47 | bucket_sort(array, n); 48 | for (j = 0; j < n; j++) { 49 | printf("%f ", array[j]); 50 | } 51 | printf("\n"); 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /bin_sort/bin_sort.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math/rand" 6 | "sort" 7 | ) 8 | 9 | // Bucket is a type alias of []float32. It is used in BucketSort() to represent 10 | // individual buckets. 11 | type Bucket []float32 12 | 13 | // Methods required for sort.Sort() 14 | func (b Bucket) Len() int { 15 | return len(b) 16 | } 17 | 18 | func (b Bucket) Swap(i, j int) { 19 | b[i], b[j] = b[j], b[i] 20 | } 21 | 22 | func (b Bucket) Less(i, j int) bool { 23 | return b[i] < b[j] 24 | } 25 | 26 | // BucketSort sorts provided slice of floats using Bucket Sort algorithm 27 | // Time Complexity: O(n)-> Avg case and O(n^2)-> Worst Case 28 | // Constraints: 0 <= arr[i] <= 1 29 | func BucketSort(arr []float32) []float32 { 30 | n := len(arr) 31 | 32 | // Create n empty buckets, each can hold up to n elements 33 | buckets := make([]Bucket, n) 34 | for i := 0; i < n; i++ { 35 | // Set length to 0, but allocate memory for n elements 36 | buckets[i] = make([]float32, 0, n) 37 | } 38 | 39 | // Place all the elements into corresponding buckets 40 | for i := 0; i < n; i++ { 41 | bi := int(float32(n) * arr[i]) 42 | buckets[bi] = append(buckets[bi], arr[i]) 43 | } 44 | 45 | // Sort elements in each bucket 46 | for i := 0; i < n; i++ { 47 | sort.Sort(buckets[i]) 48 | } 49 | 50 | // Put sorted elements into the resulting array 51 | sorted := make([]float32, 0, n) 52 | for i := 0; i < n; i++ { 53 | for j := 0; j < len(buckets[i]); j++ { 54 | sorted = append(sorted, buckets[i][j]) 55 | } 56 | } 57 | return sorted 58 | } 59 | 60 | func makeRandomNumbers(n int) []float32 { 61 | arr := make([]float32, n) 62 | for i := range arr { 63 | arr[i] = rand.Float32() 64 | } 65 | return arr 66 | } 67 | 68 | func main() { 69 | n := 10 70 | arr := makeRandomNumbers(n) 71 | sorted := BucketSort(arr) 72 | fmt.Println(sorted) 73 | } 74 | -------------------------------------------------------------------------------- /bin_sort/bin_sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | Following is the implementation of bin sort algorithm. 3 | It will sort the input array with time complexity 0(N + K) 4 | N being the size of array, K being the number of buckets. 5 | Space complexity is at worst O(NK). 6 | """ 7 | 8 | 9 | def insertion_sort(a): 10 | """ 11 | :param a: list 12 | List of objects with an order 13 | :return: list 14 | Sorted list with insertion sort algorithm 15 | """ 16 | 17 | for i in range(1, len(a)): 18 | current_value = a[i] 19 | position = i 20 | 21 | while position > 0 and a[position - 1] > current_value: 22 | a[position] = a[position - 1] 23 | position -= 1 24 | a[position] = current_value 25 | 26 | return a 27 | 28 | 29 | def get_buckets(a, bucket_size): 30 | """ 31 | :param a: list 32 | List of objects with an order 33 | :param bucket_size: int 34 | Size of buckets to fill 35 | :return: list 36 | List of buckets to sort array with 37 | """ 38 | 39 | min_v, max_v = min(a), max(a) # min and max values in array 40 | bucket_count = (max_v - min_v) // bucket_size + 1 41 | buckets = [[] for _ in range(int(bucket_count))] # initialize buckets 42 | for x in a: # distribute values into buckets 43 | buckets[int((x - min_v) // bucket_size)].append(x) 44 | return buckets 45 | 46 | 47 | def bin_sort(a, bucket_size=16): 48 | """ 49 | :param a: list 50 | List of objects with an order 51 | :param bucket_size: int 52 | Size of buckets to fill 53 | :return: list 54 | Sorted list with bin sort algorithm 55 | """ 56 | 57 | if len(a) == 0: # trivial case 58 | return a 59 | 60 | buckets = get_buckets(a, bucket_size) # get buckets 61 | a = [] 62 | for bucket in buckets: # sort each bucket ... 63 | a += insertion_sort(bucket) # ... and place back into array 64 | return a 65 | 66 | 67 | def main(): 68 | """ 69 | Sorts sample list with bin sort algorithm, 70 | then prints sorted list 71 | """ 72 | 73 | unsorted_list = [ 74 | 4372.30, 851821, 184.681, 173673, 133.06, 768361, 431.982, 9567.00, 75 | 5566.81, 1982.08, 983511, 170.469, 313978, 552536, 3348.18, 527289, 76 | 95.9491, 303675, 532988, 65143 77 | ] 78 | 79 | sorted_list = bin_sort(unsorted_list) 80 | print(sorted_list) 81 | 82 | 83 | if __name__ == '__main__': 84 | main() 85 | -------------------------------------------------------------------------------- /binary_search/BinarySearch.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class BinarySearch 4 | { 5 | public static void Main() 6 | { 7 | int[] data = new int[] {1, 5, 6, 8, 13, 45, 65, 121, 123, 163, 245, 334}; 8 | int target = 123; 9 | int index = Search(data, target); 10 | if(index >= 0) 11 | { 12 | Console.WriteLine("Index of target: " + index); 13 | } 14 | else 15 | { 16 | Console.WriteLine("Not found\n"); 17 | } 18 | } 19 | 20 | public static int Search(int[] data, int target) 21 | { 22 | int left = 0, right = data.Length; 23 | while(left <= right) 24 | { 25 | int mid = (left + right) / 2; 26 | if (data[mid] == target) 27 | { 28 | return mid; 29 | } 30 | if (data[mid] < target) 31 | { 32 | left = mid + 1; 33 | } 34 | else 35 | { 36 | right = mid - 1; 37 | } 38 | } 39 | return -1; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /binary_search/BinarySearch.java: -------------------------------------------------------------------------------- 1 | public class BinarySearch { 2 | 3 | /** 4 | *

Searches searchElement in arr and returns the index where it's found or -1 if not found.

5 | * 6 | *

The given array must be already sorted otherwise the results are undefined.

7 | * 8 | *

If there a duplicate elements, there is no guarantee which one will be found.

9 | * 10 | *

This implementation avoids a possible overflow while calculating the index for the middle element. 11 | * @see Extra, Extra - 12 | * Read All About It: Nearly All Binary Searches and Mergesorts are Broken

13 | * 14 | * @param arr 15 | * @param searchElement 16 | * @return 17 | */ 18 | public static int binarySearch(int[] arr, int searchElement) { 19 | int left = 0; 20 | int right = arr.length - 1; 21 | while (left <= right) { 22 | int mid = left + (right - left) / 2; // identical to (left + right) / 2 but avoids overflow 23 | if (arr[mid] == searchElement) { // Element found 24 | return mid; 25 | } 26 | if (arr[mid] < searchElement) { // Look in right half 27 | left = mid + 1; 28 | } else { // Look in left half 29 | right = mid - 1; 30 | } 31 | } 32 | 33 | return -1; // Element not found 34 | } 35 | 36 | public static void main(String[] args) { 37 | int[] arr = new int[] {1, 5, 35, 112, 258, 324}; 38 | int[] searchArr = new int[] {1, 35, 112, 324, 67}; 39 | int pos; 40 | for (int i = 0; i < searchArr.length; i++) { 41 | pos = binarySearch(arr, searchArr[i]); //search key and get poistion 42 | if (pos >= 0) { 43 | System.out.println(searchArr[i] + "-> found at index : " + pos); 44 | } else { 45 | System.out.println(searchArr[i] + "-> not found"); 46 | } 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /binary_search/binarySearch.js: -------------------------------------------------------------------------------- 1 | function binarySearchIterative (arr, item) { 2 | /* 3 | Performs a binary search iteratively 4 | :param arr: List of elements to search from 5 | :param item: Element to search for 6 | :return: returns index if element found else -1 7 | */ 8 | let begin = 0; 9 | let end = arr.length - 1; 10 | while (begin <= end) { 11 | let mid = Math.floor((begin + end) / 2); 12 | if (arr[mid] === item) { 13 | return mid; 14 | } else if (arr[mid] > item) { 15 | end = mid - 1; 16 | } else { 17 | begin = mid + 1; 18 | } 19 | } 20 | return -1; 21 | } 22 | 23 | function binarySearchRecursive (arr, item, begin, end) { 24 | /* 25 | Performs a binary search recursively 26 | :param arr: List of elements to search from 27 | :param item: Element to search for 28 | :param begin: Left limit of array 29 | :param end: Right limit of array 30 | :return: returns index if element found else -1 31 | */ 32 | if (begin <= end) { 33 | let mid = Math.floor((begin + end) / 2); 34 | if (arr[mid] === item) { 35 | return mid; 36 | } else if (arr[mid] > item) { 37 | return binarySearchRecursive(arr, item, begin, mid - 1); 38 | } else { 39 | return binarySearchRecursive(arr, item, mid + 1, end); 40 | } 41 | } else { 42 | return -1; 43 | } 44 | } 45 | 46 | function main () { 47 | let arr = [2, 5, 6, 7, 8, 9, 10]; 48 | let item = 5; 49 | if (binarySearchIterative(arr, item) === -1) { 50 | console.log('Element is not found'); 51 | } else { 52 | console.log('Element is found'); 53 | } 54 | 55 | if (binarySearchRecursive(arr, item, 0, arr.length - 1) === -1) { 56 | console.log('Element is not found'); 57 | } else { 58 | console.log('Element is found'); 59 | } 60 | } 61 | 62 | main(); 63 | -------------------------------------------------------------------------------- /binary_search/binary_search.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | /* 4 | * @arr Array pointer 5 | * @arr_size Size of array 6 | * @search_element Element to be searched 7 | */ 8 | 9 | /* function to perform recursive binary search 10 | * input parameters: 11 | * @ar - user-input array. 12 | * @l - left index of array. 13 | * @r - right index of array. 14 | * @ele - element to be searched. 15 | */ 16 | int binary_search_recursive(const int *ar, int l, int r, int ele) { 17 | if (r >= l) { 18 | 19 | int mid = l + (r - l) / 2; //calculate mid point of the array 20 | 21 | // If the element is present at the middle itself 22 | if (ar[mid] == ele) { 23 | return mid; 24 | } 25 | 26 | // If element is smaller than mid, then it can only be present 27 | // in left subarray 28 | if (ar[mid] > ele) { 29 | return binary_search_recursive(ar, l, mid - 1, ele); 30 | } 31 | 32 | // Else the element can only be present in right subarray 33 | return binary_search_recursive(ar, mid + 1, r, ele); 34 | } 35 | 36 | // We reach here when element is not present in array 37 | return -1; 38 | } 39 | 40 | //Function to perform iterative binary search 41 | int binary_search(const int *arr, int arr_size, int search_element) { 42 | int left = 0, right = arr_size - 1; 43 | 44 | while (left <= right) { 45 | int mid = left + (right - left) / 2; 46 | 47 | if (arr[mid] == search_element) // Element found 48 | return mid; 49 | if (arr[mid] < search_element) // Look in right half 50 | left = mid + 1; 51 | else // Look in left half 52 | right = mid - 1; 53 | } 54 | 55 | return -1; // Element not found 56 | } 57 | 58 | int main() { 59 | int arr[] = {1, 5, 35, 112, 258, 324}; 60 | int search_arr[] = {1, 35, 112, 324, 67}; 61 | int i; 62 | 63 | for (i = 0 ; i < 5 ; i++) { 64 | 65 | int pos; 66 | pos = binary_search(arr, 6, search_arr[i]); 67 | if (pos >= 0) { 68 | printf("%d found at index %d.\n", search_arr[i], pos); 69 | } else { 70 | printf("%d not found.\n", search_arr[i]); 71 | } 72 | 73 | pos = binary_search_recursive(arr, 0, 5, search_arr[i]); 74 | if (pos >= 0) { 75 | printf("%d found at index %d, recursively\n", search_arr[i], pos); 76 | } else { 77 | printf("%d not found.\n", search_arr[i]); 78 | } 79 | } 80 | 81 | return 0; 82 | } 83 | -------------------------------------------------------------------------------- /binary_search/binary_search.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to implement recursive Binary Search 2 | #include 3 | using namespace std; 4 | //header file 5 | 6 | int binarySearch(int arr[], int low, int high, int target) 7 | { 8 | if (high >= low){ 9 | int mid = low + (high-low)/2;//middle of the array 10 | if (arr[mid] == target) 11 | return mid;//If we find the tarrget element in the middle of the array 12 | else if(arr[mid] > target)//target element to left of the mid 13 | return binarySearch(arr, low, mid - 1, target); 14 | else if(arr[mid] < target)//target element to the right of the mid 15 | return binarySearch(arr, mid + 1, high, target); 16 | } 17 | return -1;//target eleement is not present in the array 18 | } 19 | 20 | int main() 21 | { int n; 22 | cout<<"Enter the size of array: "; 23 | cin>>n; 24 | int *arr= new int[n]; 25 | cout<<"Enter the array(it should be in ascending order)"<>arr[i]; 28 | int x; 29 | cout<<"Enter the target element: "; 30 | cin>>x; 31 | int result = binarySearch(arr, 0, n - 1, x); 32 | (result == -1) 33 | ? cout << "Element is not present in array" 34 | : cout << "Element is present at index " << result; 35 | return 0; 36 | } 37 | 38 | //Time Complexity: O(log n) 39 | //Space Complexity:O(log n) 40 | -------------------------------------------------------------------------------- /binary_search/binary_search.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | // BinarySearch perform Binary Search by Iterative Method. 6 | // Time Complexity : O(log(len(array))) 7 | func BinarySearch(array []int, target int) int { 8 | left, right := 0, len(array)-1 9 | for left <= right { 10 | mid := (left + right) / 2 11 | if array[mid] == target { 12 | return mid 13 | } 14 | if array[mid] < target { 15 | left = mid + 1 16 | } else { 17 | right = mid - 1 18 | } 19 | } 20 | return -1 21 | } 22 | 23 | func main() { 24 | array := []int{1, 5, 35, 112, 258, 324, 456, 512} 25 | index := BinarySearch(array, 112) 26 | if index == -1 { 27 | fmt.Println("Element is not present in array") 28 | } else { 29 | fmt.Println("Element is present at index :", index) 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /binary_search/binary_search.py: -------------------------------------------------------------------------------- 1 | from random import randint 2 | 3 | 4 | def binary_search(array, element): 5 | """ 6 | Perform Binary Search by Iterative Method. 7 | 8 | :param array: Iterable of elements 9 | :param element: element to search 10 | :return: returns value of index of element (if found) else return None 11 | """ 12 | left = 0 13 | right = len(array) - 1 14 | while left <= right: 15 | mid = (right + left) // 2 16 | # indices of a list must be integer 17 | if array[mid] == element: 18 | return mid 19 | elif array[mid] > element: 20 | right = mid - 1 21 | else: 22 | left = mid + 1 23 | return None 24 | 25 | 26 | def binary_search_recursive(array, element, left=0, right=None): 27 | """ 28 | Perform Binary Search by Iterative Method. 29 | 30 | :param array: Iterable of elements 31 | :param left: start limit of array 32 | :param right: end limit of array 33 | :param element: element to be searched 34 | :return: returns value of index of element (if found) else return None 35 | """ 36 | right = len(array) - 1 if right is None else right 37 | if right >= left: 38 | mid = (right + left) // 2 39 | if array[mid] == element: 40 | return mid 41 | elif array[mid] > element: 42 | return binary_search_recursive(array, element, left, mid - 1) 43 | else: 44 | return binary_search_recursive(array, element, mid + 1, right) 45 | else: 46 | return None 47 | 48 | 49 | def main(): 50 | size = 100 # user can change it 51 | domain = 100 # user can change it 52 | array = [1, 9, 11, 13, 5, 7, 8, 5, 17, 1156, 114] 53 | array.sort() 54 | element = 13 55 | result = binary_search_recursive(array, element) 56 | if result is None: 57 | print('Recursive Binary Search : Element not present in array') 58 | else: 59 | print('Recursive Binary Search : Element is present at index', result) 60 | result = binary_search(array, element) 61 | if result is None: 62 | print('Iterative Binary Search : Element not present in array') 63 | else: 64 | print('Iterative Binary Search : Element is present at index', result) 65 | 66 | 67 | if __name__ == '__main__': 68 | main() 69 | -------------------------------------------------------------------------------- /binary_search_tree/Mirror_of_Binary_Search_Tree.java: -------------------------------------------------------------------------------- 1 | package Binarytree; 2 | 3 | 4 | import java.util.Scanner; 5 | 6 | class Node{ 7 | int data; 8 | Node left; 9 | Node right; 10 | Node(int element) 11 | { 12 | this.data = element; 13 | this.left = this.right = null; 14 | } 15 | } 16 | 17 | class BST_mirror{ 18 | Node root; 19 | BST_mirror() 20 | { 21 | root = null; 22 | } 23 | void addNode(int element) 24 | { 25 | root = add(root,element); 26 | } 27 | Node add(Node node, int element) 28 | { 29 | if(node == null) 30 | return new Node(element); 31 | if(element<=node.data) 32 | node.left = add(node.left,element); 33 | else 34 | if(element>node.data) 35 | node.right = add(node.right,element); 36 | 37 | return node; 38 | } 39 | 40 | 41 | void inorder(Node root) 42 | { 43 | if(root == null) 44 | return; 45 | inorder(root.left); 46 | System.out.print(root.data+" "); 47 | inorder(root.right); 48 | } 49 | Node mirror() 50 | { 51 | return mirrorify(root); 52 | } 53 | Node mirrorify(Node node) 54 | { 55 | if(node == null) 56 | return null; 57 | // now in each step we have to create a new node and replace left right elem of old root node with new node's right left 58 | Node mirror_temp = new Node(node.data); 59 | mirror_temp.left = mirrorify(node.right); 60 | mirror_temp.right = mirrorify(node.left); 61 | return mirror_temp; 62 | } 63 | } 64 | 65 | public class mirror_Tree { 66 | public static void main(String[] args) { 67 | Scanner s = new Scanner(System.in); 68 | BST_mirror obj = new BST_mirror(); 69 | 70 | obj.addNode(9); 71 | obj.addNode(6); 72 | obj.addNode(8); 73 | obj.addNode(7); 74 | obj.addNode(13); 75 | obj.addNode(17); 76 | obj.addNode(19); 77 | System.out.println("Inorder of original Tree"); 78 | obj.inorder(obj.root); 79 | 80 | System.out.println(); 81 | System.out.println("Inorder of original Tree"); 82 | Node mirror_node; 83 | mirror_node = obj.mirror(); 84 | obj.inorder(mirror_node); 85 | 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /breadth_first_search/BreadthFirstSearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | vector BreadthFirstSearch(int vertex,vector adjacent[],int start_vertex,int destination){ 5 | queue que; 6 | //bfsPath will store the path 7 | vector bfsPath; 8 | //this array will take care of duplicate traversing 9 | bool visited[vertex]; 10 | vector::iterator it; 11 | que.push(start_vertex); 12 | bfsPath.push_back(start_vertex); 13 | visited[start_vertex]=true; 14 | int flag=0; 15 | while(!que.empty()){ 16 | int tem = que.front(); 17 | que.pop(); 18 | for(it = adjacent[tem].begin();itbfsPath){ 43 | vector::iterator it; 44 | for(it = bfsPath.begin();it adjacent[vertex]; 53 | adjacent[0].push_back(1); 54 | adjacent[0].push_back(3); 55 | adjacent[1].push_back(2); 56 | adjacent[2].push_back(3); 57 | //starting vertex 58 | int start_vertex = 0; 59 | //destination 60 | int destination = 3; 61 | vector bfsPath = BreadthFirstSearch(vertex,adjacent,start_vertex,destination); 62 | if(!bfsPath.empty()){ 63 | printTraversal(bfsPath); 64 | }else{ 65 | cout<<"path not found"; 66 | } 67 | return 0; 68 | } 69 | 70 | -------------------------------------------------------------------------------- /breadth_first_search/breadth_first_search.py: -------------------------------------------------------------------------------- 1 | """ 2 | Breadth-first search (BFS) is an algorithm for searching tree or 3 | graph data structures. It produces a set of actions to be follwed to reach a 4 | target state from the start state. Starting at the initial state (often the 5 | root node for a tree) it explores all neighbor nodes at each level 6 | before moving to the next level. 7 | """ 8 | 9 | from collections import deque, namedtuple 10 | 11 | 12 | def breadth_first_search(graph, start, target): 13 | """ Performs a breadth-first search on a graph 14 | 15 | Args: 16 | graph (list of list of int): Adjacency matrix representation of graph 17 | source (int): Index of source vertex to begin search from 18 | 19 | Returns: 20 | tuple (path, distance): path traversed from start to target, total 21 | distance of path 22 | None,None if target not found 23 | """ 24 | vertex_info = {} 25 | VistitedVertex = namedtuple("VisitedVertex", "parent distance") 26 | vertex_info[start] = VistitedVertex(None, 0) 27 | 28 | search_queue = deque() 29 | visited = set() 30 | search_queue.append(start) 31 | 32 | while search_queue: 33 | u = search_queue.popleft() 34 | if u == target: 35 | return construct_path(u, vertex_info) 36 | for v in graph[u]: 37 | if v not in visited: 38 | if v not in search_queue: 39 | vertex_info[v] = VistitedVertex( 40 | u, vertex_info[u].distance + 1) 41 | search_queue.append(v) 42 | visited.add(u) 43 | return None, None 44 | 45 | 46 | def construct_path(vertex, vertex_info): 47 | path = [] 48 | distance = vertex_info[vertex].distance 49 | while True: 50 | path.append(vertex) 51 | if vertex_info[vertex].parent is not None: 52 | vertex = vertex_info[vertex].parent 53 | else: 54 | break 55 | return path[::-1], distance 56 | 57 | 58 | def main(): 59 | graph_adj_list = [ 60 | [1], 61 | [0, 4, 5], 62 | [3, 4, 5], 63 | [2, 6], 64 | [1, 2], 65 | [1, 2, 6], 66 | [3, 5], 67 | [] 68 | ] 69 | 70 | start = 0 71 | target = 10 72 | path, distance = breadth_first_search(graph_adj_list, start, target) 73 | print('Path from vertex {} to vertex {}: {}'.format(start, target, path)) 74 | print('Path distance: {}'.format(distance)) 75 | 76 | 77 | if __name__ == '__main__': 78 | main() 79 | -------------------------------------------------------------------------------- /breadth_first_traversal/breadthFirstTraversal.java: -------------------------------------------------------------------------------- 1 | /* 2 | *Implementation of Breadth First Traversal in Graph 3 | *Time Complexity => O(v+e) v is no. of vertex and e is no. of edges 4 | *Space Complexity => O(v) 5 | *Adjacency List representation is used here 6 | */ 7 | 8 | import java.util.*; 9 | public class breadthFirstTraversal { 10 | 11 | public static void main(String[] args) { 12 | Graph g=new Graph(7); 13 | //1 Based indexing 14 | g.addEdge(1, 2); 15 | g.addEdge(1, 6); 16 | g.addEdge(2, 3); 17 | g.addEdge(2, 5); 18 | g.addEdge(6, 3); 19 | g.addEdge(6, 5); 20 | g.addEdge(5, 4); 21 | g.addEdge(3, 4); 22 | System.out.println("BFS Traversal of the given graph is -"); 23 | g.breadthFirstTraverse(1); 24 | } 25 | 26 | } 27 | 28 | 29 | class Graph 30 | { 31 | private int V; // No. of vertices 32 | private LinkedList adj[]; //Adjacency Lists 33 | // Constructor 34 | public Graph(int v) 35 | { 36 | V = v; 37 | adj = new LinkedList[v]; 38 | for (int i=0; i queue = new LinkedList(); 56 | // Mark the current node as visited and enqueue it 57 | visited[s]=true; 58 | queue.add(s); 59 | while (queue.size() != 0) 60 | { 61 | // Dequeue a vertex from queue and print it 62 | s = queue.poll(); 63 | System.out.print(s+" "); 64 | // Get all adjacent vertices of the dequeued vertex s 65 | // If a adjacent has not been visited, then mark it 66 | // visited and enqueue it 67 | Iterator i = adj[s].listIterator(); 68 | while (i.hasNext()) 69 | { 70 | int n = i.next(); 71 | if (!visited[n]) 72 | { 73 | visited[n] = true; 74 | queue.add(n); 75 | } 76 | } 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /breadth_first_traversal/breadth_first_traversal.cpp: -------------------------------------------------------------------------------- 1 | //@ raunak kumar jaiswal 2 | 3 | #include 4 | using namespace std; 5 | 6 | void bfstraversal(vector>& g, vector& visited, vector& ans, int node) 7 | { 8 | queueqq; 9 | qq.push(node); 10 | visited[node] = true; 11 | while(!qq.empty()) 12 | { 13 | auto it = qq.front(); 14 | qq.pop(); 15 | for(auto itt : g[it]) 16 | { 17 | if(visited[itt]==false) 18 | { 19 | visited[itt] = true; 20 | qq.push(itt); 21 | } 22 | } 23 | ans.push_back(it); 24 | } 25 | 26 | } 27 | 28 | void makegraph( vector>& g, int num_edge) 29 | { 30 | for(int i=0;i>a>>b; 34 | g[a].push_back(b); 35 | g[b].push_back(a); 36 | } 37 | } 38 | 39 | int main() 40 | { 41 | vector>g; 42 | vectorvisited; 43 | int num_node , num_edge; 44 | cout<<"Enter number of Node"<>num_node; 46 | cout<<"Enter number of Edges"<>num_edge; 48 | 49 | g.assign(num_node,vector()); 50 | visited.assign(num_node, false); 51 | 52 | cout<<"Enter the edges between vertex"<ans; 56 | 57 | for (int i=0;i [{distance: _, predecessor: _ }] 21 | """ 22 | vertex_info = [] 23 | for i in range(len(graph)): 24 | vertex_info.append({"distance": None, "predecessor": None}) 25 | vertex_info[source]["distance"] = 0 26 | 27 | search_queue = deque() 28 | search_queue.append(source) 29 | 30 | while search_queue: 31 | u = search_queue.popleft() 32 | for v in graph[u]: 33 | if vertex_info[v]["distance"] is None: 34 | vertex_info[v]["distance"] = vertex_info[u]["distance"] + 1 35 | vertex_info[v]["predecessor"] = u 36 | search_queue.append(v) 37 | return vertex_info 38 | 39 | 40 | def main(): 41 | graph_adj_list = [ 42 | [1], 43 | [0, 4, 5], 44 | [3, 4, 5], 45 | [2, 6], 46 | [1, 2], 47 | [1, 2, 6], 48 | [3, 5], 49 | [] 50 | ] 51 | vertex_info = breadth_first_traversal(graph_adj_list, 3) 52 | 53 | for i in range(len(graph_adj_list)): 54 | print("vertex %s : distance = %s, predecessor = %s" % 55 | (i, vertex_info[i]["distance"], vertex_info[i]["predecessor"])) 56 | 57 | assert(vertex_info[0] == { 58 | "distance": 4, 59 | "predecessor": 1 60 | }) 61 | assert(vertex_info[1] == { 62 | "distance": 3, 63 | "predecessor": 4 64 | }) 65 | assert(vertex_info[2] == { 66 | "distance": 1, 67 | "predecessor": 3 68 | }) 69 | assert(vertex_info[3] == { 70 | "distance": 0, 71 | "predecessor": None 72 | }) 73 | assert(vertex_info[4] == { 74 | "distance": 2, 75 | "predecessor": 2 76 | }) 77 | assert(vertex_info[5] == { 78 | "distance": 2, 79 | "predecessor": 2 80 | }) 81 | assert(vertex_info[6] == { 82 | "distance": 1, 83 | "predecessor": 3 84 | }) 85 | assert(vertex_info[7] == { 86 | "distance": None, 87 | "predecessor": None 88 | }) 89 | 90 | 91 | if __name__ == '__main__': 92 | main() 93 | -------------------------------------------------------------------------------- /coin_change_problem/CoinChangeProblem.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class CoinChangeProblem { 4 | 5 | /** 6 | * Implementation of famous dynamic programming problem 7 | * that aims to find out the maximum number of ways in 8 | * which a value can be achieved using some fixed valued 9 | * coins. 10 | * 11 | * In the implementation, the time complexity is O(mn) 12 | * and extra space required is O(n). 13 | * 14 | * @param coins 15 | * @param n 16 | * @return 17 | */ 18 | public static int coinChangeProblem(int[] coins, int value) { 19 | int[] possibilities = new int[value + 1]; 20 | Arrays.fill(possibilities, 0); 21 | possibilities[0] = 1; 22 | // Build the possibilities table in bottom-up manner 23 | // For all coins, 24 | // Update array if the current coin is capable of 25 | // incrementing the possibility 26 | for (int i = 0; i < coins.length; i++) { 27 | for (int j = coins[i]; j <= value; j++) { 28 | possibilities[j] += possibilities[j - coins[i]]; 29 | } 30 | } 31 | return possibilities[value]; 32 | } 33 | 34 | public static void main(String[] args) { 35 | int[] coins = {2, 5, 3, 6}; 36 | int value = 10; 37 | System.out.println(coinChangeProblem(coins, value)); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /coin_change_problem/coinChangeProblem.js: -------------------------------------------------------------------------------- 1 | function coinChangeProblem (coins, amount) { 2 | /* 3 | * Find out maximum number of ways in which a amount can 4 | * be obtained using fixed value coins. 5 | * Time Complexity : O((type of coins)*amount) 6 | * :param coins: Iterable of elements containing value of coins. 7 | * :param amount: It is value which is to be obtained with coins. 8 | * :return: returns maximum number of ways amount can be arranged in. 9 | */ 10 | let possibilities = new Array(amount + 1); 11 | possibilities.fill(0); 12 | possibilities[0] = 1; 13 | for (let i = 0; i < coins.length; i++) { 14 | for (let j = coins[i]; j <= amount; j++) { 15 | possibilities[j] += possibilities[j - coins[i]]; 16 | } 17 | } 18 | return possibilities[amount]; 19 | } 20 | 21 | function main () { 22 | let coins = [1, 2, 3]; 23 | let amount = 10; 24 | console.log(coinChangeProblem(coins, amount)); 25 | } 26 | 27 | main(); 28 | -------------------------------------------------------------------------------- /coin_change_problem/coin_change_problem.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Implementation of famous dynamic programming problem 3 | * that aims to find out the maximum number of ways in 4 | * which a value can be achieved using some fixed valued 5 | * coins. 6 | * 7 | * In the implementation, the time complexity is O(mn) 8 | * and extra space required is O(n). 9 | */ 10 | #include 11 | #include 12 | 13 | /* 14 | * coin: Array containing value of coins 15 | * m: Number of types of coins 16 | * n: Value to find the change for 17 | */ 18 | int coin_change_problem(const int *coin, int m, int n) { 19 | int i, j; 20 | int possibilities[n+1]; 21 | 22 | memset(possibilities, 0, sizeof(possibilities)); 23 | 24 | // Base case for n == 0 25 | possibilities[0] = 1; 26 | 27 | // Build the possibilities table in bottom-up manner 28 | // For all coins, 29 | // Update array if the current coin is capable of 30 | // incrementing the possibility 31 | for (i = 0; i < m; i++) { 32 | for (j = coin[i]; j <= n; j++) { 33 | possibilities[j] += possibilities[j-coin[i]]; 34 | } 35 | } 36 | 37 | return possibilities[n]; 38 | } 39 | 40 | int main() { 41 | int coin[] = {2, 5, 3, 6}; 42 | int n = 10, m = sizeof(coin)/sizeof(coin[0]); 43 | printf("%d\n", coin_change_problem(coin, m, n)); 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /coin_change_problem/coin_change_problem.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | // CoinChangeProblem find out maximum number of ways in which a amount can 6 | // be obtained using fixed value coins. 7 | // Time Complexity : O((number of type of coins)*amount) 8 | func CoinChangeProblem(coins []int, amount int) int { 9 | possibilities := make([]int, amount+1) 10 | possibilities[0] = 1 11 | for i := 0; i < len(coins); i++ { 12 | for j := coins[i]; j <= amount; j++ { 13 | possibilities[j] += possibilities[j-coins[i]] 14 | } 15 | } 16 | return possibilities[amount] 17 | } 18 | 19 | func main() { 20 | coins := []int{1, 2, 3} 21 | amount := 10 22 | fmt.Println(CoinChangeProblem(coins, amount)) 23 | } 24 | -------------------------------------------------------------------------------- /coin_change_problem/coin_change_problem.py: -------------------------------------------------------------------------------- 1 | def coin_change_problem(coins, amount): 2 | """ 3 | Find out maximum number of ways in which a amount can 4 | be obtained using fixed value coins. 5 | 6 | Time Complexity : O((type of coins)*amount) 7 | :param coins: Iterable of elements containing value of coins. 8 | :param amount: It is value which is to be obtained with coins. 9 | :return: returns maximum number of ways amount can be arranged in. 10 | """ 11 | possibilities = [0] * (amount + 1) 12 | possibilities[0] = 1 13 | for i in coins: 14 | for j in range(i, amount + 1): 15 | possibilities[j] += possibilities[j - i] 16 | return possibilities[amount] 17 | 18 | 19 | def main(): 20 | coins = [1, 2, 5] 21 | amount = 10 22 | print(coin_change_problem(coins, amount)) 23 | 24 | 25 | if __name__ == '__main__': 26 | main() 27 | -------------------------------------------------------------------------------- /counting_sort/CountingSort.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class CountingSort 4 | { 5 | 6 | /** 7 | * Sorts the array using counting sort 8 | * Time Complexity: O(n + k) where n is the number of elements in the array and k is the range of input 9 | * Space Complexity: O(n + k) 10 | */ 11 | public static int[] DoCountingSort(int[] arr) 12 | { 13 | // finding the maximum value in the array 14 | int maxValue = Int32.MinValue; 15 | foreach (int num in arr) 16 | maxValue = Math.Max(maxValue, num); 17 | 18 | // counting the frequency of each element in the array 19 | int[] frequency = new int[maxValue + 1]; 20 | foreach (int num in arr) 21 | frequency[num]++; 22 | 23 | // modifying each element in the frequency array to the total of all the elements before it 24 | for (int i = 1; i < frequency.Length; i++) 25 | frequency[i] += frequency[i - 1]; 26 | 27 | // constructing the sorted array based on the freqency of each element in ascending order 28 | int[] sortedArr = new int[arr.Length]; 29 | for (int i = 0; i < arr.Length; i++) { 30 | sortedArr[frequency[arr[i]] - 1] = arr[i]; 31 | frequency[arr[i]]--; 32 | } 33 | return sortedArr; 34 | } 35 | 36 | public static void Main() 37 | { 38 | int[] arr = new int[] {10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; 39 | int[] sortedArr = DoCountingSort(arr); 40 | foreach (int num in sortedArr) 41 | Console.WriteLine(num); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /counting_sort/CountingSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Random; 2 | 3 | class CountingSort { //Time complexity = O(n) 4 | private static void countOccurences(int[] a, int[] c) { //Basically counting occurences of particular number and store in its index 5 | for (int i = 0; i < a.length; i++) //Counting occurence of each number 6 | c[a[i]]++; 7 | for(int i = 1; i < c.length; i++) //counting total number of numbers less then or equal to that number 8 | c[i] = c[i-1] + c[i]; 9 | } 10 | 11 | public static int[] countingSort(int[] a, int k) { // For Sorting 12 | int[] b = new int[a.length]; //b Array stores sorted array 13 | int[] c = new int[k+1]; //array c count occurences 14 | countOccurences(a, c); 15 | for (int i = a.length-1; i >= 0; i--) { //storing number in ascending order in b 16 | b[c[a[i]]-1] = a[i]; //Stores number to it respective position 17 | c[a[i]]--; //Decrease c 18 | } 19 | return b; //Return sorted array 20 | } 21 | 22 | public static void main(String[] args) { 23 | int[] A = new int[10000]; 24 | int k = 0; 25 | Random rand = new Random(); 26 | for (int i = 0; i < A.length; i++) { 27 | A[i] = rand.nextInt(100); 28 | if (k < A[i]) //Every number must be between 0 to k 29 | k = A[i]; //K is max number 30 | } 31 | A = countingSort(A, k); 32 | for (int i = 0; i < A.length; i++) 33 | System.out.print(A[i] + " "); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /counting_sort/countingSort.js: -------------------------------------------------------------------------------- 1 | /* Following algorithm sorts the input array in ascending order 2 | * Time complexity is O(n+k) 3 | * Auxiliary space is O(n+k) 4 | * n is number of elements and k is the range of input 5 | * max is the maximum element in array 6 | */ 7 | 8 | function countingSort (arr, max) { 9 | /* 10 | :param arr: Array to be sorted 11 | :param max: Maximum value in array 12 | :return: Sorted array 13 | */ 14 | let n = arr.length; 15 | let count = new Array(max + 1); 16 | let temp = new Array(n); 17 | count.fill(0); 18 | for (let i = 0; i < n; i++) { 19 | count[arr[i]]++; 20 | } 21 | for (let i = 1; i <= max; i++) { 22 | count[i] += count[i - 1]; 23 | } 24 | for (let i = 0; i < n; ++i) { 25 | temp[count[arr[i]] - 1] = arr[i]; 26 | count[arr[i]]--; 27 | } 28 | return temp; 29 | } 30 | 31 | function main () { 32 | let max = 10; 33 | let arr = [3, 7, 10, 3, 1, 9, 4, 9]; 34 | arr = countingSort(arr, max); 35 | console.log(arr); 36 | } 37 | 38 | main(); 39 | -------------------------------------------------------------------------------- /counting_sort/counting_sort.c: -------------------------------------------------------------------------------- 1 | /* Following algorithm sorts the input array in ascending order 2 | * Time complexity is O(n+k) 3 | * Auxiliary space is O(n+k) 4 | * n is number of elements and k is the range of input 5 | * max is the maximum element in array 6 | */ 7 | 8 | #include 9 | #include 10 | 11 | void counting_sort(int arr[], int n, int max) { 12 | // Function to sort input array arr. 13 | int i; 14 | int count[max + 1]; // Array to store count's of elements. 15 | memset(count, 0, sizeof(count)); 16 | int temp[n]; 17 | for (i = 0; i < n; ++i) // Count the occurences of contents of array. 18 | count[arr[i]]++; 19 | for (i = 1; i <= max; ++i) 20 | count[i] += count[i-1]; 21 | for (i = 0; i < n; ++i) { // Sort the array according to occurences of elements. 22 | temp[count[arr[i]] - 1] = arr[i]; 23 | count[arr[i]]--; 24 | } 25 | for (i = 0; i < n; ++i) // Copy the sorted array back to original array. 26 | arr[i] = temp[i]; 27 | } 28 | 29 | int main() { 30 | int i; 31 | int max = 10; // max is the maximum number in the array 32 | int arr[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; 33 | int n = sizeof(arr) / sizeof(arr[0]); 34 | counting_sort(arr, n, max); 35 | for (i = 0; i < n; ++i) 36 | printf("%d ", arr[i]); 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /counting_sort/counting_sort.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | // CountingSort sorts the input array in ascending order 6 | // Time complexity is O(z) where z = max(len(data), max(data)) 7 | func CountingSort(data []int) { 8 | size := len(data) 9 | temp := make([]int, size) 10 | max := 0 11 | for _, elem := range data { 12 | if elem > max { 13 | max = elem 14 | } 15 | } 16 | count := make([]int, max+1) 17 | for _, item := range data { 18 | count[item]++ 19 | } 20 | for i := 1; i <= max; i++ { 21 | count[i] += count[i-1] 22 | } 23 | for i := 0; i < size; i++ { 24 | temp[count[data[i]]-1] = data[i] 25 | count[data[i]]-- 26 | } 27 | for i := 0; i < size; i++ { 28 | data[i] = temp[i] 29 | } 30 | } 31 | 32 | func main() { 33 | data := []int{1, 202, 2, 675, 901, 116, 312, 1, 2} 34 | CountingSort(data) 35 | fmt.Println(data) 36 | } 37 | -------------------------------------------------------------------------------- /counting_sort/counting_sort.py: -------------------------------------------------------------------------------- 1 | # Running time Complexity: O(z) where z = max(len(array), max(array)) 2 | # Auxillary Space: O(n) 3 | 4 | 5 | def count_occurences(array, count_array): 6 | """ 7 | :param array: iterable of elements 8 | :param count_array: Intermediate variable 9 | Time Complexity: O(n) 10 | """ 11 | for i in array: 12 | count_array[i] += 1 13 | for i in range(1, len(count_array)): 14 | count_array[i] += count_array[i - 1] 15 | 16 | 17 | def counting_sort(array, max_value): 18 | """ 19 | :param array: Iterable of elements 20 | :param max_value: Maximum value in array 21 | :return: Sorted array 22 | """ 23 | b = [0] * len(array) 24 | count_array = [0] * (max_value + 1) 25 | count_occurences(array, count_array) 26 | for i in range(len(array) - 1, -1, -1): 27 | b[count_array[array[i]] - 1] = array[i] 28 | count_array[array[i]] -= 1 29 | return b 30 | 31 | 32 | def main(): 33 | array = [3, 4, 5, 3, 6, 3, 3, 5, 5, 3, 2, 1, 5, 8] 34 | max_value = max(array) 35 | print(counting_sort(array, max_value)) 36 | 37 | 38 | if __name__ == '__main__': 39 | main() 40 | -------------------------------------------------------------------------------- /depth_first_traversal/DepthFirstTraversal.java: -------------------------------------------------------------------------------- 1 | import java.util.HashSet; 2 | import java.util.Iterator; 3 | import java.util.LinkedList; 4 | import java.util.Set; 5 | import java.util.ArrayList; 6 | 7 | 8 | public class DepthFirstTraversal { 9 | 10 | // ArrayList for Adjacency List Representation 11 | public static ArrayList> adj; 12 | 13 | // Function to add an edge into the DepthFirstTraversal 14 | private static void addEdge(int v, int w) { 15 | adj.get(v).add(w); 16 | } 17 | 18 | // A function used by DFS 19 | private static void depthFirstTraversal(int v, Set visited) { 20 | // Mark the current node as visited 21 | visited.add(v); 22 | System.out.println(v); 23 | Iterator i = adj.get(v).listIterator(); 24 | while (i.hasNext()) { 25 | int n = i.next(); 26 | if (!visited.contains(n)) { 27 | depthFirstTraversal(n, visited); 28 | } 29 | } 30 | } 31 | 32 | public static void dfs(int v) { 33 | // false by default in java) 34 | Set visited = new HashSet(); 35 | // Call the recursive helper function to print DFS traversal 36 | depthFirstTraversal(v, visited); 37 | } 38 | 39 | public static void initEdges(int n) { 40 | adj = new ArrayList>(); 41 | for (int i = 0; i < n; ++i) { 42 | adj.add(new LinkedList()); 43 | } 44 | } 45 | 46 | public static void main(String[] args) { 47 | initEdges(4); 48 | addEdge(0, 1); 49 | addEdge(0, 2); 50 | addEdge(1, 2); 51 | addEdge(2, 0); 52 | addEdge(2, 3); 53 | addEdge(3, 0); 54 | System.out.println("Depth First Traversal starting from vertex 2"); 55 | dfs(2); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /depth_first_traversal/DepthFirstTraversal.py: -------------------------------------------------------------------------------- 1 | def depthFirstTraversalRecursive(graph, node, visited): 2 | if node not in visited: 3 | visited.append(node) 4 | childs = graph[node] 5 | if len(childs) > 0: 6 | for child in childs: 7 | depthFirstTraversalRecursive(graph, child, visited) 8 | return visited 9 | 10 | 11 | def depthFirstTraversalIterative(graph, node): 12 | visited = [] 13 | stack = [] 14 | stack.append(node) 15 | while len(stack) > 0: 16 | node = stack[-1] 17 | if node not in visited: 18 | visited.append(node) 19 | childs = graph[node] 20 | while len(childs) > 0: 21 | # add the non-visited childs to the stack in reverse order 22 | child = childs.pop() 23 | if child not in visited: 24 | stack.append(child) 25 | else: 26 | stack.pop() 27 | return visited 28 | 29 | 30 | def main(): 31 | graph = {'A': ['B', 'C', 'E'], 32 | 'B': ['D', 'F'], 33 | 'C': ['G'], 34 | 'D': [], 35 | 'E': ['F'], 36 | 'F': ['C'], 37 | 'G': []} 38 | 39 | print("Recusrive:") 40 | result = depthFirstTraversalRecursive(graph, 'A', []) 41 | for node in result: 42 | print(node) 43 | 44 | print("Iterative:") 45 | result2 = depthFirstTraversalIterative(graph, 'A') 46 | for node in result2: 47 | print(node) 48 | 49 | 50 | if __name__ == '__main__': 51 | main() 52 | -------------------------------------------------------------------------------- /dijkstra/dijkstra.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Following implementation of dijsktra's algorithm prints the minimum distance from given source to destination using adjacency matrix. 3 | * Time complexity : O(V^2). 4 | * Space Complexity : O(V). 5 | */ 6 | 7 | #include 8 | #include // For using INT_MAX 9 | #include // bool datatype 10 | #include // for using memset() 11 | 12 | #define VERTICES 8 13 | #define INFINITY INT_MAX 14 | 15 | // This function will find the minimum distance from the unselected vertices 16 | int minimum_distance(const int min_distances[], const bool shortest_paths[]) { 17 | int i; 18 | int minimum = INFINITY, index; 19 | for (i = 0; i < VERTICES; ++i) { 20 | if (!shortest_paths[i] && min_distances[i] <= minimum) { 21 | minimum = min_distances[i]; 22 | index = i; 23 | } 24 | } 25 | return index; 26 | } 27 | 28 | // This function returns the minimum distance from given source to destination 29 | int dijkstra(const int graph[VERTICES][VERTICES], int souce, int destination) { 30 | int i, j; 31 | int min_distances[VERTICES]; 32 | bool shortest_paths[VERTICES]; 33 | memset(shortest_paths, false, VERTICES); 34 | for (i = 0; i < VERTICES; ++i) { 35 | min_distances[i] = INFINITY; // Initiallt set all distances to INFINITY 36 | } 37 | min_distances[souce] = 0; // Distance from source to itself is zero 38 | for (i = 0; i < VERTICES - 1; ++i) { 39 | int temp = minimum_distance(min_distances, shortest_paths); 40 | shortest_paths[temp] = true; 41 | for (j = 0; j < VERTICES; ++j) { 42 | if ((!shortest_paths[j]) && (graph[temp][j] != 0) && (min_distances[temp] != INFINITY) && (min_distances[temp] + graph[temp][j]) < min_distances[j]) { 43 | min_distances[j] = min_distances[temp] + graph[temp][j]; 44 | } 45 | } 46 | } 47 | return min_distances[destination]; 48 | } 49 | 50 | int main() { 51 | int source = 0; 52 | int destination = 4; 53 | const int graph[VERTICES][VERTICES] = { 54 | {0, 4, 0, 0, 0, 0, 0, 8}, 55 | {4, 0, 8, 0, 0, 0, 0, 11}, 56 | {0, 8, 0, 7, 0, 4, 0, 0}, 57 | {0, 0, 7, 0, 9, 14, 0, 0}, 58 | {0, 0, 0, 9, 0, 10, 0, 0}, 59 | {0, 0, 4, 14, 10, 0, 2, 0}, 60 | {0, 0, 0, 0, 0, 2, 0, 1}, 61 | {8, 11, 0, 0, 0, 0, 1, 0}, 62 | }; 63 | printf("The minimum distance from %d to %d is %d\n", source, destination, dijkstra(graph, source, destination)); 64 | return 0; 65 | } 66 | -------------------------------------------------------------------------------- /dijkstra/dijkstra.js: -------------------------------------------------------------------------------- 1 | 2 | // @raunak kumar jaiswal 3 | function mindistance(ans, visited) { 4 | var min_index = -1; 5 | var min_value = Number.MAX_VALUE; 6 | for (var i = 0; i < visited.length; i++) { 7 | if (visited[i] == 0 && ans[i] < min_value) { 8 | min_value = ans[i]; 9 | min_index = i; 10 | } 11 | } 12 | return min_index; 13 | } 14 | 15 | function dijjj(visited, graph, ans, total) { 16 | for (var j = 0; j < total; j++) { 17 | var min_index = mindistance(ans, visited); 18 | if (min_index == -1) { 19 | return 20 | } 21 | visited[min_index] = 1; 22 | var dist = ans[min_index]; 23 | for (var i = 0; i < graph[min_index].length; i++) { 24 | var ele = graph[min_index][i]; 25 | var vrr = ele[0]; 26 | var w = ele[1]; 27 | if (visited[vrr] == 0 && dist + w < ans[vrr]) { 28 | ans[vrr] = dist + w; 29 | } 30 | } 31 | } 32 | } 33 | 34 | function make_graph(edge, graph) { 35 | edge.forEach(ede => { 36 | graph[ede[0]].push([ede[1], ede[2]]) 37 | graph[ede[1]].push([ede[0], ede[2]]) 38 | }) 39 | } 40 | 41 | const dijkshtra = () => { 42 | var node = 6; 43 | var graph = []; 44 | for (var i = 0; i < node; i++) { 45 | graph[i] = []; 46 | } 47 | var edge = [[0, 1, 1], [0, 3, 7], [1, 3, 5], [0, 2, 3], [1, 2, 1], [1, 4, 3], [4, 5, 6], [5, 2, 2]]; 48 | make_graph(edge, graph) 49 | var ans = new Array(node); 50 | var visited = new Array(node); 51 | for (var i = 0; i < node; i++) { 52 | ans[i] = Number.MAX_VALUE 53 | visited[i] = 0; 54 | } 55 | var sort_dist_from = 0; 56 | ans[sort_dist_from] = 0; 57 | dijjj(visited, graph, ans, node) 58 | console.log("distance from source node that is 0 by default") 59 | console.log("node distance") 60 | for (var i = 0; i < ans.length; i++) { 61 | console.log(i + " " + ans[i]) 62 | } 63 | } 64 | dijkshtra() -------------------------------------------------------------------------------- /dijkstra/dijkstra.py: -------------------------------------------------------------------------------- 1 | """ 2 | Dijktra's shortest path algorithm. Finds the path and distance from source to target. 3 | To add an edge between vertex a and b with distance dist: 4 | graph[a].append((b, dist)) and graph[b].append((a, dist)). 5 | """ 6 | 7 | 8 | import heapq 9 | 10 | 11 | def dijkstra(graph, source, target): 12 | """ 13 | Finds the shortest path and shortest distance from source to target 14 | 15 | :param graph: Dictionary linking the vertices using list of tuples 16 | :param source: The vertex to start the path. 17 | :param target: The vertex to end the path. 18 | :return: shortest path and distance from source to target 19 | """ 20 | INF = float('Inf') 21 | predecessors = {x: x for x in graph} 22 | distances = {x: INF for x in graph} 23 | distances[source] = 0 24 | temp = [] 25 | heapq.heappush(temp, [source, distances[source]]) 26 | 27 | while temp: 28 | u = heapq.heappop(temp) 29 | u_dist = u[1] 30 | u_idx = u[0] 31 | if u_dist == distances[u_idx]: 32 | for v in graph[u_idx]: 33 | v_idx = v[0] 34 | u2v = v[1] 35 | if distances[u_idx] + u2v < distances[v_idx]: 36 | distances[v_idx] = distances[u_idx] + u2v 37 | heapq.heappush(temp, [v_idx, distances[v_idx]]) 38 | predecessors[v_idx] = u_idx 39 | 40 | if distances[target] == INF: 41 | return None, None 42 | else: 43 | path = [] 44 | vertex = target 45 | while True: 46 | path.append(str(vertex)) 47 | if vertex == predecessors[vertex]: 48 | break 49 | vertex = predecessors[vertex] 50 | return path[::-1], distances[target] 51 | 52 | 53 | def main(): 54 | """ 55 | driver function to test the dijkstra's algorithm 56 | """ 57 | graph = {'s': [('a', 2), ('b', 1)], 58 | 'a': [('s', 3), ('b', 4), ('c', 8)], 59 | 'b': [('s', 4), ('a', 2), ('d', 2)], 60 | 'c': [('a', 2), ('d', 7), ('t', 4)], 61 | 'd': [('b', 1), ('c', 11), ('t', 5)], 62 | 't': [('c', 3), ('d', 5)] 63 | } 64 | source = 'a' 65 | target = 't' 66 | path, cost = dijkstra(graph, source, target) 67 | print('The path from ' + source + ' to ' + target + ' :') 68 | if path is None or cost is None: 69 | print('does not exist') 70 | else: 71 | print(str(path) + ' with cost: ' + str(cost)) 72 | 73 | 74 | if __name__ == "__main__": 75 | main() 76 | -------------------------------------------------------------------------------- /euclidean_gcd/EuclideanGCD.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int euclidean_gcd_recursive(int a, int b) 5 | { 6 | if (a == 0) 7 | return b; 8 | return euclidean_gcd_recursive(b % a, a); 9 | } 10 | 11 | int euclidean_gcd_iterative(int a, int b) { 12 | while(b != 0) { 13 | int temp = b; 14 | b = a % b; 15 | a = temp; 16 | } 17 | return a; 18 | } 19 | 20 | int main() { 21 | int a = 69; 22 | int b = 11; 23 | int answer_recursive = euclidean_gcd_recursive(a, b); 24 | int answer_iterative = euclidean_gcd_iterative(a, b); 25 | cout<<"GCD of "<< a <<" and "<< b <<" is : "<< answer_recursive<<" by recursive algo"< First number 3 | * second --> Second number 4 | * There are two implementations: 5 | * Recursive(euclideanGCDRecursive) and Non-Recursive(euclideanGCD) 6 | */ 7 | 8 | public class EuclideanGCD { 9 | static int euclideanGCD(int first, int second) { 10 | while(second != 0) { // Iterate till second becomes zero 11 | int temp = second; // Temporary variable to hold value of second 12 | second = first % second; 13 | first = temp; 14 | } 15 | return first; // When second becomes 0, first becomes gcd of both 16 | } 17 | 18 | static int euclideanGCDRecursive(int first, int second) { 19 | return (second == 0) ? first : euclideanGCDRecursive(second, (first % second)); 20 | // First becomes GCD when second becomes zero 21 | } 22 | 23 | public static void main(String[] args) { 24 | int first = 25; 25 | int second = 5; 26 | int answerIterative = EuclideanGCD.euclideanGCD(first, second); 27 | int answerRecursive = EuclideanGCD.euclideanGCDRecursive(first, second); 28 | System.out.printf("GCD of %d and %d is : %d by recursive algo.\n", first, 29 | second, answerRecursive); 30 | System.out.printf("GCD of %d and %d is : %d by iterative algo.\n", first, 31 | second, answerIterative); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /euclidean_gcd/euclideanGCD.js: -------------------------------------------------------------------------------- 1 | function euclideanGCDRecursive (first, second) { 2 | /* 3 | Calculates GCD of two numbers using Euclidean Recursive Algorithm 4 | :param first: First number 5 | :param second: Second number 6 | :return: GCD of the numbers 7 | */ 8 | if (second === 0) { 9 | return first; 10 | } else { 11 | return euclideanGCDRecursive(second, (first % second)); 12 | } 13 | } 14 | 15 | function euclideanGCDIterative (first, second) { 16 | /* 17 | Calculates GCD of two numbers using Euclidean Iterative Algorithm 18 | :param first: First number 19 | :param second: Second number 20 | :return: GCD of the numbers 21 | */ 22 | while (second !== 0) { 23 | let temp = second; 24 | second = first % second; 25 | first = temp; 26 | } 27 | return first; 28 | } 29 | 30 | function main () { 31 | let first = 20; 32 | let second = 30; 33 | console.log('Recursive GCD for %d and %d is %d', first, second, euclideanGCDRecursive(first, second)); 34 | console.log('Iterative GCD for %d and %d is %d', first, second, euclideanGCDIterative(first, second)); 35 | } 36 | 37 | main(); 38 | -------------------------------------------------------------------------------- /euclidean_gcd/euclidean_gcd.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | /* 4 | * first --> First number 5 | * second --> Second number 6 | * There are two implementations: Recursive (euclidean_gcd_recursive) and Non-Recursive (euclidean_gcd) 7 | */ 8 | 9 | int euclidean_gcd_recursive(int first, int second) { 10 | if(second == 0) { 11 | return first; // First becomes gcd if second becomes zero 12 | } else { 13 | return euclidean_gcd_recursive(second, (first % second)); 14 | } 15 | } 16 | 17 | int euclidean_gcd(int first, int second) { 18 | while(second != 0) { // Iterate till second becomes zero 19 | int temp = second; // Temporary variable to hold value of second which is to be assigned to first later 20 | second = first % second; 21 | first = temp; 22 | } 23 | return first; // When second becomes 0, first becomes gcd of both 24 | } 25 | 26 | int main() { 27 | int first = 49; 28 | int second = 7; 29 | int answer_recursive = euclidean_gcd_recursive(first, second); 30 | int answer_iterative = euclidean_gcd(first, second); 31 | printf("GCD of %d and %d is : %d by recursive algo.\n", first, second, answer_recursive); 32 | printf("GCD of %d and %d is : %d by iterative algo.\n", first, second, answer_iterative); 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /euclidean_gcd/euclidean_gcd.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | // EuclideanGCD finds GCD of given numbers by iterative method 6 | // first : first number 7 | // second : second number 8 | // Time complexity :O(log min(first,second)) 9 | func EuclideanGCD(first int, second int) int { 10 | for second != 0 { 11 | tmp := second 12 | second = first % second 13 | first = tmp 14 | } 15 | return first 16 | } 17 | 18 | // EuclideanGCDRecursive finds GCD of given numbers by recursion 19 | // first : first number 20 | // second : second number 21 | // Time complexity : O(log min(first,second)) 22 | func EuclideanGCDRecursive(first int, second int) int { 23 | if second != 0 { 24 | return EuclideanGCDRecursive(second, (first % second)) 25 | } 26 | return first 27 | } 28 | 29 | func main() { 30 | first := 90 31 | second := 65 32 | fmt.Println("GCD of numbers is :") 33 | fmt.Println(EuclideanGCD(first, second)) 34 | fmt.Println(EuclideanGCDRecursive(first, second)) 35 | } 36 | -------------------------------------------------------------------------------- /euclidean_gcd/euclidean_gcd.py: -------------------------------------------------------------------------------- 1 | """ 2 | There are two implementations: 3 | Recursive (euclidean_gcd_recursive) and 4 | Non-Recursive (euclidean_gcd) 5 | """ 6 | 7 | 8 | def euclidean_gcd_recursive(first, second): 9 | """ 10 | Calculates GCD of two numbers using Euclidean Recursive Algorithm 11 | :param first: First number 12 | :param second: Second number 13 | :return: GCD of the numbers 14 | """ 15 | if second == 0: 16 | return first # First becomes gcd if second becomes zero 17 | else: 18 | return euclidean_gcd(second, first % second) 19 | 20 | 21 | def euclidean_gcd(first, second): 22 | """ 23 | Calculates GCD of two numbers using Euclidean Iterative Algorithm 24 | :param first: First number 25 | :param second: Second number 26 | :return: GCD of the numbers 27 | """ 28 | while second != 0: # Iterate till second becomes zero 29 | temp = second # Temporary variable to hold value of second 30 | second = first % second 31 | first = temp # Temporary variable assigned to first 32 | return first # When second becomes 0, first becomes gcd of both 33 | 34 | 35 | def main(): 36 | first = 36 37 | second = 6 38 | answer_iterative = euclidean_gcd(first, second) 39 | answer_recursive = euclidean_gcd_recursive(first, second) 40 | print("GCD of %d and %d is : %d by recursive algo." % (first, second, 41 | answer_recursive)) 42 | print("GCD of %d and %d is : %d by iterative algo." % (first, second, 43 | answer_iterative)) 44 | 45 | 46 | if __name__ == '__main__': 47 | main() 48 | -------------------------------------------------------------------------------- /exponentiation_by_squaring/ExponentiationBySquaring.java: -------------------------------------------------------------------------------- 1 | /* Algorithm to calculate base raised to power power very efficiently 2 | * Can be used as a great alternative to normal pow function 3 | * base - base of the expression 4 | * power - power of expression 5 | */ 6 | 7 | public class ExponentiationBySquaring { 8 | public static double exponentiationBySquaring(double base, int power) { 9 | if (power < 0) { // Negative powers 10 | return exponentiationBySquaring(1.0 / base, -power); 11 | } else if (power == 0) { // Base case 1 12 | return 1; 13 | } else if (power == 1) { // Base case 2 14 | return base; 15 | } else if (power % 2 == 0){ // Even powers 16 | return exponentiationBySquaring(base * base, power / 2); 17 | } else { // Odd powers 18 | return base * exponentiationBySquaring(base * base, (power - 1) / 2); 19 | } 20 | } 21 | 22 | public static void main(String[] args) { 23 | double base = 2; 24 | int power = -1; 25 | System.out.println(base + " raised to " + power + " is: " + exponentiationBySquaring(base, power)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /exponentiation_by_squaring/exponentiationBySquaring.js: -------------------------------------------------------------------------------- 1 | function exponentiationBySquaring (base, power) { 2 | /* 3 | Performs Exponentiation By Squaring. 4 | :param base: Base of expression. 5 | :param power: Power of expression. 6 | :return: Returns (base ^ power). 7 | */ 8 | if (power < 0) { // When Power is Negative 9 | return exponentiationBySquaring(1 / base, -power); 10 | } else if (power === 0) { // Power = 0 (Base Case 1) 11 | return 1; 12 | } else if (power === 1) { // Power = 1 (Base Case 2) 13 | return base; 14 | } else if (power % 2 === 0) { // When Power is Even 15 | return exponentiationBySquaring(base * base, power >> 1); 16 | } else { // When Power is Odd 17 | return base * exponentiationBySquaring(base * base, (power - 1) >> 1); 18 | } 19 | } 20 | 21 | function main () { 22 | let base = 3; 23 | let power = 6; 24 | let res = exponentiationBySquaring(base, power); 25 | console.log('%d\n', res); 26 | } 27 | 28 | main(); 29 | -------------------------------------------------------------------------------- /exponentiation_by_squaring/exponentiation_by_squaring.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | /* Algorithm to calculate x raised to power k very efficiently 4 | * Can be used as a great alternative to normal pow function 5 | * base - base of the expression 6 | * power - power of expression 7 | */ 8 | 9 | long double exponentation_by_squaring(long double base, int power) { 10 | if (power < 0) { // Negative power case 11 | return exponentation_by_squaring(1 / base, -power); 12 | } else if (power == 0) { // Base case1 13 | return 1; 14 | } else if (power == 1) { // Base case2 15 | return base; 16 | } else if (power % 2 == 0) { 17 | return exponentation_by_squaring(base * base, power / 2); 18 | } else if (power % 2 == 1) { 19 | return base * exponentation_by_squaring(base * base, (power - 1) / 2); 20 | } 21 | } 22 | 23 | int main() { 24 | long double base = 2; 25 | int power = 31; 26 | printf("%LG raised to %d is %LG\n", base, power, exponentation_by_squaring(base, power)); 27 | 28 | base = 2; 29 | power = -2; 30 | printf("%LG raised to %d is %LG\n", base, power, exponentation_by_squaring(base, power)); 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /exponentiation_by_squaring/exponentiation_by_squaring.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | // ExponentiationBySquaring calculates base^power efficiently. 6 | func ExponentiationBySquaring(base int, power int) int { 7 | if power < 0 { // Negative power case 8 | return ExponentiationBySquaring((1 / base), -power) 9 | } else if power == 0 { // Base case1 10 | return 1 11 | } else if power == 1 { // Base case2 12 | return base 13 | } else if power%2 == 0 { 14 | return ExponentiationBySquaring(base*base, power/2) 15 | } else { 16 | return base * ExponentiationBySquaring(base*base, (power-1)/2) 17 | } 18 | } 19 | 20 | func main() { 21 | base, power := 5, 10 22 | fmt.Println(ExponentiationBySquaring(base, power)) 23 | } 24 | -------------------------------------------------------------------------------- /exponentiation_by_squaring/exponentiation_by_squaring.py: -------------------------------------------------------------------------------- 1 | def exponentation_by_squaring(base, power): 2 | """ 3 | Calculates base ^ power using recursion, efficient algorithm to inbuilt pow() function 4 | :param base: Base of expression 5 | :param power: Power of expression 6 | :return: returns base ^ power 7 | """ 8 | 9 | if power < 0: # Negative powers 10 | return exponentation_by_squaring(1. / base, -power) 11 | elif power == 0: # Base case 12 | return 1 13 | elif power % 2 == 0: 14 | return exponentation_by_squaring(base * base, power // 2) 15 | elif power % 2 == 1: 16 | return base * exponentation_by_squaring(base * base, (power - 1) // 2) 17 | 18 | 19 | def main(): 20 | """ 21 | driver function to calculate base ^ power 22 | """ 23 | 24 | base = 2 25 | power = 3 26 | print(str(base) + ' raised to ' + str(power) + ' is ' + 27 | str(exponentation_by_squaring(base, power))) 28 | 29 | 30 | if __name__ == '__main__': 31 | main() 32 | -------------------------------------------------------------------------------- /fibonacci_number/FibonacciNumber.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | long long int FibonacciNumber(long long int n) 4 | { 5 | //Because first fibonacci number is 0 and second fibonacci number is 1. 6 | if (n == 1 || n == 2) 7 | { 8 | return (n - 1); 9 | } 10 | else 11 | { 12 | //store last fibonacci number 13 | long long int a = 1; 14 | //store second last fibonacci number 15 | long long int b = 0; 16 | //store current fibonacci number 17 | long long int nth_Fib; 18 | for (long long int i = 3; i <= n; i++) 19 | { 20 | nth_Fib = a + b; 21 | b = a; 22 | a = nth_Fib; 23 | } 24 | return nth_Fib; 25 | } 26 | } 27 | 28 | int main() 29 | { 30 | long long int n; 31 | printf("Enter a Number : "); 32 | scanf("%lli", &n); 33 | if (n < 1) 34 | { 35 | printf("Number must be greater than 0"); 36 | } 37 | else 38 | { 39 | long long int nth_Fib = FibonacciNumber(n); 40 | printf("Fibonacci Number is %lli", nth_Fib); 41 | } 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /fibonacci_number/FibonacciNumber.java: -------------------------------------------------------------------------------- 1 | public class FibonacciNumber { 2 | 3 | // fibonacci function return the nth fibonacci no for all n>0 4 | public static int fibonacci(int n) { 5 | if (n == 1 || n == 2) { 6 | return (n - 1); 7 | } else { 8 | // Store second last fibonacci number 9 | int a = 0; 10 | // Store last fibonacci number 11 | int b = 1; 12 | // Store current fibonacci number which is sum of last and second last fibonacci no 13 | int fib = 0; 14 | for (int i = 2; i < n; i++) { 15 | fib = a + b; 16 | a = b; 17 | b = fib; 18 | } 19 | return (fib); 20 | } 21 | } 22 | 23 | public static void main(String[] args) { 24 | // n>0 25 | int n = 5; 26 | if (n <= 0) { 27 | System.out.println("n must be greater than 0"); 28 | return; 29 | } 30 | System.out.println(fibonacci(n)); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /fibonacci_number/FibonacciNumber.js: -------------------------------------------------------------------------------- 1 | function fibonacci(p) { 2 | if(p === 1 || p === 2) { 3 | return p-1; // base case 4 | } else { 5 | 6 | let a = 0; 7 | let b = 1; 8 | // 0 1 1 2 3 5 8 ... 9 | let fib = 0; 10 | for(var i = 2 ; i < p ; i = i + 1) { 11 | fib = a + b; 12 | a = b; 13 | b = fib; 14 | } 15 | 16 | return fib; 17 | } 18 | } 19 | 20 | function main() { 21 | const readline = require('readline').createInterface({ 22 | input: process.stdin, 23 | output: process.stdout 24 | }); 25 | 26 | readline.question("Enter value of n ", n => { 27 | console.log(fibonacci(n)); 28 | readline.close() 29 | }); 30 | } 31 | 32 | main(); 33 | 34 | 35 | -------------------------------------------------------------------------------- /fibonacci_number/FibonacciNumber.py: -------------------------------------------------------------------------------- 1 | def fib(n): 2 | if(n <= 1): 3 | return n 4 | else: 5 | return fib(n-1) + fib(n-2) 6 | 7 | def main(): 8 | print("Enter the number :") 9 | t = int(input()) 10 | if(t == 0): 11 | print("Enter correct number!") 12 | else: 13 | 14 | for i in range(t): 15 | x = fib(i) 16 | print("fibonacci number is :") 17 | print(x) 18 | 19 | if __name__ == '__main__': 20 | main() 21 | -------------------------------------------------------------------------------- /heap_sort/HeapSort.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Following is the implementation of HeapSort algorithm. 3 | * It will sort the input array with time complexity O(N*logN) 4 | * N being the size of array. 5 | * Space complexity is O(1). 6 | */ 7 | 8 | public class HeapSort { 9 | 10 | public static void maxHeapify(int[] arr, int size, int parent) { // Build max-heap of subtree of parent index 11 | int left = 2 * parent; 12 | int right = left + 1; 13 | int largest = parent; // Initially considering parent as largest 14 | if (left < size && arr[left] > arr[largest]) // Left child is greater than parent 15 | largest = left; 16 | if (right < size && arr[right] > arr[largest]) // Right child is greater than parent 17 | largest = right; 18 | if (largest != parent) { // If parent is largest then subtree is max-heap 19 | int temp = arr[parent]; 20 | arr[parent] = arr[largest]; // Swap largest child with parent 21 | arr[largest] = temp; 22 | maxHeapify(arr, size, largest); // Convert upper subtree to max-heap 23 | } 24 | } 25 | 26 | public static void heapSort(int[] arr) { 27 | for (int i = arr.length / 2 - 1; i >= 0; --i) 28 | maxHeapify(arr, arr.length, i); // Create max-heap 29 | 30 | for (int i = arr.length - 1; i >= 0; --i) { 31 | int temp = arr[0]; // Swap first and last element 32 | arr[0] = arr[i]; 33 | arr[i] = temp; 34 | maxHeapify(arr, i, 0); // Create Max-Heap on reduced array 35 | } 36 | } 37 | 38 | public static void main(String[] args) { 39 | int[] arr = new int[] {10, 4, 3, 13, 1, 123}; // Creating Test array 40 | 41 | heapSort(arr); // Sort the array 42 | for (int element : arr) // Printing sorted array 43 | System.out.print(element + " "); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /heap_sort/heapSort.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Implementation of heap sort sorting algorithm. 3 | * Time Complexity: O(N*logN), N being size of array 4 | * Space Complexity: O(1) 5 | */ 6 | 7 | function maxHeapify (arr, size, parent) { 8 | /* 9 | * :param arr: input array. 10 | * :param size: hypothetical size of input array. 11 | * :param parent: index of current node to create max-heap from. 12 | */ 13 | let left = 2 * parent; 14 | let right = left + 1; 15 | let largest = parent; // Initially considering parent as largest 16 | if (left < size && arr[left] > arr[largest]) { // Left child is greater than parent 17 | largest = left; 18 | } 19 | if (right < size && arr[right] > arr[largest]) { // Right child is greater than parent 20 | largest = right; 21 | } 22 | if (largest !== parent) { // If parent is largest then subtree is max-heap 23 | let temp = arr[parent]; 24 | arr[parent] = arr[largest]; // Swap largest child with parent 25 | arr[largest] = temp; 26 | maxHeapify(arr, size, largest); // Convert upper subtree to max-heap 27 | } 28 | } 29 | 30 | function heapSort (arr) { 31 | /* 32 | * :param arr: Input array to be sorted. 33 | */ 34 | for (let i = arr.length / 2 - 1; i >= 0; --i) { // Build max-heap 35 | maxHeapify(arr, arr.length, i); 36 | } 37 | 38 | for (let i = arr.length - 1; i >= 0; --i) { 39 | let temp = arr[0]; // Swap first and last element 40 | arr[0] = arr[i]; 41 | arr[i] = temp; 42 | maxHeapify(arr, i, 0); // Create Max-Heap on reduced array 43 | } 44 | } 45 | 46 | function main () { 47 | let arr = [10, -4, 3, 13, 1, 123]; 48 | heapSort(arr); 49 | console.log(arr); 50 | } 51 | 52 | main(); 53 | -------------------------------------------------------------------------------- /heap_sort/heap_sort.c: -------------------------------------------------------------------------------- 1 | /* 2 | * C program to Implement Heap sort. 3 | * Time complexity: Average = O( n log( n ) ), worst case complexity = O( n log( n ) ). 4 | * Space complexity: O(1). 5 | */ 6 | 7 | #include 8 | 9 | // root = index root of the subtree, a is an array, heapsize = size of heap 10 | void max_heapify(int a[], int root, int heapsize) { 11 | int largest = root; 12 | int l = (2 * root) + 1; // left child 13 | int r = (2 * root) + 2; // Right child 14 | // Check if left child is larger than root. 15 | if ((l < heapsize) && (a[l] > a[root])) { 16 | largest = l; 17 | } 18 | // Check if right child is larger than largest. 19 | if ((r < heapsize) && (a[r] > a[largest])) { 20 | largest = r ; 21 | } 22 | // If root is not the largest. 23 | if (largest != root) { 24 | int tmp = a[root]; 25 | a[root] = a[largest]; 26 | a[largest] = tmp; 27 | max_heapify(a, largest, heapsize); 28 | } 29 | } 30 | 31 | // a is the array. 32 | void heap_sort(int a[], int heapsize) { 33 | int i; 34 | // Building max heap. 35 | for (i = (heapsize / 2) - 1; i >= 0; i--) { 36 | max_heapify(a, i, heapsize); 37 | } 38 | // One by one extract an element from heap 39 | for (i = heapsize - 1; i > 0; i--) { 40 | int tmp = a[i]; 41 | a[i] = a[0]; 42 | a[0] = tmp; 43 | heapsize--; 44 | // Again build max heap with the reduced array. 45 | max_heapify(a, 0, heapsize); 46 | } 47 | } 48 | 49 | int main() { 50 | int i, r; 51 | // Unsorted data 52 | int a[] = {10000, -999, 240, 1111111, 3, 2, 452, -65}; 53 | int size = sizeof(a) / sizeof(a[0]); 54 | // Calling heap_sort function 55 | heap_sort(a, size); 56 | printf("After Sorting:\t"); 57 | 58 | for (i = 0; i < size; i++) { 59 | printf("%d ", a[i]); 60 | } 61 | 62 | return 0; 63 | } 64 | -------------------------------------------------------------------------------- /heap_sort/heapsort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void swap(int array[], int index1, int index2) //swapping function wihout using third variable 5 | { 6 | array[index1] = array[index1] + array[index2]; 7 | array[index2] = array[index1] - array[index2]; 8 | array[index1] = array[index1] - array[index2]; 9 | } 10 | void heapify(int array[], int size, int index) 11 | { 12 | int largest = index; //considering largest as root 13 | int left = 2 * index + 1; 14 | int right = 2 * index + 2; 15 | 16 | if (left < size && array[left] > array[largest]) //left child is larger then root 17 | largest = left; 18 | 19 | if (right < size && array[right] > array[largest]) //right child is larger then root 20 | largest = right; 21 | 22 | if (largest != index) //condition if largest is not root 23 | { 24 | swap(array, index, largest); 25 | heapify(array, size, largest); 26 | } 27 | } 28 | void heapsort(int array[], int size) 29 | { 30 | 31 | for (int i = size / 2 - 1; i >= 0; i--) //Create heap from array rearrangement 32 | heapify(array, size, i); 33 | 34 | for (int i = size - 1; i > 0; i--) //move current root to end a step for Extract min process 35 | { 36 | 37 | swap(array, 0, i); //swap element 38 | 39 | heapify(array, i, 0); //excecuting heapify to bring all elements in correct position again 40 | } 41 | } 42 | void display(int array[], int size) 43 | { 44 | int i = 0; 45 | for (i = 0; i < size; i++) 46 | cout << array[i] << " "; 47 | cout << endl; 48 | } 49 | int main() 50 | { 51 | int array[] = {6, 3, 6, 343, 42, 1, 43, 35, 34, 43}; 52 | int size = sizeof(array) / sizeof(array[0]); 53 | cout << "Unsorted array is :" << endl; 54 | display(array, size); //display the unsorted array 55 | heapsort(array, size); 56 | cout << "sorted array is :" << endl; 57 | display(array, size); //display the sorted array 58 | } 59 | -------------------------------------------------------------------------------- /insertion_sort/InsertionSort.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class InsertionSort 4 | { 5 | public static void Sort(int[] data) 6 | { 7 | int key; 8 | for(int i = 1; i < data.Length; i++) 9 | { 10 | int j = i - 1; 11 | key = data[i]; 12 | while (j >= 0 && data[j] > key) 13 | { 14 | data[j + 1] = data[j]; 15 | j = j - 1; 16 | } 17 | data[j + 1] = key; 18 | } 19 | } 20 | 21 | public static void Main() 22 | { 23 | int[] arr = new int[] {1000, 45, -45, 121, 47, 45, 65, 121, -1, 103, 45, 34}; 24 | Sort(arr); 25 | for(int i = 0; i < arr.Length; i++) 26 | { 27 | Console.Write(arr[i] + " "); 28 | } 29 | Console.WriteLine(""); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /insertion_sort/InsertionSort.java: -------------------------------------------------------------------------------- 1 | public class InsertionSort { 2 | 3 | private static void insertionSort(int[] arr) { 4 | for (int i = 1; i < arr.length; i++) { 5 | int j = i - 1; 6 | int key = arr[i]; // Element to be compared 7 | 8 | /* Move elements of arr[0...i-1], that are 9 | greater than key, to one position ahead 10 | of their current position */ 11 | while(j >= 0 && arr[j] > key) { 12 | arr[j+1] = arr[j]; 13 | j--; 14 | } 15 | arr[j+1] = key; // Putting key to the position where all numbers before it are sorted 16 | } 17 | } 18 | 19 | public static void main(String[] args) { 20 | int[] arr = {12, 11, 13, 5, 6}; 21 | insertionSort(arr); 22 | 23 | for (int x: arr) { // Printing sorted array 24 | System.out.print(x+" "); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /insertion_sort/insertionSort.js: -------------------------------------------------------------------------------- 1 | /* Following algorithm sorts the input array in ascending order 2 | * Time Complexity : O(n^2) 3 | * Auxiliary Space: O(1) 4 | * n is the number of elements in the array to be sorted 5 | */ 6 | 7 | function insertionSort (arr) { 8 | /* 9 | : param arr : Array to be sorted 10 | : return : Sorted Array 11 | */ 12 | for (let i = 1; i < arr.length; i++) { 13 | let j = i - 1; 14 | let temp = arr[i]; 15 | while (j >= 0 && arr[j] > temp) { 16 | arr[j + 1] = arr[j]; 17 | j--; 18 | } 19 | arr[j + 1] = temp; 20 | } 21 | return arr; 22 | } 23 | 24 | function main () { 25 | let arr = [5, 9, 3, 1, 99]; 26 | arr = insertionSort(arr); 27 | console.log(arr); 28 | } 29 | 30 | main(); 31 | -------------------------------------------------------------------------------- /insertion_sort/insertion_sort.c: -------------------------------------------------------------------------------- 1 | /* 2 | * arr - array to be sorted 3 | * arr_size - size of array 4 | */ 5 | #include 6 | 7 | void insertion_sort(int *arr, int arr_size) { 8 | int i, j; 9 | for (i = 1; i < arr_size; i++) { 10 | int key = arr[i]; 11 | j = i - 1; 12 | /* Move elements of arr[0...i-1], that are 13 | greater than key, to one position ahead 14 | of their current position */ 15 | while (j >= 0 && arr[j] > key) { 16 | arr[j+1] = arr[j]; 17 | j--; 18 | } 19 | arr[j+1] = key; 20 | } 21 | } 22 | 23 | int main() { 24 | int arr[] = {12, 11, 13, 5, 6}; 25 | int arr_size = sizeof(arr) / sizeof(arr[0]); 26 | int i; 27 | 28 | insertion_sort(arr, arr_size); 29 | 30 | for (i = 0; i < arr_size; i++) { // Printing the sorted array 31 | printf("%d ", arr[i]); 32 | } 33 | printf("\n"); 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /insertion_sort/insertion_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void insertionSort(int array[], int size) 4 | { 5 | int i = 0, tempElement = 0, j = 0; 6 | for (i = 1; i < size; i++) 7 | { 8 | tempElement = array[i]; //Choosing element whose correct index to be found. 9 | j = i - 1; 10 | while (j >= 0 && array[j] > tempElement) 11 | { 12 | array[j + 1] = array[j]; //Shifting element one position right side untill we get correct position 13 | j = j - 1; 14 | } 15 | array[j + 1] = tempElement; // got the correct position for tempElement 16 | } 17 | } 18 | void display(int array[], int size) 19 | { 20 | int i = 0; 21 | for (i = 0; i < size; i++) 22 | cout << array[i] << " "; 23 | cout << endl; 24 | } 25 | int main() 26 | { 27 | int size; 28 | cout<<"Enter the size of the array :"<>size; //size of the array 30 | int array[size]; 31 | cout<<"Enter array elements"<>array[i]; //taking input 34 | cout << "unsorted array is :" << endl; 35 | display(array, size); //display unsorted array 36 | insertionSort(array, size); 37 | cout << "sorted array is :" << endl; 38 | display(array, size); //display the sorted array 39 | } 40 | -------------------------------------------------------------------------------- /insertion_sort/insertion_sort.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | // InsertionSort function returns sorted data 6 | // Time complexity: O(n^2) 7 | // Space complexity: O(1) 8 | func InsertionSort(data []int) []int { 9 | for i := 1; i < len(data); i++ { 10 | key := data[i] 11 | j := i - 1 12 | for j >= 0 && data[j] > key { 13 | data[j+1] = data[j] 14 | j-- 15 | } 16 | data[j+1] = key 17 | } 18 | return data 19 | } 20 | 21 | func main() { 22 | data := []int{1000, 45, -45, 121, 47, 45, 65, 121, -1, 103, 45, 34} 23 | data = InsertionSort(data) 24 | fmt.Println(data) 25 | } 26 | -------------------------------------------------------------------------------- /insertion_sort/insertion_sort.py: -------------------------------------------------------------------------------- 1 | def insertionSort(alist): 2 | """ 3 | Performs a insertion sort 4 | :type alist: object 5 | """ 6 | for index in range(1, len(alist)): 7 | current_value = alist[index] 8 | position = index 9 | while position > 0 and alist[position - 1] > current_value: 10 | alist[position] = alist[position - 1] 11 | position -= 1 12 | alist[position] = current_value 13 | 14 | 15 | def main(): 16 | alist = [54, 26, 93, 17, 77, 31, 44, 55, 20] 17 | insertionSort(alist) 18 | print(alist) 19 | 20 | 21 | if __name__ == '__main__': 22 | main() 23 | -------------------------------------------------------------------------------- /largest_sum_contiguous_subarray/LargestSumContiguousSubarray.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Implementation of famous dynamic programming problem 3 | * Largest Sum Contiguous Subarray 4 | * Kadane Algorithm 5 | * Time complexity O(n) 6 | */ 7 | 8 | public class LargestSumContiguousSubarray { 9 | 10 | public static int largestSumContiguousSubarray(int[] array) { // maximum sum method implemention 11 | int prevSum; 12 | int currentSum; 13 | int i; 14 | prevSum = array[0]; // initialize current sum amd previous sum 15 | currentSum = array[0]; 16 | for (i = 1; i < array.length; i++) { 17 | currentSum += array[i]; // add values in current sum 18 | if (currentSum < 0) { // if current sum is negative , make it zero 19 | currentSum = 0; 20 | } else if (currentSum > prevSum) { // if current sum is greate than previous sum 21 | prevSum = currentSum; // update previous sum 22 | } 23 | } 24 | return prevSum; 25 | } 26 | 27 | public static void main(String[] args) { 28 | 29 | int[] array = new int[] {-2, 1, -3, 4, -1, 2, 1, -5, 4}; 30 | System.out.println("Largest Sum of Contiguous Subarray:" + "\t" + largestSumContiguousSubarray(array)); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /largest_sum_contiguous_subarray/largestSumContiguousSubarray.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int largestSumContinousSubArray(int arr[], int size) { 5 | int max_till = 0; 6 | int max_int = 0; 7 | for (int i = 0; i < size; i++) { 8 | max_int = max_int + arr[i]; 9 | if(max_till < max_int) { 10 | max_till = max_int; 11 | } 12 | if (max_int < 0) { 13 | max_int = 0; 14 | } 15 | } 16 | return max_till; 17 | } 18 | 19 | int main() { 20 | int array[10]; 21 | for (int k = 0; k < 10; k++) { 22 | array[k] = rand() % 10; 23 | } 24 | printf("%d", largestSumContinousSubArray(array, 10)); 25 | } 26 | -------------------------------------------------------------------------------- /largest_sum_contiguous_subarray/largestSumContiguousSubarray.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | // largestSumContinousSubArray is main kadane's algorithm function 6 | func largestSumContinousSubArray(arr []int) int { 7 | maxTill := 0 8 | maxTemp := 0 9 | size := len(arr) 10 | for i := 0; i < size; i++ { 11 | maxTemp = maxTemp + arr[i] 12 | if maxTill < maxTemp { 13 | maxTill = maxTemp 14 | } 15 | if maxTemp < 0 { 16 | maxTemp = 0 17 | } 18 | } 19 | return maxTill 20 | } 21 | 22 | func main() { 23 | array := []int{-2, -3, 3, -1, -2, 1, 5, -3} 24 | fmt.Println(largestSumContinousSubArray(array)) 25 | } 26 | -------------------------------------------------------------------------------- /largest_sum_contiguous_subarray/largestSumContiguousSubarray.js: -------------------------------------------------------------------------------- 1 | function largestSumContiguousSubarray (arr) { 2 | /* 3 | * Find the subarray with maximum sum from all subarrays. 4 | * :param arr: List of numbers to form subarray from. 5 | * :return: The maximum sum in all subarrays. 6 | */ 7 | let maxPrev = 0; 8 | let maxNow = 0; 9 | for (let x = 0; x < arr.length; x++) { 10 | maxNow += arr[x]; 11 | maxPrev = Math.max(maxPrev, maxNow); 12 | maxNow = Math.max(0, maxNow); 13 | } 14 | return maxPrev; 15 | } 16 | 17 | function main () { 18 | let arr = [-2, -3, 4, -1, -2, 1, 5, -3]; 19 | console.log('Maximum contiguous sum is : ' + largestSumContiguousSubarray(arr)); 20 | } 21 | 22 | main(); 23 | -------------------------------------------------------------------------------- /largest_sum_contiguous_subarray/largest_sum_contiguous_subarray.py: -------------------------------------------------------------------------------- 1 | def largest_sum_contiguous_subarray(arr): 2 | """ 3 | Find the subarray with maximum sum from all subarrays. 4 | 5 | :param arr: List of numbers to form subarray from. 6 | :return: The maximum sum in all subarrays. 7 | """ 8 | max_now = 0 9 | max_next = 0 10 | for i in arr: 11 | max_next += i 12 | max_now = max(max_next, max_now) 13 | max_next = max(0, max_next) 14 | return max_now 15 | 16 | 17 | def main(): 18 | arr = [-2, -3, 4, -1, -2, 1, 5, -3] 19 | print('Maximum contiguous sum is', largest_sum_contiguous_subarray(arr)) 20 | 21 | 22 | if __name__ == '__main__': 23 | main() 24 | -------------------------------------------------------------------------------- /linear_search/LinearSearch.cs: -------------------------------------------------------------------------------- 1 | /*Linear Search algorithm searches for a given number in array 2 | Time complexity is O(n) , n is size of array*/ 3 | 4 | using System; 5 | 6 | public class LinearSearch 7 | { 8 | public static int Search(int[] data, int target) 9 | { 10 | for (int i = 0; i < data.Length; i++) 11 | if (data[i] == target) 12 | return i; 13 | return -1; 14 | } 15 | 16 | public static void Main() 17 | { 18 | int[] array = new int[100]; 19 | // Initializing array with 1,2,....,100 20 | for(int i = 1; i <= 100; i++) 21 | array[i-1] = i; 22 | // Elements to be searched in the array 23 | int[] search = {12,55,34,102,78}; 24 | for(int i = 0; i < 5; i++) 25 | { 26 | int index = Search(array, search[i]); 27 | if(index >= 0) 28 | Console.WriteLine(search[i] + " found at index " + index); 29 | else 30 | Console.WriteLine(search[i] + " not found in the list"); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /linear_search/LinearSearch.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Linear Search algorithm searches for a given number in array 3 | * Time complexity is O(n) , n is size of array 4 | */ 5 | public class LinearSearch { 6 | 7 | public static int linearSearch(int[] arr, int searchElement) { 8 | for(int i = 0; i < arr.length; i++) { 9 | if(arr[i] == searchElement) 10 | return i; // Element found 11 | } 12 | return -1; // Element not found 13 | } 14 | 15 | public static void main(String[] args) { 16 | int[] array = new int[100]; 17 | // Initializing array with 1,2,....,100 18 | for(int i = 1; i <= 100; i++) 19 | array[i-1] = i; 20 | // Elements to be searched in the array 21 | int[] search = {12,55,34,102,78}; 22 | for(int i = 0; i < 5; i++) { 23 | int index = linearSearch(array, search[i]); 24 | if(index >= 0) 25 | System.out.println(search[i] + " found at index " + index); 26 | else 27 | System.out.println(search[i] + " not found in the list"); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /linear_search/Linear_Search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int search(int a[],int key,int n){ 4 | for(int i = 0; i 2 | /* 3 | * Algorithm to find a given number in an array 4 | * *arr : given array to search in 5 | * search_element : Element to be searched 6 | * size : size of array 7 | */ 8 | int linear_search(const int *arr, int size, int search_element) { 9 | int i; 10 | for (i = 0; i < size; i++) { 11 | if (arr[i] == search_element) 12 | return i; // Element found 13 | } 14 | return -1; // Element not found 15 | } 16 | 17 | int main() { 18 | int array[100], i; 19 | 20 | // Initializing array with 1,2,....,100 21 | for (i = 1; i <= 100; i++) 22 | array[i-1] = i; 23 | 24 | // Elements to be searched in the array 25 | int search[5] = {12, 55, 34, 102, 78}; 26 | 27 | for (i = 0; i < 5; i++) { 28 | int index = linear_search(array, 100, search[i]); 29 | 30 | if (index >= 0) 31 | printf("%d found at index %d\n", search[i], index); 32 | else 33 | printf("%d not found in the list\n", search[i]); 34 | } 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /linear_search/linear_search.py: -------------------------------------------------------------------------------- 1 | def linear_search(arr, x): 2 | """ 3 | Performs a linear search 4 | :param arr: Iterable of elements 5 | :param x: Element to search for 6 | :return: Index if element found else None 7 | """ 8 | l = len(arr) 9 | for i in range(l): 10 | if arr[i] == x: 11 | return i 12 | return None 13 | 14 | 15 | def main(): 16 | arr = range(100) 17 | index = linear_search(arr, 55) 18 | if index is None: 19 | print('Element not found in array') 20 | else: 21 | print('Element found at index %s' % index) 22 | 23 | 24 | if __name__ == '__main__': 25 | main() 26 | -------------------------------------------------------------------------------- /linked_list/linked_list.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | ) 7 | 8 | // List is a A general List interface 9 | type List interface { 10 | Add(newVal int) 11 | Len() int 12 | PeekLast() (int, error) 13 | PeekFirst() (int, error) 14 | ToSlice() []int 15 | } 16 | 17 | type linkedListNode struct { 18 | value int 19 | next *linkedListNode 20 | } 21 | 22 | // LinkedList is a singly-linked LinkedList 23 | type LinkedList struct { 24 | root *linkedListNode 25 | tail *linkedListNode 26 | length int 27 | } 28 | 29 | // Len returns the length of the LinkedList 30 | func (ll *LinkedList) Len() int { return ll.length } 31 | 32 | // Add adds a new element to the LinkedList Time Complexity: O(1) 33 | func (ll *LinkedList) Add(newVal int) { 34 | newNode := new(linkedListNode) 35 | newNode.value = newVal 36 | if ll.length == 0 { 37 | ll.root = newNode 38 | ll.root.next = nil 39 | } else if ll.length == 1 { 40 | ll.tail = newNode 41 | ll.root.next = ll.tail 42 | } else { 43 | ll.tail.next = newNode 44 | ll.tail = newNode 45 | } 46 | 47 | ll.length++ 48 | } 49 | 50 | // RemoveFirst removes the first element from the LinkedList Time Complexity: O(1) 51 | func (ll *LinkedList) RemoveFirst() (val int, err error) { 52 | if ll.length == 0 { 53 | return 0, errors.New("there is nothing to remove") 54 | } else if ll.length == 1 { 55 | val = ll.root.value 56 | ll.root = nil 57 | } else if ll.length == 2 { 58 | val = ll.root.value 59 | ll.root = ll.tail 60 | ll.tail = nil 61 | } else { 62 | val = ll.root.value 63 | ll.root = ll.root.next 64 | } 65 | 66 | ll.length-- 67 | return 68 | } 69 | 70 | // ToSlice converts the LinkedList to a Slice Time Complexity: O(n) 71 | func (ll *LinkedList) ToSlice() []int { 72 | var sliceList []int 73 | 74 | for currNode := ll.root; currNode != nil; currNode = currNode.next { 75 | sliceList = append(sliceList, currNode.value) 76 | } 77 | 78 | return sliceList 79 | } 80 | 81 | // PeekLast returns the last element of the LinkedList, without removing it Time Complexity: O(1) 82 | func (ll *LinkedList) PeekLast() (val int, err error) { 83 | if ll.length == 0 { 84 | return 0, errors.New("there is nothing to peek") 85 | } else if ll.length == 1 { 86 | val = ll.root.value 87 | } else { 88 | val = ll.tail.value 89 | } 90 | 91 | return val, nil 92 | } 93 | 94 | // PeekFirst returns the first element of the LinkedList, without removing it Time Complexity: O(1) 95 | func (ll *LinkedList) PeekFirst() (val int, err error) { 96 | if ll.length == 0 { 97 | return 0, errors.New("there is nothing to peek") 98 | } 99 | 100 | val = ll.root.value 101 | 102 | return val, nil 103 | } 104 | 105 | func main() { 106 | var ll LinkedList 107 | ll.Add(10) 108 | ll.Add(15) 109 | ll.Add(25) 110 | first, err := ll.RemoveFirst() 111 | for err == nil { 112 | fmt.Println(first) 113 | first, err = ll.RemoveFirst() 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /longest_common_subsequence/LongestCommonSubsequence.java: -------------------------------------------------------------------------------- 1 | public class LongestCommonSubsequence { 2 | //Function that returns Longest Common Subsequence of two strings 3 | //Time Complexity - O( len(str1) * len(str2) ) 4 | //Space Complexity - O( len(str1)*len(str2) ) 5 | private static String longestCommonSubsequence(String str1, String str2) { 6 | int[][] arr = new int[str1.length() + 1][str2.length() + 1]; 7 | for (int i = str1.length() - 1; i >= 0; i--) { 8 | for (int j = str2.length() - 1; j >= 0; j--) { 9 | if (str1.charAt(i) == str2.charAt(j)) { 10 | arr[i][j] = arr[i + 1][j + 1] + 1; 11 | } 12 | else { 13 | arr[i][j] = Math.max(arr[i + 1][j], arr[i][j + 1]); 14 | } 15 | } 16 | } 17 | String res = ""; 18 | int i = 0; 19 | int j = 0; 20 | while (i < str1.length() && j < str2.length()) { 21 | if (str1.charAt(i) == str2.charAt(j)) { 22 | res = res + str1.charAt(i); 23 | i++; 24 | j++; 25 | } 26 | else if (arr[i + 1][j] >= arr[i][j + 1]) { 27 | i++; 28 | } 29 | else { 30 | j++; 31 | } 32 | } 33 | return res; 34 | } 35 | 36 | public static void main(String[] args) { 37 | String s1 = "applebanana"; 38 | String s2 = "alphabet"; 39 | System.out.println(longestCommonSubsequence(s1, s2)); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /longest_common_subsequence/longestCommonSubsequence.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define max(a,b) (a > b) ? a : b 5 | 6 | // Function that computes the longest common subsequence 7 | // Complexity: O( len(string1) * len(string2) ) 8 | int longestCommonSubsequence(char *string1, char *string2) { 9 | int len1 = (int) strlen(string1); 10 | int len2 = (int) strlen(string2); 11 | int lcs[len1 + 1][len2 + 1]; 12 | 13 | for (int i = 0; i <= len1; ++i) { 14 | for (int j = 0; j <= len2; ++j) { 15 | if (i == 0 || j == 0) { 16 | lcs[i][j] = 0; 17 | } else if (string1[i - 1] == string2[j - 1]) { 18 | lcs[i][j] = lcs[i - 1][j - 1] + 1; 19 | } else { 20 | lcs[i][j] = max(lcs[i - 1][j], lcs[i][j - 1]); 21 | } 22 | } 23 | } 24 | 25 | return lcs[len1][len2]; 26 | } 27 | 28 | 29 | int main() { 30 | // String from which Longest common subsequence have to find 31 | // Maximum length of string should be 100 char long 32 | char str1[100]; 33 | char str2[100]; 34 | strcpy(str1, "mathematicians study maths"); 35 | strcpy(str2, "people study matrix multiplication"); 36 | printf("%d\n", longestCommonSubsequence(str1, str2)); 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /longest_common_subsequence/longestCommonSubsequence.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | ) 7 | 8 | // Time complexity : O(len(str1)*len(str2)) 9 | // longestCommonSubsequence returns length of the LCS 10 | func longestCommonSubsequence(str1, str2 string) int { 11 | len1 := len(str1) 12 | len2 := len(str2) 13 | lcs := make([][]int, len1+1) 14 | for i := range lcs { 15 | lcs[i] = make([]int, len2+1) 16 | } 17 | for i := 0; i <= len1; i++ { 18 | for j := 0; j <= len2; j++ { 19 | if i == 0 || j == 0 { 20 | lcs[i][j] = 0 21 | } else if str1[i-1] == str2[j-1] { 22 | lcs[i][j] = lcs[i-1][j-1] + 1 23 | } else { 24 | lcs[i][j] = int(math.Max(float64(lcs[i-1][j]), float64(lcs[i][j-1]))) 25 | } 26 | } 27 | } 28 | return lcs[len1][len2] 29 | } 30 | 31 | // Driver function to test above algorithm 32 | func main() { 33 | str1 := "mohit" 34 | str2 := "mokyit" 35 | fmt.Println(longestCommonSubsequence(str1, str2)) 36 | } 37 | -------------------------------------------------------------------------------- /longest_common_subsequence/longestCommonSubsequence.js: -------------------------------------------------------------------------------- 1 | function longestCommonSubsequence (str1, str2) { 2 | /* 3 | * Time Complexity - O(len(str1) * len(str2)) 4 | * Space Complexity - O(len(str1) * len(str2)) 5 | * :param seq1: First sequence 6 | * :param seq2: Second sequence 7 | * :return: The longest common subsequence of two input sequences 8 | */ 9 | let len1 = str1.length; 10 | let len2 = str2.length; 11 | let lcs = new Array(len1 + 1); 12 | for (let x = 0; x <= len1; x++) { 13 | lcs[x] = new Array(len2 + 1); 14 | } 15 | for (let i = 0; i <= len1; i++) { 16 | for (let j = 0; j <= len2; j++) { 17 | if (i === 0 || j === 0) { 18 | lcs[i][j] = 0; 19 | } else if (str1[i - 1] === str2[j - 1]) { 20 | lcs[i][j] = lcs[i - 1][j - 1] + 1; 21 | } else { 22 | lcs[i][j] = Math.max(lcs[i - 1][j], lcs[i][j - 1]); 23 | } 24 | } 25 | } 26 | let res = ''; 27 | let i = len1; 28 | let j = len2; 29 | while (i > 0 && j > 0) { 30 | if (str1[i - 1] === str2[j - 1]) { 31 | res = str1[i - 1] + res; 32 | i--; 33 | j--; 34 | } else if (lcs[i - 1][j] > lcs[i][j - 1]) { 35 | i--; 36 | } else { 37 | j--; 38 | } 39 | } 40 | return res; 41 | } 42 | 43 | function main () { 44 | let a = 'whattheheckman'; 45 | let b = 'whatareyoudoinghere'; 46 | console.log('Longest Common Subsequence : ' + longestCommonSubsequence(a, b)); 47 | } 48 | 49 | main(); 50 | -------------------------------------------------------------------------------- /longest_common_subsequence/longest_common_subsequence.py: -------------------------------------------------------------------------------- 1 | def longest_common_subsequence(seq1, seq2): 2 | """ 3 | Returns the longest common subsequence 4 | :param seq1: First sequence 5 | :param seq2: Second sequence 6 | :return: The longest common subsequence of two input sequences 7 | """ 8 | len1 = len(seq1) 9 | len2 = len(seq2) 10 | sequences = [[0 for x in range(len2 + 1)] for x in range(len1 + 1)] 11 | for i in range(len1 + 1): 12 | for j in range(len2 + 1): 13 | if i == 0 or j == 0: 14 | sequences[i][j] = 0 15 | elif seq1[i - 1] == seq2[j - 1]: 16 | sequences[i][j] = sequences[i - 1][j - 1] + 1 17 | else: 18 | sequences[i][j] = max(sequences[i - 1][j], sequences[i][j - 1]) 19 | prev_selected = sequences[len1][len2] 20 | lcs = [''] * (prev_selected + 1) 21 | lcs[prev_selected] = '\0' # End of line char 22 | i = len1 23 | j = len2 24 | while i > 0 and j > 0: 25 | if seq1[i - 1] == seq2[j - 1]: 26 | lcs[prev_selected - 1] = seq1[i - 1] 27 | i -= 1 28 | j -= 1 29 | prev_selected -= 1 30 | elif sequences[i - 1][j] > sequences[i][j - 1]: 31 | i -= 1 32 | else: 33 | j -= 1 34 | return lcs 35 | 36 | 37 | def main(): 38 | """ 39 | Driver function for testing. 40 | """ 41 | seq1 = 'iiitv/algos' 42 | seq2 = 'iiitv/Odyssy' 43 | print('longest common subsequence is', 44 | longest_common_subsequence(seq1, seq2)) 45 | 46 | 47 | if __name__ == '__main__': 48 | main() 49 | -------------------------------------------------------------------------------- /longest_palindromic_substring/LongestPalindromicSubstring.java: -------------------------------------------------------------------------------- 1 | public class LongestPalindromicSubstring { 2 | 3 | /* 4 | This method is used to determine palindrome about a point in string. 5 | @param test: Input string whose substrings are to be checked 6 | @param left: Left end of result palindromic substring 7 | @param right: Right end of result palindromic substring 8 | @return: Length of palindromic substring 9 | */ 10 | private static int expandAroundCenter(String test, int left, int right) { 11 | int lengthOfString = test.length(); 12 | while (left >= 0 && right < lengthOfString && test.charAt(left) == test.charAt(right)) { 13 | left -= 1; 14 | right += 1; 15 | } 16 | return right - left - 1; 17 | } 18 | 19 | /* 20 | Method to find longest substring which is a palindrome. 21 | @param test: Input string whose substrings are to be checked 22 | @return: Longest substring of input string which is a palindrome 23 | 24 | Time complexity: O(lengthOfString^2) 25 | Space complexity: O(1) 26 | */ 27 | public static String longestPalindromicSubstring(String test) { 28 | String toTest = test.toLowerCase(); 29 | int start = 0; 30 | int end = 0; 31 | int lengthOfString = test.length(); 32 | for (int i = 0; i < lengthOfString; ++i) { 33 | int length = Math.max(expandAroundCenter(toTest, i, i), expandAroundCenter(toTest, i, i + 1)); 34 | if (length > end - start) { 35 | start = i - (length - 1) / 2; 36 | end = i + length / 2; 37 | } 38 | } 39 | return test.substring(start, end + 1); 40 | } 41 | 42 | public static void main(String[] args) { 43 | String test = "Nitin"; 44 | System.out.println("Longest Palindromic Substring of " + 45 | test + " is " + 46 | longestPalindromicSubstring(test)); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /longest_palindromic_substring/longestPalindromicSubstring.js: -------------------------------------------------------------------------------- 1 | function expandAroundCenter (test, left, right) { 2 | /* 3 | :param test: Input string whose substrings are to be checked 4 | :param left: Left end of result palindromic substring 5 | :param right: Right end of result palindromic substring 6 | :return: Length of palindromic substring 7 | */ 8 | let n = test.length; 9 | while (left >= 0 && right < n && test.charAt(left) === test.charAt(right)) { 10 | left--; 11 | right++; 12 | } 13 | return right - left - 1; 14 | } 15 | 16 | function longestPalindromicSubstring (test) { 17 | /* 18 | Function to find longest substring which is a palindrome 19 | 20 | :param test: Input string whose substrings are to be checked 21 | :return: Longest substring of input string which is a palindrome 22 | 23 | Time complexity: O(n^2) 24 | Space complexity: O(1) 25 | */ 26 | let start = 0; 27 | let end = 0; 28 | 29 | for (let i = 0; i < test.length; i++) { 30 | let length = Math.max(expandAroundCenter(test, i, i), 31 | expandAroundCenter(test, i, i + 1)); 32 | if (length > end - start) { 33 | start = i - Math.floor((length - 1) / 2); 34 | end = i + Math.floor(length / 2); 35 | } 36 | } 37 | return test.slice(start, end + 1); 38 | } 39 | 40 | function main () { 41 | let test = 'geeksforgeeks'; 42 | console.log('Longest Palindromic Substring of', 43 | test, 'is', longestPalindromicSubstring(test)); 44 | } 45 | 46 | main(); 47 | -------------------------------------------------------------------------------- /longest_palindromic_substring/longest_palindromic_substring.cpp: -------------------------------------------------------------------------------- 1 | // Implementation of dp problem: Longest Palindromic substring 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | /* 9 | Returns the length of palindromic substring 10 | 11 | @param test: input string whose substrings are to be checked 12 | @param left: Left end of result palindromic substring 13 | @param right: Right end of result palindromic substring 14 | @return: Length of palindromic substring 15 | */ 16 | 17 | int expand_around_center(string test, int left, int right) { 18 | int n = test.length(); 19 | 20 | while (left >= 0 && right < n && test[left] == test[right]) { 21 | left -= 1; 22 | right += 1; 23 | } 24 | return right - left - 1; 25 | } 26 | 27 | /* 28 | Returns the longest substring which is a pallindrome 29 | 30 | @param test: input string whose substrings are to be checked 31 | @return longest substring of input string which is a pallindrome 32 | 33 | Time complexity: O(n^2) 34 | Space complexity: O(1) 35 | n is size of input string 36 | */ 37 | 38 | string longest_palindromic_substring(string test) { 39 | int start = 0, end = 0; 40 | int n = test.length(); 41 | 42 | for (int i = 0; i < n; ++i) { 43 | int length = max(expand_around_center(test, i, i), expand_around_center(test, i, i + 1)); 44 | if (length > end - start) { 45 | start = i - (int)((length - 1) / 2); 46 | end = i + (int)(length / 2); 47 | } 48 | } 49 | return test.substr(start, end - start + 1); 50 | } 51 | 52 | int main() { 53 | string test = "iiit"; 54 | cout << "Longest palindromic substring is: " << longest_palindromic_substring(test) << endl; 55 | return 0; 56 | } 57 | 58 | -------------------------------------------------------------------------------- /longest_palindromic_substring/longest_palindromic_substring.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | // expandAroundCenter returns length of palindromic substring 6 | func expandAroundCenter(runes []rune, left int, right int) int { 7 | n := len(runes) 8 | 9 | for left >= 0 && right < n && runes[left] == runes[right] { 10 | left-- 11 | right++ 12 | } 13 | return right - left - 1 14 | } 15 | 16 | // LongestPalindromicSubstring returns the longest palindromic substring in 17 | // provided string. 18 | // Time complexity: O(n^2) 19 | // Space complexity: O(1) 20 | func LongestPalindromicSubstring(str string) string { 21 | start, end := 0, 0 22 | runes := []rune(str) 23 | 24 | for i := 0; i < len(runes); i++ { 25 | a := expandAroundCenter(runes, i, i) 26 | b := expandAroundCenter(runes, i, i+1) 27 | 28 | length := 0 29 | if a > b { 30 | length = a 31 | } else { 32 | length = b 33 | } 34 | 35 | if length > end-start { 36 | start = i - (length-1)/2 37 | end = i + length/2 38 | } 39 | } 40 | return string(runes[start : end+1]) 41 | } 42 | 43 | func main() { 44 | str := "And the longest palindrome is... neveroddoreven!" 45 | fmt.Println(LongestPalindromicSubstring(str)) 46 | } 47 | -------------------------------------------------------------------------------- /longest_palindromic_substring/longest_palindromic_substring.py: -------------------------------------------------------------------------------- 1 | def expand_around_center(test, left, right): 2 | """ 3 | :param test: Input string whose substrings are to be checked 4 | :param left: Left end of result palindromic substring 5 | :param right: Right end of result palindromic substring 6 | :return: Length of palindromic substring 7 | """ 8 | n = len(test) 9 | while left >= 0 and right < n and test[left] is test[right]: 10 | left -= 1 11 | right += 1 12 | return right - left - 1 13 | 14 | 15 | def longest_palindromic_substring(test): 16 | """ 17 | Function to find longest substring which is a palindrome 18 | 19 | :param test: Input string whose substrings are to be checked 20 | :return: Longest substring of input string which is a palindrome 21 | 22 | Time complexity: O(n^2) 23 | Space complexity: O(1) 24 | """ 25 | start = end = 0 26 | for i in range(len(test)): 27 | length = max(expand_around_center(test, i, i), 28 | expand_around_center(test, i, i + 1) 29 | ) 30 | if length > end - start: 31 | start = i - (length - 1) // 2 32 | end = i + length // 2 33 | return test[start: end + 1] 34 | 35 | 36 | def main(): 37 | """ 38 | Driver function to test the code. 39 | """ 40 | test = 'geeksforgeeks' 41 | print('Longest palindromic substring of', test, 42 | 'is', longest_palindromic_substring(test)) 43 | 44 | 45 | if __name__ == '__main__': 46 | main() 47 | -------------------------------------------------------------------------------- /merge_sort/MergeSort.java: -------------------------------------------------------------------------------- 1 | public class MergeSort { 2 | 3 | private static void merge(int[] a, int first, int mid, int last) { 4 | int l = mid - first + 1; 5 | int r = last - mid; 6 | int[] left = new int[l]; 7 | int[] right = new int[r]; 8 | 9 | for (int i = 0; i < l; i++) { //copy left 10 | left[i] = a[first + i]; 11 | } 12 | for (int j = 0; j < r; j++) { //copy right 13 | right[j] = a[mid + j + 1]; 14 | } 15 | int i = 0; 16 | int j = 0; 17 | int k = first; 18 | while (i < l && j < r) { //merging 19 | if (left[i] <= right[j]) { 20 | a[k] = left[i]; 21 | i++; 22 | } else { 23 | a[k] = right[j]; 24 | j++; 25 | } 26 | k++; 27 | } 28 | while (i < l) { //remainig left element 29 | a[k] = left[i]; 30 | i++; 31 | k++; 32 | } 33 | while (j < r) { //remainig right element 34 | a[k] = right[j]; 35 | j++; 36 | k++; 37 | } 38 | } 39 | 40 | private static void mergeSort(int[] a, int first, int last) { 41 | if (first < last) { 42 | int mid = (first + last) / 2; //find the middle 43 | mergeSort(a, first, mid); //sort left half 44 | mergeSort(a, mid + 1, last); //sort right half 45 | merge(a, first, mid, last); //merge above two sorted halves 46 | } 47 | } 48 | 49 | public static void main(String[] args) { 50 | int[] arr = new int[] {2, 4, 9, 6, 7, 8}; 51 | mergeSort(arr, 0, arr.length - 1); 52 | for (int element : arr) { 53 | System.out.println(element); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /merge_sort/mergeSort.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Implementation of merge sort algorithm 3 | * Time complexity: O(size*log(size)) 4 | * Space complexity: O(size) 5 | */ 6 | function merge (left, right) { 7 | let i = 0; 8 | let j = 0; 9 | let size = left.length + right.length; 10 | let arr = []; 11 | for (let k = 0; k < size; k++) { 12 | if (i > left.length - 1 && j < right.length) { 13 | arr[k] = right[j]; 14 | j++; 15 | } else if (j > right.length - 1 && i < left.length) { 16 | arr[k] = left[i]; 17 | i++; 18 | } else if (left[i] < right[j]) { 19 | arr[k] = left[i]; 20 | i++; 21 | } else { 22 | arr[k] = right[j]; 23 | j++; 24 | } 25 | } 26 | return arr; 27 | } 28 | 29 | /* 30 | * :param arr: array to be sorted 31 | */ 32 | function mergeSort (arr) { 33 | if (arr.length < 2) { 34 | return arr; 35 | } 36 | let middle = parseInt(arr.length / 2); 37 | let left = arr.slice(0, middle); 38 | let right = arr.slice(middle, arr.length); 39 | return merge(mergeSort(left), mergeSort(right)); 40 | } 41 | 42 | function main () { 43 | let arr = [2, 1, 6, 444, 8, 99, 10]; 44 | console.log('Sorted data is :'); 45 | arr = mergeSort(arr); 46 | console.log(arr); 47 | } 48 | 49 | main(); 50 | -------------------------------------------------------------------------------- /merge_sort/merge_sort.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Following Algorithm sorts the given array in worst case time complexity O(n*log(n)) 3 | * and space complexity O(n), n being size of array. 4 | */ 5 | 6 | #include 7 | 8 | void merge(int *arr, int left, int mid, int right) { 9 | int i, j, k; 10 | int n_left = mid - left + 1; 11 | int n_right = right - mid; 12 | int left_arr[n_left]; 13 | int right_arr[n_right]; 14 | for (i = 0; i < n_left; i++) 15 | left_arr[i] = arr[left + i]; 16 | for (j = 0; j < n_right; j++) 17 | right_arr[j] = arr[mid + 1 + j]; 18 | i = 0; 19 | j = 0; 20 | k = left; 21 | while (i < n_left && j < n_right) { 22 | if (left_arr[i] <= right_arr[j]) { 23 | arr[k] = left_arr[i]; 24 | i++; 25 | } else { 26 | arr[k] = right_arr[j]; 27 | j++; 28 | } 29 | k++; 30 | } 31 | while (i < n_left) { 32 | arr[k] = left_arr[i]; 33 | i++; 34 | k++; 35 | } 36 | while (j < n_right) { 37 | arr[k] = right_arr[j]; 38 | j++; 39 | k++; 40 | } 41 | } 42 | 43 | void merge_sort(int *arr, int left, int right) { 44 | if (left < right) { 45 | int mid = (left + right) / 2; 46 | merge_sort(arr, left, mid); 47 | merge_sort(arr, mid + 1, right); 48 | merge(arr, left, mid, right); 49 | } 50 | } 51 | 52 | int main() { 53 | int i; 54 | int arr[] = {7, 10, 14, 1, 2, 6, 17, 0}; 55 | int size = sizeof(arr) / sizeof(arr[0]); 56 | merge_sort(arr, 0, size - 1); 57 | for (i = 0; i < size; i++) { 58 | printf("%d ", arr[i]); 59 | } 60 | return 0; 61 | } 62 | -------------------------------------------------------------------------------- /merge_sort/merge_sort.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | // MergeSort divides the slice into two parts, sorts both the part of slice and then merge it 6 | // Time complexity : O(size(log(size))) 7 | // Space complexity : O(size) 8 | func MergeSort(slice []int) []int { 9 | if len(slice) < 2 { 10 | return slice 11 | } 12 | mid := (len(slice)) / 2 13 | return merge(MergeSort(slice[:mid]), MergeSort(slice[mid:])) 14 | } 15 | 16 | // merge merges two sorted slice 17 | // Time complexity : O(size) 18 | // Space complexity : O(size) 19 | func merge(left []int, right []int) []int { 20 | i := 0 21 | j := 0 22 | size := len(left) + len(right) 23 | slice := make([]int, size, size) // make built-in function allocates and initializes an object of type slice 24 | for k := 0; k < size; k++ { 25 | if i > len(left)-1 && j < len(right) { 26 | slice[k] = right[j] 27 | j++ 28 | } else if j > len(right)-1 && i < len(left) { 29 | slice[k] = left[i] 30 | i++ 31 | } else if left[i] < right[j] { 32 | slice[k] = left[i] 33 | i++ 34 | } else { 35 | slice[k] = right[j] 36 | j++ 37 | } 38 | } 39 | return slice 40 | } 41 | 42 | func main() { 43 | slice := []int{8, 2, 4, 9, 1, 699, 0, 9999} 44 | fmt.Println("Sorted data is:") 45 | slice = MergeSort(slice) 46 | fmt.Println(slice) 47 | } 48 | -------------------------------------------------------------------------------- /merge_sort/merge_sort.py: -------------------------------------------------------------------------------- 1 | def merge(array, left, right): 2 | """ 3 | Perform Merge Operation between arrays. 4 | Time Complexity: Theta(nLogn) 5 | Auxiliary Space: O(n) 6 | :param array: Iterable of elements 7 | :param left: left limit for merge sort 8 | :param right: right limit for merge sort 9 | :return: no returns, merges arrays. 10 | """ 11 | mid = (left + right) // 2 12 | l = array[left:mid + 1] 13 | r = array[mid + 1:right + 1] 14 | k = left 15 | while l and r: 16 | if l[0] < r[0]: 17 | array[k] = l.pop(0) 18 | else: 19 | array[k] = r.pop(0) 20 | k += 1 21 | while l: 22 | array[k] = l.pop(0) 23 | k += 1 24 | while r: 25 | array[k] = r.pop(0) 26 | k += 1 27 | 28 | 29 | def merge_sort(array, left, right): 30 | """ 31 | Perform sort using merge function. 32 | Time Complexity : O(nlog(n)). 33 | Space Complexity : O(n). 34 | :param array: Iterable of elements 35 | :param left: left limit for merge sort 36 | :param right: right limit for merge sort 37 | :return: no returns, sorts array 38 | """ 39 | if left < right: 40 | mid = (left + right) // 2 41 | merge_sort(array, left, mid) 42 | merge_sort(array, mid + 1, right) 43 | merge(array, left, right) 44 | 45 | 46 | def main(): 47 | a = [15, 19, 18, 26, 456, 87, 45, -1, 558897984] 48 | merge_sort(a, 0, len(a) - 1) 49 | print(a) 50 | 51 | 52 | if __name__ == '__main__': 53 | main() 54 | -------------------------------------------------------------------------------- /modular_exponential/ModularExponential.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | 3 | public class ModularExponential { 4 | public static BigInteger modularExponential(long base, long power, long mod) { 5 | BigInteger result = BigInteger.ONE; 6 | base = base % mod; 7 | while(power > 0) { 8 | if(power % 2 == 1) { 9 | result = result.multiply(BigInteger.valueOf(base)); 10 | result = result.mod(BigInteger.valueOf(mod)); 11 | } 12 | power = power / 2; 13 | base = (base * base) % mod; 14 | } 15 | return result; 16 | } 17 | 18 | public static void main(String[] args) { 19 | long base = 78; 20 | long pow = 20; 21 | long mod = 65; 22 | System.out.println(modularExponential(base, pow, mod)); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /modular_exponential/modularExponential.js: -------------------------------------------------------------------------------- 1 | function modularExponential (base, power, mod) { 2 | /* 3 | Performs Modular Exponential. 4 | Time Complexity : O(log (power)) 5 | :param base: Number that is going to be raised. 6 | :param power: Power to which the number is raised. 7 | :param mod: Number by which modulo has to be performed. 8 | :return: Returns (base ^ power) % mod 9 | */ 10 | let answer = 1; 11 | base = base % mod; 12 | while (power) { 13 | if (power & 1) { 14 | answer = (answer * base) % mod; 15 | } 16 | power = power >> 1; 17 | base = (base * base) % mod; 18 | } 19 | return answer; 20 | } 21 | 22 | function main () { 23 | let base = 3; 24 | let power = 5; 25 | let mod = 61; 26 | let res = modularExponential(base, power, mod); 27 | console.log('%d\n', res); 28 | } 29 | 30 | main(); 31 | -------------------------------------------------------------------------------- /modular_exponential/modular_exponential.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // Time Complexity : O(log (power)) 4 | long long modularExponential(long long base, long power, long long mod) { 5 | long long answer = 1; 6 | base = base % mod; 7 | while (power) { 8 | if (power & 1) { 9 | answer = (answer * base) % mod; 10 | } 11 | power = power >> 1; 12 | base = (base * base) % mod; 13 | } 14 | return answer; 15 | } 16 | 17 | int main() { 18 | long long base = 2; 19 | long power = 10; 20 | long long mod = 100000; 21 | printf("%lld\n", modularExponential(base, power, mod)); 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /modular_exponential/modular_exponential.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | // ModularExponential computes x^y 6 | // Time Complexity : O(log(power)) 7 | func ModularExponential(base int64, power int, mod int64) int64 { 8 | result := int64(1) 9 | base = base % mod 10 | for power > 0 { 11 | if power%2 == 1 { 12 | result = (result * base) % mod 13 | } 14 | power = power >> 1 15 | base = (base * base) % mod 16 | } 17 | return result 18 | } 19 | 20 | func main() { 21 | base, power, mod := int64(2), 20, int64(100000) 22 | fmt.Println(ModularExponential(base, power, mod)) 23 | } 24 | -------------------------------------------------------------------------------- /modular_exponential/modular_exponential.py: -------------------------------------------------------------------------------- 1 | """ 2 | Modular Exponential 3 | """ 4 | 5 | 6 | def mod_exponent(base, power, mod): 7 | """ 8 | Modular exponential of a number 9 | 10 | :param base : number which is going to be raised 11 | :param power : power to which the number is raised 12 | :param mod : number by modulo has to be performed 13 | 14 | :return : number raised to power and modulo by mod [(base ^ power) % mod] 15 | """ 16 | res = 1 # Initialize result 17 | base = base % mod # Update base if it is more than or equal mod_ 18 | while power > 0: 19 | if power & 1: # if pow_ is odd multiply it with result 20 | res = (res * base) % mod 21 | power = power >> 1 # _pow must be even now 22 | base = (base * base) % mod 23 | return res 24 | 25 | 26 | def main(): 27 | """ 28 | Driver function 29 | """ 30 | base = 42 31 | power = 58 32 | mod = 69 33 | print(mod_exponent(base, power, mod)) 34 | 35 | 36 | if __name__ == '__main__': 37 | main() 38 | -------------------------------------------------------------------------------- /n_queen_problem/NQueenProblem.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Implementation of popular N-Queen Problem using Backtracking algorithm. 3 | * The size of a chess board is given, suppose n, then we have to suggest such a configuration than n queens could be placed on the chess board and no queen is under attack 4 | * There can be a number of possible solutions for a specific board. 5 | * This implementation prints only one valid configuration, it can be extended to print all possible valid configurations. 6 | * A good example of recursion. 7 | * You can see the solution for various sizes by changing the value of Size in 13th line.. 8 | */ 9 | #include 10 | #include 11 | using namespace std; 12 | 13 | #define SIDE 8 /* Size of the board = (SIDE X SIDE) */ 14 | 15 | /* The Queen is safe, if 16 | * There's no other Queen in the same row. 17 | * There's no other Queen in the same column. 18 | * There's no other Queen in the same diagonal. 19 | */ 20 | bool queen_is_safe(int board[SIDE][SIDE], int row, int col) { 21 | int i,j; 22 | for (i = 0; i < col; i++) { 23 | if (board[row][i] == 1) { 24 | return false; // * return false, if there's another Queen present in the same row. 25 | } 26 | } 27 | 28 | for (i = row, j = col; i >= 0 && j >= 0; i--, j--) { 29 | if (board[i][j] == 1) { 30 | return false; // * return false, if there's another Queen present in the upper diagonal. 31 | } 32 | } 33 | 34 | for (i = row, j = col; j >= 0 && i < SIDE; i++, j--) { 35 | if (board[i][j]==1) { 36 | return false; // * return false, if there's another Queen present in the lower diagonal. 37 | } 38 | } 39 | 40 | return true; 41 | } 42 | 43 | bool n_queen_solution(int board[SIDE][SIDE], int col) { 44 | if (col >= SIDE) { 45 | return true; // * return true, 46 | } 47 | 48 | for (int i = 0; i < SIDE; i++) { 49 | if ( queen_is_safe(board, i, col) ) { 50 | board[i][col] = 1; // * A queen is placed on (i, col). 51 | if (n_queen_solution(board, col + 1)) { // * Calling n_queen_solution() to place the rest of the queens. 52 | return true; 53 | } else { 54 | board[i][col] = 0; // * Backtrack 55 | } 56 | } 57 | } 58 | return false; 59 | } 60 | 61 | int main() { 62 | int board[SIDE][SIDE]; // * A chess board of rows = SIDE & columns = SIDE. 63 | memset(board, 0, sizeof(board)); // * Initially the board is empty, so all elements of 2-D array board are 0. 64 | 65 | if ( n_queen_solution(board, 0) == false ) { 66 | cout << "No possible configuration exists.\n\n"; 67 | return 0; 68 | } 69 | // * Printing the answer. 70 | cout << "\n No. of queens = " << SIDE << "\n"; 71 | cout << "\n Chess board size = " << SIDE << " X " << SIDE << "\n\n"; 72 | 73 | for (int i = 0; i < SIDE; i++) { 74 | for (int j = 0; j < SIDE; j++) { 75 | cout << " "< board_size: # more queens than the board can contain 64 | return [] # pigeonhole principle -> 0 solutions 65 | 66 | return get_solutions(board_size, queens) 67 | 68 | 69 | def main(): 70 | board_size = 10 71 | solutions = n_queen_problem(board_size, board_size) 72 | print(len(solutions)) 73 | 74 | 75 | if __name__ == '__main__': 76 | main() 77 | -------------------------------------------------------------------------------- /npm-requirements.txt: -------------------------------------------------------------------------------- 1 | happiness 2 | eclint@2.2.0 3 | -------------------------------------------------------------------------------- /pip2-requirements.txt: -------------------------------------------------------------------------------- 1 | numpy 2 | requests 3 | matplotlib 4 | -------------------------------------------------------------------------------- /pip3-requirements.txt: -------------------------------------------------------------------------------- 1 | coala-bears 2 | requests 3 | numpy 4 | matplotlib 5 | -------------------------------------------------------------------------------- /prime_factor/PrimeFactor.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class PrimeFactor { 4 | 5 | public static ArrayList primeFactor(int n) { 6 | ArrayList primeNo = new ArrayList(); 7 | for (int i = 2; i <= n; i++) { 8 | if (n % i == 0) { 9 | primeNo.add(i); 10 | while (n % i == 0) { 11 | n = n / i; 12 | } 13 | } 14 | } 15 | return primeNo; 16 | } 17 | 18 | public static void main(String[] args) { 19 | int n = 8; 20 | System.out.println("Prime Factors are:"); 21 | for (Integer i : primeFactor(n)) { 22 | System.out.println(i); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /prime_factor/primeFactor.js: -------------------------------------------------------------------------------- 1 | function primeFactor (n) { 2 | /* 3 | Finding all the prime factors of a given number 4 | :param n: Number whose prime factors are going to be found 5 | :returns: Array with prime numbers 6 | */ 7 | let primes = []; 8 | for (let i = 2; i <= Math.sqrt(n); i++) { 9 | if (n % i === 0) { 10 | primes.push(i); 11 | while (n % i === 0) { 12 | n = n / i; 13 | } 14 | } 15 | } 16 | if (n !== 1) { 17 | primes.push(n); 18 | } 19 | return primes; 20 | } 21 | 22 | function main () { 23 | let n = 582; 24 | console.log('Prime factors are:'); 25 | let primes = primeFactor(n); 26 | for (let i = 0; i < primes.length; i++) { 27 | console.log(primes[i]); 28 | } 29 | } 30 | 31 | main(); 32 | -------------------------------------------------------------------------------- /prime_factor/prime_factor.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include // for memset 3 | #include // for bool type 4 | #include 5 | 6 | int prime_factors(int num, int *primes) { 7 | int cnt = 0; // index to the last location in the array 8 | bool flag[num]; 9 | memset(flag, true, sizeof(flag)); 10 | flag[0] = false; 11 | flag[1] = false; 12 | for (int i = 2; i*i < num; ++i) { 13 | if (flag[i]) { 14 | if (num % i == 0) { 15 | for (int j = 2 * i; j < num; j += i) { 16 | flag[j] = false; // Non prime number; flag is unset 17 | } 18 | } else { 19 | flag[i] = false; // Not a multiple; flag is unset 20 | } 21 | } 22 | } 23 | for (int i = 0; i < num; ++i) { 24 | if (flag[i] && num % i == 0) { 25 | primes[cnt] = i; 26 | cnt += 1; 27 | } 28 | } 29 | return cnt; // returns the size of the prime array 30 | } 31 | 32 | int main() { 33 | int no = 1562; 34 | int primes[(int)(sqrt(no))]; // array size is sqrt(no) 35 | int idx = prime_factors(no, primes); 36 | printf("Prime Factors: "); // printing of primes 37 | for (int i = 0; i < idx; i++) { 38 | printf("%d ", primes[i]); 39 | } 40 | printf("\n"); 41 | return 0; 42 | } 43 | 44 | -------------------------------------------------------------------------------- /prime_factor/prime_factor.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | ) 7 | 8 | // PrimeFactor finds all the prime factor of given number 9 | func PrimeFactor(n int) []int { 10 | var primes []int 11 | sqrt := int(math.Sqrt(float64(n))) 12 | for i := 2; i <= sqrt; i++ { 13 | if n%i == 0 { 14 | primes = append(primes, i) 15 | for n%i == 0 { 16 | n = n / i 17 | } 18 | } 19 | } 20 | if n != 1 { 21 | primes = append(primes, n) 22 | } 23 | return primes 24 | } 25 | 26 | func main() { 27 | n := 8 28 | fmt.Println("Prime Factors are :") 29 | fmt.Println(PrimeFactor(n)) 30 | } 31 | -------------------------------------------------------------------------------- /prime_factor/prime_factor.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | 4 | def prime_factor(num): 5 | """ 6 | Finds all the prime factor of a number. 7 | 8 | :param num : number whose prime factors we want to find. 9 | :return : return a list of prime factors of number. 10 | """ 11 | factor_list = [] 12 | sqrt_num = int(math.sqrt(num)) + 1 13 | for start in range(2, sqrt_num): 14 | if num % start == 0: 15 | factor_list.append(start) 16 | while (num % start == 0): 17 | num /= start 18 | if num != 1: 19 | factor_list.append(num) 20 | return factor_list 21 | 22 | 23 | def main(): 24 | """ 25 | Driver function 26 | """ 27 | num = 362880 28 | print("Prime Factors are :", prime_factor(num)) 29 | 30 | 31 | if __name__ == '__main__': 32 | main() 33 | -------------------------------------------------------------------------------- /prims/Prims.java: -------------------------------------------------------------------------------- 1 | public class Prims { 2 | private static int[] generate(int[][] ar) { 3 | int length = ar.length; 4 | // Stores the parent of each vertex 5 | int parent[] = new int[length]; 6 | // key value of each vertex 7 | int key[] = new int[length]; 8 | // Flag for included in the MST 9 | boolean mstSet[] = new boolean[length]; 10 | // Initialization of arguments 11 | for (int i = 0; i < length; i++) { 12 | mstSet[i] = false; 13 | key[i] = Integer.MAX_VALUE; 14 | } 15 | 16 | // Starting from the first vertex 17 | // As the first vertex is the root 18 | // So it doesn't have any parent 19 | key[0] = 0; 20 | parent[0] = -1; 21 | 22 | for (int i = 0; i < length - 1; i++) { 23 | // minimum key from given vertices 24 | int u = minKey(key, mstSet); 25 | mstSet[u] = true; 26 | 27 | // Updating the neighbours key 28 | for (int j = 0; j < length; j++) { 29 | if (ar[u][j] != 0 && !mstSet[j] && ar[u][j] < key[j]) { 30 | parent[j] = u; 31 | key[j] = ar[u][j]; 32 | } 33 | } 34 | 35 | } 36 | 37 | return parent; 38 | } 39 | 40 | private static int minKey(int[] key, boolean[] visited) { 41 | int min = Integer.MAX_VALUE; 42 | int minIdx = -1; 43 | int length = key.length; 44 | for (int i = 0; i < length; i++) { 45 | if (!visited[i] && key[i] < min) { 46 | min = key[i]; 47 | minIdx = i; 48 | } 49 | } 50 | return minIdx; 51 | } 52 | 53 | public static void main(String[] args) { 54 | // Given graph 55 | int nodes[][] = new int[][] { 56 | {0, 2, 0, 6, 0}, 57 | {2, 0, 3, 8, 5}, 58 | {0, 3, 0, 0, 7}, 59 | {6, 8, 0, 0, 9}, 60 | {0, 5, 7, 9, 0}, 61 | }; 62 | // parent of all the vertices 63 | int parent[] = generate(nodes); 64 | int length = nodes.length; 65 | 66 | // printing the MST (Prism Algorithm) 67 | System.out.println("Edge : Weight"); 68 | for (int i = 1; i < length; i++) { 69 | System.out.println(parent[i] + " - " + i + " : " + nodes[i][parent[i]]); 70 | } 71 | } 72 | 73 | } 74 | 75 | -------------------------------------------------------------------------------- /prims/prims.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define SIZE 5 6 | 7 | // This function finds the minimal spanning tree by Prim's Algorithm 8 | void prims(int G[SIZE][SIZE], int *parent) { 9 | int select[SIZE], i, j, k; 10 | int v1 = 0, v2 = 0; 11 | for (i = 0; i < SIZE; ++i) { // Initialize the selected vertices list 12 | select[i] = 0; 13 | } 14 | select[0] = 1; 15 | for (k = 1; k < SIZE; ++k) { 16 | int min_dist = INT_MAX; 17 | for (i = 0; i < SIZE; ++i) { // Select an edge such that one vertex is selected and other is not and the edge 18 | for (j = 0; j < SIZE; ++j) { // has the least weight. 19 | if (G[i][j] && ((select[i] && !select[j]) || (!select[i] && select[j]))) { 20 | if (G[i][j] < min_dist) { //obtained edge with minimum wt 21 | min_dist = G[i][j]; 22 | v1 = i; 23 | parent[j] = v1; 24 | v2 = j; //picking up those vertices 25 | } 26 | } 27 | } 28 | } 29 | select[v1] = select[v2] = 1; 30 | } 31 | } 32 | 33 | int main() { 34 | int G[SIZE][SIZE] = { 35 | {0, 2, 0, 6, 0}, 36 | {2, 0, 3, 8, 5}, 37 | {0, 3, 0, 0, 7}, 38 | {6, 8, 0, 0, 9}, 39 | {0, 5, 7, 9, 0}}; 40 | int i, j; 41 | int parent[SIZE]; 42 | memset(parent, 0, SIZE); 43 | printf("Edge\tWeight\n"); 44 | prims(G,parent); 45 | for (i = 1; i < SIZE; ++i) { 46 | printf("%d - %d\t%d \n", parent[i], i, G[i][parent[i]]); 47 | } 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /prims/prims.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | ) 7 | 8 | // Prims finds a minimum spanning tree of given graph, starting at [0] and 9 | // using Prim's algorithm. 10 | func Prims(graph [][]int) []int { 11 | length := len(graph) 12 | // Stores the parent of each vertex 13 | parents := make([]int, length) 14 | // Stores key value of each vertex 15 | keys := make([]int, length) 16 | // true if already included in MST. Otherwise, false. 17 | visited := make([]bool, length) 18 | for i := 0; i < length; i++ { 19 | keys[i] = math.MaxInt32 20 | } 21 | 22 | // Make the first node the root one (no parent) 23 | keys[0] = 0 24 | parents[0] = -1 25 | 26 | for i := 1; i < length; i++ { 27 | // Find the minimum key 28 | u := minKey(keys, visited) 29 | visited[u] = true 30 | 31 | // Update the neighbours 32 | for j := 0; j < length; j++ { 33 | if graph[u][j] != 0 && !visited[j] && graph[u][j] < keys[j] { 34 | parents[j] = u 35 | keys[j] = graph[u][j] 36 | } 37 | } 38 | } 39 | return parents 40 | } 41 | 42 | func minKey(keys []int, visited []bool) int { 43 | min := math.MaxInt32 44 | minID := -1 45 | length := len(keys) 46 | for i := 0; i < length; i++ { 47 | if !visited[i] && keys[i] < min { 48 | min = keys[i] 49 | minID = i 50 | } 51 | } 52 | return minID 53 | } 54 | 55 | func main() { 56 | graph := [][]int{ 57 | {0, 2, 0, 6, 0}, 58 | {2, 0, 3, 8, 5}, 59 | {0, 3, 0, 0, 7}, 60 | {6, 8, 0, 0, 9}, 61 | {0, 5, 7, 9, 0}, 62 | } 63 | // Get parents of all the nodes 64 | parents := Prims(graph) 65 | 66 | // Print the Minimum Spanning Tree 67 | fmt.Println("Edge\tWeight") 68 | for i := 1; i < len(graph); i++ { 69 | fmt.Printf("%d - %d\t%d\n", parents[i], i, graph[i][parents[i]]) 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /prims/prims.js: -------------------------------------------------------------------------------- 1 | function minKey (key, visited) { 2 | let min = Number.MAX_VALUE; 3 | let minIdx = -1; 4 | let length = key.length; 5 | 6 | for (let i = 0; i < length; i++) { 7 | if (!visited[i] && key[i] < min) { 8 | min = key[i]; 9 | minIdx = i; 10 | } 11 | } 12 | 13 | return minIdx; 14 | } 15 | 16 | function generate (graph) { 17 | /* 18 | * Get the parent nodes in the MST 19 | * :param graph: array which represents the graph 20 | * :return: returns array of parent nodes 21 | */ 22 | let length = graph.length; 23 | 24 | // stores the parent of each vertex 25 | let parent = []; 26 | // key value of each vertex 27 | let key = []; 28 | // flag for included in the MST 29 | let mstSet = []; 30 | 31 | // initialize arguments 32 | for (let i = 0; i < length; i++) { 33 | mstSet[i] = false; 34 | key[i] = Number.MAX_VALUE; 35 | } 36 | 37 | // starting from the first vertex 38 | // the first vertex is the root, so it doesn't have any parent 39 | key[0] = 0; 40 | parent[0] = -1; 41 | 42 | for (let i = 0; i < length - 1; i++) { 43 | // minimum key from given vertices 44 | let u = minKey(key, mstSet); 45 | mstSet[u] = true; 46 | 47 | // updating the neighbours key 48 | for (let j = 0; j < length; j++) { 49 | if (graph[u][j] !== 0 && !mstSet[j] && graph[u][j] < key[j]) { 50 | parent[j] = u; 51 | key[j] = graph[u][j]; 52 | } 53 | } 54 | } 55 | 56 | return parent; 57 | } 58 | 59 | function main () { 60 | // given graph 61 | let graph = [ 62 | [0, 2, 0, 6, 0], 63 | [2, 0, 3, 8, 5], 64 | [0, 3, 0, 0, 7], 65 | [6, 8, 0, 0, 9], 66 | [0, 5, 7, 9, 0] 67 | ]; 68 | 69 | // get the parent nodes of all the vertices 70 | let parent = generate(graph); 71 | let length = graph.length; 72 | 73 | // print the MST 74 | console.log('Edge : Weight'); 75 | for (let i = 1; i < length; i++) { 76 | console.log(parent[i] + ' - ' + i + ' : ' + graph[i][parent[i]]); 77 | } 78 | } 79 | 80 | main(); 81 | -------------------------------------------------------------------------------- /queue/queue.py: -------------------------------------------------------------------------------- 1 | class Queue(object): 2 | 3 | def __init__(self): 4 | self._list = [] 5 | 6 | def count(self): 7 | return len(self._list) 8 | 9 | def is_empty(self): 10 | return self.count() == 0 11 | 12 | def enqueue(self, item): 13 | self._list.append(item) 14 | 15 | def dequeue(self): 16 | try: 17 | return self._list.pop(0) 18 | except IndexError: 19 | raise IndexError('pop from empty stack') 20 | 21 | 22 | def main(): 23 | queue = Queue() 24 | n = 100 25 | 26 | print('Empty queue: {0}'.format(queue.is_empty())) 27 | 28 | while queue.count() < 5: 29 | print('pushing elements: {0}'.format(n)) 30 | queue.enqueue(n) 31 | n = n + 100 32 | 33 | print('Number of items: {0}'.format(queue.count())) 34 | print('Empty queue: {0}'.format(queue.is_empty())) 35 | 36 | while True: 37 | try: 38 | print('Removing element: {0}'.format(queue.dequeue())) 39 | except Exception as e: 40 | print('Exception: {0}'.format(e)) 41 | break 42 | 43 | print('Number of items: {0}'.format(queue.count())) 44 | print('Empty queue: {0}'.format(queue.is_empty())) 45 | 46 | 47 | if __name__ == '__main__': 48 | main() 49 | -------------------------------------------------------------------------------- /quick_select/QuickSelect.java: -------------------------------------------------------------------------------- 1 | public class QuickSelect { 2 | /* 3 | * partition function 4 | * array : array on which partitioning has to be done 5 | * left : left index of the partitioning subarray 6 | * right : right index of the partitioning subarray 7 | * pivotIndex : pivot index from which partition has to done 8 | * return : the index of the last element of the left subarray 9 | */ 10 | private static int partition(int[] array, int left, int right, int pivotIndex) { 11 | int pivotValue = array[pivotIndex]; 12 | int temp = array[right]; 13 | array[right] = array[pivotIndex]; 14 | array[pivotIndex] = temp; 15 | int storeIndex = left; 16 | while (left < right) { 17 | if (array[left] < pivotValue) { 18 | temp = array[storeIndex]; 19 | array[storeIndex] = array[left]; 20 | array[left] = temp; 21 | storeIndex++; 22 | } 23 | left++; 24 | } 25 | temp = array[right]; 26 | array[right] = array[storeIndex]; 27 | array[storeIndex] = temp; 28 | return storeIndex; 29 | } 30 | 31 | /* 32 | * Quick Select function 33 | * left : left index of the subarray 34 | * right : right index of the subarray 35 | * pos : position to find the element using quick sort 36 | * return : the value of element at pos place in the sorted array 37 | */ 38 | public static int quickSelect(int[] array, int left, int right, int pos) { 39 | int pivotIndex; 40 | if(pos < 0 || pos >= array.length) { 41 | throw new IndexOutOfBoundsException("index: " + pos); 42 | } 43 | if (left == right) { 44 | return array[left]; 45 | } 46 | pivotIndex = right - 1; 47 | pivotIndex = partition(array, left, right, pivotIndex); 48 | if (pos == pivotIndex) { 49 | return array[pivotIndex]; 50 | } 51 | else if (pos < pivotIndex) { 52 | return quickSelect(array, left, pivotIndex - 1, pos); 53 | } 54 | else { 55 | return quickSelect(array, pivotIndex + 1, right, pos); 56 | } 57 | } 58 | 59 | public static void main(String[] args) { 60 | int[] array = {10, 5, 1, 6, 7, 3, 2, 4, 8, 9}; 61 | System.out.println(quickSelect(array, 0, array.length - 1, 3)); 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /quick_select/quick_select.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | /* 4 | * partition function 5 | * ar : array on which partitioning has to be done 6 | * left : left index of the partitioning subarray 7 | * right : right index of the partitioning subarray 8 | * pivot_idx : pivot index from which partition has to done 9 | * store_idx : index of the last element of the left subarray 10 | * return : the index of the last element of the left subarray 11 | */ 12 | int partition(int *ar, int left, int right, int pivot_idx) { 13 | int pivot_value = ar[pivot_idx]; 14 | int temp = ar[right]; 15 | ar[right] = ar[pivot_idx]; 16 | ar[pivot_idx] = temp; 17 | 18 | int store_idx = left; 19 | while (left < right) { 20 | if (ar[left] < pivot_value) { 21 | temp = ar[store_idx]; 22 | ar[store_idx] = ar[left]; 23 | ar[left] = temp; 24 | store_idx++; 25 | } 26 | left++; 27 | } 28 | temp = ar[right]; 29 | ar[right] = ar[store_idx]; 30 | ar[store_idx] = temp; 31 | return store_idx; 32 | } 33 | 34 | /* 35 | * Quick Select function 36 | * left : left index of the subarray 37 | * right : right index of the subarray 38 | * pos : position to find the element using quick sort 39 | * pivot_index : pivot index 40 | * return : the value of element at pos place in the sorted array 41 | */ 42 | int quick_select(int *ar, int left, int right, int pos) { 43 | int pivot_index; 44 | if (left == right) 45 | return ar[left]; 46 | pivot_index = right - 1; 47 | pivot_index = partition(ar, left, right, pivot_index); 48 | if (pos == pivot_index) { 49 | return ar[pivot_index]; 50 | } else if (pos < pivot_index) { 51 | return quick_select(ar, left, pivot_index - 1, pos); 52 | } else { 53 | return quick_select(ar, pivot_index + 1, right, pos); 54 | } 55 | } 56 | 57 | int main() { 58 | int ar[] = {10, 5, 1, 6, 7, 3, 2, 4, 8, 9}; 59 | printf("%d\n", quick_select(ar, 0, 9, 3)); 60 | return 0; 61 | } 62 | -------------------------------------------------------------------------------- /quick_select/quick_select.py: -------------------------------------------------------------------------------- 1 | def partition(array, start, end): 2 | """ 3 | Perform Partition Operation on array a. 4 | Time Complexity: O(nLogn) 5 | Auxiliary Space: O(n) 6 | :param a: Iterable of elements 7 | :param start: pivot value for array 8 | :param end: right limit of array 9 | :return: return i value for function, used in partitioning of array. 10 | """ 11 | i = start - 1 12 | pivot = array[end] 13 | for j in range(start, end): 14 | if array[j] <= pivot: 15 | i += 1 16 | array[i], array[j] = array[j], array[i] 17 | i += 1 18 | array[i], array[end] = array[end], array[i] 19 | return i 20 | 21 | 22 | def quick_select(array, k): 23 | """ 24 | Perform quick select operation i.e find kth minimum element from array 25 | Time Complexity: O(n) for average case and O(n^2) for worst cases 26 | param a: Array on which operation would perfom 27 | param k: kth minimun element have to find 28 | return: returns kth minimum value 29 | """ 30 | start = 0 31 | end = len(array) - 1 32 | is_found = False 33 | while not is_found: 34 | pos = partition(array, start, end) 35 | if pos == k: 36 | is_found = True 37 | return array[pos] 38 | elif pos < k: 39 | start = pos + 1 40 | else: 41 | end = pos - 1 42 | 43 | 44 | def main(): 45 | a = [2, 4, 6, 2, 1, 4, 2, 7, 8, 9, 5, -4, 23, 0, 8] 46 | k = 10 47 | if a is None: 48 | print("Array doesn't exist") 49 | elif k >= len(a): 50 | print("k is greater than size of array") 51 | else: 52 | print(quick_select(a, k)) 53 | 54 | 55 | if __name__ == '__main__': 56 | main() 57 | -------------------------------------------------------------------------------- /quick_sort/QuickSort.java: -------------------------------------------------------------------------------- 1 | public class QuickSort { 2 | 3 | private static int compare(int[] arr, int i, int j) { 4 | if (arr[i] > arr[j]) { 5 | return i; 6 | } else { 7 | return j; 8 | } 9 | } 10 | 11 | /* 12 | This method returns the index of median of array at i, j, k. 13 | @param arr: Input array to be sorted. 14 | @param i: Left end index of array. 15 | @param j: Right end index of array. 16 | @param k: Middle index of array. 17 | @return: Index of median of array at i, j, k. 18 | */ 19 | private static int median(int[] arr, int i, int j, int k) { 20 | if (arr[i] > arr[j] && arr[i] > arr[k]) { 21 | return compare(arr, k, j); 22 | } else if (arr[j] > arr[i] && arr[j] > arr[k]) { 23 | return compare(arr, k, i); 24 | } else { 25 | return compare(arr, i, j); 26 | } 27 | } 28 | 29 | private static int partition(int[] arr, int start, int end) { 30 | int l = median(arr, start, end, (start + end) / 2); 31 | int p_idx = start - 1; 32 | int tmp = arr[l]; 33 | arr[l] = arr[end]; 34 | arr[end] = tmp; 35 | int pivot = arr[end]; 36 | for (int i = start; i < end; ++i) { 37 | if (arr[i] <= pivot) { 38 | p_idx++; 39 | tmp = arr[i]; 40 | arr[i] = arr[p_idx]; 41 | arr[p_idx] = tmp; 42 | } 43 | } 44 | p_idx++; 45 | tmp = arr[p_idx]; 46 | arr[p_idx] = arr[end]; 47 | arr[end] = tmp; 48 | return p_idx; 49 | } 50 | 51 | public static void quickSort(int[] a, int left, int right) { 52 | if (left < right) { 53 | int pi = partition(a, left, right); //pi index of pivot 54 | quickSort(a, left, pi - 1); //sort left of pivot 55 | quickSort(a, pi + 1, right); //sort right of pivot 56 | } 57 | } 58 | 59 | public static void main(String[] args) { 60 | int[] arr = new int[] {2, 4, 2, 6, 7, -1}; 61 | quickSort(arr, 0, arr.length - 1); 62 | for (int element : arr) { 63 | System.out.println(element); 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /quick_sort/quickSort.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Implementation of quicksort algorithm 3 | * Time complexity: O(nlogn) 4 | * Space complexity: O(n) 5 | * n is the size of array 6 | */ 7 | function median (arr, i, j, k) { 8 | /* 9 | :param arr: array of elements 10 | :param i: index of first element 11 | :param j: index of last element 12 | :param k: index of middle element 13 | :return: return median of values at indices i, j and k 14 | */ 15 | if (arr[i] > arr[j] && arr[i] > arr[k]) { 16 | if (arr[k] > arr[j]) { 17 | return k; 18 | } else { 19 | return j; 20 | } 21 | } else if (arr[j] > arr[i] && arr[j] > arr[k]) { 22 | if (arr[k] > arr[i]) { 23 | return k; 24 | } else { 25 | return i; 26 | } 27 | } else { 28 | if (arr[i] > arr[j]) { 29 | return i; 30 | } else { 31 | return j; 32 | } 33 | } 34 | } 35 | 36 | function partition (arr, start, end) { 37 | /* 38 | :param arr: array of elements 39 | :param start: index of first element 40 | :param end: index of last element 41 | :return: return value for function, used in partitioning of array 42 | */ 43 | let j = start - 1; 44 | let tmp; 45 | let pi = median(arr, start, end, parseInt((start + end) / 2)); 46 | tmp = arr[pi]; 47 | arr[pi] = arr[end]; 48 | arr[end] = tmp; 49 | let pivot = arr[end]; 50 | for (let i = start; i < end; i++) { 51 | if (arr[i] <= pivot) { 52 | j++; 53 | tmp = arr[i]; 54 | arr[i] = arr[j]; 55 | arr[j] = tmp; 56 | } 57 | } 58 | tmp = arr[j + 1]; 59 | arr[j + 1] = arr[end]; 60 | arr[end] = tmp; 61 | return j + 1; 62 | } 63 | 64 | function quickSort (arr, left = 0, right = arr.length - 1) { 65 | /* 66 | :param arr: array to be sorted 67 | :param left: index of first element 68 | :param right: index of last element 69 | */ 70 | if (left < right) { 71 | let p = partition(arr, left, right); 72 | quickSort(arr, left, p - 1); 73 | quickSort(arr, p + 1, right); 74 | } 75 | } 76 | 77 | function main () { 78 | let arr = [2, 1, 6, 44, 8, 9, 10]; 79 | quickSort(arr); 80 | console.log('Sorted data is', arr); 81 | } 82 | 83 | main(); 84 | -------------------------------------------------------------------------------- /quick_sort/quick_sort.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | // partitionArray finds the pivot index 6 | func partitionArray(data []int, left int, right int) int { 7 | pivotIndex := left 8 | for true { 9 | for data[pivotIndex] <= data[right] && pivotIndex != right { 10 | right-- 11 | } 12 | if pivotIndex == right { 13 | break 14 | } else if data[pivotIndex] > data[right] { 15 | data[right], data[pivotIndex] = data[pivotIndex], data[right] 16 | pivotIndex = right 17 | } 18 | for data[pivotIndex] >= data[left] && pivotIndex != left { 19 | left++ 20 | } 21 | if pivotIndex == left { 22 | break 23 | } else if data[pivotIndex] < data[left] { 24 | data[left], data[pivotIndex] = data[pivotIndex], data[left] 25 | pivotIndex = left 26 | } 27 | } 28 | return pivotIndex 29 | } 30 | 31 | func quickSort(data []int, begin int, end int) { 32 | if begin < end { 33 | pivotIndex := partitionArray(data, begin, end) 34 | quickSort(data, begin, pivotIndex-1) 35 | quickSort(data, pivotIndex+1, end) 36 | } 37 | } 38 | 39 | // QuickSort sorts data by quicksort algorithm 40 | // Time complexity : O(n log n) 41 | // Space Complexity : O(n) 42 | func QuickSort(data []int) { 43 | quickSort(data, 0, len(data)-1) 44 | } 45 | 46 | func main() { 47 | data := []int{1, 1122002, 2, 88171, 6754, 79901, 119856, -312, 1, -2} 48 | QuickSort(data) 49 | fmt.Println(data) 50 | } 51 | -------------------------------------------------------------------------------- /quick_sort/quick_sort.py: -------------------------------------------------------------------------------- 1 | def median(a, i, j, k): 2 | """ 3 | Return median of 3 integers from array a. 4 | :param a: Iterable of elements 5 | :param i: start element index 6 | :param j: end element index 7 | :param k: middle element index 8 | :return: return median of values at indices i, j and k. 9 | """ 10 | ai, aj, ak = a[i], a[j], a[k] 11 | med_val = ai + aj + ak - max(ai, aj, ak) - min(ai, aj, ak) 12 | if ai == med_val: 13 | return i 14 | elif aj == med_val: 15 | return j 16 | return k 17 | 18 | 19 | def partition(array, l, r): 20 | """ 21 | Perform Partition Operation on array. 22 | Time Complexity: Theta(nLogn) 23 | Auxiliary Space: O(n) 24 | :param array: Iterable of elements 25 | :param l: pivot value for array 26 | :param r: right limit of array 27 | :return: return q value for function, used in partitioning of array. 28 | """ 29 | i = l - 1 30 | pivot_index = median(array, l, r, (l+r) // 2) 31 | array[pivot_index], array[r] = array[r], array[pivot_index] 32 | pivot = array[r] 33 | for j in range(l, r): 34 | if array[j] <= pivot: 35 | i += 1 36 | array[i], array[j] = array[j], array[i] 37 | i += 1 38 | array[r], array[i] = array[i], array[r] 39 | return i 40 | 41 | 42 | def quick_sort(array, left, right): 43 | """ 44 | Perform sort using partition function. 45 | Time Complexity : O(nlog(n)). 46 | Space Complexity : O(n). 47 | :param array: Iterable of elements 48 | :param left: used as left limit of quick sort 49 | :param right: right limit for quick sort 50 | :return: no returns, sorts array 51 | """ 52 | if left < right: 53 | q = partition(array, left, right) 54 | quick_sort(array, left, q - 1) 55 | quick_sort(array, q + 1, right) 56 | 57 | 58 | def main(): 59 | a = [1, 2, 1, 2, 3, 1, 2, 2, 1] 60 | quick_sort(a, 0, len(a) - 1) 61 | print(a) 62 | 63 | 64 | if __name__ == '__main__': 65 | main() 66 | -------------------------------------------------------------------------------- /quick_sort/quicksort.c: -------------------------------------------------------------------------------- 1 | #include "stdio.h" 2 | 3 | /* 4 | * @ar_size array size 5 | * @ar array pointer 6 | */ 7 | void quicksort(int ar_size, int * ar) { 8 | int piv; 9 | piv = ar[ar_size-1]; // chose last element as pivot 10 | int i, temp, c = 0; 11 | int prevmax, prevind = -1; // stores last number >= pivot 12 | 13 | for (i=0; i -1) && (ar[i] < prevmax)){ 16 | // swap current and previous large element 17 | // current element is less than prevmax so move it to the left side 18 | // and prevmax to the right side 19 | temp = ar[i]; 20 | ar[i] = prevmax; 21 | ar[prevind] = temp; 22 | // prevind now has a less than pivot element, no need for it now 23 | // therefore increment it for the next number 24 | prevind = prevind + 1; 25 | prevmax = ar[prevind]; 26 | } 27 | c++; // pivot's final location (depends on count of items smaller than pivot) 28 | } 29 | else if (prevind < 0) { 30 | // init first larger than pivot element 31 | // it may be swapped out later (above block) 32 | prevmax = ar[i]; 33 | prevind = i; 34 | } 35 | } 36 | 37 | if (prevind > -1){ // if some swaps were done 38 | ar[ar_size-1] = ar[c]; 39 | ar[c] = piv; // swap pivot to its correct position 40 | } 41 | 42 | if (ar_size > 2){ 43 | if (c != 0) 44 | quicksort(c, &ar[0]); // recursively quicksort left partition 45 | if (ar_size-c-1 != 0) 46 | quicksort(ar_size-c-1, &ar[c+1]); // right partition 47 | } 48 | } 49 | 50 | int main() { 51 | int ar_size = 4, i; 52 | int a[4] = {2, 3, 0, 4}; 53 | quicksort(ar_size, a); 54 | 55 | for (i=0; i m) 20 | m = array[i]; 21 | } 22 | 23 | while(m / ex > 0) { 24 | 25 | int[] bucket = new int[10]; 26 | 27 | for(int i = 0; i < n; i++) 28 | bucket[(array[i] / ex) % 10]++; 29 | for(int i = 1; i < 10; i++) 30 | bucket[i] += bucket[i - 1]; 31 | for(int i = n - 1; i >= 0; i--) 32 | b[--bucket[(array[i] / ex) % 10]] = array[i]; 33 | 34 | for(int i = 0; i < n; i++) 35 | array[i] = b[i]; 36 | ex *= 10; 37 | } 38 | } 39 | 40 | public static void main(String args[]) { 41 | int test[] = new int[]{170, 45, 75, 90, 802, 24, 2, 6}; 42 | radixSort(test); 43 | 44 | for(int i: test) { 45 | System.out.print(i + " "); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /radix_sort/radix_sort.c: -------------------------------------------------------------------------------- 1 | #include "stdio.h" 2 | #include 3 | #include 4 | 5 | /* 6 | * Returns maximum number in an array 7 | * @a array pointer 8 | * @n number of elements in the array 9 | */ 10 | int max(int * a, int n) { 11 | int max = a[0]; 12 | for (int i = 1; i < n; i++) { 13 | if (a[i] > max) { 14 | max = a[i]; 15 | } 16 | } 17 | return max; 18 | } 19 | 20 | /* 21 | * Performs Radix Sort on a given array 22 | * @a array pointer 23 | * @n number of elements in the array 24 | */ 25 | void radix_sort(int * a, int n) { 26 | int m = max(a, n); 27 | int b[10] = {0}; 28 | 29 | for (int exp = 1; m / exp > 0; exp*=10) { 30 | int bucket[10] = {0}; 31 | 32 | for (int i = 0; i < n; i++) 33 | bucket[(a[i] / exp) % 10]++; 34 | for (int i = 1; i < n; i++) 35 | bucket[i] += bucket[i - 1]; 36 | for (int i = n - 1; i >= 0; i--) 37 | b[--bucket[(a[i] / exp) % 10]] = a[i]; 38 | 39 | for (int i = 0; i < n; i++) 40 | a[i] = b[i]; 41 | } 42 | } 43 | 44 | int main() { 45 | srand(time(NULL)); 46 | int n = 10; 47 | 48 | int test_array[n]; 49 | for (int i = 0; i < n; i++) { 50 | test_array[i] = rand() % 1000; 51 | } 52 | 53 | radix_sort(test_array, n); 54 | for (int i = 0; i < n; i++) { 55 | printf("%d ", test_array[i]); 56 | } 57 | printf("\n"); 58 | return 0; 59 | } 60 | -------------------------------------------------------------------------------- /radix_sort/radix_sort.cs: -------------------------------------------------------------------------------- 1 | // radix sort algorithm in c# uploaded by elliot37 2 | using System; 3 | class radix { 4 | static void Main(string[] args) { 5 | int[] arr = new int[]{23, 4, 2234, 3253, 46, 43, 1, 23, 45, 67}; 6 | Console.WriteLine("\ngiven array : "); 7 | foreach (var num in arr) { 8 | Console.Write(" " + num); 9 | } 10 | 11 | sorting(arr); 12 | Console.WriteLine("\nafter sorting : "); 13 | foreach (var num in arr) { 14 | Console.Write(" " + num); 15 | } 16 | Console.WriteLine("\n"); 17 | } 18 | 19 | static void sorting(int[] arr) { 20 | int i, j; 21 | int[] temp = new int[arr.Length]; 22 | for (int k = 31; k > -1; --k) { 23 | j = 0; 24 | for (i = 0; i < arr.Length; ++i) { 25 | bool t = (arr[i] << k) >= 0; 26 | if (k == 0 ? !t : t) 27 | arr[i - j] = arr[i]; 28 | else 29 | temp[j++] = arr[i]; 30 | } 31 | Array.Copy(temp, 0, arr, arr.Length - j, j); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /radix_sort/radix_sort.py: -------------------------------------------------------------------------------- 1 | # Following is the implementation of Radix Sort. 2 | 3 | 4 | def radix_sort(arr, radix=10): 5 | """ 6 | :param arr: Iterable of elements to sort. 7 | :param radix: Base of input numbers 8 | :return: Sorted list of input. 9 | Time complexity: O(d * (n + b)) 10 | where, n is the size of input list. 11 | b is base of representation. 12 | d is number of digits in largest number in that base. 13 | Space complexity: O(n + k) 14 | where, k is the range of input. 15 | """ 16 | max_length = False 17 | tmp, digit = -1, 1 18 | 19 | while not max_length: 20 | max_length = True 21 | # declare and initialize buckets 22 | buckets = [[] for _ in range(radix)] 23 | 24 | # split arr between lists 25 | for i in arr: 26 | tmp = i // digit 27 | buckets[tmp % radix].append(i) 28 | if max_length and tmp > 0: 29 | max_length = False 30 | 31 | # empty lists into arr array 32 | a = 0 33 | for b in range(radix): 34 | buck = buckets[b] 35 | for i in buck: 36 | arr[a] = i 37 | a += 1 38 | 39 | # move to next digit 40 | digit *= radix 41 | return arr 42 | 43 | 44 | def main(): 45 | """ 46 | Driver function to test radix sort. 47 | """ 48 | test = [170, 45, 75, 90, 802, 24, 2, 66] 49 | print('Sorted array:', radix_sort(test)) 50 | 51 | 52 | if __name__ == '__main__': 53 | main() 54 | -------------------------------------------------------------------------------- /rod_cutting_problem/RodCutting.java: -------------------------------------------------------------------------------- 1 | /* 2 | Problem Statement: Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n. 3 | Determine the maximum value obtainable by cutting up the rod and selling the pieces. 4 | 5 | Time Complexity: O(n^2) 6 | Space Complexity: O(n) 7 | */ 8 | 9 | public class RodCutting { 10 | 11 | public static int cutRod(int[] price) { 12 | int n = price.length; 13 | int[] best_price = new int[n+1]; 14 | best_price[0] = 0; 15 | for (int i = 1; i <= n; i++) { 16 | int tmax = Integer.MIN_VALUE; 17 | for (int j = 0; j < i; j++) 18 | tmax = Math.max(tmax, price[j] + best_price[i-j-1]); 19 | best_price[i] = tmax; 20 | } 21 | return best_price[n]; 22 | } 23 | 24 | public static void main(String[] args) { 25 | int[] price = new int[] {10, 52, 84, 93, 101, 17, 117, 20}; 26 | System.out.println("Maximum Obtainable Value is " + cutRod(price)); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /rod_cutting_problem/rodCuttingProblem.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Problem Statement: Given a rod of length n and an array of prices that contains prices of all pieces of size smaller than n. 3 | * Determine the maximum value obtainable by cutting up the rod and selling the pieces. 4 | */ 5 | 6 | function rodCuttingProblem (price) { 7 | /* 8 | Computes maximum money that can be earned by cutting a rod of length n (Bottom-Up Approach). 9 | Time Complexity : O(n ^ 2) 10 | Space Complexity : O(n) 11 | :param price: Array in which price[i] denotes price of rod of length i. 12 | :return: returns maximum value obtainable by cutting up the rod and selling the pieces. 13 | */ 14 | let n = price.length; 15 | let bestPrice = new Array(n + 1); 16 | bestPrice.fill(0); 17 | for (let i = 1; i < bestPrice.length; i++) { 18 | bestPrice[i] = price[i - 1]; 19 | } 20 | for (let i = 1; i <= n; i++) { 21 | let tmax = Number.MIN_SAFE_INTEGER; 22 | for (let j = 0; j < i; j++) { 23 | tmax = Math.max(tmax, bestPrice[i - j - 1] + price[j]); 24 | } 25 | bestPrice[i] = tmax; 26 | } 27 | return bestPrice[n]; 28 | } 29 | 30 | function main () { 31 | let price = [10, 52, 84, 93, 101, 17, 117, 20]; 32 | console.log('Maximum obtainable value is : ' + rodCuttingProblem(price)); 33 | } 34 | 35 | main(); 36 | -------------------------------------------------------------------------------- /rod_cutting_problem/rod_cutting.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Given a rod of length n and an array of prices that contains prices of all pieces of size smaller than n. 3 | * Determine the maximum new_prices obtainable by cutting up the rod and selling the pieces. 4 | * Time Complexity: O(n^2) 5 | * Space Complexity: O(n) 6 | */ 7 | 8 | #include 9 | #include 10 | 11 | #define max(a, b) (a > b) ? a : b; 12 | 13 | int rod_cutting(const int *prices) { 14 | unsigned int i, j; 15 | unsigned int n = sizeof(prices); 16 | int new_prices[n + 1]; 17 | memset(new_prices, 0, n + 1); 18 | for (i = 1; i < n + 1; ++i) { 19 | int maxi = -1; 20 | for (j = 0; j < i; ++j) { 21 | maxi = max(maxi, (prices[j] + new_prices[i - j - 1])); 22 | } 23 | new_prices[i] = maxi; 24 | } 25 | return new_prices[n]; 26 | } 27 | 28 | int main() { 29 | int prices[] = {10, 52, 84, 93, 101, 17, 117, 20}; 30 | printf("%d\n", rod_cutting(prices)); 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /rod_cutting_problem/rod_cutting.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | // RodCutting computes maximum money that can be earned by cutting a rod of length len(price) 6 | // Time Complexity : O((length^2) 7 | // Space Complexity : O(length) 8 | func RodCutting(price []int) int { 9 | length := len(price) 10 | optPrice := make([]int, length+1, length+1) 11 | for i := 1; i <= length; i++ { 12 | maxim := -1 13 | for j := 0; j < i; j++ { 14 | if maxim < price[j]+optPrice[i-j-1] { 15 | maxim = price[j] + optPrice[i-j-1] 16 | } 17 | } 18 | optPrice[i] = maxim 19 | } 20 | return optPrice[length] 21 | } 22 | 23 | func main() { 24 | price := []int{1, 5, 8, 9, 10, 17, 17, 20, 24, 30} 25 | fmt.Println(RodCutting(price)) 26 | } 27 | -------------------------------------------------------------------------------- /rod_cutting_problem/rod_cutting.py: -------------------------------------------------------------------------------- 1 | """ 2 | This module calculates optimized solution for rod cutting 3 | by function rod_cutting() with arguments as defined 4 | in main() 5 | """ 6 | 7 | 8 | def rod_cutting(price): 9 | """ 10 | Computes maximum money that can be earned by cutting 11 | a rod of length len(price) (Bottom-Up Approach). 12 | 13 | Time Complexity : O((len(price))^2) 14 | Space Complexity : O(len(price)) 15 | :param price: List in which price[i] denotes price of rod of length i. 16 | :return: returns optimal solution for rod of length len(price). 17 | """ 18 | length = len(price) 19 | opt_price = [0] * (length + 1) 20 | 21 | for i in range(1, length + 1): 22 | opt_price[i] = max( 23 | [-1] + [price[j] + opt_price[i - j - 1] for j in range(i)]) 24 | return opt_price[length] 25 | 26 | 27 | def main(): 28 | """ 29 | Main Function of this program. 30 | """ 31 | price = [1, 5, 8, 9, 10, 17, 17, 20, 24, 30] 32 | print(rod_cutting(price)) 33 | 34 | 35 | if __name__ == '__main__': 36 | main() 37 | -------------------------------------------------------------------------------- /shell_sort/ShellSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | // Use '-std=c++11' or higher flag while compiling 6 | // g++ -std=c++11 -o ShellSort ShellSort.cpp 7 | 8 | using namespace std; 9 | 10 | // Worst case time complexity = O(n^2) 11 | // Best case complexity = O(nlog(n)) 12 | 13 | vector shellSort(vector data) { 14 | for (int i = static_cast(data.size() / 2); i > 0; i /= 2) { 15 | for (int j = i; j < data.size(); ++j) { 16 | for (int k = j - i; k >= 0; k -= i) { 17 | if (data[k+i] >= data[k]) { 18 | break; 19 | } else { 20 | swap(data[k], data[k+i]); 21 | } 22 | } 23 | } 24 | } 25 | return data; 26 | } 27 | 28 | void print(vector data) { 29 | for (auto item : data) { 30 | cout << item << " "; 31 | } 32 | cout << '\n'; 33 | } 34 | 35 | int main() { 36 | vector data = {1000, 45, -45, 121, 47, 45, 65, 121, -1, 103, 45, 34}; 37 | cout << "Data to be sorted:" << '\n'; 38 | print(data); 39 | cout << "Sorted data:" << '\n'; 40 | data = shellSort(data); 41 | print(data); 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /shell_sort/ShellSort.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class ShellSort 4 | { 5 | public static void Main() 6 | { 7 | int[] data = new int[] {1000, 45, -45, 121, 47, 45, 65, 121, -1, 103, 45, 34}; 8 | Console.WriteLine("Data to be sorted:"); 9 | Print(data); 10 | Sort(data); 11 | Console.WriteLine("Sorted data:"); 12 | Print(data); 13 | } 14 | 15 | public static void Sort(int[] data) 16 | { 17 | for (int i = data.Length / 2; i > 0; i /= 2) 18 | { 19 | for (int j = i; j < data.Length; ++j) 20 | { 21 | for (int k = j - i; k >= 0; k -= i) 22 | { 23 | if (data[k+i] >= data[k]) 24 | { 25 | break; 26 | } 27 | else 28 | { 29 | int temp = data[k]; 30 | data[k] = data[k+i]; 31 | data[k+i] = temp; 32 | } 33 | } 34 | } 35 | } 36 | } 37 | 38 | public static void Print(int[] data) 39 | { 40 | foreach(int elem in data) 41 | { 42 | Console.Write(elem + " "); 43 | } 44 | Console.WriteLine(""); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /shell_sort/ShellSort.java: -------------------------------------------------------------------------------- 1 | public class ShellSort { 2 | /** 3 | * sorting function 4 | * Worst case time complexity = O(n^2) 5 | * Best case complexity = O(nlog(n)) 6 | * n is input size 7 | */ 8 | public static int[] shellSort(int[] data) { 9 | for (int i = data.length / 2; i > 0; i /= 2) { 10 | for (int j = i; j < data.length; ++j) { 11 | for (int k = j - i; k >= 0; k -= i) { 12 | if (data[k + i] >= data[k]) { 13 | break; 14 | } else { 15 | //swap the value 16 | int temp = data[k]; 17 | data[k] = data[k + i]; 18 | data[k + i] = temp; 19 | } 20 | } 21 | } 22 | } 23 | return data; 24 | } 25 | 26 | // print function 27 | public static void print(int[] data) { 28 | for (Integer item : data) { 29 | System.out.println(item); 30 | } 31 | } 32 | 33 | public static void main(String[] args) { 34 | int[] data = {1000, 45, -45, 121, 47, 45, 65, 121, -1, 103, 45, 34}; 35 | System.out.println("Data to be sorted:"); 36 | print(data); 37 | System.out.println("Sorted data:"); 38 | data = shellSort(data); 39 | print(data); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /shell_sort/shellSort.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Worst case time complexity = O(n^2) 3 | * Best case complexity = O(nlog(n)) 4 | * @param {Array} data 5 | * returns sorted data 6 | */ 7 | function shellSort (data) { 8 | let temp; 9 | for (let i = Math.floor(data.length / 2); i > 0; i = Math.floor(i / 2)) { 10 | for (let j = i; j < data.length; j++) { 11 | for (let k = j - i; k >= 0; k -= i) { 12 | if (data[k + i] >= data[k]) { 13 | break; 14 | } else { 15 | temp = data[k]; 16 | data[k] = data[k + i]; 17 | data[k + i] = temp; 18 | } 19 | } 20 | } 21 | } 22 | return data; 23 | } 24 | 25 | function main () { 26 | let data = [1000, 45, -45, 121, 47, 45, 65, 121, -1, 103, 45, 34]; 27 | console.log(shellSort(data)); 28 | } 29 | 30 | main(); 31 | -------------------------------------------------------------------------------- /shell_sort/shell_sort.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | // ShellSort function returns sorted data 6 | // Worst case time complexity = O(n^2) 7 | // Best case complexity = O(nlog(n)) 8 | func ShellSort(data []int) []int { 9 | for i := len(data) / 2; i > 0; i /= 2 { 10 | for j := i; j < len(data); j++ { 11 | for k := j - i; k >= 0; k -= i { 12 | if data[k+i] >= data[k] { 13 | break 14 | } else { 15 | data[k], data[k+i] = data[k+i], data[k] 16 | } 17 | } 18 | } 19 | } 20 | return data 21 | } 22 | 23 | func main() { 24 | data := []int{1000, 45, -45, 121, 47, 45, 65, 121, -1, 103, 45, 34} 25 | fmt.Println("Data to be sorted: ", data) 26 | data = ShellSort(data) 27 | fmt.Println("Sorted data:", data) 28 | } 29 | -------------------------------------------------------------------------------- /shell_sort/shell_sort.py: -------------------------------------------------------------------------------- 1 | def shell_sort(array): 2 | """ 3 | Sorts the given array of integers using the Shell Sort algorithm 4 | Time Complexity : O((len(array))^2) 5 | Space Complexity : O(len(array)) 6 | :param array: A List of integers. 7 | :return: returns the array sorted 8 | """ 9 | 10 | # calculate the gap using Knuth's formula 11 | gap = 1 12 | while gap < len(array) // 3: 13 | gap = (gap * 3) + 1 14 | 15 | while gap > 0: 16 | # using this gap, exchange elements while you can 17 | for idx in range(gap, len(array)): 18 | val_to_insert = array[idx] 19 | candidate_idx = idx 20 | 21 | # shift all bigger elements to the right, creating a hole 22 | while candidate_idx > gap - 1 and array[candidate_idx - gap] > val_to_insert: 23 | array[candidate_idx] = array[candidate_idx - gap] 24 | candidate_idx -= gap 25 | 26 | # insert our element at the hole 27 | array[candidate_idx] = val_to_insert 28 | 29 | # decrease gap, math alert 30 | gap = (gap - 1) // 3 31 | 32 | return array 33 | 34 | 35 | def main(): 36 | sample_arr = [1, -312, 4, 12, 3, 17, 2542, 20, 18] 37 | print(shell_sort(sample_arr)) 38 | 39 | 40 | if __name__ == '__main__': 41 | main() 42 | -------------------------------------------------------------------------------- /sieve_of_eratosthenes/SieveOfEratosthenes.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | *

This class represents a Sieve of Eratosthenes. It exposes an isPrime(int) method.

5 | * 6 | *

When creating a Sieve, you need to specify the max number that you might query.

7 | * 8 | *

Time complexity for creating the Sieve is O(n * n) but for querying is O(1). Space complexity is O(n)

9 | * 10 | * @see Sieve of Eratosthenes 11 | */ 12 | public class SieveOfEratosthenes { 13 | 14 | private boolean[] sieve; 15 | 16 | /** 17 | * Creates a sieve that can be queried for numbers up to maxNumber. 18 | * 19 | * @param maxNumber 20 | */ 21 | public SieveOfEratosthenes(final int maxNumber) { 22 | initSieve(maxNumber); 23 | crossMultiplesOfKnownPrimes(); 24 | } 25 | 26 | private void initSieve(int maxNumber) { 27 | this.sieve = new boolean[maxNumber + 1]; 28 | Arrays.fill(sieve, true); 29 | cross(0); 30 | cross(1); 31 | } 32 | 33 | /** 34 | * Iterates the sieve and when it finds a prime in it, it'll cross its multiples, since by definition those numbers are not prime. 35 | */ 36 | private void crossMultiplesOfKnownPrimes() { 37 | for (int n = 2; n * n < sieve.length; ++n) { 38 | if (isPrime(n)) { 39 | crossMultiplesOf(n); 40 | } 41 | } 42 | } 43 | 44 | /** 45 | * Given prime, crosses all multiples of prime in the sieve 46 | * 47 | * @param prime 48 | */ 49 | private void crossMultiplesOf(final int prime) { 50 | for (int n = prime * prime; n < sieve.length; n += prime) { 51 | cross(n); 52 | } 53 | } 54 | 55 | /** 56 | * Marks n as a non-prime in the sieve. 57 | * 58 | * @param n 59 | */ 60 | private void cross(final int n) { 61 | sieve[n] = false; 62 | } 63 | 64 | /** 65 | * Returns true if n is a prime number, false otherwise. 66 | * 67 | * @param n 68 | * @return 69 | */ 70 | public boolean isPrime(final int n) { 71 | return sieve[n]; 72 | } 73 | 74 | public static void main(String[] args) { 75 | int max = 100; 76 | SieveOfEratosthenes sieve = new SieveOfEratosthenes(max); 77 | for (int n = 0; n < 100; ++n) { 78 | if (sieve.isPrime(n)) { 79 | System.out.println(n); 80 | } 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /sieve_of_eratosthenes/sieveOfEratosthenes.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include // for using square root 4 | #include // to include bool datatype 5 | 6 | void sieveOfEratosthenes(int n, bool *primes) { 7 | int i, sqrtOfn = sqrt(n)+1, j; 8 | memset(primes, true, n+1); 9 | primes[0] = false; 10 | primes[1] = false; 11 | 12 | for (i = 2; i <= sqrtOfn; i++) { 13 | if (primes[i]) { 14 | for (j = 2*i; j < n+1; j += i) { 15 | primes[j] = false; 16 | } 17 | } 18 | } 19 | } 20 | 21 | int main() { 22 | int n, k; 23 | n = 100; 24 | bool primes[n+1]; 25 | sieveOfEratosthenes(n, primes); 26 | for (k = 2; k < n; k++) { 27 | if (primes[k]) { 28 | printf("%d ", k); 29 | } 30 | } 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /sieve_of_eratosthenes/sieveOfEratosthenes.js: -------------------------------------------------------------------------------- 1 | function sieveOfEratosthenes (n) { 2 | /* 3 | * Calculates prime numbers till a number n 4 | * :param n: Number upto which to calculate primes 5 | * :return: A boolean list contaning only primes 6 | */ 7 | let primes = new Array(n + 1); 8 | primes.fill(true); // set all as true initially 9 | primes[0] = primes[1] = false; // Handling case for 0 and 1 10 | let sqrtn = Math.ceil(Math.sqrt(n)); 11 | for (let i = 2; i <= sqrtn; i++) { 12 | if (primes[i]) { 13 | for (let j = 2 * i; j <= n; j += i) { 14 | primes[j] = false; 15 | } 16 | } 17 | } 18 | return primes; 19 | } 20 | 21 | function main () { 22 | let n = 319; // number till where we wish to find primes 23 | let primes = sieveOfEratosthenes(n); 24 | for (let i = 2; i <= n; i++) { 25 | if (primes[i]) { 26 | console.log(i); 27 | } 28 | } 29 | } 30 | 31 | main(); 32 | -------------------------------------------------------------------------------- /sieve_of_eratosthenes/sieve_of_eratosthenes.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | ) 7 | 8 | // SieveOfEratosthenes returns bool array primes 9 | func SieveOfEratosthenes(n int) []bool { 10 | primes := make([]bool, n+1) 11 | sqrtOfN := int(math.Floor(math.Sqrt(float64(n))) + 1) 12 | for j := range primes { 13 | primes[j] = true 14 | } 15 | for i := 2; i <= sqrtOfN; i++ { 16 | if primes[i] { 17 | for j := 2 * i; j < n+1; j += i { 18 | primes[j] = false 19 | } 20 | } 21 | } 22 | return primes 23 | } 24 | 25 | func main() { 26 | // Change the value of n to get all primes <= n 27 | n := 29 28 | primes := SieveOfEratosthenes(n) 29 | for i := 2; i <= n; i++ { 30 | if primes[i] { 31 | fmt.Println(i) 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /sieve_of_eratosthenes/sieve_of_eratosthenes.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | 4 | def sieve_of_eratosthenes(n): 5 | """ 6 | Calculates prime numbers till a number n 7 | :param n: Number upto which to calculate primes 8 | :return: A boolean list contaning only primes 9 | """ 10 | primes = [True] * (n + 1) # Setting all as True initially 11 | primes[0] = primes[1] = False # Since 0 and 1 are not primes 12 | sqrt_n = int(math.ceil(math.sqrt(n))) 13 | for i in range(2, sqrt_n, 1): 14 | if primes[i]: 15 | for j in range(2 * i, n + 1, i): 16 | primes[j] = False 17 | return primes 18 | 19 | 20 | def main(): 21 | n = 425 22 | primes = sieve_of_eratosthenes(n) 23 | for i in range(n + 1): # Printing primes 24 | if primes[i]: 25 | print(i) 26 | 27 | 28 | if __name__ == '__main__': 29 | main() 30 | -------------------------------------------------------------------------------- /sleep_sort/SleepSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Vector; 2 | 3 | /** 4 | * A Java implementation of sleep sort. 5 | * Time Complexity : O(max(input)) 6 | * (Will work for integers and not real numbers) 7 | */ 8 | public class SleepSort { 9 | private static final int DELAY_CONST = 25; 10 | 11 | public static void main(String[] args) { 12 | int[] data = new int[] { 9, 2, 3, 4, 0 }; 13 | sleepSort(data); 14 | for (int element : data) { 15 | System.out.println(element); 16 | } 17 | } 18 | 19 | private static void sleepSort(int[] data) { 20 | if (data.length == 0 || data.length == 0) 21 | return; 22 | SorterThread[] sorterThreads = new SorterThread[data.length]; 23 | Vector sortedList = new Vector<>(); 24 | for (int i = 0; i < sorterThreads.length; i++) { 25 | sorterThreads[i] = new SorterThread(data[i], sortedList); 26 | sorterThreads[i].start(); 27 | } 28 | while (sortedList.size() != data.length) { 29 | try { 30 | Thread.sleep(DELAY_CONST * DELAY_CONST); 31 | } catch (InterruptedException e) { 32 | e.printStackTrace(); 33 | } 34 | } 35 | for (int i = 0; i < data.length; i++) { 36 | data[i] = sortedList.get(i); 37 | } 38 | } 39 | 40 | private static class SorterThread extends Thread { 41 | private int sleepTimer; 42 | private Vector target; 43 | 44 | public SorterThread(int sleepTimer, Vector target) { 45 | this.sleepTimer = sleepTimer * DELAY_CONST; 46 | this.target = target; 47 | } 48 | 49 | public void run() { 50 | try { 51 | Thread.sleep(sleepTimer); 52 | } catch (Exception e) { 53 | } 54 | target.add(sleepTimer / DELAY_CONST); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /sleep_sort/sleep_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | /* 8 | * Function implementing sleep sort 9 | * args: 10 | * ar : Initial array containing elements (unsorted) 11 | * ans : sorted array elements vector 12 | * threads : vector containing threads for each array element 13 | * Time Complexity : O(max(input)) 14 | */ 15 | void sleep_sort(int ar[], vector &ans) { 16 | vector threads; 17 | for (int i = 0; i < 4; ++i) { 18 | threads.emplace_back([i, &ar, &ans]() { 19 | this_thread::sleep_for(chrono::seconds(ar[i])); 20 | ans.push_back(ar[i]); 21 | }); 22 | } 23 | 24 | for (auto& th : threads) { 25 | th.join(); 26 | } 27 | } 28 | 29 | /* 30 | * Driver function 31 | * For compilation of the code use -pthread 32 | * compilation looks like : g++ -std=c++11 sleep_sort.cpp -o sleep_sort -pthread 33 | */ 34 | int main() { 35 | int ar[] = {8, 4, 9, 1}; 36 | vector sorted; 37 | sleep_sort(ar, sorted); 38 | for (auto& item : sorted) { 39 | cout << item << endl; 40 | } 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /sleep_sort/sleep_sort.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | ) 7 | 8 | // SleepSort sorts an array using SleepSort algorithm 9 | func SleepSort(numbers []int) []int { 10 | channel := make(chan int, len(numbers)) 11 | 12 | for _, n := range numbers { 13 | go func(n int) { 14 | time.Sleep(time.Duration(n) * time.Second) 15 | channel <- n 16 | 17 | }(n) 18 | } 19 | 20 | // Get the result 21 | sorted := make([]int, len(numbers)) 22 | for i := 0; i < len(numbers); i++ { 23 | sorted[i] = <-channel 24 | } 25 | return sorted 26 | } 27 | 28 | func main() { 29 | sorted := SleepSort([]int{2, 3, 0, 4, 1}) 30 | fmt.Println(sorted) 31 | } 32 | -------------------------------------------------------------------------------- /sleep_sort/sleep_sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | Sleep sort is a proof of concept sorting algorithm that creates threads for 3 | each number in the sorting queue and sleeps for the amount of time before 4 | giving the result. 5 | 6 | It has no practical usage and doesn't works for negative numbers. Also for 7 | very close positive numbers, results are not guaranteed to be consistent. 8 | """ 9 | try: 10 | import queue 11 | except ImportError: 12 | import Queue as queue 13 | import threading 14 | import time 15 | 16 | 17 | def sleeper(number, sorted_numbers): 18 | """ 19 | Worker function for sleep sort's thread. 20 | :param number: Number for the thread 21 | :param sorted_numbers: Queue which contains the sorted numbers 22 | """ 23 | time.sleep(number) 24 | sorted_numbers.put(number) 25 | 26 | 27 | def sleep_sort(numbers, reverse=False): 28 | """ 29 | Sorts the numbers using sleep sort algorithm. 30 | :param numbers: Iterable object containing numbers 31 | :param reverse: Whether results need to be reverse 32 | :returns: A generator with sorted numbers 33 | """ 34 | threads = [] 35 | sorted_numbers = queue.LifoQueue() if reverse else queue.Queue() 36 | for number in numbers: 37 | thread = threading.Thread(target=sleeper, 38 | args=(number, sorted_numbers)) 39 | thread.start() 40 | threads.append(thread) 41 | for thread in threads: 42 | thread.join() 43 | while not sorted_numbers.empty(): 44 | yield sorted_numbers.get() 45 | 46 | 47 | def main(): 48 | numbers = [2, 3, 4, 1] 49 | print("Ascending order: ") 50 | for number in sleep_sort(numbers): 51 | print(number) 52 | print("Descending order: ") 53 | for number in sleep_sort(numbers, reverse=True): 54 | print(number) 55 | 56 | 57 | if __name__ == '__main__': 58 | main() 59 | -------------------------------------------------------------------------------- /stack/Stack.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Following implementation of Stack uses LinkedList 3 | * The last element of LinkedList is considered as the Top of Stack 4 | * T defines the type of Stack we wish to create 5 | */ 6 | 7 | import java.util.LinkedList; 8 | import java.util.NoSuchElementException; 9 | 10 | public class Stack { 11 | private LinkedList stack; 12 | 13 | public Stack() { // Constructor to create empty Stack 14 | stack = new LinkedList<>(); 15 | } 16 | 17 | public void push(T data) { // Add element to Top of Stack 18 | stack.addLast(data); 19 | } 20 | 21 | public T pop() throws NoSuchElementException { // Remove element from top of Stack 22 | return stack.removeLast(); 23 | } 24 | 25 | public static void main(String[] args) { 26 | Stack obj = new Stack<>(); 27 | System.out.println("Putting element in the stack."); 28 | for (int i = 1; i <= 10; i++) { 29 | obj.push(i); 30 | System.out.println("Pushed "+i); 31 | } 32 | System.out.println("\nPoping elements out of stack."); 33 | while(true) { // Remove the elements till stack is empty, 34 | try { 35 | Integer curr_element = obj.pop(); 36 | System.out.println("Popped " + curr_element); 37 | } 38 | catch(NoSuchElementException nsee) { 39 | System.out.println("Stack is empty now."); 40 | break; 41 | } 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /stack/stack.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | typedef struct stack { 5 | void *data; 6 | struct stack *next; 7 | } Stack; 8 | 9 | Stack *new_stack_node(void *data) { 10 | Stack *new_node = (Stack*) malloc(sizeof(Stack)); 11 | if (new_node == NULL) { 12 | return NULL; 13 | } 14 | new_node -> data = data; 15 | new_node -> next = NULL; 16 | return new_node; 17 | } 18 | 19 | int push(Stack **stack, void *data) { 20 | Stack *new_node = new_stack_node(data); 21 | if (new_node == NULL) { 22 | return 0; 23 | } 24 | new_node -> next = *stack; 25 | *stack = new_node; 26 | return 1; 27 | } 28 | 29 | void *pop(Stack **stack) { 30 | if (*stack == NULL) { 31 | return NULL; 32 | } 33 | Stack *temp = *stack; 34 | *stack = (*stack) -> next; 35 | temp -> next = NULL; 36 | void *data = temp -> data; 37 | free(temp); 38 | return data; 39 | } 40 | 41 | int main() { 42 | int a = 5; 43 | float b = 6.0; 44 | char c[] = "Hello World!"; 45 | Stack *st = NULL; 46 | push(&st, (void*) (&a)); 47 | push(&st, (void*) (&b)); 48 | push(&st, (void*) (c)); 49 | char *c_popped = (char*) pop(&st); 50 | float b_popped = *((float*) pop(&st)); 51 | int a_popped = *((int*) pop(&st)); 52 | printf("%d %f %s\n", a_popped, b_popped, c_popped); 53 | if (pop(&st) == NULL) { 54 | printf("Unable to pop from empty stack\n"); 55 | } 56 | return 0; 57 | } 58 | -------------------------------------------------------------------------------- /stack/stack.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | ) 7 | 8 | // Stack implements stack DS 9 | type Stack struct { 10 | list []int 11 | } 12 | 13 | // Push pushes to stack 14 | func (s *Stack) Push(data int) error { 15 | s.list = append(s.list, data) 16 | return nil 17 | } 18 | 19 | // Pop pops from stack 20 | func (s *Stack) Pop() (int, error) { 21 | if len(s.list) == 0 { 22 | return -1, errors.New("pop from empty stack") 23 | } 24 | last := s.list[len(s.list)-1] 25 | s.list = s.list[:len(s.list)-1] 26 | return last, nil 27 | } 28 | 29 | func main() { 30 | var s Stack 31 | s.Push(2) 32 | s.Push(3) 33 | s.Push(5) 34 | last, err := s.Pop() 35 | for err == nil { 36 | fmt.Println(last) 37 | last, err = s.Pop() 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /stack/stack.js: -------------------------------------------------------------------------------- 1 | class Stack { 2 | constructor (size = 0) { 3 | this._array = []; 4 | this._size = size; 5 | } 6 | 7 | push (argument) { 8 | if (this._size > 0 && this._array.length === this._size) { 9 | throw new Error('Unable to push to full stack'); 10 | } 11 | this._array.push(argument); 12 | } 13 | 14 | pop () { 15 | if (this._array.length === 0) { 16 | throw new Error('Unable to pop from empty stack'); 17 | } 18 | return this._array.pop(); 19 | } 20 | } 21 | 22 | function main () { 23 | let st = new Stack(); 24 | st.push('Hello World!'); 25 | st.push(1223); 26 | st.push('last one'); 27 | console.log(st.pop()); 28 | console.log(st.pop()); 29 | console.log(st.pop()); 30 | try { 31 | console.log(st.pop()); 32 | } catch (error) { 33 | console.log('Error: ' + error.message); 34 | } 35 | } 36 | 37 | main(); 38 | -------------------------------------------------------------------------------- /stack/stack.py: -------------------------------------------------------------------------------- 1 | class Stack(object): 2 | 3 | def __init__(self): 4 | self._list = [] 5 | 6 | def push(self, item): 7 | self._list.append(item) 8 | 9 | def pop(self): 10 | try: 11 | return self._list.pop() 12 | except IndexError: 13 | raise IndexError('pop from empty stack') 14 | 15 | 16 | def main(): 17 | st = Stack() 18 | # Push and print 19 | for i in range(10): 20 | st.push(i) 21 | print("Pushed ", i) 22 | st.push('Hello World') 23 | 24 | # Pop 25 | print(st.pop()) 26 | 27 | # Exceptions 28 | while True: # Empty the stack 29 | try: 30 | st.pop() 31 | except Exception as e: 32 | print('Exception: {0}'.format(e)) 33 | break 34 | 35 | 36 | if __name__ == '__main__': 37 | main() 38 | -------------------------------------------------------------------------------- /trie/Trie.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | class TrieNode 5 | { 6 | public char c; 7 | public Dictionary children; 8 | public bool isWord; 9 | 10 | public TrieNode() 11 | { 12 | children = new Dictionary(); 13 | } 14 | 15 | public TrieNode(char c) 16 | { 17 | this.c = c; 18 | children = new Dictionary(); 19 | } 20 | } 21 | 22 | public class Trie 23 | { 24 | private TrieNode root; 25 | 26 | public Trie() 27 | { 28 | root = new TrieNode(); 29 | } 30 | 31 | /// 32 | /// Inserts a word into the Trie 33 | /// Time Complexity: O(len(word)) 34 | /// 35 | /// The word to insert 36 | public void Insert(String word) 37 | { 38 | TrieNode curr = root; 39 | 40 | foreach (char c in word) 41 | { 42 | if (!curr.children.ContainsKey(c)) 43 | curr.children[c] = new TrieNode(c); 44 | 45 | curr = curr.children[c]; 46 | } 47 | 48 | curr.isWord = true; 49 | } 50 | 51 | /// 52 | /// Searches the trie for a word 53 | /// Time Complexity: O(len(word)) 54 | /// 55 | /// The word to search for 56 | /// True if the word was found, false otherwise 57 | public bool Search(String word) 58 | { 59 | TrieNode curr = root; 60 | 61 | foreach (char c in word) 62 | { 63 | if (!curr.children.ContainsKey(c)) 64 | return false; 65 | 66 | curr = curr.children[c]; 67 | } 68 | 69 | return curr.isWord; 70 | } 71 | 72 | public static void Main() 73 | { 74 | Trie dictionary = new Trie(); 75 | // Input keys words 76 | dictionary.Insert("the"); 77 | dictionary.Insert("a"); 78 | dictionary.Insert("there"); 79 | dictionary.Insert("answer"); 80 | dictionary.Insert("any"); 81 | dictionary.Insert("by"); 82 | dictionary.Insert("bye"); 83 | dictionary.Insert("their"); 84 | // Search for different keys words 85 | Console.WriteLine(dictionary.Search("the")); 86 | Console.WriteLine(dictionary.Search("these")); 87 | Console.WriteLine(dictionary.Search("thaw")); 88 | Console.WriteLine(dictionary.Search("their")); 89 | } 90 | } 91 | --------------------------------------------------------------------------------