├── .github ├── ISSUE_TEMPLATE │ └── create-an-issue.md └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── C# ├── Algorithms │ ├── Backtracking │ │ └── readme.md │ ├── Branch-and-Bound │ │ └── readme.md │ ├── Divide-and-Conquer │ │ └── readme.md │ ├── Dynamic-Programming │ │ └── readme.md │ ├── Geometric-Algorithms │ │ └── readme.md │ ├── Graph-Algorithms │ │ └── readme.md │ ├── Greedy-Algorithms │ │ └── readme.md │ ├── Mathematical │ │ └── readme.md │ ├── Pattern-Searching │ │ └── readme.md │ ├── Randomized-Algorithms │ │ └── readme.md │ ├── Searching-Algorithms │ │ ├── BinarySearchTree │ │ │ └── BinarySearchTree.cs │ │ ├── LinearSearch │ │ │ └── LinearSearch.cs │ │ └── readme.md │ └── Sorting-Algorithms │ │ ├── BubbleSort │ │ └── BubbleSort.cs │ │ └── readme.md └── Data-Structures │ ├── LinkedList │ └── DoublyLinkedList.cs │ ├── Queue │ └── Queue.cs │ └── Stack │ └── Stack.cs ├── C++ ├── Algorithms │ ├── Backtracking │ │ ├── CROOSWARD.cpp │ │ ├── Permutation_of_string.cpp │ │ ├── RAT IN MAZE problem.cpp │ │ ├── RAT_IN_MAZE_problem.cpp │ │ ├── Subsets.cpp │ │ ├── nqueens.cpp │ │ ├── readme.md │ │ ├── sudokuSolver.cpp │ │ └── word_break_problem.cpp │ ├── Branch-and-Bound │ │ └── readme.md │ ├── Divide-and-Conquer │ │ ├── TowerOfHanoi.cpp │ │ ├── painter’s partition problem.cpp │ │ ├── readme.md │ │ └── tower_of_hanoi.cpp │ ├── Dynamic-Programming │ │ ├── 0-1 Knapsack Problem │ │ │ └── 0-1 Knapsack Problem.cpp │ │ ├── Activity_Selection.cpp │ │ ├── Building_bridges.cpp │ │ ├── Coin Change Problem.cpp │ │ ├── Josephus problem.cpp │ │ ├── Kadane-Algorithm.cpp │ │ ├── Longest Palindromic Sequence.cpp │ │ ├── Longest Common Subsequence.cpp │ │ ├── LongestPalindromicSubstring.cpp │ │ ├── Matrix-Chain-Multiplication │ │ │ └── matrix_chain_multiplication.cpp │ │ ├── Max Profit with K transactions.cpp │ │ ├── Minimum Number of Jumps.cpp │ │ ├── Minimum no of coins(Greedy Approach).cpp │ │ ├── SubsetSum │ │ │ └── Subset_Sum_dp.cpp │ │ ├── Unique_Paths.cpp │ │ ├── Wildcard_matching.cpp │ │ ├── egg_dropping_problem.cpp │ │ ├── longest_bitonic_subsequence.cpp │ │ ├── readme.md │ │ └── wordbreak.cpp │ ├── Factorial │ │ ├── factRecursion.cpp │ │ ├── factUsual.cpp │ │ └── readme.md │ ├── Geometric-Algorithms │ │ └── readme.md │ ├── Graph-Algorithms │ │ ├── A_star_Search_Algorithm.cpp │ │ ├── ArticulationPointandBridges.cpp │ │ ├── Bellman_Ford Algorithm.cpp │ │ ├── Bipartite_Graph.cpp │ │ ├── Breadth First Search.cpp │ │ ├── Component_count.cpp │ │ ├── Cycle_detection_directed_graph.cpp │ │ ├── Depth First Search.cpp │ │ ├── Dijkstra's Algorithm.cpp │ │ ├── FordFulkerson.cpp │ │ ├── Kosaraju.cpp │ │ ├── Kruskal's.cpp │ │ ├── Number_of_Islands.cpp │ │ ├── Topological_sort.cpp │ │ ├── Transitive_Closure.cpp │ │ ├── prims.cpp │ │ └── readme.md │ ├── Greedy-Algorithms │ │ ├── Fractional Knapsack.cpp │ │ ├── Huffman.cpp │ │ ├── Is_Subsequence.cpp │ │ ├── WeightedJobScheduling.cpp │ │ ├── interval queries │ │ ├── interval queries.cpp │ │ └── readme.md │ ├── Mathematical │ │ ├── Armstrong_number.cpp │ │ ├── Armstrong_number_comment.cpp │ │ ├── Euler's Totient Function │ │ ├── FFT │ │ │ └── FFT(Iterative).cpp │ │ ├── Fibonacci_no.cpp │ │ ├── Hosoya.cpp │ │ ├── Lucky_number_comment.cpp │ │ ├── Min_subsequence.cpp │ │ ├── Particular_sum │ │ ├── Power_Func.cpp │ │ ├── Program for nth Catalan number.cpp │ │ ├── Sieve of eratosthenes.cpp │ │ ├── Square_root.cpp │ │ ├── Subarray_with_sum_zero.cpp │ │ └── readme.md │ ├── Pattern-Searching │ │ ├── Rabin-Karp_Algorithm.cpp │ │ ├── boyermoore.cpp │ │ ├── kmp.cpp │ │ ├── longestRunHeadsTails.cpp │ │ ├── manachers.cpp │ │ ├── readme.md │ │ └── zalgorithm.cpp │ ├── Randomized-Algorithms │ │ ├── FloodFill │ │ │ ├── Flood_Fill_Algorithm.cpp │ │ │ └── flood-fill.cpp │ │ └── readme.md │ ├── Resolution │ │ └── 24to8bit.CPP │ ├── Searching-Algorithms │ │ ├── BinarySearch │ │ │ ├── AggressiveCows.cpp │ │ │ ├── BinarySearch.cpp │ │ │ └── BinarySearch_on_Rotated_Array.cpp │ │ ├── Find_kth_element.cpp │ │ ├── InterpolationSearch.cpp │ │ ├── JumpSearch.cpp │ │ ├── KthSmallestSearch.cpp │ │ ├── LinearSearch.cpp │ │ ├── Max_oR_min.cpp │ │ ├── TernarySearch.cpp │ │ ├── bellman_ford.cpp │ │ └── readme.md │ ├── Sorting-Algorithms │ │ ├── 3-Way Quick Sort │ │ │ ├── 3_Way_Quick_Sort.cpp │ │ │ ├── inputf.in │ │ │ └── outputf.in │ │ ├── Bitonic Sort │ │ │ ├── Bitonic_Sort.cpp │ │ │ ├── inputf.in │ │ │ └── outputf.in │ │ ├── BubbleSort │ │ │ └── Bubble_Sort.cpp │ │ ├── Cocktail Shaker Sort │ │ │ └── Cocktail_Shaker_Sort.cpp │ │ ├── CycleSort │ │ │ └── Cycle_Sort.cpp │ │ ├── Heapsort │ │ │ └── Heapsort.cpp │ │ ├── InsertionSort │ │ │ └── InsertionSort.cpp │ │ ├── InversionCount │ │ │ └── InversionsCount.cpp │ │ ├── MergeSort │ │ │ └── Merge_Sort.cpp │ │ ├── Pigeonhole Sort │ │ │ └── Pigeonhole_Sort.cpp │ │ ├── QuickSort │ │ │ └── Quick_Sort.cpp │ │ ├── RadixSort │ │ │ └── radixSort.cpp │ │ ├── SelectionSort │ │ │ └── selection_sort.cpp │ │ ├── SpiralMatrixSort.cpp │ │ ├── Topological sorting.cpp │ │ ├── bin or bucket │ │ │ └── bin.cpp │ │ ├── readme.md │ │ └── shell │ │ │ └── shell.cpp │ └── Two-Pointer-Algorithms │ │ ├── 3Sum.cpp │ │ ├── Floyd's-Cycle-Finding-Algorithm.cpp │ │ └── readme.md └── Data-Structures │ ├── Array │ ├── Move-neg-to-left.cpp │ ├── Move-neg-to-left_comment.cpp │ ├── PositiveAtEvenNegativeAtOdd.c++ │ ├── PositiveAtEvenNegativeAtOdd_comment.c++ │ ├── Remove_duplicates.cpp │ ├── Remove_duplicates_add_example.cpp │ ├── Rotate-an-array.cpp │ ├── Subarray With Sum Zero │ │ ├── Count_and_Print_0_sum_subarray.cpp │ │ └── Only_Count_Subarray_with_sum_0.cpp │ ├── Sum_of_two_arrays.cpp │ ├── Sum_of_two_arrays_comment.cpp │ ├── move_all_zeroes.cpp │ ├── move_all_zeroes_comment.cpp │ ├── readme.md │ ├── sort012.cpp │ └── threeSum.cpp │ ├── BST │ ├── BST_implementation │ ├── BST_implementation.cpp │ ├── Constructing BST from Level Order Traversal │ ├── Constructing BST from Level Order Traversal.cpp │ ├── Deletion From A BST.cpp │ ├── check_bst.cpp │ ├── pair_sum_in_bst.cpp │ └── readme.md │ ├── Disjoint Set │ ├── Disjoint_set_ranked_by_size_of_set.cpp │ ├── Implementation of disjoint set.cpp │ └── readme.md │ ├── Graph │ ├── BFS.cpp │ ├── ConnectedComponents.cpp │ └── readme.md │ ├── Hashing │ ├── readme.md │ └── trivial_hashing.cpp │ ├── Heap │ └── Heap (Kth Largest Element in a Stream ) C++ │ │ ├── KthLargestElementInAStream.cpp │ │ └── Readme.md │ ├── LinkedList │ ├── Circular Linked List Operations.cpp │ ├── Deleting a node in linklist.cpp │ ├── DeletionCircularLL.cpp │ ├── DoublyLinkedList.cpp │ ├── Flatten_List.cpp │ ├── InsertANodeLinkedList.cpp │ ├── Merge two sorted Linked Lists.cpp │ ├── MergeSort in Linked List.cpp │ ├── OrderedLinkedListStrings.cpp │ ├── ReverseALinkedList.cpp │ ├── Single_Linked_List.cpp │ └── readme.md │ ├── PriorityQueue │ ├── PriorityQueue.cpp │ └── readme.md │ ├── Queue │ ├── Queue using stacks.cpp │ ├── Queue.cpp │ ├── Queue_using_Array.cpp │ ├── Queue_using_LinkedList.cpp │ └── readme.md │ ├── Stack │ ├── Reverse_Words_of_String_using_Stack.cpp │ ├── Reverse_stack_without_using_extra_space.cpp │ ├── Stack.cpp │ ├── Stack_Using_Linked_List .cpp │ ├── TowerOfHanoi.cpp │ ├── balanced_brackets.cpp │ ├── infix_to_postfix_notation.cpp │ ├── readme.md │ ├── reverse a stack using recursion.cpp │ ├── sort_stack_using_temp_stack.cpp │ ├── stack_using_Array.cpp │ ├── stack_using_LinkedList.cpp │ ├── stack_using_Linked_List_Template.cpp │ └── stack_using_two_queues.cpp │ ├── Tree │ ├── AVL_Tree.cpp │ ├── Binary_Search_Tree_Implementation.cpp │ ├── Construct_Tree_from_given_Inorder_and_Preorder_traversals.cpp │ ├── Euler_tree_flattening.cpp │ ├── ExpressionTree.cpp │ ├── LCA_binary_lifting.cpp │ ├── Morris_Traversal │ │ ├── MorrisTraversal_Inorder.cpp │ │ └── MorrisTraversal_Preorder.cpp │ ├── Segment_Tree_with_Lazy_Propagation.cpp │ ├── fenwick_tree.cpp │ ├── huffman_decoding.cpp │ ├── readme.md │ └── segment tree for max subsequnce(cont) for range queries.cpp │ ├── Trie │ ├── Trie.cpp │ └── readme.md │ └── graph │ ├── bfs using queue.cpp │ ├── dfs using stack.cpp │ ├── graph implementation using adjacency list.cpp │ └── graph_implementation.cpp ├── C ├── Algorithms │ ├── Backtracking │ │ ├── N-Queen.c │ │ └── readme.md │ ├── Branch-and-Bound │ │ └── readme.md │ ├── Divide-and-Conquer │ │ ├── Tower Of Hanoi │ │ │ └── towerofhanoi.c │ │ └── readme.md │ ├── Dynamic-Programming │ │ ├── LonestCommonSubsequence.c │ │ └── readme.md │ ├── Geometric-Algorithms │ │ └── readme.md │ ├── Graph-Algorithms │ │ ├── Breadth_first_search.c │ │ ├── readme.md │ │ └── tree_traversal.c │ ├── Greedy-Algorithms │ │ ├── FractionalKnapsack.c │ │ └── readme.md │ ├── Mathematical │ │ ├── Factorial.c │ │ └── readme.md │ ├── Pattern-Searching │ │ ├── kmp_algorithm.c │ │ └── readme.md │ ├── Preemptive Priority Scheduling Algorithm │ │ └── Preemptive Priority Scheduling Algorithm.c │ ├── Randomized-Algorithms │ │ └── readme.md │ ├── Searching-Algorithms │ │ ├── Binary_search.c │ │ ├── Fibonacci_Search.c │ │ ├── jump_search.c │ │ ├── linear_search.c │ │ └── ternary-search_string.c │ └── Sorting-Algorithms │ │ ├── BubbleSort │ │ └── Bubble_sort.c │ │ ├── Bucket Sort │ │ └── BucketSort.c │ │ ├── HeapSort │ │ └── heap_sort.c │ │ ├── InsertionSort │ │ ├── InsertionSort.cpp │ │ ├── README.md │ │ └── insertion_sort.c │ │ ├── Merge Sort │ │ ├── MergeSort.c │ │ └── mergesort_3way.c │ │ ├── QuickSort │ │ ├── QuickSort.cpp │ │ └── README.md │ │ ├── Radix sort │ │ └── radixsort.c │ │ ├── SelectionSort │ │ └── SelectionSort.c │ │ └── Wave Sort │ │ └── wave_sort.c └── Data-Structures │ ├── Arrays │ ├── Largest_Smallest_Element_in_Array.c │ ├── addition_2x2_matrix.c │ ├── arrays.c │ └── operations_on_array.c │ ├── Graphs │ └── adjacencylist.c │ ├── LinkedList │ ├── CircularDoublyLinkedList.c │ ├── Circular_linked_list.c │ ├── DoublyLinkedList.c │ ├── ReverseSinglyLL.c │ ├── SelfLoopLinkedList.c │ ├── SwapNodesWithoutSwappingData.c │ ├── linked_list_of_linked_list.c │ └── linkedlist.c │ ├── Queue │ ├── Input_restricted_queue.c │ ├── Priority_queue.c │ ├── Queue_using_Stacks.c │ ├── queue_using_array.c │ └── queue_using_pointers.c │ ├── Stack │ ├── InfixToPostfixConv.c │ ├── InfixToPrefixConv.c │ ├── PostfixToPrefixConversion.c │ ├── Stack_using_doubly_linked_lists.c │ ├── Stack_using_linked_lists.c │ ├── Stack_using_queues.c │ ├── Tower_of_Hanoi.c │ └── stack_using_array.c │ └── Tree │ └── BinarySearchTree.c ├── CODE_OF_CONDUCT.md ├── CODE_OF_CONDUCT_korean_version.md ├── CONTRIBUTING.md ├── CONTRIBUTING_korean_version.md ├── Go ├── Algorithms │ ├── Backtracking │ │ ├── N-Queens-Problem │ │ │ └── main.go │ │ └── readme.md │ ├── Branch-and-Bound │ │ └── readme.md │ ├── Divide-and-Conquer │ │ └── readme.md │ ├── Dynamic-Programming │ │ ├── EditDistance.go │ │ ├── LongestCommonSubsequence.go │ │ └── readme.md │ ├── Geometric-Algorithms │ │ └── readme.md │ ├── Graph-Algorithms │ │ ├── DFS │ │ │ └── dfs.go │ │ ├── djikstras │ │ │ ├── Example │ │ │ │ └── main.go │ │ │ └── minheapmap │ │ │ │ └── minheapmap.go │ │ └── readme.md │ ├── Greedy-Algorithms │ │ └── readme.md │ ├── Mathematical │ │ ├── Fibonacci_till_nth_term.go │ │ └── readme.md │ ├── Pattern-Searching │ │ └── readme.md │ ├── Randomized-Algorithms │ │ └── readme.md │ ├── Searching-Algorithms │ │ ├── Binary-Search │ │ │ └── main.go │ │ ├── Interpolation-Search │ │ │ └── main.go │ │ ├── Linear-Search │ │ │ └── main.go │ │ └── readme.md │ └── Sorting-Algorithms │ │ ├── BubbleSort │ │ └── BubbleSort.go │ │ ├── HeapSort │ │ └── heap_sort.go │ │ ├── InsertionSort │ │ └── main.go │ │ ├── MergeSort │ │ └── MergeSort.go │ │ ├── QuickSort │ │ └── QuickSort.go │ │ └── readme.md └── Data-Structures │ ├── README.md │ ├── binary-search-tree │ └── main.go │ ├── hash-table │ └── main.go │ ├── linked-list │ └── main.go │ ├── queue │ ├── main.go │ └── queue_test.go │ ├── stack │ └── main.go │ └── trie │ └── main.go ├── Haskell └── Algorithms │ ├── Searching-Algorithms │ └── BinarySearch.hs │ └── Sorting-Algorithms │ └── InsertionSort.hs ├── Java ├── Algorithms │ ├── Backtracking │ │ ├── N-Queen.java │ │ └── readme.md │ ├── Branch-and-Bound │ │ └── readme.md │ ├── Divide-and-Conquer │ │ ├── Karatsuba.java │ │ └── readme.md │ ├── Dynamic-Programming │ │ ├── Binary │ │ │ └── ConvertBinary.java │ │ ├── Fibonacci │ │ │ └── Fibonacci.java │ │ ├── Hex │ │ │ └── ConvertHex.java │ │ └── readme.md │ ├── Geometric-Algorithms │ │ └── readme.md │ ├── Graph-Algorithms │ │ ├── BFS.java │ │ ├── BellmanFord.java │ │ ├── Dfs.java │ │ ├── Dijkstra.java │ │ ├── FordFulkerson.java │ │ └── readme.md │ ├── Greedy-Algorithms │ │ ├── Huffman_Encode.java │ │ ├── JobScheduling │ │ │ └── jobscheduling.java │ │ ├── PrimsAlgorithm.java │ │ └── readme.md │ ├── Mathematical │ │ ├── Lucky Number │ │ │ └── LuckyNumber.java │ │ ├── Median.java │ │ ├── StandardDeviation.java │ │ └── readme.md │ ├── Pattern-Searching │ │ ├── KMP_Pattern_SearchingAlgorithms │ │ │ └── KMPPatternSearching.java │ │ └── readme.md │ ├── Percolation │ │ ├── Percolation.java │ │ └── PercolationStats.java │ ├── Randomized-Algorithms │ │ └── readme.md │ ├── Searching-Algorithms │ │ ├── BinarySearch │ │ │ ├── BinarySearch.java │ │ │ ├── Binary_Search.java │ │ │ ├── SearchInSortedArray.java │ │ │ └── rotated_binary_search.java │ │ ├── Exponential Search │ │ │ └── Exponential.java │ │ ├── InterpolationSearch │ │ │ └── interpolationsearch.java │ │ ├── LinearSearch │ │ │ └── LinearSearch.java │ │ ├── fibonaccisearch.java │ │ └── readme.md │ ├── Sorting-Algorithms │ │ ├── BubbleSort │ │ │ ├── BubbleSort.java │ │ │ └── RecursiveBubbleSort.java │ │ ├── CountingSort.java │ │ ├── HeapSort │ │ │ └── heapSort.java │ │ ├── InsertionSort │ │ │ └── InsertionSort.java │ │ ├── MergeSort │ │ │ └── MergeSort.java │ │ ├── PigeonHoleSort.java │ │ ├── QuickSort.java │ │ ├── RadixSort.java │ │ ├── Randomized_Quick_Sort.java │ │ ├── SelectionSort │ │ │ └── SelectionSort.java │ │ └── readme.md │ └── towerOfHanoi.java └── Data-Structures │ ├── Array │ └── RLEdecode.java │ ├── Binary search tree │ └── binary_search_tree.java │ ├── DSU │ └── DisjointUnionSet.java │ ├── Heap │ ├── FibonacciHeap.java │ ├── MaxHeapByArrayList.java │ ├── MinHeapByArrayList.java │ └── TreeSetHeap.java │ ├── LinkedList │ ├── Circular_linkedlist.java │ ├── DoublyLinkedList.java │ ├── SelfLoopLinkedList.java │ ├── SingleLinkedList.java │ └── SingleLinkedListMain.java │ ├── Queue │ ├── Queue.java │ ├── Queue_LinkedList.java │ └── Queue_TwoStacks.java │ ├── SegmentTree │ └── segment_tree.java │ ├── Stack │ ├── node │ │ └── SingleNode.java │ └── stack │ │ ├── StackByArray.java │ │ ├── StackByArrayMain.java │ │ ├── StackByLinkedList.java │ │ ├── StackByLinkedListMain.java │ │ └── StackSorting.java │ ├── String │ └── Palindrome.java │ ├── Trie │ └── Trie.java │ └── tree │ ├── WAVLTree │ └── WAVLTree.java │ └── creating_a_binary_tree_using_circular_queue.java ├── LICENSE ├── Python ├── Algorithms │ ├── Backtracking │ │ ├── Backtracking_in_Python.py │ │ ├── NQueens.py │ │ └── readme.md │ ├── Branch-and-Bound │ │ └── readme.md │ ├── Deep Learning Algorithms │ │ ├── ActivationFunction.py │ │ ├── ConvolutionalNN.py │ │ ├── FeedForwardNeuralNetwork.py │ │ ├── Layers.py │ │ ├── LossFunction.py │ │ └── Optimizers.py │ ├── Dijkstra-Algorithm │ │ ├── dijkstra_algorithm.py │ │ └── readme.md │ ├── Divide-and-Conquer │ │ ├── Divide_and_Conquer.py │ │ └── readme.md │ ├── Dynamic-Programming │ │ ├── 0-1_knapsack.py │ │ ├── Longest-bitonic-subsequence.py │ │ ├── fibonacci-number.py │ │ ├── largest-sum-contiguous-subarray.py │ │ ├── longest_common_subsequence.py │ │ ├── readme.md │ │ ├── subset_sum_problem.py │ │ └── travelling_salesman_problem.py │ ├── Face_mask_detector │ │ ├── ARMD.py │ │ ├── LOGO.PNG │ │ ├── face_detector │ │ │ ├── deploy.prototxt │ │ │ └── res10_300x300_ssd_iter_140000.caffemodel │ │ ├── mask_detector.model │ │ ├── plot.png │ │ └── requirements.txt │ ├── Geometric-Algorithms │ │ └── readme.md │ ├── Graph-Algorithms │ │ ├── BridgesAndArticulationPoints.py │ │ ├── Decision Tree │ │ │ └── decisionTree.py │ │ ├── Kruskal │ │ │ ├── 1000EWG.txt │ │ │ ├── Kruskal.py │ │ │ ├── KruskalDriver.py │ │ │ ├── ewgraph1.txt │ │ │ └── min_heap.py │ │ ├── Union Find │ │ │ └── UnionFind.py │ │ └── readme.md │ ├── Greedy-Algorithms │ │ ├── Egyptian-Fraction.py │ │ ├── activity_selection.py │ │ ├── currency_denomiations.py │ │ ├── egyptian_fraction.py │ │ ├── fractional_knapsack.py │ │ ├── jobsquence.py │ │ ├── police_thief.py │ │ ├── problem_specifications.txt │ │ └── readme.md │ ├── Machine Learning Algorithms │ │ ├── Gaussian_Process_Regression.py │ │ ├── KNN(Supervised-Classification).ipynb │ │ ├── KmeansClustering.py │ │ ├── Linear_Regression_Normal_Equation.py │ │ ├── Naive Bayes in python.py │ │ └── PCA.py │ ├── Mathematical │ │ ├── JoynernacciSequence.py │ │ ├── Pascals_triangle.py │ │ ├── Smith_number.py │ │ ├── readme.md │ │ └── sieve_of_eratosthenes.py │ ├── Pattern-Searching │ │ ├── rabin_karp_algorithm.py │ │ └── readme.md │ ├── Randomized-Algorithms │ │ └── readme.md │ ├── Searching-Algorithms │ │ ├── binary_Search_iterative.py │ │ ├── binary_Search_recursive.py │ │ ├── exponential_search.py │ │ ├── fibonacci_search.py │ │ ├── interpolation_search.py │ │ ├── jump_search.py │ │ ├── linear_Search.py │ │ └── readme.md │ └── Sorting-Algorithms │ │ ├── binary_insertion_sort.py │ │ ├── bogo_sort.py │ │ ├── bubble_sort.py │ │ ├── bucket_sort.py │ │ ├── comb_sort.py │ │ ├── counting_sort.py │ │ ├── heapsort.py │ │ ├── insertion_sort.py │ │ ├── merge_sort.py │ │ ├── pigeonhole_sort.py │ │ ├── quicksort.py │ │ ├── radix.py │ │ ├── readme.md │ │ ├── selection_sort.py │ │ ├── shell_sort.py │ │ └── tim_sort.py └── DataStructures │ ├── AVLTree │ └── AVLTree.py │ ├── Array │ └── LUDecompositionMatrix.py │ ├── BinarySearchTree │ ├── binary_search_tree.py │ ├── extended_binary_search_tree.py │ └── splay_tree.py │ ├── Circular Queue │ └── CircQueue.py │ ├── Doubly Linked List │ ├── ReverseDoublyLinkedList.py │ └── doublylist.py │ ├── DoublyLinkedList │ ├── doubly_linked_list.py │ └── test │ │ └── test_doubly_linked_list.py │ ├── Graph │ ├── BFS for Graph.py │ ├── DFS for Graph.py │ ├── MultiPurposeSegmentTree.py │ └── graph.py │ ├── Hashmaps │ └── hashmap.py │ ├── Heap │ └── Heap.py │ ├── LinkedList │ └── linkedList.py │ ├── Priority Queue │ └── priorityqueue.py │ ├── Queue │ ├── Queue.py │ └── queue_via_stack.py │ ├── Red-Black-Search-Tree │ └── Red-Black-Search-Tree.py │ ├── Stack │ ├── reverse_int_using_stack.py │ ├── stack.py │ └── test │ │ └── test_stack.py │ └── Trie │ └── trie.py ├── README.md ├── README_korean_version.md └── Swift ├── Algorithms └── Searching-Algorithms │ └── binary_search.swift └── Data-Structures ├── Linked-List ├── DoubleLinkedList.swift └── SingleLinkedList.swift ├── Queue └── Queue.swift └── Stack └── Stack.swift /.github/ISSUE_TEMPLATE/create-an-issue.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Create an Issue 3 | about: For creating a new issue for HacktoberFest 4 | title: 'Algorithm or Data Structure name | Language' 5 | labels: good first issue 6 | assignees: '' 7 | 8 | --- 9 | 10 | ## **`Title`** - 11 | 12 | **what will change** - 13 | 14 | ### Type of Issue - 15 | 16 | Please add/delete options that are not relevant. 17 | 18 | - [x] Adding New Code 19 | - [x] Improving Code 20 | - [x] Improving Documentation 21 | - [x] Bug Fix 22 | 23 | ### Programming Language 24 | 25 | Please add/delete options that are not relevant. 26 | 27 | - [x] Python 28 | - [x] C++ 29 | - [x] Java 30 | - [x] C 31 | - [x] Go 32 | - [x] Other language 33 | 34 | ### Self Check 35 | 36 | - Ask for issue assignment before making Pull Request. 37 | - Add your file in the proper folder 38 | - `Clean Code` and `Documentation` for better readability 39 | - Add `Title` and `Description` of the program in the file 40 | 41 | :star2: Star it :fork_and_knife:Fork it :handshake: Contribute to it! 42 | 43 | Happy Coding! 44 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ## Pull Request Template 2 | 3 | ### What have you Changed(must) 4 | 5 | Write here what you have changed in codebase 6 | 7 | ### Issue no.(must) - # 8 | 9 | Pr will be closed and marked as spam. If issue number not found or issue was assigned to someone else. 10 | Marking as spam can block your account from HacktoberFest. 11 | ### Self Check(Tick After Making pull Request) 12 | 13 | - [ ] This issue was assigned to me if not it will marked as spam. 14 | - [ ] My file is in proper folder. 15 | - [ ] I am following clean code and Documentation. 16 | - [ ] I have added title and what program will do first in the file. 17 | 18 | ### README - [How to Contribute](https://github.com/div-bargali/Data-Structures-and-Algorithms/blob/main/CONTRIBUTING.md) 19 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .vscode 3 | /.vs/slnx.sqlite 4 | /.vs/Data-Structures-and-Algorithms/v16/ipch/AutoPCH/4139952b9b5e1f52/BELLMAN_FORD ALGORITHM.ipch 5 | /.vs/Data-Structures-and-Algorithms/v16/Browse.VC.opendb 6 | /.vs/Data-Structures-and-Algorithms/v16/Browse.VC.db-wal 7 | /.vs/Data-Structures-and-Algorithms/v16/Browse.VC.db-shm 8 | /.vs/Data-Structures-and-Algorithms/v16/Browse.VC.db 9 | /.vs/Data-Structures-and-Algorithms/v16/.suo 10 | -------------------------------------------------------------------------------- /C#/Algorithms/Backtracking/readme.md: -------------------------------------------------------------------------------- 1 | ### Backtracking-Algorithms -------------------------------------------------------------------------------- /C#/Algorithms/Branch-and-Bound/readme.md: -------------------------------------------------------------------------------- 1 | ### Branch-and-Bound -------------------------------------------------------------------------------- /C#/Algorithms/Divide-and-Conquer/readme.md: -------------------------------------------------------------------------------- 1 | ### Divide-and-Conquer 2 | -------------------------------------------------------------------------------- /C#/Algorithms/Dynamic-Programming/readme.md: -------------------------------------------------------------------------------- 1 | ### Dynamic-Programming 2 | -------------------------------------------------------------------------------- /C#/Algorithms/Geometric-Algorithms/readme.md: -------------------------------------------------------------------------------- 1 | ### Geometric-Algorithms -------------------------------------------------------------------------------- /C#/Algorithms/Graph-Algorithms/readme.md: -------------------------------------------------------------------------------- 1 | ### Graph-Algorithms -------------------------------------------------------------------------------- /C#/Algorithms/Greedy-Algorithms/readme.md: -------------------------------------------------------------------------------- 1 | ### Greedy-Algorithms -------------------------------------------------------------------------------- /C#/Algorithms/Mathematical/readme.md: -------------------------------------------------------------------------------- 1 | ### Mathematical -------------------------------------------------------------------------------- /C#/Algorithms/Pattern-Searching/readme.md: -------------------------------------------------------------------------------- 1 | ### Pattern-Searching -------------------------------------------------------------------------------- /C#/Algorithms/Randomized-Algorithms/readme.md: -------------------------------------------------------------------------------- 1 | ### Randomized-Algorithms -------------------------------------------------------------------------------- /C#/Algorithms/Searching-Algorithms/LinearSearch/LinearSearch.cs: -------------------------------------------------------------------------------- 1 | // C# implementation of a simple linear search 2 | using System; 3 | 4 | class LinearSearch { 5 | 6 | // Returns the index of the searched for element if present, else returns -1 7 | static T LinearSearch(T[] arr, T itemToFind) where T : class 8 | { 9 | int index = 0; 10 | foreach (var item in arr) { 11 | if (item == itemToFind) { 12 | return index; 13 | } 14 | index ++; 15 | } 16 | 17 | // If this point is reached then element has not been found 18 | return -1; 19 | } 20 | 21 | } 22 | 23 | // Driver method to test above 24 | public static void Main() { 25 | 26 | Console.WriteLine("Input array to search through, separated by spaces"); 27 | 28 | var arr = Console.ReadLine(); 29 | 30 | Console.WriteLine("Input item to search for"); 31 | 32 | var itemToFind = Console.ReadLine(); 33 | 34 | var result = LinearSearch(arr, itemToFind); 35 | 36 | if (result == -1) 37 | Console.WriteLine("Element not present"); 38 | else 39 | Console.WriteLine("Element found at index " 40 | + result); 41 | } 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /C#/Algorithms/Searching-Algorithms/readme.md: -------------------------------------------------------------------------------- 1 | ### Searching-Algorithms -------------------------------------------------------------------------------- /C#/Algorithms/Sorting-Algorithms/readme.md: -------------------------------------------------------------------------------- 1 | ### Sorting-Algorithms 2 | -------------------------------------------------------------------------------- /C++/Algorithms/Backtracking/Permutation_of_string.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Function to find all Permutations of a given string str[i..n-1] 5 | // containing all distinct characters and which u want to change 6 | 7 | void permutations(string str, int i, int n) 8 | { 9 | // base condition 10 | if (i == n - 1) 11 | { 12 | cout << str << endl; 13 | return; 14 | } 15 | 16 | // process each character of the remaining string 17 | for (int j = i; j < n; j++) 18 | { 19 | // swap character at index i with current character 20 | swap(str[i], str[j]); // STL swap() used 21 | 22 | // recur for string [i+1, n-1] 23 | permutations(str, i + 1, n); 24 | 25 | // backtrack (restore the string to its original state) 26 | swap(str[i], str[j]); 27 | } 28 | } 29 | 30 | // Find all Permutations of a string 31 | int main() 32 | { 33 | string str = "ABC"; 34 | 35 | permutations(str, 0, str.length()); 36 | 37 | return 0; 38 | } -------------------------------------------------------------------------------- /C++/Algorithms/Backtracking/RAT IN MAZE problem.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | 6 | void printSolution(int** solution,int n){ 7 | for(int i=0;i=n || x<0 || y>=n || y<0 || maze[x][y] ==0 || solution[x][y] ==1){ 24 | return; 25 | } 26 | solution[x][y] = 1; 27 | mazeHelp(maze,n,solution,x-1,y); 28 | mazeHelp(maze,n,solution,x+1,y); 29 | mazeHelp(maze,n,solution,x,y-1); 30 | mazeHelp(maze,n,solution,x,y+1); 31 | solution[x][y] = 0; 32 | } 33 | void ratInAMaze(int maze[][20], int n){ 34 | 35 | int** solution = new int*[n]; 36 | for(int i=0;i> n ; 50 | int maze[20][20]; 51 | for(int i = 0; i < n ;i++){ 52 | for(int j = 0; j < n; j++){ 53 | cin >> maze[i][j]; 54 | } 55 | } 56 | ratInAMaze(maze, n); 57 | } 58 | 59 | 60 | -------------------------------------------------------------------------------- /C++/Algorithms/Branch-and-Bound/readme.md: -------------------------------------------------------------------------------- 1 | ### Branch-and-Bound -------------------------------------------------------------------------------- /C++/Algorithms/Divide-and-Conquer/TowerOfHanoi.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | //Function that would calculate no of steps for discs transfer from tower 1 to tower 3 5 | 6 | //count is accepted as reference to directly reflect changes in main() 7 | void solveTower(int n,int s,int h,int d,int &count){ 8 | if(n==1){ 9 | count++; 10 | return ; 11 | } 12 | 13 | // recursively transferring n-1 discs from source to helper tower 14 | solveTower(n-1,s,d,h,count); 15 | count++; 16 | 17 | //transfering discs from helper to destination tower 18 | solveTower(n-1,h,s,d,count); 19 | 20 | } 21 | 22 | 23 | int main(){ 24 | 25 | int n,source=1,helper=2,dest=3,count=0; 26 | 27 | //input n discs 28 | cin>>n; 29 | 30 | //calling function 31 | solveTower(n,source,helper,dest,count); 32 | 33 | //displaying no. of steps 34 | cout< 3 | #include 4 | using namespace std; 5 | 6 | // function to calculate sum between two indices 7 | // in array 8 | int sum(int arr[], int from, int to) 9 | { 10 | int total = 0; 11 | for (int i = from; i <= to; i++) 12 | total += arr[i]; 13 | return total; 14 | } 15 | 16 | // bottom up tabular dp 17 | int findMax(int arr[], int n, int k) 18 | { 19 | // initialize table 20 | int dp[k + 1][n + 1] = { 0 }; 21 | 22 | // base cases 23 | // k=1 24 | for (int i = 1; i <= n; i++) 25 | dp[1][i] = sum(arr, 0, i - 1); 26 | 27 | // n=1 28 | for (int i = 1; i <= k; i++) 29 | dp[i][1] = arr[0]; 30 | 31 | // 2 to k partitions 32 | for (int i = 2; i <= k; i++) { // 2 to n boards 33 | for (int j = 2; j <= n; j++) { 34 | 35 | // track minimum 36 | int best = INT_MAX; 37 | 38 | // i-1 th separator before position arr[p=1..j] 39 | for (int p = 1; p <= j; p++) 40 | best = min(best, max(dp[i - 1][p], 41 | sum(arr, p, j - 1))); 42 | 43 | dp[i][j] = best; 44 | } 45 | } 46 | 47 | // required 48 | return dp[k][n]; 49 | } 50 | 51 | // driver function 52 | int main() 53 | { 54 | int arr[] = { 10, 20, 60, 50, 30, 40 }; 55 | int n = sizeof(arr) / sizeof(arr[0]); 56 | int k = 3; 57 | cout << findMax(arr, n, k) << endl; 58 | return 0; 59 | } 60 | -------------------------------------------------------------------------------- /C++/Algorithms/Divide-and-Conquer/readme.md: -------------------------------------------------------------------------------- 1 | ### Divide-and-Conquer 2 | - [Painter's Partition Problem](painter%E2%80%99s%20partition%20problem.cpp) 3 | 4 | Painter's Partition Problem is to find the minimum time when we have to paint n boards of length {A1,A2,....,An} and there are k painters available and each takes 1 unit time to paint 1 unit of board under the constraints that any painter will only paint continuous sections of boards like board {2,3,4} or only board {1}, or nothing but not board {2,4,5} 5 | 6 | Time complexity = O(k*N^3) 7 | 8 | - [Tower of Hanoi1](tower_of_hanoi.cpp), [Tower of Hanoi2](TowerOfHanoi.cpp) 9 | 10 | Tower of Hanoi is a mathematic puzzle which consists of three towers and more than one rings. There are three rules in this algorithm in moving all the disks to some another tower without violationg the sequence of arrangement. 1. Only one disk can be moved among the towers at any given time 2. Only the top disk can be removed 3. No large disk can sit over a small disk 11 | 12 | Time complexity = O(n) -------------------------------------------------------------------------------- /C++/Algorithms/Divide-and-Conquer/tower_of_hanoi.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void tower_of_hanoi(int n, char from_rod, char to_rod, char tmp_rod) { 5 | if (n == 1) { 6 | cout << "Move disk 1 from rod " << from_rod << " to rod " << to_rod << endl; 7 | return; 8 | } 9 | tower_of_hanoi(n - 1, from_rod, tmp_rod, to_rod); 10 | cout << "Move disk " << n << " from rod " << from_rod << " to rod " << to_rod << endl; 11 | tower_of_hanoi(n - 1, tmp_rod, to_rod, from_rod); 12 | } 13 | 14 | int main() { 15 | int n; // Number of disks 16 | cout << "Enter the no. of disks : "; 17 | cin >> n; 18 | tower_of_hanoi(n, 'X', 'Z', 'Y'); 19 | // 'X' - name of from_rod 20 | // 'Z' - name of to_rod 21 | // 'Y' - name of tmp_rod 22 | return 0; 23 | } -------------------------------------------------------------------------------- /C++/Algorithms/Dynamic-Programming/Coin Change Problem.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem Statement - Given a value N, find the number of ways to make change for N cents, 3 | if we have infinite supply of each of S = { S1, S2, .. , SM } valued coins. 4 | Input: 5 | n = 4 , m = 3 6 | S[] = {1,2,3} 7 | Output: 4 8 | Explanation: Four Possible ways are: 9 | {1,1,1,1},{1,1,2},{2,2},{1,3}. 10 | 11 | Approach Used - Dynamic Programming 12 | */ 13 | #include 14 | using namespace std; 15 | int coin_change(int coin[],int n,int cent) 16 | { 17 | //dp array 18 | int dp[n+1][cent+1]; 19 | for(int i=0;i>t; 40 | while(t--) 41 | { 42 | int n; 43 | cin>>n; 44 | int coin[n]; 45 | for(int i=0;i>coin[i]; 46 | int cent; 47 | cin>>cent; 48 | cout< 2 | using namespace std; 3 | 4 | int josephus(int n, int k) 5 | { 6 | if (n == 1) 7 | return 1; 8 | else 9 | /* The position returned by josephus(n - 1, k) 10 | is adjusted because the recursive call 11 | josephus(n - 1, k) considers the 12 | original position k % n + 1 as position 1 */ 13 | return (josephus(n - 1, k) + k-1) % n + 1; 14 | } 15 | 16 | // Driver Program to test above function 17 | int main() 18 | { 19 | int n, k; 20 | cin>>n>>k; 21 | cout << "The chosen place is " << josephus(n, k); 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /C++/Algorithms/Dynamic-Programming/Kadane-Algorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | //function to find the maximum sum of contiguous sub-array 4 | int maxSumSubArray(int array[], int size) { 5 | int current_sum = array[0], maximum_sum = array[0]; 6 | for(int i = 1; i < size; ++i) { 7 | if(array[i] > current_sum + array[i]) { 8 | current_sum = array[i]; 9 | } 10 | else { 11 | current_sum += array[i]; 12 | } 13 | if(current_sum > maximum_sum) { 14 | maximum_sum = current_sum; 15 | } 16 | } 17 | return maximum_sum; 18 | } 19 | 20 | int main() { 21 | 22 | int array[] = {-2, -3, 4, -1, -2, 1, 5, -3}; 23 | // Other test cases: array[] = {-1, -2, -3, -4} 24 | int size = sizeof(array) / sizeof(array[0]); 25 | int maximum_sum = maxSumSubArray(array, size); 26 | cout << "Largest sum of contiguos subarray is " << maximum_sum << endl; 27 | 28 | return 0; 29 | } 30 | 31 | -------------------------------------------------------------------------------- /C++/Algorithms/Dynamic-Programming/Longest Common Subsequence.cpp: -------------------------------------------------------------------------------- 1 | /* Given Strings A = "xyxyxyxyx" and B = "xysdxyxyzuc" find length of longest common substring in these */ 2 | int lcs(char*X,char*Y,int m,int n) 3 | { 4 | int L[m+1][n+1]; 5 | int i,j; 6 | for(i = 0; i<=m; i++) 7 | for(j=0;j<=n;j++) 8 | { 9 | if(i==0||j==0) 10 | L[i][j]=0; 11 | else if(X[i-1]==Y[j-1]) 12 | L[i][j] = L[i-1][j-1] + 1; 13 | else 14 | L[i][j] = max(L[i][j-1],L[i-1][j]); 15 | } 16 | 17 | return L[m][n]; 18 | } 19 | -------------------------------------------------------------------------------- /C++/Algorithms/Dynamic-Programming/Max Profit with K transactions.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Function try to find maximum profit by doing k transactions 5 | int maxProfitWithKTransactions(vector prices, int k) { 6 | 7 | //Base Case 8 | if(prices.size() == 0) 9 | return 0; 10 | 11 | //2D DP array with transactions as row and price array as column 12 | vector> profits(k+1, vector(prices.size(),0)); 13 | 14 | for(int i =1;i 17 | #include 18 | using namespace std; 19 | int jumps(int arr[],int n) 20 | { 21 | if(arr[0] == 0) return -1; 22 | int dp[n]; 23 | dp[0] = 0; 24 | for(int i=1;i>t; 42 | while(t--) 43 | { 44 | int n; 45 | cin>>n; 46 | int arr[n]; 47 | for(int i=0;i>arr[i]; 49 | cout< 11 | using namespace std; 12 | 13 | // m is size of coins array (number of different coins) 14 | int minCoins(int coins[], int m, int V) 15 | { 16 | // base case 17 | if (V == 0) return 0; 18 | 19 | // Initialize result 20 | int res = INT_MAX; 21 | 22 | // Try every coin that has smaller value than V 23 | for (int i=0; i 5 | using namespace std; 6 | typedef long long int ll; 7 | 8 | int main() 9 | { 10 | ll n,i,j,k; 11 | //n = Number of Eggs 12 | // k =Number of Floors 13 | cout<<"Enter number of eggs: "; 14 | cin>>n; 15 | cout<<"Enter number of Floors: "; 16 | cin>>k; 17 | ll dp[n+1][k+1]; 18 | for (i = 1; i <= n; i++) { 19 | dp[i][1] = 1; 20 | dp[i][0] = 0; 21 | } 22 | 23 | for (j = 1; j <= k; j++) 24 | dp[1][j] = j; 25 | ll ans; 26 | ll x; 27 | for (i = 2; i <= n; i++) { 28 | for (j = 2; j <= k; j++) { 29 | dp[i][j] = INT_MAX; 30 | for (x = 1; x <= j; x++) { 31 | ans = 1 + max(dp[i - 1][x - 1],dp[i][j - x]); 32 | if (ans < dp[i][j]) 33 | dp[i][j] = ans; 34 | } 35 | } 36 | } 37 | cout<<"Minimum Trials: "< 3 | 4 | using namespace std; 5 | //Recursive function to calculate factorial of the number 6 | int fact(int num) 7 | { 8 | if(num<0) //Because factorial of negative numbers do not exist 9 | return -1; 10 | else if(num==0||num==1) //0!=1 and 1!=1 (Base Case) 11 | return 1; 12 | else 13 | { 14 | return num*fact(num-1); //Recursive call 15 | } 16 | } 17 | 18 | int main() 19 | { 20 | int n, factorial; 21 | cout<<"\nEnter a number for which factorial is to be computed: "; 22 | cin>>n; 23 | factorial=fact(n); 24 | if(factorial==-1) 25 | { 26 | cout<<"\nFactorial for negative numbers cannot be computed\n"; 27 | } 28 | else{ 29 | cout<<"\nFactorial of "< 3 | 4 | using namespace std; 5 | 6 | //function to calculate factorial 7 | int fact(int num) 8 | { 9 | int i, fact=1; 10 | if(num<0) //factorial cannot be calculated for negative numbers 11 | return -1; 12 | else if(num==0||num==1) //0!=1 and 1!=1 13 | return 1; 14 | else 15 | { 16 | for(i=2;i<=num;i++) 17 | { 18 | fact=fact*i; 19 | } 20 | return fact; 21 | } 22 | } 23 | 24 | int main() 25 | { 26 | int n, factorial; 27 | cout<<"\nEnter a number for which factorial is to be computed: "; 28 | cin>>n; 29 | factorial=fact(n); 30 | if(factorial==-1) 31 | { 32 | cout<<"\nFactorial for negative numbers cannot be computed\n"; 33 | } 34 | else{ 35 | cout<<"\nFactorial of "< 8 | using namespace std; 9 | #include 10 | #include 11 | #include 12 | #define lli long long int 13 | #include 14 | #define vi vector 15 | #define fo(i,n) for(int i=1;i<=n;i++) 16 | 17 | #include 18 | 19 | vi adj[2003]; 20 | int vis[2003] , col[2003]; 21 | 22 | bool dfs(int node,int color){ 23 | 24 | vis[node]=1; 25 | col[node]=color; 26 | 27 | for(int child: adj[node]){ 28 | if(!vis[child]){ 29 | if(!dfs(child,color^1)) return false;} 30 | 31 | else if(vis[child]==1){ 32 | if(col[child]==col[node]) return false; 33 | } 34 | 35 | } 36 | 37 | return true; 38 | } 39 | 40 | int main(){ 41 | int t,a,b; cin>>t; 42 | 43 | fo(k,t){ 44 | 45 | for(int i=0;i<2003;i++) vis[i]=0, adj[i].clear(); 46 | 47 | lli n,m; cin>>n>>m; 48 | 49 | while(m--) 50 | 51 | cin>>a>>b , adj[a].push_back(b) , adj[b].push_back(a); 52 | 53 | cout<<"Scenario #"< 11 | using namespace std; 12 | #include 13 | #include 14 | #include 15 | #define lli long long int 16 | #include 17 | #define vi vector 18 | #define mod 1000000007 19 | #define pb push_back 20 | #define fo(i,n) for(int i=1;i<=n;i++) 21 | 22 | #include 23 | 24 | vi adj[100003]; 25 | int vis[100003],member; 26 | 27 | void dfs(int node){ 28 | vis[node]=1; 29 | member++; 30 | for(int child: adj[node]){ 31 | if(!vis[child]){ 32 | dfs(child); 33 | } 34 | } 35 | } 36 | 37 | int main(){ 38 | int t,n,m,a,b; 39 | cin>>t; 40 | 41 | while(t--){ 42 | lli ans=1,cc=0; 43 | 44 | cin>>n>>m; 45 | 46 | fo(i,n) vis[i]=0, adj[i].clear(); 47 | 48 | fo(i,m) cin>>a>>b, adj[a].pb(b), adj[b].pb(a); 49 | fo(i,n) 50 | if(!vis[i]){ 51 | member=0; 52 | cc++; dfs(i); 53 | ans = (ans * member)%mod; 54 | } 55 | cout< 7 | using namespace std; 8 | bool isSubsequence(string s, string t) { 9 | int i, j = 0; 10 | if (s.length() == 0) // empty string is always a subsequence 11 | return true; 12 | char c = s[0]; //c stores first character of s 13 | if (t.length() < s.length()) // a string s containing less characters than t cannot be its subsequence 14 | return false; 15 | for (i = 0; i < t.length(); i++) 16 | { 17 | if (t[i] == c) 18 | { 19 | j++; //it moves the iterator to the next character of s 20 | if (j == s.length()) //if the iterator has reached the limit of s , it means it is present as subsequence 21 | return true; 22 | c = s[j]; 23 | } 24 | } 25 | return false; //if the conditions are not satisified above, then s is not a subsequence of t 26 | } 27 | int main() 28 | { 29 | string s, t; 30 | cin >> s >> t; 31 | cout << boolalpha; //to display true for 1 and false for 0 32 | cout << isSubsequence(s, t); 33 | return 0; 34 | } -------------------------------------------------------------------------------- /C++/Algorithms/Mathematical/Armstrong_number.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | int n, ognum, d, ct = 0, sum = 0, power; 8 | cout << "Enter an integer: "; 9 | cin >> n; 10 | 11 | ognum = n; 12 | 13 | while (ognum != 0) { 14 | ognum /= 10; 15 | ++ct; 16 | } 17 | ognum = n; 18 | 19 | while (ognum != 0) { 20 | d = ognum % 10; 21 | power = round(pow(d, ct)); 22 | sum += power; 23 | ognum /= 10; 24 | } 25 | 26 | if (sum == n) 27 | cout << n << " is an Armstrong number."; 28 | else 29 | cout << n << " is not an Armstrong number."; 30 | return 0; 31 | } -------------------------------------------------------------------------------- /C++/Algorithms/Mathematical/Armstrong_number_comment.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This function is a function that calculates the sum of the number of digits in the integer entered by the user by the number of digits in the entered integer. 3 | If the number is the same as the number initially entered, it prints that the Armstrong number is correct, and if it is different, it prints that it is not. 4 | */ 5 | #include 6 | #include 7 | 8 | using namespace std; 9 | 10 | int main() { 11 | int n, ognum, d, ct = 0, sum = 0, power; 12 | cout << "Enter an integer: "; 13 | cin >> n; 14 | 15 | ognum = n; 16 | 17 | while (ognum != 0) { // Finding the number of digits of the input integer 18 | ognum /= 10; 19 | ++ct; 20 | } 21 | ognum = n; 22 | 23 | while (ognum != 0) { // Square the numbers in each digit by the number of digits in the input integer. Then, the squared numbers are added together 24 | d = ognum % 10; 25 | power = round(pow(d, ct)); 26 | sum += power; 27 | ognum /= 10; 28 | } 29 | 30 | if (sum == n) // Armstrong's number if the sum of the number of digits from the inputted integers squared by the number of digits received is equal to the number initially input 31 | cout << n << " is an Armstrong number."; 32 | else // If it's wrong, it's not Armstrong's number. 33 | cout << n << " is not an Armstrong number."; 34 | return 0; 35 | } -------------------------------------------------------------------------------- /C++/Algorithms/Mathematical/Euler's Totient Function: -------------------------------------------------------------------------------- 1 | // Euler's Totient Function 2 | #include 3 | using namespace std; 4 | 5 | // Function to return gcd of a and b 6 | int gcd(int a, int b) 7 | { 8 | if (a == 0) 9 | return b; 10 | return gcd(b % a, a); 11 | } 12 | 13 | // A simple method to evaluate Euler Totient Function 14 | int phi(unsigned int n) 15 | { 16 | unsigned int result = 1; 17 | for (int i = 2; i < n; i++) 18 | if (gcd(i, n) == 1) 19 | result++; 20 | return result; 21 | } 22 | 23 | // Driver program to test above function 24 | int main() 25 | { 26 | int n; 27 | for (n = 1; n <= 10; n++) 28 | cout << "phi("< 3 | using namespace std; 4 | 5 | int fib(int n) 6 | { 7 | 8 | int a = 0, b = 1, c, i; 9 | if( n == 0) 10 | return a; 11 | for(i = 2; i <= n; i++) 12 | { 13 | c = a + b; 14 | a = b; 15 | b = c; 16 | } 17 | return b; 18 | 19 | } 20 | 21 | 22 | // Driver code 23 | int main() 24 | { 25 | int n; 26 | int a = 0, b = 1, c, i; 27 | cout << "Enter the number : "; 28 | cin >> n; 29 | cout << "The last fibonacci number is : " << fib(n); 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /C++/Algorithms/Mathematical/Hosoya.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | int Hosoya(int n, int m) 6 | { 7 | // Base case 8 | if ((n == 0 && m == 0) || (n == 1 && m == 0) || (n == 1 && m == 1) || (n == 2 && m == 1)) 9 | return 1; 10 | 11 | // Recursive step 12 | if (n > m) 13 | return Hosoya(n - 1, m) 14 | + Hosoya(n - 2, m); 15 | 16 | else if (m == n) 17 | return Hosoya(n - 1, m - 1) 18 | + Hosoya(n - 2, m - 2); 19 | 20 | else 21 | return 0; 22 | } 23 | 24 | // Print the Hosoya triangle of height n. 25 | void printHosoya(int n) 26 | { 27 | for (int i = 0; i < n; i++) { 28 | for (int j = 0; j <= i; j++) 29 | cout << Hosoya(i, j) << " "; 30 | 31 | cout << endl; 32 | } 33 | } 34 | 35 | 36 | int main() 37 | { 38 | int n = 5; 39 | printHosoya(n); 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /C++/Algorithms/Mathematical/Lucky_number_comment.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This function receives the value of n1 from the user, and outputs a "lucky number" 3 | if there is a duplicate number among the input numbers, and a "not lucky number" if there is no duplicate number. 4 | */ 5 | 6 | #include 7 | using namespace std; 8 | 9 | int main() { 10 | int n,n1,n2,d1,d2,ct=0,flag=0; 11 | cout<<"Enter a number: "; 12 | cin>>n1; 13 | n2=n1; 14 | n=n1; 15 | while(n1>0) 16 | { 17 | d1=n1%10; 18 | while(n2>0) 19 | { 20 | d2=n2%10; 21 | if(d1==d2) 22 | ct++; 23 | n2=n2/10; 24 | } 25 | if(ct>1) 26 | { 27 | flag=1; 28 | break; 29 | } 30 | ct=0; 31 | n2=n; 32 | n1=n1/10; 33 | } 34 | if(flag==1) // flag == 1 it means that the numbers do overlap 35 | cout< 2 | using namespace std; 3 | 4 | 5 | //These 2 functions will accept user input and return the resulting power of that user input 6 | 7 | 8 | //Iterative Function 9 | double powerIterative(double base, unsigned int n) { 10 | double power = 1.0; 11 | 12 | for (int i = 1; i <= n; i++) //For loop 13 | { 14 | power = power * base; 15 | } 16 | 17 | return (power); 18 | } 19 | 20 | 21 | //Recursive function 22 | double powerRecursive(double base, unsigned int n) { 23 | 24 | 25 | if (n != 0) 26 | return (base * powerRecursive(base, n - 1)); //Function calling itself 27 | else 28 | return 1; //base function 29 | 30 | } 31 | 32 | int main(void){ 33 | 34 | 35 | 36 | //Iterative Function 37 | 38 | cout << "Iterative Function" << endl; 39 | cout << "Please enter a number" << endl; 40 | double iF; 41 | cin >> iF; 42 | double answerIterative = powerIterative(2, iF); 43 | cout << answerIterative << endl; 44 | 45 | 46 | //Recursive Function 47 | cout << "Recursive Function" << endl; 48 | cout << "Please enter a number" << endl; 49 | double rF; 50 | cin >> rF; 51 | double answerRecursion = powerRecursive(2, rF); 52 | cout << answerRecursion << endl; 53 | 54 | 55 | } 56 | -------------------------------------------------------------------------------- /C++/Algorithms/Mathematical/Program for nth Catalan number.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // A recursive function to find nth catalan number 5 | unsigned long int catalan(unsigned int n) 6 | { 7 | // Base case 8 | if (n <= 1) return 1; 9 | 10 | // catalan(n) is sum of catalan(i)*catalan(n-i-1) 11 | unsigned long int res = 0; 12 | for (int i=0; i 3 | using namespace std; 4 | 5 | void SieveOfEratosthenes(int n) 6 | { 7 | // Create a boolean array "prime[0..n]" and initialize 8 | // all entries it as true. A value in prime[i] will 9 | // finally be false if i is Not a prime, else true. 10 | bool prime[n+1]; 11 | memset(prime, true, sizeof(prime)); 12 | 13 | for (int p=2; p*p<=n; p++) 14 | { 15 | // If prime[p] is not changed, then it is a prime 16 | if (prime[p] == true) 17 | { 18 | // Update all multiples of p greater than or 19 | // equal to the square of it 20 | // numbers which are multiple of p and are 21 | // less than p^2 are already been marked. 22 | for (int i=p*p; i<=n; i += p) 23 | prime[i] = false; 24 | } 25 | } 26 | 27 | // Print all prime numbers 28 | for (int p=2; p<=n; p++) 29 | if (prime[p]) 30 | cout << p << " "; 31 | } 32 | 33 | // Driver Program to test above function 34 | int main() 35 | { 36 | int n = 30; 37 | cout << "Following are the prime numbers smaller " 38 | << " than or equal to " << n << endl; 39 | SieveOfEratosthenes(n); 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /C++/Algorithms/Mathematical/Square_root.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include //for log10(), fabs(), pow() 3 | 4 | using namespace std; 5 | 6 | #define DBL_EPSILON 2.2204460492503131e-16 7 | 8 | //These 2 functions will accept user input and return the resulting Square Root of that user input 9 | 10 | //Iterative Function 11 | double sqrtIterative(double x) 12 | { 13 | double sqrt = x * pow(0.3, log10(x)); 14 | for (int i = 0; i < 5; i++) 15 | sqrt = (sqrt + (x / sqrt)) * 0.5; 16 | return sqrt; 17 | } 18 | 19 | //Recursive function 20 | double sqrtRecursive(double num, double prev) 21 | { 22 | double next = (prev + num / prev) / 2; 23 | if (fabs(next - prev) < DBL_EPSILON * next) 24 | return next; 25 | return sqrtRecursive(num, next); 26 | } 27 | 28 | int main(void) 29 | { 30 | 31 | //Iterative Function 32 | cout << "*************************Iterative Function*************************" << endl; 33 | cout << "Please enter a number : "; 34 | double it; 35 | cin >> it; 36 | double answerIterative = sqrtIterative(it); 37 | cout << "The Square Root is : " << answerIterative << endl 38 | << endl; 39 | 40 | //Recursive Function 41 | cout << "*************************Recursive Function*************************" << endl; 42 | cout << "Please enter a numbers : "; 43 | double rc; 44 | cin >> rc; 45 | double answerRecursion = sqrtRecursive(rc, 1); 46 | cout << "The Square Root is : " << answerRecursion << endl; 47 | } -------------------------------------------------------------------------------- /C++/Algorithms/Pattern-Searching/readme.md: -------------------------------------------------------------------------------- 1 | ### Pattern-Searching -------------------------------------------------------------------------------- /C++/Algorithms/Randomized-Algorithms/readme.md: -------------------------------------------------------------------------------- 1 | ### Randomized-Algorithms 2 | 3 | - [Flood Fill](FloodFill/Flood_Fill_Algorithm.cpp) 4 | 5 | As a coloring algorithm, when you use an app such as Paint, press the fill button and press a shape, and the color is colored inside the shape. Likewise in the case of minesweeper, when you click a non-mines part, all parts of the surrounding area without mines are pressed. This algorithm is called a flood-fill algorithm. 6 | 7 | Time complexity = O(N^2) (N reprsent length of the side of a square) -------------------------------------------------------------------------------- /C++/Algorithms/Resolution/24to8bit.CPP: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace cv; 3 | 4 | int main( int argc, char** argv ) 5 | { 6 | char* ImageFile = argv[1]; //image file 7 | Mat image; //mat object for storing data 8 | image = imread( ImageFile, IMREAD_COLOR ); //read the image file 9 | if( argc != 2 || !image.data ) 10 | { 11 | printf( " No image data \n " ); 12 | return -1; 13 | } 14 | Mat gray_image; 15 | cvtColor( image, gray_image, COLOR_BGR2GRAY ); //convert image from colour to grey 16 | imwrite( "/home/crmgogo/Pictures/greyImage.png", gray_image ); 17 | namedWindow( ImageFile, WINDOW_AUTOSIZE ); 18 | namedWindow( "Gray image", WINDOW_AUTOSIZE ); 19 | imshow( ImageFile, image ); //show window containing images 20 | imshow( "Gray image", gray_image ); 21 | waitKey(0); //to exit 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /C++/Algorithms/Searching-Algorithms/BinarySearch/BinarySearch.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to implement recursive Binary Search 2 | #include 3 | using namespace std; 4 | 5 | // A iterative binary search function. It returns 6 | // location of x in given array arr[l..r] if present, 7 | // otherwise -1 8 | int binarySearch(int arr[], int l, int r, int x) 9 | { 10 | while (l <= r) { 11 | int m = l + (r - l) / 2; 12 | 13 | // Check if x is present at mid 14 | if (arr[m] == x) 15 | return m; 16 | 17 | // If x greater, ignore left half 18 | if (arr[m] < x) 19 | l = m + 1; 20 | 21 | // If x is smaller, ignore right half 22 | else 23 | r = m - 1; 24 | } 25 | 26 | // if we reach here, then element was 27 | // not present 28 | return -1; 29 | } 30 | 31 | int main(void) 32 | { 33 | int arr[] = { 2, 3, 4, 10, 40 }; 34 | int x = 10; 35 | int n = sizeof(arr) / sizeof(arr[0]); 36 | int result = binarySearch(arr, 0, n - 1, x); 37 | (result == -1) ? cout << "Element is not present in array" 38 | : cout << "Element is present at index " << result; 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /C++/Algorithms/Searching-Algorithms/Find_kth_element.cpp: -------------------------------------------------------------------------------- 1 | /* Problem Statement 2 | Given an array arr of positive integers sorted in a strictly increasing order, and an integer k. 3 | Find the kth positive integer that is missing from this array 4 | Constraints: 5 | 1 <= arr.length <= 1000 6 | 1 <= arr[i] <= 1000 7 | 1 <= k <= 1000 8 | arr[i] < arr[j] for 1 <= i < j <= arr.length 9 | */ 10 | #include 11 | using namespace std; 12 | int findKthPositive(vector& arr, int k) 13 | { 14 | int b[10001]; 15 | int i; int ans = 0; 16 | for (i = 0; i <= 10000; i++) 17 | b[i] = i; //stores value i at every index i 18 | for (i = 0; i < arr.size(); i++) 19 | b[arr[i]] = -1; //stores -1 for elements already in the array 20 | 21 | for (i = 1; i <= 10000; i++) 22 | { 23 | if (b[i] != -1) //if it is not -1, then it is counted towards kth integer, so k-- 24 | k--; 25 | if (k == 0) // if k becomes 0, it means we have found kth positive integer 26 | { 27 | ans = i; //value is stored in ans 28 | break; 29 | } 30 | } 31 | return ans; 32 | } 33 | int main() 34 | { 35 | vector arr; 36 | int n, k, i; 37 | cin >> n >> k; 38 | for (i = 0; i < n; i++) //takes input from user 39 | { 40 | int a; 41 | cin >> a; 42 | arr.push_back(a); 43 | } 44 | cout << findKthPositive(arr, k); 45 | return 0; 46 | } -------------------------------------------------------------------------------- /C++/Algorithms/Searching-Algorithms/LinearSearch.cpp: -------------------------------------------------------------------------------- 1 | // C++ code to linearly search x in arr[]. If x 2 | // is present then return its location, otherwise 3 | // return -1 4 | 5 | #include 6 | using namespace std; 7 | 8 | int search(int arr[], int n, int x) 9 | { 10 | int i; 11 | for (i = 0; i < n; i++) 12 | if (arr[i] == x) 13 | return i; 14 | return -1; 15 | } 16 | 17 | int main(void) 18 | { 19 | int arr[] = { 2, 3, 4, 10, 40 }; 20 | int x = 10; 21 | int n = sizeof(arr) / sizeof(arr[0]); 22 | int result = search(arr, n, x); 23 | (result == -1)? cout<<"Element is not present in array" 24 | : cout<<"Element is present at index " < 2 | using namespace std; 3 | 4 | 5 | int ternarySearch(int l, int r, int key, int ar[]) 6 | 7 | { 8 | while (r >= l) { 9 | 10 | int mid1 = l + (r - l) / 3; 11 | int mid2 = r - (r - l) / 3; 12 | 13 | if (ar[mid1] == key) { 14 | return mid1; 15 | } 16 | if (ar[mid2] == key) { 17 | return mid2; 18 | } 19 | 20 | 21 | 22 | if (key < ar[mid1]) { 23 | 24 | 25 | r = mid1 - 1; 26 | } 27 | else if (key > ar[mid2]) { 28 | 29 | l = mid2 + 1; 30 | } 31 | else { 32 | 33 | l = mid1 + 1; 34 | r = mid2 - 1; 35 | } 36 | } 37 | 38 | return -1; 39 | } 40 | 41 | int main() 42 | { 43 | int l, r, p, key, n; 44 | cin >> n; 45 | int arr[n]; 46 | 47 | for (int i = 0; i < n; i++) { 48 | cin >> arr[i]; 49 | } 50 | l = 0; 51 | r = n - 1; 52 | 53 | cin >> key; 54 | 55 | p = ternarySearch(l, r, key, arr); 56 | 57 | cout << "Index of " << key << " is " << p << endl; 58 | 59 | return 0; 60 | } -------------------------------------------------------------------------------- /C++/Algorithms/Sorting-Algorithms/3-Way Quick Sort/inputf.in: -------------------------------------------------------------------------------- 1 | 7 2 | 10 90 49 2 1 5 23 -------------------------------------------------------------------------------- /C++/Algorithms/Sorting-Algorithms/3-Way Quick Sort/outputf.in: -------------------------------------------------------------------------------- 1 | Before Sorting: 10 90 49 2 1 5 23 2 | After Sorting: 1 2 5 10 23 49 90 3 | -------------------------------------------------------------------------------- /C++/Algorithms/Sorting-Algorithms/Bitonic Sort/inputf.in: -------------------------------------------------------------------------------- 1 | 8 2 | 3 7 4 8 6 2 1 5 -------------------------------------------------------------------------------- /C++/Algorithms/Sorting-Algorithms/Bitonic Sort/outputf.in: -------------------------------------------------------------------------------- 1 | 1 2 3 4 5 6 7 8 2 | -------------------------------------------------------------------------------- /C++/Algorithms/Sorting-Algorithms/BubbleSort/Bubble_Sort.cpp: -------------------------------------------------------------------------------- 1 | // Bubble Sort : Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order. 2 | 3 | #include 4 | using namespace std; 5 | 6 | // swap two elements 7 | void swap(int *x, int *y) 8 | { 9 | int temp = *x; 10 | *x = *y; 11 | *y = temp; 12 | } 13 | 14 | //Function to implement bubble sort 15 | void bubbleSort(int arr[], int n) 16 | { 17 | int i, j; 18 | for (i = 0; i < n-1; i++) 19 | 20 | // Last i elements are already in place 21 | for (j = 0; j < n-i-1; j++) 22 | 23 | // swap if arr[j] is greater than arr[j+1] 24 | if (arr[j] > arr[j+1]) 25 | { 26 | swap(&arr[j], &arr[j+1]); 27 | } 28 | 29 | } 30 | // DRIVER CODE 31 | int main() 32 | { 33 | int n; 34 | cout<<"Enter the size of the array"<>n; 37 | 38 | int arr[n]; 39 | cout<<"Input the array"<>arr[i]; 45 | } 46 | 47 | bubbleSort(arr, n); 48 | cout<<"Sorted array: \n"; 49 | 50 | // print the sorted array 51 | for(int i=0;i 12 | using namespace std; 13 | 14 | void insertionSort(int arr[], int n) 15 | { 16 | int i, key, j; 17 | for (i = 1; i < n; i++) // Cycle 18 | { 19 | key = arr[i]; 20 | j = i - 1; 21 | while (j >= 0 && arr[j] > key) // If arr[j]> arr[i], the value must be swapped, so the value is replaced. 22 | { 23 | arr[j + 1] = arr[j]; // swap 24 | j = j - 1; 25 | } 26 | arr[j + 1] = key; // swap 27 | } 28 | } 29 | 30 | void printArray(int arr[], int n) // print Array 31 | { 32 | int i; 33 | for (i = 0; i < n; i++) 34 | cout << arr[i] << " "; 35 | cout << endl; 36 | } 37 | 38 | int main() 39 | { 40 | int arr[] = { 5, 13, 11, 15, 16 }; 41 | int n = sizeof(arr) / sizeof(arr[0]); // n is arr's size 42 | 43 | insertionSort(arr, n); 44 | printArray(arr, n); 45 | 46 | return 0; 47 | } -------------------------------------------------------------------------------- /C++/Algorithms/Sorting-Algorithms/MergeSort/Merge_Sort.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Merge Sort 3 | The list is divided into lists until the length is 0 or 1, then the partial lists are recursively sorted using merge sort, merged again, and repeated until the initial list length is reached. 4 | Time Complexity(worst/averaage/Best) : (n*log(n)) 5 | Space Complexity: n 6 | Contributor : Ankit Surwade 7 | */ 8 | 9 | #include 10 | using namespace std; 11 | 12 | void merge(int arr[], int low, int mid, int high){ 13 | int i, j, k; 14 | int n1 = mid + 1 - low; 15 | int n2 = high - mid; 16 | int l[n1], r[n2]; 17 | for(int i=0; i>n; 45 | int arr[n]; 46 | //enter elemetns 47 | for(int i=0;i>arr[i]; 48 | //called Function 49 | mergeSort(arr,0,n-1); 50 | //after Sort array 51 | for(int i=0;i 6 | using namespace std; 7 | 8 | /* Sorts the array using pigeonhole algorithm */ 9 | void pigeonholeSort(int arr[], int n) 10 | { 11 | // Find minimum and maximum values in arr[] 12 | int min = arr[0], max = arr[0]; 13 | for (int i = 1; i < n; i++) 14 | { 15 | if (arr[i] < min) 16 | min = arr[i]; 17 | if (arr[i] > max) 18 | max = arr[i]; 19 | } 20 | int range = max - min + 1; // Find range 21 | 22 | // Create an array of vectors. Size of array 23 | // range. Each vector represents a hole that 24 | // is going to contain matching elements. 25 | vector holes[range]; 26 | 27 | // Traverse through input array and put every 28 | // element in its respective hole 29 | for (int i = 0; i < n; i++) 30 | holes[arr[i]-min].push_back(arr[i]); 31 | 32 | // Traverse through all holes one by one. For 33 | // every hole, take its elements and put in 34 | // array. 35 | int index = 0; // index in sorted array 36 | for (int i = 0; i < range; i++) 37 | { 38 | vector::iterator it; 39 | for (it = holes[i].begin(); it != holes[i].end(); ++it) 40 | arr[index++] = *it; 41 | } 42 | } 43 | 44 | // main program to test the above function 45 | int main() 46 | { 47 | int arr[] = {8, 3, 2, 7, 4, 6, 8}; 48 | int n = sizeof(arr)/sizeof(arr[0]); 49 | 50 | pigeonholeSort(arr, n); 51 | 52 | printf("Sorted order is : "); 53 | for (int i = 0; i < n; i++) 54 | printf("%d ", arr[i]); 55 | 56 | return 0; 57 | } 58 | -------------------------------------------------------------------------------- /C++/Algorithms/Sorting-Algorithms/SelectionSort/selection_sort.cpp: -------------------------------------------------------------------------------- 1 | 2 | //Time Complexity: O(n2) as there are two nested loops. 3 | 4 | //Auxiliary Space: O(1) 5 | //The good thing about selection sort is it never makes more than O(n) swaps and can be useful when memory write is a costly operation. 6 | 7 | 8 | #include 9 | using namespace std; 10 | int main() 11 | { 12 | long long int n,i,j,pos,t; 13 | cin>>n; // array's size 14 | long long int a[n]; 15 | for(i=0;i>a[i]; // write input 16 | for(i=0;i 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | //bin sort 8 | void bin(vector arr){ 9 | 10 | auto p=max_element(arr.begin(),arr.end()); //p is max element used for creating the array(or bin) to store the elements at same index as value 11 | vector> a(*p+1,vector()); //2d vector of size max element + 1 12 | 13 | for(int i:arr){ //pushing our value's of arr to 2d vector (index == value) 14 | a[i].push_back(i); 15 | } 16 | 17 | arr.clear(); //clearing arr before pushing values into it 18 | for(auto i:a){ 19 | for(int j=0;j>size; 34 | vector arr (size); 35 | cout<<"enter the array"; 36 | for(auto &a:arr) 37 | { 38 | int value; 39 | cin>>value; 40 | a=value; 41 | } 42 | bin(arr); 43 | 44 | 45 | 46 | } 47 | -------------------------------------------------------------------------------- /C++/Algorithms/Two-Pointer-Algorithms/3Sum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of n integers, are there elements a, b, c in nums such that a + b + c = 0? 3 | Find all unique triplets in the array which gives the sum of zero. 4 | Notice that the solution set must not contain duplicate triplets. 5 | */ 6 | 7 | /* Sample inputs and outputs 8 | Input: arr = [-1,0,1,2,-1,-4] 9 | Output: [-1,-1,2] [-1,0,1] 10 | 11 | Input: arr= [0] 12 | Output: [] 13 | */ 14 | 15 | #include 16 | #include 17 | using namespace std; 18 | 19 | 20 | //Function to check if triplet with sum = 0 exists 21 | void threeSum(int arr[],int n) { 22 | 23 | sort(arr,arr + n); 24 | for(int i = 0; i < n; i++) 25 | { 26 | if(i != 0 && arr[i] == arr[i-1])continue; 27 | int j = i+1, k = n-1; 28 | while(j < k) 29 | { 30 | int sum = arr[i] + arr[j] + arr[k]; 31 | if(sum == 0) 32 | { 33 | cout<<"[ "< 0) k--; 39 | else j++; 40 | } 41 | } 42 | 43 | } 44 | 45 | //Driver code to test the threeSum function 46 | int main(){ 47 | 48 | int arr[]={ -1, 0, 1, 2, -1, -4 }; 49 | int n = 6; 50 | 51 | threeSum(arr,n); 52 | 53 | return 0; 54 | } -------------------------------------------------------------------------------- /C++/Algorithms/Two-Pointer-Algorithms/Floyd's-Cycle-Finding-Algorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Node { 4 | public: 5 | int data; 6 | Node *next; 7 | }; 8 | // each data is inserted in the front of linkedlist 9 | Node* push(Node *head, int data) { 10 | Node *new_node = new Node(); 11 | new_node->data = data; 12 | new_node->next = head; 13 | head = new_node; 14 | } 15 | void detectLoop(Node *head) { 16 | Node *slow_ptr = head, *fast_ptr = head; 17 | while(slow_ptr && fast_ptr && fast_ptr->next) { 18 | slow_ptr = slow_ptr->next; // moves one step at a time 19 | fast_ptr = fast_ptr->next->next; // moves two steps at a time 20 | if(slow_ptr == fast_ptr) { // when both the pointers intersect each other 21 | cout << "Loop Detected" << endl; 22 | return; 23 | } 24 | } 25 | cout << "No Loop Detected" << endl; 26 | return; 27 | } 28 | int main() { 29 | // initially list is empty 30 | Node *head = NULL; // head -> NULL 31 | head = push(head, 1); // head -> 1 -> NULL 32 | head = push(head, 2); // head -> 2 -> 1 -> NULL 33 | head = push(head, 3); // head -> 3 -> 2 -> 1 -> NULL 34 | head = push(head, 4); // head -> 4 -> 3 -> 2 -> 1 -> NULL 35 | head = push(head, 5); // head -> 5 -> 4 -> 3 -> 2 -> 1 -> NULL 36 | // to create a loop 37 | head->next->next->next->next->next = head; // head -> 5 -> 4 -> 3 -> 2 -> 1 -> head 38 | detectLoop(head); 39 | return 0; 40 | } -------------------------------------------------------------------------------- /C++/Algorithms/Two-Pointer-Algorithms/readme.md: -------------------------------------------------------------------------------- 1 | ### Two-Pointer-Algorithms 2 | - [3 Sum](3Sum.cpp) 3 | 4 | Problem of taking an array of n integers and returning a subset where the sum of three elements is 0. 5 | 6 | Time complexity = O(n^3) 7 | 8 | - [Floyd's Cycle Finding Algorithms](Floyd's-Cycle-Finding-Algorithms.cpp) 9 | 10 | It is a simple algorithm that if two pointers of different speeds enter the loop and proceed, in the case of a cycle, they eventually point to the same node. Slowptr advances one space at a time and fastptr advances two spaces at a time. This means that if it is not recursive, it eventually encounters the null and terminates the program. If it is cyclic, it means that slowptr and fastptr meet, and it becomes a loop. If the loop is found by the Floyd loop finding algorithm, when the node where slowptr and fastptr meet in the loop starts again from the head, the distance from the node where the loop starts is the same. 11 | 12 | Time complexity = O(n) -------------------------------------------------------------------------------- /C++/Data-Structures/Array/Move-neg-to-left.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void printArray(int array[], int size) { 4 | for (int i = 0; i < size; ++i) { 5 | cout << array[i] << " "; 6 | } 7 | cout << endl; 8 | } 9 | void shiftArray(int array[], int size) { 10 | int left = 0, right = size-1; 11 | while(left <= right) { 12 | if(array[left] < 0 && array[right] < 0) { 13 | left++; 14 | } 15 | else if(array[left] < 0 && array[right] > 0) { 16 | right--; 17 | } 18 | else if(array[left] > 0 && array[right] < 0) { 19 | swap(array[left], array[right]); 20 | right--; 21 | left++; 22 | } 23 | else { 24 | right--; 25 | } 26 | } 27 | } 28 | int main() { 29 | int size; 30 | cout << "Enter the size of array:\n"; 31 | cin >> size; 32 | int array[size]; 33 | cout << "Enter the elements of the array:\n"; 34 | for(int i = 0; i < size; ++i) { 35 | cin >> array[i]; 36 | } 37 | cout << "Original Array:\t"; 38 | printArray(array, size); 39 | cout << "After moving all negative elements to left:\t"; 40 | shiftArray(array, size); 41 | printArray(array, size); 42 | return 0; 43 | } 44 | 45 | -------------------------------------------------------------------------------- /C++/Data-Structures/Array/Move-neg-to-left_comment.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void printArray(int array[], int size) { 4 | for (int i = 0; i < size; ++i) { 5 | cout << array[i] << " "; //print array 6 | } 7 | cout << endl; 8 | } 9 | void shiftArray(int array[], int size) { 10 | int left = 0, right = size-1; 11 | while(left <= right) { //sorting 12 | if(array[left] < 0 && array[right] < 0) { 13 | left++; 14 | } 15 | else if(array[left] < 0 && array[right] > 0) { 16 | right--; 17 | } 18 | else if(array[left] > 0 && array[right] < 0) { 19 | swap(array[left], array[right]); 20 | right--; 21 | left++; 22 | } 23 | else { 24 | right--; 25 | } 26 | } 27 | } 28 | int main() { 29 | int size; 30 | cout << "Enter the size of array:\n"; 31 | cin >> size; //input size 32 | int array[size]; 33 | cout << "Enter the elements of the array:\n"; 34 | for(int i = 0; i < size; ++i) { 35 | cin >> array[i]; //input value 36 | } 37 | cout << "Original Array:\t"; 38 | printArray(array, size); //print original array 39 | cout << "After moving all negative elements to left:\t"; 40 | shiftArray(array, size); //Run sorting function 41 | printArray(array, size); //print shift array 42 | return 0; 43 | } 44 | 45 | 46 | -------------------------------------------------------------------------------- /C++/Data-Structures/Array/PositiveAtEvenNegativeAtOdd.c++: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | #define MAXSIZE 100 5 | 6 | int main() { 7 | ll arr[MAXSIZE],i=0; 8 | while(cin>>arr[i]){ 9 | i++; 10 | } 11 | ll n = i; 12 | 13 | ll pos[n],neg[n]; 14 | ll i,pi=0,pn=0,xp=0,xn=0; 15 | for(i=0;i= 0){ 17 | pos[pi] = arr[i]; 18 | pi++; 19 | } 20 | else{ 21 | neg[pn] = arr[i]; 22 | pn++; 23 | } 24 | } 25 | for(i=0;i=pi){ 35 | arr[i] = neg[xn++]; 36 | } 37 | else if(xn>=pn){ 38 | arr[i] = pos[xp++]; 39 | } 40 | } 41 | 42 | for(i=0;i 2 | using namespace std; 3 | #define ll long long int 4 | #define MAXSIZE 100 5 | 6 | int main() { 7 | ll arr[MAXSIZE] = {NULL, } ,i=0; 8 | while(cin>>arr[i]){ 9 | i++; //input value (if value is ^z[ctrl + z] break while) 10 | } 11 | ll n = i; 12 | 13 | ll pos[MAXSIZE],neg[MAXSIZE]; 14 | ll pi=0,pn=0,xp=0,xn=0; 15 | for(i=0;i= 0){ 17 | pos[pi] = arr[i]; //positive number = pos[] 18 | pi++; 19 | } 20 | else{ 21 | neg[pn] = arr[i]; //negative number = neg[] 22 | pn++; 23 | } 24 | } 25 | for(i=0;i=pi){ //else if xp >= pi 35 | arr[i] = neg[xn++]; 36 | } 37 | else if(xn>=pn){ 38 | arr[i] = pos[xp++]; //else if xn >= pn 39 | } 40 | } 41 | 42 | for(i=0;i 2 | using namespace std; 3 | void rotate(int array[], int size) { 4 | // when the array contains only one element 5 | if(size == 1) { 6 | return; 7 | } 8 | int i = size - 1; 9 | // swaps the last element repeatidly 10 | while(i > 0) { 11 | swap(array[i], array[i-1]); 12 | i--; 13 | } 14 | } 15 | void printArray(int array[], int size) { 16 | for(int i = 0; i < size; ++i) { 17 | cout << array[i] << " "; 18 | } 19 | cout << endl; 20 | } 21 | int main() 22 | { 23 | int size; 24 | cout << "Enter the size of array:\n"; 25 | cin >> size; 26 | int array[size]; 27 | cout << "Enter the elements of the array:\n"; 28 | for(int i = 0; i < size; ++i) { 29 | cin >> array[i]; 30 | } 31 | cout << "Original Array:\t"; 32 | printArray(array, size); 33 | cout << "After Rotating:\t"; 34 | rotate(array, size); 35 | printArray(array, size); 36 | return 0; 37 | } -------------------------------------------------------------------------------- /C++/Data-Structures/Array/move_all_zeroes.cpp: -------------------------------------------------------------------------------- 1 | /** Move all zeroes to end of array **/ 2 | 3 | 4 | #include 5 | using namespace std; 6 | 7 | void pushZerosToEnd(int arr[], int n) 8 | { 9 | int count = 0; 10 | for (int i = 0; i < n; i++) 11 | if (arr[i] != 0) 12 | arr[count++] = arr[i]; 13 | 14 | while (count < n) 15 | arr[count++] = 0; 16 | } 17 | 18 | int main() 19 | { 20 | 21 | int arr[10000],n; 22 | cin>>n; 23 | for(int i=0;i>arr[i]; 26 | } 27 | 28 | pushZerosToEnd(arr, n); 29 | cout << "Array after pushing all zeros to end of array :\n"; 30 | for (int i = 0; i < n; i++) 31 | cout << arr[i] << " "; 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /C++/Data-Structures/Array/move_all_zeroes_comment.cpp: -------------------------------------------------------------------------------- 1 | /** Move all zeroes to end of array **/ 2 | #include 3 | using namespace std; 4 | 5 | void pushZerosToEnd(int arr[], int n) 6 | { 7 | int count = 0; 8 | for (int i = 0; i < n; i++) 9 | if (arr[i] != 0) 10 | arr[count++] = arr[i]; //copy the value of arr 11 | 12 | while (count < n) 13 | arr[count++] = 0; //input zero 14 | } 15 | 16 | int main() 17 | { 18 | 19 | int arr[10000],n; 20 | cin>>n; //length of string 21 | for(int i=0;i>arr[i]; // input string 24 | } 25 | 26 | pushZerosToEnd(arr, n); 27 | cout << "Array after pushing all zeros to end of array :\n"; 28 | for (int i = 0; i < n; i++) 29 | cout << arr[i] << " "; //Outputs zero as long as the string. 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /C++/Data-Structures/BST/BST_implementation: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/div-bargali/Data-Structures-and-Algorithms/7bc4af2022098e850078ef1c556fbadd51583ddc/C++/Data-Structures/BST/BST_implementation -------------------------------------------------------------------------------- /C++/Data-Structures/BST/readme.md: -------------------------------------------------------------------------------- 1 | ### BST 2 | - [BST Implementation](BST_implementation.cpp) 3 | 4 | The BST implementation algorithm is to create the BST structure. Repeat inserting data smaller than the parent node on the left, relative to the parent node, larger than the parent node on the right. 5 | 6 | Time complexity = O(h) 7 | 8 | - [Check BST](check_bst.cpp) 9 | 10 | The BST check algorithm verifies that BST is normally generated. Output False if root is null and True if not null. 11 | 12 | Time complexity = O(n) 13 | 14 | - [Constructing BST from Level Order Traversal](Constructing%20BST%20from%20Level%20Order%20Traversal.cpp) 15 | 16 | The Constructing BST from Level Order Traversal algorithm explores BST with the Level Order Traversal method. The methods of navigation include pre-order, inorder, postorder, and level order. 17 | 18 | Time complexity = O(n^2) 19 | 20 | - [Deletion From A BST](Deletion%20From%20A%20BST.cpp) 21 | 22 | The Delete From A BST algorithm deletes a specific node that exists in BST. The number of cases in which a node is deleted is divided into the absence of a child, the existence of only the left child, the existence of only the right child, or both. 23 | 24 | Time complexity = O(n) 25 | 26 | - [Pair Sum In BST](pair_sum_in_bst.cpp) 27 | 28 | The pair_sum_in_bst algorithm adds the sum of both in search of when both child nodes exist. 29 | 30 | Time complexity = O(n) -------------------------------------------------------------------------------- /C++/Data-Structures/Disjoint Set/readme.md: -------------------------------------------------------------------------------- 1 | ### Disjoint Set 2 | 3 | Dispoint sets are data structures that store and manipulate information about elements divided into non-redundant subsets. 4 | Bit vectors, arrays, connection lists, trees, etc. can be used to implement a set, but they are implemented using the most efficient tree structure of them. 5 | Operation of the Dispoint Set 6 | make-set(x): Initialization operation, creating a new roll-unset with x as the only element. 7 | find(x): Returns the representative value (root node) of the set to which x belongs. That is, an operation to find out which set x belongs to. 8 | union(x, y): Add the set to which x belongs and the set to which y belongs. 9 | 10 | - [Disjoint SEt Ranked by Size of Set](Disjoint_set_ranked_by_size_of_set.cpp) 11 | 12 | Time complexity = O(n) 13 | 14 | - [Implementation of Disjoint Set](Implementation%20of%20disjoint%20set.cpp) 15 | 16 | Time complexity = O(n) -------------------------------------------------------------------------------- /C++/Data-Structures/Graph/BFS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #pragma GCC optimize("Ofast") 5 | #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,fma") 6 | #pragma GCC optimize("unroll-loops") 7 | const unsigned int M = 1000000007; 8 | using namespace std; 9 | // Check 10 | using namespace __gnu_pbds; 11 | typedef tree,rb_tree_tag,tree_order_statistics_node_update> T_set; // PBDS_set 12 | typedef tree,rb_tree_tag,tree_order_statistics_node_update> T_multiset; // PBDS_multiset 13 | 14 | void solve() 15 | { 16 | int n ,m,u,v; 17 | cin>>n>>m; 18 | vector> adj(n+1); 19 | vector vis(n+1,false); 20 | for(int i = 0; i < n ; i++ ){ 21 | cin>>u>>v; 22 | adj[u].push_back(v); 23 | adj[v].push_back(u); 24 | } 25 | queue temp; 26 | temp.push(1); 27 | vis[1] = true; 28 | while(!temp.empty()){ 29 | int curr = temp.front(); 30 | cout< 3 | using namespace std; 4 | #define N 100000 5 | 6 | vector gr1[N], gr2[N]; 7 | 8 | bool vis1[N], vis2[N]; 9 | 10 | // Function to add edges 11 | void Add_edge(int u, int v) 12 | { 13 | gr1[u].push_back(v); 14 | gr2[v].push_back(u); 15 | } 16 | 17 | // DFS function 18 | void dfs1(int x) 19 | { 20 | vis1[x] = true; 21 | 22 | for (auto i : gr1[x]) 23 | if (!vis1[i]) 24 | dfs1(i); 25 | } 26 | 27 | // DFS function 28 | void dfs2(int x) 29 | { 30 | vis2[x] = true; 31 | 32 | for (auto i : gr2[x]) 33 | if (!vis2[i]) 34 | dfs2(i); 35 | } 36 | 37 | bool Is_Connected(int n) 38 | { 39 | // Call for correct direction 40 | memset(vis1, false, sizeof vis1); 41 | dfs1(1); 42 | 43 | // Call for reverse direction 44 | memset(vis2, false, sizeof vis2); 45 | dfs2(1); 46 | 47 | for (int i = 1; i <= n; i++) { 48 | 49 | // If any vertex it not visited in any direction 50 | // Then graph is not connected 51 | if (!vis1[i] and !vis2[i]) 52 | return false; 53 | } 54 | 55 | // If graph is connected 56 | return true; 57 | } 58 | 59 | 60 | int main() 61 | { 62 | int n = 4; 63 | 64 | // Add edges 65 | Add_edge(1, 2); 66 | Add_edge(1, 3); 67 | Add_edge(2, 3); 68 | Add_edge(3, 4); 69 | 70 | // Function call 71 | if (Is_Connected(n)) 72 | cout << "Yes"; 73 | else 74 | cout << "No"; 75 | 76 | return 0; 77 | } 78 | -------------------------------------------------------------------------------- /C++/Data-Structures/Hashing/readme.md: -------------------------------------------------------------------------------- 1 | ### Hashing 2 | - [Trivial Hashing](trivial_hashing.cpp) 3 | 4 | trivial_hashing accesses an item by calculating the address of the table in which the item is stored by applying an arithmetic operation directly to the key value. 5 | 6 | Time complexity = O(n) -------------------------------------------------------------------------------- /C++/Data-Structures/Hashing/trivial_hashing.cpp: -------------------------------------------------------------------------------- 1 | // CPP program to implement trivial hashing 2 | 3 | #include 4 | using namespace std; 5 | #define MAX 1000 6 | 7 | bool has[MAX + 1][2]; 8 | 9 | bool search(int X) 10 | { 11 | if (X >= 0) { 12 | if (has[X][0] == 1) 13 | return true; 14 | else 15 | return false; 16 | } 17 | 18 | // if X is negative take the absolute 19 | // value of X. 20 | X = abs(X); 21 | if (has[X][1] == 1) 22 | return true; 23 | 24 | return false; 25 | } 26 | 27 | void insert(int a[], int n) 28 | { 29 | for (int i = 0; i < n; i++) { 30 | if (a[i] >= 0) 31 | has[a[i]][0] = 1; 32 | else 33 | has[abs(a[i])][1] = 1; 34 | } 35 | } 36 | 37 | // Driver code 38 | int main() 39 | { 40 | int a[100],n ; 41 | cin>>n; 42 | for(int i=0;i>a[i]; 45 | } 46 | insert(a, n); 47 | int X;//variable to search 48 | cin>>X; 49 | 50 | if (search(X) == true) 51 | cout << "Present"; 52 | else 53 | cout << "Not Present"; 54 | return 0; 55 | } 56 | 57 | -------------------------------------------------------------------------------- /C++/Data-Structures/Heap/Heap (Kth Largest Element in a Stream ) C++/Readme.md: -------------------------------------------------------------------------------- 1 | A Simple Solution is to keep an array of size k. The idea is to keep the array sorted so that the k’th largest element can be found in O(1) time (we just need to return first element of array if array is sorted in increasing order) 2 | How to process a new element of stream? 3 | For every new element in stream, check if the new element is smaller than current k’th largest element. If yes, then ignore it. If no, then remove the smallest element from array and insert new element in sorted order. Time complexity of processing a new element is O(k). 4 | 5 | A Better Solution is to use a Self Balancing Binary Search Tree of size k. The k’th largest element can be found in O(Logk) time. 6 | How to process a new element of stream? 7 | For every new element in stream, check if the new element is smaller than current k’th largest element. If yes, then ignore it. If no, then remove the smallest element from the tree and insert new element. Time complexity of processing a new element is O(Logk). 8 | 9 | An Efficient Solution is to use Min Heap of size k to store k largest elements of stream. The k’th largest element is always at root and can be found in O(1) time. 10 | How to process a new element of stream? 11 | Compare the new element with root of heap. If new element is smaller, then ignore it. Otherwise replace root with new element and call heapify for the root of modified heap. Time complexity of finding the k’th largest element is O(Logk). 12 | -------------------------------------------------------------------------------- /C++/Data-Structures/PriorityQueue/PriorityQueue.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Title: Priority Queue in c++ 3 | Priority Queue is an extension of queue. 4 | It is designed such that all elements in the queue are in non increasing order. 5 | While dequeue, an element with high priority is dequeued before an element with low priority. 6 | Function used: priorityQueue.top(), priorityQueue.push(), priorityQueue.empty(), priorityQueue.pop(), priorityQueue.size() 7 | Author: Sharmila 8 | */ 9 | 10 | #include 11 | #include 12 | 13 | using namespace std; 14 | 15 | void showPriQueue(priority_queue pri_queue) { 16 | while (!pri_queue.empty()){ 17 | cout << pri_queue.top()<<" "; 18 | pri_queue.pop(); 19 | } 20 | } 21 | 22 | int main (){ 23 | priority_queue myqueue; 24 | int number_values; 25 | 26 | cout << "Enter the total number of element: "; 27 | cin >> number_values; 28 | 29 | for (int index = 0; index < number_values; index++) { 30 | myqueue.push(index); 31 | } 32 | 33 | cout << "Values in myqueue : "; 34 | showPriQueue(myqueue); 35 | cout << "\nSize of myqueue : " << myqueue.size() << endl; 36 | cout << "First element of the myqueue : " << myqueue.top() << endl; 37 | cout << "Pop element from myqueue "; 38 | myqueue.pop(); 39 | cout << "\nValues in myqueue after pop : "; 40 | showPriQueue(myqueue); 41 | 42 | return 0; 43 | } -------------------------------------------------------------------------------- /C++/Data-Structures/PriorityQueue/readme.md: -------------------------------------------------------------------------------- 1 | ### PriorityQueue 2 | - [Priority Queue](PriorityQueue.cpp) 3 | 4 | PriorityQueue, which is an extension of queue with following properties. First, every item has a priority associated with it. Next, an element with high priority is dequeued before an element with low priority. Finally, if two elements have the same priority, they are served according to their order in the queue. 5 | 6 | Time complexity => O(nlog n) -------------------------------------------------------------------------------- /C++/Data-Structures/Queue/Queue using stacks.cpp: -------------------------------------------------------------------------------- 1 | // CPP program to implement Queue using 2 | // two stacks with costly enQueue() 3 | // output 1 4 | // 2 5 | // 3 6 | #include 7 | using namespace std; 8 | 9 | struct Queue { 10 | stack s1, s2; 11 | 12 | void enQueue(int x) 13 | { 14 | // Move all elements from s1 to s2 15 | while (!s1.empty()) { 16 | s2.push(s1.top()); 17 | s1.pop(); 18 | } 19 | 20 | // Push item into s1 21 | s1.push(x); 22 | 23 | // Push everything back to s1 24 | while (!s2.empty()) { 25 | s1.push(s2.top()); 26 | s2.pop(); 27 | } 28 | } 29 | 30 | // Dequeue an item from the queue 31 | int deQueue() 32 | { 33 | // if first stack is empty 34 | if (s1.empty()) { 35 | cout << "Q is Empty"; 36 | exit(0); 37 | } 38 | 39 | // Return top of s1 40 | int x = s1.top(); 41 | s1.pop(); 42 | return x; 43 | } 44 | }; 45 | 46 | // Driver code 47 | int main() 48 | { 49 | Queue q; 50 | q.enQueue(1); 51 | q.enQueue(2); 52 | q.enQueue(3); 53 | 54 | cout << q.deQueue() << '\n'; 55 | cout << q.deQueue() << '\n'; 56 | cout << q.deQueue() << '\n'; 57 | 58 | return 0; 59 | } 60 | -------------------------------------------------------------------------------- /C++/Data-Structures/Queue/Queue.cpp: -------------------------------------------------------------------------------- 1 | // stl library for cp 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | //function for queue 8 | void showq(queue gq) 9 | { 10 | queue g = gq; 11 | while (!g.empty()) 12 | { 13 | cout << '\t' << g.front(); 14 | g.pop(); 15 | } 16 | cout << '\n'; 17 | } 18 | 19 | //main 20 | int main() 21 | { 22 | queue q; 23 | q.push(10); 24 | q.push(20); 25 | q.push(30); 26 | 27 | cout << "The queue q is : "; 28 | showq(q); 29 | 30 | cout << "\nq.size() : " << q.size(); 31 | cout << "\nq.front() : " << q.front(); 32 | cout << "\nq.back() : " << q.back(); 33 | 34 | cout << "\nq.pop() : "; 35 | q.pop(); 36 | showq(q); 37 | 38 | return 0; 39 | } 40 | 41 | 42 | /* 43 | Output: 44 | 45 | The queue q is : 10 20 30 46 | 47 | q.size() : 3 48 | q.front() : 10 49 | q.back() : 30 50 | q.pop() : 20 30 51 | */ 52 | -------------------------------------------------------------------------------- /C++/Data-Structures/Stack/Reverse_Words_of_String_using_Stack.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | //function to reverse the words 6 | //of the given string without using strtok(). 7 | void reverse(string s) 8 | { 9 | //create an empty string stack 10 | stack stc; 11 | 12 | //create an empty temporary string 13 | string temp=""; 14 | 15 | //traversing the entire string 16 | for(int i=0;i 2 | using namespace std; 3 | 4 | // C++ recursive function to solve tower of hanoi puzzle 5 | void TOH(int n,char Sour, char Aux,char Des) 6 | { 7 | if(n==1) 8 | { 9 | cout<<"Move Disk "<>n; 25 | //calling the TOH 26 | TOH(n,'A','B','C');//A,B,C are no of rods 27 | 28 | return 0; 29 | } -------------------------------------------------------------------------------- /C++/Data-Structures/Stack/balanced_brackets.cpp: -------------------------------------------------------------------------------- 1 | //Check if the brackets are balanced using using stack. 2 | // Testcase: 3 | // Input 1: ([{}]) 4 | // Output: true 5 | 6 | // Input 2: (){[]) 7 | // Output: false 8 | 9 | #include 10 | #include 11 | #include 12 | using namespace std; 13 | 14 | bool isBalanced(string exp) { 15 | // Write your code here 16 | 17 | stack s; 18 | 19 | int i=0; 20 | while(exp[i]!='\0'){ 21 | 22 | if(exp[i]=='(' || exp[i]=='{' || exp[i]=='[') 23 | s.push(exp[i]); 24 | 25 | else if(exp[i]==')'){ 26 | if(s.size()==0 || s.top()!='(') 27 | return false; 28 | s.pop(); 29 | } 30 | 31 | else if(exp[i]==']'){ 32 | if(s.size()==0 || s.top()!='[') 33 | return false; 34 | s.pop(); 35 | } 36 | 37 | else if(exp[i]=='}'){ 38 | if(s.size()==0 || s.top()!='{') 39 | return false; 40 | s.pop(); 41 | } 42 | 43 | i++; 44 | } 45 | 46 | return true; 47 | 48 | } 49 | 50 | int main() 51 | { 52 | string input; 53 | cin >> input; 54 | cout << ((isBalanced(input)) ? "true" : "false"); 55 | } 56 | -------------------------------------------------------------------------------- /C++/Data-Structures/Stack/infix_to_postfix_notation.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/div-bargali/Data-Structures-and-Algorithms/7bc4af2022098e850078ef1c556fbadd51583ddc/C++/Data-Structures/Stack/infix_to_postfix_notation.cpp -------------------------------------------------------------------------------- /C++/Data-Structures/Stack/sort_stack_using_temp_stack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | stack sort_stack(stack &input) 5 | { 6 | stack tmpStack; 7 | 8 | while (!input.empty()) 9 | { 10 | // pop out the first element 11 | int tmp = input.top(); 12 | input.pop(); 13 | 14 | // while temporary stack is not empty and top 15 | // of stack is greater than temp 16 | while (!tmpStack.empty() && tmpStack.top() > tmp) 17 | { 18 | // pop from temporary stack and push 19 | // it to the input stack 20 | input.push(tmpStack.top()); 21 | tmpStack.pop(); 22 | } 23 | 24 | // push temp in tempory of stack 25 | tmpStack.push(tmp); 26 | } 27 | 28 | return tmpStack; 29 | } 30 | 31 | // main function 32 | int main() 33 | { 34 | int n,t; 35 | cin>>n; 36 | stack input; 37 | for(i=0;i>t; 40 | input.push(t); 41 | } 42 | 43 | stack tmpStack = sort_stack(input); 44 | 45 | while (!tmpStack.empty()) 46 | { 47 | cout << tmpStack.top()<< " "; 48 | tmpStack.pop(); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /C++/Data-Structures/Stack/stack_using_LinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | template 5 | class Node { 6 | public: 7 | T data; 8 | Node *next; 9 | Node(T data) { 10 | this->data = data; 11 | next = NULL; 12 | 13 | } 14 | }; 15 | template 16 | class StackUsingLL { 17 | Node* head; 18 | int size; 19 | public: 20 | StackUsingLL() { 21 | head = NULL; 22 | size = 0; 23 | } 24 | 25 | int getsize() { 26 | return size; 27 | } 28 | bool isEmpty() { 29 | return size == 0; 30 | } 31 | void push(T n) { 32 | Node *newNode = new Node(n); 33 | newNode->next = head; 34 | head = newNode; 35 | size++; 36 | } 37 | T pop() { 38 | if (isEmpty()) { 39 | return 0; 40 | } 41 | T ans = head->data; 42 | Node *temp = head; 43 | head = head->next; 44 | delete temp; 45 | size--; 46 | return ans; 47 | } 48 | T top() { 49 | if (isEmpty()) { 50 | return 0; 51 | } 52 | return head->data; 53 | } 54 | 55 | 56 | }; 57 | 58 | int main() { 59 | #ifndef ONLINE_JUDGE 60 | freopen("input.txt", "r", stdin); 61 | freopen("output.txt", "w", stdout); 62 | #endif 63 | 64 | StackUsingLL s; 65 | s.push(101); 66 | s.push(102); 67 | s.push(103); 68 | s.push(104); 69 | s.push(105); 70 | 71 | 72 | cout << s.getsize() << endl; 73 | cout << s.top() << endl; 74 | cout << s.pop() << endl; 75 | cout << s.pop() << endl; 76 | cout << s.pop() << endl; 77 | cout << s.pop() << endl; 78 | cout << s.pop() << endl; 79 | return 0; 80 | } -------------------------------------------------------------------------------- /C++/Data-Structures/Stack/stack_using_two_queues.cpp: -------------------------------------------------------------------------------- 1 | // Implement Stack operations pop(),push() using two queues 2 | #include 3 | using namespace std; 4 | class Stack 5 | { 6 | queue q1, q2; 7 | 8 | public: 9 | // push function to get element into stack 10 | void push(int x) 11 | { 12 | // Push item into q1 13 | q1.push(x); 14 | } 15 | 16 | // pop the top element from the stack and return it 17 | int pop() 18 | { 19 | // if q1 is empty 20 | if (q1.empty()) { 21 | cout << "Stack is empty"; 22 | return 0; 23 | } 24 | 25 | // Move all elements except last from q1 to q2 26 | int f; 27 | while (!q1.empty()) 28 | { 29 | if (q1.size() == 1) 30 | f= q1.front(); 31 | else 32 | q2.push(q1.front()); 33 | 34 | q1.pop(); 35 | } 36 | 37 | //last element (i.e when q1 size==1 )is the element that will be returned after moving all elements except last to q1 38 | // Below loop can be replaced with a call to swap(q1, q2) 39 | while (!q2.empty()) { 40 | q1.push(q2.front()); 41 | q2.pop(); 42 | } 43 | 44 | return f; 45 | } 46 | }; 47 | 48 | int main() 49 | { 50 | int a[]= { 1, 2, 3, 4}; 51 | int n=sizeof(a)/sizeof(a[0]); 52 | 53 | // insert above elements into the stack 54 | Stack s; 55 | for (int i=0;i 2 | using namespace std; 3 | //Data Structure to store a Binary Search Tree node 4 | struct Node{ 5 | int data; 6 | Node* left; 7 | Node* right; 8 | }; 9 | 10 | //Function creates the new binary search tree node with the given value. 11 | Node* newNode(int value) 12 | { 13 | Node* node= new Node; 14 | node->data=value; 15 | node->left=NULL; 16 | node->right=NULL; 17 | return node; 18 | } 19 | //Function to insert a value into Binary search tree, 20 | //It's a Recursive function, that will insert the value at it's right position 21 | Node* Insertion(Node *root,int value) 22 | { 23 | if(root==NULL) 24 | return newNode(value); 25 | 26 | if(valuedata) 27 | root->left=Insertion(root->left,value); 28 | 29 | else 30 | root->right=Insertion(root->right,value); 31 | 32 | return root; 33 | } 34 | //You can also Transverse the Tree and One of the way is by doing inorder Transversal 35 | void inorder(Node* root) 36 | { 37 | if(root==NULL) 38 | { 39 | return; 40 | } 41 | inorder(root->left); 42 | cout<data<<" "; 43 | inorder(root->right); 44 | } 45 | int main() { 46 | //creating a root pointer 47 | Node* root= NULL; 48 | 49 | //We'll insert these values into BST 50 | int ar[]={15,10,20,8,12,16,25}; 51 | 52 | for(int i=0;i<7;i++) 53 | { 54 | root=Insertion(root,ar[i]); 55 | } 56 | inorder(root); 57 | return 0; 58 | } 59 | -------------------------------------------------------------------------------- /C++/Data-Structures/Tree/fenwick_tree.cpp: -------------------------------------------------------------------------------- 1 | // fenwick tree code 2 | // one application for finding the number of inversions in an array 3 | 4 | 5 | // definition of inversion-----> 6 | // in an array if there is a pair of index i,j such that 7 | // i < j and array[i] > array[j] is counted as one inversion 8 | 9 | #include 10 | using namespace std; 11 | 12 | const int N = 8; 13 | int bit[N]; 14 | 15 | void update(int i, int x){ 16 | for(; i < N; i += (i&-i)){ 17 | bit[i] += x; 18 | cout<<"update "< 0; i -= (i&-i)){ 25 | ans += bit[i]; 26 | cout<<"sum bit "<> n; 34 | long long a[n+10]; 35 | map mp; 36 | for(int i = 1;i <= n; ++i){ 37 | cin >> a[i]; 38 | mp[a[i]]; 39 | } 40 | 41 | 42 | // compression of numbers for the case where a[i] > 10 ^ 6 43 | int ptr = 1; 44 | for(auto &pr : mp){ 45 | pr.second = ptr++; 46 | } 47 | 48 | for(int i = 1; i <= n; ++i){ 49 | a[i] = mp[a[i]]; 50 | } 51 | 52 | // Finding Inversion count 53 | 54 | 55 | int inversion_ct = 0; 56 | for(int i = n; i>= 1; --i){ 57 | // cout<<"sum n "< 2 | using namespace std; 3 | int n=1000; 4 | vector graph[1002]; 5 | int vis[n]={0}; 6 | 7 | 8 | void bfs(int root) //bfs using queue also used to find min path 9 | {vis[root]=1; 10 | queueq; 11 | q.push(root); 12 | while(!q.empty()){ 13 | int k=q.pop(); 14 | for(i=0;i>c>>d; 26 | graph[c].push_back(d); //create tree 27 | graph[d].push_back(c); 28 | } 29 | bfs(1); //call bfs function 30 | return 0; 31 | } 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /C++/Data-Structures/graph/dfs using stack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int n=1000; 4 | vector graph[1002]; 5 | int vis[n]={0}; 6 | void dfs(int root)// dfs using stack 7 | {vis[root]=1; 8 | stack st; 9 | st.push(root); 10 | while(!st.empty()) 11 | { int k=st.top(); 12 | st.pop(); 13 | for(i=0;i>c>>d; 31 | graph[c].push_back(d); 32 | graph[d].push_back(c); 33 | } 34 | dfs(1); 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /C++/Data-Structures/graph/graph implementation using adjacency list.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() { 6 | int n;//number of vertices 7 | int m;//number of edges 8 | cin>>n>>m; 9 | int i; 10 | vector v[n+1]; 11 | for(i=0;i>x>>y;//input the vertices which are connected 15 | v[x].push_back(y); //put the vertex y in the list of x 16 | v[y].push_back(x); // put the vertex x in the list of y 17 | } 18 | int q; 19 | cin>>q;// queries to check whether a edge exist or not 20 | while(q--) 21 | { 22 | int x,y; 23 | cin>>x>>y;//check whether edge between x or y exist or not 24 | int flg=-1; 25 | for(i=0;i 2 | #include 3 | 4 | void TOH(int n, char A, char B, char C) 5 | { 6 | if (n > 0) 7 | { 8 | TOH(n - 1, A, C, B); 9 | printf("Move disk %d from %c to %c", n, A, C); 10 | printf("\n"); 11 | TOH(n - 1, B, A, C); 12 | } 13 | } 14 | 15 | int main() 16 | { 17 | int n; 18 | scanf("%d", &n); 19 | 20 | //How the TOH works 21 | //We basically create a recurrence relation 22 | //by observing the patterns for n = 1, and n = 2, and n = 3 23 | 24 | //The total recursive approach gives a large time comlexity 25 | //thus this algo works for lower contraints on "n" 26 | 27 | //Total time complexity : O(2^n) 28 | 29 | TOH(n, 'A', 'B', 'C'); // A, B and C are names of the disks 30 | 31 | return 0; 32 | } 33 | 34 | /***** 35 | Test Cases: 36 | 37 | n = 3 38 | 39 | Move disk 1 from A to C 40 | Move disk 2 from A to B 41 | Move disk 1 from C to B 42 | Move disk 3 from A to C 43 | Move disk 1 from B to A 44 | Move disk 2 from B to C 45 | Move disk 1 from A to C 46 | 47 | n = 4 48 | 49 | Move disk 1 from A to B 50 | Move disk 2 from A to C 51 | Move disk 1 from B to C 52 | Move disk 3 from A to B 53 | Move disk 1 from C to A 54 | Move disk 2 from C to B 55 | Move disk 1 from A to B 56 | Move disk 4 from A to C 57 | Move disk 1 from B to C 58 | Move disk 2 from B to A 59 | Move disk 1 from C to A 60 | Move disk 3 from B to C 61 | Move disk 1 from A to B 62 | Move disk 2 from A to C 63 | Move disk 1 from B to C 64 | 65 | */ 66 | 67 | -------------------------------------------------------------------------------- /C/Algorithms/Divide-and-Conquer/readme.md: -------------------------------------------------------------------------------- 1 | ### Divide-and-Conquer 2 | -------------------------------------------------------------------------------- /C/Algorithms/Dynamic-Programming/LonestCommonSubsequence.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int max(int a,int b){ 4 | return (a>b)? a: b; 5 | } 6 | int LCS(char * a,char * b,int n1,int n2){ 7 | if(n1==0 || n2==0) return 0; 8 | 9 | // if two character are common than check for subproblems 10 | if(a[n1-1]==b[n2-1]) 11 | return 1+LCS(a,b,n1-1,n2-1); 12 | // If two character is not common than two cases are arises 13 | // case 1: to leave the character of first string and check for subproblem with second string 14 | // case 2: to leave the character of second string and check for subproblem with first string 15 | return max(LCS(a,b,n1-1,n2),LCS(a,b,n1,n2-1)); 16 | } 17 | int main(){ 18 | int n1,n2; scanf("%d %d",&n1,&n2); 19 | 20 | char a[n1],b[n2]; 21 | scanf("%s",a); 22 | scanf("%s",b); 23 | printf("longest common subsequence is %d\n",LCS(a,b,n1,n2)); 24 | return 0; 25 | } -------------------------------------------------------------------------------- /C/Algorithms/Dynamic-Programming/readme.md: -------------------------------------------------------------------------------- 1 | ### Dynamic-Programming 2 | -------------------------------------------------------------------------------- /C/Algorithms/Geometric-Algorithms/readme.md: -------------------------------------------------------------------------------- 1 | ### Geometric-Algorithms -------------------------------------------------------------------------------- /C/Algorithms/Graph-Algorithms/Breadth_first_search.c: -------------------------------------------------------------------------------- 1 | #include 2 | int a[20][20], q[20], visited[20], n, i, j, f = 0, r = -1; 3 | 4 | void bfs(int v) { 5 | for(i = 1; i <= n; i++) 6 | if(a[v][i] && !visited[i]) 7 | q[++r] = i; 8 | if(f <= r) { 9 | visited[q[f]] = 1; 10 | bfs(q[f++]); 11 | } 12 | } 13 | 14 | void main() { 15 | int v; 16 | printf("\n Enter the number of vertices:"); 17 | scanf("%d", &n); 18 | 19 | for(i=1; i <= n; i++) { 20 | q[i] = 0; 21 | visited[i] = 0; 22 | } 23 | 24 | printf("\n Enter graph data in matrix form:\n"); 25 | for(i=1; i<=n; i++) { 26 | for(j=1;j<=n;j++) { 27 | scanf("%d", &a[i][j]); 28 | } 29 | } 30 | 31 | printf("\n Enter the starting vertex:"); 32 | scanf("%d", &v); 33 | bfs(v); 34 | printf("\n The node which are reachable are:\n"); 35 | 36 | for(i=1; i <= n; i++) { 37 | if(visited[i]) 38 | printf("%d\t", i); 39 | else { 40 | printf("\n Bfs is not possible. Not all nodes are reachable"); 41 | break; 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /C/Algorithms/Graph-Algorithms/readme.md: -------------------------------------------------------------------------------- 1 | ### Graph-Algorithms -------------------------------------------------------------------------------- /C/Algorithms/Greedy-Algorithms/readme.md: -------------------------------------------------------------------------------- 1 | ### Greedy-Algorithms -------------------------------------------------------------------------------- /C/Algorithms/Mathematical/Factorial.c: -------------------------------------------------------------------------------- 1 | /** 2 | * Factorial Algorithm 3 | * 4 | * Mathematical explanation: 5 | * The factorial function has the following format: 6 | * factorial(n) = !n = n.!(n-1) = n.(n-1).(n-2). ... !0 7 | * Where, 8 | * factorial(0) = !0 = 1 9 | * factorial(1) = !1 = 1.!0 = 1 10 | * factorial(2) = !2 = 2.!1 = 2 11 | * ... 12 | * factorial(n) = !n = n.!(n-1) = n.(n-1).(n-2). ... !0 13 | * 14 | * Code explanation: 15 | * factorial(n) - calculates the factorial to the index `n` 16 | * example() - example of how factorial function works 17 | */ 18 | #include 19 | 20 | int factorial(int index) 21 | { 22 | if (index == 0) return 1; ///< zero case 23 | else return index*factorial(index - 1); ///< general case 24 | } 25 | 26 | void example() 27 | { 28 | for(int i = 0; i < 10; i++) 29 | printf("\n%d", factorial(i)); 30 | } 31 | 32 | int main() 33 | { 34 | example(); 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /C/Algorithms/Mathematical/readme.md: -------------------------------------------------------------------------------- 1 | ### Mathematical -------------------------------------------------------------------------------- /C/Algorithms/Pattern-Searching/readme.md: -------------------------------------------------------------------------------- 1 | ### Pattern-Searching -------------------------------------------------------------------------------- /C/Algorithms/Randomized-Algorithms/readme.md: -------------------------------------------------------------------------------- 1 | ### Randomized-Algorithms -------------------------------------------------------------------------------- /C/Algorithms/Searching-Algorithms/Binary_search.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define N 10 // SIZE OF ARRAY 4 | 5 | int low = 0, high = N-1, mid; // LOW, HIGH AND MID INDEX FOR BINARY SEARCH FUNCTION 6 | int Index = -1; //RETURN VALUE 7 | 8 | int Binary_search(int A[], int x) // SEARCH FUNCTION 9 | { 10 | if(high > low) 11 | { 12 | mid = (low + high)/2; 13 | if(A[mid] == x) 14 | Index = mid; 15 | else if(A[mid] < x) 16 | { 17 | low = mid+1; 18 | Index = Binary_search( A, x); 19 | } 20 | else 21 | { 22 | high = mid-1; 23 | Index = Binary_search( A, x); 24 | } 25 | return Index; 26 | 27 | } 28 | else 29 | { 30 | return Index; 31 | } 32 | } 33 | 34 | int main() 35 | { 36 | int A[N] = {2, 5, 8 ,9 ,12, 15 ,23, 29, 35, 37}; // SORTED ARRAY 37 | int x = 12; // 38 | 39 | int result = Binary_search( A, x); 40 | 41 | if(result == -1) // IF NOT FOUND 42 | { 43 | printf("%d not found\n", x); 44 | } 45 | else 46 | { 47 | printf("%d is present at index : %d\n", x, result); 48 | } 49 | 50 | return 0; 51 | 52 | 53 | } 54 | 55 | // OUTPUT OF PROGRAM 56 | // 12 is present at index : 4 57 | -------------------------------------------------------------------------------- /C/Algorithms/Searching-Algorithms/ternary-search_string.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | 4 | int ternarySearch(int l, int r, int key, int ar[]) 5 | 6 | { 7 | while (r >= l) { 8 | 9 | int mid1 = l + (r - l) / 3; 10 | int mid2 = r - (r - l) / 3; 11 | 12 | if (ar[mid1] == key) { 13 | return mid1; 14 | } 15 | if (ar[mid2] == key) { 16 | return mid2; 17 | } 18 | 19 | if (key < ar[mid1]) { 20 | 21 | r = mid1 - 1; 22 | } 23 | else if (key > ar[mid2]) { 24 | 25 | l = mid2 + 1; 26 | } 27 | else { 28 | 29 | l = mid1 + 1; 30 | r = mid2 - 1; 31 | } 32 | } 33 | 34 | return -1; 35 | } 36 | 37 | int main() 38 | { 39 | int l, r, p, key; 40 | 41 | int ar[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 42 | 43 | l = 0; 44 | 45 | r = 9; 46 | 47 | 48 | key = 5; 49 | 50 | p = ternarySearch(l, r, key, ar); 51 | 52 | printf("Index of %d is %d\n", key, p); 53 | 54 | 55 | key = 50; 56 | 57 | p = ternarySearch(l, r, key, ar); 58 | 59 | printf("Index of %d is %d", key, p); 60 | } 61 | -------------------------------------------------------------------------------- /C/Algorithms/Sorting-Algorithms/BubbleSort/Bubble_sort.c: -------------------------------------------------------------------------------- 1 | //Implementation of Bubble sort in C 2 | #include 3 | #include 4 | #define swap(t, x, y) t z = x; x = y; y = z; 5 | typedef int TYPE; 6 | void bubble_sort(TYPE [], int); 7 | void print_array(TYPE [], int); 8 | 9 | int main(){ 10 | TYPE A[] = {4, 5, 3, 2, 11}; 11 | int n = sizeof(A) / sizeof(TYPE); 12 | 13 | printf("Unsorted: "); 14 | print_array(A, n); 15 | 16 | printf("Sorted: "); 17 | bubble_sort(A, n); 18 | print_array(A, n); 19 | 20 | return EXIT_SUCCESS; 21 | } 22 | 23 | void bubble_sort(TYPE A[], int n) { 24 | int i, j, sorted; 25 | 26 | for(i = 0; i < n; i++) { 27 | sorted = 1; 28 | 29 | for(j = 0; j < n - 1; j++) { 30 | if(A[j] > A[j + 1]) { 31 | swap(TYPE, A[j], A[j+1]); 32 | sorted = 0; 33 | } 34 | } 35 | 36 | if(sorted) break; 37 | /*if array is sorted break. 38 | This way we have O(n) in best case, instead of always O(n^2)*/ 39 | } 40 | } 41 | void print_array(TYPE A[], int n) { 42 | int i = 0; 43 | putchar('['); 44 | while(i < n) { 45 | if(i > 0) printf(", "); 46 | printf("%d", A[i++]); //first A[i] is done then i = i + 1 47 | } 48 | puts("]"); 49 | } -------------------------------------------------------------------------------- /C/Algorithms/Sorting-Algorithms/InsertionSort/InsertionSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(void) 4 | 5 | { 6 | int array[25], n, temp, j; 7 | 8 | printf("Enter the number of entries: "); 9 | scanf("%d", &n); 10 | printf("Enter the %d elements: ", n); 11 | //user-input 12 | for(int i = 0; i < n; i++) 13 | { 14 | scanf("%d", &array[i]); 15 | } 16 | //The main algo of insertion-sort 17 | //it considers first to be smallest then compares, if other number is found smaller then the choosen one then that number is taken out 18 | //now shift the sorted elemnt according to how smaaler the number is taken out and so on... 19 | for(int i = 1; i < n; i++) 20 | { 21 | temp = array[i]; 22 | j = i - 1; 23 | while((temp < array[j]) && (j >= 0)) 24 | { 25 | array[j + 1] = array[j]; 26 | j = j - 1; 27 | } 28 | array[j + 1] = temp; 29 | } 30 | //printing the sorted array 31 | printf("The sorted array is: \n"); 32 | for(int i = 0; i < n; i++) 33 | { 34 | printf("%d ", array[i]); 35 | } 36 | } -------------------------------------------------------------------------------- /C/Algorithms/Sorting-Algorithms/InsertionSort/README.md: -------------------------------------------------------------------------------- 1 |

