├── .gitignore ├── .vscode └── settings.json ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── algorithms ├── EuclideanAlgorithm │ ├── c │ │ └── euclid.c │ └── python │ │ └── euclideanAlgorithm.py ├── Graph │ └── connected_components_in_undirected_graph │ │ └── python │ │ └── ConnectedComponents.py ├── a_search │ └── cpp │ │ └── a_star.cpp ├── backtracking │ └── c │ │ ├── n_queens_problem.c │ │ ├── rat_in_a_maze_problem.c │ │ ├── sudoku_problem.c │ │ └── the_knight_tour_problem.c ├── bellman_ford │ ├── cpp │ │ └── bellman_ford.cpp │ └── java │ │ └── BellmanFord.java ├── bfs │ ├── cpp │ │ └── bfs.cpp │ └── java │ │ └── Graph.java ├── binary_search │ ├── PHP │ │ └── binarysearch.php │ ├── binary_search.md │ ├── c │ │ └── binary_search.c │ ├── cpp │ │ └── binary_search.cpp │ ├── java │ │ └── binarysearch.java │ ├── javascript │ │ └── binary_search.js │ ├── python │ │ └── binary_search.py │ └── ruby │ │ └── binary_search.rb ├── bipartite_check │ └── cpp │ │ └── bipartite.cpp ├── bitwise │ ├── cpp │ │ └── generating_subsets.cpp │ └── java │ │ ├── AddTwoNumbersWithoutPlusOperator.java │ │ ├── BinaryPalidrome.java │ │ ├── NegateANumberWithoutPlusOperator.java │ │ ├── Optimized_permutation │ │ └── Subsets.java ├── bogo_sort │ ├── java │ │ └── BogoSort.java │ ├── python │ │ └── bogo.py │ └── ruby │ │ └── bogo_sort.rb ├── breadth_first_search │ └── cpp │ │ └── bfs.cpp ├── bubble_sort │ ├── README.md │ ├── assembly_mips │ │ └── bubble_sort.asm │ ├── bash │ │ └── bubblesort.sh │ ├── c │ │ └── bubble_sort.c │ ├── cpp │ │ ├── bubble_sort_1.cpp │ │ └── bubblesort.cpp │ ├── crystal │ │ └── bubble_sort.cr │ ├── csharp │ │ └── BubbleSort.cs │ ├── elixir │ │ ├── README.md │ │ └── bubblesort.ex │ ├── go │ │ └── bubble-sort-algorithm.go │ ├── haskell │ │ └── bubble_sort.hs │ ├── java │ │ ├── BubbleSortExample.java │ │ └── GenericBubbleSort.java │ ├── javascript │ │ ├── bubble-sort.js │ │ ├── bubbleSort.js │ │ └── main_bs.js │ ├── kotlin │ │ └── bubblesort.kt │ ├── objetive-c │ │ └── BubbleSort.m │ ├── perl │ │ └── BubbleSort.pl │ ├── power_shell │ │ └── bubble_sort.ps1 │ ├── python │ │ └── bubble_sort.py │ ├── ruby │ │ └── bubble_sort.rb │ ├── swift │ │ └── bubble_sort.swift │ └── vb │ │ └── bubble_sort.bas ├── bucket_sort │ ├── bucket_sort.cpp │ ├── bucket_sort.java │ ├── bucket_sort.py │ └── c │ │ └── bucket_sort.c ├── caesar_cipher │ ├── java │ │ └── caesar.java │ └── javascript │ │ └── caesarCipher.js ├── check_pallindrome_number │ ├── c │ │ └── checkPalindrome.c │ └── cpp │ │ └── checkPall.cpp ├── closest │ └── java │ │ └── Closest.java ├── count_sort │ └── javascript │ │ └── count_sort.js ├── cycle_sort │ └── java │ │ └── cycleSort.java ├── decoding │ └── c │ │ └── base64_decoder.c ├── dfs │ ├── cpp │ │ └── dfs.cpp │ ├── java │ │ └── Graph.java │ └── python │ │ └── Dfs.py ├── dijkstra │ ├── cpp │ │ └── Dijkstras.cpp │ ├── java │ │ └── ShortestPath.java │ └── python │ │ └── djikstra.py ├── doomsday │ ├── java │ │ └── doomsday.java │ └── javascript │ │ └── doomsday.js ├── dynamic_programming │ ├── c │ │ ├── 0_1_knapsack_problem.c │ │ ├── Coin_change_DP.c │ │ ├── coinChange.c │ │ ├── count_no_of_ways_to_reach_nth_stair.c │ │ ├── longestIncreasingSubsequence.c │ │ ├── longestRepeatedSequence.c │ │ ├── longest_pallindrome_sequence.c │ │ ├── maxSumIncSequence.c │ │ └── subsetSum.c │ ├── cpp │ │ ├── kadens.cpp │ │ ├── nCr.cpp │ │ └── subset_sum.cpp │ └── java │ │ └── MinCostPath.java ├── encoding │ └── base64_encoder.c ├── fibonacci │ └── cpp │ │ └── constexpr-fibonacci.cpp ├── floyd_warshall │ └── java │ │ └── ShortestPath.java ├── greedy_search │ └── cpp │ │ └── prims_algorithm.cpp ├── heap_sort │ ├── crystal │ │ └── heap_sort.cr │ ├── java │ │ ├── heap_sort.java │ │ └── heapsort.java │ ├── javascript │ │ └── heap_sort.js │ └── python │ │ └── heap_sort.py ├── histogram_equalization │ └── java │ │ └── HistogramEqualization.java ├── huffmann_algorithm │ └── java │ │ └── Huffman.java ├── insertion_sort │ ├── ada │ │ └── insertion_sort.adb │ ├── c │ │ └── InsertionSort.c │ ├── cpp │ │ └── insertion_sort.cpp │ ├── crystal │ │ └── insertion_sort.cr │ ├── java │ │ └── InsertionSort.java │ ├── javascript │ │ ├── insertionSort.js │ │ └── insertion_sort.js │ ├── python │ │ └── insertionsort.py3 │ └── ruby │ │ └── insertion_sort.rb ├── inversion_count │ └── cpp │ │ └── inversion_count.cpp ├── jarvis │ └── cpp │ │ └── jarvis.cpp ├── johnson_algorithm │ └── cpp │ │ └── johnson_algorithm.cpp ├── kmp_search │ ├── cpp │ │ └── KMPSearch.cpp │ ├── java │ │ └── KMPSearch.java │ └── python │ │ └── KMPSearch.py ├── linear_search │ ├── c │ │ └── linearsearch.C │ ├── cpp │ │ └── linearSearch.cpp │ ├── java │ │ └── LinearSearch.java │ ├── javascript │ │ └── linear_search.js │ └── python │ │ └── linear_search.py ├── longest_common_subsequence │ ├── cpp │ │ └── LongestCommonSubsequence.cpp │ ├── javaj │ │ └── LCS.java │ ├── javascript │ │ └── longest_common_subsequence.js │ └── python │ │ └── LCS.py ├── longest_common_substring │ └── java │ │ └── LongestCommonSubString.java ├── matrix_chain_multiplication │ ├── cpp │ │ └── MCM.cpp │ ├── java │ │ └── MCM.java │ └── python │ │ └── MCM.py ├── merge_sort │ ├── c# │ │ └── MergeSort.cs │ ├── cpp │ │ └── merge_sort.cpp │ ├── haskell │ │ └── merge_sort.hs │ ├── java │ │ └── merge_sort.java │ ├── javascript │ │ └── MergeSort.js │ ├── python │ │ └── merge_sort.py │ └── ruby │ │ └── merge_sort.rb ├── minimum_spanning_tree │ └── cpp │ │ └── MST.cpp ├── optimal_binary_search_tree │ └── java │ │ └── OptimalBst.java ├── parse_tree │ └── python │ │ └── parse_tree.py ├── permutations │ ├── java │ │ └── Permutation.java │ └── javascript │ │ └── permutations.js ├── quick_sort │ ├── ada │ │ └── quick_sort.adb │ ├── c │ │ └── quick_sort.c │ ├── cpp │ │ └── quickSort.cpp │ ├── csharp │ │ ├── QuickSort.cs │ │ └── quicksort.cs │ ├── haskell │ │ └── quicksort.hs │ ├── java │ │ └── QuickSort.java │ ├── javascript │ │ └── quick_sort.js │ ├── kotlin │ │ └── quicksort.kt │ ├── python │ │ └── quicksort.py │ └── ruby │ │ └── quick_sort.rb ├── rabin_karp │ └── java │ │ └── RabinKarp.java ├── radixsort │ ├── c++ │ │ └── radixsort.cpp │ └── python │ │ └── lsd_radixsort.py ├── selection_sort │ ├── c │ │ └── SelectionSort.c │ ├── crystal │ │ └── selection_sort.cr │ ├── java │ │ └── SelectionSort.java │ ├── javascript │ │ └── selection_sort.js │ ├── python │ │ └── selection_sort.py │ └── ruby │ │ └── selection_sort.rb ├── shell_sort │ ├── C++ │ │ └── ShellSort.cpp │ ├── C │ │ └── ShellSort.c │ ├── Java │ │ └── ShellSort.java │ └── python │ │ └── shellsort.py ├── sieve_of_eratosthenes │ ├── cpp │ │ └── sieve_of_eratosthenes.cpp │ ├── java │ │ └── sieve.java │ ├── javascript │ │ └── sieve.js │ └── python │ │ └── sieve.py ├── sort │ └── heap_sort │ │ └── java │ │ └── heap_sort.java ├── strings │ └── cpp │ │ └── anagrams.cpp └── tower_of_hanoi │ ├── cpp │ └── tower_of_hanoi.cpp │ ├── java │ └── towers_of_hanoi.java │ ├── javascript │ └── tower_of_hanoi.js │ ├── php │ └── towers_of_hanoi.php │ └── python │ └── tower_of_hanoi.py ├── data_structures ├── arraylist │ └── java │ │ └── arraylist.java ├── avl_tree │ ├── java │ │ └── AVL.java │ └── javascript │ │ └── avl.js ├── bag │ └── java │ │ └── Bag.java ├── binary_search_tree │ ├── binary_search_tree.md │ ├── c │ │ └── BSTtraversal.c │ ├── cpp │ │ └── BST.h │ ├── java │ │ ├── binary_search_tree.java │ │ └── bst_operations │ │ │ ├── CheckBST.java │ │ │ ├── CorrectBST.java │ │ │ ├── FindAncestor.java │ │ │ ├── InorderSuccessor.java │ │ │ ├── LargestBST.java │ │ │ ├── LevelOrder.java │ │ │ ├── MorrisTraversal.java │ │ │ ├── Node.java │ │ │ └── PathFromRootToNode.java │ ├── javascript │ │ ├── binary_tree.js │ │ ├── binary_tree_search.js │ │ ├── breadth_first_search.js │ │ └── depth_first_search.js │ └── python │ │ ├── bst.py │ │ ├── bst1.py │ │ └── bst2.py ├── binary_tree │ ├── c │ │ └── diameterBT.c │ ├── cpp │ │ ├── binary_tree.cpp │ │ └── boundaryTraversal.cpp │ ├── csharp │ │ └── BinaryTree.cs │ ├── java │ │ ├── binary_tree_bfs.java │ │ └── binary_tree_dfs.java │ └── python │ │ └── binary_tree.py ├── bloom_filter │ └── python │ │ └── bloom_filter.py ├── circular_queue │ ├── circular_queue.md │ ├── cpp │ │ └── circular queue.cpp │ ├── java │ │ └── circular_queue.java │ └── python │ │ └── circular_queue.py ├── d_heap │ └── c │ │ └── d_heap.c ├── dimaeter_of_a_tree │ ├── cpp │ │ └── Diameter.cpp │ ├── diameter_of_a_tree.md │ └── java │ │ └── Diameter.java ├── double_linked_list │ └── cpp │ │ └── doublelinkedlist.cpp ├── doubly_linked_list │ ├── java │ │ └── DoublyLinkedList.java │ └── python │ │ └── DoublyLinkedList.py ├── generic_tree │ └── java │ │ └── gt.java ├── graph │ ├── cpp │ │ └── graph.cpp │ └── python │ │ └── graph.py ├── hash_table │ ├── cpp │ │ └── hashtable.h │ ├── csharp │ │ └── hash_table.cs │ ├── java │ │ └── Hash_table.java │ └── python │ │ └── hashTable.py ├── hashmap │ └── java │ │ └── hashmap.java ├── hashset │ └── java │ │ └── hashset.java ├── heap │ ├── cpp │ │ └── MinHeap.h │ ├── java │ │ ├── Heap.java │ │ └── heaps.java │ ├── python │ │ └── minheap.py │ └── ruby │ │ └── heap.rb ├── heapify_insert_extract_min │ └── cpp │ │ └── max-heap_functions.cpp ├── left_learning_red_black_tree │ ├── c │ │ └── llrb_tree.c │ └── java │ │ └── left_leaning_red_black_tree.java ├── linked_list │ ├── c │ │ └── linked_list.c │ ├── cpp │ │ ├── LinkedList.cpp │ │ └── singly_linked_list.cpp │ ├── csharp │ │ └── LinkedList.cs │ ├── go │ │ └── linked_list.go │ ├── java │ │ ├── LinkedList.java │ │ ├── LinkedListLinkedList.java │ │ └── LinkedListTest.java │ ├── kotlin │ │ └── LinkedList.kt │ ├── linked_list.md │ ├── python │ │ └── linked_list.py │ └── ruby │ │ └── linked_list.rb ├── linked_list_queue │ └── cpp │ │ └── queue_linked_list.cpp ├── min_heap │ └── cpp │ │ ├── impl_minHeap.cpp │ │ ├── minHeap.cpp │ │ └── minHeap.hpp ├── mirror_of_a_tree.java │ └── java │ │ └── Mirror.java ├── mirrot_of_a_tree.cpp │ └── mirror.cpp ├── mst │ ├── cpp │ │ └── mst.cpp │ └── java │ │ └── prims.java ├── priority_queue │ └── c │ │ └── priority_queue.cpp ├── queue │ ├── c │ │ └── queue.c │ ├── cpp │ │ ├── Queue.cpp │ │ └── Queue.h │ ├── csharp │ │ └── Queue.cs │ ├── go │ │ └── queue.go │ ├── java │ │ └── IterableQueue.java │ ├── javascript │ │ ├── queue_ES5.js │ │ └── queue_ES6.js │ ├── kotlin │ │ └── IterableQueue.kt │ ├── php │ │ └── queue.php │ ├── python │ │ └── queue_two_stacks.py │ └── ruby │ │ └── queue.rb ├── simple_queue │ ├── java │ │ ├── QueueImplementation.java │ │ ├── arrayQueue.java │ │ └── queue.java │ ├── python │ │ └── queue.py │ └── simple_queue.md ├── stack │ ├── c# │ │ ├── main.cs │ │ └── stack.cs │ ├── c │ │ └── stack1.c │ ├── cpp │ │ ├── celement.h │ │ ├── cstack.cpp │ │ ├── cstack.h │ │ ├── cstack.test.cpp │ │ ├── stack_balanced_paranthesis.cpp │ │ ├── templated_stack.cpp │ │ └── templated_stack.hpp │ ├── crystal │ │ └── stack.cr │ ├── csharp │ │ └── Stack.cs │ ├── go │ │ └── stack.go │ ├── java │ │ ├── Node.java │ │ ├── Stack.java │ │ └── integer_stack.java │ ├── javascript │ │ ├── stack.js │ │ └── usingstack.js │ ├── lisp │ │ ├── Stack.bak │ │ └── Stack.rkt │ ├── php │ │ └── stack.php │ ├── python │ │ └── stack.py │ └── ruby │ │ └── stack.rb ├── treemap │ └── java │ │ └── treemap.java ├── treeset │ └── java │ │ └── treeset.java ├── trie │ ├── Trie.md │ ├── java │ │ └── Trie.java │ └── javascript │ │ └── Trie.js └── union_find │ ├── cpp │ └── UnionFind.cpp │ ├── java │ └── UnionFind.java │ ├── python │ └── UnionFind.py │ └── union_find.md ├── design_patterns └── behavioral │ └── javascript │ ├── mediator-example.js │ └── mediator.js ├── logo.svg ├── package-lock.json └── package.json /.gitignore: -------------------------------------------------------------------------------- 1 | *.out 2 | javascript/node_modules 3 | .idea -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "vector": "cpp" 4 | } 5 | } -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to this repo 2 | **Implementing new File/Directory Structure** 3 | * Try to keep things as modular as possible, the new file/directory structure should be: 4 | ``` 5 | /data_structures/structure/language/file 6 | ex: /data_structures/char_stack/cpp/cstack.cpp 7 | /algorithms/algorithm/language/file 8 | ex: /algorithms/bubble_sort/cpp/bubble_sort.cpp 9 | ``` 10 | 11 | ## How To: 12 | 13 | 1. `git clone https://github.com/bareinhard/Hacktoberfest-Data-Structure-and-Algorithms` 14 | 2. `git checkout -b ` 15 | 3. Code your files in the proper directory based on the instructions above 16 | 4. add all your files `git add your/directory/path/to/file/` (see new directory structure above) 17 | 5. commit your file changes `git commit -m "Whatever you did here, e.g. created linkedlist class in C++"` 18 | 6. push your changes `git push origin ` 19 | 7. Create a Pull Request to master 20 | 21 | ### Alternate via Web 22 | 23 | 1. Fork Repo on Web Page 24 | 2. Make your changes on your forked repo 25 | 3. Make Pull Request to master 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Hacktoberfest-Data-Structure-and-Algorithms 2 | A repository containing data structures and algorithms, regardless of language. 3 | 4 | No longer active 5 | 6 | ***Not Affiliated with Digital Ocean or Hacktoberfest*** 7 | 8 | ![Hacktoberfest](https://pbs.twimg.com/media/Dn4njsBXkAEQWZs.jpg) 9 | 10 | # CONTRIBUTING! 11 | 12 | # Contributing to this repo 13 | **Implementing new File/Directory Structure** 14 | * Try to keep things as modular as possible, the new file/directory structure should be: 15 | ``` 16 | /data_structures/structure/language/file 17 | ex: /data_structures/char_stack/cpp/cstack.cpp 18 | /algorithms/algorithm/language/file 19 | ex: /algorithms/bubble_sort/cpp/bubble_sort.cpp 20 | ``` 21 | 22 | 23 | 24 | ## How To: 25 | 26 | 1. Fork Repo on Web Page 27 | 2. `git clone https://github.com/{your-username}/Hacktoberfest-Data-Structure-and-Algorithms` 28 | 3. Code your files in the proper directory based on the instructions above 29 | 4. add all your files `git add your/directory/path/to/file/` (see new directory structure above) 30 | 5. commit your file changes `git commit -m "Whatever you did here, e.g. created linkedlist class in C++"` 31 | 6. push your changes `git push` 32 | 7. Create a Pull Request to master on Web Page 33 | 34 | ### Alternate via Web 35 | 36 | 1. Fork Repo on Web Page 37 | 2. Make your changes on your forked repo 38 | 3. Make Pull Request to master 39 | 40 | #### Credits 41 | Logo created with: http://logomakr.com 42 | -------------------------------------------------------------------------------- /algorithms/EuclideanAlgorithm/c/euclid.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int gcd(int x, int y){ 4 | if(x == 0) 5 | return y; 6 | return gcd(y % x, x); 7 | } 8 | 9 | void main(){ 10 | int hcf, a, b; 11 | printf("Enter the 2 numbers: "); 12 | scanf("%d%d",&a, &b); 13 | hcf = gcd(a, b); 14 | printf("The HCF is: %d\n",hcf); 15 | } 16 | -------------------------------------------------------------------------------- /algorithms/EuclideanAlgorithm/python/euclideanAlgorithm.py: -------------------------------------------------------------------------------- 1 | def euclidean(a,b):#for natural numbers a,b 2 | 3 | #sanitize the inputs 4 | a=int(a) 5 | b=int(b) 6 | 7 | if(not(a and b)):#if either are 0 8 | return(0) 9 | 10 | if(b>a):#to have it so a>=b 11 | temp=a 12 | a=b 13 | b=temp 14 | 15 | while(1): 16 | remainder=a%b 17 | a=b 18 | b=remainder 19 | if(b==0): 20 | return(a) 21 | -------------------------------------------------------------------------------- /algorithms/Graph/connected_components_in_undirected_graph/python/ConnectedComponents.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Question source -- LeetCode 3 | Given n nodes labeled from 0 to n - 1 and a list of undirected edges 4 | (where each edge is a pair of nodes), write a function to find the number 5 | of connected components in an undirected graph. 6 | 7 | ''' 8 | 9 | def countComponents( n, edges): 10 | """ 11 | :type n: int 12 | :type edges: List[List[int]] 13 | :rtype: int 14 | """ 15 | # finds the path recursively 16 | def find(data, i): 17 | if i != data[i]: 18 | data[i] = find(data, data[i]) 19 | return data[i] 20 | 21 | # creates the union find data structure 22 | def union(data, i, j): 23 | root_i, root_j = find(data, i), find(data, j) 24 | if root_i != root_j: 25 | data[root_i] = root_j 26 | 27 | data = [i for i in range(n)] 28 | 29 | for i,j in edges: 30 | union(data, i, j) 31 | # set data structure to eliminate the possibilities of duplicates. 32 | res = set() 33 | 34 | # union-find the roots of the each nodes in the components. 35 | for i in range(n): 36 | res.add(find(data,i)) 37 | 38 | # the total length of the root nodes determine the total number of components. 39 | return len(res) 40 | 41 | 42 | print(countComponents(5, [[0, 1], [1, 2], [3, 4]])) 43 | 44 | -------------------------------------------------------------------------------- /algorithms/bellman_ford/cpp/bellman_ford.cpp: -------------------------------------------------------------------------------- 1 | /* 1. shortest path from source to vertices 2 | 2. can be used for negetive weights 3 | 3.can be used to detect neg cycle. 4 | */ 5 | #include 6 | using namespace std; 7 | #define pii pair 8 | #define mp make_pair 9 | #define INF (1<<20); 10 | pair G[1000]; 11 | int dis[1000]; 12 | 13 | int main() 14 | { 15 | int nodes,edges; 16 | cin>>nodes>>edges; 17 | for(int i=0;i>u>>v>>w; 21 | G[i]=mp(u,mp(v,w)); 22 | // v[v].push_back(mp(u,w)); for undirected; 23 | } 24 | for(int i=1;i<=nodes;i++) 25 | dis[i]=INF; 26 | dis[1]=0; 27 | for(int i=0;idis[u]+w) 36 | { 37 | dis[v]=dis[u]+w; 38 | } 39 | } 40 | } 41 | bool negc=false; 42 | for(int j=0;jdis[u]+w) 49 | { 50 | negc=true; 51 | break; 52 | } 53 | } 54 | if(negc) 55 | cout<<"negetive cycle"; 56 | else 57 | { 58 | for(int i=1;i<=nodes;i++) 59 | { 60 | cout<<"1"<<" - "< queue = new LinkedList<>(); 38 | 39 | visited[source] = true; 40 | queue.add(source); 41 | 42 | while (queue.size() != 0) { 43 | source = queue.poll(); 44 | System.out.print(source + " "); 45 | 46 | for (Integer n : (Iterable) adj[source]) { 47 | if (!visited[n]) { 48 | visited[n] = true; 49 | queue.add(n); 50 | } 51 | } 52 | } 53 | } 54 | 55 | /** 56 | * Test 57 | * @param args 58 | */ 59 | public static void main(String args[]) { 60 | Graph g = new Graph(4); 61 | 62 | g.addEdge(0, 1); 63 | g.addEdge(0, 2); 64 | g.addEdge(1, 2); 65 | g.addEdge(2, 0); 66 | g.addEdge(2, 3); 67 | g.addEdge(3, 3); 68 | 69 | g.BFS(2); 70 | } 71 | } -------------------------------------------------------------------------------- /algorithms/binary_search/PHP/binarysearch.php: -------------------------------------------------------------------------------- 1 | '; print_r( $sourceArr ); echo ''; 36 | echo ( $position >= 0 ) ? 'Keyword ' . $keyword . ' is found at position: ' . $position : 'Your keyword is not found.'; 37 | 38 | ?> -------------------------------------------------------------------------------- /algorithms/binary_search/c/binary_search.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int binarySearch(int arr[], int l, int r, int key) { 4 | if (r >= l) { 5 | int mid = l + (r - l)/2; 6 | 7 | // If the element is present at the middle 8 | if (arr[mid] == key) return mid; 9 | 10 | // If element is smaller than mid, then it can only be present in left subarray 11 | else if (arr[mid] > key) return binarySearch(arr, l, mid-1, key); 12 | 13 | // Else the element can only be present in right subarray 14 | return binarySearch(arr, mid+1, r, key); 15 | } 16 | // When element is not present in array 17 | return -1; 18 | } 19 | 20 | int main(void) { 21 | int arr[] = {2, 3, 4, 10, 40}; 22 | int n = sizeof(arr)/ sizeof(arr[0]); 23 | int key = 10; 24 | int result = binarySearch(arr, 0, n-1, key); 25 | (result == -1) ? printf("Element is not present in array") : printf("Element is present at index %d", result); 26 | return 0; 27 | } -------------------------------------------------------------------------------- /algorithms/binary_search/java/binarysearch.java: -------------------------------------------------------------------------------- 1 | // Java implementation of Binary Search 2 | class BinarySearch 3 | { 4 | // Returns index of x if it is present in arr[l..r], else return -1 5 | int binarySearch(int ar[], int l, int r, int x){ 6 | if(ar.length == 0) { 7 | return -1; 8 | } 9 | 10 | if (r >= l){ 11 | int mid = l + (r - l) / 2; 12 | // If the search is present at the mid postion 13 | if (ar[mid] == x){ 14 | return mid; 15 | } 16 | // If element is smaller than mid, then it can only be in left subarray 17 | if (ar[mid] > x){ 18 | return binarySearch(ar, l, mid - 1, x); 19 | } 20 | // Else the element can only be present in right subarray 21 | return binarySearch(ar, mid + 1, r, x); 22 | } 23 | // We reach here when element is not present in array 24 | return -1; 25 | } 26 | // Main method for testing 27 | public static void main(String args[]) 28 | { 29 | BinarySearch ob = new BinarySearch(); 30 | int arr[] = {1, 4, 5, 10, 11, 27, 36, 67, 90}; 31 | int n = arr.length; 32 | int x = 10; 33 | int result = ob.binarySearch(arr, 0, n - 1, x); 34 | if (result == -1){ 35 | System.out.println("Element not present"); 36 | } 37 | else{ 38 | System.out.println("Element found at index " + result); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /algorithms/binary_search/javascript/binary_search.js: -------------------------------------------------------------------------------- 1 | function binarySearch(ar, el, compare_fn) { 2 | var m = 0; 3 | var n = ar.length - 1; 4 | while (m <= n) { 5 | var k = (n + m) >> 1; 6 | var cmp = compare_fn(el, ar[k]); 7 | if (cmp > 0) { 8 | m = k + 1; 9 | } else if(cmp < 0) { 10 | n = k - 1; 11 | } else { 12 | return k; 13 | } 14 | } 15 | return -m - 1; 16 | } 17 | -------------------------------------------------------------------------------- /algorithms/binary_search/python/binary_search.py: -------------------------------------------------------------------------------- 1 | #Simple implementation of the binary search 2 | 3 | def b_search(a,s,start,end): 4 | target = int((start+end)/2) 5 | if start > end: 6 | return -1 7 | if s == a[target]: 8 | return target 9 | if s > a[target]: 10 | return b_search(a,s, target+1, end) 11 | if s < a[target]: 12 | return b_search(a,s, start, target-1) 13 | 14 | #input: s = target, a = array 15 | print('Insert array (list of ints separated by a space): ') 16 | a = list(map(int, input().split())) 17 | print('Insert target: ') 18 | s = int(input()) 19 | print('Pos: ') 20 | print(b_search(a,s,0,len(a)-1)) 21 | -------------------------------------------------------------------------------- /algorithms/binary_search/ruby/binary_search.rb: -------------------------------------------------------------------------------- 1 | def binary_search(an_array, item) 2 | first = 0 3 | last = an_array.length - 1 4 | 5 | while first <= last 6 | i = (first + last) / 2 7 | 8 | if an_array[i] == item 9 | return i 10 | elsif an_array[i] > item 11 | last = i - 1 12 | elsif an_array[i] < item 13 | first = i + 1 14 | else 15 | return -1 16 | end 17 | end 18 | end 19 | 20 | arr = [0,1,2,3,4,27,5,6,7,8,9] 21 | 22 | binary_search(arr, 27) 23 | # => 5 24 | -------------------------------------------------------------------------------- /algorithms/bipartite_check/cpp/bipartite.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int col[100]; 4 | int G[100][100]; 5 | int nodes,edges; 6 | bool bipartite(int src) 7 | { 8 | col[src]=1; 9 | queue q; 10 | q.push(src); 11 | while(!q.empty()) 12 | { 13 | int u=q.front(); 14 | q.pop(); 15 | for(int i=1;i<=nodes;i++) 16 | { 17 | if(G[u][i]==1 && col[i]==-1) 18 | { 19 | col[i]=1-col[u]; 20 | q.push(i); 21 | } 22 | else 23 | if(G[u][i]==1 && col[i]==col[u]) 24 | return false; 25 | } 26 | } 27 | return true; 28 | 29 | } 30 | int main() 31 | { 32 | 33 | cin>>nodes>>edges; 34 | for(int i=0;i<100;i++) 35 | { 36 | col[i]=-1; 37 | for(int j=0;j<100;j++) 38 | { 39 | G[i][j]=0; 40 | } 41 | } 42 | for(int i=0;i>u>>v; 46 | G[u][v]=1; 47 | G[v][u]=1; 48 | 49 | } 50 | cout< 2 | #include 3 | 4 | #define pb push_back 5 | 6 | using namespace std; 7 | 8 | int main(void) 9 | { 10 | vector v = {1,2,3}; 11 | int numSubsets = 1 << v.size(); 12 | for(int i = 0; i < numSubsets; ++i) 13 | { 14 | int pos = v.size() - 1; 15 | int subsetMask = i; 16 | cout << "{ "; 17 | while(subsetMask > 0) 18 | { 19 | if(subsetMask & 1) 20 | cout << v[pos] << " "; 21 | subsetMask >>= 1; 22 | pos--; 23 | } 24 | cout << "}\n"; 25 | } 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /algorithms/bitwise/java/AddTwoNumbersWithoutPlusOperator.java: -------------------------------------------------------------------------------- 1 | 2 | public class AddTwoNumbersWithoutPlusOperator { 3 | public static void main(String[] args) { 4 | int a = 10; 5 | int b = 90; 6 | add(a, b); 7 | } 8 | 9 | private static void add(int a, int b) { 10 | int carry; 11 | while (b != 0) { 12 | carry = a & b; 13 | a = a ^ b; 14 | b = carry << 1; 15 | } 16 | System.out.println("The sum " + a); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /algorithms/bitwise/java/BinaryPalidrome.java: -------------------------------------------------------------------------------- 1 | public class BinaryPalidrome { 2 | // check if binary representation of a number is palidrome 3 | public static void main(String[] args) { 4 | int n = 153; 5 | if (new BinaryPalidrome().isPalidrome(n)) { 6 | System.out.println("Yes, the binary representation of the number " + n + " is palidrome."); 7 | } else { 8 | System.out.println("No, the binary representation of the number " + n + " is not a palidrome."); 9 | } 10 | } 11 | 12 | private boolean isPalidrome(int n) { 13 | int m = getTotalBits(n) - 1; 14 | int i = 0; 15 | while (i <= m) { 16 | if (kthBit(n, i) != kthBit(n, m)) { 17 | return false; 18 | } 19 | i++; 20 | m--; 21 | } 22 | return true; 23 | } 24 | 25 | private int kthBit(int n, int kthBit) { 26 | return (n & 1 << kthBit) > 0 ? 1 : 0; 27 | } 28 | 29 | private int getTotalBits(int n) { 30 | int totalBits = 0; 31 | while (n != 0) { 32 | totalBits++; 33 | n = n >> 1; 34 | } 35 | return totalBits; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /algorithms/bitwise/java/NegateANumberWithoutPlusOperator.java: -------------------------------------------------------------------------------- 1 | public class NegateANumberWithoutPlusOperator { 2 | public static void main(String[] args) { 3 | NegateANumberWithoutPlusOperator number = new NegateANumberWithoutPlusOperator(); 4 | int n = 54; 5 | System.out.println("Negation of number " + n + " is " + number.negate(n)); 6 | } 7 | 8 | private int negate(int n) { 9 | n = ~n; 10 | return add(n, 1); 11 | } 12 | private int add(int a, int b) { 13 | int carry; 14 | while (b != 0) { 15 | carry = a & b; 16 | a = a ^ b; 17 | b = carry << 1; 18 | } 19 | return a; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /algorithms/bitwise/java/Optimized_permutation: -------------------------------------------------------------------------------- 1 | //Initial values 2 | int x = 0; 3 | int y = 1; 4 | //Optimzed permutation: 5 | x = x ^ y; 6 | y = x ^ y; 7 | x = x ^ y; 8 | //Yields: x = 1 and y = 0 9 | -------------------------------------------------------------------------------- /algorithms/bitwise/java/Subsets.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Subsets of a set: 3 | * input: array of size of n elements 4 | * output: 2^n subsets 5 | */ 6 | 7 | public class Subsets { 8 | public static void main(String[] args) { 9 | char[] array = {'a', 'b', 'c'}; 10 | Subsets set = new Subsets(); 11 | set.printSubsets(array); 12 | } 13 | 14 | private void printSubsets(char[] set) { 15 | int n = set.length; 16 | int totalSubsets = 1 << n; 17 | for (int i = 0; i < totalSubsets; i++) { 18 | System.out.print("{ "); 19 | for (int j = 0; j < n; j++) { 20 | if ((i & (1 << j)) > 0) { 21 | System.out.print(set[j] + " "); 22 | } 23 | } 24 | System.out.println(" }"); 25 | 26 | } 27 | 28 | 29 | } 30 | } -------------------------------------------------------------------------------- /algorithms/bogo_sort/java/BogoSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.List; 3 | import java.util.Collections; 4 | 5 | public class BogoSort { 6 | 7 | public static List bogoSort(List nums) { 8 | if (isSorted(nums)) { 9 | return nums; 10 | } 11 | 12 | for (;;) { 13 | Collections.shuffle(nums); 14 | 15 | if (isSorted(nums)) { 16 | break; 17 | } 18 | } 19 | 20 | return nums; 21 | } 22 | 23 | public static boolean isSorted(List x) { 24 | for (int i = 0; i < x.size() - 1; i++) { 25 | if (x.get(i) > x.get(i + 1)) { 26 | return false; 27 | } 28 | } 29 | 30 | return true; 31 | } 32 | } -------------------------------------------------------------------------------- /algorithms/bogo_sort/python/bogo.py: -------------------------------------------------------------------------------- 1 | from random import * 2 | 3 | seed() 4 | x = [] 5 | for i in range(0, 10): 6 | x.append(randint(0, 100)) 7 | 8 | def inorder(x): 9 | i = 0 10 | j = len(x) 11 | while i + 1 < j: 12 | if x[i] > x[i + 1]: 13 | return False 14 | i += 1 15 | return True 16 | 17 | def bogo(x): 18 | while not inorder(x): 19 | shuffle(x) 20 | return x 21 | 22 | -------------------------------------------------------------------------------- /algorithms/bogo_sort/ruby/bogo_sort.rb: -------------------------------------------------------------------------------- 1 | def bogosort(arr) 2 | arr.shuffle! while !arr.each_cons(2).all? do |x, y| 3 | x <= y 4 | end 5 | end 6 | array = [ 0, 5, 4, 3, 2, 8, 7, 1, 9, 6] 7 | bogosort(array) 8 | puts array # => 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 9 | -------------------------------------------------------------------------------- /algorithms/bubble_sort/README.md: -------------------------------------------------------------------------------- 1 | # Bubble Sort 2 | 3 | This folder contains examples of the bubble sort algorithm in the following programming languages: 4 | 5 | * bash 6 | * C 7 | * C++ 8 | * Crystal 9 | * C# 10 | * Elixir 11 | * Go 12 | * Haskell 13 | * Java 14 | * JavaScript 15 | * Kotlin 16 | * Objective-C 17 | * Power Shell 18 | * Python 19 | * Ruby 20 | * Swift 21 | * Visual Basic 22 | -------------------------------------------------------------------------------- /algorithms/bubble_sort/bash/bubblesort.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | echo "enter maximum number" 3 | read n 4 | 5 | 6 | echo "enter Numbers in array:" 7 | for (( i = 0; i < $n; i++ )) 8 | do 9 | read nos[$i] 10 | done 11 | 12 | for (( i = 0; i < $n ; i++ )) 13 | do 14 | for (( j = $i; j < $n; j++ )) 15 | do 16 | if [ ${nos[$i]} -gt ${nos[$j]} ]; then 17 | t=${nos[$i]} 18 | nos[$i]=${nos[$j]} 19 | nos[$j]=$t 20 | fi 21 | done 22 | done 23 | 24 | # Printing the sorted number 25 | echo -e "\nSorted Numbers " 26 | for (( i=0; i < $n; i++ )) 27 | do 28 | echo ${nos[$i]} 29 | done 30 | -------------------------------------------------------------------------------- /algorithms/bubble_sort/c/bubble_sort.c: -------------------------------------------------------------------------------- 1 | //algorithm of bubble sort in c 2 | //start from the first elemnent 3 | /*1. start comparing it with the next element 4 | 2. swap the element with the first smaller element it encounters. 5 | 3. every traversal pushes the largest element towards the end. 6 | */ 7 | 8 | 9 | 10 | 11 | void bubbleSort(int arr[], int n) 12 | { 13 | int i, j; 14 | for (i = 0; i < n-1; i++) 15 | 16 | // Last i elements are already in place 17 | for (j = 0; j < n-i-1; j++) 18 | if (arr[j] > arr[j+1]) 19 | swap(&arr[j], &arr[j+1]); 20 | } 21 | 22 | int main() 23 | { 24 | int i,j,k; 25 | int a[5]; 26 | for(i=0;i<5;i++) 27 | scanf("%d",&a[i]); 28 | bubblesort(a,5); 29 | for(i=0;i<5;i++) 30 | printf("%d\n",a[i]); 31 | 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /algorithms/bubble_sort/cpp/bubble_sort_1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | //global variables for ease of use 5 | long long int array[1000],n,temp; 6 | 7 | //function for bubble sort 8 | void bubble_sort() 9 | { 10 | 11 | for(register long long int i=0;iarray[j+1]) 16 | { 17 | temp=array[j]; 18 | array[j]=array[j+1]; 19 | array[j+1]=temp; 20 | } 21 | } 22 | } 23 | } 24 | int main() 25 | { 26 | // Enter the number of elements 27 | cin>>n; 28 | 29 | //Entering the elements 30 | for(register long long int i=0;i>array[i]; 33 | } 34 | 35 | //buuble sort 36 | bubble_sort(); 37 | 38 | //Sorted order 39 | for(register long long int i=0;i 4 | #include 5 | void main() 6 | { 7 | clrscr(); 8 | int n, i, arr[50], j, temp; 9 | cout<<"Enter total number of elements :"; 10 | cin>>n; 11 | cout<<"Enter "<>arr[i]; 15 | } 16 | cout<<"Sorting array using bubble sort technique...\n"; 17 | for(i=0; i<(n-1); i++) 18 | { 19 | for(j=0; j<(n-i-1); j++) 20 | { 21 | if(arr[j]>arr[j+1]) 22 | { 23 | temp=arr[j]; 24 | arr[j]=arr[j+1]; 25 | arr[j+1]=temp; 26 | } 27 | } 28 | } 29 | cout<<"Elements sorted successfully..!!\n"; 30 | cout<<"Sorted list in ascending order :\n"; 31 | for(i=0; i array[i + 1] 9 | array[i], array[i + 1] = array[i + 1], array[i] 10 | swapped = true 11 | end 12 | 13 | i += 1 14 | break if i == array.size - 1 15 | end 16 | 17 | break if !swapped 18 | 19 | count += 1 20 | break if count == array.size - 1 21 | end 22 | 23 | array 24 | end 25 | 26 | numbers = [4, 2, 8, 1, 0, 10] 27 | 28 | puts "Unsorted: #{numbers}" 29 | 30 | puts "Sorted: #{bubbleSort(numbers)}" 31 | -------------------------------------------------------------------------------- /algorithms/bubble_sort/csharp/BubbleSort.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | 5 | public class BubbleSort { 6 | private static void Main(string[] args) { 7 | Console.WriteLine("Input the elements of the array"); 8 | var isNumber = true; 9 | var userInput = new List(); 10 | while (isNumber) { 11 | var input = Console.ReadLine(); 12 | if (int.TryParse(input, out var temp )) { 13 | userInput.Add(temp); 14 | } else { 15 | isNumber = false; 16 | } 17 | } 18 | Console.Write('\n'); 19 | Console.WriteLine("Array before Sorting with Bubble Sort"); 20 | foreach (var entry in userInput) { 21 | Console.Write(entry + " "); 22 | } 23 | BubbleSort(userInput); 24 | Console.Write('\n'); 25 | Console.WriteLine("Array after Sorting with Bubble Sort"); 26 | foreach (var entry in userInput) { 27 | Console.Write(entry + " "); 28 | } 29 | Console.Read(); 30 | } 31 | 32 | private static void BubbleSort(IList list) { 33 | var n = list.Count; 34 | do { 35 | var newn = 1; 36 | for (var i = 0; i < n - 1; i++) { 37 | if (list[i] <= list[i + 1]) { 38 | continue; 39 | } 40 | var temp = list[i]; 41 | list[i] = list[i + 1]; 42 | list[i + 1] = temp; 43 | newn = i + 1; 44 | } 45 | n = newn; 46 | } while (n > 1); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /algorithms/bubble_sort/elixir/README.md: -------------------------------------------------------------------------------- 1 | # Elixir BubbleSort 2 | 3 | A simple implementation of the bubble sort algorithm in Elixir. 4 | 5 | Example of usage: 6 | 7 | ``` 8 | iex(1)> c("bubblesort.ex") 9 | [BubbleSort] 10 | iex(2)> BubbleSort.sort(1..1_000 |> Enum.reverse) 11 | [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 12 | 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 13 | 43, 44, 45, 46, 47, 48, 49, 50, ...] 14 | ``` 15 | -------------------------------------------------------------------------------- /algorithms/bubble_sort/elixir/bubblesort.ex: -------------------------------------------------------------------------------- 1 | defmodule BubbleSort do 2 | def sort([]), do: [] 3 | def sort(list) do 4 | round = swap(list) 5 | cond do 6 | round == list -> list 7 | true -> sort(round) 8 | end 9 | end 10 | 11 | defp swap([head | []]), do: [head] 12 | defp swap([head | [second | tail]]) do 13 | cond do 14 | head < second -> [head | swap([second | tail])] 15 | true -> [second | swap([head | tail])] 16 | end 17 | end 18 | end 19 | -------------------------------------------------------------------------------- /algorithms/bubble_sort/go/bubble-sort-algorithm.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | var numbers []int = []int{5, 4, 2, 3, 1, 0} 7 | fmt.Println("Unsorted:", numbers) 8 | 9 | bubbleSort(numbers) 10 | fmt.Println("Sorted:", numbers) 11 | } 12 | 13 | func bubbleSort(numbers []int) { 14 | var N int = len(numbers) 15 | var i int 16 | for i = 0; i < N; i++ { 17 | sweep(numbers) 18 | } 19 | } 20 | 21 | func sweep(numbers []int) { 22 | var N int = len(numbers) 23 | var firstIndex int = 0 24 | var secondIndex int = 1 25 | 26 | for secondIndex < N { 27 | var firstNumber int = numbers[firstIndex] 28 | var secondNumber int = numbers[secondIndex] 29 | 30 | if firstNumber > secondNumber { 31 | numbers[firstIndex] = secondNumber 32 | numbers[secondIndex] = firstNumber 33 | } 34 | 35 | firstIndex++ 36 | secondIndex++ 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /algorithms/bubble_sort/haskell/bubble_sort.hs: -------------------------------------------------------------------------------- 1 | import Debug.Trace 2 | 3 | main :: IO() 4 | main = do 5 | let sorted = bubbleSort [6, 5, 3, 1, 8, 7, 2, 4] :: [Integer] 6 | print sorted 7 | 8 | bubbleSort :: (Ord a, Show a) => [a] -> [a] 9 | --bubbleSort lst | trace ("sorting: " ++ show lst) False = undefined 10 | bubbleSort [] = [] 11 | bubbleSort [x] = [x] 12 | bubbleSort (x:y:rest) = 13 | bubbleSort (init bubbled) ++ [last bubbled] 14 | where 15 | (first, second) = if x > y then (y,x) else (x,y) 16 | bubbled = first : bubbleSort (second:rest) 17 | -------------------------------------------------------------------------------- /algorithms/bubble_sort/java/BubbleSortExample.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class BubbleSortExample { 4 | 5 | private static void bubbleSort(int[] arr) { 6 | int n = arr.length; 7 | int temp = 0; 8 | for(int i=0; i < n; i++){ 9 | for(int j=1; j < (n-i); j++){ 10 | if(arr[j-1] > arr[j]){ 11 | //swap elements 12 | temp = arr[j-1]; 13 | arr[j-1] = arr[j]; 14 | arr[j] = temp; 15 | } 16 | 17 | } 18 | } 19 | 20 | } 21 | public static void main(String[] args) { 22 | 23 | Scanner in = new Scanner(System.in); 24 | 25 | System.out.println("Input the size of array"); 26 | int n = in.nextInt(); 27 | int[] arr = new int[n]; 28 | 29 | System.out.println("Input the elements of array"); 30 | for(int i=0; i> void bubble_sort(T array[]){ 5 | boolean swapped; 6 | int indexOfLastUnsortedElement = array.length; 7 | do{ 8 | swapped = false; 9 | for(int i=0; i < indexOfLastUnsortedElement - 1; i++){ 10 | if(array[i].compareTo(array[i+1]) > 0){ 11 | swap(i, array); 12 | swapped = true; 13 | } 14 | } 15 | indexOfLastUnsortedElement--; 16 | printArray(array); 17 | }while(swapped); 18 | } 19 | 20 | private static void swap(int index, T[] array){ 21 | T temp = array[index]; 22 | array[index] = array[index + 1]; 23 | array[index + 1] = temp; 24 | } 25 | 26 | private static void printArray(T[] input){ 27 | for(int i = 0; i < input.length; i++){ 28 | System.out.print(input[i] + " "); 29 | } 30 | System.out.print("\n"); 31 | } 32 | 33 | public static void main(String[] args){ 34 | bubble_sort(new Integer[] {4, 2, 9, 6, 23, 12, 34, 0, 1}); 35 | bubble_sort(new String[] { "c", "a", "e", "d", "b" }); 36 | } 37 | } -------------------------------------------------------------------------------- /algorithms/bubble_sort/javascript/bubble-sort.js: -------------------------------------------------------------------------------- 1 | function bubbleSort(a) 2 | { 3 | let swapped; 4 | do { 5 | swapped = false; 6 | for (let i=0; i < a.length-1; i++) { 7 | if (a[i] > a[i+1]) { 8 | let temp = a[i]; 9 | a[i] = a[i+1]; 10 | a[i+1] = temp; 11 | swapped = true; 12 | } 13 | } 14 | } while (swapped); 15 | return a; 16 | } 17 | -------------------------------------------------------------------------------- /algorithms/bubble_sort/javascript/bubbleSort.js: -------------------------------------------------------------------------------- 1 | function bubbleSort(array) { 2 | let len = array.length; 3 | let temp; 4 | 5 | for (let i = 0; i < len; i++) { 6 | for (let j = 0; j < len; j++) { 7 | if (array[i] < array[j]) { 8 | temp = array[i]; 9 | array[i] = array[j]; 10 | array[j] = temp; 11 | } 12 | } 13 | } 14 | } 15 | // export default bubbleSort; 16 | module.exports = bubbleSort; 17 | -------------------------------------------------------------------------------- /algorithms/bubble_sort/javascript/main_bs.js: -------------------------------------------------------------------------------- 1 | let bubbleSort = require('./bubbleSort'); 2 | // import bubbleSort from './bubbleSort'; 3 | let rl = require('readline'); 4 | // import rl from 'readline'; 5 | // allow input through console 6 | let prompt = rl.createInterface(process.stdin, 7 | process.stdout); 8 | 9 | let array = []; 10 | let flag = true; 11 | console.log('Enter all the values. Press q to stop input'); 12 | 13 | function readInput() { 14 | prompt.question('>>', function(inp) { 15 | if (inp == 'q') { 16 | console.log('initial array: ', array); 17 | bubbleSort(array); 18 | console.log('final array: ', array); 19 | 20 | return prompt.close(); 21 | } 22 | 23 | array.push(Number(inp)); 24 | readInput(); 25 | }); 26 | } 27 | 28 | readInput(); 29 | -------------------------------------------------------------------------------- /algorithms/bubble_sort/kotlin/bubblesort.kt: -------------------------------------------------------------------------------- 1 | public class bubbleSort : Algorithm{ 2 | 3 | public override fun sort(arr: Array): Array { 4 | var swappedElements : Boolean; 5 | do { 6 | swappedElem = false; 7 | for (i in 0..arr.size - 2){ 8 | if (arr[i] > arr[i + 1]){ 9 | swap(arr, i, i + 1); 10 | swappedElem = true; 11 | } 12 | } 13 | } while (swappedElem); 14 | return arr; 15 | } 16 | 17 | public override fun getName(): String { 18 | return "BubbleSort Algorithm"; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /algorithms/bubble_sort/objetive-c/BubbleSort.m: -------------------------------------------------------------------------------- 1 | - (NSArray *)bubbleSort:(NSArray *)unsortedArray { 2 | //create mutable copy of the array 3 | NSMutableArray *unsortedMutableArray = [unsortedArray mutableCopy]; 4 | 5 | for (int i = 0; i < unsortedMutableArray.count; ++i) { 6 | for (int j = 0; j < (unsortedMutableArray.count - i - 1); ++j) { 7 | //reading integer values of the current and the next elements in the array 8 | NSInteger currElement = [unsortedMutableArray[j] integerValue]; 9 | NSInteger nextElement = [unsortedMutableArray[j + 1] integerValue]; 10 | 11 | //comparing the elements 12 | if (currElement > nextElement) { 13 | NSNumber *temp = unsortedMutableArray[j]; //keeping the current element in a temp 14 | //swapping the elements 15 | unsortedMutableArray[j] = unsortedMutableArray[j + 1]; 16 | unsortedMutableArray[j + 1] = temp; 17 | } 18 | } 19 | } 20 | //return the sorted array 21 | return [NSArray arrayWithArray:unsortedMutableArray]; 22 | } 23 | -------------------------------------------------------------------------------- /algorithms/bubble_sort/perl/BubbleSort.pl: -------------------------------------------------------------------------------- 1 | my @array = ( 5, 6, 3, 1, 7, 3, 2, 9, 10, 4 ); 2 | 3 | for my $x ( reverse 1 .. $#array ) { 4 | for my $y ( 0 .. $x - 1 ) { 5 | @array[ $y, $y + 1 ] = @array[ $y + 1, $y ] 6 | if $array[$y] > $array[ $y + 1 ]; 7 | } 8 | } 9 | 10 | print "@array\n"; -------------------------------------------------------------------------------- /algorithms/bubble_sort/power_shell/bubble_sort.ps1: -------------------------------------------------------------------------------- 1 | function bubblesort ($a) { 2 | $l = $a.Length 3 | $hasChanged = $true 4 | while ($hasChanged) { 5 | $hasChanged = $false 6 | $l-- 7 | for ($i = 0; $i -lt $l; $i++) { 8 | if ($a[$i] -gt $a[$i+1]) { 9 | $a[$i], $a[$i+1] = $a[$i+1], $a[$i] 10 | $hasChanged = $true 11 | } 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /algorithms/bubble_sort/python/bubble_sort.py: -------------------------------------------------------------------------------- 1 | def bubbleSort(a): 2 | n = len(a) 3 | sorted = False 4 | while not sorted: 5 | sorted = True 6 | for i in range(0, n - 1): 7 | if a[i] > a[i + 1]: 8 | sorted = False 9 | a[i], a[i + 1] = a[i + 1], a[i] 10 | 11 | a = [12, 33, 1, 3, 54, 32, 78, 54, 99, 6] 12 | print(a) 13 | bubbleSort(a) 14 | print(a) 15 | -------------------------------------------------------------------------------- /algorithms/bubble_sort/ruby/bubble_sort.rb: -------------------------------------------------------------------------------- 1 | def bubble_sort(array) 2 | n = array.length 3 | loop do 4 | swapped = false 5 | 6 | (n-1).times do |i| 7 | next unless array[i] > array[i+1] 8 | array[i], array[i+1] = array[i+1], array[i] 9 | swapped = true 10 | end 11 | 12 | break if not swapped 13 | end 14 | 15 | array 16 | end 17 | 18 | arr = [1,4,5,2,6,7,8,3] 19 | bubble_sort(arr) 20 | # => [1, 2, 3, 4, 5, 6, 7, 8] 21 | -------------------------------------------------------------------------------- /algorithms/bubble_sort/swift/bubble_sort.swift: -------------------------------------------------------------------------------- 1 | func bubbleSort(unsortedArray: Array) -> Array { 2 | //mutable copy of the initial array 3 | var mutableArray = unsortedArray 4 | //double looping through the array 5 | for i in 0.. mutableArray[j + 1] as! Int) { 9 | let temp = mutableArray[j] //storing into a temp value 10 | //swapping the elements 11 | mutableArray[j] = mutableArray[j + 1] 12 | mutableArray[j + 1] = temp 13 | } 14 | } 15 | } 16 | //returning the sorted array 17 | let sortedArray = mutableArray 18 | return sortedArray 19 | } 20 | -------------------------------------------------------------------------------- /algorithms/bubble_sort/vb/bubble_sort.bas: -------------------------------------------------------------------------------- 1 | Option Explicit 2 | 'VB6 Specific 3 | Private Sub bubble_sort() 4 | Dim i As Integer 5 | Dim j As Integer 6 | Dim k As Integer 7 | Dim array_unsorted(1001) As String 8 | Dim array_sorted(1001) As String 9 | Dim temp As String 10 | Dim swapped As Boolean 11 | i = 1000 12 | j = 0 13 | Do 14 | swapped = False 15 | For j = 1 To i - 1 16 | If LCase(array_unsorted(j)) > LCase(array_unsorted(j + 1)) Then 17 | temp = array_unsorted(j) 18 | array_unsorted(j) = array_unsorted(j + 1) 19 | array_unsorted(j + 1) = temp 20 | swapped = True 21 | End If 22 | Next j 23 | i = i - 1 24 | Loop Until Not swapped 25 | For k = 1 To 1000 26 | array_sorted(k) = array_unsorted(k) 27 | Next k 28 | End Sub 29 | 30 | 31 | -------------------------------------------------------------------------------- /algorithms/bucket_sort/bucket_sort.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to sort an array using bucket sort 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | // Function to sort arr[] of size n using bucket sort 8 | void bucketSort(float arr[], int n) 9 | { 10 | // 1) Create n empty buckets 11 | vector b[n]; 12 | 13 | // 2) Put array elements in different buckets 14 | for (int i=0; i maxValue) 34 | maxValue = sequence[i]; 35 | return maxValue; 36 | } 37 | 38 | public static void main(String args[]) 39 | { 40 | System.out 41 | .println("Sorting of randomly generated numbers using BUCKET SORT"); 42 | Random random = new Random(); 43 | int N = 20; 44 | int[] sequence = new int[N]; 45 | 46 | for (int i = 0; i < N; i++) 47 | sequence[i] = Math.abs(random.nextInt(100)); 48 | 49 | int maxValue = maxValue(sequence); 50 | 51 | System.out.println("\nOriginal Sequence: "); 52 | printSequence(sequence); 53 | 54 | System.out.println("\nSorted Sequence: "); 55 | printSequence(sort(sequence, maxValue)); 56 | } 57 | } -------------------------------------------------------------------------------- /algorithms/bucket_sort/bucket_sort.py: -------------------------------------------------------------------------------- 1 | def bucketsort( A ): 2 | # get hash codes 3 | code = hashing( A ) 4 | buckets = [list() for _ in range( code[1] )] 5 | # distribute data into buckets: O(n) 6 | for i in A: 7 | x = re_hashing( i, code ) 8 | buck = buckets[x] 9 | buck.append( i ) 10 | 11 | # Sort each bucket: O(n). 12 | # I mentioned above that the worst case for bucket sort is counting 13 | # sort. That's because in the worst case, bucket sort may end up 14 | # with one bucket per key. In such case, sorting each bucket would 15 | # take 1^2 = O(1). Even after allowing for some probabilistic 16 | # variance, to sort each bucket would still take 2-1/n, which is 17 | # still a constant. Hence, sorting all the buckets takes O(n). 18 | 19 | for bucket in buckets: 20 | insertionsort( bucket ) 21 | 22 | ndx = 0 23 | # merge the buckets: O(n) 24 | for b in range( len( buckets ) ): 25 | for v in buckets[b]: 26 | A[ndx] = v 27 | ndx += 1 28 | 29 | import math 30 | 31 | def hashing( A ): 32 | m = A[0] 33 | for i in range( 1, len( A ) ): 34 | if ( m < A[i] ): 35 | m = A[i] 36 | result = [m, int( math.sqrt( len( A ) ) )] 37 | return result 38 | 39 | 40 | def re_hashing( i, code ): 41 | return int( i / code[0] * ( code[1] - 1 ) ) -------------------------------------------------------------------------------- /algorithms/bucket_sort/c/bucket_sort.c: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | * C Program to Sort Array using Bucket Sort 4 | 5 | */ 6 | 7 | #include 8 | 9 | 10 | 11 | /* Function for bucket sort */ 12 | 13 | void Bucket_Sort(int array[], int n) 14 | 15 | { 16 | 17 | int i, j; 18 | 19 | int count[n]; 20 | 21 | for (i = 0; i < n; i++) 22 | 23 | count[i] = 0; 24 | 25 | 26 | 27 | for (i = 0; i < n; i++) 28 | 29 | (count[array[i]])++; 30 | 31 | 32 | 33 | for (i = 0, j = 0; i < n; i++) 34 | 35 | for(; count[i] > 0; (count[i])--) 36 | 37 | array[j++] = i; 38 | 39 | } 40 | 41 | /* End of Bucket_Sort() */ 42 | 43 | 44 | 45 | /* The main() begins */ 46 | 47 | int main() 48 | 49 | { 50 | 51 | int array[100], i, num; 52 | 53 | 54 | 55 | printf("Enter the size of array : "); 56 | 57 | scanf("%d", &num); 58 | 59 | printf("Enter the %d elements to be sorted:\n",num); 60 | 61 | for (i = 0; i < num; i++) 62 | 63 | scanf("%d", &array[i]); 64 | 65 | printf("\nThe array of elements before sorting : \n"); 66 | 67 | for (i = 0; i < num; i++) 68 | 69 | printf("%d ", array[i]); 70 | 71 | printf("\nThe array of elements after sorting : \n"); 72 | 73 | Bucket_Sort(array, num); 74 | 75 | for (i = 0; i < num; i++) 76 | 77 | printf("%d ", array[i]); 78 | 79 | printf("\n"); 80 | 81 | return 0; 82 | 83 | } 84 | -------------------------------------------------------------------------------- /algorithms/check_pallindrome_number/c/checkPalindrome.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int checkPall(char str[]) 5 | { 6 | for(int i = 0; i < strlen(str); i++) 7 | { 8 | if(str[i] != str[strlen(str)-i-1]) 9 | { 10 | return 0; 11 | } 12 | } 13 | return 1; 14 | } 15 | int main() 16 | { 17 | char str[10000]; 18 | gets(str); 19 | if(checkPall(str)) 20 | { 21 | printf("YES"); 22 | } 23 | else 24 | { 25 | printf("NO"); 26 | } 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /algorithms/check_pallindrome_number/cpp/checkPall.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | int checkPall(char str[]) 6 | { 7 | for(int i = 0; i < strlen(str); i++) 8 | { 9 | if(str[i] != str[strlen(str)-i-1]) 10 | { 11 | return 0; 12 | } 13 | } 14 | return 1; 15 | } 16 | int main() 17 | { 18 | char str[10000]; 19 | cin >> str; 20 | if(checkPall(str)) 21 | { 22 | cout << "YES" << endl; 23 | } 24 | else 25 | { 26 | cout << "NO" << endl; 27 | } 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /algorithms/closest/java/Closest.java: -------------------------------------------------------------------------------- 1 | package algorithms.closest.java; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.Scanner; 6 | 7 | /* 8 | This algorithm searches through a list of integers and finds the distance between 9 | the two closest element. It then prints this integer. 10 | */ 11 | public class Closest { 12 | public static void main(String[] args) { 13 | //get input 14 | Scanner sc = new Scanner(System.in).useDelimiter(" "); 15 | ArrayList input = new ArrayList<>(); 16 | //add input to ArrayList 17 | while (sc.hasNextInt()) { 18 | input.add(sc.nextInt()); 19 | } 20 | //sort the list 21 | Collections.sort(input); 22 | //initialize closest values, with the first two elements in the list 23 | int closest = input.get(1)-input.get(0); 24 | //check all elements in the list 25 | for(int i = 2; i < input.size(); i++) { 26 | //change closest if we find two elements with a shorter distance. 27 | closest = Math.min(closest, input.get(i)-input.get(i-1)); 28 | } 29 | //print the shortest distance 30 | System.out.println(closest); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /algorithms/count_sort/javascript/count_sort.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var countSort = (arr, range)=>{ 3 | /** 4 | * Consider the input is in range of 1 to 9 5 | */ 6 | // this can vary depending on your input array 7 | let countArr = []; 8 | //Initialise count array to 0; 9 | for(let i=0; i <= range; i++){ 10 | countArr[i] = 0; 11 | } 12 | for(let i=0; i < arr.length; i++){ 13 | ++countArr[arr[i]]; 14 | } 15 | for(let i=1; i<= countArr.length-1; i++){ 16 | countArr[i] += countArr[i-1]; 17 | } 18 | //Take the sorted array and insert the data of input array based on the count array and 19 | // decrease the value by 1 every time the element is inserted in sorted array 20 | 21 | let sortedArray = new Array(arr.length -1); 22 | for(let i=0; i 4 | #import 5 | #import 6 | 7 | 8 | class Vertex { 9 | public: 10 | Vertex(std::string n); 11 | 12 | bool visited; 13 | Vertex * prev; //predecessor 14 | int dist; 15 | std::string name; 16 | std::vector neighbours; 17 | }; 18 | 19 | Vertex::Vertex(std::string n) { 20 | prev = nullptr; 21 | dist = -1; 22 | name = n; 23 | } 24 | 25 | void VisitVertex(Vertex *v, Vertex * predecessor){ 26 | v->prev = predecessor; 27 | v->visited = true; 28 | for (Vertex * successor : v->neighbours) { 29 | if (!successor->visited) 30 | VisitVertex(successor,v); 31 | } 32 | } 33 | 34 | void DFS(std::vector graph){ 35 | Vertex * predecessor = nullptr; 36 | for (Vertex * v: graph ) { 37 | v->visited = false; 38 | } 39 | for (Vertex * v: graph ) { 40 | if (!v->visited) 41 | VisitVertex(v, predecessor); 42 | predecessor = v; 43 | } 44 | 45 | } 46 | 47 | int main() { 48 | 49 | //testing 50 | 51 | Vertex v1("v1"); 52 | Vertex v2("v2"); 53 | Vertex v3("v3"); 54 | Vertex v4("v4"); 55 | v1.neighbours.emplace_back(&v2); 56 | v1.neighbours.emplace_back(&v3); 57 | v4.neighbours.emplace_back(&v3); 58 | v3.neighbours.emplace_back(&v4); 59 | v1.neighbours.emplace_back(&v4); 60 | 61 | std::vector graph; 62 | graph.emplace_back(&v1); 63 | graph.emplace_back(&v2); 64 | graph.emplace_back(&v3); 65 | graph.emplace_back(&v4); 66 | 67 | DFS(graph); 68 | std::cout << "v1 prev: " << v1.prev <name <name <name < adj[]; 9 | 10 | /** 11 | * 12 | * @param v number of vertex 13 | */ 14 | Graph(int v) { 15 | vertexNumber = v; 16 | adj = new LinkedList[v]; 17 | for (int i=0; i console.log(test.join('/') + ': ' + dayMapping[dayOfTheWeek(...test)])) 20 | -------------------------------------------------------------------------------- /algorithms/dynamic_programming/c/0_1_knapsack_problem.c: -------------------------------------------------------------------------------- 1 | // A Dynamic Programming based solution for 0-1 Knapsack problem 2 | #include 3 | 4 | // A utility function that returns maximum of two integers 5 | int max(int a, int b) { return (a > b)? a : b; } 6 | 7 | // Returns the maximum value that can be put in a knapsack of capacity W 8 | int knapSack(int W, int wt[], int val[], int n) 9 | { 10 | int i, w; 11 | int K[n+1][W+1]; 12 | 13 | // Build table K[][] in bottom up manner 14 | for (i = 0; i <= n; i++) 15 | { 16 | for (w = 0; w <= W; w++) 17 | { 18 | if (i==0 || w==0) 19 | K[i][w] = 0; 20 | else if (wt[i-1] <= w) 21 | K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]); 22 | else 23 | K[i][w] = K[i-1][w]; 24 | } 25 | } 26 | 27 | return K[n][W]; 28 | } 29 | 30 | int main() 31 | { 32 | int val[] = {60, 100, 120}; 33 | int wt[] = {10, 20, 30}; 34 | int W = 50; 35 | int n = sizeof(val)/sizeof(val[0]); 36 | printf("%d", knapSack(W, wt, val, n)); 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /algorithms/dynamic_programming/c/Coin_change_DP.c: -------------------------------------------------------------------------------- 1 | //Coin change problem : 2 | /* 3 | Given a value N, if we want to make change for N cents, and we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins, how many ways can we make the change? 4 | The order of coins doesn’t matter. 5 | 6 | For example, for N = 4 and S = {1,2,3}, there are four solutions: 7 | {1,1,1,1},{1,1,2},{2,2},{1,3}. 8 | So output should be 4. 9 | 10 | For N = 10 and S = {2, 5, 3, 6}, there are five solutions: {2,2,2,2,2}, {2,2,3,3}, {2,2,6}, {2,3,5} and {5,5}. 11 | So the output should be 5. 12 | */ 13 | 14 | 15 | #include 16 | 17 | int count( int S[], int m, int n ) 18 | { 19 | int i, j, x, y; 20 | 21 | // We need n+1 rows as the table is consturcted in bottom up manner using 22 | // the base case 0 value case (n = 0) 23 | int table[n+1][m]; 24 | 25 | // Fill the enteries for 0 value case (n = 0) 26 | for (i=0; i= 0)? table[i - S[j]][j]: 0; 36 | 37 | // Count of solutions excluding S[j] 38 | y = (j >= 1)? table[i][j-1]: 0; 39 | 40 | // total count 41 | table[i][j] = x + y; 42 | } 43 | } 44 | return table[n][m-1]; 45 | } 46 | 47 | // Driver program to test above function 48 | int main() 49 | { 50 | int arr[] = {1, 2, 3}; 51 | int m = sizeof(arr)/sizeof(arr[0]); 52 | int n = 4; 53 | printf(" %d ", count(arr, m, n)); 54 | return 0; 55 | } -------------------------------------------------------------------------------- /algorithms/dynamic_programming/c/coinChange.c: -------------------------------------------------------------------------------- 1 | #include 2 | int count( int S[], int m, int n ) 3 | { 4 | // table[i] will be storing the number of solutions for 5 | // value i. We need n+1 rows as the table is consturcted 6 | // in bottom up manner using the base case (n = 0) 7 | int table[n+1]; 8 | 9 | // Initialize all table values as 0 10 | memset(table, 0, sizeof(table)); 11 | 12 | // Base case (If given value is 0) 13 | table[0] = 1; 14 | 15 | // Pick all coins one by one and update the table[] values 16 | // after the index greater than or equal to the value of the 17 | // picked coin 18 | for(int i=0; i 4 | 5 | // A recursive function used by countWays 6 | int countWaysUtil(int n, int m) 7 | { 8 | int res[n]; 9 | res[0] = 1; res[1] = 1; 10 | for (int i=2; i 3 | #include 4 | 5 | /* lis() returns the length of the longest increasing 6 | subsequence in arr[] of size n */ 7 | int lis( int arr[], int n ) 8 | { 9 | int *lis, i, j, max = 0; 10 | lis = (int*) malloc ( sizeof( int ) * n ); 11 | 12 | /* Initialize LIS values for all indexes */ 13 | for (i = 0; i < n; i++ ) 14 | lis[i] = 1; 15 | 16 | /* Compute optimized LIS values in bottom up manner */ 17 | for (i = 1; i < n; i++ ) 18 | for (j = 0; j < i; j++ ) 19 | if ( arr[i] > arr[j] && lis[i] < lis[j] + 1) 20 | lis[i] = lis[j] + 1; 21 | 22 | /* Pick maximum of all LIS values */ 23 | for (i = 0; i < n; i++ ) 24 | if (max < lis[i]) 25 | max = lis[i]; 26 | 27 | /* Free memory to avoid memory leak */ 28 | free(lis); 29 | 30 | return max; 31 | } 32 | 33 | /* Driver program to test above function */ 34 | int main() 35 | { 36 | int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 }; 37 | int n = sizeof(arr)/sizeof(arr[0]); 38 | printf("Length of lis is %dn", lis( arr, n ) ); 39 | return 0; 40 | } -------------------------------------------------------------------------------- /algorithms/dynamic_programming/c/longest_pallindrome_sequence.c: -------------------------------------------------------------------------------- 1 | # A Dynamic Programming based Python program for LPS problem 2 | # Returns the length of the longest palindromic subsequence in seq 3 | #include 4 | #include 5 | 6 | // A utility function to get max of two integers 7 | int max (int x, int y) { return (x > y)? x : y; } 8 | 9 | // Returns the length of the longest palindromic subsequence in seq 10 | int lps(char *str) 11 | { 12 | int n = strlen(str); 13 | int i, j, cl; 14 | int L[n][n]; // Create a table to store results of subproblems 15 | 16 | 17 | // Strings of length 1 are palindrome of lentgh 1 18 | for (i = 0; i < n; i++) 19 | L[i][i] = 1; 20 | 21 | // Build the table. Note that the lower diagonal values of table are 22 | // useless and not filled in the process. The values are filled in a 23 | // manner similar to Matrix Chain Multiplication DP solution (See 24 | // http://www.geeksforgeeks.org/archives/15553). cl is length of 25 | // substring 26 | for (cl=2; cl<=n; cl++) 27 | { 28 | for (i=0; i 4 | 5 | /* maxSumIS() returns the maximum sum of increasing subsequence 6 | in arr[] of size n */ 7 | int maxSumIS( int arr[], int n ) 8 | { 9 | int i, j, max = 0; 10 | int msis[n]; 11 | 12 | /* Initialize msis values for all indexes */ 13 | for ( i = 0; i < n; i++ ) 14 | msis[i] = arr[i]; 15 | 16 | /* Compute maximum sum values in bottom up manner */ 17 | for ( i = 1; i < n; i++ ) 18 | for ( j = 0; j < i; j++ ) 19 | if ( arr[i] > arr[j] && msis[i] < msis[j] + arr[i]) 20 | msis[i] = msis[j] + arr[i]; 21 | 22 | /* Pick maximum of all msis values */ 23 | for ( i = 0; i < n; i++ ) 24 | if ( max < msis[i] ) 25 | max = msis[i]; 26 | 27 | return max; 28 | } 29 | 30 | /* Driver program to test above function */ 31 | int main() 32 | { 33 | int arr[] = {1, 101, 2, 3, 100, 4, 5}; 34 | int n = sizeof(arr)/sizeof(arr[0]); 35 | printf("Sum of maximum sum increasing subsequence is %dn", 36 | maxSumIS( arr, n ) ); 37 | return 0; 38 | } -------------------------------------------------------------------------------- /algorithms/dynamic_programming/c/subsetSum.c: -------------------------------------------------------------------------------- 1 | // A recursive solution for subset sum problem 2 | #include 3 | 4 | // Returns true if there is a subset of set[] with sun equal to given sum 5 | bool isSubsetSum(int set[], int n, int sum) 6 | { 7 | // Base Cases 8 | if (sum == 0) 9 | return true; 10 | if (n == 0 && sum != 0) 11 | return false; 12 | 13 | // If last element is greater than sum, then ignore it 14 | if (set[n-1] > sum) 15 | return isSubsetSum(set, n-1, sum); 16 | 17 | /* else, check if sum can be obtained by any of the following 18 | (a) including the last element 19 | (b) excluding the last element */ 20 | return isSubsetSum(set, n-1, sum) || 21 | isSubsetSum(set, n-1, sum-set[n-1]); 22 | } 23 | 24 | // Driver program to test above function 25 | int main() 26 | { 27 | int set[] = {3, 34, 4, 12, 5, 2}; 28 | int sum = 9; 29 | int n = sizeof(set)/sizeof(set[0]); 30 | if (isSubsetSum(set, n, sum) == true) 31 | printf("Found a subset with given sum"); 32 | else 33 | printf("No subset with given sum"); 34 | return 0; 35 | } -------------------------------------------------------------------------------- /algorithms/dynamic_programming/cpp/kadens.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to print largest contiguous array sum 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int maxSubArraySum(int a[], int size) 7 | { 8 | int max_so_far = INT_MIN, max_ending_here = 0; 9 | 10 | for (int i = 0; i < size; i++) 11 | { 12 | max_ending_here = max_ending_here + a[i]; 13 | if (max_so_far < max_ending_here) 14 | max_so_far = max_ending_here; 15 | 16 | if (max_ending_here < 0) 17 | max_ending_here = 0; 18 | } 19 | return max_so_far; 20 | } 21 | 22 | /*Driver program to test maxSubArraySum*/ 23 | int main() 24 | { 25 | int a[] = {-2, -3, 4, -1, -2, 1, 5, -3}; 26 | int n = sizeof(a)/sizeof(a[0]); 27 | int max_sum = maxSubArraySum(a, n); 28 | cout << "Maximum contiguous sum is " << max_sum; 29 | return 0; 30 | } -------------------------------------------------------------------------------- /algorithms/dynamic_programming/cpp/nCr.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Returns nCr % p 5 | int nCrModp(int n, int r, int p) 6 | { 7 | // The array C is going to store last row of 8 | // pascal triangle at the end. And last entry 9 | // of last row is nCr 10 | int C[r+1]; 11 | memset(C, 0, sizeof(C)); 12 | 13 | C[0] = 1; // Top row of Pascal Triangle 14 | 15 | // One by constructs remaining rows of Pascal 16 | // Triangle from top to bottom 17 | for (int i = 1; i <= n; i++) 18 | { 19 | // Fill entries of current row using previous 20 | // row values 21 | for (int j = min(i, r); j > 0; j--) 22 | 23 | // nCj = (n-1)Cj + (n-1)C(j-1); 24 | C[j] = (C[j] + C[j-1])%p; 25 | } 26 | return C[r]; 27 | } 28 | 29 | // Driver program 30 | int main() 31 | { 32 | int n = 10, r = 2, p = 13; 33 | cout << "Value of nCr % p is " << nCrModp(n, r, p); 34 | return 0; 35 | } -------------------------------------------------------------------------------- /algorithms/dynamic_programming/cpp/subset_sum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int arr[1000]; 4 | int sum=0; 5 | int cache[100][100]; 6 | int m_diff(int idx,int sub_sum) 7 | { 8 | if(cache[idx][sub_sum]) 9 | return cache[idx][sub_sum]; 10 | 11 | if(idx==0) 12 | { 13 | cache[0][sub_sum]=abs((sum-sub_sum)-sub_sum); 14 | return cache[0][sub_sum]; 15 | } 16 | cache[idx][sub_sum]=min(m_diff(idx-1,sub_sum-arr[idx]),m_diff(idx-1,sub_sum)); 17 | return cache[idx][sub_sum]; 18 | } 19 | int main() 20 | { 21 | memset(cache,0,sizeof cache); 22 | int n; 23 | cin>>n; 24 | for(int i=0;i>arr[i]; 27 | sum+=arr[i]; 28 | } 29 | cout<= 0; j--) { 13 | storage[m - 1][j] = storage[m - 1][j + 1] + arr[m - 1][j]; 14 | } 15 | // Last Column 16 | for (int i = m - 2; i >= 0; i--) { 17 | storage[i][n - 1] = storage[i + 1][n - 1] + arr[i][n - 1]; 18 | } 19 | 20 | for (int i = m - 2; i >= 0; i--) { 21 | for (int j = n - 2; j >= 0; j--) { 22 | storage[i][j] = arr[i][j] 23 | + Math.min(storage[i][j + 1], Math.min( 24 | storage[i + 1][j + 1], storage[i + 1][j])); 25 | } 26 | } 27 | return storage[0][0]+arr[row][column]; 28 | } 29 | 30 | public static void main(String args[]) { 31 | Scanner s = new Scanner(System.in); 32 | int rows = s.nextInt(); 33 | int columns = s.nextInt(); 34 | int arr[][] = new int[rows][columns]; 35 | for (int i = 0; i < rows; i++) { 36 | for (int j = 0; j < columns; j++) { 37 | arr[i][j] = s.nextInt(); 38 | } 39 | } 40 | int row = s.nextInt(); 41 | int column = s.nextInt(); 42 | System.out.println(minCostPathDP(arr,row,column)); 43 | s.close(); 44 | } 45 | } 46 | 47 | -------------------------------------------------------------------------------- /algorithms/fibonacci/cpp/constexpr-fibonacci.cpp: -------------------------------------------------------------------------------- 1 | // Computes a specific index of the Fibonacci sequence 2 | // Can be computed at compile-time under certain conditions 3 | 4 | constexpr unsigned int fibonacci(unsigned int index) { 5 | 6 | constexpr auto gr = (1 + std::sqrt(5)) / 2; 7 | 8 | if(index == 0) { 9 | return 0; 10 | } else if(index == 1) { 11 | return 1; 12 | } 13 | 14 | return static_cast( 15 | (std::pow(gr, index) - std::pow(1 - gr, index)) / sqrt(5) 16 | ); 17 | } 18 | -------------------------------------------------------------------------------- /algorithms/heap_sort/crystal/heap_sort.cr: -------------------------------------------------------------------------------- 1 | def heap_sort(array) 2 | to_heap(array) 3 | bottom = array.size - 1 4 | 5 | while bottom > 0 6 | array[0], array[bottom] = array[bottom], array[0] 7 | sift_down(array, 0, bottom) 8 | bottom -= 1 9 | end 10 | 11 | array 12 | end 13 | 14 | def to_heap(array) 15 | i = (array.size/2) - 1 16 | 17 | while i >= 0 18 | sift_down(array, i, array.size) 19 | i -= 1 20 | end 21 | 22 | array 23 | end 24 | 25 | def sift_down(array, i, max) 26 | i_big, c1, c2 = 0, 0, 0 27 | 28 | while i < max 29 | i_big = i 30 | c1 = (2*i) + 1 31 | c2 = c1 + 1 32 | 33 | if c1 < max && array[c1] > array[i_big] 34 | i_big = c1 35 | end 36 | 37 | if c2 < max && array[c2] > array[i_big] 38 | i_big = c2 39 | end 40 | 41 | break if i_big == i 42 | 43 | array[i], array[i_big] = array[i_big], array[i] 44 | 45 | i = i_big 46 | end 47 | 48 | array 49 | end 50 | 51 | numbers = [4, 2, 8, 1, 30, 0, 10, 16] 52 | 53 | puts "Unsorted: #{numbers}" 54 | 55 | puts "Sorted: #{heap_sort(numbers)}" 56 | -------------------------------------------------------------------------------- /algorithms/heap_sort/javascript/heap_sort.js: -------------------------------------------------------------------------------- 1 | var array_length; 2 | /* to create MAX array */ 3 | function heap_root(input, i) { 4 | var left = 2 * i + 1; 5 | var right = 2 * i + 2; 6 | var max = i; 7 | 8 | if (left < array_length && input[left] > input[max]) { 9 | max = left; 10 | } 11 | 12 | if (right < array_length && input[right] > input[max]) { 13 | max = right; 14 | } 15 | 16 | if (max != i) { 17 | swap(input, i, max); 18 | heap_root(input, max); 19 | } 20 | } 21 | 22 | function swap(input, index_A, index_B) { 23 | var temp = input[index_A]; 24 | 25 | input[index_A] = input[index_B]; 26 | input[index_B] = temp; 27 | } 28 | 29 | function heapSort(input) { 30 | 31 | array_length = input.length; 32 | 33 | for (var i = Math.floor(array_length / 2); i >= 0; i -= 1) { 34 | heap_root(input, i); 35 | } 36 | 37 | for (i = input.length - 1; i > 0; i--) { 38 | swap(input, 0, i); 39 | array_length--; 40 | 41 | 42 | heap_root(input, 0); 43 | } 44 | } 45 | 46 | var arr = [3, 0, 2, 5, -1, 4, 1]; 47 | heapSort(arr); 48 | console.log(arr); 49 | -------------------------------------------------------------------------------- /algorithms/heap_sort/python/heap_sort.py: -------------------------------------------------------------------------------- 1 | from heapq import heappush, heappop 2 | 3 | def heap_sort(heap_iterable): 4 | ''' 5 | Heap sort implementation 6 | ''' 7 | heap = [] 8 | for val in heap_iterable: 9 | heappush(heap, val) 10 | return [heappop(heap) for _ in range(len(heap))] 11 | 12 | # Test 13 | if __name__ == '__main__': 14 | test_cases = ( 15 | [1, 3, 5, 7, 9, 2, 4, 6, 8, 0], 16 | [3, 15, 68, 34, 39, 85, 85, 71, 47, 84], 17 | [3, 10, 68, 34, 15, 85, 85, 71, 47, 84, 39], 18 | [2, 10, 3, 34, 15, 68, 85, 71, 47, 84, 39, 85], 19 | [1, 10, 2, 34, 15, 3, 85, 71, 47, 84, 39, 85, 68], 20 | range(50) 21 | ) 22 | for iterable in test_cases: 23 | assert heap_sort(iterable) == sorted(iterable) 24 | -------------------------------------------------------------------------------- /algorithms/insertion_sort/c/InsertionSort.c: -------------------------------------------------------------------------------- 1 | // C program for insertion sort 2 | #include 3 | /* Function to sort an array using insertion sort */ 4 | void insertionSort(int ar[], int n) 5 | { 6 | int i, key, j; 7 | for (i = 1; i < n; i++) 8 | { 9 | key = ar[i]; 10 | j = i-1; 11 | /* Move elements with indices from 0 to i-1 that are greater 12 | than key, to one position ahead of their current position */ 13 | while (j >= 0 && ar[j] > key) 14 | { 15 | ar[j+1] = ar[j]; 16 | j = j-1; 17 | } 18 | ar[j+1] = key; 19 | } 20 | } 21 | // method to print array 22 | void print(int ar[], int n) 23 | { 24 | for (int i=0; i < n; i++){ 25 | printf("%d ", ar[i]); 26 | } 27 | } 28 | /* To test insertion sort function */ 29 | int main() 30 | { 31 | int arr[] = {10, 29, 1, 9, 37, 24, 6, 3, 11}; 32 | // Calculates array size 33 | int n = sizeof(arr) / sizeof(arr[0]); 34 | insertionSort(arr, n); 35 | print(arr, n); 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /algorithms/insertion_sort/cpp/insertion_sort.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Created by radligna on 05.10.17. 3 | // 4 | 5 | 6 | // C++ program for insertion sort 7 | 8 | //needed to print the sorted array 9 | #include 10 | 11 | /* Function to sort an array using insertion sort */ 12 | void insertionSort( int tab[], int arraySize ) { 13 | int temp, iter2; 14 | for( int iter1 = 1; iter1 < arraySize; iter1++ ) { 15 | temp = tab[iter1]; 16 | for( iter2 = iter1 - 1; iter2 >= 0 and tab[iter2] > temp; iter2-- ) 17 | tab[ iter2 + 1 ] = tab[ iter2 ]; 18 | tab[ iter2 + 1 ] = temp; 19 | } 20 | } 21 | // method to print array 22 | void printArray(int arr[], int arraySize) { 23 | for (int i=0; i < arraySize; i++) 24 | std::cout< 0 && array[i-1] > array[i] 7 | array[i], array[i - 1] = array[i - 1], array[i] 8 | i -= 1 9 | end 10 | 11 | x += 1 12 | break if x == array.size 13 | end 14 | 15 | array 16 | end 17 | 18 | numbers = [4, 2, 8, 1, 30, 0, 10, 16] 19 | 20 | puts "Unsorted: #{numbers}" 21 | 22 | puts "Sorted: #{insertion_sort(numbers)}" 23 | -------------------------------------------------------------------------------- /algorithms/insertion_sort/java/InsertionSort.java: -------------------------------------------------------------------------------- 1 | class InsertionSort { 2 | 3 | /* 4 | This class sorts an array using insertion sort 5 | */ 6 | 7 | public static int[] insertionSort(int[] array) { 8 | int key, 9 | previousIndex; 10 | 11 | for (int index = 1; index < array.length; index++) { 12 | key = array[index]; 13 | previousIndex = index - 1; 14 | 15 | while(previousIndex >= 0 && array[previousIndex] > key){ 16 | array[previousIndex + 1] = array[previousIndex]; 17 | previousIndex -= 1; 18 | array[previousIndex + 1] = key; 19 | } 20 | } 21 | return array; 22 | } 23 | 24 | public static void main(String[] args) { 25 | int[] array = new int[10]; 26 | 27 | 28 | for (int i = 10; i > 0 ; i--) { 29 | array[10 - i] = i; 30 | } 31 | 32 | int[] sortedArray = insertionSort(array); 33 | 34 | for (int i: sortedArray) { 35 | System.out.print(i + " "); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /algorithms/insertion_sort/javascript/insertionSort.js: -------------------------------------------------------------------------------- 1 | function insertionSort(array) { 2 | for (let i = 0; i < array.length; i++) { 3 | let temp = array[i]; 4 | let j = i - 1; 5 | 6 | while (j >= 0 && array[j] > temp) { 7 | array[j + 1] = array[j]; 8 | j--; 9 | } 10 | 11 | array[j + 1] = temp; 12 | } 13 | 14 | return array; 15 | } 16 | -------------------------------------------------------------------------------- /algorithms/insertion_sort/javascript/insertion_sort.js: -------------------------------------------------------------------------------- 1 | function insertionSort(unsortedList) { 2 | let len = unsortedList.length; 3 | 4 | for (let i = 1; i < len; i++) { 5 | let ele = unsortedList[i]; 6 | 7 | for (var j = i - 1; j >= 0 && (unsortedList[j] > ele); j--) { 8 | unsortedList[j+1] = unsortedList[j]; 9 | } 10 | 11 | unsortedList[j+1] = ele; 12 | } 13 | } -------------------------------------------------------------------------------- /algorithms/insertion_sort/python/insertionsort.py3: -------------------------------------------------------------------------------- 1 | # Python program for implementation of Insertion Sort 2 | 3 | # Function to do insertion sort 4 | def insertionSort(arr): 5 | 6 | # Traverse through 1 to len(arr) 7 | for i in range(1, len(arr)): 8 | 9 | key = arr[i] 10 | 11 | # Move elements of arr[0..i-1], that are 12 | # greater than key, to one position ahead 13 | # of their current position 14 | j = i-1 15 | while j >=0 and key < arr[j] : 16 | arr[j+1] = arr[j] 17 | j -= 1 18 | arr[j+1] = key 19 | 20 | 21 | #Test case 22 | arr = [12, 11, 13, 5, 6] 23 | insertionSort(arr) 24 | for i in range(len(arr)): 25 | print ("%d" %arr[i]) 26 | -------------------------------------------------------------------------------- /algorithms/insertion_sort/ruby/insertion_sort.rb: -------------------------------------------------------------------------------- 1 | def insertion_sort(numbers) 2 | for i in 1...numbers.length 3 | key = numbers[i] 4 | j = i - 1 5 | while j >= 0 and numbers[j] > key 6 | numbers[j+1] = numbers[j] 7 | j = j - 1 8 | end 9 | numbers[j+1] = key 10 | end 11 | numbers 12 | end 13 | 14 | unsorted = [5, 2, 6, 7, 20, 9, 1, 3] 15 | 16 | puts "Unsorted " + unsorted.inspect 17 | 18 | sorted = insertion_sort(unsorted) 19 | puts "Sorted " + sorted.inspect 20 | -------------------------------------------------------------------------------- /algorithms/inversion_count/cpp/inversion_count.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | long merge(vector &arr, vector &tmp, int left, int mid, int right) { 5 | int i = left; 6 | int k = left; 7 | int j = mid; 8 | long count = 0; 9 | while(i <= (mid-1) && j <= right) { 10 | if(arr[i] <= arr[j] ) tmp[k++] = arr[i++]; 11 | else { 12 | tmp[k++] = arr[j++]; 13 | count += mid - i; 14 | } 15 | } 16 | while(i <= mid - 1) 17 | tmp[k++] = arr[i++]; 18 | while(j <= right) 19 | tmp[k++] = arr[j++]; 20 | for (int i = left; i <= right; ++i) { 21 | arr[i] = tmp[i]; 22 | } 23 | return count; 24 | } 25 | 26 | long mergeSort(vector &arr, vector &tmp, int left, int right) { 27 | long count = 0; 28 | int mid; 29 | if(left < right) { 30 | mid = (right + left)/2; 31 | count += mergeSort(arr, tmp, left, mid); 32 | count += mergeSort(arr, tmp , mid+1 , right); 33 | count += merge(arr, tmp, left, mid+1, right); 34 | } 35 | return count; 36 | } 37 | 38 | long countInversions(vector arr) { 39 | vector tmp(arr.size()); 40 | return mergeSort(arr, tmp, 0, arr.size()-1); 41 | } 42 | 43 | int main() { 44 | int n; 45 | cin >> n; 46 | vector arr(n); 47 | for(int arr_i = 0; arr_i < n; arr_i++) { 48 | cin >> arr[arr_i]; 49 | } 50 | long result = countInversions(arr); 51 | cout << result << endl; 52 | return 0; 53 | } -------------------------------------------------------------------------------- /algorithms/kmp_search/cpp/KMPSearch.cpp: -------------------------------------------------------------------------------- 1 | //CPP Implementation of Knuth-Morris-Pratt(KMP) algorithm for pattern matching in a given text string. 2 | 3 | #include 4 | #define MAX 10000 5 | using namespace std; 6 | 7 | char text[MAX],pattern[MAX]; 8 | int prefix_array[MAX],m,n; 9 | 10 | void Compute_Prefix_Array(); 11 | int Kmp_Search(); 12 | 13 | int main(void) 14 | { 15 | int find_pattern; 16 | cout<<"Specify Input Text: "; 17 | cin>>text; 18 | cout<<"Specify Input Pattern: "; 19 | cin>>pattern; 20 | m=strlen(text); 21 | n=strlen(pattern); 22 | find_pattern=Kmp_Search(); 23 | if(find_pattern>=0) 24 | { 25 | cout<<"\nMatching Pattern FOUND at position "<-1 && pattern[k+1]!=text[i]) 42 | { 43 | k=prefix_array[k]; 44 | } 45 | if(text[i] == pattern[k+1]) 46 | { 47 | k++; 48 | } 49 | if(k==n-1) 50 | { 51 | return i-k+1; 52 | } 53 | } 54 | return -1; 55 | } 56 | 57 | void Compute_Prefix_Array() 58 | { 59 | int k=-1; 60 | int i=1; 61 | prefix_array[0]=k; 62 | for(i=1;i-1&&pattern[k+1]!=pattern[i]) 65 | { 66 | k=prefix_array[k]; 67 | } 68 | if(pattern[i]==pattern[k+1]) 69 | { 70 | k++; 71 | } 72 | prefix_array[i]=k; 73 | } 74 | } 75 | 76 | /* 77 | SAMPLE OUTPUT: 78 | Specify Input Text: ababdabacdababcabab 79 | Specify Input Pattern: ababcabab 80 | 81 | Matching Pattern FOUND at position 11 in the input Text. 82 | */ 83 | -------------------------------------------------------------------------------- /algorithms/kmp_search/python/KMPSearch.py: -------------------------------------------------------------------------------- 1 | class KMP: 2 | def partial(self, pattern): 3 | """ Calculate partial match table: String -> [Int]""" 4 | ret = [0] 5 | 6 | for i in range(1, len(pattern)): 7 | j = ret[i - 1] 8 | while j > 0 and pattern[j] != pattern[i]: 9 | j = ret[j - 1] 10 | ret.append(j + 1 if pattern[j] == pattern[i] else j) 11 | return ret 12 | 13 | def search(self, T, P): 14 | """ 15 | KMP search main algorithm: String -> String -> [Int] 16 | Return all the matching position of pattern string P in S 17 | """ 18 | partial, ret, j = self.partial(P), [], 0 19 | 20 | for i in range(len(T)): 21 | while j > 0 and T[i] != P[j]: 22 | j = partial[j - 1] 23 | if T[i] == P[j]: j += 1 24 | if j == len(P): 25 | ret.append(i - (j - 1)) 26 | j = 0 27 | 28 | return ret -------------------------------------------------------------------------------- /algorithms/linear_search/c/linearsearch.C: -------------------------------------------------------------------------------- 1 | #include 2 | // linear search function 3 | int linear(int a[], int n, int x){ 4 | for(int i = 0; i < n; i++){ 5 | // if element found return its position 6 | if(a[i] == x){ 7 | return i + 1; 8 | } 9 | } 10 | // If element not in array 11 | return -1; 12 | } 13 | int main(){ 14 | // Sample array 15 | int a[] = {1, 2, 5, 10, 7, 11, 8, 9, 22, 3}; 16 | //Size of array 17 | int n = sizeof(a) / sizeof(a[0]); 18 | // Element to be searched 19 | int x = 7; 20 | // Return value after search 21 | int c = linear(a, n, x); 22 | if(c == -1) 23 | printf("Element not present in list"); 24 | else 25 | printf("Element is at position %d", c); 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /algorithms/linear_search/cpp/linearSearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int linearSearch(int* arr, int size, int num){ 5 | for(int i = 0; i < size; i++){ 6 | if(arr[i] == num){ 7 | return i; 8 | } 9 | } 10 | return -1; 11 | } 12 | int main(){ 13 | int arr[] = {1, 2, 5, 10, 7, 11, 8, 9, 22, 3}; 14 | int size = sizeof(arr) / sizeof(arr[0]); 15 | int num = 7; 16 | int result = linearSearch(arr, size, num); 17 | if(result == -1) 18 | cout << "Element not present in list" << endl; 19 | else 20 | cout << "Element is at position " << result << endl; 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /algorithms/linear_search/java/LinearSearch.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class LinearSearch { 4 | 5 | public static void main(String args[]) 6 | { 7 | int i; 8 | int desiredNumber; 9 | int numList[]; 10 | 11 | Scanner in = new Scanner(System.in); 12 | numList = new int[] {1,2,3,4,5,6,7,8,9,10}; 13 | 14 | System.out.println("Desired Number: "); 15 | desiredNumber = in.nextInt(); 16 | 17 | for (i = 0; i < numList.length; i++) 18 | { 19 | if (numList[i] == desiredNumber) 20 | { 21 | System.out.println("Number found in the array"); 22 | break; 23 | } 24 | } 25 | if (i == numList.length) 26 | System.out.println("Number not in the array"); 27 | } 28 | } 29 | 30 | 31 | -------------------------------------------------------------------------------- /algorithms/linear_search/javascript/linear_search.js: -------------------------------------------------------------------------------- 1 | var linearSearch = function(list, target){ 2 | var result = null, 3 | i = 0, value; 4 | for(; i < list.length; i++){ 5 | value = list[i]; 6 | if(value === target){ 7 | result = i; 8 | break; 9 | } 10 | } 11 | return result; 12 | }; 13 | -------------------------------------------------------------------------------- /algorithms/linear_search/python/linear_search.py: -------------------------------------------------------------------------------- 1 | def linear_search(a,target): 2 | i = 0 3 | while i < len(a) and a[i] != target: 4 | i = i+1 5 | return i < len(a); 6 | 7 | #input: target = target, a = array 8 | print('Insert array (list of ints separated by a space): ') #For example: "1 2 3 4" 9 | a = list(map(int, input().split())) 10 | print('Insert target: ') 11 | target = int(input()) 12 | print('Pos: ') 13 | print(linear_search(a,target)) -------------------------------------------------------------------------------- /algorithms/longest_common_subsequence/cpp/LongestCommonSubsequence.cpp: -------------------------------------------------------------------------------- 1 | /* Dynamic Programming C/C++ implementation of LCS problem */ 2 | #include 3 | 4 | int max(int a, int b); 5 | 6 | /* Returns length of LCS for X[0..m-1], Y[0..n-1] */ 7 | int lcs( char *X, char *Y, int m, int n ) 8 | { 9 | int L[m+1][n+1]; 10 | int i, j; 11 | 12 | /* Following steps build L[m+1][n+1] in bottom up fashion. Note 13 | that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ 14 | for (i=0; i<=m; i++) 15 | { 16 | for (j=0; j<=n; j++) 17 | { 18 | if (i == 0 || j == 0) 19 | L[i][j] = 0; 20 | 21 | else if (X[i-1] == Y[j-1]) 22 | L[i][j] = L[i-1][j-1] + 1; 23 | 24 | else 25 | L[i][j] = max(L[i-1][j], L[i][j-1]); 26 | } 27 | } 28 | 29 | /* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */ 30 | return L[m][n]; 31 | } 32 | 33 | /* Utility function to get max of 2 integers */ 34 | int max(int a, int b) 35 | { 36 | return (a > b)? a : b; 37 | } 38 | 39 | /* Driver program to test above function */ 40 | int main() 41 | { 42 | char X[] = "AGGTAB"; 43 | char Y[] = "GXTXAYB"; 44 | 45 | int m = strlen(X); 46 | int n = strlen(Y); 47 | 48 | printf("Length of LCS is %dn", lcs( X, Y, m, n ) ); 49 | 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /algorithms/longest_common_subsequence/javaj/LCS.java: -------------------------------------------------------------------------------- 1 | /* Returns length of LCS for X[0..m-1], Y[0..n-1] */ 2 | int lcs( char[] X, char[] Y, int m, int n ) 3 | { 4 | int L[][] = new int[m+1][n+1]; 5 | 6 | /* Following steps build L[m+1][n+1] in bottom up fashion. Note 7 | that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ 8 | for (int i=0; i<=m; i++) 9 | { 10 | for (int j=0; j<=n; j++) 11 | { 12 | if (i == 0 || j == 0) 13 | L[i][j] = 0; 14 | else if (X[i-1] == Y[j-1]) 15 | L[i][j] = L[i-1][j-1] + 1; 16 | else 17 | L[i][j] = max(L[i-1][j], L[i][j-1]); 18 | } 19 | } 20 | return L[m][n]; 21 | } 22 | 23 | /* Utility function to get max of 2 integers */ 24 | int max(int a, int b) 25 | { 26 | return (a > b)? a : b; 27 | } 28 | 29 | public static void main(String[] args) 30 | { 31 | LongestCommonSubsequence lcs = new LongestCommonSubsequence(); 32 | String s1 = "AGGTAB"; 33 | String s2 = "GXTXAYB"; 34 | 35 | char[] X=s1.toCharArray(); 36 | char[] Y=s2.toCharArray(); 37 | int m = X.length; 38 | int n = Y.length; 39 | 40 | System.out.println("Length of LCS is" + " " + 41 | lcs.lcs( X, Y, m, n ) ); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /algorithms/longest_common_subsequence/javascript/longest_common_subsequence.js: -------------------------------------------------------------------------------- 1 | function lcs(a, b) { 2 | var aSub = a.substr(0, a.length - 1); 3 | var bSub = b.substr(0, b.length - 1); 4 | 5 | if (a.length === 0 || b.length === 0) { 6 | return ''; 7 | } else if (a.charAt(a.length - 1) === b.charAt(b.length - 1)) { 8 | return lcs(aSub, bSub) + a.charAt(a.length - 1); 9 | } else { 10 | var x = lcs(a, bSub); 11 | var y = lcs(aSub, b); 12 | return (x.length > y.length) ? x : y; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /algorithms/longest_common_subsequence/python/LCS.py: -------------------------------------------------------------------------------- 1 | # Dynamic Programming implementation of LCS problem 2 | 3 | def lcs(X , Y): 4 | # find the length of the strings 5 | m = len(X) 6 | n = len(Y) 7 | 8 | # declaring the array for storing the dp values 9 | L = [[None]*(n+1) for i in xrange(m+1)] 10 | 11 | """Following steps build L[m+1][n+1] in bottom up fashion 12 | Note: L[i][j] contains length of LCS of X[0..i-1] 13 | and Y[0..j-1]""" 14 | for i in range(m+1): 15 | for j in range(n+1): 16 | if i == 0 or j == 0 : 17 | L[i][j] = 0 18 | elif X[i-1] == Y[j-1]: 19 | L[i][j] = L[i-1][j-1]+1 20 | else: 21 | L[i][j] = max(L[i-1][j] , L[i][j-1]) 22 | 23 | # L[m][n] contains the length of LCS of X[0..n-1] & Y[0..m-1] 24 | return L[m][n] 25 | #end of function lcs 26 | 27 | 28 | # Driver program to test the above function 29 | X = "AGGTAB" 30 | Y = "GXTXAYB" 31 | print "Length of LCS is ", lcs(X, Y) 32 | -------------------------------------------------------------------------------- /algorithms/matrix_chain_multiplication/cpp/MCM.cpp: -------------------------------------------------------------------------------- 1 | // See the Cormen book for details of the following algorithm 2 | #include 3 | #include 4 | 5 | // Matrix Ai has dimension p[i-1] x p[i] for i = 1..n 6 | int MatrixChainOrder(int p[], int n) 7 | { 8 | 9 | /* For simplicity of the program, one extra row and one 10 | extra column are allocated in m[][]. 0th row and 0th 11 | column of m[][] are not used */ 12 | int m[n][n]; 13 | 14 | int i, j, k, L, q; 15 | 16 | /* m[i,j] = Minimum number of scalar multiplications needed 17 | to compute the matrix A[i]A[i+1]...A[j] = A[i..j] where 18 | dimension of A[i] is p[i-1] x p[i] */ 19 | 20 | // cost is zero when multiplying one matrix. 21 | for (i=1; i 2 | int a[50]; 3 | void merge(int,int,int); 4 | void merge_sort(int low,int high) 5 | { 6 | int mid; 7 | if(lowmid) 37 | { 38 | for(k=j;k<=high;k++) 39 | { 40 | b[i]=a[k]; 41 | i++; 42 | } 43 | } 44 | else 45 | { 46 | for(k=h;k<=mid;k++) 47 | { 48 | b[i]=a[k]; 49 | i++; 50 | } 51 | } 52 | for(k=low;k<=high;k++) a[k]=b[k]; 53 | } 54 | void main() 55 | { 56 | int num,i; 57 | 58 | cout<<"******************************************************************* 59 | *************"<>num; 70 | cout<>a[i] ; 76 | } 77 | merge_sort(1,num); 78 | cout<[a] -> [a] -> [a] 8 | merge [] ys = ys 9 | merge xs [] = xs 10 | merge (x:xs) (y:ys) 11 | | x > y = y:x:(merge xs ys) 12 | | y >= x = x:y:(merge xs ys) 13 | 14 | mergeSort' :: Ord a => Int -> [a] -> [a] 15 | mergeSort' 1 [x] = [x] 16 | mergeSort' len xs = merge (mergeSort' middle left) (mergeSort' (len-middle) right) 17 | where 18 | middle = len `div` 2 19 | (left, right) = splitAt middle xs 20 | 21 | mergeSort :: Ord a => [a] -> [a] 22 | mergeSort [] = [] 23 | mergeSort [x] = [x] 24 | mergeSort xs = mergeSort' (length xs) xs 25 | -------------------------------------------------------------------------------- /algorithms/merge_sort/javascript/MergeSort.js: -------------------------------------------------------------------------------- 1 | var a = [34, 203, 3, 746, 200, 984, 198, 764, 9]; 2 | 3 | function mergeSort(arr) 4 | { 5 | if (arr.length < 2) 6 | return arr; 7 | 8 | var middle = parseInt(arr.length / 2); 9 | var left = arr.slice(0, middle); 10 | var right = arr.slice(middle, arr.length); 11 | 12 | return merge(mergeSort(left), mergeSort(right)); 13 | } 14 | 15 | function merge(left, right) 16 | { 17 | var result = []; 18 | 19 | while (left.length && right.length) { 20 | if (left[0] <= right[0]) { 21 | result.push(left.shift()); 22 | } else { 23 | result.push(right.shift()); 24 | } 25 | } 26 | 27 | while (left.length) 28 | result.push(left.shift()); 29 | 30 | while (right.length) 31 | result.push(right.shift()); 32 | 33 | return result; 34 | } 35 | 36 | console.log(mergeSort(a)); 37 | -------------------------------------------------------------------------------- /algorithms/merge_sort/python/merge_sort.py: -------------------------------------------------------------------------------- 1 | def merge_sort(li): 2 | # recursively split the lists 3 | if len(li) <= 1: 4 | return li 5 | middle = len(li) / 2 6 | left = li[:middle] 7 | right = li[middle:] 8 | return merge(merge_sort(left), merge_sort(right)) 9 | 10 | 11 | def merge(left, right): 12 | # Merge the two lists back together 13 | result = [] 14 | while left or right: 15 | if left and right: 16 | if left[0] < right[0]: 17 | result.append(left.pop(0)) 18 | else: 19 | result.append(right.pop(0)) 20 | elif left: 21 | result.append(left.pop(0)) 22 | else: 23 | result.append(right.pop(0)) 24 | return result 25 | -------------------------------------------------------------------------------- /algorithms/merge_sort/ruby/merge_sort.rb: -------------------------------------------------------------------------------- 1 | def sort(numbers) 2 | return numbers if numbers.size <= 1 3 | 4 | arr_len = numbers.size 5 | half_size = (arr_len / 2).round 6 | 7 | left_array = numbers.take(half_size) 8 | right_array = numbers.drop(half_size) 9 | 10 | sorted_left = sort(left_array) 11 | sorted_right = sort(right_array) 12 | 13 | merge(sorted_left, sorted_right) 14 | end 15 | 16 | def merge(left, right) 17 | return left if right.empty? 18 | return right if left.empty? 19 | 20 | smallest_number = if left.first <= right.first 21 | left.shift 22 | else 23 | right.shift 24 | end 25 | recursive = merge(left, right) 26 | [smallest_number].concat(recursive) 27 | end 28 | 29 | arr = [1,8,4,5,7,3,9,2,6] 30 | sort(arr) 31 | # => [1, 2, 3, 4, 5, 6, 7, 8, 9] 32 | -------------------------------------------------------------------------------- /algorithms/minimum_spanning_tree/cpp/MST.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int parent[1000]; 5 | int size[1000]; 6 | 7 | //// union find 8 | void init() 9 | { 10 | for(int i=0;i<1000;i++) 11 | { 12 | parent[i]=i; 13 | } 14 | 15 | } 16 | int root(int i) 17 | { 18 | while(parent[i]!=i) 19 | { 20 | parent[i]=parent[parent[i]]; 21 | i=parent[i]; 22 | } 23 | return i; 24 | } 25 | void unio(int a,int b) 26 | { 27 | int root_a=root(a); 28 | int root_b=root(b); 29 | parent[root_a]=parent[root_b]; 30 | } 31 | 32 | ////// krushkal() 33 | #define ll long long 34 | #define mp make_pair 35 | vector > > v; 36 | ll nodes,edges; 37 | 38 | ll kruskal(){ 39 | 40 | int x,y; 41 | ll cost=0,mincost=0; 42 | // step 2. loop through sorted array until all nodes are in same set 43 | for(ll i=0;i>nodes>>edges; 62 | for(int i=0;i>a>>b>>w; 67 | v.push_back(make_pair(w, make_pair(a, b))); 68 | } 69 | // 1. step is to sort all the edges by its weights 70 | sort(v.begin(),v.end()); 71 | cout<<"ans ="< { 12 | if (arr.length === 0) { 13 | result.push(m); 14 | 15 | } else { 16 | for (let i = 0; i < arr.length; i++) { 17 | let current = arr.slice(); 18 | let next = current.splice(i, 1); 19 | 20 | permute(current.slice(), m.concat(next), result); 21 | }; 22 | }; 23 | }; 24 | -------------------------------------------------------------------------------- /algorithms/quick_sort/c/quick_sort.c: -------------------------------------------------------------------------------- 1 | #include 2 | void quicksort(int number[25],int first,int last){ 3 | int i, j, pivot, temp; 4 | 5 | if(firstnumber[pivot]) 14 | j--; 15 | if(i 2 | #include 3 | using namespace std; 4 | 5 | void quickSort(vector&,int,int); 6 | 7 | int partition(vector&, int,int); 8 | 9 | int main() 10 | { 11 | vector A = {6,10,13,5,8,3,2,25,4,11}; 12 | int start = 0; 13 | int end = 10; 14 | 15 | cout << "Before:" << endl; 16 | for(auto value : A) 17 | cout << value <<" "; 18 | cout << endl; 19 | 20 | quickSort(A, start, end); 21 | 22 | cout << "After: " << endl; 23 | for(auto value : A) 24 | cout << value <<" "; 25 | cout << endl; 26 | } 27 | 28 | 29 | void quickSort(vector& A, int start,int end) 30 | { 31 | int pivot; 32 | if(start < end) 33 | { 34 | pivot=partition(A, start, end); 35 | quickSort(A, start, pivot); 36 | quickSort(A, pivot+1, end); 37 | } 38 | } 39 | 40 | 41 | int partition(vector& A, int start,int end) 42 | { 43 | int x = A[start]; 44 | int i = start; 45 | int j; 46 | 47 | for(j = start+1; j < end; j++) 48 | { 49 | if(A[j]<=x) 50 | { 51 | i=i+1; 52 | swap(A[i],A[j]); 53 | } 54 | 55 | } 56 | 57 | swap(A[i],A[start]); 58 | return i; 59 | } 60 | -------------------------------------------------------------------------------- /algorithms/quick_sort/csharp/QuickSort.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace QuickSort 4 | { 5 | class QuickSort 6 | { 7 | static void Main(string[] args) 8 | { 9 | int[] array = { 3, 10, 7, 9, 1, 5, 8 }; 10 | 11 | QuickSort qs = new QuickSort(); 12 | qs.Sort(array, 0, array.Length - 1); 13 | 14 | foreach (var item in array) 15 | { 16 | Console.Write(item.ToString() + ","); 17 | } 18 | } 19 | 20 | void Sort(int[] arr, int low, int high) 21 | { 22 | if (low < high) 23 | { 24 | int index = Partition(arr, low, high); 25 | Sort(arr, low, index - 1); 26 | Sort(arr, index + 1, high); 27 | } 28 | } 29 | 30 | int Partition(int[] arr, int low, int high) 31 | { 32 | int pivot = arr[high]; 33 | int i = (low - 1); 34 | for (int j = low; j < high; j++) 35 | { 36 | if (arr[j] <= pivot) 37 | { 38 | i++; 39 | int aux = arr[i]; 40 | arr[i] = arr[j]; 41 | arr[j] = aux; 42 | } 43 | } 44 | 45 | int temp = arr[i + 1]; 46 | arr[i + 1] = arr[high]; 47 | arr[high] = temp; 48 | 49 | return i + 1; 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /algorithms/quick_sort/haskell/quicksort.hs: -------------------------------------------------------------------------------- 1 | quicksort [] = [] 2 | quicksort (p:xs) = (quicksort lesser) ++ [p] ++ (quicksort greater) 3 | where (lesser, greater) = partition (< p) xs -------------------------------------------------------------------------------- /algorithms/quick_sort/java/QuickSort.java: -------------------------------------------------------------------------------- 1 | public class QuickSort{ 2 | static void quickSort(int[] arr,int start, int end){ 3 | if (start < end){ 4 | int pivot_pos = partition(arr,start,end); 5 | quickSort (arr,start, pivot_pos-1); 6 | quickSort (arr,pivot_pos+1, end); 7 | } 8 | } 9 | 10 | static int partition(int [] arr, int start, int end){ 11 | int pivot = arr[end]; 12 | int i = start, j = end - 1; 13 | while (i <= j) { 14 | if (arr[j] <= pivot && arr[i] > pivot){ 15 | swap(arr,i,j); 16 | } 17 | if (arr[i] <= pivot) { 18 | i++; 19 | } 20 | if (arr [j] > pivot){ 21 | j--; 22 | } 23 | } 24 | swap(arr,i,end); 25 | return i; 26 | } 27 | 28 | static void swap(int[] arr,int i, int j){ 29 | int tmp = arr[i] ; 30 | arr[i] = arr[j]; 31 | arr[j] = tmp; 32 | } 33 | 34 | static void print(int [] arr){ 35 | for (int i = 0; i < arr.length; i++) 36 | System.out.print(arr[i] + " "); 37 | System.out.println(); 38 | } 39 | 40 | public static void main(String [] args){ 41 | int [] arr = {9, 7, 5, 11, 12, 2, 14, 3, 10, 4, 6}; 42 | System.out.print("Before: "); 43 | print(arr); 44 | quickSort(arr,0, arr.length-1); 45 | System.out.print("After: "); 46 | print(arr); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /algorithms/quick_sort/javascript/quick_sort.js: -------------------------------------------------------------------------------- 1 | /* Quicksort implementation in JavaScript */ 2 | 3 | function quicksort(arr, p, r) { 4 | if ( p < r ) { 5 | q = partition(arr, p, r); 6 | quicksort(arr, p, q-1); 7 | quicksort(arr, q+1, r); 8 | } 9 | return arr; 10 | } 11 | 12 | 13 | function partition(arr, p, r) { 14 | x = arr[r]; 15 | i = p-1; 16 | var temp; 17 | for(var j = p; j < r; j++) { 18 | if (arr[j] < x) { 19 | i++; 20 | temp = arr[i]; 21 | arr[i] = arr[j]; 22 | arr[j] = temp; 23 | } 24 | } 25 | i++; 26 | temp = arr[i]; 27 | arr[i] = arr[r]; 28 | arr[r] = temp; 29 | 30 | return i; 31 | } 32 | 33 | 34 | var arr = [9, 8, 7, 6, 5, 4, 3, 2, 1]; 35 | console.log(quicksort(arr, 0, arr.length-1)); 36 | -------------------------------------------------------------------------------- /algorithms/quick_sort/kotlin/quicksort.kt: -------------------------------------------------------------------------------- 1 | class QuickSort { 2 | private fun quickSort(arr: IntArray, start: Int, end: Int) { 3 | if (start < end) { 4 | val pivot_pos = partition(arr, start, end) 5 | quickSort(arr, start, pivot_pos - 1) 6 | quickSort(arr, pivot_pos + 1, end) 7 | } 8 | } 9 | 10 | private fun partition(arr: IntArray, start: Int, end: Int): Int { 11 | val pivot = arr[end] 12 | var i = start 13 | var j = end - 1 14 | while (i <= j) { 15 | if (arr[j] <= pivot && arr[i] > pivot) { 16 | swap(arr, i, j) 17 | } 18 | if (arr[i] <= pivot) { 19 | i++ 20 | } 21 | if (arr[j] > pivot) { 22 | j-- 23 | } 24 | } 25 | swap(arr, i, end) 26 | return i 27 | } 28 | 29 | private fun swap(arr: IntArray, i: Int, j: Int) { 30 | val tmp = arr[i] 31 | arr[i] = arr[j] 32 | arr[j] = tmp 33 | } 34 | 35 | private fun print(arr: IntArray) { 36 | for (i in arr.indices) { 37 | print(arr[i].toString() + " ") 38 | } 39 | print('\n') 40 | } 41 | 42 | fun main() { 43 | val arr = intArrayOf(9, 7, 5, 11, 12, 2, 14, 3, 10, 4, 6) 44 | print("Before: ") 45 | print(arr) 46 | quickSort(arr, 0, arr.size - 1) 47 | print("After: ") 48 | print(arr) 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /algorithms/quick_sort/python/quicksort.py: -------------------------------------------------------------------------------- 1 | def partition(li, start, end): 2 | pivot = li[start] 3 | left = start + 1 4 | right = end 5 | done = False 6 | 7 | while not done: 8 | while left <= right and li[left] <= pivot: 9 | left += 1 10 | while right >= left and li[right] >= pivot: 11 | right -= 1 12 | if right < left: 13 | done = True 14 | else: 15 | li[left], li[right] = li[right], li[left] 16 | li[start], li[right] = li[right], li[start] 17 | return right 18 | 19 | 20 | def quicksort(li, start=0, end=None): 21 | if not end: 22 | end = len(li) - 1 23 | if start < end: 24 | pivot = partition(li, start, end) 25 | # Recursively perform same operation on first and last halves of list 26 | quicksort(li, start, pivot - 1) 27 | quicksort(li, pivot + 1, end) 28 | return li 29 | -------------------------------------------------------------------------------- /algorithms/quick_sort/ruby/quick_sort.rb: -------------------------------------------------------------------------------- 1 | def quicksort(array) 2 | return array if array.length <= 1 3 | 4 | pivot_index = (array.length / 2).to_i 5 | pivot_value = array[pivot_index] 6 | array.delete_at(pivot_index) 7 | 8 | lesser = Array.new 9 | greater = Array.new 10 | 11 | array.each do |x| 12 | if x <= pivot_value 13 | lesser << x 14 | else 15 | greater << x 16 | end 17 | end 18 | 19 | quicksort(lesser) + [pivot_value] + quicksort(greater) 20 | end 21 | 22 | arr = [1,8,4,5,7,3,9,2,6] 23 | quicksort(arr) 24 | # => [1, 2, 3, 4, 5, 6, 7, 8, 9] 25 | -------------------------------------------------------------------------------- /algorithms/rabin_karp/java/RabinKarp.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | import java.util.Random; 3 | public class RabinKarp { 4 | private long patHash; 5 | private int M; 6 | private long Q; 7 | private int R; 8 | private long RM; 9 | public RabinKarp(String pat) 10 | { 11 | M=pat.length(); 12 | R=256; 13 | Q=longPrimeNumber(); 14 | RM=1; 15 | for (int i=1;i<=M-1;i++) 16 | { 17 | RM=(R*RM)%Q; 18 | } 19 | } 20 | private long hash(String key,int M) 21 | { 22 | long h=0; 23 | for (int i=0;i 2 | 3 | using namespace std; 4 | 5 | int getMax(int arr[], int n) 6 | { 7 | int mx = arr[0]; 8 | for (int i = 1; i < n; i++) 9 | if (arr[i] > mx) 10 | mx = arr[i]; 11 | return mx; 12 | } 13 | 14 | void countSort(int arr[], int n, int exp) 15 | { 16 | int output[n]; 17 | int i, count[10] = {0}; 18 | for (i = 0; i < n; i++) 19 | count[ (arr[i]/exp)%10 ]++; 20 | 21 | for (i = 1; i < 10; i++) 22 | count[i] += count[i - 1]; 23 | 24 | for (i = n - 1; i >= 0; i--) 25 | { 26 | output[count[ (arr[i]/exp)%10 ] - 1] = arr[i]; 27 | count[ (arr[i]/exp)%10 ]--; 28 | } 29 | 30 | for (i = 0; i < n; i++) 31 | arr[i] = output[i]; 32 | } 33 | 34 | void radixsort(int arr[], int n) 35 | { 36 | int m = getMax(arr, n); 37 | for (int exp = 1; m/exp > 0; exp *= 10) 38 | countSort(arr, n, exp); 39 | } 40 | 41 | void print(int arr[], int n) 42 | { 43 | for (int i = 0; i < n; i++) 44 | cout << arr[i] << " "; 45 | } 46 | 47 | int main() 48 | { 49 | int arr[] = {170, 45, 75, 90, 802, 24, 2, 66}; 50 | int n = sizeof(arr)/sizeof(arr[0]); 51 | radixsort(arr, n); 52 | print(arr, n); 53 | return 0; 54 | } 55 | -------------------------------------------------------------------------------- /algorithms/radixsort/python/lsd_radixsort.py: -------------------------------------------------------------------------------- 1 | import functools 2 | 3 | 4 | def get_digit(number, digit): 5 | return int((number % (10 ** digit)) / (10 ** (digit - 1))) 6 | 7 | 8 | def lsd_radix_sort(array): 9 | MAX_DIGITS = 10 10 | for digit in range(1, MAX_DIGITS + 1): 11 | buckets = [[] for _ in range(10)] 12 | for number in array: 13 | buckets[get_digit(number, digit)].append(number) 14 | array = functools.reduce(lambda x, y: x + y, buckets, []) 15 | return array 16 | 17 | 18 | if __name__ == '__main__': 19 | print (lsd_radix_sort([43, 1243, 354, 0, 1, 22])) 20 | print (lsd_radix_sort([2, 10])) 21 | print (lsd_radix_sort([1])) 22 | print (lsd_radix_sort([])) 23 | -------------------------------------------------------------------------------- /algorithms/selection_sort/c/SelectionSort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | const int SIZE=100; 4 | 5 | void SelectionSort(int arr[SIZE]){ 6 | int i,j,temp,min=999999,index; 7 | for (i = 0; i < SIZE; i++) { 8 | for (j = i; j < SIZE; j++) { 9 | if(arr[j] array[j] 10 | min_index = j 11 | end 12 | j += 1 13 | break if j == array.size 14 | end 15 | 16 | array[i], array[min_index] = array[min_index], array[i] 17 | 18 | i += 1 19 | break if i == array.size 20 | end 21 | 22 | array 23 | end 24 | 25 | numbers = [4, 2, 8, 1, 30, 0, 10, 16] 26 | 27 | puts "Unsorted: #{numbers}" 28 | 29 | puts "Sorted: #{selection_sort(numbers)}" 30 | -------------------------------------------------------------------------------- /algorithms/selection_sort/java/SelectionSort.java: -------------------------------------------------------------------------------- 1 | // Java program for implementation of Selection Sort 2 | class SelectionSort 3 | { 4 | // Implementation of Selection Sort 5 | void sort(int ar[]) 6 | { 7 | int n = ar.length; 8 | for (int i = 0; i < n-1; i++) 9 | { 10 | int min = i, temp; 11 | for (int j = i+1; j < n; j++) 12 | if (ar[j] < ar[min]){ 13 | min = j; 14 | } 15 | temp = ar[min]; 16 | ar[min] = ar[i]; 17 | ar[i] = temp; 18 | } 19 | } 20 | // Prints the array 21 | void printArray(int arr[]) 22 | { 23 | int n = arr.length; 24 | for (int i = 0; i < n; i++) 25 | System.out.print(arr[i] + " "); 26 | } 27 | // Main function to test 28 | public static void main(String args[]) 29 | { 30 | SelectionSort ob = new SelectionSort(); 31 | int arr[] = {79, 34, 7, 23, 11, 10, 99, 1, 15, 11}; 32 | ob.sort(arr); 33 | System.out.println("Sorted array:"); 34 | ob.printArray(arr); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /algorithms/selection_sort/javascript/selection_sort.js: -------------------------------------------------------------------------------- 1 | var selectionSort = function(array){ 2 | for(var i = 0; i < array.length; i++){ 3 | //set min to the current iteration of i 4 | var min = i; 5 | for(var j = i+1; j < array.length; j++){ 6 | if(array[j] < array[min]){ 7 | min = j; 8 | } 9 | } 10 | var temp = array[i]; 11 | array[i] = array[min]; 12 | array[min] = temp; 13 | } 14 | return array; 15 | }; 16 | -------------------------------------------------------------------------------- /algorithms/selection_sort/python/selection_sort.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sun Oct 1 21:17 2017 4 | @author: john2ksonn 5 | 6 | Just a simple implementation of the selectionsort algo 7 | """ 8 | 9 | def selectionsort(a): 10 | n = len(a) 11 | left = 0 12 | while left < n: 13 | minVal = left 14 | for i in range(left + 1, n): 15 | if(a[i] < a[minVal]): 16 | minVal = i 17 | temp = a[left] 18 | a[left] = a[minVal] 19 | a[minVal] = temp 20 | left += 1 21 | 22 | 23 | a = [12, 33, 1, 3, 54, 32, 78, 54, 99, 6] 24 | print(a) 25 | selectionsort(a) 26 | print(a) 27 | -------------------------------------------------------------------------------- /algorithms/selection_sort/ruby/selection_sort.rb: -------------------------------------------------------------------------------- 1 | def selection_sort(input_arr) 2 | arr = input_arr.dup 3 | n = arr.size - 1 4 | 5 | n.times do |i| 6 | index_min = i 7 | (i + 1).upto(n) do |j| 8 | index_min = j if arr[j] < arr[index_min] 9 | end 10 | arr[i], arr[index_min] = arr[index_min], arr[i] if index_min != i 11 | end 12 | arr 13 | end 14 | 15 | arr = [1,8,4,5,7,3,9,2,6] 16 | selection_sort(arr) 17 | # => [1, 2, 3, 4, 5, 6, 7, 8, 9] 18 | -------------------------------------------------------------------------------- /algorithms/shell_sort/C++/ShellSort.cpp: -------------------------------------------------------------------------------- 1 | // C++ implementation of Shell Sort 2 | #include 3 | using namespace std; 4 | 5 | /* function to sort arr using shellSort */ 6 | int shellSort(int arr[], int n) 7 | { 8 | // Start with a big gap, then reduce the gap 9 | for (int gap = n/2; gap > 0; gap /= 2) 10 | { 11 | // Do a gapped insertion sort for this gap size. 12 | // The first gap elements a[0..gap-1] are already in gapped order 13 | // keep adding one more element until the entire array is 14 | // gap sorted 15 | for (int i = gap; i < n; i += 1) 16 | { 17 | // add a[i] to the elements that have been gap sorted 18 | // save a[i] in temp and make a hole at position i 19 | int temp = arr[i]; 20 | 21 | // shift earlier gap-sorted elements up until the correct 22 | // location for a[i] is found 23 | int j; 24 | for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) 25 | arr[j] = arr[j - gap]; 26 | 27 | // put temp (the original a[i]) in its correct location 28 | arr[j] = temp; 29 | } 30 | } 31 | return 0; 32 | } 33 | 34 | void printArray(int arr[], int n) 35 | { 36 | for (int i=0; i 2 | 3 | void shellsort(int arr[], int num) 4 | { 5 | int i, j, k, tmp; 6 | for (i = num / 2; i > 0; i = i / 2) 7 | { 8 | for (j = i; j < num; j++) 9 | { 10 | for(k = j - i; k >= 0; k = k - i) 11 | { 12 | if (arr[k+i] >= arr[k]) 13 | break; 14 | 15 | else 16 | { 17 | tmp = arr[k]; 18 | arr[k] = arr[k+i]; 19 | arr[k+i] = tmp; 20 | } 21 | } 22 | } 23 | } 24 | } 25 | 26 | int main() 27 | { 28 | int arr[] = {12, 34, 54, 2, 3}, i; 29 | int n = sizeof(arr)/sizeof(arr[0]); 30 | shellsort(arr, n); 31 | printf("\n Sorted array is: "); 32 | for (i = 0; i < n; i++) 33 | printf("%d ", arr[i]); 34 | return 0; 35 | 36 | } 37 | -------------------------------------------------------------------------------- /algorithms/shell_sort/Java/ShellSort.java: -------------------------------------------------------------------------------- 1 | // Java implementation of ShellSort 2 | class ShellSort 3 | { 4 | /* An utility function to print array of size n*/ 5 | static void printArray(int arr[]) 6 | { 7 | int n = arr.length; 8 | for (int i=0; i 0; gap /= 2) 20 | { 21 | // Do a gapped insertion sort for this gap size. 22 | // The first gap elements a[0..gap-1] are already 23 | // in gapped order keep adding one more element 24 | // until the entire array is gap sorted 25 | for (int i = gap; i < n; i += 1) 26 | { 27 | // add a[i] to the elements that have been gap 28 | // sorted save a[i] in temp and make a hole at 29 | // position i 30 | int temp = arr[i]; 31 | 32 | // shift earlier gap-sorted elements up until 33 | // the correct location for a[i] is found 34 | int j; 35 | for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) 36 | arr[j] = arr[j - gap]; 37 | 38 | // put temp (the original a[i]) in its correct 39 | // location 40 | arr[j] = temp; 41 | } 42 | } 43 | return 0; 44 | } 45 | 46 | // Driver method 47 | public static void main(String args[]) 48 | { 49 | int arr[] = {12, 34, 54, 2, 3}; 50 | System.out.println("Array before sorting"); 51 | printArray(arr); 52 | 53 | ShellSort ob = new ShellSort(); 54 | ob.sort(arr); 55 | 56 | System.out.println("Array after sorting"); 57 | printArray(arr); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /algorithms/shell_sort/python/shellsort.py: -------------------------------------------------------------------------------- 1 | def shellSort(arr): 2 | 3 | # Start with a big gap, then reduce the gap 4 | n = len(arr) 5 | gap = n/2 6 | 7 | # Do a gapped insertion sort for this gap size. 8 | # The first gap elements a[0..gap-1] are already in gapped 9 | # order keep adding one more element until the entire array 10 | # is gap sorted 11 | while gap > 0: 12 | 13 | for i in range(gap,n): 14 | 15 | # add a[i] to the elements that have been gap sorted 16 | # save a[i] in temp and make a hole at position i 17 | temp = arr[i] 18 | 19 | # shift earlier gap-sorted elements up until the correct 20 | # location for a[i] is found 21 | j = i 22 | while j >= gap and arr[j-gap] >temp: 23 | arr[j] = arr[j-gap] 24 | j -= gap 25 | 26 | # put temp (the original a[i]) in its correct location 27 | arr[j] = temp 28 | gap /= 2 29 | -------------------------------------------------------------------------------- /algorithms/sieve_of_eratosthenes/cpp/sieve_of_eratosthenes.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to print all primes smaller than or equal to 2 | // n using Sieve of Eratosthenes 3 | #include 4 | using namespace std; 5 | 6 | void SieveOfEratosthenes(int n) 7 | { 8 | // Create a boolean array "prime[0..n]" and initialize 9 | // all entries it as true. A value in prime[i] will 10 | // finally be false if i is Not a prime, else true. 11 | bool prime[n+1]; 12 | memset(prime, true, sizeof(prime)); 13 | 14 | for (int p=2; p*p<=n; p++) 15 | { 16 | // If prime[p] is not changed, then it is a prime 17 | if (prime[p] == true) 18 | { 19 | // Update all multiples of p 20 | for (int i=p*2; i<=n; i += p) 21 | prime[i] = false; 22 | } 23 | } 24 | 25 | // Print all prime numbers 26 | for (int p=2; p<=n; p++) 27 | if (prime[p]) 28 | cout << p << " "; 29 | } 30 | 31 | // Driver Program to test above function 32 | int main() 33 | { 34 | int n = 100; 35 | cout << "Following are the prime numbers smaller " 36 | << " than or equal to " << n << endl; 37 | SieveOfEratosthenes(n); 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /algorithms/sieve_of_eratosthenes/javascript/sieve.js: -------------------------------------------------------------------------------- 1 | let sieveOfEratosthenes = function(n) { 2 | let array = []; 3 | let upperLimit = Math.sqrt(n); 4 | let output = []; 5 | 6 | for (let i = 0; i < n; i++) { 7 | array.push(true); 8 | } 9 | 10 | for (let i = 2; i <= upperLimit; i++) { 11 | if (array[i]) { 12 | for (let j = i * i; j < n; j += i) { 13 | array[j] = false; 14 | } 15 | } 16 | } 17 | 18 | for (let i = 2; i < n; i++) { 19 | if (array[i]) { 20 | output.push(i); 21 | } 22 | } 23 | 24 | return output; 25 | }; 26 | -------------------------------------------------------------------------------- /algorithms/sieve_of_eratosthenes/python/sieve.py: -------------------------------------------------------------------------------- 1 | def run_sieve(N, isPrime): 2 | for i in range(N+1): 3 | if isPrime[i]: 4 | for j in range(i+1, N+1): 5 | if j % i == 0: 6 | isPrime[j] = False 7 | 8 | 9 | def print_sieve(N, isPrime): 10 | for i in range(N+1): 11 | if isPrime[i]: 12 | print i, 13 | 14 | 15 | def sieve(N): 16 | isPrime = [True] * (N+1) 17 | isPrime[0], isPrime[1] = False, False 18 | run_sieve(N, isPrime) 19 | print_sieve(N, isPrime) 20 | 21 | 22 | sieve(int(input("Input size of sieve: "))) 23 | -------------------------------------------------------------------------------- /algorithms/strings/cpp/anagrams.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | bool isAnagram(string a, string b) 5 | { 6 | sort(a.begin(),a.end()); 7 | sort(b.begin(),b.end()); 8 | if(a.compare(b)==0) 9 | return true; 10 | return false; 11 | } 12 | 13 | vector findAnagrams(string arr[], int n) 14 | { 15 | vector v; 16 | for(int i=0;i"< ress = findAnagrams(arr, n); 38 | for(int i=0;i 2 | using namespace std; 3 | int moves(0); 4 | void Hanoi(int m, char a, char b, char c); 5 | int main(){ 6 | 7 | int discs; 8 | cout << "Enter the number of discs: " << endl; 9 | cin >> discs; 10 | Hanoi(discs, 'A', 'B', 'C'); 11 | cout << "It took " << moves << " moves. " << endl; 12 | return 0; 13 | } 14 | 15 | void Hanoi(int m, char a, char b, char c) 16 | { 17 | moves++; 18 | if(m == 1){ 19 | cout << "Move disc " << m << " from " << a << " to " << c << endl; 20 | } 21 | else{ 22 | Hanoi(m-1, a,c,b); 23 | cout << "Move disc " << m << " from " << a << " to " << c << endl; 24 | Hanoi(m-1,b,a,c); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /algorithms/tower_of_hanoi/java/towers_of_hanoi.java: -------------------------------------------------------------------------------- 1 | public class TowersOfHanoi { 2 | 3 | public void solve(int n, String start, String auxiliary, String end) { 4 | if (n == 1) { 5 | System.out.println(start + " -> " + end); 6 | } else { 7 | solve(n - 1, start, end, auxiliary); 8 | System.out.println(start + " -> " + end); 9 | solve(n - 1, auxiliary, start, end); 10 | } 11 | } 12 | 13 | public static void main(String[] args) { 14 | TowersOfHanoi towersOfHanoi = new TowersOfHanoi(); 15 | System.out.print("Enter number of discs: "); 16 | Scanner scanner = new Scanner(System.in); 17 | int discs = scanner.nextInt(); 18 | towersOfHanoi.solve(discs, "A", "B", "C"); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /algorithms/tower_of_hanoi/javascript/tower_of_hanoi.js: -------------------------------------------------------------------------------- 1 | 2 | // Prints the movement 3 | function moveDisk(from_pole, to_pole) { 4 | console.log("Moving disk from " + 5 | from_pole + " to " + to_pole); 6 | } 7 | 8 | // Tower of Hanoi implementation 9 | function towerOfHanoi(height, from_pole=1, to_pole=2, aux=3) { 10 | if (height > 0) { 11 | towerOfHanoi(height - 1, from_pole, to_pole, aux); 12 | moveDisk(from_pole, to_pole); 13 | towerOfHanoi(height - 1, aux, from_pole, to_pole); 14 | } 15 | } 16 | 17 | towerOfHanoi(3); 18 | -------------------------------------------------------------------------------- /algorithms/tower_of_hanoi/php/towers_of_hanoi.php: -------------------------------------------------------------------------------- 1 | = 1){ 5 | move($n-1, $src,$temp, $dest); 6 | printf("Moving %d -> %d ",$src, $dest); 7 | echo "
"; 8 | move($n-1, $temp , $dest , $src); 9 | } 10 | } 11 | 12 | move(3,1,3,2); 13 | 14 | ?> -------------------------------------------------------------------------------- /algorithms/tower_of_hanoi/python/tower_of_hanoi.py: -------------------------------------------------------------------------------- 1 | 2 | def move_disk(from_pole, to_pole): 3 | ''' 4 | Prints the movement 5 | ''' 6 | print('Moving disk from', from_pole, ' to ', to_pole) 7 | 8 | def tower_of_hanoi(height, from_pole=1, to_pole=2, aux=3): 9 | ''' 10 | Tower of Hanoi implementation 11 | ''' 12 | if height > 0: 13 | tower_of_hanoi(height - 1, from_pole, to_pole, aux) 14 | move_disk(from_pole, to_pole) 15 | tower_of_hanoi(height - 1, aux, from_pole, to_pole) 16 | 17 | if __name__ == '__main__': 18 | tower_of_hanoi(3) 19 | -------------------------------------------------------------------------------- /data_structures/arraylist/java/arraylist.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class arraylist { 3 | 4 | public static void main(String args[]) { 5 | // create an array list 6 | ArrayList al = new ArrayList(); 7 | System.out.println("Initial size of al: " + al.size()); 8 | 9 | // add elements to the array list 10 | al.add("C"); 11 | al.add("A"); 12 | al.add("E"); 13 | al.add("B"); 14 | al.add("D"); 15 | al.add("F"); 16 | al.add(1, "A2"); 17 | System.out.println("Size of al after additions: " + al.size()); 18 | 19 | // display the array list 20 | System.out.println("Contents of al: " + al); 21 | 22 | // Remove elements from the array list 23 | al.remove("F"); 24 | al.remove(2); 25 | System.out.println("Size of al after deletions: " + al.size()); 26 | System.out.println("Contents of al: " + al); 27 | } 28 | } -------------------------------------------------------------------------------- /data_structures/binary_search_tree/binary_search_tree.md: -------------------------------------------------------------------------------- 1 | 2 | ## ELI5 3 | A tree is a container that stores items in sorted order in memory.It's like the inversed version of an actual tree. 4 | 5 | ### Pros 6 | * BSTs allow fast lookup, addition and removal of items. 7 | ### Cons 8 | * Tree gets skewed to one side when we save sorted items.The advantage of fast operations is lost. 9 | 10 | ## Technical Explaination 11 | Binary Search Tree is a node-based binary tree data structure. 12 | *NODE: All items are stored in nodes. 13 | *ROOT: The top node in a tree. 14 | *CHILD: A node directly connected to another node when moving away from the Root.Each node can have 0 to 2 child nodes.Left child's value is smaller than its parent and right child's value is greater than its parent. 15 | *LEAVES: Nodes with no child nodes. 16 | *HEIGHT: Number of edges on the longest path between the root and a leaf. 17 | *DEPTH: The depth of a node is the number of edges from the tree's root node to the node. 18 | 19 | Storing 2,4,1,10,3 in a BST: 20 | 2 21 | / \ 22 | 1 4 23 | / \ 24 | 3 10 25 | 26 | 27 | ### Pros 28 | * Time Complexity of insertion,deletion and search is O(h). h=height of tree 29 | i.e. O(log n) which is less than linked list and array. n=number of nodes 30 | ### Cons 31 | * For a skewed binary tree time complexity of insertion,deletion and search is O(n). 32 | As for a skewed binary tree height h is O(n). 33 | e.g 2,3,4,5 34 | 2 35 | \ 36 | 3 37 | \ 38 | 4 39 | \ 40 | 5 41 | 42 | -------------------------------------------------------------------------------- /data_structures/binary_search_tree/java/bst_operations/CheckBST.java: -------------------------------------------------------------------------------- 1 | package bst_operations; 2 | 3 | public class CheckBST { 4 | public static void main(String[] args) { 5 | new CheckBST().demo(); 6 | } 7 | 8 | private void demo() { 9 | Node n = new Node(4); 10 | // left 11 | n.left = new Node(2); 12 | n.left.left = new Node(1); 13 | n.left.right = new Node(3); 14 | 15 | //right 16 | n.right = new Node(5); 17 | System.out.println(isBST(n, Integer.MIN_VALUE, Integer.MAX_VALUE)); 18 | } 19 | 20 | private boolean isBST(Node n, int min, int max) { 21 | if (n == null) { 22 | return true; 23 | } 24 | if (n.data < min || n.data > max) { 25 | return false; 26 | } 27 | if(n.data == max || n.data == min) { 28 | System.out.println("duplication of data"); 29 | return false; 30 | } 31 | return isBST(n.left, min, n.data) && isBST(n.right, n.data, max); 32 | } 33 | } 34 | 35 | -------------------------------------------------------------------------------- /data_structures/binary_search_tree/java/bst_operations/CorrectBST.java: -------------------------------------------------------------------------------- 1 | package bst_operations; 2 | 3 | import java.util.ArrayList; 4 | 5 | /** 6 | * Two nodes of a BST are swapped, correct the BST 7 | */ 8 | public class CorrectBST { 9 | public static void main(String[] args) { 10 | new CorrectBST().demo(); 11 | } 12 | 13 | private void demo() { 14 | Node n = new Node(10); 15 | n.left = new Node(5); 16 | n.left.left = new Node(2); 17 | n.left.right = new Node(20); 18 | n.right = new Node(8); 19 | /* 20 | 10 21 | / \ 22 | 5 8 23 | / \ 24 | 2 20 25 | */ 26 | ArrayList list = new ArrayList(); 27 | display(n); 28 | balanceBST(n, list, Integer.MIN_VALUE, Integer.MAX_VALUE); 29 | System.out.println(); 30 | list.get(0).data = list.get(0).data + list.get(1).data; 31 | list.get(1).data = list.get(0).data - list.get(1).data; 32 | list.get(0).data = list.get(0).data - list.get(1).data; 33 | System.out.println("After"); 34 | display(n); 35 | } 36 | 37 | private void display(Node n) { 38 | if (n != null) { 39 | display(n.left); 40 | System.out.print(n.data + "\t"); 41 | display(n.right); 42 | } 43 | } 44 | 45 | private void balanceBST(Node n, ArrayList list, int min, int max) { 46 | if (n == null) { 47 | return; 48 | } 49 | if (n.data > max || n.data < min) { 50 | list.add(n); 51 | } 52 | balanceBST(n.left, list, min, n.data); 53 | balanceBST(n.right, list, n.data, max); 54 | 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /data_structures/binary_search_tree/java/bst_operations/InorderSuccessor.java: -------------------------------------------------------------------------------- 1 | package bst_operations; 2 | 3 | public class InorderSuccessor { 4 | public static void main(String[] args) { 5 | new InorderSuccessor().demo(); 6 | } 7 | 8 | private void demo() { 9 | Node n = new Node(8); 10 | // left 11 | n.left = new Node(3); 12 | n.left.left = new Node(1); 13 | n.left.right = new Node(6); 14 | n.left.right.left = new Node(4); 15 | n.left.right.right = new Node(7); 16 | 17 | //right 18 | n.right = new Node(10); 19 | n.right.right = new Node(14); 20 | n.right.right.left = new Node(13); 21 | 22 | /* 23 | 8 24 | 3 10 25 | 1 6 14 26 | 4 7 13 27 | * 28 | * */ 29 | System.out.println(getNextSuccessor(n, new Node(8))); 30 | } 31 | 32 | private Integer getNextSuccessor(Node root, Node target) { 33 | if (root == null || target == null) { 34 | return null; 35 | } 36 | Boolean found = false; 37 | Node candidate = null; 38 | Node current = root; 39 | while (current != null) { 40 | if (current.data == target.data) { 41 | found = true; 42 | current = current.right; 43 | } else if (current.data > target.data) { 44 | candidate = current; 45 | current = current.left; 46 | } else { 47 | current = current.right; 48 | } 49 | } 50 | return found && candidate != null ? candidate.data : null; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /data_structures/binary_search_tree/java/bst_operations/Node.java: -------------------------------------------------------------------------------- 1 | package bst_operations; 2 | 3 | public class Node { 4 | int data; 5 | Node left; 6 | Node right; 7 | 8 | public Node(int d) { 9 | data = d; 10 | } 11 | } 12 | 13 | -------------------------------------------------------------------------------- /data_structures/binary_search_tree/javascript/binary_tree.js: -------------------------------------------------------------------------------- 1 | // Cleaner Logging 2 | export const _ = (...vals) => console.log(...vals); 3 | 4 | // Create BST Node 5 | export function BST(val) { 6 | let self = Object.create(BST.prototype); 7 | 8 | // Create Based Properties of BST Node 9 | self.value = val; 10 | self.right = undefined; 11 | self.left = undefined; 12 | 13 | // Insert Function, to properly place value in tree structure 14 | 15 | return self; 16 | } 17 | BST.prototype.insert = function(value) { 18 | let node = BST(value); 19 | function recurse(bst) { 20 | if (bst.value > value && bst.left === undefined) { 21 | bst.left = node; 22 | } else if (bst.value > value) { 23 | recurse(bst.left); 24 | } else if (bst.value < value && bst.right === undefined) { 25 | bst.right = node; 26 | } else if (bst.value < value) { 27 | recurse(bst.right); 28 | } 29 | } 30 | 31 | recurse(this); 32 | }; 33 | -------------------------------------------------------------------------------- /data_structures/binary_search_tree/python/bst1.py: -------------------------------------------------------------------------------- 1 | # Python program to demonstrate insert operation in binary search tree 2 | 3 | # A utility class that represents an individual node in a BST 4 | class Node: 5 | def __init__(self,key): 6 | self.left = None 7 | self.right = None 8 | self.val = key 9 | 10 | # A utility function to insert a new node with the given key 11 | def insert(root,node): 12 | if root is None: 13 | root = node 14 | else: 15 | if root.val < node.val: 16 | if root.right is None: 17 | root.right = node 18 | else: 19 | insert(root.right, node) 20 | else: 21 | if root.left is None: 22 | root.left = node 23 | else: 24 | insert(root.left, node) 25 | 26 | # A utility function to do inorder tree traversal 27 | def inorder(root): 28 | if root: 29 | inorder(root.left) 30 | print(root.val) 31 | inorder(root.right) 32 | 33 | 34 | # Driver program to test the above functions 35 | # Let us create the following BST 36 | # 50 37 | # / \ 38 | # 30 70 39 | # / \ / \ 40 | # 20 40 60 80 41 | r = Node(50) 42 | insert(r,Node(30)) 43 | insert(r,Node(20)) 44 | insert(r,Node(40)) 45 | insert(r,Node(70)) 46 | insert(r,Node(60)) 47 | insert(r,Node(80)) 48 | 49 | # Print inoder traversal of the BST 50 | inorder(r) 51 | -------------------------------------------------------------------------------- /data_structures/binary_tree/cpp/binary_tree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct Node { 4 | int key; 5 | Node *leftnode; 6 | Node *rightnode; 7 | std::string value; 8 | Node(int tkey, const std::string& tvalue) : leftnode(nullptr), rightnode(nullptr), key(tkey), value(tvalue) {} 9 | }; 10 | 11 | Node root_node(1, "Node #1"); 12 | std::string query_bst(const int key) { 13 | Node *cur_node = &root_node; 14 | while (cur_node != nullptr) { 15 | if (key == cur_node->key) { 16 | return cur_node->value; 17 | } 18 | if (key < cur_node->key) { 19 | cur_node = cur_node->leftnode; 20 | } else { 21 | cur_node = cur_node->rightnode; 22 | } 23 | } 24 | return ""; 25 | } 26 | 27 | void insert_bst(int key, const std::string& value) { 28 | Node *cur_node; 29 | Node *next_node = &root_node; 30 | while (next_node != nullptr) { 31 | cur_node = next_node; 32 | if (key < cur_node->key) { 33 | next_node = cur_node->leftnode; 34 | } else { 35 | next_node = cur_node->rightnode; 36 | } 37 | } 38 | if (key < cur_node->key) { 39 | cur_node->leftnode = new Node(key, value); 40 | } 41 | else { 42 | cur_node->rightnode = new Node(key, value); 43 | } 44 | } 45 | 46 | int main() { 47 | insert_bst(2, "Node #2"); 48 | insert_bst(3, "Node #3"); 49 | std::cout << query_bst(3) << '\n'; 50 | } 51 | -------------------------------------------------------------------------------- /data_structures/binary_tree/java/binary_tree_dfs.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Node{ 4 | int data; 5 | Node left,right; 6 | 7 | public Node(int item){ 8 | data = item; 9 | left = right = null; 10 | } 11 | 12 | } 13 | 14 | class BinaryTree{ 15 | 16 | Node root; 17 | BinaryTree(){ 18 | root = null; 19 | } 20 | 21 | 22 | public void preorder_rec(Node node){ 23 | 24 | if(node == null) return; 25 | System.out.println(node.data); 26 | 27 | preorder_rec(node.left); 28 | 29 | preorder_rec(node.right); 30 | 31 | } 32 | 33 | 34 | 35 | public void inorder_rec(Node node){ 36 | 37 | if(node == null) return; 38 | 39 | inorder_rec(node.left); 40 | 41 | System.out.println(node.data); 42 | 43 | inorder_rec(node.right); 44 | 45 | } 46 | 47 | 48 | 49 | public void postorder(Node node){ 50 | 51 | if(node == null) return; 52 | postorder(node.left); 53 | 54 | postorder(node.right); 55 | 56 | System.out.println(node.data); 57 | 58 | } 59 | 60 | 61 | 62 | public static void main(String[] args){ 63 | 64 | BinaryTree bt = new BinaryTree(); 65 | 66 | bt.root = new Node(1); 67 | bt.root.left = new Node(2); 68 | bt.root.right = new Node(3); 69 | bt.root.left.left = new Node(4); 70 | bt.root.left.right = new Node(5); 71 | bt.root.right.right = new Node(7); 72 | bt.root.right.left = new Node(6); 73 | bt.queue.add(bt.root); 74 | 75 | 76 | System.out.println("Preorder Recursive"); 77 | bt.preorder_rec(bt.root); 78 | 79 | System.out.println("Inorder Recursive"); 80 | bt.inorder_rec(bt.root); 81 | 82 | System.out.println("Postorder"); 83 | bt.postorder(bt.root); 84 | 85 | 86 | 87 | } 88 | 89 | } -------------------------------------------------------------------------------- /data_structures/binary_tree/python/binary_tree.py: -------------------------------------------------------------------------------- 1 | class BinaryTree: 2 | def __init__(self,rootObj): 3 | self.key = rootObj 4 | self.leftChild = None 5 | self.rightChild = None 6 | 7 | def insertLeft(self,newNode): 8 | if self.leftChild == None: 9 | self.leftChild = BinaryTree(newNode) 10 | else: 11 | t = BinaryTree(newNode) 12 | t.leftChild = self.leftChild 13 | self.leftChild = t 14 | 15 | def insertRight(self,newNode): 16 | if self.rightChild == None: 17 | self.rightChild = BinaryTree(newNode) 18 | else: 19 | t = BinaryTree(newNode) 20 | t.rightChild = self.rightChild 21 | self.rightChild = t 22 | 23 | 24 | def getRightChild(self): 25 | return self.rightChild 26 | 27 | def getLeftChild(self): 28 | return self.leftChild 29 | 30 | def setRootVal(self,obj): 31 | self.key = obj 32 | 33 | def getRootVal(self): 34 | return self.key 35 | 36 | -------------------------------------------------------------------------------- /data_structures/bloom_filter/python/bloom_filter.py: -------------------------------------------------------------------------------- 1 | # A simple bloom filter in Python 3 2 | # Author: Flora Rosenkreuz (reindeer-cafe) 3 | import math 4 | 5 | class BloomFilter: 6 | 7 | # very simple string encode 8 | def SimpleStringEncode(self, data): 9 | hash = 0 10 | for x in data: hash += (ord(x)) 11 | return hash % 20 12 | 13 | # implementation of the fnv hash 14 | def FNV(self, data): 15 | hash = 2166136261 16 | b = bytes(data, 'utf-8') 17 | for byte in b: 18 | hash = hash ^ byte 19 | hash = hash * 16777619 20 | return hash % 20 21 | 22 | # add a string to the filter 23 | def Add(self, data): 24 | h1 = self.SimpleStringEncode(data) 25 | h2 = self.FNV(data) 26 | self.Vector[h1] = 1 27 | self.Vector[h2] = 1 28 | 29 | # false positives are possible in a bloom filter hence is "possibly" in 30 | def IsPossiblyIn(self, data): 31 | #m num b 32 | h1 = self.SimpleStringEncode(data) 33 | h2 = self.FNV(data) 34 | return True if (self.Vector[h1] and self.Vector[h2]) else False 35 | 36 | # computes the approximate false positive rate 37 | def ComputeCollisionRate(self): 38 | n = 0 39 | for b in self.Vector: 40 | n += 1 if b else 0 41 | return math.pow((1 - (math.pow(math.e, (((-1 * 2) * n) / 20)))), 2) 42 | 43 | def __init__(self): 44 | self.Vector = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] 45 | -------------------------------------------------------------------------------- /data_structures/circular_queue/circular_queue.md: -------------------------------------------------------------------------------- 1 | ## ELI5 2 | CIRCULAR QUEUE is a queue in which last position is connected back to first position,i.e. after last location of the list we visit the first location.Forms a circle. 3 | 4 | ### Pros: 5 | * Fast operations of adding and removing elements. 6 | * Utilizes memory efficiently. 7 | 8 | ### Cons: 9 | * May become a never-ending loop. 10 | 11 | ## TECHNICAL EXPLAINATION 12 | A FIFO data structure ,also called ‘Ring Buffer’,where last element points back to the first element to make a circle. 13 | * Operations on Circular Queue:. 14 | *enqueue(element): This function is used to insert an element into the circular queue. The new element is always inserted at Rear position. 15 | Steps: 16 | Check whether queue is Full – Check ((REAR == SIZE && FRONT == 1) || (REAR == FRONT-1)) If TRUE,queue is full. If queue is not full then insert element. 17 | *dequeue(): This function is used to delete an element from the circular queue.The element is always deleted from FRONT position. 18 | eg. CQueue = 1,2,3,4,_ 19 | enqueue(5) gives CQueue=1,2,3,4,5 20 | dequeue() gives CQueue= _,2,3,4,5 21 | enqueue(6) gives CQueue=6,2,3,4,5 22 | 23 | ### Pros: 24 | * Time complexity of enqueue(), dequeue() operation is O(1). 25 | * Prevents wastage of space of Simple Queue. 26 | 27 | ### Cons: 28 | * A circular queue might cause an an infinite loop, impairing processing - if not implemented properly or in a multi-threaded environment. 29 | * Complex to code. 30 | -------------------------------------------------------------------------------- /data_structures/circular_queue/java/circular_queue.java: -------------------------------------------------------------------------------- 1 | //circular queue 2 | import java.util.*; 3 | interface queue1 4 | { 5 | void insert(); 6 | void delete(); 7 | void display(); 8 | 9 | } 10 | class myqueue1 implements queue1 11 | { 12 | int arr[]=new int[3]; 13 | int front=0,rear=0; 14 | Scanner s1 = new Scanner(System.in); 15 | public void insert() 16 | { 17 | int a; 18 | System.out.println("enter element:"); 19 | a=s1.nextInt(); 20 | arr[rear]=a; 21 | rear++; 22 | if(rear==3) 23 | rear=0; 24 | } 25 | public void delete() 26 | { 27 | if (rear==front) 28 | System.out.println("queue is empty"); 29 | else 30 | { 31 | int a; 32 | a=arr[front]; 33 | front++; 34 | System.out.println("element deleted : "+a ); 35 | if(front==3) 36 | front=0; 37 | } 38 | } 39 | public void display() 40 | { 41 | System.out.println("elements are"); 42 | for(int i=front;i=self.head: 25 | return (self.tail-self.head) 26 | return (self.maxSize - (self.head-self.tail)) -------------------------------------------------------------------------------- /data_structures/dimaeter_of_a_tree/diameter_of_a_tree.md: -------------------------------------------------------------------------------- 1 | //Diameter of a tree 2 | ## ELI5 3 | The diameter of a tree is its width.The maximum possible number of items between any two end-most items in a tree. 4 | 5 | ## Explaination 6 | The diameter of a tree (sometimes called the width) is the number of nodes on the longest path between two leaves in the tree. 7 | 8 | The diameter of a tree T is the largest of the following quantities: 9 | 10 | * the diameter of T’s left subtree 11 | * the diameter of T’s right subtree 12 | * the longest path between leaves that goes through the root of T (this can be computed from the heights of the subtrees of T) 13 | -------------------------------------------------------------------------------- /data_structures/dimaeter_of_a_tree/java/Diameter.java: -------------------------------------------------------------------------------- 1 | import java.lang.Math; 2 | 3 | 4 | class Diameter{ 5 | Node root; 6 | 7 | public Diameter(Node root){ 8 | this.root = root; 9 | } 10 | 11 | public static int c_diameter(Node node){ 12 | 13 | if(node == null)return 0; 14 | 15 | 16 | //heights of left & right subtrees 17 | int c_left_height = c_height(node.left); 18 | int c_right_height = c_height(node.right); 19 | 20 | //diameters of left an right subtrees 21 | int c_left_diameter = c_diameter(node.left); 22 | int c_right_diameter = c_diameter(node.right); 23 | 24 | //return 25 | return Math.max(c_left_height+c_right_height+1,Math.max(c_left_diameter,c_right_diameter)); 26 | 27 | } 28 | 29 | 30 | public static int c_height(Node node){ 31 | if(node == null) return 0; 32 | 33 | 34 | return 1 + Math.max(c_height(node.left),c_height(node.right)); 35 | } 36 | 37 | 38 | 39 | 40 | 41 | public static void main(String[] args){ 42 | Node root = new Node(1); 43 | root.left = new Node(2); 44 | root.right = new Node(3); 45 | root.left.left = new Node(4); 46 | root.left.right = new Node(5); 47 | root.left.left.left = new Node(6); 48 | 49 | Diameter diameter = new Diameter(root); 50 | 51 | System.out.println(c_diameter(root)); 52 | 53 | } 54 | } -------------------------------------------------------------------------------- /data_structures/graph/cpp/graph.cpp: -------------------------------------------------------------------------------- 1 | //Graph C++ 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | //class for graph , easily customisable 7 | class graph 8 | { 9 | int vertices; 10 | int edges; 11 | vector *v; 12 | 13 | public: 14 | //constructors 15 | graph() 16 | { 17 | vertices=0; 18 | edges=0; 19 | v=NULL; 20 | } 21 | graph(int ver,int e) 22 | { 23 | vertices=ver; 24 | edges=e; 25 | v=new vector[ver+2]; 26 | } 27 | 28 | //0 for undirected 29 | //1 for directed 30 | void addedge(int a,int b,int dir) 31 | { 32 | if(a>vertices || a<0 || b>vertices || b<0) 33 | return; 34 | v[a].push_back(b); 35 | if(dir==0) 36 | v[b].push_back(a); 37 | } 38 | void printedges() 39 | { 40 | vector::iterator it; 41 | for(int i=0;i<=vertices;i++) 42 | { 43 | for(it=v[i].begin();it!=v[i].end();it++) 44 | { 45 | cout<= 0 9 | heapq.heappush(self._heap, (priority, item)) 10 | 11 | def pop(self): 12 | item = heapq.heappop(self._heap)[1] 13 | return item 14 | 15 | def __len__(self): 16 | return len(self._heap) 17 | 18 | def __iter__(self): 19 | return self 20 | 21 | def next(self): 22 | try: 23 | return self.pop() 24 | except IndexError: 25 | raise StopIteration -------------------------------------------------------------------------------- /data_structures/heap/ruby/heap.rb: -------------------------------------------------------------------------------- 1 | class Heap 2 | def initialize 3 | @store = Array.new 4 | end 5 | 6 | def push(data) 7 | @store.push(data) 8 | tear_up(size - 1) 9 | end 10 | 11 | def top 12 | @store.first 13 | end 14 | 15 | def pop 16 | data = top 17 | if size > 1 18 | @store[0] = @store.pop 19 | tear_down(0) 20 | else 21 | @store.pop 22 | end 23 | return data 24 | end 25 | 26 | def size 27 | @store.size 28 | end 29 | 30 | private 31 | 32 | def tear_up(pos) 33 | return if pos == 0 34 | parent = (pos - 1) / 2 35 | 36 | if @store[parent] < @store[pos] 37 | @store[parent], @store[pos] = @store[pos], @store[parent] 38 | tear_up(parent) 39 | end 40 | end 41 | 42 | def tear_down(pos) 43 | return if pos >= size 44 | left = pos * 2 + 1 45 | right = pos * 2 + 2 46 | 47 | max_leaf = -1 48 | 49 | if left >= size 50 | max_leaf = -1 51 | elsif right >= size 52 | max_leaf = left 53 | else 54 | if @store[right] > @store[left] 55 | max_leaf = right 56 | else 57 | max_leaf = left 58 | end 59 | end 60 | 61 | if max_leaf != -1 62 | @store[max_leaf], @store[pos] = @store[pos], @store[max_leaf] 63 | tear_down(max_leaf) 64 | end 65 | end 66 | end 67 | 68 | # Usage 69 | H = Heap.new 70 | H.push(5) 71 | H.push(3) 72 | H.push(9) 73 | H.push(10) 74 | H.push(1) 75 | H.push(4) 76 | 77 | # 10 78 | puts H.top() 79 | 80 | # 10 9 5 4 3 1 81 | while H.size() > 0 do 82 | puts H.pop() 83 | end -------------------------------------------------------------------------------- /data_structures/linked_list/go/linked_list.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | type Node struct { 6 | Value interface{} 7 | next *Node 8 | } 9 | 10 | func (n *Node) Next() *Node { 11 | return n.next 12 | } 13 | 14 | type LinkedList struct { 15 | first *Node 16 | last *Node 17 | } 18 | 19 | func (l *LinkedList) Add(v interface{}) { 20 | n := new(Node) 21 | n.Value = v 22 | if l.first == nil { 23 | l.first = n 24 | l.last = n 25 | } else { 26 | l.last.next = n 27 | l.last = n 28 | } 29 | } 30 | 31 | func (l *LinkedList) First() *Node { 32 | return l.first 33 | } 34 | 35 | func (l *LinkedList) ToString() string { 36 | str := "" 37 | if l.first != nil { 38 | n := l.first 39 | str += n.Value.(string) 40 | for n.next != nil { 41 | str += "," + n.next.Value.(string) 42 | n = n.next 43 | } 44 | } 45 | return str 46 | } 47 | 48 | func main() { 49 | list := new(LinkedList) 50 | list.Add("a") 51 | list.Add("b") 52 | list.Add("c") 53 | 54 | fmt.Printf(list.ToString() + "\n") 55 | } 56 | -------------------------------------------------------------------------------- /data_structures/linked_list/java/LinkedListTest.java: -------------------------------------------------------------------------------- 1 | import static org.junit.Assert.*; 2 | 3 | import org.junit.Test; 4 | 5 | /** 6 | * Testing LinkedList 7 | * @author Prohunt 8 | * 9 | */ 10 | public class LinkedListTest { 11 | @Test 12 | public void testLinkedList(){ 13 | LinkedList intList = new LinkedList(); 14 | assertTrue(intList.add(1)); 15 | assertTrue(intList.add(2)); 16 | assertEquals(new Integer(1), intList.head()); 17 | assertEquals(new Integer(2), intList.tail()); 18 | assertTrue(intList.add(3)); 19 | assertEquals(new Integer(3), intList.tail()); 20 | assertEquals(3, intList.size()); 21 | 22 | assertFalse(intList.add(null)); 23 | 24 | assertTrue(intList.remove(new Integer(3))); 25 | assertFalse(intList.contains(new Integer(3))); 26 | assertEquals(2, intList.size()); 27 | 28 | assertTrue(intList.contains(new Integer(2))); 29 | 30 | assertFalse(intList.remove(new Integer(3))); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /data_structures/linked_list/python/linked_list.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, data=None, next_node=None): 3 | self.data = data 4 | self.next = next_node 5 | self.prev = None 6 | 7 | def __repr__(self): 8 | return self.data or '' 9 | 10 | 11 | class LinkedList: 12 | ''' 13 | Implementation of Linked list data structure 14 | ''' 15 | 16 | def __init__(self, data_iterable): 17 | self.head = None 18 | for data in data_iterable: 19 | self.add(data) 20 | 21 | def add(self, data): 22 | node = Node(data) 23 | node.next = self.head 24 | self.head = node 25 | if node.next: 26 | node.next.prev = node 27 | 28 | def search(self, data): 29 | node = self.head 30 | while node: 31 | if node.data == data: 32 | return node 33 | node = node.next 34 | return None 35 | 36 | def remove(self, node): 37 | if node is self.head: 38 | self.head = node.next 39 | else: 40 | node.prev.next = node.next 41 | if node.next: 42 | node.next.prev = node.prev 43 | 44 | def __repr__(self): 45 | node = self.head 46 | data = [] 47 | while node: 48 | data.append(node.data) 49 | node = node.next 50 | return ' '.join(data) 51 | 52 | 53 | if __name__ == '__main__': 54 | l = LinkedList(['d', 'c', 'b']) 55 | assert str(l) == 'b c d' 56 | l.add('a') 57 | assert str(l) == 'a b c d' 58 | l.remove(l.search('a')) 59 | l.remove(l.search('c')) 60 | assert str(l) == 'b d' 61 | 62 | -------------------------------------------------------------------------------- /data_structures/linked_list_queue/cpp/queue_linked_list.cpp: -------------------------------------------------------------------------------- 1 | // Simple queue data structure using singly linked list 2 | #include 3 | 4 | // List node 5 | template 6 | struct QueueNode { 7 | // Constructor. Set node value and initialize next node pointer to NULL 8 | QueueNode(T _value) { 9 | value = _value; 10 | pNext = NULL; 11 | } 12 | 13 | T value; // Value stored in node 14 | QueueNode *pNext; // Next node in linked list 15 | }; 16 | 17 | // Queue structure 18 | template 19 | class CQueue { 20 | public: 21 | // Constructor. Initialize head & tail pointer to NULL. 22 | CQueue() { 23 | m_pHead = m_pTail = NULL; 24 | } 25 | 26 | // Push a new element into the queue 27 | void enqueue(T value) { 28 | QueueNode *pNewTail = new QueueNode(value); 29 | 30 | if (m_pHead == NULL) 31 | m_pHead = m_pTail = pNewTail; 32 | else { 33 | m_pTail->pNext = pNewTail; 34 | m_pTail = pNewTail; 35 | } 36 | } 37 | 38 | // Pop the head element from the queue 39 | T dequeue() { 40 | if (m_pHead == NULL) 41 | return NULL; 42 | 43 | T value = m_pHead->value; 44 | QueueNode *pNewHead = m_pHead->pNext; 45 | delete m_pHead; 46 | m_pHead = pNewHead; 47 | 48 | return value; 49 | } 50 | 51 | // Check if the queue is empty 52 | bool isEmpty() { 53 | return m_pHead == NULL; 54 | } 55 | 56 | private: 57 | QueueNode *m_pHead; // Head node of linked list 58 | QueueNode *m_pTail; // Tail node of linked list 59 | }; 60 | 61 | using namespace std; 62 | 63 | int main() { 64 | CQueue queue; 65 | 66 | queue.enqueue(1); 67 | queue.enqueue(2); 68 | queue.enqueue(3); 69 | queue.enqueue(4); 70 | queue.enqueue(5); 71 | 72 | while (!queue.isEmpty()) 73 | cout << queue.dequeue() << ' '; 74 | 75 | return 0; 76 | } 77 | -------------------------------------------------------------------------------- /data_structures/min_heap/cpp/impl_minHeap.cpp: -------------------------------------------------------------------------------- 1 | // Insert the following numbers into the heap, printing the heap after each insert: 2 | // 2 3 7 22 5 21 1 28 4 16 0 17 12 18 20 25 3 | 4 | // deleteMin() the numbers in the heap, into a new list (array or vector is fine), printing the heap after each deleteMin() (I want to see how your heap structure changes after each deleteMin). 5 | // Print the new sorted list of numbers. 6 | #include "minHeap.cpp" 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | using std::cout; 13 | using std::endl; 14 | using std::string; 15 | 16 | int main(){ 17 | int unsortedNums[] = {2, 3, 7, 22, 5, 21, 1, 28, 4, 16, 0, 17, 12, 18, 20, 25}; 18 | int sortedNums[16]; 19 | MinHeap heap; 20 | 21 | cout << "Printing unsorted List: \n"; 22 | for(int k = 0;k<16;k++){ 23 | cout << unsortedNums[k] << ", "; 24 | } 25 | cout << "\n\n========================================================\nInserting to min heap: \n"; 26 | for(int i = 0;i<16;i++){ 27 | heap.insert(unsortedNums[i]); 28 | heap.printSelf(); 29 | cout << endl; 30 | } 31 | cout << "========================================================\nSorting List: \n"; 32 | for(int j = 0;j<16;j++){ 33 | int min = heap.deleteMin(); 34 | sortedNums[j] = min; 35 | heap.printSelf(); 36 | cout << endl; 37 | } 38 | cout << "========================================================\nPrinting Sorted List: \n"; 39 | for(int k = 0;k<16;k++){ 40 | cout << sortedNums[k] << ", "; 41 | } 42 | cout << endl; 43 | } 44 | -------------------------------------------------------------------------------- /data_structures/min_heap/cpp/minHeap.hpp: -------------------------------------------------------------------------------- 1 | #ifndef MINHEAP_H 2 | #define MINHEAP_H 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | using std::vector; 9 | 10 | class MinHeap{ 11 | public: 12 | MinHeap(); 13 | ~MinHeap(); 14 | void insert(int item); 15 | int deleteMin(); 16 | void printSelf(); 17 | private: 18 | void bubbleUp(int index); 19 | void bubbleDown(int index); 20 | vector _heap; 21 | }; 22 | 23 | #endif //MINHEAP_H 24 | -------------------------------------------------------------------------------- /data_structures/mirror_of_a_tree.java/java/Mirror.java: -------------------------------------------------------------------------------- 1 | class Mirror{ 2 | 3 | Node root = null; 4 | Node mRoot = null; 5 | public void mirror(Node node){ 6 | 7 | if(node == null) return ; 8 | 9 | mirror(node.left); 10 | 11 | mirror(node.right); 12 | 13 | Node temp = node.left; 14 | node.left = node.right; 15 | node.right = temp; 16 | 17 | } 18 | 19 | public void printTree(Node node){ 20 | 21 | if(node == null) return; 22 | 23 | printTree(node.left); 24 | 25 | System.out.print(node.data+" "); 26 | 27 | printTree(node.right); 28 | 29 | } 30 | public static void main(String[] args){ 31 | 32 | Mirror bt = new Mirror(); 33 | 34 | bt.root = new Node(1); 35 | bt.root.left = new Node(2); 36 | bt.root.right = new Node(3); 37 | bt.root.left.left = new Node(4); 38 | bt.root.left.right = new Node(5); 39 | bt.root.right.right = new Node(7); 40 | bt.root.right.left = new Node(6); 41 | 42 | 43 | 44 | System.out.println("Original Tree\n"); 45 | bt.printTree(bt.root); 46 | 47 | bt.mirror(bt.root); 48 | System.out.println(); 49 | 50 | System.out.println("Mirror Tree\n"); 51 | bt.printTree(bt.root); 52 | 53 | } 54 | 55 | } -------------------------------------------------------------------------------- /data_structures/mirrot_of_a_tree.cpp/mirror.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | typedef struct btree { 8 | int data; 9 | struct btree *left; 10 | struct btree *right; 11 | }btree; 12 | 13 | btree *makeTree(btree *root , int d) { 14 | btree *nn = (btree*)malloc(sizeof(btree)); 15 | nn->data = d; 16 | nn->left = NULL; 17 | nn->right = NULL; 18 | if(root==NULL) { 19 | return nn; 20 | } 21 | else { 22 | queue q; 23 | q.push(root); 24 | while(!q.empty()) { 25 | btree *node = q.front(); 26 | q.pop(); 27 | if(node->left) q.push(node->left); 28 | else { 29 | node->left = nn; 30 | return root; 31 | } 32 | 33 | if(node->right) q.push(node->right); 34 | else { 35 | node->right = nn; 36 | return root; 37 | } 38 | } 39 | } 40 | } 41 | 42 | btree *mirror(btree *root) { 43 | if(root==NULL) return NULL; 44 | btree *nn = (btree*)malloc(sizeof(btree)); 45 | 46 | nn->data = root->data; 47 | nn->right = mirror(root->left); 48 | nn->left = mirror(root->right); 49 | 50 | return nn; 51 | } 52 | 53 | void printTreeLevelOrder(btree *root) { 54 | queue q; 55 | q.push(root); 56 | while(!q.empty()) { 57 | btree *node = q.front(); 58 | q.pop(); 59 | cout<data<<" "; 60 | if(node->left) q.push(node->left); 61 | 62 | if(node->right) q.push(node->right); 63 | } 64 | } 65 | 66 | int main() 67 | { 68 | btree *a = NULL; 69 | a = makeTree(a,1); 70 | a = makeTree(a,2); 71 | a = makeTree(a,3); 72 | a = makeTree(a,4); 73 | a = makeTree(a,5); 74 | a = makeTree(a,6); 75 | a = makeTree(a,7); 76 | 77 | btree *b = mirror(a); 78 | printTreeLevelOrder(b); 79 | cout< 2 | #include 3 | struct node{ 4 | int data,priority; 5 | struct node* next; 6 | }; 7 | struct node *header=NULL; 8 | 9 | void enque(int data,int priority) 10 | { 11 | struct node* ptr2; 12 | ptr2=(struct node*)malloc(sizeof(struct node)); 13 | ptr2->data=data; 14 | ptr2->priority=priority; 15 | ptr2->next=header; 16 | header=ptr2; 17 | } 18 | 19 | void deque() 20 | { 21 | struct node *ptr,*min,*prev; 22 | prev=NULL; 23 | ptr=header; 24 | min=ptr; 25 | ptr=ptr->next; 26 | if(ptr==NULL) 27 | { 28 | printf("empty\n"); 29 | return; 30 | } 31 | while(ptr!=NULL) 32 | { 33 | if(min->priority>ptr->priority) 34 | { 35 | prev=min; 36 | min=ptr; 37 | } 38 | ptr=ptr->next; 39 | } 40 | printf("dequeued element: %d\tpriority: %d\n",min->data,min->priority); 41 | prev->next=min->next; 42 | free(min); 43 | } 44 | 45 | void display() 46 | { 47 | struct node *ptr; 48 | ptr=header; 49 | if(ptr==NULL) 50 | { 51 | printf("empty\n"); 52 | return; 53 | } 54 | while(ptr!=NULL) 55 | { 56 | printf("%d,%d\t",ptr->data,ptr->priority); 57 | ptr=ptr->next; 58 | } 59 | printf("\n"); 60 | } 61 | int main() 62 | { 63 | int c,x,p; 64 | while(1) 65 | { 66 | printf("1.enque\n2.deque\n3.display\n4.exit\n"); 67 | scanf("%d",&c); 68 | switch(c) 69 | { 70 | case 1: printf("enter element and priority: "); 71 | scanf("%d%d",&x,&p); 72 | enque(x,p); 73 | break; 74 | case 2: deque(); 75 | break; 76 | case 3: display(); 77 | break; 78 | case 4: goto end; 79 | } 80 | } 81 | end:; 82 | } 83 | 84 | -------------------------------------------------------------------------------- /data_structures/queue/c/queue.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | # define max 5 4 | int queue[max]; 5 | int f=0,r=-1; 6 | int count=0; 7 | int main() 8 | { 9 | int n; 10 | do 11 | { 12 | printf("\nEnter choice:\n1.Push\n2.POP\n3.Display\n4.Exit\n"); 13 | scanf("%d",&n); 14 | switch(n) 15 | { 16 | case 1: 17 | push(); 18 | break; 19 | case 2: 20 | pop(); 21 | break; 22 | case 3: 23 | display(); 24 | break; 25 | case 4: 26 | exit(0); 27 | break; 28 | } 29 | }while(n!=4); 30 | return 0; 31 | } 32 | 33 | void push() 34 | { 35 | int data; 36 | printf("\n"); 37 | if((f==0 && r==max-1) || (f>0 && r==f-1)) 38 | printf("queue overflow\n"); 39 | else if((r==-1 && f==0) || (f==0 && r0 && r!=f)) 40 | { 41 | r=(r+1)%max; 42 | printf("Enter element\n"); 43 | scanf("%d",&queue[r]); 44 | count++; 45 | } 46 | printf("\n\n"); 47 | } 48 | 49 | void pop() 50 | { 51 | if(r==-1 || (f>0 && f==(r+1)%max)) 52 | printf("\nUnderflow\n"); 53 | else 54 | { 55 | printf("\nElement %d is popped out\n",queue[f]); 56 | f=(f+1)%max; 57 | count--; 58 | } printf("\n\n"); 59 | } 60 | 61 | void display() 62 | { 63 | printf("\n"); 64 | int i; 65 | printf("\nElements present are\n"); 66 | for(i=0;i 4 | using namespace std; 5 | 6 | template 7 | class Queue 8 | { 9 | struct Node 10 | { 11 | Node(T v, Node* pre){value = v; prev = pre;} 12 | T value; 13 | Node* prev; 14 | }; 15 | public: 16 | Queue(); 17 | Queue(T value, int intial_size); 18 | T* Front(); 19 | void Pop(); 20 | void Push(T value); 21 | int Size(); 22 | void Print(); 23 | virtual ~Queue(); 24 | 25 | protected: 26 | 27 | private: 28 | Node* tail; 29 | Node* head; 30 | int sz; 31 | }; 32 | 33 | #endif // QUEUE_H 34 | -------------------------------------------------------------------------------- /data_structures/queue/csharp/Queue.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace DataStructures 8 | { 9 | class Queue 10 | { 11 | 12 | private List queue = new List(); 13 | 14 | public Object dequeue() 15 | { 16 | if (queue.Count > 0) 17 | { 18 | Object temp = queue[0]; 19 | queue.RemoveAt(0); 20 | return temp; 21 | } 22 | else 23 | { 24 | return null; 25 | } 26 | } 27 | 28 | 29 | public Object peek() 30 | { 31 | if (queue.Count > 0) 32 | { 33 | return queue[0]; 34 | } 35 | else 36 | { 37 | return null; 38 | } 39 | } 40 | 41 | 42 | public void enqueue(Object newItem) 43 | { 44 | queue.Add(newItem); 45 | } 46 | 47 | 48 | public bool isEmpty() 49 | { 50 | return (queue.Count == 0); 51 | } 52 | 53 | 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /data_structures/queue/go/queue.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | type queue struct { 6 | data []interface{} 7 | } 8 | 9 | func NewQueue() queue { 10 | return queue{nil} 11 | } 12 | 13 | func (q *queue) Enqueue(value interface{}) { 14 | q.data = append(q.data, value) 15 | } 16 | 17 | func (q *queue) Dequeue() (interface{}) { 18 | value := q.data[0] 19 | q.data = q.data[1: len(q.data)] 20 | return value 21 | } 22 | 23 | func main() { 24 | q := NewQueue() 25 | q.Enqueue(10) 26 | q.Enqueue("Hello") 27 | q.Enqueue(20) 28 | q.Enqueue(10) 29 | q.Enqueue("Hello") 30 | q.Enqueue(20) 31 | q.Enqueue(10) 32 | q.Enqueue("Hello") 33 | q.Enqueue(20) 34 | q.Enqueue(10) 35 | q.Enqueue("Hello") 36 | q.Enqueue(20) 37 | q.Enqueue(10) 38 | q.Enqueue("Hello") 39 | q.Enqueue(20) 40 | q.Enqueue(10) 41 | q.Enqueue("Hello") 42 | q.Enqueue(20) 43 | fmt.Println(q) 44 | fmt.Println(q.Dequeue()) 45 | fmt.Println(q.Dequeue()) 46 | fmt.Println(q) 47 | } 48 | -------------------------------------------------------------------------------- /data_structures/queue/javascript/queue_ES5.js: -------------------------------------------------------------------------------- 1 | function Queue() { 2 | this._oldestIndex = 1; 3 | this._newestIndex = 1; 4 | this._storage = {}; 5 | } 6 | 7 | Queue.prototype.size = function() { 8 | return this._newestIndex - this._oldestIndex; 9 | }; 10 | 11 | Queue.prototype.enqueue = function(data) { 12 | this._storage[this._newestIndex] = data; 13 | this._newestIndex++; 14 | }; 15 | 16 | Queue.prototype.dequeue = function() { 17 | var oldestIndex = this._oldestIndex, 18 | newestIndex = this._newestIndex, 19 | deletedData; 20 | 21 | if (oldestIndex !== newestIndex) { 22 | deletedData = this._storage[oldestIndex]; 23 | delete this._storage[oldestIndex]; 24 | this._oldestIndex++; 25 | 26 | return deletedData; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /data_structures/queue/javascript/queue_ES6.js: -------------------------------------------------------------------------------- 1 | class Queue { 2 | constructor() { 3 | this._oldestIndex = 1; 4 | this._newestIndex = 1; 5 | this._storage = {}; 6 | } 7 | 8 | size() { 9 | return this._newestIndex - this._oldestIndex; 10 | } 11 | 12 | enqueue(data) { 13 | this._storage[this._newestIndex] = data; 14 | this._newestIndex++; 15 | } 16 | 17 | dequeue() { 18 | let oldestIndex = this._oldestIndex; 19 | let newestIndex = this._newestIndex; 20 | let deletedData; 21 | 22 | if (oldestIndex !== newestIndex) { 23 | deletedData = this._storage.oldestIndex; 24 | delete this._storage.oldestIndex; 25 | this._oldestIndex++; 26 | 27 | return deletedData; 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /data_structures/queue/php/queue.php: -------------------------------------------------------------------------------- 1 | enqueue($item); 22 | } 23 | } 24 | } 25 | 26 | /** 27 | * @return int 28 | */ 29 | public function size(){ 30 | return count($this->_data); 31 | } 32 | 33 | /** 34 | * @param $item 35 | */ 36 | public function enqueue($item){ 37 | $this->_data[] = $item; 38 | } 39 | 40 | /** 41 | * @return mixed 42 | * @throws Exception 43 | */ 44 | public function dequeue(){ 45 | if($this->size() > 0){ 46 | return array_shift($this->_data); 47 | } else { 48 | throw new Exception('Can\'t dequeue an empty queue!'); 49 | } 50 | } 51 | } 52 | 53 | $queue = new Queue(['1','2','3','4']); 54 | $queue->dequeue(); //1 55 | $queue->enqueue('5'); //2,3,4,5 56 | ?> -------------------------------------------------------------------------------- /data_structures/queue/python/queue_two_stacks.py: -------------------------------------------------------------------------------- 1 | def get_command(): 2 | parts = input().strip().split(' ') 3 | command = int(parts[0]) 4 | 5 | if len(parts) == 1: 6 | return (command, None) 7 | try: 8 | arg = int(parts[1]) 9 | except ValueError: 10 | arg = parts[1] 11 | 12 | return command, arg 13 | 14 | 15 | class Stack: 16 | def __init__(self): 17 | self._l = [] 18 | 19 | def __len__(self): 20 | return len(self._l) 21 | 22 | def push(self, data): 23 | self._l.append(data) 24 | 25 | def pop(self): 26 | return self._l.pop() 27 | 28 | def top(self): 29 | if self._l: 30 | return self._l[-1] 31 | return None 32 | 33 | 34 | class Queue: 35 | def __init__(self): 36 | self._head = Stack() 37 | self._tail = Stack() 38 | 39 | def enqueue(self, data): 40 | self._tail.push(data) 41 | 42 | def dequeue(self): 43 | if self._head: 44 | return self._head.pop() 45 | 46 | return self._tail_to_head().pop() 47 | 48 | def peek(self): 49 | if self._head: 50 | return self._head.top() 51 | 52 | return self._tail_to_head().top() 53 | 54 | def _tail_to_head(self): 55 | while self._tail: 56 | self._head.push(self._tail.pop()) 57 | 58 | return self._head 59 | 60 | 61 | def main(): 62 | 63 | queue = Queue() 64 | 65 | command_no = int(input().strip()) 66 | for _ in range(command_no): 67 | command, arg = get_command() 68 | if command == ENQUEUE: 69 | queue.enqueue(arg) 70 | elif command == DEQUEUE: 71 | queue.dequeue() 72 | elif command == PRINT: 73 | print(queue.peek()) 74 | 75 | 76 | if __name__ == '__main__': 77 | main() 78 | -------------------------------------------------------------------------------- /data_structures/queue/ruby/queue.rb: -------------------------------------------------------------------------------- 1 | class Queue 2 | def initialize 3 | @store = Array.new 4 | end 5 | 6 | def enqueue(data) 7 | @store.push(data) 8 | end 9 | 10 | def dequeue() 11 | raise Exception if size == 0 12 | @store.shift 13 | end 14 | 15 | def front() 16 | raise Exception if size == 0 17 | @store.first 18 | end 19 | 20 | def back() 21 | @store.last 22 | end 23 | 24 | def size() 25 | @store.size 26 | end 27 | end 28 | 29 | # Usage 30 | Q = Queue.new 31 | Q.enqueue(1) 32 | Q.enqueue(2) 33 | Q.enqueue(3) 34 | 35 | puts Q.front() 36 | puts Q.back() 37 | 38 | puts Q.dequeue() 39 | puts Q.dequeue() -------------------------------------------------------------------------------- /data_structures/simple_queue/java/queue.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | interface queue 3 | { 4 | void insert(); 5 | void delete(); 6 | void display(); 7 | 8 | } 9 | class myqueue implements queue 10 | { 11 | int arr[]=new int[10]; 12 | int front=0,rear=0; 13 | Scanner s1 = new Scanner(System.in); 14 | public void insert() 15 | { 16 | if (rear>10) 17 | System.out.println("queue overflow"); 18 | else 19 | { 20 | int a; 21 | System.out.println("enter element:"); 22 | a=s1.nextInt(); 23 | arr[rear]=a; 24 | rear++; 25 | } 26 | } 27 | public void delete() 28 | { 29 | if (rear==front) 30 | System.out.println("queue is empty"); 31 | else 32 | { 33 | int a; 34 | a=arr[front]; 35 | front++; 36 | System.out.println("element deleted : "+a ); 37 | } 38 | } 39 | public void display() 40 | { 41 | System.out.println("elements are"); 42 | for(int i=front;i stack = new Stack(); 7 | stack.Push(1); 8 | stack.Push(3); 9 | Console.WriteLine(stack.Top()); 10 | stack.Pop(); 11 | Console.WriteLine(stack.Top()); 12 | 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /data_structures/stack/c#/stack.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace Stack{ 5 | public class Stack { 6 | private List _array; // Storage for stack elements 7 | private int _size; 8 | private int _top; // Number of items in the stack. 9 | static List _emptyArray = new List(); 10 | public Stack(){ 11 | 12 | _array = _emptyArray; 13 | _size = 0; 14 | _top = -1; 15 | 16 | } 17 | public void Push(t data){ 18 | _array.Add(data); 19 | _size++; 20 | _top++; 21 | } 22 | public void Pop(){ 23 | _array.RemoveAt(_top--); 24 | } 25 | public t Top(){ 26 | return _array[_top]; 27 | } 28 | } 29 | } 30 | 31 | 32 | -------------------------------------------------------------------------------- /data_structures/stack/c/stack1.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | 5 | struct node{ 6 | int data; 7 | struct node* next; 8 | }; 9 | 10 | struct node* head; 11 | void insertatthebegin(int x) 12 | { 13 | struct node* temp=(struct node*)malloc(sizeof(struct node)); 14 | temp->data=x; 15 | temp->next=head; 16 | head=temp; 17 | 18 | } 19 | 20 | 21 | void print() 22 | { 23 | struct node* temp=head; 24 | 25 | if(temp== NULL) 26 | printf("empty list\n"); 27 | else{ 28 | while(temp!=NULL) 29 | { 30 | printf("%d ",temp->data); 31 | temp=temp->next; 32 | } 33 | } 34 | printf("\n"); 35 | 36 | } 37 | 38 | 39 | void reverse() 40 | { 41 | struct node* prev, *current , *next; 42 | prev=NULL; 43 | 44 | current=head; 45 | 46 | while(current !=NULL) 47 | { 48 | next=current->next; 49 | current->next=prev; 50 | prev=current; 51 | current=next; 52 | } 53 | head=prev; 54 | 55 | } 56 | 57 | int main() 58 | { 59 | int i,j,n,k,l,x; 60 | head=NULL; 61 | printf("enter the number of elements\n"); 62 | scanf("%d",&n); 63 | 64 | printf("enter the elements and the position\n"); 65 | for(i=0;i_element_below; 27 | delete _top; //Do not forget to free memory 28 | _top = new_top; 29 | } 30 | } 31 | // Pushes new value to the top of the stack 32 | void CStack::Push(char val) 33 | { 34 | CElement *new_top = new CElement(); //Allocate memory for the new top element 35 | new_top->_element_below = _top; 36 | new_top->_val = val; 37 | _top = new_top; 38 | } 39 | // Returns value at top of the stack 40 | char CStack::Top() 41 | { 42 | // If array is empty, return null character 43 | if (IsEmpty()) 44 | { 45 | return '\0'; 46 | // Else return top Stack value 47 | } 48 | else 49 | { 50 | return _top->_val; 51 | } 52 | } 53 | // Checks whether the stack is empty, returns bool 54 | bool CStack::IsEmpty() 55 | { 56 | return _top == nullptr; 57 | } 58 | -------------------------------------------------------------------------------- /data_structures/stack/cpp/cstack.h: -------------------------------------------------------------------------------- 1 | 2 | #ifndef CSTACK_H 3 | #define CSTACK_H 4 | 5 | #include "celement.h" 6 | 7 | // Header File 8 | class CStack 9 | { 10 | public: 11 | CStack(const CStack&) = delete; //Forbid usage of Copy Constructor because we use raw pointers 12 | CStack& operator=(const CStack&) = delete; //Forbid usage of copy assignment for the same reason 13 | CStack(); 14 | ~CStack(); 15 | char Top(); 16 | void Pop(); 17 | void Push(char); 18 | bool IsEmpty(); 19 | 20 | private: 21 | CElement *_top; 22 | }; 23 | #endif 24 | -------------------------------------------------------------------------------- /data_structures/stack/cpp/cstack.test.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "cstack.h" 3 | 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | char input; 9 | CStack stack; 10 | 11 | // Prompt user for expression 12 | cout << "Please Enter an expression (must end with the EOF character) : "; //EOF is CTRL^D (Linux) or CTRL^Z (Windows) 13 | 14 | // Fill stack with char values 15 | while(cin >> input) { 16 | stack.Push(input); 17 | } 18 | 19 | // Show LIFO 20 | cout << endl; 21 | while(!stack.IsEmpty()){ 22 | cout << stack.Top(); 23 | stack.Pop(); 24 | } 25 | cout << endl; 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /data_structures/stack/cpp/stack_balanced_paranthesis.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | int t; 9 | cout<<"Enter no of test cases"; 10 | cin>>t; 11 | string s=" "; 12 | 13 | while(t--) 14 | { 15 | stack st; 16 | cout<<"\nEnter the string\n"; 17 | cin>>s; 18 | int flag=0; 19 | for(int i=0;i 2 | #include 3 | 4 | #include "Stack.hpp" 5 | 6 | /* 7 | * Main is only used to test different 8 | * methods on my stack 9 | * 10 | */ 11 | 12 | int main(void) { 13 | Stack s; 14 | 15 | std::cout << "Initializing stack" << std::endl; 16 | 17 | for (int i = 0; i < 10; ++i) 18 | s.push(i); 19 | 20 | std::cout << "Done!" << std::endl; 21 | 22 | while ( !s.empty() ) 23 | { 24 | std::cout << s.top() << std::endl; 25 | s.pop(); 26 | } 27 | 28 | std::cout << "Popping off another (inexistant) element" << std::endl; 29 | 30 | try 31 | { 32 | s.pop(); 33 | } 34 | catch (std::exception& e) 35 | { 36 | std::cerr << "[ERR] " << e.what() << std::endl; 37 | } 38 | 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /data_structures/stack/cpp/templated_stack.hpp: -------------------------------------------------------------------------------- 1 | #ifndef STACK_H 2 | #define STACK_H 3 | 4 | #include 5 | 6 | /* 7 | * Templated class declaration and definition 8 | * in a single file for portability 9 | * 10 | */ 11 | template 12 | class Stack { 13 | private: 14 | class Node { 15 | friend Stack; 16 | private: 17 | Node * next; 18 | Object data; 19 | public: 20 | Node(const Object & d, Node * n): 21 | data(d), next(n) { } 22 | }; 23 | 24 | int length {0}; 25 | Node * head {nullptr}; 26 | 27 | public: 28 | // Default ctor but clear on destruction 29 | Stack() { }; 30 | ~Stack() { clear(); }; 31 | 32 | // Returns the number of elements in the stack 33 | int size() { 34 | return length; 35 | } 36 | 37 | // Adds an element on top of the stack 38 | void push(const Object & value) { 39 | head = new Node(value, head); 40 | ++length; 41 | } 42 | 43 | // Returns top element form the stack 44 | Object top() { 45 | if ( head != nullptr ) 46 | return head->data; 47 | throw std::logic_error("Cannot return top from an empty stack"); 48 | } 49 | 50 | // Removes top element from the stack 51 | void pop() { 52 | if ( head != nullptr ) 53 | { 54 | Node * tmp {head}; 55 | head = head->next; 56 | --length; 57 | delete tmp; 58 | } else 59 | throw std::logic_error("Cannot remove top from an empty stack"); 60 | } 61 | 62 | // Tests wether or not the stack is empty 63 | bool empty() { 64 | return length == 0; 65 | } 66 | 67 | // Removes all element from the stack 68 | void clear() { 69 | while ( !empty() ) 70 | pop(); 71 | } 72 | }; 73 | #endif 74 | -------------------------------------------------------------------------------- /data_structures/stack/crystal/stack.cr: -------------------------------------------------------------------------------- 1 | class Stack(T) 2 | @size : Int32 3 | 4 | def initialize(@stack : Array(T)) 5 | @size = @stack.size 6 | end 7 | 8 | # Returns size (Implicit return) 9 | def push(item : T) 10 | @stack << item 11 | @size += 1 12 | end 13 | 14 | # Returns size (Implicit return) 15 | def pop() 16 | @stack.pop 17 | @size -= 1 18 | end 19 | 20 | def peek() 21 | @stack.last 22 | end 23 | 24 | def size() 25 | @size 26 | end 27 | end 28 | 29 | # Union together Types you might need since crystal is type-checked at compile time 30 | # You'll get an error if you try and push a type that isn't in the union 31 | stack = Stack.new([] of Int32|String) 32 | 33 | puts stack.size() # ==> 0 34 | stack.push(30) # ==> [30] 35 | stack.push("Hello") # ==> [30, "hello"] 36 | stack.pop() # ==> 1 37 | puts stack.peek() # ==> 30 38 | 39 | -------------------------------------------------------------------------------- /data_structures/stack/csharp/Stack.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace DataStructures 8 | { 9 | class Stack 10 | { 11 | private List items = new List(); 12 | 13 | public Object pop() 14 | { 15 | if (items.Count > 0) 16 | { 17 | int lastPos = items.Count - 1; 18 | Object temp = items[lastPos]; 19 | items.RemoveAt(lastPos); 20 | return temp; 21 | } 22 | else 23 | { 24 | throw new Exception("Underflow: Stack is empty"); 25 | } 26 | } 27 | 28 | public void push(Object newItem) 29 | { 30 | items.Add(newItem); 31 | } 32 | 33 | 34 | public bool isEmpty() 35 | { 36 | return (items.Count == 0); 37 | } 38 | 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /data_structures/stack/go/stack.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | type stack struct { 4 | data []interface{} 5 | } 6 | 7 | func (s *stack) Push(value interface{}) { 8 | s.data = append(s.data, value) 9 | } 10 | 11 | func (s *stack) Pop() interface{} { 12 | //get last item 13 | value := s.data[len(s.data)-1] 14 | //shrink array 15 | s.data = s.data[0 : len(s.data)-1] 16 | 17 | return value 18 | } 19 | -------------------------------------------------------------------------------- /data_structures/stack/java/Node.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Node{ 4 | private T data; 5 | private Node nextNode; 6 | private Node previewNode; 7 | private int index; 8 | 9 | public Node(T data){ 10 | this.data = data; 11 | this.nextNode = null; 12 | this.previewNode = null; 13 | this.index = 0; 14 | } 15 | 16 | public Node(){ 17 | this.data = null; 18 | this.nextNode = null; 19 | this.previewNode = null; 20 | this.index = 0; 21 | } 22 | 23 | public T getData(){ 24 | return this.data; 25 | } 26 | 27 | public void setData(T data){ 28 | this.data = data; 29 | } 30 | 31 | public int getIndex(){ 32 | return this.index; 33 | } 34 | 35 | public void setNext(Node node){ 36 | this.nextNode = node; 37 | } 38 | 39 | public Node getNext(){ 40 | return this.nextNode; 41 | } 42 | 43 | public void setPreview(Node node){ 44 | this.previewNode = node; 45 | } 46 | 47 | public Node getPreview(){ 48 | return this.previewNode; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /data_structures/stack/java/integer_stack.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | public class Stack { 5 | private List _data = new ArrayList(); 6 | private int _top = -1; 7 | public Stack(){ 8 | 9 | } 10 | public void Push(int val){ 11 | _top++; 12 | _data.add(val); 13 | } 14 | 15 | public void Pop(){ 16 | if(!isEmpty()) 17 | _data.remove(_top--); 18 | else 19 | System.out.println("Queue Is Empty"); 20 | } 21 | 22 | public int Top(){ 23 | return _data.get(_top); 24 | } 25 | private boolean isEmpty(){ 26 | return _top == -1; 27 | } 28 | } 29 | 30 | -------------------------------------------------------------------------------- /data_structures/stack/javascript/usingstack.js: -------------------------------------------------------------------------------- 1 | import Stack from './stack'; 2 | import readline from 'readline'; 3 | (async function RunMe(){ 4 | let stack = Stack(); 5 | let input; 6 | const cin = readline.createInterface({ 7 | input: process.stdin, 8 | output: process.stdout 9 | }); 10 | 11 | cin.question('Test the stack class, type something it will output it backwards. Aka LIFO: ', (answer) => { 12 | input = answer; 13 | cin.close(); 14 | for(let char of input){ 15 | stack.Push(char); 16 | } 17 | while(stack.Top()!==null){ 18 | console.log(stack.Top()); 19 | stack.Pop(); 20 | } 21 | }); 22 | 23 | 24 | })(); 25 | 26 | -------------------------------------------------------------------------------- /data_structures/stack/lisp/Stack.bak: -------------------------------------------------------------------------------- 1 | (define (make-stack) 2 | 3 | (define arr '()) 4 | (define length 0) 5 | (define temp '()) 6 | 7 | (define (size) 8 | length) 9 | 10 | (define (pop) 11 | (set! temp (car arr)) 12 | (set! arr (cons arr)) 13 | temp) 14 | 15 | (define (dispatch method) 16 | (cond ((eq? method 'size) size) 17 | ((eq? method 'pop) pop) 18 | (else (lambda() (display "Unknown Stack Request")(display method)(newline))))) 19 | 20 | dispatch) -------------------------------------------------------------------------------- /data_structures/stack/lisp/Stack.rkt: -------------------------------------------------------------------------------- 1 | (define (make-stack) 2 | 3 | ;backing structure 4 | (define arr '()) 5 | (define length 0) 6 | (define temp '()) 7 | 8 | ;size method 9 | (define (size) 10 | length) 11 | 12 | ;print method 13 | (define (print) 14 | (display arr)) 15 | 16 | ;receiving mpair violation instead of exiting procedure call 17 | ;pop method: removes the head and returns it 18 | (define (pop) 19 | (if (eqv? length 0) (display "Can't Pop")) 20 | (set! length (- length 1)) 21 | (set! temp (cdr arr)) 22 | (set! arr (cdr arr)) 23 | temp) 24 | 25 | ;push method: puts x at the head 26 | (define (push x) 27 | (set! length (+ length 1)) 28 | (set! arr (cons x arr))) 29 | 30 | ;method to get method from user 31 | (define (dispatch method) 32 | (cond ((eq? method 'size) size) 33 | ((eq? method 'pop) pop) 34 | ((eq? method 'print) print) 35 | ((eq? method 'push) push) 36 | (else (lambda() (display "Unknown Stack Request")(display method)(newline))))) 37 | 38 | dispatch) 39 | 40 | ;how to use 41 | (define (testing) 42 | (define stack (make-stack)) 43 | ((stack 'push) 0) 44 | ((stack 'push) 1) 45 | ((stack 'push) 2) 46 | ((stack 'print))(newline) 47 | ((stack 'pop)) 48 | ((stack 'print))(newline) 49 | ((stack 'pop)) 50 | ((stack 'print))(newline) 51 | ((stack 'pop)) 52 | ;((stack 'pop)) 53 | ) 54 | 55 | (testing) 56 | 57 | -------------------------------------------------------------------------------- /data_structures/stack/php/stack.php: -------------------------------------------------------------------------------- 1 | _top == -1){ 7 | throw new Exception("Stack is empty"); 8 | }else{ 9 | $this->_top--; 10 | } 11 | } 12 | public function Push($data) { 13 | 14 | $this->_top++; 15 | array_push($this->_data,$data); 16 | } 17 | public function Top(){ 18 | return $this->_data[$this->_top]; 19 | } 20 | 21 | } 22 | 23 | $stack = new Stack(); 24 | $stack->Push("First Input"); 25 | $stack->Push("Second Input"); 26 | 27 | echo $stack->Top(); 28 | $stack->Pop(); 29 | echo $stack->Top(); 30 | ?> 31 | -------------------------------------------------------------------------------- /data_structures/stack/python/stack.py: -------------------------------------------------------------------------------- 1 | class Stack: 2 | def __init__(self): 3 | self.data = [] 4 | 5 | def push(self, item): 6 | self.data.append(item) 7 | 8 | def pop(self): 9 | return self.data.pop() 10 | 11 | def peek(self): 12 | return self.data[-1] 13 | -------------------------------------------------------------------------------- /data_structures/stack/ruby/stack.rb: -------------------------------------------------------------------------------- 1 | class Stack 2 | def initialize 3 | @store = Array.new 4 | end 5 | 6 | def push(data) 7 | @store.push(data) 8 | end 9 | 10 | def pop() 11 | raise Exception if size == 0 12 | @store.pop 13 | end 14 | 15 | def top() 16 | raise Exception if size == 0 17 | @store.last 18 | end 19 | 20 | def size() 21 | @store.size 22 | end 23 | end 24 | 25 | # Usage 26 | S = Stack.new 27 | S.push(1) 28 | S.push(2) 29 | S.push(3) 30 | 31 | puts S.top() 32 | puts S.size() 33 | 34 | puts S.pop() 35 | puts S.pop() -------------------------------------------------------------------------------- /data_structures/treemap/java/treemap.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class treemap { 3 | 4 | public static void main(String args[]) { 5 | // Create a hash map 6 | TreeMap tm = new TreeMap(); 7 | 8 | // Put elements to the map 9 | tm.put(1, "one"); 10 | tm.put(2, "two"); 11 | tm.put(3,"three"); 12 | tm.put(1,"ONE"); 13 | tm.put(4,"four"); 14 | //storing values in key-value pairs with sorted order of keys, by eliminating duplicate keys 15 | System.out.println(tm);//1-ONE,2-two,3-three,4-four 16 | } 17 | } -------------------------------------------------------------------------------- /data_structures/treeset/java/treeset.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class treeset { 3 | 4 | public static void main(String args[]) { 5 | // Create a tree set 6 | TreeSet ts = new TreeSet(); 7 | 8 | // Add elements to the tree set 9 | ts.add(3); 10 | ts.add(2); 11 | ts.add(3); 12 | ts.add(2); 13 | ts.add(1); 14 | ts.add(4); 15 | //Treeset is very helpful datastructure for avoid duplicatses and maintain the values in sorted order 16 | System.out.println(ts);// output will be {1,2,3,4} 17 | } 18 | } -------------------------------------------------------------------------------- /data_structures/trie/Trie.md: -------------------------------------------------------------------------------- 1 | ## ELI5 2 | Trie is an information re'trie'val data container.It's a tree useful in searching strings. 3 | USES:Autocomplete in text messages etc. 4 | ### Pros 5 | * Searching is easier and faster. 6 | ### Cons 7 | * Storage takes more space. 8 | 9 | ## Technical Explaination 10 | A Trie, also called a digital tree or prefix tree, is a search tree that is used to store a dynamic set or associative array.The keys of a Trie are mostly strings.The postition of node in tree defines its key. All the descendants of a node have a common prefix of the string associated with that node, and the root is associated with the empty string. 11 | Each brach of tree represents a character. 12 | * isEndOfWord : It is the last node of a word. 13 | 14 | ### Pros 15 | * Search in trie is O(M) where M is length of the key. Faster than BST. 16 | ### Cons 17 | * Tries can be slower in some cases than hash tables for looking up data 18 | * Require more space. 19 | -------------------------------------------------------------------------------- /data_structures/union_find/java/UnionFind.java: -------------------------------------------------------------------------------- 1 | 2 | class UnionFind{ 3 | private int[] parent, size; 4 | private int components; 5 | 6 | // Creates the Union-Find data structure 7 | // n = number of nodes 8 | public UnionFind(int n){ 9 | components = n; 10 | parent = new int[n]; 11 | size = new int[n]; 12 | for(int i=0; i (http://brettreinhard.com)", 14 | "license": "GPL-3.0", 15 | "bugs": { 16 | "url": "https://github.com/bareinhard/Hacktoberfest-Data-Structure-and-Algorithms/issues" 17 | }, 18 | "homepage": "https://github.com/bareinhard/Hacktoberfest-Data-Structure-and-Algorithms#readme", 19 | "devDependencies": { 20 | "babel-cli": "^6.26.0", 21 | "babel-preset-env": "^1.6.0" 22 | } 23 | } 24 | --------------------------------------------------------------------------------