├── .github ├── ISSUE_TEMPLATE │ ├── add-algorithm.md │ ├── add-documentation.md │ ├── bug_report.md │ ├── feature_request.md │ └── improve-an-algorithm.md └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── Bit Algorithms ├── Rotate Bits │ └── C++ │ │ └── rotate_bits.cpp └── Toggle Bits │ └── C++ │ └── toggle_bits.cpp ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── Data Structures ├── .gitkeep ├── BST │ └── Java │ │ ├── BST.java │ │ ├── BSTInterface.java │ │ ├── BSTTest.java │ │ └── Node.java ├── Heap │ └── C++ │ │ ├── BinaryHeap.cpp │ │ ├── BinaryHeap.hpp │ │ ├── BinaryHeapIntImpl.cpp │ │ ├── Exception.hpp │ │ ├── Heap.h │ │ ├── Test │ │ ├── Makefile │ │ └── test.cpp │ │ ├── heap.cpp │ │ └── main.cpp ├── Linked Lists │ ├── C++ │ │ └── linkedlist.cpp │ ├── Doubly-linked-list.png │ ├── Java │ │ ├── SinglyLinkedList.java │ │ └── doublylinkedlist.java │ ├── README.md │ └── Singly-linked-list.png ├── Queue │ └── C++ │ │ ├── CircularQueue │ │ ├── CircularQueue.cpp │ │ ├── CircularQueue.hpp │ │ └── CircularQueueIntImpl.cpp │ │ ├── StandardQueue │ │ ├── SimpleQueue.cpp │ │ ├── SimpleQueue.hpp │ │ └── SimpleQueueIntImpl.cpp │ │ ├── Test │ │ ├── Makefile │ │ └── test.cpp │ │ └── resources │ │ ├── Exceptions.hpp │ │ └── Queue.hpp └── Stack │ ├── C++ │ ├── Exceptions.hpp │ ├── Stack.hpp │ └── Test │ │ ├── Makefile │ │ ├── test │ │ └── test.cpp │ ├── Java │ └── Stack.java │ └── Python │ └── stack.py ├── Dynamic Programming ├── .gitkeep ├── EditDistance │ ├── Java │ │ └── EditDistance.java │ └── README.md ├── Fibonacci Sequence │ ├── Fibonacci_series.txt │ ├── Java │ │ └── Fibonacci.java │ └── README.md ├── Longest Increasing Subsequence │ ├── C++ │ │ └── LongestIncreasingSubsequence.cpp │ └── README.md ├── buy_sell_stocks │ ├── C++ │ │ └── buy_sell_stock_dp.cpp │ └── README.md ├── climb_stairs │ ├── C++ │ │ └── distinct_ways_to_climb_stairs.cpp │ └── README.md ├── coin_change_problem │ ├── C++ │ │ └── coin_change_problem.cpp │ └── README.md ├── jan-ken-puzzle │ └── python │ │ ├── puzzle_hash.py │ │ ├── test │ │ ├── heavy │ │ │ ├── 01.in │ │ │ ├── 02.in │ │ │ ├── 03.in │ │ │ ├── 04.in │ │ │ ├── 05.in │ │ │ ├── 06.in │ │ │ ├── 07.in │ │ │ ├── 08.in │ │ │ ├── 09.in │ │ │ ├── 10.in │ │ │ ├── results01 │ │ │ ├── results02 │ │ │ ├── results03 │ │ │ ├── results04 │ │ │ ├── results05 │ │ │ ├── results06 │ │ │ ├── results07 │ │ │ ├── results08 │ │ │ ├── results09 │ │ │ └── results10 │ │ └── light │ │ │ ├── 01.in │ │ │ ├── 02.in │ │ │ ├── 03.in │ │ │ ├── 04.in │ │ │ ├── 05.in │ │ │ ├── 06.in │ │ │ ├── 07.in │ │ │ ├── 08.in │ │ │ ├── 09.in │ │ │ ├── 10.in │ │ │ ├── results │ │ │ ├── results0 │ │ │ ├── results01 │ │ │ ├── results02 │ │ │ ├── results03 │ │ │ ├── results04 │ │ │ ├── results05 │ │ │ ├── results06 │ │ │ ├── results07 │ │ │ ├── results08 │ │ │ ├── results09 │ │ │ ├── results1 │ │ │ ├── results10 │ │ │ ├── results2 │ │ │ ├── results3 │ │ │ ├── results4 │ │ │ ├── results5 │ │ │ └── results6 │ │ ├── tests_heavy.sh │ │ └── tests_light.sh └── ways_to_decode │ ├── C++ │ └── dp_ways_to_decode.cpp │ └── README.md ├── Fibonacci_series.py ├── Graphs ├── .gitkeep ├── BFS │ ├── C++ │ │ └── BFS.cpp │ └── Python │ │ └── bfs.py ├── DFS │ ├── C++ │ │ └── DFS.cpp │ └── Python │ │ └── dfs.py ├── c++ │ └── bellman_ford.cpp └── cpp │ └── dijkstra_shortest_path.cpp ├── Greedy └── .gitkeep ├── JS Design Patterns └── singleton.js ├── Java Design Patterns ├── .gitkeep ├── AbstractFactory │ ├── App.java │ ├── FactoryCar.java │ ├── GMCFactory.java │ ├── Minivan.java │ ├── Pickup.java │ ├── Savana.java │ ├── Sienna.java │ ├── Sierra.java │ ├── Tacoma.java │ ├── ToyotaFactory.java │ └── readme.md ├── DAO │ ├── DaoPatternDemo.java │ ├── README.md │ ├── Student.java │ ├── StudentDao.java │ └── StudentDaoImpl.java ├── Singleton │ ├── README.md │ └── Singleton.java └── builder │ ├── README.md │ └── builder.java ├── LICENSE ├── LL.java ├── Machine Learning ├── .gitkeep └── Gradient Descent │ ├── C++ │ ├── SimpleGradientDescent.cpp │ └── Utility.h │ └── README.md ├── Maths ├── Euclidean Algorithm │ ├── C++ │ │ └── GCD.cpp │ ├── C │ │ └── GCD.c │ ├── Java │ │ └── GCD.java │ ├── Python │ │ └── GCD.py │ └── README.md ├── Factorial │ ├── C# │ │ └── Factorial.cs │ ├── C++ │ │ └── factorial.cpp │ ├── C │ │ └── factorial.c │ ├── Java │ │ └── Factorial.java │ ├── Python │ │ └── factorial.py │ └── README.md └── Fibonacci │ ├── C++ │ └── Fibonacci.cpp │ └── Python │ ├── Fibonacci_series.txt │ └── fibonacci.py ├── README.md ├── Searching ├── .gitkeep ├── Binary Search │ ├── C++ │ │ └── BinarySearch.cpp │ ├── C │ │ └── BinarySearch.c │ ├── Java │ │ └── BinarySearch.java │ ├── Javascript │ │ └── BinarySearch.js │ ├── Kotlin │ │ └── BinarySearch.kt │ ├── PHP │ │ └── BinarySearch.php │ ├── Python │ │ └── BinarySearch.py │ └── README.md └── Linear Search │ ├── C++ │ └── LinearSearch.cpp │ ├── C │ └── LinearSearch.c │ ├── Java │ └── LinearSearch.java │ ├── Javascript │ └── LinearSearch.js │ ├── Python │ └── LinearSearch.py │ └── README.md ├── Sorting ├── Bubble Sort │ ├── C# │ │ └── BubbleSort.cs │ ├── C++ │ │ └── BubbleSort.cpp │ ├── C │ │ └── BubbleSort.c │ ├── Go │ │ └── BubbleSort.go │ ├── Java │ │ └── BubbleSort.java │ ├── JavaScript │ │ └── BubbleSort.js │ └── Python │ │ └── bubblesort ├── Counting Sort │ └── Java │ │ └── CountingSort.java ├── Heap Sort │ ├── C++ │ │ └── HeapSort.cpp │ ├── HeapSort.java │ ├── JavaScript │ │ └── HeapSort.js │ ├── Python │ │ └── HeapSort.py │ └── Readme.md ├── Insertion Sort │ ├── C++ │ │ └── InsertionSort.cpp │ ├── Java │ │ └── InsertionSort.java │ ├── Python │ │ └── insertion_sort.py │ ├── README.md │ ├── Racket │ │ └── InsertionSort.rkt │ └── Scala │ │ └── InsertionSort.scala ├── Merge Sort │ ├── C++ │ │ ├── Arrays │ │ │ ├── MergeSortArray.cpp │ │ │ ├── MergeSortArray.h │ │ │ └── MergeSortArrayTest.cpp │ │ ├── Linked Lists │ │ │ ├── MergeSortLinkedList.cpp │ │ │ ├── MergeSortLinkedList.h │ │ │ └── MergeSortLinkedListTest.cpp │ │ └── MergeSortArray.cpp │ └── Java │ │ └── MergeSort.java ├── Quick Sort │ ├── C++ │ │ └── QuickSort.cpp │ ├── Java │ │ └── QuickSort.java │ ├── Python │ │ └── quickSortPython │ └── Readme.md ├── QuickSort.java ├── Radix Sort │ └── C │ │ └── RadixSort.cpp └── Selection Sort │ ├── C++ │ ├── SelectionSort │ └── SelectionSort.cpp │ ├── Java │ └── SelectionSort.java │ ├── JavaScript │ └── SelectionSort.js │ ├── Python │ └── selectionSortPython │ ├── README.md │ └── python │ └── selection_sort.py ├── String Manipulation ├── .gitkeep └── Knuth-Morris-Pratt │ ├── C++ │ └── KMP.cpp │ └── README.md ├── heap in java └── runme.bh /.github/ISSUE_TEMPLATE/add-algorithm.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Add Algorithm 3 | about: Add an algorithm to the repository 4 | 5 | --- 6 | 7 | Please search if an issue has already be placed before adding another issue. 8 | 9 | If you want to add an algorithm to the repository. 10 | Please include the following in the issue. 11 | 12 | ## Title: 13 | Algorithm (Language) 14 | 15 | ## Body: 16 | Include the specific variant of the algorithm you want to add. 17 | 18 | 19 | Are you working on this? - **Yes/No** 20 | (**If you are going to work on the issue yourself, make sure you comment on the issue to let others know.** 21 | We do not want multiple people to be working in the same issue without notice.) 22 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/add-documentation.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Add Documentation 3 | about: Add documentation for an algorithm 4 | 5 | --- 6 | 7 | Please search if an issue has already be placed before adding another issue. 8 | 9 | If you want to add an algorithm to the repository. 10 | Please include the following in the issue. 11 | 12 | ## Title: 13 | Documentation of Algorithm 14 | 15 | Are you working on this? - **Yes/No** 16 | (**If you are going to work on the issue yourself, make sure you comment on the issue to let others know.** 17 | We do not want multiple people to be working in the same issue without notice.) 18 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | 5 | --- 6 | 7 | **Describe the bug** 8 | A clear and concise description of what the bug is. 9 | 10 | **To Reproduce** 11 | Steps to reproduce the behavior: 12 | 1. Go to '...' 13 | 2. Click on '....' 14 | 3. Scroll down to '....' 15 | 4. See error 16 | 17 | **Expected behavior** 18 | A clear and concise description of what you expected to happen. 19 | 20 | **Screenshots** 21 | If applicable, add screenshots to help explain your problem. 22 | 23 | **Desktop (please complete the following information):** 24 | - OS: [e.g. iOS] 25 | - Browser [e.g. chrome, safari] 26 | - Version [e.g. 22] 27 | 28 | **Smartphone (please complete the following information):** 29 | - Device: [e.g. iPhone6] 30 | - OS: [e.g. iOS8.1] 31 | - Browser [e.g. stock browser, safari] 32 | - Version [e.g. 22] 33 | 34 | **Additional context** 35 | Add any other context about the problem here. 36 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | 5 | --- 6 | 7 | **Is your feature request related to a problem? Please describe.** 8 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 9 | 10 | **Describe the solution you'd like** 11 | A clear and concise description of what you want to happen. 12 | 13 | **Describe alternatives you've considered** 14 | A clear and concise description of any alternative solutions or features you've considered. 15 | 16 | **Additional context** 17 | Add any other context or screenshots about the feature request here. 18 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/improve-an-algorithm.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Improve an algorithm 3 | about: Improve an existing algorithm 4 | 5 | --- 6 | 7 | Please search if an issue has already be placed before adding another issue. 8 | 9 | If you want to improve an algorithm in the repository. 10 | Please include the following in the issue. 11 | 12 | ## Title: 13 | Algorithm (Language) 14 | 15 | ##Body: 16 | Why was wrong with the algorithm. How you plan to improve it. 17 | 18 | *If you are going to work on the issue yourself, make sure you comment on the issue to let others know.* 19 | We do not want multiple people to be working in the same issue without notice. 20 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | IMPORTANT: Please do not create a Pull Request without creating an issue first. 2 | 3 | Any change needs to be discussed before proceeding. 4 | 5 | ## Description 6 | Please describe what changes you have made. 7 | 8 | For Example: 9 | 10 | * Added a file(s) named '...' that implements '...'. 11 | 12 | * Changed the algorithm for performance/readablity/bugs. 13 | 14 | * Added documentation to the algorithm 15 | 16 | 17 | ## Related Issue 18 | 19 | This project only accepts pull requests related to open issues. 20 | 21 | If suggesting a new feature or change, please discuss it in an issue first. 22 | 23 | If fixing a bug, there should be an issue describing it with steps to reproduce. 24 | 25 | Please link to the issue here: 26 | 27 | ## How Has This Been Tested? (Optional) 28 | 29 | Please describe in detail how you tested your changes. 30 | You can skip this if you have not added any tests. 31 | 32 | ## Screenshots (Optional) 33 | 34 | ## Types of changes 35 | 36 | What types of changes does your code introduce? Put an `x` in all the boxes that apply: 37 | 38 | - [ ] Bug fix (change which fixes an issue with the algorithm) 39 | 40 | - [ ] New Algorithm (non-breaking change which adds functionality) 41 | 42 | - [ ] Documentation 43 | 44 | ## Checklist: 45 | Go over all the following points, and put an `x` in all the boxes that apply. 46 | 47 | If you're unsure about any of these, don't hesitate to ask. We're here to help! 48 | 49 | - [ ] My code follows the code style of this project. 50 | 51 | - [ ] My change requires a change to the documentation. 52 | 53 | - [ ] I have updated the documentation accordingly. 54 | 55 | - [ ] I have read the **CONTRIBUTING** document. 56 | 57 | -------------------------------------------------------------------------------- /Bit Algorithms/Rotate Bits/C++/rotate_bits.cpp: -------------------------------------------------------------------------------- 1 | //Do Left and Right rotate given the number n and the shift-by value d 2 | //Number is n 3 | //The number of bits by which n should be rotated is given by d 4 | //Both rotate right and rotate left is provided 5 | //32 bit frame is taken 6 | 7 | #include 8 | #include 9 | using namespace std; 10 | #define MAX 32 11 | int bit_rright(int n, int l) 12 | { 13 | int a = n<<(MAX-l); 14 | int b = n>>l; 15 | return (a|b); 16 | } 17 | int bit_rleft(int n , int l) 18 | { 19 | int a = n<>(MAX-l); 21 | return (a|b); 22 | } 23 | 24 | int main() 25 | { 26 | int n,d; 27 | cin>>n>>d; 28 | int x=bit_rright(n,d); 29 | int y = bit_rleft(n,d); 30 | cout< 110010 3 | // l = 2 4 | // r = 5 5 | // Result -> 101100 = 44 6 | 7 | #include 8 | #include 9 | using namespace std; 10 | 11 | int toggle(int n , int l , int r) 12 | { 13 | int c=0; 14 | int b=1; //For a new num, set bits between l to r 15 | b = b<<(l-1); 16 | for(int i=0;i>n>>l>>r; 29 | int x = toggle(n,l,r); 30 | cout< { 10 | /** 11 | * Search an element in a binary search tree structure 12 | * @return Node with element 13 | * */ 14 | public Node search(T element); 15 | /** 16 | * Insert an element in a binary search tree 17 | * @param element 18 | * */ 19 | public void insert(T element); 20 | /** 21 | * Remove an element in a binary search tree 22 | * */ 23 | public void remove(T element); 24 | /** 25 | * Get node with the predecessor of data element 26 | * @return Node with predecessor 27 | * */ 28 | public Node predecessor(T element); 29 | /** 30 | * Get node with the sucessor of data element 31 | * @return Node with sucessor 32 | * */ 33 | public Node sucessor(T element); 34 | /** 35 | * Return Root Node 36 | * @return Node root 37 | * */ 38 | public Node getRoot(); 39 | /** 40 | * Return True if binary search tree is empty or False if not 41 | * */ 42 | public boolean isEmpty(); 43 | /** 44 | * Return node with maximum data value in binary search tree 45 | * @return Node maximum 46 | * */ 47 | public Node maximum(); 48 | /** 49 | * Return node with minimum data value in binary search tree 50 | * @return minimum 51 | * */ 52 | public Node minimum(); 53 | /** 54 | * Return array with bst elements in order(left , root, right) 55 | * @return Ordered array 56 | * */ 57 | public T[] toArrayOrder(); 58 | /** 59 | * Return array with bst elements in pre order(root,left,right) 60 | * @return Pre Order array 61 | * */ 62 | public T[] toArrayPreOrder(); 63 | /** 64 | * Return array with bst elements in post order(left,right,root) 65 | * @return Post Order array 66 | * */ 67 | public T[] toArrayPostOrder(); 68 | /** 69 | * Return number of elements in Binary Search Tree 70 | * @return size 71 | * */ 72 | public int size(); 73 | /** 74 | * Return max height of Binary Search Tree 75 | * @return height 76 | * */ 77 | public int height(); 78 | 79 | } 80 | -------------------------------------------------------------------------------- /Data Structures/BST/Java/Node.java: -------------------------------------------------------------------------------- 1 | package BST; 2 | /** 3 | * @author Ionesio Junior 4 | * */ 5 | 6 | /** 7 | * Node Class for Binary Search Tree Implementation 8 | */ 9 | public class Node { 10 | //Attributes 11 | private T data; 12 | private Node left; 13 | private Node right; 14 | private Node parent; 15 | /** 16 | * Node Constructor (Empty) 17 | * */ 18 | public Node(){ 19 | 20 | } 21 | /** 22 | * Node Constructor 23 | * @param element 24 | * @param left Node 25 | * @param right Node 26 | * @param parent Node 27 | * */ 28 | public Node(T element,Node left,Node right,Node parent){ 29 | this.data = data; 30 | this.left = left; 31 | this.right = right; 32 | this.parent = parent; 33 | } 34 | /** 35 | * Return true if data is null or false if not 36 | * @return boolean 37 | * */ 38 | public boolean isNIL(){ 39 | return this.data == null; 40 | } 41 | /** 42 | * Return true if this node is a bst leaf or false if not 43 | * @return boolean 44 | * */ 45 | public boolean isLeaf(){ 46 | return (this.left.data == null && this.right.data == null); 47 | } 48 | /** 49 | * Return data 50 | * @return data 51 | * */ 52 | public T getData(){ 53 | return this.data; 54 | } 55 | /** 56 | * Return left Node 57 | * @return Node 58 | * */ 59 | public Node getLeft(){ 60 | return this.left; 61 | } 62 | /** 63 | * Return right Node 64 | * @return Node 65 | * */ 66 | public Node getRight(){ 67 | return this.right; 68 | } 69 | /** 70 | * Return parent Node 71 | * @return Node 72 | * */ 73 | public Node getParent(){ 74 | return this.parent; 75 | } 76 | /** 77 | * Set data value 78 | * @param value 79 | * */ 80 | public void setData(T element){ 81 | this.data = element; 82 | } 83 | /** 84 | * Set left node 85 | * @param value 86 | * */ 87 | public void setLeft(Node newLeft){ 88 | this.left = newLeft; 89 | } 90 | /** 91 | * Set right node 92 | * @param value 93 | * */ 94 | public void setRight(Node newRight){ 95 | this.right = newRight; 96 | } 97 | /** 98 | * Set parent node 99 | * @param value 100 | * */ 101 | public void setParent(Node newParent){ 102 | this.parent = newParent; 103 | } 104 | 105 | public boolean equals(Object obj) { 106 | boolean resp = false; 107 | if (obj instanceof Node) { 108 | if (!this.isNIL() && !((Node) obj).isNIL()) { 109 | resp = this.data.equals(((Node) obj).data); 110 | } else { 111 | resp = this.isNIL() && ((Node) obj).isNIL(); 112 | } 113 | 114 | } 115 | return resp; 116 | } 117 | } -------------------------------------------------------------------------------- /Data Structures/Heap/C++/BinaryHeap.hpp: -------------------------------------------------------------------------------- 1 | #ifndef _HEAP_H_ 2 | #define _HEAP_H_ 3 | 4 | /* 5 | *@author Ionésio Junior 6 | */ 7 | 8 | #include 9 | #include 10 | #include "Exception.hpp" 11 | 12 | /* Auxiliar array structure implementation 13 | * 14 | */ 15 | template 16 | struct Array{ 17 | int size; 18 | T *ptr; 19 | bool operator==(Array &other){ 20 | if(this->size != other.size){ 21 | return false; 22 | }else{ 23 | for(int i = 0; i < this->size;i++){ 24 | if(this->ptr[i] != other.ptr[i]){ 25 | return false; 26 | } 27 | } 28 | return true; 29 | } 30 | } 31 | 32 | T operator[](int index){ 33 | return this->ptr[index]; 34 | } 35 | 36 | bool operator!=(Array other){ 37 | return !(*this == other); 38 | } 39 | 40 | Array(int length){ 41 | this->size = length; 42 | this->ptr = (T*) calloc(this->size,sizeof(T)); 43 | } 44 | }; 45 | 46 | /* 47 | * Binary Heap class 48 | */ 49 | template 50 | class BinaryHeap{ 51 | private: 52 | HeapUnderflowException underflow; 53 | Array *array; 54 | int index; 55 | int parent(int index); 56 | int left(int index); 57 | int right(int index); 58 | void heapify(int index); 59 | void responsiveArray(); 60 | public: 61 | BinaryHeap(int size); 62 | bool isEmpty(); 63 | bool isFull(); 64 | void insert(T element); 65 | T extractRoot(); 66 | T* rootElement(); 67 | Array heapSort(T inputArray[],int size); 68 | Array toArray(); 69 | void buildHeap(T inputArray[],int size); 70 | int size(); 71 | }; 72 | 73 | #endif 74 | -------------------------------------------------------------------------------- /Data Structures/Heap/C++/BinaryHeapIntImpl.cpp: -------------------------------------------------------------------------------- 1 | #include "BinaryHeap.cpp" 2 | 3 | template class BinaryHeap; 4 | -------------------------------------------------------------------------------- /Data Structures/Heap/C++/Exception.hpp: -------------------------------------------------------------------------------- 1 | #ifndef _HEAPEXCEPTION_H_ 2 | #define _HEAPEXCEPTION_H_ 3 | 4 | #include 5 | /* 6 | * @author : Ionesio Junior 7 | */ 8 | class HeapUnderflowException : public std::exception{ 9 | virtual const char* what() const throw(){ 10 | return "Heap is Empty!!"; 11 | } 12 | }; 13 | 14 | #endif 15 | -------------------------------------------------------------------------------- /Data Structures/Heap/C++/Heap.h: -------------------------------------------------------------------------------- 1 | 2 | #ifndef MAXHEAP_H 3 | #define MAXHEAP_H 4 | 5 | void swap(int *x, int *y); 6 | 7 | class Maxheap 8 | { 9 | int *arr; 10 | int capacity; 11 | int heap_size; 12 | public: 13 | 14 | Maxheap(int capacity); 15 | 16 | 17 | void Maxheapify(int ); 18 | 19 | int parent(int i) { return (i-1)/2; } 20 | 21 | 22 | int left(int i) { return (2*i + 1); } 23 | 24 | 25 | int right(int i) { return (2*i + 2); } 26 | 27 | 28 | int extractMax(); 29 | 30 | 31 | void increaseKey(int i, int new_val); 32 | 33 | 34 | int getMax() { return arr[0]; } 35 | 36 | 37 | void deleteKey(int i); 38 | 39 | 40 | void insertKey(int k); 41 | }; 42 | 43 | #endif 44 | -------------------------------------------------------------------------------- /Data Structures/Heap/C++/Test/Makefile: -------------------------------------------------------------------------------- 1 | LIB = -L/usr/lib/x86_64-linux-gnu/ 2 | LIBS = -lboost_unit_test_framework 3 | 4 | all: Test 5 | 6 | ../BinaryHeapIntImpl.o : ../BinaryHeap.cpp ../BinaryHeap.hpp ../BinaryHeapIntImpl.cpp 7 | g++ -c ../BinaryHeapIntImpl.cpp -o ../BinaryHeap.o 8 | 9 | Test: ../BinaryHeapIntImpl.o 10 | g++ ../BinaryHeap.o test.cpp -o test $(LIB) $(LIBS) -std=c++14 11 | 12 | clean: 13 | rm test 14 | rm ../BinaryHeap.o 15 | -------------------------------------------------------------------------------- /Data Structures/Heap/C++/heap.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "Heap.h" 4 | 5 | Maxheap::Maxheap(int capacity) 6 | { 7 | heap_size = 0; 8 | capacity = capacity; 9 | arr = new int[capacity]; 10 | } 11 | 12 | 13 | void Maxheap::insertKey(int k) 14 | { 15 | if (heap_size == capacity) 16 | { 17 | std :: cout << "\nOverflow: Could not insertKey\n"; 18 | return; 19 | } 20 | 21 | 22 | heap_size++; 23 | int i = heap_size - 1; 24 | arr[i] = k; 25 | 26 | 27 | while (i != 0 && arr[parent(i)] < arr[i]) 28 | { 29 | swap(&arr[i], &arr[parent(i)]); 30 | i = parent(i); 31 | } 32 | } 33 | 34 | void Maxheap::increaseKey(int i, int new_val) 35 | { 36 | arr[i] = new_val; 37 | while (i != 0 && arr[parent(i)] < arr[i]) 38 | { 39 | swap(&arr[i], &arr[parent(i)]); 40 | i = parent(i); 41 | } 42 | } 43 | 44 | int Maxheap::extractMax() 45 | { 46 | if (heap_size <= 0) 47 | return INT_MIN; 48 | if (heap_size == 1) 49 | { 50 | heap_size--; 51 | return arr[0]; 52 | } 53 | 54 | 55 | int root = arr[0]; 56 | arr[0] = arr[heap_size-1]; 57 | heap_size--; 58 | Maxheapify(0); 59 | 60 | return root; 61 | } 62 | 63 | 64 | 65 | void Maxheap::deleteKey(int i) 66 | { 67 | increaseKey(i, INT_MAX); 68 | extractMax(); 69 | } 70 | 71 | void Maxheap::Maxheapify(int i) 72 | { 73 | int l = left(i); 74 | int r = right(i); 75 | int largest = i; 76 | if (l < heap_size && arr[l] > arr[i]) 77 | largest = l; 78 | if (r < heap_size && arr[r] > arr[largest]) 79 | largest = r; 80 | if (largest != i) 81 | { 82 | swap(&arr[i], &arr[largest]); 83 | Maxheapify(largest); 84 | } 85 | } 86 | 87 | 88 | void swap(int *x, int *y) 89 | { 90 | int temp = *x; 91 | *x = *y; 92 | *y = temp; 93 | } -------------------------------------------------------------------------------- /Data Structures/Heap/C++/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "Heap.h" 4 | 5 | int main() 6 | { 7 | Maxheap h(13); 8 | h.insertKey(4); 9 | h.insertKey(3); 10 | h.deleteKey(2); 11 | h.insertKey(16); 12 | h.insertKey(6); 13 | h.insertKey(5); 14 | h.insertKey(46); 15 | std :: cout << h.extractMax() << " "; 16 | std :: cout << h.getMax() << " "; 17 | h.increaseKey(2, 7); 18 | std :: cout << h.getMax(); 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /Data Structures/Linked Lists/C++/linkedlist.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int l; 5 | void FindLocation(); 6 | struct student{ 7 | int data; 8 | student* link; 9 | } *start,*loc,*ptr1; 10 | 11 | void insertion_begin(int y){ 12 | student* temp=new student(); 13 | temp->data=y; 14 | temp->link=start; 15 | start=temp; 16 | } 17 | void insertion_end(int y){ 18 | student* temp=new student(); 19 | temp->data=y; 20 | if(start==NULL){ 21 | temp->link=NULL; 22 | start=temp; 23 | } 24 | else{ 25 | student* ptr=start; 26 | while(ptr->link!=NULL) 27 | ptr=ptr->link; 28 | temp->link=NULL; 29 | ptr->link=temp; 30 | } 31 | } 32 | void insertion_after(int y){ 33 | 34 | student* temp=new student(); 35 | temp->data=y; 36 | cout<>l; 38 | FindLocation(); 39 | 40 | if(loc==NULL){ 41 | temp->link=start; 42 | start=temp; 43 | } 44 | else{ 45 | temp->link=loc->link; 46 | loc->link=temp; 47 | } 48 | } 49 | void insertion_at(){ 50 | int a,count=1,item; 51 | cout<<"enter the location at which data to be inserted: "; 52 | cin>>a; 53 | cout<>item; 55 | student* temp=new student(); 56 | student* ptr=start; 57 | while(ptr->link!=NULL){ 58 | if(count==a){ 59 | temp->data=item; 60 | temp->link=ptr->link; 61 | ptr->link=temp; 62 | } 63 | else{ 64 | count++; 65 | ptr=ptr->link; 66 | 67 | } 68 | } 69 | 70 | } 71 | void FindLocation(){ 72 | ptr1=start; 73 | while(ptr1!=NULL){ 74 | if(ptr1->data==l){ 75 | loc=ptr1; 76 | return; 77 | } 78 | else 79 | ptr1=ptr1->link; 80 | } 81 | loc=NULL; 82 | 83 | } 84 | void display() 85 | { 86 | student* temp=start; 87 | while(temp!=NULL){ 88 | cout<data<<" "; 89 | temp=temp->link; 90 | } 91 | cout<>k; 107 | switch(k) 108 | { 109 | case 1: cout<>n; 111 | cout<<"enter the number:"; 112 | for(i=0;i>x; 114 | insertion_begin(x); 115 | } 116 | break; 117 | case 2: cout<>n; 119 | cout<<"enter the number:"; 120 | for(i=0;i>x; 122 | insertion_end(x); 123 | } 124 | break; 125 | case 3: cout<<"enter the element to be inserted: "; 126 | cin>>m; 127 | insertion_after(m); 128 | break; 129 | case 4: insertion_at(); 130 | break; 131 | case 5: display(); 132 | break; 133 | case 6: return(0); 134 | default: cout<<"incorrect choice"< 8 | CircularQueue::CircularQueue(int size){ 9 | this->head_ptr = (T*) calloc(size,sizeof(T)); 10 | this->head_index = -1; 11 | this->tail = -1; 12 | this->elements = 0; 13 | this->size = size; 14 | } 15 | 16 | 17 | /* 18 | * Insert a new element in tail of the queue or throw an exception if queue is full. 19 | * Complexity : O(1) 20 | * @param element 21 | * @throw QueueOverflowException 22 | */ 23 | template 24 | void CircularQueue::enqueue(T element){ 25 | if(this->isFull()){ 26 | throw this->overflow; 27 | } 28 | this->elements++; 29 | if(this->head_index == -1 && this->tail == -1){ 30 | this->head_index = (this->head_index + 1 ) % this->size; 31 | } 32 | this->tail = (this->tail + 1 ) % this->size; 33 | this->head_ptr[this->tail] = element; 34 | } 35 | 36 | /* 37 | 38 | * Remove head element of the queue or throw an exception if queue is empty 39 | * Complexity : O(1) 40 | * @return element 41 | * @throw QueueUnderflowException 42 | */ 43 | template 44 | T* CircularQueue::dequeue(){ 45 | if(this->isEmpty()){ 46 | throw this->underflow; 47 | } 48 | this->elements--; 49 | T* aux = &this->head_ptr[this->head_index]; 50 | this->head_index = (this->head_index + 1) % size; 51 | return aux; 52 | } 53 | 54 | 55 | /* 56 | * Return element in the head of the queue without remove, or NULL if queue is empty. 57 | * Complexity: O(1) 58 | * @return element 59 | */ 60 | template 61 | T* CircularQueue::head(){ 62 | if(this->isEmpty()){ 63 | return NULL; 64 | }else{ 65 | return &this->head_ptr[this->head_index]; 66 | } 67 | } 68 | 69 | 70 | /* 71 | * Return true if queue is empty or false,otherwise. 72 | * Complexity : O(1) 73 | * @return bool 74 | */ 75 | template 76 | bool CircularQueue::isEmpty(){ 77 | return this->elements == 0; 78 | } 79 | 80 | 81 | /* 82 | * Return true if queue is full or false,otherwise. 83 | * Complexity : O(1) 84 | * @return bool 85 | */ 86 | template 87 | bool CircularQueue::isFull(){ 88 | return this->elements == this->size; 89 | } 90 | -------------------------------------------------------------------------------- /Data Structures/Queue/C++/CircularQueue/CircularQueue.hpp: -------------------------------------------------------------------------------- 1 | #ifndef _CIRCULARQUEUE_H_ 2 | #define _CIRCULARQUEUE_H_ 3 | /* 4 | *@author Ionésio Junior 5 | */ 6 | 7 | #include "resources/Queue.hpp" 8 | 9 | /* 10 | * Queue in circular implementation 11 | */ 12 | template 13 | class CircularQueue : public Queue{ 14 | private: 15 | T *head_ptr; 16 | int tail; 17 | int head_index; 18 | int size; 19 | int elements; 20 | public: 21 | CircularQueue(int size); 22 | bool isEmpty() override; 23 | bool isFull() override; 24 | void enqueue(T element) override; 25 | T* dequeue() override; 26 | T* head() override; 27 | }; 28 | 29 | #endif 30 | -------------------------------------------------------------------------------- /Data Structures/Queue/C++/CircularQueue/CircularQueueIntImpl.cpp: -------------------------------------------------------------------------------- 1 | #include "CircularQueue.cpp" 2 | 3 | template class CircularQueue; 4 | -------------------------------------------------------------------------------- /Data Structures/Queue/C++/StandardQueue/SimpleQueue.cpp: -------------------------------------------------------------------------------- 1 | #include "SimpleQueue.hpp" 2 | 3 | /* 4 | * SimpleQueue class constructor 5 | * @params length of the queue 6 | */ 7 | template 8 | SimpleQueue::SimpleQueue(int size){ 9 | this->head_ptr = (T*) calloc(size,sizeof(T)); 10 | this->tail = this->head_ptr - 1; 11 | this->size = size; 12 | } 13 | 14 | 15 | /* 16 | * Return true if queue is empty or false,otherwise. 17 | * Complexity : O(1) 18 | * @return bool 19 | */ 20 | template 21 | bool SimpleQueue::isEmpty(){ 22 | return (this->tail < this->head_ptr); 23 | } 24 | 25 | 26 | /* 27 | * Return true if queue is full or false,otherwise. 28 | * Complexity : O(1) 29 | * @return bool 30 | */ 31 | template 32 | bool SimpleQueue::isFull(){ 33 | return (this->tail == (this->head_ptr + this->size - 1)); 34 | } 35 | 36 | 37 | /* 38 | * Insert a new element in tail of the queue or throw an exception if queue is full. 39 | * Complexity : O(1) 40 | * @param element 41 | * @throw QueueOverflowException 42 | */ 43 | template 44 | void SimpleQueue::enqueue(T element){ 45 | if(!this->isFull()){ 46 | this->tail++; 47 | *this->tail = element; 48 | }else{ 49 | throw this->overflow; 50 | } 51 | } 52 | 53 | 54 | /* 55 | * Remove head element of the queue or throw an exception if queue is empty 56 | * Complexity : O(n) 57 | * @return element 58 | * @throw QueueUnderflowException 59 | */ 60 | template 61 | T* SimpleQueue::dequeue(){ 62 | if(!this->isEmpty()){ 63 | T removedElement = *(this->head_ptr); 64 | this->shiftLeft(); 65 | this->tail--; 66 | this->tail[1] = removedElement; 67 | return &this->tail[1]; 68 | }else{ 69 | throw this->underflow; 70 | } 71 | } 72 | 73 | 74 | /* 75 | * When an element is removed, this method move each element to the previous position. 76 | */ 77 | template 78 | void SimpleQueue::shiftLeft(){ 79 | for(int *i = this->head_ptr; i < this->tail;i++){ 80 | *i = *(i + 1); 81 | } 82 | } 83 | 84 | 85 | /* 86 | * Return element in the head of the queue without remove, or NULL if queue is empty. 87 | * Complexity : O(1) 88 | * @return element 89 | */ 90 | template 91 | T* SimpleQueue::head(){ 92 | if(!this->isEmpty()){ 93 | return this->head_ptr; 94 | }else{ 95 | return NULL; 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /Data Structures/Queue/C++/StandardQueue/SimpleQueue.hpp: -------------------------------------------------------------------------------- 1 | #ifndef _SIMPLEQUEUE_H_ 2 | #define _SIMPLEQUEUE_H_ 3 | 4 | /* 5 | *@author Ionésio Junior 6 | */ 7 | #include "resources/Queue.hpp" 8 | 9 | //Queue.hpp 10 | /* 11 | * Simple Queue Implementation 12 | */ 13 | 14 | template 15 | class SimpleQueue : public Queue{ 16 | private: 17 | T *head_ptr; 18 | T *tail; 19 | int size; 20 | void shiftLeft(); 21 | public: 22 | SimpleQueue(int size); 23 | bool isEmpty() override; 24 | bool isFull() override; 25 | void enqueue(T element) override; 26 | T* dequeue() override; 27 | T* head() override; 28 | }; 29 | 30 | #endif 31 | -------------------------------------------------------------------------------- /Data Structures/Queue/C++/StandardQueue/SimpleQueueIntImpl.cpp: -------------------------------------------------------------------------------- 1 | #include "SimpleQueue.cpp" 2 | 3 | template class SimpleQueue; 4 | -------------------------------------------------------------------------------- /Data Structures/Queue/C++/Test/Makefile: -------------------------------------------------------------------------------- 1 | LIB = -L/usr/lib/x86_64-linux-gnu/ 2 | LIBS = -lboost_unit_test_framework 3 | INCLUDE = -I../. 4 | 5 | all: Test 6 | 7 | ../StandardQueue/SimpleQueue.o: ../StandardQueue/SimpleQueueIntImpl.cpp ../StandardQueue/SimpleQueue.hpp ../StandardQueue/SimpleQueue.cpp 8 | g++ -c $< -o $@ $(INCLUDE) 9 | 10 | ../CircularQueue/CircularQueue.o: ../CircularQueue/CircularQueueIntImpl.cpp ../CircularQueue/CircularQueue.cpp ../CircularQueue/CircularQueue.hpp 11 | g++ -c $< -o $@ $(INCLUDE) 12 | 13 | Test: ../CircularQueue/CircularQueue.o ../StandardQueue/SimpleQueue.o 14 | g++ $^ test.cpp -o test $(LIB) $(LIBS) $(INCLUDE) -std=c++14 15 | 16 | clean: 17 | rm ../StandardQueue/SimpleQueue.o 18 | rm ../CircularQueue/CircularQueue.o 19 | rm test 20 | -------------------------------------------------------------------------------- /Data Structures/Queue/C++/resources/Exceptions.hpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | class QueueUnderflowException : public std::exception{ 5 | virtual const char* what() const throw(){ 6 | return "Queue is Empty!!"; 7 | } 8 | }; 9 | 10 | class QueueOverflowException : public std::exception{ 11 | virtual const char* what() const throw(){ 12 | return "Queue is Full!!"; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Data Structures/Queue/C++/resources/Queue.hpp: -------------------------------------------------------------------------------- 1 | #ifndef _QUEUE_H_ 2 | #define _QUEUE_H_ 3 | /* 4 | *@author Ionésio Junior 5 | */ 6 | #include 7 | #include 8 | #include "Exceptions.hpp" 9 | 10 | /* 11 | * Queue Abstract class implementation 12 | */ 13 | template 14 | class Queue{ 15 | public: 16 | QueueUnderflowException underflow; 17 | QueueOverflowException overflow; 18 | virtual bool isEmpty() = 0; 19 | virtual bool isFull() = 0; 20 | virtual void enqueue(T element) = 0; 21 | virtual T* dequeue() = 0; 22 | virtual T* head() = 0; 23 | }; 24 | 25 | #endif 26 | -------------------------------------------------------------------------------- /Data Structures/Stack/C++/Exceptions.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | *@author Ionesio Junior 3 | */ 4 | 5 | #include 6 | #include 7 | 8 | class StackOverflowException : public std::exception { 9 | virtual const char* what() const throw(){ 10 | return "Stack is Full!!!"; 11 | } 12 | }; 13 | 14 | class StackUnderflowException : public std::exception{ 15 | virtual const char* what() const throw(){ 16 | return "Stack is Empty!!"; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Data Structures/Stack/C++/Stack.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @author Ionésio Junior 3 | */ 4 | 5 | #include 6 | #include 7 | #include "Exceptions.hpp" 8 | 9 | //Stack.hpp 10 | template 11 | class Stack{ 12 | private: 13 | StackOverflowException overflow; 14 | StackUnderflowException underflow; 15 | T *top_ptr; 16 | T *begin; 17 | int size; 18 | public: 19 | Stack(int size); 20 | bool isEmpty(); 21 | bool isFull(); 22 | void push(T element); 23 | T* pop(); 24 | T* top(); 25 | }; 26 | 27 | 28 | //Stack.cpp 29 | 30 | /* 31 | * Constructor of stack class 32 | * @param lenght of stack 33 | */ 34 | /////////////////////////////////////////////////////////////////////////// 35 | 36 | template 37 | Stack::Stack(int size){ 38 | this->size = size; 39 | this->begin = (T*) calloc(this->size,sizeof(T)); 40 | this->top_ptr = this->begin - 1; 41 | } 42 | 43 | /////////////////////////////////////////////////////////////////////////// 44 | 45 | 46 | /* 47 | * Return True if stack is empty or false,otherwise 48 | * Complexity: O(1) 49 | * @return bool 50 | */ 51 | /////////////////////////////////////////////////////////////////////////// 52 | 53 | template 54 | bool Stack::isEmpty(){ 55 | return this->top_ptr == (this->begin - 1); 56 | } 57 | 58 | /////////////////////////////////////////////////////////////////////////// 59 | 60 | /* 61 | * Return True if stack is full or false,otherwise 62 | * Complexity: O(1) 63 | * @return bool 64 | */ 65 | /////////////////////////////////////////////////////////////////////////// 66 | 67 | template 68 | bool Stack::isFull(){ 69 | return this->top_ptr == (this->begin + size - 1); 70 | } 71 | 72 | //////////////////////////////////////////////////////////////////////////// 73 | 74 | 75 | /* 76 | * Insert a new element in the top of stack or throw an exception if stack is full 77 | * null elements aren't allowed 78 | * Complexity : O(1) 79 | * @param element 80 | * @throw StackOverflowException 81 | */ 82 | //////////////////////////////////////////////////////////////////////////// 83 | 84 | template 85 | void Stack::push(T element){ 86 | if(!this->isFull()){ 87 | this->top_ptr++; 88 | *this->top_ptr = element; 89 | }else{ 90 | throw overflow; 91 | } 92 | } 93 | 94 | ///////////////////////////////////////////////////////////////////////////// 95 | 96 | 97 | /* 98 | * Remove element in top of the stack of throw an exception if stack is empty. 99 | * Complexity: O(1) 100 | * @throw StackUnderflowException 101 | */ 102 | ////////////////////////////////////////////////////////////////////////////// 103 | 104 | template 105 | T* Stack::pop(){ 106 | if(!this->isEmpty()){ 107 | T* removedValue = this->top_ptr; 108 | --this->top_ptr; 109 | return removedValue; 110 | }else{ 111 | throw underflow; 112 | } 113 | } 114 | 115 | /////////////////////////////////////////////////////////////////////////////// 116 | 117 | /* 118 | * Return the top element of stack without remove this.(if stack is empty, return NULL). 119 | * Complexity: O(1) 120 | * @return element 121 | */ 122 | /////////////////////////////////////////////////////////////////////////////// 123 | 124 | template 125 | T* Stack::top(){ 126 | if(!this->isEmpty()){ 127 | return (this->top_ptr); 128 | }else{ 129 | return NULL; 130 | } 131 | } 132 | 133 | //////////////////////////////////////////////////////////////////////////////// 134 | -------------------------------------------------------------------------------- /Data Structures/Stack/C++/Test/Makefile: -------------------------------------------------------------------------------- 1 | LIB = -L/usr/lib/x86_64-linux-gnu/ 2 | LIBS = -lboost_unit_test_framework 3 | 4 | Test: 5 | g++ test.cpp -o test $(LIB) $(LIBS) -std=c++14 6 | -------------------------------------------------------------------------------- /Data Structures/Stack/C++/Test/test: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Asiatik/codezilla/9d870af843d0143daf7ec39aa7df4ef922cb4c3d/Data Structures/Stack/C++/Test/test -------------------------------------------------------------------------------- /Data Structures/Stack/C++/Test/test.cpp: -------------------------------------------------------------------------------- 1 | #define BOOST_TEST_DYN_LINK 2 | #define BOOST_TEST_MODULE StackTest 3 | 4 | #include 5 | #include "../Stack.hpp" 6 | #include 7 | 8 | struct StackInit{ 9 | Stack *stack = new Stack(10); 10 | }; 11 | 12 | BOOST_FIXTURE_TEST_SUITE(StackTest,StackInit) 13 | 14 | BOOST_AUTO_TEST_CASE(testInit){ 15 | BOOST_CHECK(true == stack->isEmpty()); 16 | BOOST_CHECK(false == stack->isFull()); 17 | BOOST_CHECK(NULL == stack->top()); 18 | } 19 | 20 | BOOST_AUTO_TEST_CASE(testIsEmpty){ 21 | BOOST_CHECK(true == stack->isEmpty()); 22 | stack->push(5); 23 | BOOST_CHECK(false == stack->isEmpty()); 24 | stack->top(); 25 | BOOST_CHECK(false == stack->isEmpty()); 26 | stack->pop(); 27 | BOOST_CHECK(true == stack->isEmpty()); 28 | } 29 | 30 | BOOST_AUTO_TEST_CASE(testIsFull){ 31 | BOOST_CHECK(false == stack->isFull()); 32 | for(int i = 0 ; i < 9;i++){ 33 | stack->push(i); 34 | } 35 | BOOST_CHECK(false == stack->isFull()); 36 | stack->push(20); 37 | BOOST_CHECK(true == stack->isFull()); 38 | } 39 | 40 | BOOST_AUTO_TEST_CASE(testPush){ 41 | BOOST_CHECK(true == stack->isEmpty()); 42 | stack->push(0); 43 | BOOST_CHECK(false == stack->isEmpty()); 44 | BOOST_CHECK(false == stack->isFull()); 45 | BOOST_CHECK(0 == *(stack->top())); 46 | for(int i = 1 ; i < 10;i++){ 47 | stack->push(i); 48 | BOOST_CHECK(i == *(stack->top())); 49 | } 50 | BOOST_CHECK(true == stack->isFull()); 51 | } 52 | 53 | BOOST_AUTO_TEST_CASE(testPop){ 54 | BOOST_CHECK(true == stack->isEmpty()); 55 | for(int i = 0 ; i < 10;i++){ 56 | stack->push(i); 57 | } 58 | BOOST_CHECK(false == stack->isEmpty()); 59 | BOOST_CHECK(true == stack->isFull()); 60 | 61 | for(int i = 9 ; i >= 0;i--){ 62 | BOOST_CHECK(i == *(stack->pop())); 63 | } 64 | 65 | BOOST_CHECK(true == stack->isEmpty()); 66 | BOOST_CHECK(false == stack->isFull()); 67 | } 68 | 69 | BOOST_AUTO_TEST_CASE(testTop){ 70 | BOOST_CHECK(true == stack->isEmpty()); 71 | BOOST_CHECK(NULL == stack->top()); 72 | for(int i = 0 ; i < 10;i++){ 73 | stack->push(i); 74 | BOOST_CHECK(i == *(stack->top())); 75 | } 76 | BOOST_CHECK(true == stack->isFull()); 77 | BOOST_CHECK(false == stack->isEmpty()); 78 | 79 | for(int i = 9; i >= 0;i--){ 80 | BOOST_CHECK(i == *(stack->top())); 81 | stack->pop(); 82 | } 83 | BOOST_CHECK(false == stack->isFull()); 84 | BOOST_CHECK(true == stack->isEmpty()); 85 | } 86 | 87 | BOOST_AUTO_TEST_CASE(testException){ 88 | BOOST_CHECK_THROW(stack->pop(),StackUnderflowException); 89 | for(int i = 0; i < 10;i++){ 90 | stack->push(i); 91 | } 92 | BOOST_CHECK_THROW(stack->push(10),StackOverflowException); 93 | } 94 | 95 | BOOST_AUTO_TEST_SUITE_END() 96 | -------------------------------------------------------------------------------- /Data Structures/Stack/Java/Stack.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * This class Implements Stack 4 | * @author hamza39460 5 | */ 6 | public class Stack { 7 | /** 8 | * node for stack 9 | */ 10 | private static class Node{ 11 | // data to store in node 12 | K data; 13 | // next node reference 14 | Node next; 15 | /** 16 | * Constructor for Class Node 17 | * @param data to be saved in node 18 | */ 19 | public Node(K data){this.data=data; 20 | next=null; 21 | } 22 | } 23 | // reference to head node of stack 24 | private Node headNode; 25 | // stack size 26 | private int stackSize; 27 | /** 28 | * constructor for class stack 29 | * initialize head node reference to null 30 | * initialize stack size to zero 31 | */ 32 | public Stack(){ 33 | headNode=null; 34 | stackSize=0; 35 | } 36 | /** 37 | * to create new node 38 | * @param data to be saved in node 39 | * @return new created node 40 | */ 41 | private Node addNode(T data) 42 | { 43 | Node newNode=new Node(data); 44 | return newNode; 45 | } 46 | /** 47 | * @return size of stack 48 | */ 49 | public int stackSize() 50 | { 51 | return stackSize; 52 | } 53 | /** 54 | * to push in stack 55 | * @param data to be pushed in stack 56 | */ 57 | public void push(T data) 58 | { 59 | Node newNode=addNode(data); 60 | newNode.next=headNode; 61 | headNode=newNode; 62 | stackSize++; 63 | } 64 | /** 65 | * removes top element 66 | * @return top element if not empty 67 | * else return false 68 | */ 69 | public T pop() 70 | { 71 | if (headNode!=null) 72 | { 73 | T data=(T)headNode.data; 74 | headNode=headNode.next; 75 | stackSize--; 76 | return data; 77 | } 78 | else 79 | return null; 80 | } 81 | /** 82 | * to get top element of stack 83 | * @return top of stack if stack is not empty 84 | * else return null 85 | */ 86 | public T top() 87 | { 88 | if (headNode!=null) 89 | return (T)headNode.data; 90 | else 91 | return null; 92 | } 93 | /** 94 | * to check if stack is empty 95 | * @return 96 | * true if stack is empty 97 | * false if stack is not empty 98 | */ 99 | boolean is_empty() 100 | { 101 | if (headNode==null) 102 | return true; 103 | return false; 104 | } 105 | /** 106 | * check if an element exist in stack 107 | * @param key element to check 108 | * @return 109 | * true if element exists 110 | * false if element does not exist 111 | */ 112 | boolean exist(T key) 113 | { 114 | if(headNode==null) 115 | return false; 116 | else if (headNode.data==key) 117 | return true; 118 | else { 119 | Node temp=headNode; 120 | while (temp!=null&&temp.data!=key) 121 | { 122 | temp=temp.next; 123 | } 124 | if (temp!=null) 125 | return true; 126 | } 127 | return false; 128 | } 129 | /* 130 | pop all elements from stack 131 | */ 132 | public void popAll(){ 133 | while (headNode!=null) 134 | headNode=headNode.next; 135 | } 136 | // driver program 137 | public static void main(String args[]) 138 | { 139 | Stack obj; 140 | obj = new Stack(); 141 | obj.push(2.2); 142 | obj.push(3.3); 143 | obj.push(4.4); 144 | obj.push(5.5); 145 | obj.push(6.6); 146 | while(!obj.is_empty()) 147 | { 148 | System.out.println(obj.pop()); 149 | } 150 | 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /Data Structures/Stack/Python/stack.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class Stack: 4 | 5 | def __init__(self, size = 1000000): 6 | self.stack = [] 7 | self.stack_size = size 8 | 9 | # Add element to stack 10 | def push(self, element): 11 | # Checking stack is full or not 12 | if len(self.stack) <= self.stack_size: 13 | self.stack.append(element) 14 | else: 15 | print('Stack Full. Overflow') 16 | 17 | # Delete element from stack 18 | def pop(self): 19 | if len(self.stack) == 0: 20 | print('Empty Stack. Underflow') 21 | else: 22 | self.stack.pop() 23 | 24 | # Returns top element of stack 25 | def top(self): 26 | return self.stack[-1] 27 | 28 | 29 | # Driver Program 30 | if __name__ == '__main__': 31 | stack = Stack() 32 | stack.pop() 33 | stack.push(1) 34 | stack.push(2) 35 | stack.push(3) 36 | print(stack.top()) 37 | stack.pop() 38 | print(stack.top()) 39 | -------------------------------------------------------------------------------- /Dynamic Programming/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Asiatik/codezilla/9d870af843d0143daf7ec39aa7df4ef922cb4c3d/Dynamic Programming/.gitkeep -------------------------------------------------------------------------------- /Dynamic Programming/EditDistance/Java/EditDistance.java: -------------------------------------------------------------------------------- 1 | /* 2 | A Dynamic Programming based Java program to find minimum 3 | number operations to convert str1 to str2 4 | */ 5 | class EditDistance 6 | { 7 | // Returns the min int 8 | static int min(int x,int y,int z) 9 | { 10 | if (x <= y && x <= z) return x; 11 | if (y <= x && y <= z) return y; 12 | else return z; 13 | } 14 | 15 | // Edit Distance based on DP 16 | static int editDistanceDP(String str1, String str2, int m, int n) 17 | { 18 | // Create a table to store results of subproblems 19 | int dp[][] = new int[m+1][n+1]; 20 | 21 | // Fill d[][] in bottom up manner 22 | for (int i=0; i<=m; i++) 23 | { 24 | for (int j=0; j<=n; j++) 25 | { 26 | // If first string is empty, only option is to 27 | // insert all characters of second string 28 | if (i==0) 29 | dp[i][j] = j; // Min. operations = j 30 | 31 | // If second string is empty, only option is to 32 | // remove all characters of second string 33 | else if (j==0) 34 | dp[i][j] = i; // Min. operations = i 35 | 36 | // If last characters are same, ignore last char 37 | // and recur for remaining string 38 | else if (str1.charAt(i-1) == str2.charAt(j-1)) 39 | dp[i][j] = dp[i-1][j-1]; 40 | 41 | // If the last character is different, consider all 42 | // possibilities and find the minimum 43 | else 44 | dp[i][j] = 1 + min(dp[i][j-1], // Insert 45 | dp[i-1][j], // Remove 46 | dp[i-1][j-1]); // Replace 47 | } 48 | } 49 | 50 | return dp[m][n]; 51 | } 52 | 53 | 54 | 55 | public static void main(String args[]) 56 | { 57 | String str1 = "their"; 58 | String str2 = "they're"; 59 | System.out.println( editDistanceDP( str1 , str2 , str1.length(), str2.length()) ); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /Dynamic Programming/EditDistance/README.md: -------------------------------------------------------------------------------- 1 | # Edit Distance Implementation 2 | 3 | ## Problem Statement 4 | Given two strings str1 and str2 and below operations that can performed on str1. Find minimum number of edits (operations) required to convert ‘str1’ into ‘str2’. All of the above operations are of equal cost. 5 | 6 | ## Steps 7 | 1. Create an array to store results of all the subproblems 8 | 2. Check if any of the two strings is empty 9 | 3. If the last characters are same call method recursively 10 | 4. Else-If the last character is different, consider all possibilites and find the minimum 11 | -------------------------------------------------------------------------------- /Dynamic Programming/Fibonacci Sequence/Fibonacci_series.txt: -------------------------------------------------------------------------------- 1 | # Program to display the Fibonacci sequence up to n-th term where n is provided by the user 2 | 3 | # change this value for a different result 4 | nterms = int (input("enter the no. of terms " )) 5 | 6 | # uncomment to take input from the user 7 | #nterms = int(input("How many terms? ")) 8 | 9 | # first two terms 10 | n1 = 0 11 | n2 = 1 12 | count = 0 13 | 14 | # check if the number of terms is valid 15 | if nterms <= 0: 16 | print("Please enter a positive integer") 17 | elif nterms == 1: 18 | print("Fibonacci sequence upto",nterms,":") 19 | print(n1) 20 | else: 21 | print("Fibonacci sequence upto",nterms,":") 22 | while count < nterms: 23 | print(n1,end=' , ') 24 | nth = n1 + n2 25 | # update values 26 | n1 = n2 27 | n2 = nth 28 | count += 1 29 | -------------------------------------------------------------------------------- /Dynamic Programming/Fibonacci Sequence/Java/Fibonacci.java: -------------------------------------------------------------------------------- 1 | /** 2 | * The 3 general approaches to a very basic dynamic programming problem - the fibonacci sequence 3 | */ 4 | public class Fibonacci { 5 | 6 | /** 7 | * The very basic fibonacci sequence. 8 | * Notice the run time is O(n^2) as it has to recalculate the same value numerous times. 9 | * This is something we try to avoid. 10 | * 11 | * E.G) To get fib(4): 12 | * fib(5) 13 | * / \ 14 | * fib(3) fib(4) 15 | * / \ / \ 16 | * fib(2) fib(1) fib(2) fib(3) 17 | * / \ 18 | * fib(2) fib(1) 19 | * 20 | * @param n The nth fibonacci number 21 | * @return The value of the nth fibonacci number 22 | */ 23 | public int naiveFibonacci(int n) { 24 | assert n > 0; 25 | 26 | if(n == 1 || n == 2) 27 | return 1; 28 | 29 | return naiveFibonacci(n-1) + naiveFibonacci(n-2); 30 | } 31 | 32 | private Map memo = new HashMap<>(); 33 | 34 | /** 35 | * Very similar to above but notice the reference to a map. 36 | * This is a memo and keeps track of values we have already crossed. 37 | * Since retrieval from a map is O(1) it improves the runtime of the program by not having to recalculate 38 | * same values over and over. 39 | * 40 | * @param n The nth fibonacci number 41 | * @return The value of the nth fibonacci number 42 | */ 43 | public int memoizedFibonacci(int n) { 44 | assert n > 0; 45 | 46 | if(n == 1 || n == 2) 47 | return 1; 48 | 49 | //If we already calculated the value before. 50 | if(memo.containsKey(n)) 51 | return memo.get(n); 52 | 53 | //If not, add it to the memo in case we need to retrieve it again 54 | int fib = naiveFibonacci(n-1) + naiveFibonacci(n-2); 55 | memo.put(n, fib); 56 | 57 | return fib; 58 | } 59 | 60 | /** 61 | * Now this is very different to the other two. No recursion, just a primitive array. 62 | * How this works is based of how you look at fibonacci normally: 63 | * 1,1,2,3,5,... The next number is the sum of the previous two - as can be seen in the for loop. 64 | * The first two indexes represent the first and second value (hence why the if just returns 1 if you input a value 65 | * less than 3). 66 | * The runtime complexity is also easier as it become O(n) since we only pass the loop once and O(n) space as 67 | * the array increases proportionally to the increase in input value n. 68 | * 69 | * @param n The nth fibonacci number 70 | * @return The value of the nth fibonacci number 71 | */ 72 | public int tabulatedFibonacci(int n) { 73 | assert n > 0; 74 | 75 | if(n < 3) 76 | return 1; 77 | 78 | int[] tab = new int[n]; 79 | tab[0] = 1; tab[1] = 1; 80 | 81 | for(int i=2; i 9 | This is because it is the sum of the 5th and 4th elements which are __5__ and __3__. 10 | The full sequence leading up to it is: 11 | ``` 12 | 1,1,2,3,5,8 13 | ``` 14 | 15 | A reminder that this is an infinite sequence therefore there is no end, but in programming 16 | terms, end will be reached when it reaches max value (which in Java is 2^31 since int is 32 bit). 17 | 18 | One question that may also be asked (along with the examples provided) is to get n-step fibonacci. 19 | This refers to n numbers added to create the next digit. 20 | 21 | ### Example 22 | 3 step fibonacci (also called tribonacci) will look as follows: 23 | ``` 24 | 1,1,2,4,7,13,24 25 | ``` 26 | As it is adding the 3 previous values before it. Note the _1,1,2_ as the third index only has two numbers 27 | to use, it will only be able to add them. 28 | 29 | -------------------------------------------------------------------------------- /Dynamic Programming/Longest Increasing Subsequence/C++/LongestIncreasingSubsequence.cpp: -------------------------------------------------------------------------------- 1 | /*@author Navneet Jain 2 | * 3 | * Find the longest increasing subsequence of a given sequence / array. 4 | * In other words, find a subsequence of array in which the subsequence’s elements are in strictly increasing order, and in which the subsequence is as long as possible. 5 | * This subsequence is not necessarily contiguous, or unique. 6 | * In this case, we only care about the length of the longest increasing subsequence. 7 | 8 | * Example : 9 | 10 | * Input : [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15] 11 | * Output : 6 12 | * The sequence : [0, 2, 6, 9, 13, 15] or [0, 4, 6, 9, 11, 15] or [0, 4, 6, 9, 13, 15] 13 | 14 | */ 15 | 16 | #include 17 | #include 18 | 19 | int longestSubsequence(const std::vector &A) 20 | { 21 | std::vector B(A.size(), 1); 22 | int max_value = 1; 23 | 24 | for(unsigned int i = 1 ; i < A.size(); i++) 25 | { 26 | for(unsigned int j = 0 ; j < i; j++) 27 | { 28 | if(A[j] < A[i]) 29 | { 30 | B[i] = std::max(B[i] , B[j] + 1); 31 | max_value = std::max(B[i], max_value); 32 | } 33 | } 34 | } 35 | 36 | return max_value; 37 | } 38 | 39 | int main() 40 | { 41 | std::vector A = {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}; 42 | std::cout << longestSubsequence(A); 43 | } 44 | -------------------------------------------------------------------------------- /Dynamic Programming/Longest Increasing Subsequence/README.md: -------------------------------------------------------------------------------- 1 | Problem Statement: 2 | Find the longest increasing subsequence of a given sequence / array. 3 | In other words, find a subsequence of array in which the subsequence’s elements are in strictly increasing order, and in which the subsequence is as long as possible. 4 | This subsequence is not necessarily contiguous, or unique. 5 | In this case, we only care about the length of the longest increasing subsequence. 6 | 7 | Example : 8 | 9 | Input : [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15] 10 | Output : 6 11 | The sequence : [0, 2, 6, 9, 13, 15] or [0, 4, 6, 9, 11, 15] or [0, 4, 6, 9, 13, 15] 12 | 13 | 14 | Solution Approach: 15 | The solution approach here is DP. We calculate the longest increasing subsequence for substring of length 1 to n. For every number, we see what all numbers, before the current index, are smaller than the current number and find the longest length subsequence based on that. 16 | For above example, 17 | The longest subsequence array would be 18 | 1, 1, 2, 3, 2, 3, 3, 4, 2, 4, 3, 4, 3, 5, 4, 6 19 | 20 | Hence the answer is 6 21 | -------------------------------------------------------------------------------- /Dynamic Programming/buy_sell_stocks/C++/buy_sell_stock_dp.cpp: -------------------------------------------------------------------------------- 1 | /*@author Navneet Jain 2 | * Say you have an array for which the ith element is the price of a given stock on day i. 3 | * If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. 4 | 5 | */ 6 | #include 7 | #include 8 | #include 9 | using namespace std; 10 | 11 | int maxProfit(const vector &A) { 12 | int buy = A[0], flag = 0, i = 1, max_sell = INT_MIN; 13 | int sol = 0; 14 | while(i < A.size()){ 15 | int diff = A[i] - A[i-1]; 16 | //It's a greedy appoach. If current diff is greater than 0, then add that to the solution. 17 | if(diff > 0){ 18 | sol = sol + diff; 19 | } 20 | i++; 21 | } 22 | 23 | return sol; 24 | } 25 | 26 | int main(){ 27 | vector A = {1,2}; 28 | cout << maxProfit(A); 29 | } 30 | -------------------------------------------------------------------------------- /Dynamic Programming/buy_sell_stocks/README.md: -------------------------------------------------------------------------------- 1 | Problem Statement: 2 | Say you have an array for which the ith element is the price of a given stock on day i. 3 | If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. 4 | 5 | Solution Approach: 6 | If you buy your stock on day i, you’d obviously want to sell it on the day its price is maximum after that day. 7 | So essentially at every index i, you need to find the maximum in the array in the suffix. 8 | Now this part can be done in 2 ways : 9 | 1) Have another array which stores that information. 10 | max[i] = max(max[i+1], A[i]) 11 | 12 | 2) Start processing entries from the end maintaining a maximum till now. Constant additional space requirement. 13 | 14 | 15 | -------------------------------------------------------------------------------- /Dynamic Programming/climb_stairs/C++/distinct_ways_to_climb_stairs.cpp: -------------------------------------------------------------------------------- 1 | /*@author Navneet Jain 2 | * You are climbing a stair case. It takes n steps to reach to the top. 3 | Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 4 | */ 5 | 6 | #include 7 | using namespace std; 8 | 9 | long countSteps(int A){ 10 | if(A <= 0){ 11 | return 0; 12 | } 13 | else if(A ==1){ 14 | return 1; 15 | } 16 | else if(A == 2){ 17 | return 2; 18 | } 19 | //Since only way to reach nth stair is via n-1 stair and n-2 stair. Hence adding those two to get the result recursively 20 | return countSteps(A - 1) + countSteps(A -2); 21 | 22 | 23 | } 24 | 25 | int climbStairs(int A) { 26 | return countSteps(A); 27 | 28 | } 29 | 30 | int main(){ 31 | int stair_to_reach; 32 | cin >> stair_to_reach; 33 | cout << climbStairs(stair_to_reach); 34 | } 35 | -------------------------------------------------------------------------------- /Dynamic Programming/climb_stairs/README.md: -------------------------------------------------------------------------------- 1 | Problem Statement: 2 | You are climbing a stair case. It takes n steps to reach to the top. 3 | Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 4 | 5 | Example: 6 | Input : 3 7 | Return : 3 8 | 9 | Steps : [1 1 1], [1 2], [2 1] 10 | 11 | 12 | More info: https://www.interviewbit.com/problems/stairs/ 13 | 14 | Solution Approach: 15 | The solution approach here is DP. We calculate the ways to reach a stair based on it's subproblems. 16 | One can reach nth stair from n-1th stair and n-2th stair. 17 | Hence the subproblem gives a generic equation: 18 | num_of_ways[n] = num_of_ways[n-1] + num_of_ways[n-2] 19 | 20 | And the base statement becomes number_of_ways[1] = 1 and number_of_ways[2] = 2 21 | 22 | 23 | -------------------------------------------------------------------------------- /Dynamic Programming/coin_change_problem/C++/coin_change_problem.cpp: -------------------------------------------------------------------------------- 1 | /* @author Navneet Jain 2 | * You are given a set of coins A. In how many ways can you make sum B assuming you have infinite amount of each coin in the set. 3 | * Question link - https://www.interviewbit.com/problems/coin-sum-infinite/ 4 | 5 | */ 6 | #include 7 | #include 8 | #include 9 | using namespace std; 10 | 11 | int coinchange(vector &A, int B) { 12 | 13 | int ways[B+1]; 14 | //presetting ways array to 0 15 | for(int i = 0 ; i <= B; i++){ 16 | ways[i] =0; 17 | } 18 | 19 | ways[0] = 1; 20 | 21 | //loop over each coin value 22 | for(int i = 0; i < A.size(); i++){ 23 | for(int j = A[i]; j <= B; j++){ 24 | ways[j] = ways[j] + ways[j-A[i]]; 25 | ways[j] = ways[j]%1000007; 26 | } 27 | } 28 | 29 | return ways[B]; 30 | } 31 | 32 | int main(){ 33 | int sum_to_make=4; 34 | vector coin_arr = {1,2,3}; 35 | cout << coinchange(coin_arr, sum_to_make); 36 | 37 | } 38 | -------------------------------------------------------------------------------- /Dynamic Programming/coin_change_problem/README.md: -------------------------------------------------------------------------------- 1 | Problem Statement: 2 | You are given a set of coins A. In how many ways can you make sum B assuming you have infinite amount of each coin in the set. 3 | Input : 4 | S = [1, 2, 3] 5 | N = 4 6 | 7 | Return : 4 8 | 9 | Explanation : The 4 possible ways are 10 | {1, 1, 1, 1} 11 | {1, 1, 2} 12 | {2, 2} 13 | {1, 3} 14 | 15 | 16 | Solution Approach: 17 | The solution approach here is DP. We calculate the ways to count number from 1 to n based on a subproblem. 18 | 19 | Suppose we want to calculate the number of ways to calcualate 4 with given coin denomination 1. 20 | So the subproblem here is with 1 as the coin available, the number of ways to calculate 4 is equal to the number of ways to calcualate 3. 21 | Taking this as a subproblem, we can see that 22 | numOfWays[4] = numOfWays[4] + numofWays[3] 23 | 24 | To generalize, 25 | numOfWays[value] = numOfWays[value] + numofWays[value-current_denomination] 26 | 27 | Looping over every coin denomination available, we can compute the result 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/heavy/01.in: -------------------------------------------------------------------------------- 1 | 4 4 2 | 2 3 3 3 3 | 1 3 2 3 4 | 2 2 1 2 5 | 1 2 1 1 6 | -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/heavy/02.in: -------------------------------------------------------------------------------- 1 | 4 5 2 | 1 1 2 2 1 3 | 1 3 1 1 1 4 | 3 3 1 3 3 5 | 0 0 3 2 0 6 | -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/heavy/03.in: -------------------------------------------------------------------------------- 1 | 4 5 2 | 1 2 1 3 1 3 | 2 2 3 3 1 4 | 2 1 3 0 3 5 | 1 1 1 0 2 6 | -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/heavy/04.in: -------------------------------------------------------------------------------- 1 | 4 5 2 | 2 3 1 3 1 3 | 3 1 2 2 2 4 | 2 3 1 3 2 5 | 1 3 2 1 0 6 | -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/heavy/05.in: -------------------------------------------------------------------------------- 1 | 4 5 2 | 3 1 2 2 1 3 | 1 2 2 2 1 4 | 1 2 1 1 3 5 | 3 1 3 3 2 6 | -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/heavy/06.in: -------------------------------------------------------------------------------- 1 | 5 5 2 | 2 3 3 3 2 3 | 2 3 2 3 2 4 | 0 1 2 2 2 5 | 0 2 2 1 1 6 | 0 1 0 3 1 7 | -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/heavy/07.in: -------------------------------------------------------------------------------- 1 | 4 6 2 | 1 3 2 3 3 0 3 | 3 2 2 3 1 3 4 | 1 2 2 3 2 0 5 | 1 2 1 3 3 2 6 | -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/heavy/08.in: -------------------------------------------------------------------------------- 1 | 3 8 2 | 1 3 3 1 1 1 1 0 3 | 1 3 2 2 1 1 2 3 4 | 3 2 2 2 3 2 1 1 5 | -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/heavy/09.in: -------------------------------------------------------------------------------- 1 | 3 8 2 | 3 3 3 3 1 3 1 3 3 | 2 2 2 1 3 3 1 0 4 | 1 3 2 3 3 1 1 2 5 | -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/heavy/10.in: -------------------------------------------------------------------------------- 1 | 2 3 2 | 0 0 3 3 | 2 3 3 4 | -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/heavy/results01: -------------------------------------------------------------------------------- 1 | 501215 2 | 6 3 | 2 1 3 4 | 2 3 3 5 | 3 2 3 6 | 3 4 3 7 | 4 1 3 8 | 4 3 3 9 | -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/heavy/results02: -------------------------------------------------------------------------------- 1 | 99131410 2 | 7 3 | 1 1 2 4 | 1 3 2 5 | 1 5 2 6 | 2 2 2 7 | 2 4 2 8 | 3 1 2 9 | 3 3 2 10 | -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/heavy/results03: -------------------------------------------------------------------------------- 1 | 55218735 2 | 3 3 | 1 1 2 4 | 1 3 2 5 | 2 2 2 6 | -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/heavy/results04: -------------------------------------------------------------------------------- 1 | 11491157072 2 | 10 3 | 1 1 3 4 | 1 3 3 5 | 1 5 3 6 | 2 2 3 7 | 2 4 3 8 | 3 1 3 9 | 3 3 3 10 | 3 5 3 11 | 4 2 3 12 | 4 4 3 13 | -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/heavy/results05: -------------------------------------------------------------------------------- 1 | 707769776749 2 | 9 3 | 1 1 2 4 | 1 3 2 5 | 2 2 2 6 | 2 4 2 7 | 3 1 2 8 | 3 3 2 9 | 3 5 2 10 | 4 2 2 11 | 4 4 2 12 | -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/heavy/results06: -------------------------------------------------------------------------------- 1 | 7464445170 2 | 3 3 | 1 4 1 4 | 2 5 1 5 | 3 4 1 6 | -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/heavy/results07: -------------------------------------------------------------------------------- 1 | 154887457284 2 | 6 3 | 1 2 3 4 | 2 3 3 5 | 3 2 3 6 | 3 4 3 7 | 4 1 3 8 | 4 3 3 9 | -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/heavy/results08: -------------------------------------------------------------------------------- 1 | 1329421080 2 | 4 3 | 1 2 3 4 | 2 1 3 5 | 2 3 3 6 | 3 2 3 7 | -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/heavy/results09: -------------------------------------------------------------------------------- 1 | 280997347995 2 | 4 3 | 1 4 3 4 | 2 3 3 5 | 2 5 3 6 | 3 2 3 7 | -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/heavy/results10: -------------------------------------------------------------------------------- 1 | 1 2 | 1 3 | 1 3 2 4 | -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/light/01.in: -------------------------------------------------------------------------------- 1 | 4 4 2 | 1 0 0 0 3 | 2 3 2 1 4 | 2 2 2 1 5 | 2 2 2 2 6 | -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/light/02.in: -------------------------------------------------------------------------------- 1 | 4 4 2 | 2 1 3 3 3 | 0 3 3 1 4 | 0 3 1 2 5 | 1 2 1 1 6 | -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/light/03.in: -------------------------------------------------------------------------------- 1 | 4 4 2 | 1 1 1 3 3 | 1 2 2 2 4 | 2 2 1 1 5 | 2 2 1 0 6 | -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/light/04.in: -------------------------------------------------------------------------------- 1 | 4 4 2 | 1 2 1 3 3 | 2 3 2 1 4 | 2 2 1 3 5 | 2 3 3 2 6 | -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/light/05.in: -------------------------------------------------------------------------------- 1 | 4 5 2 | 2 0 2 0 2 3 | 3 3 1 1 3 4 | 3 2 3 3 3 5 | 3 3 3 2 0 6 | -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/light/06.in: -------------------------------------------------------------------------------- 1 | 4 5 2 | 1 1 2 2 1 3 | 3 2 3 1 3 4 | 0 3 3 1 3 5 | 2 1 1 2 0 6 | -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/light/07.in: -------------------------------------------------------------------------------- 1 | 3 8 2 | 0 1 3 1 1 2 2 2 3 | 0 2 2 3 1 1 1 2 4 | 0 0 0 2 1 2 1 1 5 | -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/light/08.in: -------------------------------------------------------------------------------- 1 | 2 11 2 | 1 1 1 2 3 2 2 2 1 0 0 3 | 2 1 1 3 2 2 3 3 3 3 2 4 | -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/light/09.in: -------------------------------------------------------------------------------- 1 | 2 11 2 | 0 2 1 3 2 1 1 1 1 3 3 3 | 2 3 2 2 2 2 3 3 3 1 2 4 | -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/light/10.in: -------------------------------------------------------------------------------- 1 | 2 3 2 | 0 0 3 3 | 2 3 3 4 | -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/light/results: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Asiatik/codezilla/9d870af843d0143daf7ec39aa7df4ef922cb4c3d/Dynamic Programming/jan-ken-puzzle/python/test/light/results -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/light/results0: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Asiatik/codezilla/9d870af843d0143daf7ec39aa7df4ef922cb4c3d/Dynamic Programming/jan-ken-puzzle/python/test/light/results0 -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/light/results01: -------------------------------------------------------------------------------- 1 | 33000 2 | 5 3 | 2 1 3 4 | 2 3 3 5 | 3 2 3 6 | 4 1 3 7 | 4 3 3 8 | -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/light/results02: -------------------------------------------------------------------------------- 1 | 271700 2 | 4 3 | 1 4 2 4 | 2 3 2 5 | 3 4 2 6 | 4 3 2 7 | -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/light/results03: -------------------------------------------------------------------------------- 1 | 365248 2 | 6 3 | 1 1 3 4 | 1 3 3 5 | 2 2 3 6 | 2 4 3 7 | 3 1 3 8 | 3 3 3 9 | -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/light/results04: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Asiatik/codezilla/9d870af843d0143daf7ec39aa7df4ef922cb4c3d/Dynamic Programming/jan-ken-puzzle/python/test/light/results04 -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/light/results05: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Asiatik/codezilla/9d870af843d0143daf7ec39aa7df4ef922cb4c3d/Dynamic Programming/jan-ken-puzzle/python/test/light/results05 -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/light/results06: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Asiatik/codezilla/9d870af843d0143daf7ec39aa7df4ef922cb4c3d/Dynamic Programming/jan-ken-puzzle/python/test/light/results06 -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/light/results07: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Asiatik/codezilla/9d870af843d0143daf7ec39aa7df4ef922cb4c3d/Dynamic Programming/jan-ken-puzzle/python/test/light/results07 -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/light/results08: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Asiatik/codezilla/9d870af843d0143daf7ec39aa7df4ef922cb4c3d/Dynamic Programming/jan-ken-puzzle/python/test/light/results08 -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/light/results09: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Asiatik/codezilla/9d870af843d0143daf7ec39aa7df4ef922cb4c3d/Dynamic Programming/jan-ken-puzzle/python/test/light/results09 -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/light/results1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Asiatik/codezilla/9d870af843d0143daf7ec39aa7df4ef922cb4c3d/Dynamic Programming/jan-ken-puzzle/python/test/light/results1 -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/light/results10: -------------------------------------------------------------------------------- 1 | 1 2 | 1 3 | 1 3 2 4 | -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/light/results2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Asiatik/codezilla/9d870af843d0143daf7ec39aa7df4ef922cb4c3d/Dynamic Programming/jan-ken-puzzle/python/test/light/results2 -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/light/results3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Asiatik/codezilla/9d870af843d0143daf7ec39aa7df4ef922cb4c3d/Dynamic Programming/jan-ken-puzzle/python/test/light/results3 -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/light/results4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Asiatik/codezilla/9d870af843d0143daf7ec39aa7df4ef922cb4c3d/Dynamic Programming/jan-ken-puzzle/python/test/light/results4 -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/light/results5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Asiatik/codezilla/9d870af843d0143daf7ec39aa7df4ef922cb4c3d/Dynamic Programming/jan-ken-puzzle/python/test/light/results5 -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/test/light/results6: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Asiatik/codezilla/9d870af843d0143daf7ec39aa7df4ef922cb4c3d/Dynamic Programming/jan-ken-puzzle/python/test/light/results6 -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/tests_heavy.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | shopt -s nullglob 3 | TIMEFORMAT='%3R' 4 | 5 | for ext in .in; do 6 | files=(test/heavy/*"$ext") 7 | for i in `seq -f %02g ${#files[@]}`; do 8 | printf "\n$i,"; 9 | time (python3 puzzle_hash.py < test/heavy/$i.in | tee test/heavy/results$i &> /dev/null); 10 | # printf "\n"; 11 | # diff -y test/heavy/results$i test/heavy/$i.out; 12 | done 13 | done 14 | -------------------------------------------------------------------------------- /Dynamic Programming/jan-ken-puzzle/python/tests_light.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | shopt -s nullglob 3 | TIMEFORMAT='%3R' 4 | 5 | for ext in .in; do 6 | files=(test/light/*"$ext") 7 | for i in `seq -f %02g ${#files[@]}`; do 8 | printf "\n$i,"; 9 | time (python puzzle_hash.py < test/light/$i.in | tee test/light/results$i &> /dev/null); 10 | # printf "\n"; 11 | # diff -y test/light/results$i test/light/$i.out; 12 | done 13 | done 14 | -------------------------------------------------------------------------------- /Dynamic Programming/ways_to_decode/C++/dp_ways_to_decode.cpp: -------------------------------------------------------------------------------- 1 | /* @author Navneet Jain 2 | * A message containing letters from A-Z is being encoded to numbers using the following mapping: 3 | * 'A' -> 1 4 | * 'B' -> 2 5 | * ... 6 | * 'Z' -> 26 7 | 8 | * Given an encoded message containing digits, determine the total number of ways to decode it. 9 | 10 | * Example : 11 | * Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12). 12 | * The number of ways decoding "12" is 2. 13 | 14 | */ 15 | 16 | #include 17 | #include 18 | #include 19 | 20 | using namespace std; 21 | 22 | int numDecodings(string A) { 23 | int sizeA = A.length(); 24 | if(sizeA == 0){ 25 | return 0; 26 | } 27 | else if(A[0] - '0' == 0){ 28 | return 0; 29 | } 30 | 31 | std::vector B(sizeA + 1, 1); 32 | for(int i = 1 ; i < sizeA; i++){ 33 | if(A[i] - '0' == 0 && A[i - 1] - '0' > 2){ 34 | return 0; 35 | } 36 | else if(A[i] - '0' == 0 && i != sizeA - 1){ 37 | B[i+1] = 0; 38 | } 39 | else if(A[i] - '0' == 0 ){ 40 | B[i+1] = B[i]; 41 | } 42 | else if(A[i] - '0' <= 6 && A[i-1] - '0' <=2 ){ 43 | B[i + 1] = B[i] + B[i-1]; 44 | } 45 | else{ 46 | B[i+1] = B[i]; 47 | } 48 | } 49 | 50 | return B[sizeA]; 51 | } 52 | 53 | int main(){ 54 | string A = "123"; 55 | cout << numDecodings(A); 56 | } 57 | 58 | -------------------------------------------------------------------------------- /Dynamic Programming/ways_to_decode/README.md: -------------------------------------------------------------------------------- 1 | Problem Statement : 2 | A message containing letters from A-Z is being encoded to numbers using the following mapping: 3 | 'A' -> 1 4 | 'B' -> 2 5 | ... 6 | 'Z' -> 26 7 | 8 | Given an encoded message containing digits, determine the total number of ways to decode it. 9 | 10 | Example : 11 | Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12). 12 | The number of ways decoding "12" is 2. 13 | 14 | 15 | 16 | Solution Approach : 17 | Used a DP approach to solve the problem. Calculated the number of ways to decode string of length 1 to n. 18 | Derived the solution for string length n from the subproblems i.e. number of ways to decode string length n-1 and number of ways to decode string length n-2 19 | -------------------------------------------------------------------------------- /Fibonacci_series.py: -------------------------------------------------------------------------------- 1 | # Program to display the Fibonacci sequence up to n-th term where n is provided by the user 2 | 3 | # change this value for a different result 4 | nterms = int (input("enter the no. of terms " )) 5 | 6 | # uncomment to take input from the user 7 | #nterms = int(input("How many terms? ")) 8 | 9 | # first two terms 10 | n1 = 0 11 | n2 = 1 12 | count = 0 13 | 14 | # check if the number of terms is valid 15 | if nterms <= 0: 16 | print("Please enter a positive integer") 17 | elif nterms == 1: 18 | print("Fibonacci sequence upto",nterms,":") 19 | print(n1) 20 | else: 21 | print("Fibonacci sequence upto",nterms,":") 22 | while count < nterms: 23 | print(n1,end=' , ') 24 | nth = n1 + n2 25 | # update values 26 | n1 = n2 27 | n2 = nth 28 | count += 1 29 | -------------------------------------------------------------------------------- /Graphs/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Asiatik/codezilla/9d870af843d0143daf7ec39aa7df4ef922cb4c3d/Graphs/.gitkeep -------------------------------------------------------------------------------- /Graphs/BFS/C++/BFS.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * adikul30 3 | * Aditya Kulkarni 4 | */ 5 | #include 6 | 7 | using namespace std; 8 | 9 | #define REP(i, a, b) for(int i = a; i < b; ++i) 10 | #define pb push_back 11 | #define MAX 100 12 | 13 | typedef vector vi; 14 | 15 | bool visited[MAX]; 16 | vi adj[MAX]; 17 | int distance[MAX]; 18 | queue q; 19 | 20 | void bfs(int x){ 21 | visited[x] = true; 22 | cout << x << endl; 23 | q.push(x); 24 | while(!q.empty()){ 25 | int s = q.front(); 26 | q.pop(); 27 | for (auto u : adj[s]){ 28 | if (visited[u]) continue; 29 | visited[u] = true; 30 | cout << u << endl; 31 | q.push(u); 32 | } 33 | } 34 | } 35 | 36 | int main() 37 | { 38 | ios_base::sync_with_stdio(0); 39 | int n = 5; 40 | REP(i,1,n+1)visited[i] = false; 41 | adj[1].pb(2); 42 | adj[1].pb(3); 43 | adj[1].pb(5); 44 | adj[2].pb(3); 45 | adj[3].pb(4); 46 | 47 | bfs(1); 48 | return 0; 49 | } -------------------------------------------------------------------------------- /Graphs/BFS/Python/bfs.py: -------------------------------------------------------------------------------- 1 | import queue 2 | visited = [] 3 | MAX = 20 4 | adj = {1: set([2,3,5]), 2: set([3]), 3: set([8,4]), 4:6} 5 | q = queue.Queue(MAX) 6 | 7 | def bfs(x): 8 | visited.append(x) 9 | print(x) 10 | q.put(x) 11 | while q.empty() == False: 12 | s = q.get() 13 | children = adj.get(s) 14 | if children != None: 15 | if isinstance(children,int): # Case : values are not a set 16 | if children in visited: 17 | continue 18 | visited.append(children) 19 | print(children) 20 | q.put(children) 21 | else : # Case : values are a set 22 | for i in children: 23 | if i in visited: 24 | continue 25 | visited.append(i) 26 | print(i) 27 | q.put(i) 28 | 29 | 30 | def test(): 31 | global visited 32 | print("bfs : ") 33 | visited = [] 34 | bfs(1) 35 | 36 | test() -------------------------------------------------------------------------------- /Graphs/DFS/C++/DFS.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * adikul30 3 | * Aditya Kulkarni 4 | */ 5 | #include 6 | 7 | using namespace std; 8 | 9 | #define REP(i, a, b) for(int i = a; i < b; ++i) 10 | #define pb push_back 11 | #define MAX 100 12 | 13 | typedef vector vi; 14 | 15 | bool visited[MAX]; 16 | vi adj[MAX]; 17 | 18 | void dfs(int s){ 19 | if (visited[s]) return; 20 | visited[s] = true; 21 | cout << s << endl; 22 | for (auto u : adj[s]){ 23 | dfs(u); 24 | } 25 | } 26 | 27 | int main() 28 | { 29 | ios_base::sync_with_stdio(0); 30 | int n = 5; 31 | REP(i,1,n+1) visited[i] = false; 32 | adj[1].pb(2); 33 | adj[1].pb(3); 34 | adj[1].pb(5); 35 | adj[2].pb(3); 36 | adj[3].pb(4); 37 | dfs(1); 38 | 39 | return 0; 40 | } -------------------------------------------------------------------------------- /Graphs/DFS/Python/dfs.py: -------------------------------------------------------------------------------- 1 | import queue 2 | visited = [] 3 | MAX = 20 4 | adj = {1: set([2,3,5]), 2: set([3]), 3: set([8,4]), 4:6} 5 | q = queue.Queue(MAX) 6 | 7 | def dfs(s): 8 | if s in visited : 9 | return 10 | visited.append(s) 11 | print(s) 12 | children = adj.get(s) 13 | if children != None: 14 | if isinstance(children,int): # Case : values are not a set 15 | dfs(children) 16 | else : # Case : values are a set 17 | for i in children: 18 | dfs(i) 19 | return 20 | 21 | def test(): 22 | global visited 23 | visited = [] 24 | print("dfs : ") 25 | dfs(1) 26 | 27 | test() -------------------------------------------------------------------------------- /Graphs/c++/bellman_ford.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | vector > graph; // directed graph 9 | map s_path; // nodes with their distances from source 10 | 11 | void initialize(int,char); // initialisation of each vertex 12 | void relax(int,int,int); // relaxation of each node next to the one passed 13 | void print_path(char); // prints the distance of each vertex from source 14 | 15 | 16 | int main() 17 | { int n=4; // number of nodes in graph 18 | char s='A'; // source node 19 | bool neg_cycle=false; // determine whether negative cycle exists or not 20 | 21 | /* Define graph like below 22 | A B C D 23 | A 0 1 3 0 24 | B 0 0 2 0 25 | C 0 0 0 4 26 | D 0 0 0 0 27 | */ 28 | vector x={0, 1, 3, 0}; 29 | graph.push_back(x); 30 | x = {0, 0, 2, 0}; 31 | graph.push_back(x); 32 | x = {0, 0, 0, 4}; 33 | graph.push_back(x); 34 | x = {0, 0, 0, 0}; 35 | graph.push_back(x); 36 | 37 | initialize(n,s); 38 | for(int i=0;is_path[(char)('A'+k)]+graph[j][k]) 48 | neg_cycle=true; 49 | if(neg_cycle==true) 50 | cout<<"There exists a negative cycle...\nThus Bellman ford can't work here...!"; 51 | else 52 | print_path(s); 53 | return 0; 54 | } 55 | 56 | void initialize(int n,char s) 57 | { // make every node unvisited & mark its distance infinity 58 | for(int i=0;i((char)('A'+i),INT_MAX)); 60 | } 61 | s_path[s]=0; // mark distance for source node as 0 62 | } 63 | 64 | void relax(int i,int j,int w) 65 | { if(s_path[(char)('A'+j)]>s_path[(char)('A'+i)]+w) 66 | s_path[(char)('A'+j)]=s_path[(char)('A'+i)]+w; 67 | } 68 | 69 | void print_path(char s) 70 | { for(int i=0;i 8 | #include 9 | #include 10 | #include 11 | 12 | using namespace std; 13 | 14 | map s_path; 15 | vector unvisited; // unvisited nodes in the graph 16 | 17 | map dijkstra_shortest_path(char, vector >); 18 | void initialize(int,char); // initialisation of each vertex 19 | char find_min(); // find minimum weighted node in unvisited vector 20 | void relax(int,int,int); // relaxation of each node next to the one passed 21 | void print_path(char, map); // print shortest paths 22 | 23 | /* utility method for dijkstra's shortest path algortithm 24 | parameters: 25 | s: source node for shortest path 26 | graph: 2d array of weights along where x[i][j] is the weight of edge i->j 27 | Example graph is like below, with edges named A-E: 28 | A B C D E 29 | A 0 10 0 0 5 30 | B 0 0 1 0 2 31 | C 0 0 0 4 0 32 | D 7 0 6 0 0 33 | E 0 3 9 2 0 34 | returns: 35 | Returns map mapping minimum weight of each node from starting node 's' 36 | Example response for above graph: 37 | A : 0 38 | B : 10 39 | C : 11 40 | D : 15 41 | */ 42 | map dijkstra_shortest_path(char s, vector > graph) 43 | { int n = graph.size(); 44 | initialize(n,s); 45 | 46 | while(unvisited.size()!=0) // no unvisited node should be left 47 | { char c=find_min(); 48 | for(int i=0;i((char)('A'+i),INT_MAX)); 60 | } 61 | s_path[s]=0; // mark distance for source node as 0 62 | } 63 | 64 | char find_min() 65 | { /* c : minimum weighted node in unvisited 66 | a : weight of node c 67 | k : its index in the unvisited vector 68 | */ 69 | char c=unvisited[0]; 70 | int a=s_path.find(unvisited[0])->second,k=0; 71 | for(int i=1;isecond; 73 | if(jsecond; 75 | c=unvisited[i]; 76 | k=i; 77 | } 78 | } 79 | unvisited.erase(unvisited.begin()+k); // delete visited node 80 | return c; 81 | } 82 | 83 | void relax(int i,int j,int w) 84 | { if(s_path[(char)('A'+i)]>s_path[(char)('A'+j)]+w) 85 | s_path[(char)('A'+i)]=s_path[(char)('A'+j)]+w; 86 | } 87 | 88 | 89 | // main function 90 | int main() 91 | { 92 | int n=5; // number of nodes in graph 93 | char s='A'; // source node 94 | vector > graph; // directed graph 95 | map paths; // nodes with their distances from source 96 | 97 | /* Define graph like below 98 | A B C D E 99 | A 0 10 0 0 5 100 | B 0 0 1 0 2 101 | C 0 0 0 4 0 102 | D 7 0 6 0 0 103 | E 0 3 9 2 0 104 | */ 105 | vector x={0, 10, 0, 0, 5}; 106 | graph.push_back(x); 107 | x = {0, 0, 1, 0, 2}; 108 | graph.push_back(x); 109 | x = {0, 0, 0, 4, 0}; 110 | graph.push_back(x); 111 | x = {7, 0, 6, 0, 0}; 112 | graph.push_back(x); 113 | x = {0, 3, 9, 2, 0}; 114 | graph.push_back(x); 115 | 116 | paths = dijkstra_shortest_path(s, graph); 117 | print_path(s, paths); 118 | return 0; 119 | } 120 | 121 | void print_path(char s, map s_path) 122 | { for(int i=0;i **Data Access Object Interface** - This interface defines the standard operations to be performed on a model object(s). 6 | 7 | > **Data Access Object concrete class** - This class implements above interface. This class is responsible to get data from a data source which can be database / xml or any other storage mechanism. 8 | 9 | > **Model Object or Value Object** - This object is simple POJO containing get/set methods to store data retrieved using DAO class. 10 | 11 | We are going to create a Student object acting as a Model or Value Object.StudentDao is 12 | Data Access Object Interface.StudentDaoImpl is concrete class implementing Data Access Object Interface. 13 | DaoPatternDemo, our demo class, will use StudentDao to demonstrate the use of Data Access Object pattern. 14 | 15 | -------------------------------------------------------------------------------- /Java Design Patterns/DAO /Student.java: -------------------------------------------------------------------------------- 1 | public class Student { 2 | private String name; 3 | private int rollNo; 4 | 5 | Student(String name, int rollNo){ 6 | this.name = name; 7 | this.rollNo = rollNo; 8 | } 9 | 10 | public String getName() { 11 | return name; 12 | } 13 | 14 | public void setName(String name) { 15 | this.name = name; 16 | } 17 | 18 | public int getRollNo() { 19 | return rollNo; 20 | } 21 | 22 | public void setRollNo(int rollNo) { 23 | this.rollNo = rollNo; 24 | } 25 | } -------------------------------------------------------------------------------- /Java Design Patterns/DAO /StudentDao.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | 3 | public interface StudentDao { 4 | public List getAllStudents(); 5 | public Student getStudent(int rollNo); 6 | public void updateStudent(Student student); 7 | public void deleteStudent(Student student); 8 | } -------------------------------------------------------------------------------- /Java Design Patterns/DAO /StudentDaoImpl.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | public class StudentDaoImpl implements StudentDao { 5 | 6 | //list is working as a database 7 | List students; 8 | 9 | public StudentDaoImpl(){ 10 | students = new ArrayList(); 11 | Student student1 = new Student("Robert",0); 12 | Student student2 = new Student("John",1); 13 | students.add(student1); 14 | students.add(student2); 15 | } 16 | @Override 17 | public void deleteStudent(Student student) { 18 | students.remove(student.getRollNo()); 19 | System.out.println("Student: Roll No " + student.getRollNo() + ", deleted from database"); 20 | } 21 | 22 | //retrive list of students from the database 23 | @Override 24 | public List getAllStudents() { 25 | return students; 26 | } 27 | 28 | @Override 29 | public Student getStudent(int rollNo) { 30 | return students.get(rollNo); 31 | } 32 | 33 | @Override 34 | public void updateStudent(Student student) { 35 | students.get(student.getRollNo()).setName(student.getName()); 36 | System.out.println("Student: Roll No " + student.getRollNo() + ", updated in the database"); 37 | } 38 | } -------------------------------------------------------------------------------- /Java Design Patterns/Singleton/README.md: -------------------------------------------------------------------------------- 1 | 2 | ## Singleton 3 | 4 | Singleton Pattern is one of the Gangs of Four Design patterns 5 | and comes in the Creational Design Pattern category. 6 | From the definition, it seems to be a very simple design pattern but when it comes to implementation, 7 | it comes with a lot of implementation concerns. 8 | 9 | *Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine.* 10 | > The singleton class must provide a global access point to get the instance of the class. 11 | 12 | > Singleton pattern is used for logging, drivers objects, caching and thread pool. 13 | 14 | > Singleton design pattern is also used in other design patterns like Abstract Factory, Builder, Prototype, Facade etc. 15 | 16 | > Singleton design pattern is used in core java classes also, for example java.lang.Runtime, java.awt.Desktop. 17 | 18 | *To implement Singleton pattern, we have different approaches but all of them have following common concepts.* 19 | >Private constructor to restrict instantiation of the class from other classes. 20 | 21 | >Private static variable of the same class that is the only instance of the class. 22 | 23 | >Public static method that returns the instance of the class, this is the global access point for outer world to get the instance of the singleton class. 24 | -------------------------------------------------------------------------------- /Java Design Patterns/Singleton/Singleton.java: -------------------------------------------------------------------------------- 1 | public class SingletonClass 2 | { 3 | //static instance of SingletonClass 4 | private static SingletonClass sInstance; 5 | //unreachable constructor 6 | private SingletonClass() { 7 | 8 | } 9 | //access method to static instance of SingletonClass 10 | public static SingletonClass getInstance() 11 | { 12 | if(sInstance == null){ 13 | sInstance = new SingletonClass(); 14 | } 15 | return sInstance; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Java Design Patterns/builder /README.md: -------------------------------------------------------------------------------- 1 | ## Builder Pattern 2 | Builder pattern was introduced to solve some of the problems with Factory and Abstract Factory design patterns when the Object contains a lot of attributes. 3 | There are three major issues with Factory and Abstract Factory design patterns when the Object contains a lot of attributes. 4 | 5 | > Too Many arguments to pass from client program to the Factory class that can be error prone because most of the time, the type of arguments are same and from client side its hard to maintain the order of the argument. 6 | > Some of the parameters might be optional but in Factory pattern, we are forced to send all the parameters and optional parameters need to send as NULL. 7 | > If the object is heavy and its creation is complex, then all that complexity will be part of Factory classes that is confusing. 8 | 9 | We can solve the issues with large number of parameters by providing a constructor with required parameters and then different setter methods to set the optional parameters. The problem with this approach is that the Object state will be inconsistent until unless all the attributes are set explicitly. 10 | Builder pattern solves the issue with large number of optional parameters and inconsistent state by providing a way to build the object step-by-step and provide a method that will actually return the final Object. 11 | 12 | ## How to implement the design pattern in Java 13 | 14 | > First of all you need to create a static nested class and then copy all the arguments from the outer class to the Builder class. We should follow the naming convention and if the class name is Computer then builder class should be named as ComputerBuilder. 15 | > Java Builder class should have a public constructor with all the required attributes as parameters. 16 | > Java Builder class should have methods to set the optional parameters and it should return the same Builder object after setting the optional attribute. 17 | > The final step is to provide a build() method in the builder class that will return the Object needed by client program. For this we need to have a private constructor in the Class with Builder class as argument. 18 | -------------------------------------------------------------------------------- /Java Design Patterns/builder /builder.java: -------------------------------------------------------------------------------- 1 | 2 | class Computer { 3 | 4 | //required parameters 5 | private String HDD; 6 | private String RAM; 7 | 8 | //optional parameters 9 | private boolean isGraphicsCardEnabled; 10 | private boolean isBluetoothEnabled; 11 | public String getHDD() { 12 | return HDD; 13 | } 14 | public String getRAM() { 15 | return RAM; 16 | } 17 | public boolean isGraphicsCardEnabled() { 18 | return isGraphicsCardEnabled; 19 | } 20 | public boolean isBluetoothEnabled() { 21 | return isBluetoothEnabled; 22 | } 23 | private Computer(ComputerBuilder builder) { 24 | this.HDD=builder.HDD; 25 | this.RAM=builder.RAM; 26 | this.isGraphicsCardEnabled=builder.isGraphicsCardEnabled; 27 | this.isBluetoothEnabled=builder.isBluetoothEnabled; 28 | } 29 | 30 | //Builder Class 31 | public static class ComputerBuilder{ 32 | 33 | // required parameters 34 | private String HDD; 35 | private String RAM; 36 | 37 | // optional parameters 38 | private boolean isGraphicsCardEnabled; 39 | private boolean isBluetoothEnabled; 40 | 41 | public ComputerBuilder(String hdd, String ram){ 42 | this.HDD=hdd; 43 | this.RAM=ram; 44 | } 45 | public ComputerBuilder setGraphicsCardEnabled(boolean isGraphicsCardEnabled) { 46 | this.isGraphicsCardEnabled = isGraphicsCardEnabled; 47 | return this; 48 | } 49 | public ComputerBuilder setBluetoothEnabled(boolean isBluetoothEnabled) { 50 | this.isBluetoothEnabled = isBluetoothEnabled; 51 | return this; 52 | } 53 | public Computer build(){ 54 | return new Computer(this); 55 | } 56 | } 57 | } 58 | 59 | 60 | 61 | 62 | public class TestBuilderPattern { 63 | public static void main(String[] args) { 64 | // Using builder to get the object in a single line of code and 65 | // without any inconsistent state or arguments management issues 66 | Computer comp = new Computer.ComputerBuilder( 67 | "500 GB", "2 GB").setBluetoothEnabled(true) 68 | .setGraphicsCardEnabled(true).build(); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Asiatik 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /LL.java: -------------------------------------------------------------------------------- 1 | class Node 2 | { 3 | private int data; 4 | public Node next; 5 | 6 | 7 | public Node(int data) 8 | { 9 | this.data=data; 10 | this.next=null; 11 | } 12 | public int getData() 13 | { 14 | return this.data; 15 | } 16 | } 17 | 18 | class LinkedList 19 | { 20 | private Node head; 21 | private Node tail; 22 | public int size; 23 | 24 | public LinkedList() 25 | { 26 | head=null; 27 | tail=null; 28 | size=0; 29 | } 30 | 31 | public boolean isEmpty() 32 | { 33 | return head==tail; 34 | } 35 | 36 | public int getSize() 37 | { 38 | return size; 39 | } 40 | 41 | public void insertAtStart(int val) 42 | { 43 | Node newNode = new Node(val); 44 | size++ ; 45 | if(head == null) 46 | { 47 | head = newNode; 48 | tail = head; 49 | } 50 | else 51 | { 52 | newNode.next=head; 53 | head=newNode; 54 | } 55 | } 56 | 57 | public void insertAtLast(int val) 58 | { 59 | Node newNode=new Node(val); 60 | size++; 61 | if(head==null) 62 | { 63 | head=newNode; 64 | tail=newNode; 65 | } 66 | else 67 | { 68 | tail.next=newNode; 69 | tail=newNode; 70 | } 71 | } 72 | public void insertAtPos(int val, int pos) 73 | { 74 | Node newNode= new Node(val); 75 | Node temp=head; 76 | pos=pos-1; 77 | for(int i=0;i Predict(vector x, pair model){ 8 | int numDataPoints = x.size(); 9 | vector predictions(numDataPoints); 10 | 11 | for(int i = 0; i < numDataPoints; ++i){ 12 | predictions[i] = x[i] * model.first + model.second; 13 | } 14 | 15 | return predictions; 16 | } 17 | 18 | // Performs the gradient step. 19 | pair BatchGradientDecentStep(vector predictions, vector y, double learningRate, pair model){ 20 | int numSamples = y.size(); 21 | double gradientX = 0.0; 22 | double gradientY = 0.0; 23 | 24 | for(int k = 0; k < numSamples; ++k){ 25 | double error = y[k] - predictions[k]; 26 | gradientX += ((-2.0) / (double) numSamples) * error * y[k]; 27 | gradientY += ((-2.0) / (double) numSamples) * error; 28 | } 29 | 30 | model.first = model.first - (learningRate * gradientX); 31 | model.second = model.second - (learningRate * gradientY); 32 | 33 | return model; 34 | } 35 | 36 | // Runs through all the epchs updating the model based on the calculated gradient. 37 | pair LinearRegression(vector x, vector y, unsigned int epochs, double learningRate){ 38 | // Initialize our linear regression model as: 0x + 0. 39 | pair model(0, 0); 40 | 41 | for(int i = 0; i < epochs; ++i){ 42 | auto predictions = Predict(x, model); 43 | model = BatchGradientDecentStep(predictions, y, learningRate, model); 44 | } 45 | 46 | return model; 47 | } 48 | 49 | int main(){ 50 | // Define the x range for data generation. 51 | // Note, larger data values might cause exploding gradients. 52 | // One possible solution is to reduce the learning rate. 53 | pair range = pair(0,100); 54 | 55 | // Get data from the following linear function: 2x + 5. 56 | pair, vector> data = GetLinearFunctionData(range, 2, 5); 57 | vector xData = data.first; 58 | vector yData = data.second; 59 | 60 | // Run for 10000 epochs with a learning rate of 0.0001. 61 | pair model = LinearRegression(xData, yData, 10000, 0.0001); 62 | auto predictions = Predict(xData, model); 63 | 64 | cout << "Data generating function: 2x + 5" << endl; 65 | // Mean squared error: 2.37223. 66 | cout << "Mean squared error: " << MSE(yData, predictions) << endl; 67 | // Learned model: 2.04665x + 1.94324. 68 | cout << "Learned model: " << model.first << "x + " << model.second << endl; 69 | 70 | return 0; 71 | } -------------------------------------------------------------------------------- /Machine Learning/Gradient Descent/C++/Utility.h: -------------------------------------------------------------------------------- 1 | 2 | /* Header-only utility functions used for gradient descent */ 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | using namespace std; 11 | using namespace boost; 12 | 13 | // Generating data from a linear function. 14 | pair, vector> GetLinearFunctionData(pair range, double x, double yIntercept){ 15 | vector xData(range.second); 16 | vector yData(range.second); 17 | int numSamples = range.second - range.first; 18 | 19 | for(int i = range.first, k = 0; i < range.second, k < numSamples; ++i, ++k){ 20 | xData[k] = i; 21 | yData[k] = i * x + yIntercept; 22 | } 23 | 24 | pair, vector> data(xData, yData); 25 | return data; 26 | } 27 | 28 | // Sum of squared erros. 29 | double MSE(vector actual, vector predicted){ 30 | auto actualItt = actual.begin(); 31 | auto predictedItt = predicted.begin(); 32 | double sum = 0; 33 | for( ; actualItt != actual.end(), predictedItt != predicted.end(); ++actualItt, ++predictedItt){ 34 | sum += pow(*actualItt - *predictedItt, 2); 35 | } 36 | return sum/actual.size(); 37 | } -------------------------------------------------------------------------------- /Machine Learning/Gradient Descent/README.md: -------------------------------------------------------------------------------- 1 | 2 | # Gradient Descent Optimisation Algorithm 3 | 4 | This explanation of the algorithm will not go into details with the mathematics, however, it is an important part but it is better explained online and in books. Instead, the focus is more on a high-level explanation of the algorithm. 5 | 6 | Gradient descent is a mathematical optimization algorithm. It is essentially a hill-climbing algorithm that follows the gradient of the function being optimized in order to search for optimal values. It is called gradient descent because we minimize a function by incrementally following the gradient towards a local minimum. And it is often used when training machine learning models. 7 | 8 | A gradient is basically the derivative for multi-variable functions, but it is a vector rather than a scaler. The gradient vector encapsulates the partial derivatives of a multi-variable function with respect to its parameters. The gradient of a function with respect to its input tells us something about how it behaves when we change the input, and for gradient descent we exploit a property, that is, the gradient vector points towards the steepest ascent. Hence, minimizing a function in iterations is simply calculating the gradient and moving in the opposite direction. 9 | 10 | Practically, we derive the partial derivative of our error function with respect to our model parameters, calculate the partial derivative for each weight and incrementally update each parameter in the opposite sign of the corresponding partial derivative. 11 | 12 | ## Pseudocode 13 | Where lr is the learning rate, epochs is the number of iterations, and w are the model parameters. 14 | 15 | for i to num_epochs: 16 | for w_i in w: 17 | w_i = w_i - lr * partial_derivative(loss, w_i) 18 | -------------------------------------------------------------------------------- /Maths/Euclidean Algorithm/C++/GCD.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | //Using template here to support both long and ints. 4 | template 5 | integer gcd(integer a, integer b) 6 | { 7 | if (a == 0 || b == 0) 8 | { 9 | return a + b; 10 | } 11 | return gcd(b, b % a); 12 | } 13 | 14 | int main( int argv,char* argc[] ) 15 | { 16 | std::cout << gcd (100,10) << std::endl; 17 | std::cout << gcd (-100,10) << std::endl; 18 | std::cout << gcd (3,1) << std::endl; 19 | std::cout << gcd(3L,1L); 20 | } 21 | -------------------------------------------------------------------------------- /Maths/Euclidean Algorithm/C/GCD.c: -------------------------------------------------------------------------------- 1 | #include "stdio.h" 2 | 3 | //You should probably function overload to support longs as well. 4 | int gcd(int a, int b) 5 | { 6 | if (a==0 || b==0) 7 | { 8 | return a + b; 9 | } 10 | return gcd(b, b % a); 11 | } 12 | 13 | int main(int argc, char* argv[]) 14 | { 15 | printf("%d\n%d\n%d",gcd(100,10),gcd(100,-10),gcd(3,7)); 16 | } 17 | -------------------------------------------------------------------------------- /Maths/Euclidean Algorithm/Java/GCD.java: -------------------------------------------------------------------------------- 1 | public class GCD{ 2 | 3 | public static int gcd(int a, int b){ 4 | if ( a==0 || b==0){ 5 | return a+b; 6 | } 7 | return gcd(b, b % a) 8 | } 9 | 10 | public static void main(String args[]){ 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Maths/Euclidean Algorithm/Python/GCD.py: -------------------------------------------------------------------------------- 1 | #Using python3 2 | def gcd(a, b): 3 | if a == 0 or b == 0: 4 | return a + b 5 | return gcd(b, a % b) 6 | 7 | if __name__=='__main__': 8 | print (gcd(10,100)) 9 | print (gcd(9,145)) 10 | -------------------------------------------------------------------------------- /Maths/Euclidean Algorithm/README.md: -------------------------------------------------------------------------------- 1 | # Euclidean Algorithm 2 | 3 | [Wikipedia Entry](https://en.wikipedia.org/wiki/Euclidean_algorithm) 4 | 5 | This is one of the fastest method for finding the greatest common divisior between two numbers. 6 | 7 | 8 | ## Pseudocode 9 | 10 | function gcd(a, b) 11 | while b ≠ 0 12 | t := b; 13 | b := a mod b; 14 | a := t; 15 | return a; 16 | -------------------------------------------------------------------------------- /Maths/Factorial/C#/Factorial.cs: -------------------------------------------------------------------------------- 1 |  class Factorial 2 | { 3 | public static long factorial(int inputNum) 4 | { 5 | if (inputNum == 1) 6 | { 7 | return 1; 8 | } 9 | else 10 | { 11 | return inputNum * factorial(inputNum - 1); 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /Maths/Factorial/C++/factorial.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | template 3 | T factorial(T n); 4 | 5 | int main(int argv, char * argc[]) { 6 | 7 | std :: cout << factorial(5) << std :: endl; 8 | return 0; 9 | } 10 | template 11 | T factorial(T n) { 12 | if(n == 1) { 13 | return 1; 14 | } 15 | else { 16 | return n * factorial(n-1); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Maths/Factorial/C/factorial.c: -------------------------------------------------------------------------------- 1 | #include "stdio.h" 2 | 3 | 4 | long long factorial(long long n) { 5 | if(n == 1) { 6 | return 1; 7 | } 8 | else { 9 | return n * factorial(n-1); 10 | } 11 | } 12 | 13 | int main(int argc, char * argv[]) { 14 | printf("Enter a number"); 15 | scanf("%d",&n); 16 | } 17 | -------------------------------------------------------------------------------- /Maths/Factorial/Java/Factorial.java: -------------------------------------------------------------------------------- 1 | public class Factorial { 2 | public static long factorial(int n) { 3 | if(n == 1) { 4 | return 1; 5 | } 6 | else { 7 | return n * factorial(n-1); 8 | } 9 | } 10 | public static void main(String [] argv) { 11 | System.out.println(factorial(5)); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Maths/Factorial/Python/factorial.py: -------------------------------------------------------------------------------- 1 | def factorial(n): 2 | if(n == 1): 3 | return 1 4 | else: 5 | return n * factorial(n-1) 6 | 7 | if __name__ == "__main__": 8 | print(factorial(5)) 9 | -------------------------------------------------------------------------------- /Maths/Factorial/README.md: -------------------------------------------------------------------------------- 1 | # Factorial Algoritm 2 | 3 | Recursive Algorithm to calculate the factorial of a number. 4 | 5 | [Wikipedia Link](https://en.wikipedia.org/wiki/Factorial) 6 | 7 | ## Pseudocode 8 | 9 | ``` 10 | function factorial(n) 11 | if(n = 1) 12 | return 1 13 | else 14 | return n * factorial(n-1) 15 | ``` 16 | -------------------------------------------------------------------------------- /Maths/Fibonacci/C++/Fibonacci.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | void fibonacci(int number) 6 | { 7 | int first = 0, second = 1, next; 8 | 9 | for (int i = 0; i < number; i++) 10 | { 11 | cout << "\n" << first; 12 | next = first + second; 13 | first = second; 14 | second = next; 15 | } 16 | } 17 | 18 | int main() 19 | { 20 | int number; 21 | 22 | cout << "Enter number of terms for Series: "; 23 | cin >> number; 24 | 25 | cout << "Fibonacci Series are: \n"; 26 | fibonacci(number); 27 | } 28 | -------------------------------------------------------------------------------- /Maths/Fibonacci/Python/Fibonacci_series.txt: -------------------------------------------------------------------------------- 1 | # Program to display the Fibonacci sequence up to n-th term where n is provided by the user 2 | 3 | # change this value for a different result 4 | nterms = int (input("enter the no. of terms " )) 5 | 6 | # uncomment to take input from the user 7 | #nterms = int(input("How many terms? ")) 8 | 9 | # first two terms 10 | n1 = 0 11 | n2 = 1 12 | count = 0 13 | 14 | # check if the number of terms is valid 15 | if nterms <= 0: 16 | print("Please enter a positive integer") 17 | elif nterms == 1: 18 | print("Fibonacci sequence upto",nterms,":") 19 | print(n1) 20 | else: 21 | print("Fibonacci sequence upto",nterms,":") 22 | while count < nterms: 23 | print(n1,end=' , ') 24 | nth = n1 + n2 25 | # update values 26 | n1 = n2 27 | n2 = nth 28 | count += 1 29 | -------------------------------------------------------------------------------- /Maths/Fibonacci/Python/fibonacci.py: -------------------------------------------------------------------------------- 1 | """ 2 | A function to calculate fibonacci of x. 3 | Starting value of fib(0) = 0 4 | {0, 1, 1, 2, 3, 5, 8, 13, ...} 5 | """ 6 | 7 | def fibonacci(x): 8 | if (x <= 0): 9 | return 0 10 | elif (x == 1): 11 | return 1 12 | 13 | a = 0 14 | b = 1 15 | c = 1 16 | 17 | for i in range(2, x): 18 | a = b 19 | b = c 20 | c = a + b 21 | return c 22 | 23 | if __name__ == "__main__": 24 | assert(fibonacci(-1) == 0) 25 | assert(fibonacci(0) == 0) 26 | assert(fibonacci(1) == 1) 27 | assert(fibonacci(2) == 1) 28 | assert(fibonacci(3) == 2) 29 | assert(fibonacci(4) == 3) 30 | assert(fibonacci(5) == 5) 31 | assert(fibonacci(46) == 1836311903) 32 | assert(fibonacci(47) == 2971215073) 33 | assert(fibonacci(300) == 222232244629420445529739893461909967206666939096499764990979600) 34 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # codezilla 2 | 3 | [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT) 4 | [![Gitter](https://img.shields.io/gitter/room/DAVFoundation/DAV-Contributors.svg?)](https://gitter.im/asiatik-open/codezilla) 5 | 6 | codezilla 🦖 One giant collection of algorithms & design patterns. 7 | 8 | > The pandora box of algorithms and data structures 9 | 10 | Feel free to contribute. Create an issue, let others know which algorithm/data structure you are planning to add. Fork the repo. And make a PR! 11 | 12 | > The goal is to create a codebase for developers to access. Later we aim to develop extensions using this codebase to support multiple IDEs. 13 | 14 | 15 | ## How To Contribute to This Project 16 | Here are 3 quick and painless steps to contribute to this project: 17 | 18 | __Star this repository to show your support for Asiatik__ 19 | 20 | * Add a a program to implement an algorithm in any language. 21 | To do so, first create an issue with the task you are doing, for example: "Issue - creating bubble sort in C". Create a pull request in response to that issue and finally submit it for review. 22 | 23 | * Name your branch Like `#23 Add Bubble Sort in C`. 24 | 25 | Also create a directory for any new algorithm if it doesn't exist. 26 | eg. `observable_pattern`, `bubble_sort`. 27 | Inside these directories you can create a folder for the programming language you want to add. And finally add your own file named `program_name.language_extension` (`bubble_sort.cpp`) 28 | Create a commit of the form - fixes #(issue_number) 29 | 30 | Make sure you adhere to the algorithm/language/file folder structure while adding code. 31 | 32 | __Easiest way (Recommended)__ ⭐️ -You can run `bash runme.bh` on your terminal to make the appropriate file structure 33 | 34 | Additionally we recommend using standard convention for your language such as indentation and variable naming while writing the algorithm. Useful comments will be a help. Finally, if you can write tests for you code, we urge you to do so. 35 | 36 | * Finally, wait for it to be merged! 37 | 38 | ## Getting Started 39 | * Fork this repository (Click the Fork button in the top right of this page, click your Profile Image) 40 | * Clone your fork down to your local machine 41 | 42 | ```sh 43 | $ git clone https://github.com/Username/codezilla.git 44 | ``` 45 | For e.g:- 46 | ```sh 47 | $ git clone https://github.com/Anujg935/codezilla.git 48 | ``` 49 | in the above example Anujg935 is the username of the user who is forking the repository. 50 | 51 | 52 | * Create a branch 53 | 54 | ```sh 55 | $ git checkout -b branch-name 56 | ``` 57 | 58 | * Make your changes 59 | 60 | * Commit and Push 61 | 62 | ```sh 63 | $ git add filename 64 | $ git commit -m 'commit message' 65 | $ git push origin branch-name 66 | ``` 67 | 68 | * Create a New Pull Request from your forked repository (Click the New Pull Request button located at the top of your repo) 69 | * Wait for your PR review and merge approval! 70 | 71 | __Star this repository to show your support for Asiatik__ 72 | 73 | Don't forget to include the comments as seen above. Feel free to include additional information about the language you chose in your comments too! Like a link to a helpful introduction or tutorial. 74 | 75 | ## Reference Links 76 | * [Tutorial: Creating your first pull request](https://github.com/Roshanjossey/first-contributions) 77 | 78 | * [Managing your Forked Repo](https://help.github.com/articles/fork-a-repo/) 79 | 80 | * [Syncing a Fork](https://help.github.com/articles/syncing-a-fork/) 81 | 82 | * [Keep Your Fork Synced](https://gist.github.com/CristinaSolana/1885435) 83 | 84 | * [Awesome README examples ![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/sindresorhus/awesome) 85 | 86 | * [Github-Flavored Markdown](https://guides.github.com/features/mastering-markdown/) 87 | 88 | ## Additional References Added By Contributors 89 | 90 | * [GitHub license explained](https://choosealicense.com) 91 | 92 | -------------------------------------------------------------------------------- /Searching/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Asiatik/codezilla/9d870af843d0143daf7ec39aa7df4ef922cb4c3d/Searching/.gitkeep -------------------------------------------------------------------------------- /Searching/Binary Search/C++/BinarySearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | /* 4 | * Binary search algorithm 5 | * This is the exact implementation of the pseudocode written in README. 6 | * Notice that even if the array list contains multiple items, 7 | * it will return only one index. 8 | * Thus this algorithm is well suited to find if a item is present. 9 | * And not for finding the exact index if multiple items are present. 10 | * 11 | * With C++ you have to be careful of integer overflows. 12 | * So we must make sure that the length of itemList is below that of int. 13 | * Also the size of the array must also be sent. 14 | */ 15 | 16 | //Notice that itemList is passed as a pointer here. No expensive copying takes place. 17 | int binarySearch(int itemList[],int itemListSize,int item) 18 | { 19 | int leftIndex = 0; 20 | int rightIndex = itemListSize; 21 | int middleIndex; 22 | while (leftIndex < rightIndex) 23 | { 24 | middleIndex = (leftIndex+rightIndex)/2; 25 | if (itemList[middleIndex] < item) 26 | { 27 | leftIndex = middleIndex + 1; 28 | } 29 | else if(itemList[middleIndex] > item) 30 | { 31 | rightIndex = middleIndex - 1; 32 | } 33 | else{ 34 | return middleIndex; 35 | } 36 | } 37 | return -1; 38 | 39 | } 40 | 41 | //Simple demonstration for the algorithm 42 | int main(int argc,char* argv[]) 43 | { 44 | int arr[] = {1,2,3,4,5}; 45 | std::cout << binarySearch(arr,sizeof(arr)/sizeof(arr[0]),3) << std::endl; 46 | std::cout << binarySearch(arr,sizeof(arr)/sizeof(arr[0]),0); 47 | 48 | } 49 | -------------------------------------------------------------------------------- /Searching/Binary Search/C/BinarySearch.c: -------------------------------------------------------------------------------- 1 | #include "stdio.h" 2 | 3 | /* 4 | * Binary search algorithm 5 | * This is the exact implementation of the pseudocode written in README. 6 | * Notice that even if the array list contains multiple items, 7 | * it will return only one index. 8 | * Thus this algorithm is well suited to find if a item is present. 9 | * And not for finding the exact index if multiple items are present. 10 | * 11 | * With C you have to be careful of integer overflows. 12 | * So we must make sure that the length of itemList is below that of int. 13 | * Also the size of the array must also be sent. 14 | */ 15 | 16 | //Notice that itemList is passed as a pointer. No expensive copying takes place. 17 | int binarySearch(int itemList[],int itemListSize,int item) 18 | { 19 | int leftIndex = 0; 20 | int rightIndex = itemListSize; 21 | int middleIndex; 22 | while (leftIndex < rightIndex) 23 | { 24 | middleIndex = (leftIndex+rightIndex)/2; 25 | if (itemList[middleIndex] < item) 26 | { 27 | leftIndex = middleIndex + 1; 28 | } 29 | else if(itemList[middleIndex] > item) 30 | { 31 | rightIndex = middleIndex - 1; 32 | } 33 | else{ 34 | return middleIndex; 35 | } 36 | } 37 | return -1; 38 | 39 | } 40 | 41 | //Simple demonstration for the algorithm 42 | int main(int argc,char* argv[]) 43 | { 44 | int arr[] = {1,2,3,4,5}; 45 | printf("%d",binarySearch(arr,sizeof(arr)/sizeof(arr[0]),3)); 46 | printf("%d",binarySearch(arr,sizeof(arr)/sizeof(arr[0]),0)); 47 | 48 | } 49 | -------------------------------------------------------------------------------- /Searching/Binary Search/Java/BinarySearch.java: -------------------------------------------------------------------------------- 1 | public class BinarySearch{ 2 | 3 | /** 4 | * Binary search algorithm 5 | * This is the exact implementation of the pseudocode written in README. 6 | * Notice that even if the array list contains multiple items, 7 | * it will return only one index. 8 | * Thus this algorithm is well suited to find if a item is present. 9 | * And not for finding the exact index if multiple items are present. 10 | * 11 | * With java you have to be careful of integer overflows. 12 | * So we must make sure that the length of itemList is below that of int. 13 | * 14 | * @param itemList List of all the sorted items 15 | * @param item The item to search for 16 | * @return Index of the item 17 | */ 18 | public static int binarySearch(int itemList[],int item){ 19 | int leftIndex=0; 20 | int rightIndex=itemList.length-1; 21 | int middleIndex; 22 | 23 | while(leftIndex<=rightIndex){ 24 | middleIndex=(leftIndex+rightIndex)/2; 25 | 26 | if(itemList[middleIndex]item){ 30 | rightIndex=middleIndex-1; 31 | } 32 | else{ 33 | return middleIndex; 34 | } 35 | } 36 | return -1; 37 | } 38 | 39 | //Simple desmonstration of the function 40 | public static void main(String args[]){ 41 | System.out.println(binarySearch(new int[]{1,2,3,4,5},6)); 42 | System.out.println(binarySearch(new int[]{1,2,3,4,5},3)); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Searching/Binary Search/Javascript/BinarySearch.js: -------------------------------------------------------------------------------- 1 | /** Binary search algorithm in Javascript **/ 2 | /** Follows the README.md **/ 3 | 4 | function binarySearch(array, target) { 5 | let leftIndex = 0; 6 | let rightIndex = array.length - 1; 7 | let middleIndex; 8 | 9 | while (leftIndex <= rightIndex) { 10 | middleIndex = leftIndex + Math.floor((rightIndex - leftIndex) / 2); 11 | if (array[middleIndex] === target) { 12 | return middleIndex; 13 | } 14 | if (arr[middleIndex] < target) { 15 | leftIndex = middleIndex + 1; 16 | } else { 17 | rightIndex = middleIndex - 1; 18 | } 19 | } 20 | return -1; 21 | } -------------------------------------------------------------------------------- /Searching/Binary Search/Kotlin/BinarySearch.kt: -------------------------------------------------------------------------------- 1 | object BinarySearch { 2 | /** 3 | * Binary search algorithm using kotlin 4 | * @param elements List of all the sorted elements 5 | * @param data The data to search for 6 | * @return Index (item location in elements array) of search data item 7 | * if the item is not found then it will return -1 8 | */ 9 | fun binarySearch(elements: IntArray, data: Int): Int { 10 | var leftIndex = 0 11 | var rightIndex = elements.size - 1 12 | var midIndex: Int 13 | 14 | while (leftIndex <= rightIndex) { 15 | midIndex = (leftIndex + rightIndex) / 2 16 | 17 | if (elements[midIndex] < data) { 18 | leftIndex = midIndex + 1 19 | } else if (elements[midIndex] > data) { 20 | rightIndex = midIndex - 1 21 | } else { 22 | return midIndex 23 | } 24 | } 25 | return -1 26 | } 27 | 28 | @JvmStatic 29 | fun main(args: Array) { 30 | // sample input with data item which is not in the array of elements 31 | println(binarySearch(intArrayOf(10, 11, 12, 13, 15, 16), 20)) 32 | // sample input with data item which is present in the array of elements 33 | println(binarySearch(intArrayOf(100, 102, 103, 105, 106), 105)) 34 | } 35 | } -------------------------------------------------------------------------------- /Searching/Binary Search/PHP/BinarySearch.php: -------------------------------------------------------------------------------- 1 | $item){ 14 | $rightIndex = $middleIndex - 1; 15 | } 16 | else{ 17 | return $middleIndex; 18 | } 19 | } 20 | return -1; 21 | } 22 | 23 | // Simple demonstration of the function 24 | $array = array(1, 2, 4, 5, 6, 8, 9, 10, 14); 25 | echo binarySearch($array, 8); 26 | ?> 27 | -------------------------------------------------------------------------------- /Searching/Binary Search/Python/BinarySearch.py: -------------------------------------------------------------------------------- 1 | """ 2 | This is a simple binary search algorithm for python. 3 | This is the exact implementation of the pseudocode written in README. 4 | """ 5 | 6 | def binary_search(item_list,item): 7 | left_index = 0 8 | right_index = len(item_list)-1 9 | 10 | while left_index <= right_index: 11 | middle_index = (left_index+right_index) // 2 12 | if item_list[middle_index] < item: 13 | left_index=middle_index+1 14 | elif item_list[middle_index] > item: 15 | right_index=middle_index-1 16 | else: 17 | return middle_index 18 | return None 19 | 20 | #Simple demonstration of the function 21 | if __name__=='__main__': 22 | print (binary_search([1,3,5,7],3)) 23 | print (binary_search([1,2,5,7,97],0)) 24 | -------------------------------------------------------------------------------- /Searching/Binary Search/README.md: -------------------------------------------------------------------------------- 1 | # Binary Search 2 | 3 | >Worst Case Time Complexity: O(log n) 4 | >Best Case Time Complexity: O(1) 5 | 6 | >Space Complexity: (O(1)) 7 | 8 | [Wikipedia Entry](https://en.wikipedia.org/wiki/Binary_search_algorithm) 9 | 10 | ## Pseudocode 11 | 12 | A is the array, n is the size of array and T is the item 13 | 14 | 15 | function binary_search(A, n, T): 16 | L := 0 17 | R := n − 1 18 | 19 | while L <= R: 20 | m := floor((L + R) / 2) 21 | if A[m] < T: 22 | L := m + 1 23 | else if A[m] > T: 24 | R := m - 1 25 | else: 26 | return m 27 | return unsuccessful 28 | 29 | Notice that even if the array list contains multiple items, it will return only one index. 30 | Thus this algorithm is well suited to find if a item is present. 31 | And not for finding the exact index if multiple items are present. 32 | 33 | Binary search can also be obtain the indexes of the items present. 34 | And unlike the version here which works on numbers, binary search can work on any sorted array. For example binary search can be used in lexiographically arranged strings. 35 | -------------------------------------------------------------------------------- /Searching/Linear Search/C++/LinearSearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | /** 4 | * Linear search algorithm 5 | * This is the exact implementation of the pseudocode written in README. 6 | * Notice that even if the array list contains multiple items, 7 | * it will return only one index. 8 | * Thus this algorithm is well suited to find if a item is present. 9 | * And not for finding the exact index if multiple items are present. 10 | * With C++ you have to be careful of integer overflows. 11 | * So we must make sure that the length of itemList is below that of int. 12 | */ 13 | 14 | //Notice that itemList is passed by pointer. No unnecessary copy takes place. 15 | int linearSearch(int itemList[],int itemListSize,int item) 16 | { 17 | int index=0; 18 | while (index < itemListSize) 19 | { 20 | if (itemList[index] == item) 21 | { 22 | return index; 23 | } 24 | index++; 25 | } 26 | return -1; 27 | 28 | } 29 | 30 | //Simple demonstration for the algorithm 31 | int main(int argc,char* argv[]) 32 | { 33 | int arr[] = {1,2,3,4,5}; 34 | std::cout << linearSearch(arr,sizeof(arr)/sizeof(arr[0]),3) << std::endl; 35 | std::cout << linearSearch(arr,sizeof(arr)/sizeof(arr[0]),0); 36 | 37 | } 38 | -------------------------------------------------------------------------------- /Searching/Linear Search/C/LinearSearch.c: -------------------------------------------------------------------------------- 1 | #include "stdio.h" 2 | 3 | int linearSearch(int itemList[],int itemListSize,int item) 4 | { 5 | int index=0; 6 | while (index < itemListSize) 7 | { 8 | if (itemList[index] == item) 9 | { 10 | return index; 11 | } 12 | index++; 13 | } 14 | return -1; 15 | 16 | } 17 | //Simple demonstration for the algorithm 18 | int main(int argc,char* argv[]) 19 | { 20 | int arr[] = {1,2,3,4,5}; 21 | printf("%d\n",linearSearch(arr,sizeof(arr)/sizeof(arr[0]),3)); 22 | printf("%d",linearSearch(arr,sizeof(arr)/sizeof(arr[0]),0)); 23 | 24 | } 25 | -------------------------------------------------------------------------------- /Searching/Linear Search/Java/LinearSearch.java: -------------------------------------------------------------------------------- 1 | public class LinearSearch{ 2 | 3 | /** 4 | * Linear search algorithm 5 | * This is the exact implementation of the pseudocode written in README. 6 | * Notice that even if the array list contains multiple items, 7 | * it will return only one index. 8 | * Thus this algorithm is well suited to find if a item is present. 9 | * And not for finding the exact index if multiple items are present. 10 | * 11 | * With java you have to be careful of integer overflows. 12 | * So we must make sure that the length of itemList is below that of int. 13 | * 14 | * @param itemList List of all the sorted items 15 | * @param item The item to search for 16 | * @return Index of the item 17 | */ 18 | import java.util.Scanner; 19 | public static int linearSearch(int[] itemList,int item) 20 | { 21 | int index=0; 22 | while ( index < itemList.length ) 23 | { 24 | if ( itemList[index] == item ) 25 | { 26 | return index; 27 | } 28 | index++; 29 | } 30 | return -1; 31 | } 32 | 33 | //Simple desmonstration of the function 34 | public static void main(String args[]) 35 | { 36 | Scanner sc=new Scanner(System.in); 37 | System.out.println("Enter the total number of elements you will be entering for the search: "); 38 | int nitem=sc.nextInt(); 39 | System.out.println("Enter the integer elements into the element list: "); 40 | for(int i=0;iWorst Case Time Complexity: O(n) 4 | >Best Case Time Complexity: O(1) 5 | 6 | >Space Complexity: O(1) 7 | 8 | [Wikipedia Entry](https://en.wikipedia.org/wiki/Linear_search) 9 | 10 | ## Pseudocode 11 | 12 | A is the array, n is the size of array and T is the item 13 | 14 | 15 | function linear_search(A, n, T): 16 | i=0 17 | while i < n: 18 | if A[i] == T: 19 | return i 20 | i=i+1 21 | return unsuccessful 22 | 23 | Notice that even if the array list contains multiple items, it will return only one index. 24 | Thus this algorithm is well suited to find if a item is present. 25 | And not for finding the exact index if multiple items are present. 26 | 27 | This algorithm is rarely used since there are always better options like binary search or hash tables. 28 | -------------------------------------------------------------------------------- /Sorting/Bubble Sort/C#/BubbleSort.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace BubbleSort 4 | { 5 | class Program 6 | { 7 | static void Main(string[] args) 8 | { 9 | // declare an array of integers that are not sorted 10 | int[] nums = { 5, 10, 3, 2, 4 }; 11 | 12 | 13 | // Use this to know when to stop the sorting routine 14 | bool swapped; 15 | 16 | // Here we use a do loop but could have used for or while loops as well. 17 | do 18 | { 19 | // set swapped to false so that we can ensure at least one pass on the array 20 | swapped = false; 21 | 22 | // This loop will iterate over the array from beginning to end 23 | for (int i = 0; i < nums.Length - 1; i++) 24 | { 25 | // here we use the i for the position in the array 26 | // So i is the first value to compare and i + 1 compare the next two sets of values, etc. 27 | // Once i is incremented at the end of this loop, we compare the next two sets of values, etc. 28 | if (nums[i] > nums[i + 1]) 29 | { 30 | // swap routine. Could be a separate method as well but is used inline for simplicity here 31 | // temp is used to hold the right value in the comparison so we don't lose it. That value will be replaced in the next step 32 | int temp = nums[i + 1]; 33 | 34 | // Here we replace the right value with the large value that was on the left. See why we needed the temp variable above? 35 | nums[i + 1] = nums[i]; 36 | 37 | // Now we assign the value that is in temp, the smaller value, to the location that was just vacated by the larger number 38 | nums[i] = temp; 39 | 40 | // Indicate that we did a swap, which means we need to continue to check the remaining values. 41 | swapped = true; 42 | } 43 | } 44 | } while (swapped == true); 45 | 46 | // output the sorted array to the console 47 | 48 | Console.Write("After: "); 49 | for (int i = 0; i < nums.Length; i ++) 50 | { 51 | Console.Write("{0}, ", nums[i]); 52 | } 53 | 54 | // Use Console.ReadLine() in the event application was started with debugging. 55 | Console.ReadLine(); 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Sorting/Bubble Sort/C++/BubbleSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | int array[5]; 6 | cout<<"Enter 5 numbers : "<>array[i]; 10 | } 11 | cout<array[j+1]) 26 | { 27 | temp=array[j]; 28 | array[j]=array[j+1]; 29 | array[j+1]=temp; 30 | } 31 | } 32 | } 33 | cout<<" Sorted Array is: "< 3 | 4 | void swap(int *xp, int *yp) 5 | { 6 | int temp = *xp; 7 | *xp = *yp; 8 | *yp = temp; 9 | } 10 | 11 | void bubbleSort(int arr[], int n) 12 | { 13 | int i, j; 14 | for (i = 0; i < n-1; i++) 15 | { 16 | for (j = 0; j < n-i-1; j++) 17 | { 18 | if (arr[j] > arr[j+1]) 19 | swap(&arr[j], &arr[j+1]); 20 | } 21 | } 22 | } 23 | 24 | void printArray(int arr[], int size) 25 | { 26 | int i; 27 | for (i=0; i < size; i++) 28 | { 29 | printf("%d ", arr[i]); 30 | } 31 | printf("\n"); 32 | } 33 | 34 | int main() 35 | { 36 | int arr[] = {6, 4, 5, 8, 2, 1, 9}; 37 | int n = sizeof(arr)/sizeof(arr[0]); 38 | scanf("%d",&n); 39 | bubbleSort(arr, n); 40 | printArray(arr, n); 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /Sorting/Bubble Sort/Go/BubbleSort.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | //Test Code 7 | array := []int{1, 6, 2, 4, 9, 0, 5, 3, 7, 8} 8 | fmt.Println("Unsorted array: ", array) 9 | sort(array) 10 | fmt.Println("Sorted array: ", array) 11 | } 12 | 13 | func sort(arr []int) { 14 | for i := 0; i < len(arr); i++ { 15 | for j := 0; j < i; j++ { 16 | if arr[j] > arr[i] { 17 | swap(arr, i, j) 18 | } 19 | } 20 | } 21 | } 22 | 23 | func swap(arr []int, x, y int) { 24 | temp := arr[x] 25 | arr[x] = arr[y] 26 | arr[y] = temp 27 | } 28 | -------------------------------------------------------------------------------- /Sorting/Bubble Sort/Java/BubbleSort.java: -------------------------------------------------------------------------------- 1 | //Bubble sort Algorithm 2 | // Java program for implementation of BubbleSort 3 | import java.util.Scanner; 4 | class BubbleSort 5 | { 6 | /* Fuction Implementing Bubble Sort Algorithm */ 7 | void sort(int arr[]) 8 | { 9 | int swapped; 10 | int length = arr.length; 11 | for(int i=0; iarr[j+1]) 17 | { 18 | int temp=arr[j+1]; 19 | arr[j+1]=arr[j]; 20 | arr[j]=temp; 21 | swapped=1; 22 | } 23 | } 24 | if(swapped==0) 25 | break; 26 | } 27 | } 28 | 29 | /* A utility function to print array of size n */ 30 | static void printArray(int arr[]) 31 | { 32 | int n = arr.length; 33 | for (int i=0; i haystack[j]) { 16 | haystack[(j-1)] = haystack[j]; 17 | haystack[j] = temp; 18 | } 19 | } 20 | } 21 | 22 | return haystack; 23 | } 24 | -------------------------------------------------------------------------------- /Sorting/Bubble Sort/Python/bubblesort: -------------------------------------------------------------------------------- 1 | def bubbleSort(alist): 2 | for passnum in range(len(alist)-1,0,-1): 3 | for i in range(passnum): 4 | if alist[i]>alist[i+1]: 5 | temp = alist[i] 6 | alist[i] = alist[i+1] 7 | alist[i+1] = temp 8 | 9 | alist = [54,26,93,17,77,31,44,55,20] 10 | bubbleSort(alist) 11 | print(alist) 12 | -------------------------------------------------------------------------------- /Sorting/Counting Sort/Java/CountingSort.java: -------------------------------------------------------------------------------- 1 | public class CountingSort { 2 | 3 | private CountingSort() { } 4 | 5 | public static Integer[] sort(Integer[] unsorted) { 6 | int maxValue = findMax(unsorted); 7 | int[] counts = new int[maxValue + 1]; 8 | updateCounts(unsorted, counts); 9 | populateCounts(unsorted, counts); 10 | return unsorted; 11 | } 12 | 13 | private static int findMax(Integer[] unsorted) { 14 | int max = Integer.MIN_VALUE; 15 | for (int i : unsorted) { 16 | if (i > max) 17 | max = i; 18 | } 19 | return max; 20 | } 21 | 22 | private static void updateCounts(Integer[] unsorted, int[] counts) { 23 | for (int e : unsorted) 24 | counts[e]++; 25 | } 26 | 27 | private static void populateCounts(Integer[] unsorted, int[] counts) { 28 | int index = 0; 29 | for (int i = 0; i < counts.length; i++) { 30 | int e = counts[i]; 31 | while (e > 0) { 32 | unsorted[index++] = i; 33 | e--; 34 | } 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Sorting/Heap Sort/C++/HeapSort.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for implementation of Heap Sort using max Heap 2 | #include 3 | using namespace std; 4 | 5 | // To heapify a subtree rooted with node i which is 6 | // an index in arr[]. n is size of heap 7 | //using max heap for this implementation. 8 | //In max heap the the root node is the largest 9 | void heapify(int arr[], int n, int i) 10 | { 11 | int largest = i; // Initialize largest as root 12 | int l = 2*i + 1; // left = 2*i + 1 13 | int r = 2*i + 2; // right = 2*i + 2 14 | 15 | // If left child is larger than root 16 | if (l < n && arr[l] > arr[largest]) 17 | largest = l; 18 | 19 | // If right child is larger than largest so far 20 | if (r < n && arr[r] > arr[largest]) 21 | largest = r; 22 | 23 | // If largest is not root 24 | if (largest != i) 25 | { 26 | swap(arr[i], arr[largest]); 27 | 28 | // Recursively heapify the affected sub-tree 29 | heapify(arr, n, largest); 30 | } 31 | } 32 | 33 | // main function to do heap sort 34 | //we recursively call the heapify function in heapSort 35 | void heapSort(int arr[], int n) 36 | { 37 | // Build heap (rearrange array) 38 | for (int i = n / 2 - 1; i >= 0; i--) 39 | heapify(arr, n, i); 40 | 41 | // One by one extract an element from heap 42 | for (int i=n-1; i>=0; i--) 43 | { 44 | // Move current root to end 45 | swap(arr[0], arr[i]); 46 | 47 | // call max heapify on the reduced heap 48 | heapify(arr, i, 0); 49 | } 50 | } 51 | 52 | /* A utility function to print array of size n */ 53 | void printArray(int arr[], int n) 54 | { 55 | for (int i=0; i>size_of_arr; 71 | int arr[size_of_arr]; 72 | for(int i=0;i>arr[i]; 75 | } 76 | 77 | heapSort(arr, size_of_arr); 78 | 79 | cout << "Sorted array is \n"; 80 | printArray(arr, size_of_arr); 81 | } 82 | -------------------------------------------------------------------------------- /Sorting/Heap Sort/HeapSort.java: -------------------------------------------------------------------------------- 1 | // Java program for implementation of Heap Sort 2 | public class HeapSort 3 | { 4 | public void sort(int arr[]) 5 | { 6 | int n = arr.length; 7 | 8 | // Build heap (rearrange array) 9 | for (int i = n / 2 - 1; i >= 0; i--) 10 | heapify(arr, n, i); 11 | 12 | // One by one extract an element from heap 13 | for (int i=n-1; i>=0; i--) 14 | { 15 | // Move current root to end 16 | int temp = arr[0]; 17 | arr[0] = arr[i]; 18 | arr[i] = temp; 19 | 20 | // call max heapify on the reduced heap 21 | heapify(arr, i, 0); 22 | } 23 | } 24 | 25 | // To heapify a subtree rooted with node i which is 26 | // an index in arr[]. n is size of heap 27 | void heapify(int arr[], int n, int i) 28 | { 29 | int largest = i; // Initialize largest as root 30 | int l = 2*i + 1; // left = 2*i + 1 31 | int r = 2*i + 2; // right = 2*i + 2 32 | 33 | // If left child is larger than root 34 | if (l < n && arr[l] > arr[largest]) 35 | largest = l; 36 | 37 | // If right child is larger than largest so far 38 | if (r < n && arr[r] > arr[largest]) 39 | largest = r; 40 | 41 | // If largest is not root 42 | if (largest != i) 43 | { 44 | int swap = arr[i]; 45 | arr[i] = arr[largest]; 46 | arr[largest] = swap; 47 | 48 | // Recursively heapify the affected sub-tree 49 | heapify(arr, n, largest); 50 | } 51 | } 52 | 53 | /* A utility function to print array of size n */ 54 | static void printArray(int arr[]) 55 | { 56 | int n = arr.length; 57 | for (int i=0; i a[largest]) { 16 | largest = left; 17 | } 18 | 19 | if (right < length && a[right] > a[largest]) { 20 | largest = right; 21 | } 22 | 23 | if (i == largest) { 24 | break; 25 | } 26 | 27 | swap(a, i, largest); 28 | i = largest; 29 | } 30 | } 31 | 32 | function heapify(a, length) { 33 | for (var i = Math.floor(length/2); i >= 0; i--) { 34 | max_heapify(a, i, length); 35 | } 36 | } 37 | 38 | function heapsort(a) { 39 | heapify(a, a.length); 40 | 41 | for (var i = a.length - 1; i > 0; i--) { 42 | swap(a, i, 0); 43 | 44 | max_heapify(a, 0, i-1); 45 | } 46 | } 47 | 48 | heapsort(a); -------------------------------------------------------------------------------- /Sorting/Heap Sort/Python/HeapSort.py: -------------------------------------------------------------------------------- 1 | def heapify(arr, n, i): 2 | largest = i 3 | left = 2 * i + 1 4 | right = 2 * i + 2 5 | 6 | if left < n and arr[left] > arr[largest]: 7 | largest = left 8 | 9 | if right < n and arr[right] > arr[largest]: 10 | largest = right 11 | 12 | if largest != i: 13 | arr[i], arr[largest] = arr[largest], arr[i] 14 | heapify(arr, n, largest) 15 | 16 | 17 | def heap_sort(arr, n): 18 | for i in range(int(n / 2 - 1), -1, -1): 19 | heapify(arr, n, i) 20 | 21 | for i in range(n - 1, -1, -1): 22 | arr[0], arr[i] = arr[i], arr[0] 23 | heapify(arr, i, 0) 24 | 25 | 26 | if __name__ == '__main__': 27 | arr = [49, 35, 59, 20, 2, 4, 1, 5] 28 | 29 | heap_sort(arr, len(arr)) 30 | print(arr) 31 | 32 | -------------------------------------------------------------------------------- /Sorting/Heap Sort/Readme.md: -------------------------------------------------------------------------------- 1 | # Heap Sort 2 | Heap sort is a selection based algorithm. It has an ideia similar to Selection Sort. However, instead o search the element in a list (or array), the Heap Sort search the elements in a balanced tree computed as a Heap. 3 | The time complexiy of Heap Sort is allways O(nlogn). 4 | -------------------------------------------------------------------------------- /Sorting/Insertion Sort/C++/InsertionSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define MAX_SIZE 5 6 | 7 | using namespace std; 8 | 9 | void insertion(int[]); 10 | 11 | int main() { 12 | int arr_sort[MAX_SIZE], i; 13 | 14 | cout << "Simple C++ Insertion Sort Example - Array and Functions\n"; 15 | cout << "\nEnter " << MAX_SIZE << " Elements for Sorting : " << endl; 16 | for (i = 0; i < MAX_SIZE; i++) 17 | cin >> arr_sort[i]; 18 | 19 | cout << "\nYour Data :"; 20 | for (i = 0; i < MAX_SIZE; i++) { 21 | cout << "\t" << arr_sort[i]; 22 | } 23 | 24 | insertion(arr_sort); 25 | getch(); 26 | } 27 | 28 | void insertion(int fn_arr[]) { 29 | int i, j, a, t; 30 | for (i = 1; i < MAX_SIZE; i++) { 31 | t = fn_arr[i]; 32 | j = i - 1; 33 | 34 | while (j >= 0 && fn_arr[j] > t) { 35 | fn_arr[j + 1] = fn_arr[j]; 36 | j = j - 1; 37 | } 38 | fn_arr[j + 1] = t; 39 | 40 | cout << "\nIteration : " << i; 41 | for (a = 0; a < MAX_SIZE; a++) { 42 | cout << "\t" << fn_arr[a]; 43 | } 44 | } 45 | 46 | cout << "\n\nSorted Data :"; 47 | for (i = 0; i < MAX_SIZE; i++) { 48 | cout << "\t" << fn_arr[i]; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Sorting/Insertion Sort/Java/InsertionSort.java: -------------------------------------------------------------------------------- 1 | // insertion sort algorithm implemented in java 2 | public class InsertionSort { 3 | /* 4 | this function takes an array and assumes the first index as sorted part 5 | takes element from unsorted part and add to sorted part at appropiate position untill array is not sorted 6 | */ 7 | public void sort(int[] arr) 8 | { 9 | int size=arr.length; 10 | for (int i=1;i=0&&arr[t]>temp;t--) 15 | { 16 | arr[t+1]=arr[t]; 17 | } 18 | arr[t+1]=temp; 19 | } 20 | } 21 | // driver program 22 | public static void main(String args[]) 23 | { 24 | int arr[] = {10,1,0,11,12,20,21}; 25 | 26 | System.out.println("Given Array"); 27 | System.out.print(Arrays.toString(arr)); 28 | InsertionSort ob = new InsertionSort(); 29 | ob.sort(arr); 30 | 31 | System.out.println("\nSorted array"); 32 | System.out.print(Arrays.toString(arr)); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Sorting/Insertion Sort/Python/insertion_sort.py: -------------------------------------------------------------------------------- 1 | def insertion_sort(arr): 2 | ''' 3 | Args: Input list 4 | Returns: Sorted list 5 | ''' 6 | for i in range(1, len(arr)): 7 | key = arr[i] 8 | j = i-1 9 | # finding element greater than current value 10 | while(j>=0 and arr[j]>key): 11 | arr[j+1] = arr[j] 12 | j -= 1 13 | arr[j+1] = key 14 | 15 | return arr 16 | 17 | # Driver Program 18 | if __name__ == '__main__': 19 | arr = [5,3,9,6,1,8] 20 | arr = insertion_sort(arr) 21 | print(arr) -------------------------------------------------------------------------------- /Sorting/Insertion Sort/README.md: -------------------------------------------------------------------------------- 1 | # Insertion Sort 2 | Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort. However, insertion sort provides several advantages: 3 | - Simple implementation: Jon Bentley shows a three-line C version, and a five-line optimized version[2] 4 | - Efficient for (quite) small data sets, much like other quadratic sorting algorithms 5 | - More efficient in practice than most other simple quadratic (i.e., O(n2)) algorithms such as selection sort or bubble sort 6 | - Adaptive, i.e., efficient for data sets that are already substantially sorted: the time complexity is O(nk) when each element in the input is no more than k places away from its sorted position 7 | - Stable; i.e., does not change the relative order of elements with equal keys 8 | - In-place; i.e., only requires a constant amount O(1) of additional memory space 9 | - Online; i.e., can sort a list as it receives it 10 | # 11 | 12 | ![Insertion Sort](https://cdn.programiz.com/sites/tutorial2program/files/Insertion-Sort-Algorithm-Programming.jpg) 13 | 14 | ### Explanation 15 | Suppose, you want to sort elements in ascending as in above figure. Then: 16 | - Step 1: The second element of an array is compared with the elements that appears before it (only first element in this case). If the second element is smaller than first element, second element is inserted in the position of first element. After first step, first two elements of an array will be sorted. 17 | - Step 2: The third element of an array is compared with the elements that appears before it (first and second element). If third element is smaller than first element, it is inserted in the position of first element. If third element is larger than first element but, smaller than second element, it is inserted in the position of second element. If third element is larger than both the elements, it is kept in the position as it is. After second step, first three elements of an array will be sorted. 18 | - Step 3: Similary, the fourth element of an array is compared with the elements that appears before it (first, second and third element) and the same procedure is applied and that element is inserted in the proper position. After third step, first four elements of an array will be sorted. 19 | -------------------------------------------------------------------------------- /Sorting/Insertion Sort/Racket/InsertionSort.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | ;;insertion sort implementation 3 | (define (sort lon) 4 | (cond [(empty? lon) lon] 5 | [else (insert (first lon) (sort (rest lon)))])) 6 | 7 | (define (insert n lon) 8 | (cond [(empty? lon) (cons n lon)] 9 | [else 10 | (if (> n (first lon)) 11 | (cons (first lon) (insert n (rest lon))) 12 | (cons n lon))])) 13 | -------------------------------------------------------------------------------- /Sorting/Insertion Sort/Scala/InsertionSort.scala: -------------------------------------------------------------------------------- 1 | def insertionsort(myList: Array[Int]): Unit = { 2 | 3 | for(i <- 1 to myList.length-1){ 4 | var j = i-1 5 | var x = myList(i) 6 | 7 | while(j >= 0 && myList(j) > x){ 8 | myList(j+1) = myList(j) 9 | j = j-1 10 | } 11 | myList(j+1) = x 12 | } 13 | } 14 | 15 | 16 | var myList = Array[Int](44,2,34,9,7,5,8,3,1,5) 17 | 18 | insertionsort(myList) 19 | myList.foreach(println) 20 | -------------------------------------------------------------------------------- /Sorting/Merge Sort/C++/Arrays/MergeSortArray.cpp: -------------------------------------------------------------------------------- 1 | // This is an implemation of MergeSortArray class 2 | 3 | #include 4 | #include 5 | #include 6 | #include "MergeSortArray.h" 7 | 8 | // Uncommenet to debug the code 9 | //#define DEBUG 10 | 11 | // This is not a memober of class 12 | template 13 | void printArray(T *arr, N left, N right) { 14 | for (N i = left; i <= right; i++) { 15 | std::cout << arr[i] << " "; 16 | } 17 | std::cout << std::endl; 18 | } 19 | 20 | template 21 | MergeSortArray::MergeSortArray() { 22 | newArray = nullptr; 23 | } 24 | 25 | template 26 | void MergeSortArray::mergeSort(T* arr, N len) { 27 | newArray = new T[len]; 28 | #ifdef DEBUG 29 | std::cout << "Length: " << len << std::endl; 30 | #endif 31 | sort(arr, 0, len-1); 32 | } 33 | 34 | // left index, right index of the array to sort 35 | template 36 | void MergeSortArray::sort(T* arr, N left, N right) { 37 | if (right == left) return; 38 | // Split the array 39 | N mid = floor((left+right) / 2); 40 | 41 | #ifdef DEBUG 42 | std::cout << "Left start: " << left << " "; 43 | std::cout << "Left end: " << mid << std::endl; 44 | printArray(arr, left, mid); 45 | #endif 46 | // Call merge sort on left chunk 47 | sort(arr, left, mid); 48 | #ifdef DEBUG 49 | std::cout << "Right start: " << mid+1 << " "; 50 | std::cout << "Right end: " << right << std::endl; 51 | printArray(arr, mid+1, right); 52 | #endif 53 | // Call merge sort on right chunk 54 | sort(arr, mid+1, right); 55 | // Merge the sorted elemnts on right side 56 | mergeTheArray(arr, left, mid, right); 57 | } 58 | 59 | template 60 | void MergeSortArray::mergeTheArray(T* arr, N left, N mid, N right) { 61 | #ifdef DEBUG 62 | std::cout << "Merging the array: " << std::endl; 63 | std::cout << "Left start: " << left << " Mid: " << mid << " Right end : " << right << std::endl; 64 | #endif 65 | // Left chunk is arr[left....mid] 66 | // Right chunk is arr[mid+1....right] 67 | 68 | N k = left; 69 | N i = left; 70 | N j = mid+1; 71 | // Compare left and right chunk 72 | while (i <= mid && j <= right) { 73 | if (arr[i] > arr[j]) { 74 | newArray[k] = arr[j]; 75 | j++; 76 | } 77 | else { 78 | newArray[k] = arr[i]; 79 | i++; 80 | } 81 | k++; 82 | } 83 | // Copy the rest of the elements from left chunk if any 84 | if (i <= mid) { 85 | for (; k <= right; k++) { 86 | newArray[k] = arr[i]; 87 | i++; 88 | } 89 | } 90 | // Copy the rest of the elements from right chunk if any 91 | else if (j <= right) { 92 | for (; k <= right; k++) { 93 | newArray[k] = arr[j]; 94 | j++; 95 | } 96 | } 97 | // arr[left...right] is replaced with sorted values stored in newArray[left....right] 98 | for (k = left; k <= right; k++) { 99 | arr[k] = newArray[k]; 100 | } 101 | #ifdef DEBUG 102 | // print the sorted part 103 | printArray(arr, left, right); 104 | #endif 105 | } 106 | 107 | template 108 | MergeSortArray::~MergeSortArray() { 109 | delete[] newArray; 110 | } 111 | -------------------------------------------------------------------------------- /Sorting/Merge Sort/C++/Arrays/MergeSortArray.h: -------------------------------------------------------------------------------- 1 | #ifndef MERGESORTARRAY_H 2 | #define MERGESORTARRAY_H 3 | 4 | template 5 | class MergeSortArray { 6 | public: 7 | MergeSortArray(); 8 | void mergeSort(T* arr, N len); 9 | ~MergeSortArray(); 10 | private: 11 | void sort(T* arr, N left, N right); 12 | void mergeTheArray(T* arr, N left_start, N right_start, N right_end); 13 | // Buffer 14 | T *newArray; 15 | }; 16 | // To avoid linker error 17 | #include "MergeSortArray.cpp" 18 | 19 | #endif 20 | -------------------------------------------------------------------------------- /Sorting/Merge Sort/C++/Arrays/MergeSortArrayTest.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************************* 2 | * Instructions: 3 | * To compile: g++ MergeSort_ArrayTest.cpp -o MergeSort_ArrayTest -std=c++11 4 | * To run: ./MergeSort_ArrayTest [#elements] 5 | * Where #elements is number of elements in an array, default is 100. 6 | * Author: Mounika Ponugoti 7 | *********************************************************************************/ 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include "MergeSortArray.h" 14 | 15 | // Number of elements in an array 16 | int length = 100; 17 | 18 | // Prints the array 19 | template 20 | void printArray(T *arr, N length) { 21 | for (N i = 0; i < length; i++) { 22 | std::cout << arr[i] << " "; 23 | } 24 | std::cout << std::endl; 25 | } 26 | 27 | // Initialize the array with random values 28 | template 29 | void initializeArray(T *arr, N length) { 30 | for (N i = 0; i < length; i++) { 31 | arr[i] = static_cast (rand()) / static_cast (RAND_MAX/10); 32 | } 33 | } 34 | 35 | int main(int argc, char **argv) 36 | { 37 | if (argc == 2) { 38 | length = std::atoi(argv[1]); 39 | } 40 | if (argc > 2) { 41 | std::cout << "Usage: ./main [#elemnts]" << std::endl; 42 | exit(1); 43 | } 44 | // Seed for random number generator 45 | srand(time(NULL)); 46 | // Sorting integer Array 47 | int *arr = new int[length]; 48 | initializeArray(arr, length); 49 | std::cout << "Unsorted Array: " << std::endl; 50 | printArray(arr, length); 51 | 52 | MergeSortArray mergeSort_obj; 53 | mergeSort_obj.mergeSort(arr, length); 54 | std::cout << "Sorted Array: " << std::endl; 55 | printArray(arr, length); 56 | 57 | // Sorting floating point numbers 58 | float *arr_f = new float[length]; 59 | initializeArray(arr_f, length); 60 | std::cout << "Unsorted Array: " << std::endl; 61 | std::cout << std::fixed << std::setprecision(2); 62 | printArray(arr_f, length); 63 | 64 | MergeSortArray mergeSort_obj_2; 65 | mergeSort_obj_2.mergeSort(arr_f, length); 66 | std::cout << "Sorted Array: " << std::endl; 67 | printArray(arr_f, length); 68 | 69 | // Free the allocated memory 70 | delete[] arr; 71 | delete[] arr_f; 72 | return 0; 73 | } 74 | -------------------------------------------------------------------------------- /Sorting/Merge Sort/C++/Linked Lists/MergeSortLinkedList.h: -------------------------------------------------------------------------------- 1 | #ifndef MERGESORTLINKEDLIST_H 2 | #define MERGESORTLINKEDLIST_H 3 | 4 | // Node of a linked list 5 | template 6 | class Node { 7 | public: 8 | T val; 9 | Node* next; 10 | Node() { 11 | next = nullptr; 12 | } 13 | Node(T value) { 14 | next = nullptr; 15 | val = value; 16 | } 17 | }; 18 | 19 | template 20 | class MergeSortLinkedList { 21 | public: 22 | MergeSortLinkedList(); 23 | T2 getLength(Node* N); 24 | void insertItem(Node*& head, Node* afterNode, T1 item); 25 | void insertItem(Node*& head, T1 afterItem, T1 item); 26 | void insertItemAtEnd(Node*& head, T1 item); 27 | void deleteItemAtEnd(Node*& head); 28 | void deleteItem(Node*& head, T1 item); 29 | void mergeSort(Node*& newList); 30 | ~MergeSortLinkedList(); 31 | private: 32 | void sort(Node*& Head); 33 | Node* mergeSortedLists(Node* leftHead, Node* rightHead); 34 | }; 35 | 36 | // To avoid linker error 37 | #include "MergeSortLinkedList.cpp" 38 | 39 | #endif 40 | -------------------------------------------------------------------------------- /Sorting/Merge Sort/C++/Linked Lists/MergeSortLinkedListTest.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************************* 2 | * Instructions: 3 | * To compile: g++ MergeSort_LinkedlistTest.cpp -o MergeSort_LinkedlistTest -std=c++11 4 | * To run: ./MergeSort_LinkedlistTest [#elements] 5 | * Where #elements is number of elements in an array, default is 100. 6 | * Author: Mounika Ponugoti 7 | *********************************************************************************/ 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include "MergeSortLinkedList.h" 14 | 15 | #define NUM_MAX 15 16 | 17 | // Number of elements in an array 18 | int length = 100; 19 | 20 | // Initialize the list with random values 21 | template 22 | void initializeList(Node*& newList, T2 length) { 23 | // mark head 24 | Node* head = nullptr; 25 | for (T2 i = 0; i < length; i++) { 26 | // new node 27 | Node* N = new Node; 28 | N->val = static_cast (rand()) / static_cast (RAND_MAX / NUM_MAX); 29 | // If the list is empty this is the head 30 | if (newList == nullptr) { 31 | newList = N; 32 | head = newList; 33 | } 34 | else { 35 | newList->next = N; 36 | newList = newList->next; 37 | } 38 | } 39 | newList = head; 40 | head = nullptr; 41 | delete head; 42 | } 43 | 44 | int main(int argc, char **argv) 45 | { 46 | if (argc == 2) { 47 | length = std::atoi(argv[1]); 48 | } 49 | if (argc > 2) { 50 | std::cout << "Usage: ./main [#elemnts]" << std::endl; 51 | exit(1); 52 | } 53 | // Seed for random number generator 54 | srand(time(NULL)); 55 | // Sorting integer Array 56 | Node *newList = nullptr; 57 | initializeList(newList, length); 58 | std::cout << "Unsorted Array: " << std::endl; 59 | printList (newList); 60 | 61 | MergeSortLinkedList mergeSort_obj; 62 | mergeSort_obj.mergeSort(newList); 63 | std::cout << "Sorted Array: " << std::endl; 64 | printList(newList); 65 | 66 | // Sorting floating point numbers 67 | Node *newList_f = nullptr; 68 | MergeSortLinkedList mergeSort_obj_2; 69 | // Slower, because always go through the entire list to find where to add new element 70 | mergeSort_obj_2.insertItem(newList_f, -2, 150); 71 | mergeSort_obj_2.insertItemAtEnd(newList_f, 10.5); 72 | mergeSort_obj_2.insertItemAtEnd(newList_f, 0.1); 73 | mergeSort_obj_2.insertItemAtEnd(newList_f, 4.5); 74 | mergeSort_obj_2.insertItemAtEnd(newList_f, 2.7); 75 | mergeSort_obj_2.insertItem(newList_f, newList_f->next, 8.9); 76 | mergeSort_obj_2.insertItem(newList_f, 4.5, 12.9); 77 | mergeSort_obj_2.insertItemAtEnd(newList_f, 0.01); 78 | mergeSort_obj_2.insertItem(newList_f, newList_f->next->next->next, -1.9); 79 | mergeSort_obj_2.insertItem(newList_f, 0.01, 100); 80 | 81 | // initializeList(newList_f, length); 82 | std::cout << "Unsorted Array: " << std::endl; 83 | std::cout << std::fixed << std::setprecision(2); 84 | printList(newList_f); 85 | 86 | mergeSort_obj_2.mergeSort(newList_f); 87 | std::cout << "Sorted Array: " << std::endl; 88 | printList(newList_f); 89 | 90 | // Free the allocated memory */ 91 | delete[] newList; 92 | delete[] newList_f; 93 | return 0; 94 | } 95 | -------------------------------------------------------------------------------- /Sorting/Merge Sort/C++/MergeSortArray.cpp: -------------------------------------------------------------------------------- 1 | //Program to perform Merge sort on an array 2 | //A much better sorting algorithm for an array would be quicksort 3 | //For linked lists, merge sort will be much better. 4 | #include 5 | using namespace std; 6 | 7 | void merge(int arr[], int left, int middle, int right) 8 | { 9 | int n1 = middle - left + 1;//get the number of elements from left to mid 10 | int n2 = right - middle;//get the number of elements from mid to right. 11 | int i,j,k; 12 | 13 | 14 | //creating temporary arrays 15 | int Left[n1], Right[n2]; 16 | //the below loops are made to copy the data into the left 17 | //and right side array 18 | for(i=0;i>n; 81 | int arr[n]; 82 | for(int i=0;i>arr[i]; 85 | } 86 | int startIndex; 87 | int endIndex; 88 | 89 | //the range of startIndex and endIndex should be between 90 | //0 and size_of_array-1 91 | //including this to sort sub parts of the array 92 | //as well as the entire array if needed based on the 93 | //input given. 94 | 95 | cin>>startIndex;//between 0 and n-1 96 | cin>>endIndex;//between 0 and n-1 97 | 98 | mergeSort(arr,startIndex,endIndex); 99 | //after mergesort print the array. Can also print the sorted array from the given startIndex and EndIndex 100 | for(int i=0;i1) 12 | { 13 | int mid=(arr.length)/2; 14 | int sizel=mid; // size for left sub array 15 | int sizer=arr.length-mid; // size for right sub array 16 | int[] larr=new int[sizel]; // left sub array 17 | int[] rarr=new int[sizer]; // right sub array 18 | int t=0; 19 | for (int i=0;i 4 | 5 | using namespace std; 6 | 7 | class QuickSort 8 | { 9 | /* This function takes last element as pivot, 10 | places the pivot element at its correct 11 | position in sorted array, and places all 12 | smaller (smaller than pivot) to left of 13 | pivot and all greater elements to right 14 | of pivot */ 15 | public: 16 | 17 | int partition(int arr[], int low, int high) 18 | { 19 | int pivot = arr[high]; 20 | int i = (low-1); // index of smaller element 21 | for (int j=low; j Array to be sorted, 47 | low --> Starting index, 48 | high --> Ending index */ 49 | void sort(int arr[], int low, int high) 50 | { 51 | if (low < high) 52 | { 53 | /* pi is partitioning index, arr[pi] is 54 | now at right place */ 55 | int pi = partition(arr, low, high); 56 | 57 | // Recursively sort elements before 58 | // partition and after partition 59 | sort(arr, low, pi-1); 60 | sort(arr, pi+1, high); 61 | } 62 | } 63 | }; 64 | 65 | // Driver program 66 | int main() 67 | { 68 | int arr[] = {10, 7, 8, 9, 1, 5}; 69 | int n = *(&arr + 1) - arr; 70 | 71 | QuickSort ob; 72 | ob.sort(arr, 0, n-1); 73 | 74 | cout<<"sorted array: "; 75 | for (int i=0; i Array to be sorted, 41 | low --> Starting index, 42 | high --> Ending index */ 43 | void sort(int arr[], int low, int high) 44 | { 45 | if (low < high) 46 | { 47 | /* pi is partitioning index, arr[pi] is 48 | now at right place */ 49 | int pi = partition(arr, low, high); 50 | 51 | // Recursively sort elements before 52 | // partition and after partition 53 | sort(arr, low, pi-1); 54 | sort(arr, pi+1, high); 55 | } 56 | } 57 | 58 | /* A utility function to print array of size n */ 59 | static void printArray(int arr[]) 60 | { 61 | int n = arr.length; 62 | for (int i=0; i= pivotvalue and rightmark >= leftmark: 26 | rightmark = rightmark -1 27 | 28 | if rightmark < leftmark: 29 | done = True 30 | else: 31 | temp = alist[leftmark] 32 | alist[leftmark] = alist[rightmark] 33 | alist[rightmark] = temp 34 | 35 | temp = alist[first] 36 | alist[first] = alist[rightmark] 37 | alist[rightmark] = temp 38 | 39 | 40 | return rightmark 41 | 42 | alist = [54,26,93,17,77,31,44,55,20] 43 | quickSort(alist) 44 | print(alist) 45 | -------------------------------------------------------------------------------- /Sorting/Quick Sort/Readme.md: -------------------------------------------------------------------------------- 1 | 2 | QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and partitions the given array around the picked pivot. There are many different versions of quickSort that pick pivot in different ways. 3 | 4 | 1. Always pick first element as pivot. 5 | 2. Always pick last element as pivot (implemented below) 6 | 3. Pick a random element as pivot. 7 | 4. Pick median as pivot. 8 | The key process in quickSort is partition(). Target of partitions is, given an array and an element x of array as pivot, put x at its correct position in sorted array and put all smaller elements (smaller than x) before x, and put all greater elements (greater than x) after x. All this should be done in linear time. 9 | 10 | Analysis of QuickSort 11 | Time taken by QuickSort in general can be written as following. 12 | 13 | T(n) = T(k) + T(n-k-1) + O(n) 14 | The first two terms are for two recursive calls, the last term is for the partition process. k is the number of elements which are smaller than pivot. 15 | The time taken by QuickSort depends upon the input array and partition strategy. Following are three cases. 16 | 17 | Worst Case: The worst case occurs when the partition process always picks greatest or smallest element as pivot. If we consider above partition strategy where last element is always picked as pivot, the worst case would occur when the array is already sorted in increasing or decreasing order. Following is recurrence for worst case. 18 | 19 | T(n) = T(0) + T(n-1) + O(n) 20 | which is equivalent to 21 | T(n) = T(n-1) + O(n) 22 | The solution of above recurrence is O(n^2). 23 | 24 | Best Case: The best case occurs when the partition process always picks the middle element as pivot. Following is recurrence for best case. 25 | 26 | T(n) = 2T(n/2) + O(n) 27 | The solution of above recurrence is O(nLogn). It can be solved using case 2 of Master Theorem 28 | 29 | Average Case: 30 | To do average case analysis, we need to consider all possible permutation of array and calculate time taken by every permutation which doesn’t look easy. 31 | We can get an idea of average case by considering the case when partition puts O(n/9) elements in one set and O(9n/10) elements in other set. Following is recurrence for this case. 32 | 33 | T(n) = T(n/9) + T(9n/10) + O(n) 34 | Solution of above recurrence is also O(nLogn) 35 | 36 | Explanation 37 | arr[] = {10, 80, 30, 90, 40, 50, 70} 38 | Indexes: 0 1 2 3 4 5 6 39 | 40 | low = 0, high = 6, pivot = arr[h] = 70 41 | Initialize index of smaller element, i = -1 42 | 43 | Traverse elements from j = low to high-1 44 | j = 0 : Since arr[j] <= pivot, do i++ and swap(arr[i], arr[j]) 45 | i = 0 46 | arr[] = {10, 80, 30, 90, 40, 50, 70} // No change as i and j 47 | // are same 48 | 49 | j = 1 : Since arr[j] > pivot, do nothing 50 | // No change in i and arr[] 51 | 52 | j = 2 : Since arr[j] <= pivot, do i++ and swap(arr[i], arr[j]) 53 | i = 1 54 | arr[] = {10, 30, 80, 90, 40, 50, 70} // We swap 80 and 30 55 | 56 | j = 3 : Since arr[j] > pivot, do nothing 57 | // No change in i and arr[] 58 | 59 | j = 4 : Since arr[j] <= pivot, do i++ and swap(arr[i], arr[j]) 60 | i = 2 61 | arr[] = {10, 30, 40, 90, 80, 50, 70} // 80 and 40 Swapped 62 | j = 5 : Since arr[j] <= pivot, do i++ and swap arr[i] with arr[j] 63 | i = 3 64 | arr[] = {10, 30, 40, 50, 80, 90, 70} // 90 and 50 Swapped 65 | 66 | We come out of loop because j is now equal to high-1. 67 | Finally we place pivot at correct position by swapping 68 | arr[i+1] and arr[high] (or pivot) 69 | arr[] = {10, 30, 40, 50, 70, 90, 80} // 80 and 70 Swapped 70 | 71 | Now 70 is at its correct place. All elements smaller than 72 | 70 are before it and all elements greater than 70 are after 73 | it. 74 | -------------------------------------------------------------------------------- /Sorting/QuickSort.java: -------------------------------------------------------------------------------- 1 | // Iterative Quick Sort 2 | // Java program for implementation of QuickSort 3 | import java.util.*; 4 | 5 | class QuickSort 6 | { 7 | /* This function takes last element as pivot, 8 | places the pivot element at its correct 9 | position in sorted array, and places all 10 | smaller (smaller than pivot) to left of 11 | pivot and all greater elements to right 12 | of pivot */ 13 | static int partition(int arr[], int low, int high) 14 | { 15 | int pivot = arr[high]; 16 | int i = (low-1); // index of smaller element 17 | for (int j=low; j<=high-1; j++) 18 | { 19 | // If current element is smaller than or 20 | // equal to pivot 21 | if (arr[j] <= pivot) 22 | { 23 | i++; 24 | 25 | // swap arr[i] and arr[j] 26 | int temp = arr[i]; 27 | arr[i] = arr[j]; 28 | arr[j] = temp; 29 | } 30 | } 31 | 32 | // swap arr[i+1] and arr[high] (or pivot) 33 | int temp = arr[i+1]; 34 | arr[i+1] = arr[high]; 35 | arr[high] = temp; 36 | 37 | return i+1; 38 | } 39 | 40 | /* The main function that implements QuickSort() 41 | arr[] --> Array to be sorted, 42 | low --> Starting index, 43 | high --> Ending index */ 44 | static void qSort(int arr[], int low, int high) 45 | { 46 | if (low < high) 47 | { 48 | /* pi is partitioning index, arr[pi] is 49 | now at right place */ 50 | int pi = partition(arr, low, high); 51 | 52 | // Recursively sort elements before 53 | // partition and after partition 54 | qSort(arr, low, pi-1); 55 | qSort(arr, pi+1, high); 56 | } 57 | } 58 | 59 | // Driver code 60 | public static void main(String args[]) 61 | { 62 | 63 | int n = 5; 64 | int arr[] = {4, 2, 6, 9, 2}; 65 | 66 | qSort(arr, 0, n-1); 67 | 68 | for(int i =0;i 3 | using namespace std; 4 | 5 | // A utility function to get maximum value in arr[] 6 | int getMax(int arr[], int n) 7 | { 8 | int mx = arr[0]; 9 | for (int i = 1; i < n; i++) 10 | if (arr[i] > mx) 11 | mx = arr[i]; 12 | return mx; 13 | } 14 | 15 | // A function to do counting sort of arr[] according to 16 | // the digit represented by exp. 17 | void countSort(int arr[], int n, int exp) 18 | { 19 | int output[n]; // output array 20 | int i, count[10] = {0}; 21 | 22 | // Store count of occurrences in count[] 23 | for (i = 0; i < n; i++) 24 | count[ (arr[i]/exp)%10 ]++; 25 | 26 | // Change count[i] so that count[i] now contains actual 27 | // position of this digit in output[] 28 | for (i = 1; i < 10; i++) 29 | count[i] += count[i - 1]; 30 | 31 | // Build the output array 32 | for (i = n - 1; i >= 0; i--) 33 | { 34 | output[count[ (arr[i]/exp)%10 ] - 1] = arr[i]; 35 | count[ (arr[i]/exp)%10 ]--; 36 | } 37 | 38 | // Copy the output array to arr[], so that arr[] now 39 | // contains sorted numbers according to current digit 40 | for (i = 0; i < n; i++) 41 | arr[i] = output[i]; 42 | } 43 | 44 | // The main function to that sorts arr[] of size n using 45 | // Radix Sort 46 | void radixsort(int arr[], int n) 47 | { 48 | // Find the maximum number to know number of digits 49 | int m = getMax(arr, n); 50 | 51 | // Do counting sort for every digit. Note that instead 52 | // of passing digit number, exp is passed. exp is 10^i 53 | // where i is current digit number 54 | for (int exp = 1; m/exp > 0; exp *= 10) 55 | countSort(arr, n, exp); 56 | } 57 | 58 | // A utility function to print an array 59 | void print(int arr[], int n) 60 | { 61 | for (int i = 0; i < n; i++) 62 | cout << arr[i] << " "; 63 | } 64 | 65 | // Driver program to test above functions 66 | int main() 67 | { 68 | int arr[] = {170, 45, 75, 90, 802, 24, 2, 66}; 69 | int n = sizeof(arr)/sizeof(arr[0]); 70 | radixsort(arr, n); 71 | print(arr, n); 72 | return 0; 73 | } 74 | -------------------------------------------------------------------------------- /Sorting/Selection Sort/C++/SelectionSort: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Asiatik/codezilla/9d870af843d0143daf7ec39aa7df4ef922cb4c3d/Sorting/Selection Sort/C++/SelectionSort -------------------------------------------------------------------------------- /Sorting/Selection Sort/C++/SelectionSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int array[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; 8 | 9 | cout << "Before sort:" << endl; 10 | for (int i = 0; i < 10; i++) 11 | { 12 | cout << array[i] << ", "; 13 | } 14 | cout << endl; 15 | 16 | for(int i = 0; i < 10; i++) 17 | { 18 | int small = array[i]; 19 | int smallIndex = i; 20 | 21 | for (int j = i; j < 10; j++) 22 | { 23 | if(array[j] < small) 24 | { 25 | small = array[j]; 26 | smallIndex = j; 27 | } 28 | } 29 | 30 | swap(array[i], array[smallIndex]); 31 | } 32 | 33 | cout << "After sort: " << endl; 34 | for (int i = 0; i < 10; i++) 35 | { 36 | cout << array[i] << ", "; 37 | } 38 | cout << endl; 39 | 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /Sorting/Selection Sort/Java/SelectionSort.java: -------------------------------------------------------------------------------- 1 | // Java program for implementation of Selection Sort 2 | class SelectionSort 3 | { 4 | void sort(int arr[]) 5 | { 6 | int n = arr.length; 7 | 8 | // One by one move boundary of unsorted subarray 9 | for (int i = 0; i < n-1; i++) 10 | { 11 | // Find the minimum element in unsorted array 12 | int min_idx = i; 13 | for (int j = i+1; j < n; j++) 14 | if (arr[j] < arr[min_idx]) 15 | min_idx = j; 16 | 17 | // Swap the found minimum element with the first 18 | // element 19 | int temp = arr[min_idx]; 20 | arr[min_idx] = arr[i]; 21 | arr[i] = temp; 22 | } 23 | } 24 | 25 | // Prints the array 26 | void printArray(int arr[]) 27 | { 28 | int n = arr.length; 29 | for (int i=0; i0 and alist[position-1]>currentvalue: 8 | alist[position]=alist[position-1] 9 | position = position-1 10 | 11 | alist[position]=currentvalue 12 | 13 | alist = [54,26,93,17,77,31,44,55,20] 14 | insertionSort(alist) 15 | print(alist) 16 | -------------------------------------------------------------------------------- /Sorting/Selection Sort/README.md: -------------------------------------------------------------------------------- 1 | # Selection Sort in Java 2 | 3 | ## Introduction 4 | The selection sort algorithm it's a very simple one, but it has O(n2) time complexity, making it inefficient on large arrays, and generally performs worse than the similar [insertion sort](https://github.com/Asiatik/codezilla/tree/master/Sorting/Insertion%20Sort). 5 | Anyway, in certain situations, it can perform better than more complicated algorithms, particularly where auxiliary memory is limited. 6 | 7 | ## The algorithm 8 | The algorithm divides the input array into two parts: the subarray of items already sorted, which is built up from left to right, and the subarray of items remaining to be sorted that occupy the rest of the array. Initially, the sorted subarray is empty and the unsorted subarray is the entire input array. The algorithm proceeds by finding the smallest (or largest, depending on sorting order) element in the unsorted subarray, exchanging (swapping) it with the leftmost unsorted element (putting it in sorted order), and moving the subarray boundaries one element to the right. 9 | -------------------------------------------------------------------------------- /Sorting/Selection Sort/python/selection_sort.py: -------------------------------------------------------------------------------- 1 | def selectionSort(arr): 2 | l = len(arr) #find the length of the array 3 | 4 | for i in range(l): #traverse linearly through the array 5 | smallest = i #assume smallest is in ith position 6 | for j in range(i+1, l): #Need to search just from the next element to the smallest 7 | if arr[j] < arr[smallest]: #if jth element is less than current smallest, update smallest 8 | smallest = j 9 | #Now we have the smallest after the ith iteration. swap it with ith element 10 | temp = arr[i] 11 | arr[i] = arr[smallest] 12 | arr[smallest] = temp 13 | 14 | arr = [24, 123, 14, 10, 29] 15 | 16 | selectionSort(arr) 17 | 18 | print "The sorted array is:", arr 19 | -------------------------------------------------------------------------------- /String Manipulation/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Asiatik/codezilla/9d870af843d0143daf7ec39aa7df4ef922cb4c3d/String Manipulation/.gitkeep -------------------------------------------------------------------------------- /String Manipulation/Knuth-Morris-Pratt/C++/KMP.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | // Computes the prefix-suffix array. 7 | vector ComputePrefixFunction(string pattern){ 8 | int m = pattern.length(); 9 | vector prefixArr(m); 10 | prefixArr[0] = 0; 11 | int k = 0; 12 | 13 | for(int i=1; i 0 && pattern[k] != pattern[i]){ 15 | k = prefixArr[k]; 16 | } 17 | if(pattern[k] == pattern[i]){ 18 | k++; 19 | } 20 | prefixArr[i] = k; 21 | } 22 | 23 | return prefixArr; 24 | } 25 | 26 | // Returns a vector of indicies where there is a pattern match. 27 | vector KMP(string text, string pattern){ 28 | int n = text.length(); 29 | int m = pattern.length(); 30 | vector prefixArr = ComputePrefixFunction(pattern); 31 | int q = 0; 32 | 33 | vector results; 34 | 35 | for (int i = 0; i < n; ++i){ 36 | while(q > 0 && pattern[q] != text[i]){ 37 | q = prefixArr[q]; 38 | } 39 | if(pattern[q] == text[i]){ 40 | q++; 41 | } 42 | if(q == m){ 43 | results.push_back(i-m); 44 | q = prefixArr[q]; 45 | } 46 | } 47 | 48 | return results; 49 | } 50 | 51 | int main(){ 52 | string example1 = "bacbababaabacabababaabaca"; 53 | string pattern1 = "abaabaca"; 54 | 55 | vector result = KMP(example1, pattern1); 56 | vector::iterator itt; 57 | cout << "Matches at the following indicies..." << endl; 58 | for(itt = result.begin(); itt != result.end(); ++itt){ 59 | cout << *itt << endl; 60 | } 61 | return 0; 62 | } -------------------------------------------------------------------------------- /String Manipulation/Knuth-Morris-Pratt/README.md: -------------------------------------------------------------------------------- 1 | # Knuth-Morris-Pratt (KMP) Algorithm 2 | KMP is a linear time string matching algorithm. The problem involves finding 3 | all occurences where a string pattern matches a substring in a text. 4 | The naive approach to string matching involves 5 | looping over all indicies over a text string and finding the indicies 6 | where the pattern p matches the substring starting at the index. 7 | 8 | s.t. pattern[0 ... m - 1] = text[idx ... idx + m - 1], where idx is some offset. 9 | 10 | The worst case of this approach is O(m*(n-m+1)), where m is |p| and n is |text|. 11 | 12 | The main drawback of the naive appraoch is that it handles overlaps 13 | poorly. Since it will go deep into the second nested loop when checking 14 | whether the substring and the pattern matches. When it hits a mismatch 15 | it will start over from the next increment, thereby redoing some of its 16 | comparisons. 17 | 18 | The KMP algorithm solves this problem by relying on some clever preprocessing, 19 | thereby reaching a linear time performance. The clever preprocessing is simply 20 | creating an array that contains information calculated by a prefix function, and this information describes how the pattern matches against shifts of itself. 21 | We use this array to avoid the worst case situation of the naive approach by reusing previously performed comparisons. 22 | 23 | The prefix-function(i) is the longest prefix of p that is also a suffix of p[1 ... i]. The whole idea of finding these substrings in the 24 | pattern which are both prefixes and suffixes, is that they determine from what index in the pattern and text we should start from next, hence 25 | avoiding having to start all the way at the start index of the pattern and only one index further in the text each time we hit a 26 | character miss match. 27 | 28 | KMP runs in O(n + m). Note, KMP is only necessary when there are many overlapping parts, since it is only in such 29 | situations where the prefix-suffix array helps. However, the worst case linear time efficiency is guaranteed, meaning 30 | the KMP algorithm is useful in general cases aswell. 31 | 32 | ## Pseudocode 33 | Where t is the text string and p is the pattern. 34 | 35 | KMP-Matcher(t, p): 36 | n = len(t) 37 | m = len(p) 38 | prefix-arr = Compute-Prefix-Function(p) 39 | q = 0 40 | for i = 0 to n: 41 | while q > 0 and p[q] != t[i]: 42 | q = prefix-arr[q] 43 | if p[q] == t[i]: 44 | q++ 45 | if q == m: 46 | patterns occurs at index i - m 47 | q = prefix-arr[q] 48 | 49 | Compute-Prefix-Function(p) 50 | m = len(p) 51 | new arr[0 ... m-1] 52 | arr[0] = 0 53 | k = 0 54 | for i = 1 to m: 55 | while k > 0 and p[k] != p[i]: 56 | k = arr[k] 57 | if p[k] == p[i]: 58 | k++ 59 | arr[i] = k 60 | 61 | return arr 62 | 63 | CLRS[p. 1006]. 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /heap in java: -------------------------------------------------------------------------------- 1 | public class HeapSort { 2 | 3 | private static int[] array = new int[]{5, 3, 6, 4, 8, 9 , 1, 10}; 4 | 5 | public static void main(String[] args) { 6 | heapSort(); 7 | 8 | for(int i : array) { 9 | System.out.println(i); 10 | } 11 | } 12 | 13 | private static void heapSort() { 14 | int length = array.length; 15 | 16 | buildMaxHeap(array, length); 17 | for(int i = length - 1; i > 0; i--) { 18 | int temp = array[0]; 19 | array[0] = array[i]; 20 | array[i] = temp; 21 | maxHeapify(array, 1, i); 22 | } 23 | } 24 | 25 | private static void buildMaxHeap(int[] array, int heapSize) { 26 | if(array == null) { 27 | throw new NullPointerException("null"); 28 | } 29 | if(array.length <=0 || heapSize <= 0) { 30 | throw new IllegalArgumentException("illegal"); 31 | } 32 | if(heapSize > array.length) { 33 | heapSize = array.length; 34 | } 35 | 36 | for(int i = heapSize/2; i > 0; i--) { 37 | maxHeapify(array, i, heapSize); 38 | } 39 | } 40 | 41 | private static void maxHeapify(int[] array, int index, int heapSize) { 42 | int l = index * 2; 43 | int r = l + 1; 44 | int largest; 45 | 46 | if(l <= heapSize && array[l - 1] > array[index - 1]) { 47 | largest = l; 48 | } else { 49 | largest = index; 50 | } 51 | 52 | if(r <= heapSize && array[r - 1] > array[largest - 1]) { 53 | largest = r; 54 | } 55 | 56 | if(largest != index) { 57 | int temp = array[index - 1]; 58 | array[index - 1] = array[largest - 1]; 59 | array[largest - 1] = temp; 60 | maxHeapify(array, largest, heapSize); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /runme.bh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | intro() { 4 | echo "Thank you for forking CodeZila" 5 | echo "Please input any names without any special characters" 6 | echo "For example: 'Insertion Sort' or 'Linked Lists'" 7 | read -p "What is the name of the algorithm or design you want to implement? " algorithm 8 | checkInput "$algorithm" 9 | pickLanguague "$algorithm" 10 | printTree "$algorithm" "$language" 11 | checkDir "$algorithm" 12 | } 13 | 14 | # Checks the input to see if it does not have illegal characters 15 | checkInput() { 16 | # $1 is the string being checked 17 | if [[ "$1" == *['!'@\$%^\&*()_+]* ]] 18 | then 19 | echo "Illegal character used" 20 | exit 21 | fi 22 | } 23 | 24 | # Asks the user that language they would like to use 25 | pickLanguague() { 26 | echo "Select the language you want to implement "$1" in?" 27 | echo "1) C++" 28 | echo "2) C" 29 | echo "3) C#" 30 | echo "4) Java" 31 | echo "5) JavaScript" 32 | echo "6) GoLang" 33 | echo "7) Python" 34 | echo "8) Ruby" 35 | echo "9) Other" 36 | read n 37 | case $n in 38 | 1) language='C++';; 39 | 2) language='C';; 40 | 3) language='C#';; 41 | 4) language='Java';; 42 | 5) language='JavaScript';; 43 | 6) language='GoLang';; 44 | 7) language='Python';; 45 | 8) language='Ruby';; 46 | 9) inputLanguage "$1";; 47 | *) echo "Error" ; exit;; 48 | esac 49 | 50 | createDir "$1" "$language" 51 | } 52 | 53 | inputLanguage() { 54 | read -p "What language do you want to implement '$1' in? " lang 55 | checkInput "$lang" 56 | createDir "$1" "$lang" 57 | printTree "$1" "$lang" 58 | checkDir 59 | exit 60 | } 61 | 62 | # Shows the user the created file structure 63 | printTree() { 64 | echo "$1" 65 | echo "├── readme.md" 66 | echo "└── $2" 67 | } 68 | 69 | # Creates the file structure 70 | createDir() { 71 | if [ ! -d "$1" ] 72 | then 73 | mkdir "$1" 74 | fi 75 | 76 | if [ ! -d "$1/$2" ] 77 | then 78 | mkdir "$1"/$2 79 | fi 80 | createReadme "$1" "$2" 81 | } 82 | 83 | createReadme() { 84 | if [ -e "$1"/"$2"/readme.md ] 85 | then 86 | echo "readme file already exists for '$1/$2'" 87 | else 88 | read -p "Do you want to create a Readme (y/n)? " response 89 | case "$response" in 90 | y|Y ) echo "# $1 implemented in $2" > "$1"/"$2"/readme.md;; 91 | n|N ) ;; 92 | * ) echo "Readme not created" ;; 93 | esac 94 | fi 95 | } 96 | 97 | # Asks the user if they want to keep the files 98 | checkDir() { 99 | read -p "Is the file structure above correct? (y/n)? " choice 100 | case "$choice" in 101 | y|Y ) echo "Enjoy Coding!";; 102 | n|N ) echo "Files Deleted"; rm -rf $1 ;; 103 | * ) echo "invalid - Files not deleted";; 104 | esac 105 | } 106 | 107 | intro 108 | --------------------------------------------------------------------------------