Insertion Sort

2 | 3 | #### NOTE: THE PROGRAM IS IN C 4 |
5 | 6 | Here's a brief about Insertion sort.
7 | 8 | `The idea of this algorithm is to build your sorted array in place, shifting elements out of the way if necessary to make room as you go.`
9 | 10 | ### Sample Input-1 11 | ``` 12 | 4 13 | 34 21 43 56 14 | ``` 15 | 16 | ### Sample Output 17 | The sorted array is:
18 | `21 34 43 56` 19 | 20 | ### Sample Input-2 21 | ``` 22 | 10 23 | 44 23 56 21 54 65 87 96 54 99 24 | ``` 25 | 26 | ### Sample Output 27 | The sorted array is:
28 | `21 23 44 54 54 56 65 87 96 99`

29 | 30 | 31 | Now see the codes for proper understanding of Algorithm.

32 | 33 | 34 | ### Contributed by: 35 | [*Sarthak Luthra*](https://github.com/sarthak-21) -------------------------------------------------------------------------------- /C/Algorithms/Sorting-Algorithms/Merge Sort/MergeSort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define max 10 4 | 5 | int a[11] = { 23, 34, 17, 24, 29, 31, 33, 35, 42, 54, 0 }; 6 | int b[10]; 7 | 8 | void merging(int low, int mid, int high) { 9 | int l1, l2, i; 10 | 11 | for(l1 = low, l2 = mid + 1, i = low; l1 <= mid && l2 <= high; i++) { 12 | if(a[l1] <= a[l2]) 13 | b[i] = a[l1++]; 14 | else 15 | b[i] = a[l2++]; 16 | } 17 | 18 | while(l1 <= mid) 19 | b[i++] = a[l1++]; 20 | 21 | while(l2 <= high) 22 | b[i++] = a[l2++]; 23 | 24 | for(i = low; i <= high; i++) 25 | a[i] = b[i]; 26 | } 27 | 28 | //sorting func 29 | void sort(int low, int high) { 30 | int mid; 31 | 32 | if(low < high) { 33 | mid = (low + high) / 2; 34 | sort(low, mid); 35 | sort(mid+1, high); 36 | merging(low, mid, high); 37 | } else { 38 | return; 39 | } 40 | } 41 | 42 | int main() { 43 | int i; 44 | 45 | printf(" Before sorting\n"); 46 | 47 | for(i = 0; i <= max; i++) 48 | printf("%d ", a[i]); 49 | 50 | sort(0, max); 51 | 52 | printf("\nAfter sorting\n"); 53 | 54 | for(i = 0; i <= max; i++) 55 | printf("%d ", a[i]); 56 | } -------------------------------------------------------------------------------- /C/Algorithms/Sorting-Algorithms/QuickSort/QuickSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int values[] = { 88, 56, 100, 2, 25 }; 5 | //you can take user input as well 6 | 7 | //comparison function 8 | int cmpfunc (const void * a, const void * b) { 9 | return ( *(int*)a - *(int*)b ); 10 | } 11 | 12 | int main () { 13 | int n; 14 | printf("Before sorting the list is: \n"); 15 | for( n = 0 ; n < 5; n++ ) { 16 | printf("%d ", values[n]); 17 | } 18 | 19 | qsort(values, 5, sizeof(int), cmpfunc); 20 | //qsort(void *base, size_t items, size_t size, int (*compar)(const void *, const void*)) 21 | 22 | /* base - This is the pointer to the fisrt element of array 23 | items - This is the number of elements in the array 24 | size - This is the sizxe in bytes of each element in the array 25 | compar - This is the function that compares two element */ 26 | 27 | printf("\nAfter sorting the list is: \n"); 28 | for( n = 0 ; n < 5; n++ ) { 29 | printf("%d ", values[n]); 30 | } 31 | 32 | return(0); 33 | } -------------------------------------------------------------------------------- /C/Algorithms/Sorting-Algorithms/QuickSort/README.md: -------------------------------------------------------------------------------- 1 |

Quick Sort

2 | 3 | #### NOTE: THE PROGRAM IS IN C 4 |
5 | 6 | Here's a brief about Quick sort.
7 | 8 | 9 | `Like merge sort, Quick sort is a divide and conquer algorithm.`
10 | `It picks an element as pivot and partition the given array around the picked pivot.`

11 | 12 | 13 | Now see the codes for proper understanding of Algorithm.

14 | 15 | 16 | ### Contributed by: 17 | [*Sarthak Luthra*](https://github.com/sarthak-21) -------------------------------------------------------------------------------- /C/Algorithms/Sorting-Algorithms/SelectionSort/SelectionSort.c: -------------------------------------------------------------------------------- 1 | // C program for implementation of selection sort 2 | #include 3 | 4 | void swap(int *xp, int *yp) 5 | { 6 | int temp = *xp; 7 | *xp = *yp; 8 | *yp = temp; 9 | } 10 | 11 | void selectionSort(int arr[], int n) 12 | { 13 | int i, j, min_idx; 14 | 15 | // One by one move boundary of unsorted subarray 16 | for (i = 0; i < n-1; i++) 17 | { 18 | // Find the minimum element in unsorted array 19 | min_idx = i; 20 | for (j = i+1; j < n; j++) 21 | if (arr[j] < arr[min_idx]) 22 | min_idx = j; 23 | 24 | // Swap the found minimum element with the first element 25 | swap(&arr[min_idx], &arr[i]); 26 | } 27 | } 28 | 29 | /* Function to print an array */ 30 | void printArray(int arr[], int size) 31 | { 32 | int i; 33 | for (i=0; i < size; i++) 34 | printf("%d ", arr[i]); 35 | printf("\n"); 36 | } 37 | 38 | // Driver program to test above functions 39 | int main() 40 | { 41 | int arr[] = {64, 25, 12, 22, 11}; 42 | int n = sizeof(arr)/sizeof(arr[0]); 43 | selectionSort(arr, n); 44 | printf("Sorted array: \n"); 45 | printArray(arr, n); 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /C/Algorithms/Sorting-Algorithms/Wave Sort/wave_sort.c: -------------------------------------------------------------------------------- 1 | //wave sort in c 2 | #include 3 | #include 4 | 5 | //C function to SWAP two reference pointers/values 6 | void swap(int *x, int *y) 7 | { 8 | int temp = *x; 9 | *x = *y; 10 | *y = temp; 11 | } 12 | 13 | //C function to implement WAVE SORT 14 | void sortInWave(int arr[], int n) 15 | { 16 | 17 | //elements are arranged in the order 18 | //sequence a1 >= a2 <= a3 >= a4 <= a5 >= a6 and so on. 19 | for (int i = 0; i < n; i += 2) 20 | { 21 | if (i > 0 && arr[i - 1] > arr[i] ) 22 | swap(&arr[i], &arr[i - 1]); 23 | 24 | if (i < n - 1 && arr[i] < arr[i + 1] ) 25 | swap(&arr[i], &arr[i + 1]); 26 | } 27 | } 28 | 29 | int main() 30 | { 31 | int n; 32 | scanf("%d", &n); 33 | 34 | int ar[n]; 35 | 36 | for (int i = 0; i < n; i++) 37 | scanf("%d", &ar[i]); 38 | 39 | sortInWave(ar, n); 40 | //Time complexity of this algorithm : 41 | // O(n) time by doing a "single traversal". 42 | 43 | for (int i = 0; i < n; i++) 44 | printf("%d ", ar[i]); 45 | printf("\n"); 46 | 47 | return 0; 48 | } 49 | 50 | /* 51 | 52 | Input : 53 | 54 | 7 55 | 10 90 49 2 1 5 23 56 | 57 | Output : 58 | 59 | 90 10 49 1 5 2 23 60 | 61 | 62 | */ -------------------------------------------------------------------------------- /C/Data-Structures/Arrays/Largest_Smallest_Element_in_Array.c: -------------------------------------------------------------------------------- 1 | #include 2 | main() 3 | { 4 | int arr[5],l,s; 5 | printf("\tACCESSING THE LARGEST AND THE SMALLEST ELEMENT IN AN ARRAY\n"); 6 | int i; 7 | printf("\nEnter 5 Elements in the Array"); 8 | for(i=0;i<=4;i++) 9 | { 10 | printf("\nEnter the Element:"); 11 | scanf("%d",&arr[i]); 12 | } 13 | l=s=arr[0]; 14 | for(i=0;i<=4;i++) 15 | { 16 | if(arr[i]>l) 17 | l=arr[i]; 18 | else if(arr[i] 4 | 5 | int main () { 6 | 7 | int capacity; //aray size user input 8 | 9 | printf("Enter the array Size"); 10 | scanf("%d",&capacity); 11 | int n[ capacity ]; /* n is an array of 10 integers */ 12 | int i,j; 13 | 14 | /* initialize elements of array n to 0 */ 15 | for ( i = 0; i < capacity; i++ ) { 16 | n[ i ] = i + 100; /* set element at location i to i + 100 */ 17 | } 18 | 19 | /* output each array element's value */ 20 | for (j = 0; j < capacity; j++ ) { 21 | printf("Element[%d] = %d\n", j, n[j] ); 22 | } 23 | 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /C/Data-Structures/Queue/queue_using_array.c: -------------------------------------------------------------------------------- 1 | #include 2 | #define n 5 3 | int main() 4 | { 5 | int queue[n],ch=1,front=0,rear=0,i,j=1,x=n; 6 | printf("Queue using Array"); 7 | printf("\n1.Insertion \n2.Deletion \n3.Display \n4.Exit"); 8 | while(ch) 9 | { 10 | printf("\nEnter the Choice:"); 11 | scanf("%d",&ch); 12 | switch(ch) 13 | { 14 | case 1: 15 | if(rear==x) 16 | printf("\n Queue is Full"); 17 | else 18 | { 19 | printf("\n Enter no %d:",j++); 20 | scanf("%d",&queue[rear++]); 21 | } 22 | break; 23 | case 2: 24 | if(front==rear) 25 | { 26 | printf("\n Queue is empty"); 27 | } 28 | else 29 | { 30 | printf("\n Deleted Element is %d",queue[front++]); 31 | x++; 32 | } 33 | break; 34 | case 3: 35 | printf("\nQueue Elements are:\n "); 36 | if(front==rear) 37 | printf("\n Queue is Empty"); 38 | else 39 | { 40 | for(i=front; i 2 | 3 | // C recursive function to solve tower of hanoi puzzle 4 | void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) 5 | { 6 | if (n == 1) 7 | { 8 | printf("\n Move disk 1 from rod %c to rod %c", from_rod, to_rod); 9 | return; 10 | } 11 | towerOfHanoi(n-1, from_rod, aux_rod, to_rod); 12 | printf("\n Move disk %d from rod %c to rod %c", n, from_rod, to_rod); 13 | towerOfHanoi(n-1, aux_rod, to_rod, from_rod); 14 | } 15 | 16 | int main() 17 | { 18 | int n; // Number of disks 19 | printf("Enter no of disks"); 20 | scanf("%d",&n); 21 | towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods 22 | return 0; 23 | } -------------------------------------------------------------------------------- /Go/Algorithms/Backtracking/readme.md: -------------------------------------------------------------------------------- 1 | ### Backtracking-Algorithms -------------------------------------------------------------------------------- /Go/Algorithms/Branch-and-Bound/readme.md: -------------------------------------------------------------------------------- 1 | ### Branch-and-Bound -------------------------------------------------------------------------------- /Go/Algorithms/Divide-and-Conquer/readme.md: -------------------------------------------------------------------------------- 1 | ### Divide-and-Conquer 2 | -------------------------------------------------------------------------------- /Go/Algorithms/Dynamic-Programming/readme.md: -------------------------------------------------------------------------------- 1 | ### Dynamic-Programming 2 | -------------------------------------------------------------------------------- /Go/Algorithms/Geometric-Algorithms/readme.md: -------------------------------------------------------------------------------- 1 | ### Geometric-Algorithms -------------------------------------------------------------------------------- /Go/Algorithms/Graph-Algorithms/readme.md: -------------------------------------------------------------------------------- 1 | ### Graph-Algorithms -------------------------------------------------------------------------------- /Go/Algorithms/Greedy-Algorithms/readme.md: -------------------------------------------------------------------------------- 1 | ### Greedy-Algorithms -------------------------------------------------------------------------------- /Go/Algorithms/Mathematical/Fibonacci_till_nth_term.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | func main() { 8 | n := 4 9 | a := 0 10 | b := 1 11 | sum := 0 12 | if n < 2 { 13 | fmt.Print("Fibonacci sereies till 1st term is 0") 14 | } else if n < 3 { 15 | fmt.Print("Fibonacci sereies till 2nd term is 0 1") 16 | } else { 17 | fmt.Print("Fibonacci sereies till ", n, "th term is ", a, " ", b, " ") 18 | for i := 2; i < n; i++ { 19 | 20 | sum = a + b 21 | fmt.Print(sum, " ") 22 | a = b 23 | b = sum 24 | } 25 | 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Go/Algorithms/Mathematical/readme.md: -------------------------------------------------------------------------------- 1 | ### Mathematical -------------------------------------------------------------------------------- /Go/Algorithms/Pattern-Searching/readme.md: -------------------------------------------------------------------------------- 1 | ### Pattern-Searching -------------------------------------------------------------------------------- /Go/Algorithms/Randomized-Algorithms/readme.md: -------------------------------------------------------------------------------- 1 | ### Randomized-Algorithms -------------------------------------------------------------------------------- /Go/Algorithms/Searching-Algorithms/Binary-Search/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | type binarySearch struct{} 6 | 7 | // Returns true if key is present in data list, binary search will only work on sorted lists 8 | func (ls *binarySearch) binarySearch(data []int, key int) bool { 9 | l := 0 10 | r := len(data) - 1 11 | // loop until left index is less than or equal to right index 12 | for l <= r { 13 | // set middle index 14 | m := (l + r) / 2 15 | // if value found return true 16 | if key == data[m] { 17 | return true 18 | } 19 | //update left, right index based 20 | if key > data[m] { 21 | l = m + 1 22 | } else { 23 | r = m - 1 24 | } 25 | } 26 | return false 27 | } 28 | 29 | func main() { 30 | ls := binarySearch{} 31 | data := []int{1, 2, 5, 6, 11} 32 | fmt.Println(ls.binarySearch(data, 2)) 33 | fmt.Println(ls.binarySearch(data, 15)) 34 | 35 | data = []int{1, 3, 8, 15} 36 | fmt.Println(ls.binarySearch(data, 2)) 37 | fmt.Println(ls.binarySearch(data, 15)) 38 | } 39 | -------------------------------------------------------------------------------- /Go/Algorithms/Searching-Algorithms/Interpolation-Search/main.go: -------------------------------------------------------------------------------- 1 | // Interpolation Search in Golang 2 | package main 3 | import "fmt" 4 | 5 | func interpolationSearch(array []int, key int) int { 6 | 7 | min, max := array[0], array[len(array)-1] 8 | 9 | low, high := 0, len(array)-1 10 | 11 | for { 12 | if key < min { 13 | return low 14 | } 15 | 16 | if key > max { 17 | return high + 1 18 | } 19 | 20 | // make a guess of the location 21 | var guess int 22 | if high == low { 23 | guess = high 24 | } else { 25 | size := high - low 26 | offset := int(float64(size-1) * (float64(key-min) / float64(max-min))) 27 | guess = low + offset 28 | } 29 | 30 | // maybe we found it? 31 | if array[guess] == key { 32 | // scan backwards for start of value range 33 | for guess > 0 && array[guess-1] == key { 34 | guess-- 35 | } 36 | return guess 37 | } 38 | 39 | // if we guessed to high, guess lower or vice versa 40 | if array[guess] > key { 41 | high = guess - 1 42 | max = array[high] 43 | } else { 44 | low = guess + 1 45 | min = array[low] 46 | } 47 | } 48 | } 49 | 50 | 51 | func main(){ 52 | items := []int{1,2, 9, 20, 31, 45, 63, 70, 100} 53 | fmt.Println(interpolationSearch(items,63)) 54 | } 55 | -------------------------------------------------------------------------------- /Go/Algorithms/Searching-Algorithms/Linear-Search/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | type linearSearch struct{} 6 | 7 | // Returns true if key is present in data list 8 | func (ls *linearSearch) linearSearch(data []int, key int) bool { 9 | // iterate through list and return true if found 10 | for _, k := range data { 11 | if key == k { 12 | return true 13 | } 14 | } 15 | return false 16 | } 17 | 18 | func main() { 19 | ls := linearSearch{} 20 | data := []int{1, 2, 8, 3, 6} 21 | fmt.Println(ls.linearSearch(data, 2)) 22 | fmt.Println(ls.linearSearch(data, 5)) 23 | } 24 | -------------------------------------------------------------------------------- /Go/Algorithms/Searching-Algorithms/readme.md: -------------------------------------------------------------------------------- 1 | ### Searching-Algorithms -------------------------------------------------------------------------------- /Go/Algorithms/Sorting-Algorithms/BubbleSort/BubbleSort.go: -------------------------------------------------------------------------------- 1 | // Bubble Sort in Golang 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | "math/rand" 7 | "time" 8 | ) 9 | 10 | func main() { 11 | 12 | slice := generateSlice(20) 13 | fmt.Println("\n--- Unsorted --- \n\n", slice) 14 | bubblesort(slice) 15 | fmt.Println("\n--- Sorted ---\n\n", slice, "\n") 16 | } 17 | 18 | // Generates a slice of size, size filled with random numbers 19 | func generateSlice(size int) []int { 20 | 21 | slice := make([]int, size, size) 22 | rand.Seed(time.Now().UnixNano()) 23 | for i := 0; i < size; i++ { 24 | slice[i] = rand.Intn(999) - rand.Intn(999) 25 | } 26 | return slice 27 | } 28 | 29 | func bubblesort(items []int) { 30 | var ( 31 | n = len(items) 32 | sorted = false 33 | ) 34 | for !sorted { 35 | swapped := false 36 | for i := 0; i < n-1; i++ { 37 | if items[i] > items[i+1] { 38 | items[i+1], items[i] = items[i], items[i+1] 39 | swapped = true 40 | } 41 | } 42 | if !swapped { 43 | sorted = true 44 | } 45 | n = n - 1 46 | } 47 | } -------------------------------------------------------------------------------- /Go/Algorithms/Sorting-Algorithms/InsertionSort/main.go: -------------------------------------------------------------------------------- 1 | // Insertion Sort in Golang 2 | 3 | //TO sort an array of numbers using insertion sort 4 | package main 5 | 6 | import ( 7 | "fmt" 8 | "math/rand" 9 | "time" 10 | ) 11 | 12 | func main() { 13 | 14 | slice := generateSlice(20) //random unsorted 20 numbers 15 | fmt.Println("\n--- Unsorted --- \n\n", slice) 16 | insertionsort(slice) 17 | fmt.Println("\n--- Sorted ---\n\n", slice, "\n") 18 | } 19 | 20 | // Generates a slice of size, size filled with random numbers 21 | func generateSlice(size int) []int { 22 | 23 | slice := make([]int, size, size) 24 | rand.Seed(time.Now().UnixNano()) 25 | for i := 0; i < size; i++ { 26 | slice[i] = rand.Intn(999) - rand.Intn(999) 27 | } 28 | return slice 29 | } 30 | 31 | func insertionsort(items []int) { 32 | var n = len(items) 33 | for i := 1; i < n; i++ { 34 | j := i 35 | for j > 0 { 36 | if items[j-1] > items[j] { 37 | items[j-1], items[j] = items[j], items[j-1] 38 | } 39 | j = j - 1 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Go/Algorithms/Sorting-Algorithms/QuickSort/QuickSort.go: -------------------------------------------------------------------------------- 1 | /* 2 | Implementation of Quicksort according to https://en.wikipedia.org/wiki/Quicksort 3 | */ 4 | 5 | package main 6 | 7 | import ( 8 | "fmt" 9 | "math/rand" 10 | ) 11 | 12 | func swap(a *int64, b *int64) { 13 | t := *a 14 | *a = *b 15 | *b = t 16 | } 17 | 18 | func partition(arr []int64, low int, high int) int { 19 | pivot := arr[high] 20 | i := low 21 | for j := low; j <= high; j++ { 22 | if arr[j] < pivot { 23 | swap(&arr[i], &arr[j]) 24 | i++ 25 | } 26 | } 27 | swap(&arr[i], &arr[high]) 28 | return i 29 | } 30 | 31 | func quicksort(arr []int64, low int, high int) { 32 | if low < high { 33 | pi := partition(arr, low, high) 34 | quicksort(arr, low, pi - 1) 35 | quicksort(arr, pi + 1, high) 36 | } 37 | } 38 | 39 | func main() { 40 | //Generates n random values and sorts them with quicksort 41 | n := 100 42 | arr := make([]int64, 100) 43 | for i := 0; i < n; i++ { 44 | arr[i] = rand.Int63n(100) 45 | } 46 | 47 | quicksort(arr, 0, len(arr) - 1) 48 | fmt.Printf("%v\n", arr) 49 | } -------------------------------------------------------------------------------- /Go/Algorithms/Sorting-Algorithms/readme.md: -------------------------------------------------------------------------------- 1 | ### Sorting-Algorithms -------------------------------------------------------------------------------- /Go/Data-Structures/README.md: -------------------------------------------------------------------------------- 1 | ## Go DataStructures and Algorithms 2 | 3 | #### Testing 4 | To run a test set the current working directory to the directory containing the test and use the command `go test`. 5 | For example to run the queue tests, head to `Data-Structures/queue` and run `go test`. 6 | -------------------------------------------------------------------------------- /Go/Data-Structures/binary-search-tree/main.go: -------------------------------------------------------------------------------- 1 | /* 2 | Big O: O(h) 3 | */ 4 | package main 5 | 6 | import "fmt" 7 | 8 | // Node is for the binary search tree 9 | type Node struct { 10 | Key int 11 | Left *Node 12 | Right *Node 13 | } 14 | 15 | // Insert will add a node to the binary search tree 16 | func (n *Node) Insert(k int) { 17 | if n.Key < k { 18 | //right 19 | if n.Right == nil { 20 | n.Right = &Node{Key: k} 21 | } else { 22 | n.Right.Insert(k) 23 | } 24 | } else if n.Key > k { 25 | //left 26 | if n.Left == nil { 27 | n.Left = &Node{Key: k} 28 | } else { 29 | n.Left.Insert(k) 30 | } 31 | } 32 | 33 | } 34 | 35 | // Search will take in a key value 36 | // and RETURN true if there is a node with that value 37 | func (n *Node) Search(k int) bool { 38 | if n == nil { 39 | return false 40 | } 41 | 42 | if n.Key < k { 43 | //move right 44 | return n.Right.Search(k) 45 | } else if n.Key > k { 46 | //move left 47 | return n.Left.Search(k) 48 | } 49 | 50 | return true 51 | } 52 | 53 | func main() { 54 | tree := &Node{Key: 100} 55 | fmt.Println(tree) 56 | tree.Insert(52) 57 | tree.Insert(203) 58 | tree.Insert(19) 59 | tree.Insert(76) 60 | tree.Insert(150) 61 | tree.Insert(310) 62 | tree.Insert(7) 63 | tree.Insert(24) 64 | tree.Insert(88) 65 | tree.Insert(276) 66 | 67 | fmt.Println(tree.Search(76)) 68 | 69 | } 70 | -------------------------------------------------------------------------------- /Go/Data-Structures/queue/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | type queue struct { 6 | data []int 7 | } 8 | 9 | // Return true if queue is empty 10 | func (q *queue) isEmpty() bool { 11 | return len(q.data) == 0 12 | } 13 | 14 | // enqueue value into queue 15 | func (q *queue) enqueue(data int) { 16 | q.data = append(q.data, data) 17 | } 18 | 19 | // return data element and a boolean value, if queue is empty boolean value returned wll be false 20 | func (q *queue) dequeue() (int, bool) { 21 | if q.isEmpty() { 22 | return 0, false 23 | } 24 | data := q.data[0] 25 | q.data = q.data[1:] 26 | return data, true 27 | } 28 | 29 | func main() { 30 | var q queue 31 | q.enqueue(1) 32 | q.enqueue(2) 33 | q.enqueue(4) 34 | q.enqueue(8) 35 | fmt.Println(q.data) 36 | fmt.Println(q.dequeue()) 37 | fmt.Println(q.data) 38 | fmt.Println(q.dequeue()) 39 | fmt.Println(q.dequeue()) 40 | fmt.Println(q.data) 41 | fmt.Println(q.dequeue()) 42 | fmt.Println(q.dequeue()) 43 | fmt.Println(q.data) 44 | } 45 | -------------------------------------------------------------------------------- /Go/Data-Structures/stack/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | type stack struct { 6 | data []int 7 | } 8 | 9 | // push value into stack 10 | func (s *stack) push(data int) { 11 | s.data = append(s.data, data) 12 | } 13 | 14 | //pop value out of stack 15 | func (s *stack) isEmpty() bool { 16 | return len(s.data) == 0 17 | } 18 | 19 | // return data element and a boolean value, if stack is empty boolean value returned wll be false 20 | func (s *stack) pop() (int, bool) { 21 | if s.isEmpty() { 22 | return 0, false 23 | } 24 | lastElement := len(s.data) - 1 25 | data := s.data[lastElement] 26 | s.data = s.data[:lastElement] 27 | return data, true 28 | } 29 | 30 | func main() { 31 | var st stack 32 | st.push(1) 33 | st.push(2) 34 | st.push(4) 35 | st.push(8) 36 | fmt.Println(st.data) 37 | fmt.Println(st.pop()) 38 | fmt.Println(st.data) 39 | fmt.Println(st.pop()) 40 | fmt.Println(st.pop()) 41 | fmt.Println(st.pop()) 42 | fmt.Println(st.pop()) 43 | fmt.Println(st.data) 44 | } 45 | -------------------------------------------------------------------------------- /Haskell/Algorithms/Searching-Algorithms/BinarySearch.hs: -------------------------------------------------------------------------------- 1 | -- # Binary Search in Haskell 2 | -- This is an implementation of simple Binary Search in Haskell on any type that can be ordered. 3 | -- Binary Search is an effective searching algorithm, that can be used to find an element in a sorted list in O(lg(n)) time. 4 | 5 | -- Binary search with index carry 6 | bsWithIndex :: (Ord a) => [a] -> a -> Int -> Maybe Int 7 | bsWithIndex list n i 8 | | n == head list = Just i 9 | | len == 1 = Nothing -- only candidate in list is not the right elem 10 | | n < head ys = bsWithIndex xs n i 11 | | otherwise = bsWithIndex ys n (i + half) 12 | where 13 | len = length list 14 | half = len `div` 2 15 | (xs, ys) = splitAt half list 16 | 17 | -- Binary search returning index, or -1 if element not in list 18 | bs :: (Ord a) => [a] -> a -> Int 19 | bs list n = case bsWithIndex list n 0 of 20 | Just x -> x 21 | Nothing -> -1 22 | 23 | main :: IO () 24 | main = do 25 | let intList = [1,4,7,10,25,30] 26 | print $ bs intList 29 -- 29 -> -1 as not in list 27 | print $ bs intList 7 -- 7 -> 2 as in list 28 | -------------------------------------------------------------------------------- /Haskell/Algorithms/Sorting-Algorithms/InsertionSort.hs: -------------------------------------------------------------------------------- 1 | -- # Insertion Sort in Haskell 2 | -- This is an implementation of simple Insertion Sort in Haskell on any type that can be ordered. 3 | -- Insertion Sort is a slow, but simple sorting algorithm that has time complexity O(n^2) 4 | 5 | -- Insert element into list in order, returning sorted list 6 | insert :: (Ord a) => a -> [a] -> [a] 7 | insert e [] = [e] 8 | insert e (x:xs) 9 | | e < x = e : x : xs 10 | | otherwise = x : insert e xs 11 | 12 | -- Insertion sort on list, returning the list sorted 13 | insertionSort :: (Ord a) => [a] -> [a] 14 | insertionSort [] = [] 15 | insertionSort (x:xs) = insert x (insertionSort xs) 16 | 17 | main :: IO () 18 | main = do 19 | let intList = [1, 30, 7, 10, 4, 25] 20 | print $ insertionSort intList -- Returning [1,4,7,10,25,30] -------------------------------------------------------------------------------- /Java/Algorithms/Backtracking/readme.md: -------------------------------------------------------------------------------- 1 | ### Backtracking-Algorithms -------------------------------------------------------------------------------- /Java/Algorithms/Branch-and-Bound/readme.md: -------------------------------------------------------------------------------- 1 | ### Branch-and-Bound -------------------------------------------------------------------------------- /Java/Algorithms/Divide-and-Conquer/readme.md: -------------------------------------------------------------------------------- 1 | ### Divide-and-Conquer 2 | -------------------------------------------------------------------------------- /Java/Algorithms/Dynamic-Programming/Binary/ConvertBinary.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class ConvertBinary { 4 | 5 | //Function that decodes binary string messages 6 | public static void main(String[] args) { 7 | 8 | //Scan for binary message 9 | Scanner myObj = new Scanner(System.in); 10 | System.out.println("What is your binary input?"); 11 | String binary = myObj.nextLine(); 12 | 13 | StringBuilder finalMessage = new StringBuilder(); 14 | 15 | //Checks each byte and converts to corresponding character 16 | for (int i = 0; i < binary.length(); i += 8) { 17 | String str = binary.substring(i, i+8); 18 | finalMessage.append((char)Integer.parseInt(str, 2)); 19 | } 20 | 21 | //Prints decoded message 22 | System.out.println("Here is your message: " + finalMessage); 23 | } 24 | } 25 | 26 | -------------------------------------------------------------------------------- /Java/Algorithms/Dynamic-Programming/Fibonacci/Fibonacci.java: -------------------------------------------------------------------------------- 1 | class GFG { 2 | 3 | // Function to print N Fibonacci Number 4 | static void Fibonacci(int N) 5 | { 6 | int num1 = 0, num2 = 1; 7 | 8 | int counter = 0; 9 | 10 | // Iterate till counter is N 11 | while (counter < N) { 12 | 13 | // Print the number 14 | System.out.print(num1 + " "); 15 | 16 | // Swap 17 | int num3 = num2 + num1; 18 | num1 = num2; 19 | num2 = num3; 20 | counter = counter + 1; 21 | } 22 | } 23 | 24 | // Driver Code 25 | public static void main(String args[]) 26 | { 27 | // Given Number N 28 | int N = 10; 29 | 30 | // Function Call 31 | Fibonacci(N); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Java/Algorithms/Dynamic-Programming/Hex/ConvertHex.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | //Function that decodes hex messages 4 | class ConvertHex { 5 | public static void main(String[] args) { 6 | 7 | //Scan for hex message 8 | Scanner myObj = new Scanner(System.in); 9 | System.out.println("What is your hex input?"); 10 | String hex = myObj.nextLine(); 11 | 12 | StringBuilder finalMessage = new StringBuilder(); 13 | 14 | //Checks each hex digit and converts to ASCII character 15 | for (int i = 0; i < hex.length(); i += 2) { 16 | String str = hex.substring(i, i+2); 17 | finalMessage.append((char)Integer.parseInt(str, 16)); 18 | } 19 | 20 | //Prints decoded message 21 | System.out.println("Here is your message: " + finalMessage); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Java/Algorithms/Dynamic-Programming/readme.md: -------------------------------------------------------------------------------- 1 | ### Dynamic-Programming 2 | -------------------------------------------------------------------------------- /Java/Algorithms/Geometric-Algorithms/readme.md: -------------------------------------------------------------------------------- 1 | ### Geometric-Algorithms -------------------------------------------------------------------------------- /Java/Algorithms/Graph-Algorithms/readme.md: -------------------------------------------------------------------------------- 1 | ### Graph-Algorithms -------------------------------------------------------------------------------- /Java/Algorithms/Greedy-Algorithms/readme.md: -------------------------------------------------------------------------------- 1 | ### Greedy-Algorithms -------------------------------------------------------------------------------- /Java/Algorithms/Mathematical/Lucky Number/LuckyNumber.java: -------------------------------------------------------------------------------- 1 | // Java program to check Lucky Number 2 | import java.io.*; 3 | 4 | class GFG 5 | { 6 | public static int counter = 2; 7 | 8 | // Returns 1 if n is a lucky no. ohterwise returns 0 9 | static boolean isLucky(int n) 10 | { 11 | // variable next_position is just for readability of 12 | // the program we can remove it and use n only 13 | int next_position = n; 14 | if(counter > n) 15 | return true; 16 | if(n%counter == 0) 17 | return false; 18 | 19 | // calculate next position of input no 20 | next_position -= next_position/counter; 21 | 22 | counter++; 23 | return isLucky(next_position); 24 | } 25 | 26 | // driver program 27 | public static void main (String[] args) 28 | { 29 | int x = 5; 30 | if( isLucky(x) ) 31 | System.out.println(x+" is a lucky no."); 32 | else 33 | System.out.println(x+" is not a lucky no."); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Java/Algorithms/Mathematical/Median.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | import java.lang.*; 4 | class Median 5 | { 6 | public static void main(String args[]) 7 | { 8 | Scanner sc=new Scanner(System.in); 9 | System.out.println("Enter the number of elements in the array"); 10 | int n=sc.nextInt(); 11 | double[] input=new double[n]; 12 | System.out.println("Enter the elements of the array(" +n+ "): "); 13 | for(int i=0;i arr[j+1]) //if current element is larger than next element, swap them 18 | { 19 | swap(arr, j, j+1); 20 | sorted = false; // to check if further bubbling is necessary 21 | } 22 | } 23 | mark--; //Length for iteration can be decremented for each pass since the largest element is bubbled to the end of the array 24 | } 25 | return arr; 26 | } 27 | 28 | void swap(int[] arr, int m, int n) 29 | { 30 | //basic swapping method 31 | 32 | int temp = arr[m]; 33 | arr[m] = arr[n]; 34 | arr[n] = temp; 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /Java/Algorithms/Sorting-Algorithms/BubbleSort/RecursiveBubbleSort.java: -------------------------------------------------------------------------------- 1 | public class Program { 2 | public static void main(String[] args) { 3 | int[] arr = bubbleSort(new int[] { 64, 34, 25, 12, 22, 11, 90 }); 4 | for (int i = 0; i < arr.length; System.out.println(arr[i++])) 5 | ; 6 | 7 | } 8 | 9 | public static int[] bubbleSort(int[] arr) { 10 | for (int i = 0; i < arr.length; i++) { 11 | try { 12 | int num = arr[i]; 13 | if (arr[i + 1] < num) { 14 | arr[i] = arr[i + 1]; 15 | arr[i + 1] = num; 16 | bubbleSort(arr); 17 | } 18 | } catch (IndexOutOfBoundsException e) { 19 | continue; 20 | } 21 | } 22 | return arr; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Java/Algorithms/Sorting-Algorithms/CountingSort.java: -------------------------------------------------------------------------------- 1 | static void countSort(int[] arr) 2 | { 3 | int max = Arrays.stream(arr).max().getAsInt(); 4 | int min = Arrays.stream(arr).min().getAsInt(); 5 | int range = max - min + 1; 6 | int count[] = new int[range]; 7 | int output[] = new int[arr.length]; 8 | for (int i = 0; i < arr.length; i++) 9 | { 10 | count[arr[i] - min]++; 11 | } 12 | 13 | for (int i = 1; i < count.length; i++) 14 | { 15 | count[i] += count[i - 1]; 16 | } 17 | 18 | for (int i = arr.length - 1; i >= 0; i--) 19 | { 20 | output[count[arr[i] - min] - 1] = arr[i]; 21 | count[arr[i] - min]--; 22 | } 23 | 24 | for (int i = 0; i < arr.length; i++) 25 | { 26 | arr[i] = output[i]; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Java/Algorithms/Sorting-Algorithms/HeapSort/heapSort.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | public class heapSort { 4 | public static void heapify(int[] arr,int n,int i) { 5 | int large=i; 6 | int x,l=2*i+1; 7 | int r=2*i+2; 8 | if(l < n && arr[l] > arr[large]) 9 | large=l; 10 | if(r < n && arr[r] > arr[large]) 11 | large=r; 12 | if(large!=i) { 13 | x=arr[large]; 14 | arr[large]=arr[i]; 15 | arr[i]=x; 16 | heapify(arr,n,large); 17 | } 18 | } 19 | public static void sort(int[] arr) { 20 | int i,n=arr.length; 21 | for(i=n/2-1;i>=0;i--) { 22 | heapify(arr,n,i); 23 | } 24 | for(i=n-1;i>0;i--) { 25 | int temp=arr[0]; 26 | arr[0]=arr[i]; 27 | arr[i]=temp; 28 | heapify(arr,i,0); 29 | } 30 | } 31 | public static void main(String[] args) { 32 | // TODO Auto-generated method stub 33 | int arr[]= {5,0,2,7,9,1,3,8,4}; 34 | sort(arr); 35 | for(int i=0;i0 && intarray[i-1]>newelement;i--) { 21 | intarray[i] = intarray[i-1]; 22 | } 23 | intarray[i] = newelement; 24 | // You can remove these comments and watch the iterations for better understanding of this Algorithm 25 | // for(int j =0;j max) 11 | max = arr[a]; 12 | if(arr[a] < min) 13 | min = arr[a]; 14 | } 15 | 16 | range = max - min + 1; 17 | int[] phole = new int[range]; 18 | Arrays.fill(phole, 0); 19 | 20 | for(i = 0; i0) 28 | arr[index++]=j+min; 29 | 30 | } 31 | -------------------------------------------------------------------------------- /Java/Algorithms/Sorting-Algorithms/QuickSort.java: -------------------------------------------------------------------------------- 1 | public class QuickSort { 2 | 3 | static int partition(int[] arr, int low, it high) { 4 | int pivot = arr[high]; 5 | int i = low - 1; 6 | for (int j = low; i < high; j++) { 7 | if (arr[j] < pivot) { 8 | i++; 9 | 10 | int temp = arr[i]; 11 | arr[i] = arr[j]; 12 | arr[j] = temp; 13 | } 14 | } 15 | int temp = arr[i + 1]; 16 | arr[i + 1] = arr[high]; 17 | arr[high] = temp; 18 | 19 | return i + 1; 20 | 21 | } 22 | 23 | void sort(int[] arr, int low, int high) { 24 | if (low < high) { 25 | 26 | int p = partition(arr, low, high); 27 | 28 | sort(arr, low, p - 1); 29 | sort(arr, p + 1, high); 30 | } 31 | 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /Java/Algorithms/Sorting-Algorithms/SelectionSort/SelectionSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class SelectionSort { 4 | 5 | 6 | public static void main(String[] args) { 7 | 8 | 9 | Scanner s = new Scanner(System.in); 10 | System.out.print("Enter the No of Elements:"); 11 | int n = s.nextInt(); 12 | int[] intarray = new int[n]; 13 | System.out.print("Enter the elements:" ); 14 | for(int i=0;i0;unsoretedarrayindex-- ) { 19 | 20 | int largest=0; 21 | 22 | for(int i=1;i<=unsoretedarrayindex;i++) { 23 | if(intarray[i]>intarray[largest]) { 24 | largest=i; 25 | } 26 | swap(intarray, largest,unsoretedarrayindex); 27 | 28 | } 29 | // You can remove these comments and watch the iterations for better understanding of this Algorithm 30 | // for(int i =0;i set; 5 | 6 | TreeSetHeap() { 7 | this.set = new TreeSet(); 8 | } 9 | 10 | public int size() { 11 | return this.set.size(); 12 | } 13 | 14 | public boolean empty() { 15 | return this.set.isEmpty(); 16 | } 17 | 18 | public void insert(int v) { 19 | this.set.add((Integer)v); 20 | } 21 | 22 | 23 | 24 | public int deleteMin() { 25 | int min = this.set.first(); 26 | this.set.remove(this.set.first()); 27 | return min; 28 | } 29 | 30 | public int findMin() { 31 | if (this.empty()) 32 | return -1; 33 | return (int)(this.set.first()); 34 | } 35 | 36 | public void delete(int i) { 37 | this.set.remove((Integer)i); 38 | 39 | } 40 | } 41 | 42 | -------------------------------------------------------------------------------- /Java/Data-Structures/Stack/node/SingleNode.java: -------------------------------------------------------------------------------- 1 | package node; 2 | 3 | public class SingleNode { 4 | private int value; 5 | private SingleNode next; 6 | 7 | public int getValue() { 8 | return value; 9 | } 10 | 11 | public void setValue(int value) { 12 | this.value = value; 13 | } 14 | 15 | public SingleNode getNext() { 16 | return next; 17 | } 18 | 19 | public void setNext(SingleNode next) { 20 | this.next = next; 21 | } 22 | 23 | @Override 24 | public String toString() { 25 | return value + ""; 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /Java/Data-Structures/Stack/stack/StackByArrayMain.java: -------------------------------------------------------------------------------- 1 | package stack; 2 | 3 | public class StackByArrayMain { 4 | public static void main(String[] args) { 5 | 6 | 7 | System.out.println("Creating a stack of size 5..."); 8 | StackByArray stack = new StackByArray(5); 9 | 10 | 11 | System.out.println("Pushing 6 values in the Stack..."); 12 | for(int i=0; i<=5; i++) { 13 | stack.push(i*10); 14 | } 15 | 16 | 17 | System.out.println("Peeking value from stack"); 18 | stack.peekOperation(); 19 | 20 | 21 | System.out.println("Poping 6 values from the Stack..."); 22 | for(int i=0; i<=5; i++) { 23 | stack.pop(); 24 | } 25 | 26 | 27 | System.out.println("Deleting the Stack..."); 28 | stack.deleteStack(); 29 | 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Java/Data-Structures/Stack/stack/StackByLinkedList.java: -------------------------------------------------------------------------------- 1 | package stack; 2 | import linkedList.SingleLinkedList; 3 | import node.SingleNode; 4 | 5 | public class StackByLinkedList { 6 | 7 | SingleLinkedList list; 8 | 9 | 10 | //constructor 11 | public StackByLinkedList() { 12 | list = new SingleLinkedList(); 13 | }//end of method 14 | 15 | 16 | public void push(int value) { 17 | if(list.getHead()== null) { 18 | list.createSingleLinkedList(value); 19 | }else { 20 | list.insertInLinkedList(value, 0); 21 | } 22 | System.out.println("Inserted " + value + " in Stack !"); 23 | }//end of method 24 | 25 | 26 | public int pop() { 27 | int value = -1; 28 | if (isEmpty()) { 29 | System.out.println("Stack underflow error!!"); 30 | } else { 31 | value = list.getHead().getValue(); 32 | list.deletionOfNode(0); 33 | } 34 | return value; 35 | }// end of method 36 | 37 | 38 | public boolean isEmpty() { 39 | if (list.getHead() == null) 40 | return true; 41 | else 42 | return false; 43 | }// end of method 44 | 45 | 46 | public int peek() { 47 | if (!isEmpty()) 48 | return list.getHead().getValue(); 49 | else { 50 | System.out.println("The stack is empty!!"); 51 | return -1; 52 | } 53 | }// end of method 54 | 55 | 56 | public void deleteStack() { 57 | list.setHead(null); 58 | }//end of method 59 | 60 | }//end of method 61 | -------------------------------------------------------------------------------- /Java/Data-Structures/Stack/stack/StackByLinkedListMain.java: -------------------------------------------------------------------------------- 1 | package stack; 2 | 3 | public class StackByLinkedListMain { 4 | 5 | public static void main(String[] args) { 6 | 7 | StackByLinkedList stack = new StackByLinkedList(); 8 | 9 | System.out.println("Pushing 10 values into stack"); 10 | for (int i = 1; i <= 10; i++) { 11 | stack.push(i * 10); 12 | } 13 | System.out.println(); 14 | 15 | System.out.println("Peeking value"); 16 | System.out.println(stack.peek()); 17 | System.out.println(); 18 | 19 | System.out.println("Poping 11 values from stack"); 20 | for (int i = 1; i <= 11; i++) { 21 | System.out.println(stack.pop()); 22 | } 23 | System.out.println(); 24 | 25 | } 26 | 27 | } -------------------------------------------------------------------------------- /Java/Data-Structures/Trie/Trie.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class Trie{ 3 | //Quick Trie Implementation modify according to needs.. 4 | Map child; 5 | boolean isEnd; 6 | TrieNode(){ 7 | child = new HashMap(); 8 | } 9 | void addString(Trie root,String str){ 10 | TrieNode r = root; 11 | for(char ch:str.toCharArray()){ 12 | if(!r.child.containsKey(ch)) 13 | r.child.put(ch,new TrieNode()); 14 | r = r.child.get(ch); 15 | } 16 | r.isEnd = true; 17 | } 18 | boolean checkPrefix(TrieNode root,String prefix){ 19 | TrieNode r = root; 20 | for(char ch : prefix.toCharArray()){ 21 | if(!r.child.containsKey(ch)) 22 | return false; 23 | r = r.child.get(ch); 24 | } 25 | return true; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Divyanshu Bargali 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Python/Algorithms/Backtracking/Backtracking_in_Python.py: -------------------------------------------------------------------------------- 1 | #Backtracking is a form of recursion. But it involves choosing only option out of any possibilities. We begin by choosing an option and backtrack from it, if we reach a state where we conclude that this specific option does not give the required solution. We repeat these steps by going across each available option until we get the desired solution. 2 | #This is an example of finding all possible order of arrangements of a given set of letters. When we choose a pair we apply backtracking to verify if that exact pair has already been created or not. If not already created, the pair is added to the answer list else it is ignored. 3 | def permute(list, s): 4 | if list == 1: 5 | return s 6 | else: 7 | return [ y + x 8 | for y in permute(1, s) 9 | for x in permute(list - 1, s) 10 | ] 11 | 12 | print(permute(1, ["a","b","c"])) 13 | print(permute(2, ["a","b","c"])) 14 | 15 | #The ouput should be : 16 | #['a', 'b', 'c'] 17 | #['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc'] 18 | #Contributed by The-N3rd. Thank you. -------------------------------------------------------------------------------- /Python/Algorithms/Backtracking/NQueens.py: -------------------------------------------------------------------------------- 1 | # Function to check if generated sequence is valid or not 2 | def isValid(board,rn,cn): 3 | 4 | #Column 5 | for i in range(rn): 6 | if board[i][cn]=='Q': 7 | return False 8 | 9 | #Diagonal \ 10 | r=rn 11 | c=cn 12 | while r>=0 and c>=0: 13 | if board[r][c]=='Q': 14 | return False 15 | r-=1 16 | c-=1 17 | 18 | #Diagonal / 19 | r=rn 20 | c=cn 21 | while r>=0 and c sum) : 17 | return isSubsetSum(set, n - 1, sum); 18 | 19 | # else, check if sum can be obtained 20 | # by any of the following 21 | # (a) including the last element 22 | # (b) excluding the last element 23 | return isSubsetSum( 24 | set, n-1, sum) or isSubsetSum( 25 | set, n-1, sum-set[n-1]) 26 | 27 | 28 | # Driver program to test above function 29 | set = [3, 34, 4, 12, 5, 2] 30 | sum = int(input()) #input sum 31 | n = len(set) 32 | if (isSubsetSum(set, n, sum) == True) : 33 | print("Found a subset with given sum") 34 | else : 35 | print("No subset with given sum") 36 | 37 | -------------------------------------------------------------------------------- /Python/Algorithms/Dynamic-Programming/travelling_salesman_problem.py: -------------------------------------------------------------------------------- 1 | # Python3 program to implement traveling salesman 2 | # problem using naive approach. 3 | from sys import maxsize 4 | from itertools import permutations 5 | V = 4 6 | 7 | # implementation of traveling Salesman Problem 8 | def travellingSalesmanProblem(graph, s): 9 | 10 | # store all vertex apart from source vertex 11 | vertex = [] 12 | for i in range(V): 13 | if i != s: 14 | vertex.append(i) 15 | 16 | # store minimum weight Hamiltonian Cycle 17 | min_path = maxsize 18 | next_permutation=permutations(vertex) 19 | for i in next_permutation: 20 | 21 | # store current Path weight(cost) 22 | current_pathweight = 0 23 | 24 | # compute current path weight 25 | k = s 26 | for j in i: 27 | current_pathweight += graph[k][j] 28 | k = j 29 | current_pathweight += graph[k][s] 30 | 31 | # update minimum 32 | min_path = min(min_path, current_pathweight) 33 | 34 | return min_path 35 | 36 | 37 | # Driver Code 38 | if __name__ == "__main__": 39 | 40 | # matrix representation of graph 41 | graph = [[0, 10, 15, 20], [10, 0, 35, 25], 42 | [15, 35, 0, 30], [20, 25, 30, 0]] 43 | s = 0 44 | print(travellingSalesmanProblem(graph, s)) 45 | -------------------------------------------------------------------------------- /Python/Algorithms/Face_mask_detector/LOGO.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/div-bargali/Data-Structures-and-Algorithms/7bc4af2022098e850078ef1c556fbadd51583ddc/Python/Algorithms/Face_mask_detector/LOGO.PNG -------------------------------------------------------------------------------- /Python/Algorithms/Face_mask_detector/face_detector/res10_300x300_ssd_iter_140000.caffemodel: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/div-bargali/Data-Structures-and-Algorithms/7bc4af2022098e850078ef1c556fbadd51583ddc/Python/Algorithms/Face_mask_detector/face_detector/res10_300x300_ssd_iter_140000.caffemodel -------------------------------------------------------------------------------- /Python/Algorithms/Face_mask_detector/mask_detector.model: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/div-bargali/Data-Structures-and-Algorithms/7bc4af2022098e850078ef1c556fbadd51583ddc/Python/Algorithms/Face_mask_detector/mask_detector.model -------------------------------------------------------------------------------- /Python/Algorithms/Face_mask_detector/plot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/div-bargali/Data-Structures-and-Algorithms/7bc4af2022098e850078ef1c556fbadd51583ddc/Python/Algorithms/Face_mask_detector/plot.png -------------------------------------------------------------------------------- /Python/Algorithms/Face_mask_detector/requirements.txt: -------------------------------------------------------------------------------- 1 | tensorflow>=1.14 2 | keras==2.3.1 3 | imutils==0.5.3 4 | numpy==1.18.2 5 | opencv-python==4.1.0.25 6 | matplotlib==3.2.1 7 | scipy==1.4.1 8 | -------------------------------------------------------------------------------- /Python/Algorithms/Geometric-Algorithms/readme.md: -------------------------------------------------------------------------------- 1 | ### Geometric-Algorithms -------------------------------------------------------------------------------- /Python/Algorithms/Graph-Algorithms/Kruskal/Kruskal.py: -------------------------------------------------------------------------------- 1 | from min_heap import MinHeap 2 | from UnionFind import UnionFind 3 | vertices = set() 4 | def Kruskals(G): 5 | #put all the vertices into a set so that we don't have duplicates in the parent or rank arrays 6 | for i in G: 7 | x = UnionFind(len(vertices)) 8 | if i[1] in vertices or i[2] not in vertices: 9 | vertices.add(i[2]) 10 | x.makeset(i[2]) 11 | print(vertices) 12 | if i[1] not in vertices or i[2] in vertices: 13 | vertices.add(i[1]) 14 | x.makeset(i[1]) 15 | print(vertices) 16 | if i[1] in vertices and i[2] in vertices: 17 | continue 18 | 19 | 20 | -------------------------------------------------------------------------------- /Python/Algorithms/Graph-Algorithms/Kruskal/KruskalDriver.py: -------------------------------------------------------------------------------- 1 | from Kruskal import Kruskals 2 | def main(): 3 | file = open("ewgraph1.txt", 'r') 4 | 5 | edges = [] 6 | linenum = 0 7 | for line in file: 8 | #store each line in a tuple 9 | linenum += 1 10 | if linenum > 2: 11 | fields = line.split(" ") 12 | edges.append((float(fields[2]),int(fields[0]),int(fields[1]))) 13 | 14 | file.close() 15 | print(edges[2]) 16 | Kruskals(edges) 17 | 18 | -------------------------------------------------------------------------------- /Python/Algorithms/Graph-Algorithms/Kruskal/ewgraph1.txt: -------------------------------------------------------------------------------- 1 | 8 2 | 16 3 | 4 5 0.35 4 | 4 7 0.37 5 | 5 7 0.28 6 | 0 7 0.16 7 | 1 5 0.32 8 | 0 4 0.38 9 | 2 3 0.17 10 | 1 7 0.19 11 | 0 2 0.26 12 | 1 2 0.36 13 | 1 3 0.29 14 | 2 7 0.34 15 | 6 2 0.40 16 | 3 6 0.52 17 | 6 0 0.58 18 | 6 4 0.93 19 | -------------------------------------------------------------------------------- /Python/Algorithms/Graph-Algorithms/Union Find/UnionFind.py: -------------------------------------------------------------------------------- 1 | 2 | class UnionFind(): 3 | def __init__(self, n): 4 | self.parent = [] 5 | self.rank = [] 6 | self.size = n 7 | def makeset(self,x): 8 | self.parent[x] = x 9 | self.rank[x]=0 10 | def find(self, x): 11 | while x != self.parent[x]: 12 | x = self.parent[x] 13 | return x 14 | def union(self,x,y): 15 | i = self.find(x) 16 | j = self.find(y) 17 | if i == j: 18 | return 19 | if rank[i] > rank[j]: 20 | parent[j] = i 21 | else: 22 | parent[i] = j 23 | if rank[i] == rank[j]: 24 | rank[j] = rank[j] + 1 25 | 26 | 27 | -------------------------------------------------------------------------------- /Python/Algorithms/Graph-Algorithms/readme.md: -------------------------------------------------------------------------------- 1 | ### Graph-Algorithms -------------------------------------------------------------------------------- /Python/Algorithms/Greedy-Algorithms/Egyptian-Fraction.py: -------------------------------------------------------------------------------- 1 | # Python3 program to print a fraction in Egyptian Form using Greedy Algorithm 2 | 3 | # import math package to use 4 | # ceiling function 5 | import math 6 | 7 | # define a function egyptianFraction 8 | # which receive parameter nr as 9 | # numerator and dr as denominator 10 | def egyptianFraction(nr, dr): 11 | 12 | print("The Egyptian Fraction " + 13 | "Representation of {0}/{1} is". 14 | format(nr, dr), end="\n") 15 | 16 | # empty list ef to store 17 | # denominator 18 | ef = [] 19 | 20 | # while loop runs until 21 | # fraction becomes 0 i.e, 22 | # numerator becomes 0 23 | while nr != 0: 24 | 25 | # taking ceiling 26 | x = math.ceil(dr / nr) 27 | 28 | # storing value in ef list 29 | ef.append(x) 30 | 31 | # updating new nr and dr 32 | nr = x * nr - dr 33 | dr = dr * x 34 | 35 | # printing the values 36 | for i in range(len(ef)): 37 | if i != len(ef) - 1: 38 | print(" 1/{0} +" . 39 | format(ef[i]), end = " ") 40 | else: 41 | print(" 1/{0}" . 42 | format(ef[i]), end = " ") 43 | 44 | # calling the function 45 | egyptianFraction(6, 14) -------------------------------------------------------------------------------- /Python/Algorithms/Greedy-Algorithms/activity_selection.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | """Prints a maximum set of activities that can be done by a 4 | single person, one at a time""" 5 | # n --> Total number of activities 6 | # start--> An array that contains start time of all activities 7 | # finish --> An array that contains finish time of all activities 8 | 9 | #utility function 10 | def compare(a): 11 | return a[1] #creturn finish time of that activity 12 | 13 | 14 | 15 | def printMaxActivities(arr,n): 16 | 17 | s_arr=sorted(arr,key=compare) #sorting the array on the basis of finish time, using the key function we have just created above 18 | 19 | 20 | print("The following activities are selected") 21 | 22 | # The first activity is always selected 23 | i = 0 24 | print(s_arr[i]) 25 | 26 | # Consider rest of the activities 27 | for j in range(n): 28 | 29 | # If this activity has start time greater than 30 | # or equal to the finish time of previously 31 | # selected activity, then select it 32 | if s_arr[j][0] >= s_arr[i][1]: 33 | print(s_arr[j]) 34 | i = j 35 | 36 | # Driver code 37 | if __name__ == '__main__': 38 | print('enter the number of activities') 39 | n=int(input()) 40 | 41 | print('enter the start time and end time of activities') 42 | print('start time___end time') 43 | arr=[] 44 | for i in range(n): 45 | arr.append(list(map(int,input().split()))) #example list [[1,3],[2,4],[4,6]] 46 | 47 | printMaxActivities(arr,n) 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /Python/Algorithms/Greedy-Algorithms/currency_denomiations.py: -------------------------------------------------------------------------------- 1 | # You enter the amount of money and the program returns the max changes of available denominations 2 | 3 | # List for Denomination of Currency and its Type 4 | denom = [2000,500,100,50,20,10,5,2,1] 5 | ctype = lambda x: "coin(s)" if x in [1,2,5] else "note(s)" 6 | def unique(l): 7 | # Just a Utility Function for Better Display of Results 8 | s = [] 9 | for i in l: 10 | if i not in s: 11 | s.append(i) 12 | return s 13 | 14 | tests = int(input("\nTest Cases : ")) 15 | for t in range(tests): 16 | val = int(input(f"\nCASE #{t+1} ::::: Enter Amount : ")) 17 | change = [] 18 | 19 | # Greedy Approach : Selecting Max Currency Value 20 | i = 0 21 | while val>0: 22 | while val n - k) : 20 | k = n - k 21 | for i in range(0 , k) : 22 | res = res * (n - i) 23 | res = res // (i + 1) 24 | 25 | return res 26 | 27 | # Driver program 28 | n = int(input("Enter no. : ")) 29 | printPascal(n) -------------------------------------------------------------------------------- /Python/Algorithms/Mathematical/Smith_number.py: -------------------------------------------------------------------------------- 1 | n = int(input("Enter a number you want to check:")) 2 | 3 | def digisum(n): 4 | return sum([int(s) for s in str(n)]) 5 | 6 | def getfactors(n): 7 | k=2 8 | result=[] 9 | while k ** 2 <= n: 10 | while n%k==0: 11 | result.append(k) 12 | n = n // k 13 | k = k +1 14 | if n > 1: 15 | result.append(n) 16 | return result 17 | 18 | 19 | if digisum(n)==sum([digisum(i) for i in getfactors(n)]): 20 | print('It is a smith number') 21 | 22 | else: 23 | print('It is not a smith number') 24 | -------------------------------------------------------------------------------- /Python/Algorithms/Mathematical/readme.md: -------------------------------------------------------------------------------- 1 | ### Mathematical -------------------------------------------------------------------------------- /Python/Algorithms/Mathematical/sieve_of_eratosthenes.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import math 3 | 4 | #function prints prime numbers in a given range 5 | 6 | def sieve(n): 7 | 8 | ar=[True for i in range(n+1)] #assume all are prime numbers where index is the number 9 | 10 | ar[0],ar[1]=False,False #1 is not prime and zero is not a natural number 11 | 12 | p=2 #starting with 2 as it is the first prime number 13 | 14 | while p*p<=n: 15 | 16 | if ar[p]==True: 17 | 18 | for i in range(p*p,n+1,p): 19 | ar[i]=False #every number which is a multiple of p is not a prime number 20 | 21 | p+=1 22 | 23 | ans=[] 24 | 25 | for i in range(2,n+1): 26 | if ar[i]==True: #add the numbers in answer array and then return it 27 | ans.append(i) 28 | return ans 29 | 30 | 31 | if __name__ == '__main__': 32 | print('enter the value of n') 33 | n=int(input()) 34 | 35 | print('prime numbers lesser or equals to', n ,'are') 36 | print(sieve(n)) 37 | 38 | 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /Python/Algorithms/Pattern-Searching/readme.md: -------------------------------------------------------------------------------- 1 | ### Pattern-Searching -------------------------------------------------------------------------------- /Python/Algorithms/Randomized-Algorithms/readme.md: -------------------------------------------------------------------------------- 1 | ### Randomized-Algorithms -------------------------------------------------------------------------------- /Python/Algorithms/Searching-Algorithms/binary_Search_iterative.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | 4 | ''' variable assignment = 5 | 6 | -left is left index of array/subarray 7 | -right is right index of array/subarray 8 | -s_element is element to be searched in the array 9 | ''' 10 | 11 | # The function returns location of s_element in given array arr 12 | # if present, else returns -1 13 | 14 | def binary_search(arr, left, right, s_element): 15 | 16 | while left <= right: 17 | 18 | mid = (left + right) // 2; 19 | 20 | # Check if x is present at mid 21 | if arr[mid] == s_element: 22 | return mid 23 | 24 | # If x is greater, ignore left half 25 | elif arr[mid] < s_element: 26 | left = mid + 1 27 | 28 | # If x is smaller, ignore right half 29 | else: 30 | right = mid - 1 31 | 32 | # If we reach here, then the element 33 | # was not present 34 | return -1 35 | 36 | #driver code 37 | if __name__ == '__main__': 38 | print('enter the number of elements') 39 | n=int(input()) 40 | 41 | print('\nenter the elements in a single line with space') 42 | 43 | arr=list(map(int,input().split())) 44 | 45 | print('\nenter the element to be searched') 46 | s=int(input()) 47 | 48 | result=binary_search(arr,0,n-1,s) #calling function 49 | 50 | if result==-1: 51 | print('\nelement not present') 52 | else: 53 | print('\nelement is present at',result) 54 | 55 | 56 | -------------------------------------------------------------------------------- /Python/Algorithms/Searching-Algorithms/exponential_search.py: -------------------------------------------------------------------------------- 1 | # Exponential search 2 | 3 | # Function to perform recursive binary search 4 | def binary_search(array,low,high,value): 5 | if high>= low: 6 | mid=int(low + ( high-low )//2) 7 | if array[mid] == value: 8 | return mid 9 | if array[mid] > value: 10 | return binary_search(array,low,mid - 1,value) 11 | else: 12 | return binary_search(array,mid + 1,high,value) 13 | if high= n: 29 | return -1 30 | 31 | # Doing a linear search for s_element in 32 | # block beginning with prev. 33 | while arr[int(prev)] < s_element: 34 | prev += 1 35 | 36 | # If we reached next block or end 37 | # of array, element is not present. 38 | if prev == min(step, n): 39 | return -1 40 | 41 | # If element is found 42 | if arr[int(prev)] == s_element: 43 | return prev 44 | 45 | return -1 46 | 47 | # Driver code 48 | 49 | if __name__ == '__main__': 50 | print('enter the number of elements') 51 | n=int(input()) 52 | 53 | print('\nenter the elements in a single line with space') 54 | 55 | arr=list(map(int,input().split())) 56 | 57 | print('\nenter the element to be searched') 58 | s=int(input()) 59 | 60 | result=jump_search(arr,s,n) #calling function 61 | 62 | print("Number" , s, "is at index" ,"%.0f"%result) 63 | 64 | 65 | -------------------------------------------------------------------------------- /Python/Algorithms/Searching-Algorithms/linear_Search.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | 4 | ''' variable assignment = 5 | 6 | -n is size of array 7 | -s_element is element to be searched in the array 8 | ''' 9 | 10 | 11 | # The function returns location of s_element in given array arr 12 | # if present, else returns -1 13 | 14 | def linear_search(arr,s_element): 15 | n=len(arr) 16 | for i in range(n): #comparing each element with s_element and if found then return its index 17 | if arr[i]==s_element: 18 | return i 19 | return -1 20 | 21 | # Driver code 22 | 23 | if __name__ == '__main__': 24 | print('enter the number of elements') 25 | n=int(input()) 26 | 27 | print('\nenter the elements in a single line with space') 28 | 29 | arr=list(map(int,input().split())) 30 | 31 | print('\nenter the element to be searched') 32 | s=int(input()) 33 | 34 | result=linear_search(arr,s) #calling function 35 | 36 | print("Number" , s, "is at index" ,"%.0f"%result) -------------------------------------------------------------------------------- /Python/Algorithms/Searching-Algorithms/readme.md: -------------------------------------------------------------------------------- 1 | ### Searching-Algorithms -------------------------------------------------------------------------------- /Python/Algorithms/Sorting-Algorithms/bogo_sort.py: -------------------------------------------------------------------------------- 1 | # ##BOGO SORT## 2 | # This is a Bogo Sort sorting algorithm implemented in Python 3 | # It is a really (really) slow algorithm, and has expected time complexity of n!, given that random.shuffle is uniform. 4 | 5 | import random 6 | 7 | # Checks if a list is sorted. 8 | def is_sorted(lst): 9 | for i in range(1,len(lst)): 10 | if lst[i-1] > lst[i]: 11 | return False 12 | return True 13 | 14 | # Sorts and returns the list 15 | def bogo_sort(lst): 16 | while not is_sorted(lst): 17 | random.shuffle(lst) 18 | return lst 19 | 20 | # Driver 21 | array = [53, 43, 67, 0, 1, 4, 5, -1, 0.43] 22 | print(bogo_sort(array)) 23 | 24 | 25 | -------------------------------------------------------------------------------- /Python/Algorithms/Sorting-Algorithms/bubble_sort.py: -------------------------------------------------------------------------------- 1 | # function to sort list of integers in place 2 | # flag ascending is used to determine the sorting type i.e. ascending or descending 3 | # in bubble sort, the max or min value bubbles up to the end 4 | 5 | # time complexity = O(n^2), but better than selection since best case complexity is O(n) 6 | 7 | def bubbleSort(a, ascending=True): 8 | n = len(a) 9 | for i in range(n): 10 | for j in range(n-i-1): 11 | if ascending: 12 | if a[j] > a[j+1]: 13 | # element bubbles up one index 14 | a[j], a[j+1] = a[j+1], a[j] 15 | else: 16 | if -a[j] > -a[j+1]: 17 | # element bubbles up one index 18 | a[j], a[j+1] = a[j+1], a[j] 19 | 20 | # driver code 21 | if __name__ == "__main__": 22 | # input a list of space separated integers 23 | sort_order = input("Enter 'd' for descending order of sort (by default ascending order is selected): ") 24 | l = list(map(int, input("Enter list to sort: ").split(" "))) 25 | 26 | print("Before sorting:", l) 27 | if sort_order == 'd': 28 | bubbleSort(l, False) 29 | print("Sorting in descending order...") 30 | else: 31 | bubbleSort(l) 32 | print("Sorting in ascending order...") 33 | print("After sorting:", l) 34 | -------------------------------------------------------------------------------- /Python/Algorithms/Sorting-Algorithms/bucket_sort.py: -------------------------------------------------------------------------------- 1 | # Bucket sort Python 2 | def insertionSort(b): 3 | for i in range(1, len(b)): 4 | up = b[i] 5 | j = i - 1 6 | while j >= 0 and b[j] > up: 7 | b[j + 1] = b[j] 8 | j -= 1 9 | b[j + 1] = up 10 | return b 11 | 12 | def bucketSort(x): 13 | arr = [] 14 | slot_num = 10 # 10 means 10 slots, each 15 | # slot's size is 0.1 16 | for i in range(slot_num): 17 | arr.append([]) 18 | 19 | # Put array elements in different buckets 20 | for j in x: 21 | index_b = int(slot_num * j) 22 | arr[index_b].append(j) 23 | 24 | # Sort individual buckets 25 | for i in range(slot_num): 26 | arr[i] = insertionSort(arr[i]) 27 | 28 | # concatenate the result 29 | k = 0 30 | for i in range(slot_num): 31 | for j in range(len(arr[i])): 32 | x[k] = arr[i][j] 33 | k += 1 34 | return x 35 | 36 | # Driver code 37 | array = [0.678, 0.312, 0.912, 0.555, 0.432] 38 | print("Array is: ") 39 | print(array) 40 | print("Sorted array is: ") 41 | print(bucketSort(array)) -------------------------------------------------------------------------------- /Python/Algorithms/Sorting-Algorithms/heapsort.py: -------------------------------------------------------------------------------- 1 | # Python program for implementation of heap Sort 2 | 3 | # To heapify subtree rooted at index i. 4 | # n is size of heap 5 | def heapify(arr, n, i): 6 | largest = i # Initialize largest as root 7 | l = 2 * i + 1 # left = 2*i + 1 8 | r = 2 * i + 2 # right = 2*i + 2 9 | 10 | # See if left child of root exists and is 11 | # greater than root 12 | if l < n and arr[i] < arr[l]: 13 | largest = l 14 | 15 | # See if right child of root exists and is 16 | # greater than root 17 | if r < n and arr[largest] < arr[r]: 18 | largest = r 19 | 20 | # Change root, if needed 21 | if largest != i: 22 | arr[i],arr[largest] = arr[largest],arr[i] # swap 23 | 24 | # Heapify the root. 25 | heapify(arr, n, largest) 26 | 27 | # The main function to sort an array of given size 28 | def heapSort(arr): 29 | n = len(arr) 30 | 31 | # Build a maxheap. 32 | # Since last parent will be at ((n//2)-1) we can start at that location. 33 | for i in range(n // 2 - 1, -1, -1): 34 | heapify(arr, n, i) 35 | 36 | # One by one extract elements 37 | for i in range(n-1, 0, -1): 38 | arr[i], arr[0] = arr[0], arr[i] # swap 39 | heapify(arr, i, 0) 40 | 41 | # Driver code to test above 42 | arr = [ 12, 11, 13, 5, 6, 7] 43 | heapSort(arr) 44 | n = len(arr) 45 | print ("Sorted array is") 46 | for i in range(n): 47 | print ("%d" %arr[i]), 48 | 49 | -------------------------------------------------------------------------------- /Python/Algorithms/Sorting-Algorithms/insertion_sort.py: -------------------------------------------------------------------------------- 1 | # function to sort list of integers in place 2 | # flag ascending is used to determine the sorting type i.e. ascending or descending 3 | # insertion sort inserts elements into the left part of the array such that the left part is always sorted 4 | 5 | # time complexity = O(n^2), but better than selection since best case complexity is O(n) 6 | 7 | def insertionSort(a, ascending=True): 8 | n = len(a) 9 | # ranging from 1 and not 0 because 10 | # a[0] by itself is always sorted 11 | for i in range(1, n): 12 | key = a[i] 13 | j = i-1 14 | 15 | while j > -1: 16 | if ascending: 17 | if key < a[j]: 18 | a[j], a[j+1] = a[j+1], a[j] 19 | else: 20 | break 21 | else: 22 | # for descenfing sort just compare -1 * value of elements 23 | if -key < -a[j]: 24 | a[j], a[j+1] = a[j+1], a[j] 25 | else: 26 | break 27 | j -= 1 28 | a[j+1] = key 29 | 30 | 31 | # driver code 32 | if __name__ == "__main__": 33 | # input a list of space separated integers 34 | sort_order = input("Enter 'd' for descending order of sort (by default ascending order is selected): ") 35 | l = list(map(int, input("Enter list to sort: ").split(" "))) 36 | 37 | print("Before sorting:", l) 38 | if sort_order == 'd': 39 | insertionSort(l, False) 40 | print("Sorting in descending order...") 41 | else: 42 | insertionSort(l) 43 | print("Sorting in ascending order...") 44 | print("After sorting:", l) 45 | -------------------------------------------------------------------------------- /Python/Algorithms/Sorting-Algorithms/pigeonhole_sort.py: -------------------------------------------------------------------------------- 1 | # Python method to implement the pigeonhole sorting method on an array of integers 2 | # Sorts the original array in ascending order 3 | 4 | def pigeonhole_sort(arr): 5 | 6 | # Create empty pigeonholes, each pigeonhole containing an empty array 7 | arr_range = max(arr) - min(arr) 8 | pigeonholes = [[] for _ in range(arr_range + 1)] 9 | 10 | # Assign elements of the original array to the correct pigeonhole 11 | for i in arr: 12 | pigeonholes[i - min(arr)].append(i) 13 | 14 | # Reassign elements from pigeonholes back into original array 15 | arr.clear() 16 | for pigeonhole in pigeonholes: 17 | for i in pigeonhole: 18 | arr.append(i) 19 | 20 | # Driver code 21 | if __name__ == "__main__": 22 | 23 | # input a list of space separated values 24 | values = list(map(int, input("Enter list to sort: ").split())) 25 | 26 | print("Before sorting:", values) 27 | pigeonhole_sort(values) 28 | print("After sorting:", values) 29 | -------------------------------------------------------------------------------- /Python/Algorithms/Sorting-Algorithms/readme.md: -------------------------------------------------------------------------------- 1 | ### Sorting-Algorithms -------------------------------------------------------------------------------- /Python/Algorithms/Sorting-Algorithms/selection_sort.py: -------------------------------------------------------------------------------- 1 | # function to sort list of integers in place 2 | # flag ascending is used to determine the sorting type i.e. ascending or descending 3 | # selection sort selects the i-th minimun or i-th maximum element to be placed in index i 4 | 5 | # time complexity = O(n^2) even fro best case 6 | 7 | def selectionSort(a, ascending=True): 8 | n = len(a) 9 | # ranging to n-1 and not n because 10 | # if we put all the other elements in their right positions, 11 | # the last elemet will be in the right position too 12 | for i in range(n-1): 13 | index = i 14 | # find index of minimum/ maximum value on the right side 15 | for j in range(i+1, n): 16 | if ascending: 17 | if a[j] < a[i]: 18 | index = j 19 | else: 20 | if -a[j] < -a[i]: 21 | index = j 22 | # swap a[index] with a[i] 23 | a[index], a[i] = a[i], a[index] 24 | 25 | 26 | 27 | # driver code 28 | if __name__ == "__main__": 29 | # input a list of space separated integers 30 | sort_order = input("Enter 'd' for descending order of sort (by default ascending order is selected): ") 31 | l = list(map(int, input("Enter list to sort: ").split(" "))) 32 | 33 | print("Before sorting:", l) 34 | if sort_order == 'd': 35 | selectionSort(l, False) 36 | print("Sorting in descending order...") 37 | else: 38 | selectionSort(l) 39 | print("Sorting in ascending order...") 40 | print("After sorting:", l) 41 | -------------------------------------------------------------------------------- /Python/Algorithms/Sorting-Algorithms/shell_sort.py: -------------------------------------------------------------------------------- 1 | # Python program for implementation of Shell Sort 2 | 3 | # Shell sort is an algorithm that first sorts the elements far apart 4 | # from each other and successively reduces the interval 5 | # between the elements to be sorted. It is a generalized version of insertion sort.''' 6 | 7 | def shellSort(values): 8 | 9 | # Start with a somewhat big gap, then reduce the gap 10 | n = len(values) 11 | gap = n//2 12 | 13 | # Do a gapped insertion sort for this gap size. 14 | # The first gap elements are already in gapped 15 | # order keep adding one more element until the entire array 16 | # is gap sorted 17 | while gap > 0: 18 | 19 | for i in range(gap,n): 20 | 21 | # add a[i] to the elements that have been gap sorted 22 | # save a[i] in temp and make a hole at position i 23 | temp = values[i] 24 | 25 | # shift earlier gap-sorted elements up until the correct 26 | # location if a[i] is found 27 | j = i 28 | while j >= gap and values[j-gap] >temp: 29 | values[j] = values[j-gap] 30 | j -= gap 31 | 32 | # put temporary variable in its correct location 33 | values[j] = temp 34 | gap //= 2 35 | 36 | 37 | # Insert Test Values 38 | values = [1, 2, 4, 12, 34, 54, 2, 3, 9, 15, 20] 39 | n = len(values) 40 | 41 | print ("Array before sorting: "+ str(values)) 42 | 43 | shellSort(values) 44 | 45 | print ("Array after sorting:"+ str(values)) 46 | 47 | -------------------------------------------------------------------------------- /Python/DataStructures/Array/LUDecompositionMatrix.py: -------------------------------------------------------------------------------- 1 | #function for finding lower and upper decompositions 2 | def LU(mat, n): 3 | 4 | #initialising 5 | low = [[0 for x in range(n)] 6 | for y in range(n)] 7 | up = [[0 for x in range(n)] 8 | for y in range(n)] 9 | 10 | #Decompose the matrix into Upper and Lower triangular matrix 11 | for i in range(n): 12 | 13 | #Upper Triangle 14 | for k in range(i, n): 15 | 16 | #do sum of L(i, j) * U(j, k) 17 | sum = 0 18 | for j in range(i): 19 | sum += (low[i][j] * up[j][k]) 20 | 21 | #finding U(i, k) 22 | up[i][k] = mat[i][k] - sum 23 | 24 | #Lower Triangle 25 | for k in range(i, n): 26 | if (i == k): 27 | low[i][i] = 1 # Diagonal 1 28 | else: 29 | 30 | #Sum of L(k, j) * U(j, i) 31 | sum = 0 32 | for j in range(i): 33 | sum += (low[k][j] * up[j][i]) 34 | 35 | #finding L(k, i) 36 | low[k][i] = int((mat[k][i] - sum) / 37 | up[i][i]) 38 | 39 | 40 | print("Lower Triangular\t\tUpper Triangular") 41 | 42 | #sow the result 43 | for i in range(n): 44 | 45 | #Lower triangle 46 | for j in range(n): 47 | print(low[i][j], end = "\t") 48 | print("", end = "\t") 49 | 50 | #Upper triangle 51 | for j in range(n): 52 | print(up[i][j], end = "\t") 53 | print("") 54 | 55 | #set the required matrix 56 | mat = [[4, -1, 0], 57 | [-1, 4, -1], 58 | [0, -1, 4]] 59 | 60 | #call the function with the matrix 61 | LU(mat, 3) 62 | -------------------------------------------------------------------------------- /Python/DataStructures/Queue/Queue.py: -------------------------------------------------------------------------------- 1 | #ryanvarghese 2 | queue = [] 3 | while 1: 4 | print("Enter a number for the following functionalites "+"1 for Push and 2 for Pop") 5 | choice = input() 6 | 7 | 8 | # Adding elements to the queue 9 | def Push(): 10 | print("Enter the element you want to push into the queue") 11 | element= input() 12 | queue.append(element) 13 | 14 | # Removing elements from the queue 15 | def Remove(): 16 | print("\nElements dequeued from queue") 17 | print(queue.pop(0)) 18 | 19 | if (choice == "1"): 20 | Push() 21 | elif(choice == "2"): 22 | #to check if the queue is empty 23 | if(len(queue)==0): 24 | print("list is empty") 25 | #if the queue is not empty then pop the element 26 | else: 27 | Remove() 28 | 29 | print("Initial queue") 30 | print(queue) 31 | 32 | #displays the queue after removal of elements 33 | print("\nQueue after removing elements") 34 | print(queue) -------------------------------------------------------------------------------- /Python/DataStructures/Queue/queue_via_stack.py: -------------------------------------------------------------------------------- 1 | # Implementing a queue using two stacks 2 | 3 | class queue: 4 | def __init__(self): 5 | self.stack1 = [] 6 | self.stack2 = [] 7 | 8 | # push element into the queue 9 | def push(self, x): 10 | self.stack1.append(x) 11 | 12 | # pop element form the queue 13 | def pop_op(self): 14 | 15 | # if both the stacks are empty 16 | if len(self.stack1) == 0 and len(self.stack2) == 0: 17 | print("Queue is empty.") 18 | return 19 | 20 | # if stack2 is empty and stack1 does contain elements 21 | elif len(self.stack1) > 0 and len(self.stack2) == 0: 22 | while len(self.stack1): 23 | temp = self.stack1.pop() 24 | self.stack2.append(temp) 25 | return self.stack2.pop() 26 | 27 | # else 28 | else: 29 | return self.stack2.pop() 30 | 31 | # driver code 32 | if __name__ == "__main__": 33 | q = queue() 34 | q.push(1) 35 | q.push(4) 36 | q.push(9) 37 | q.push(16) 38 | q.push(25) 39 | q.push(36) 40 | q.push(49) 41 | q.push(64) 42 | q.push(81) 43 | q.push(100) 44 | 45 | print(q.pop_op()) 46 | print(q.pop_op()) 47 | print(q.pop_op()) 48 | print(q.pop_op()) 49 | print(q.pop_op()) 50 | print(q.pop_op()) 51 | print(q.pop_op()) 52 | print(q.pop_op()) 53 | print(q.pop_op()) 54 | print(q.pop_op()) 55 | -------------------------------------------------------------------------------- /Python/DataStructures/Stack/reverse_int_using_stack.py: -------------------------------------------------------------------------------- 1 | st = []; 2 | 3 | 4 | def push_digits(number): 5 | 6 | while (number != 0): 7 | st.append(number % 10); 8 | number = int(number / 10); 9 | 10 | 11 | def reverse_number(number): 12 | push_digits(number); 13 | 14 | reverse = 0; 15 | i = 1; 16 | 17 | while (len(st) > 0): 18 | reverse = reverse + (st[len(st) - 1] * i); 19 | st.pop(); 20 | i = i * 10; 21 | 22 | 23 | return reverse; 24 | 25 | 26 | number = int(input()); 27 | print(reverse_number(number)); 28 | -------------------------------------------------------------------------------- /Python/DataStructures/Stack/stack.py: -------------------------------------------------------------------------------- 1 | 2 | class Stack: 3 | def __init__(self): 4 | self.items = [] 5 | 6 | def is_empty(self): 7 | return self.items == [] 8 | 9 | def push(self, item): 10 | self.items.insert(0,item) 11 | 12 | def pop(self): 13 | return self.items.pop(0) 14 | 15 | def peek(self): 16 | return self.items[0] 17 | 18 | def size(self): 19 | return len(self.items) 20 | 21 | def show(self): 22 | if self.is_empty(): 23 | print("Empty stack") 24 | else: # from top 25 | print("Stack contents: ", end='') 26 | for i in range(self.size()): 27 | print(self.items[i], end=' ') 28 | print() 29 | -------------------------------------------------------------------------------- /Swift/Algorithms/Searching-Algorithms/binary_search.swift: -------------------------------------------------------------------------------- 1 | // Binary search | Swift 2 | func binarySearch(in numbers: [Int], for value: Int) -> Int? 3 | { 4 | var left = 0 5 | var right = numbers.count - 1 6 | 7 | while left <= right { 8 | 9 | let middle = Int(floor(Double(left + right) / 2.0)) 10 | 11 | if numbers[middle] < value { 12 | left = middle + 1 13 | } else if numbers[middle] > value { 14 | right = middle - 1 15 | } else { 16 | return middle 17 | } 18 | } 19 | 20 | return nil 21 | } 22 | // Driver code 23 | let numbers = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] 24 | let value = 17 25 | 26 | if let index = binarySearch(in: numbers, for: value) { 27 | print("Found \(value) at index \(index)") 28 | } else { 29 | print("Did not find \(value)") 30 | } 31 | --------------------------------------------------------------------------------