├── tree traverse.txt ├── Divide and Conquer ├── Median of Arrays │ └── c++ ├── Max Subarray Sum │ └── c++ │ │ └── MAXIMUM_SUBARRAY_SUM.cpp ├── majority_element.cpp └── closestpairofpoints.py ├── Graphs ├── README └── hamiltonian cycle.cpp ├── .gitattributes ├── desktop.ini ├── Shortest Path └── .DS_Store ├── Calculator ├── obj │ └── Debug │ │ └── main.o ├── bin │ └── Debug │ │ └── Calculator.exe └── Calculator.depend ├── Hash_alg ├── bin │ └── Release │ │ └── Hash.exe ├── Nuts_and_Bolt.cpp └── Array_is_subset_of_another_array_or_not ├── MO's Algorithm └── C++ │ └── README.md ├── Strings ├── isPalindrome.cpp ├── pangram.py ├── isPalindrome.js ├── README ├── naivestringmatching.py ├── palindrom.rkt ├── robbinkarpstringmatching.py └── kmpstringmatching.py ├── Python ├── README.md ├── .idea │ ├── vcs.xml │ ├── inspectionProfiles │ │ └── profiles_settings.xml │ ├── modules.xml │ ├── misc.xml │ └── Python.iml ├── insert_element_into_list.py ├── modularMultiplicativeInverse.py ├── magic number │ └── magic number.py ├── selectionsort.py ├── binary-search.py ├── BubbleSort.py ├── parenthesisBalancing.py ├── QuickSort.py ├── power.py ├── maxsubarr.py ├── modularExponentPower.py ├── cosine_similarity.py ├── RadixSort.py ├── prims_mst.py ├── EulerTotientFunction.py ├── sieveOfEratosthenes.py ├── Stack.py ├── z_score_for_detect_outliers.py └── fastfibonacci.py ├── CaesarCipher ├── README.md ├── Python │ └── CaesarCipher.py └── JavaScript │ └── CaesarCipher.js ├── Ranking Page └── PageRank │ └── graph.txt ├── Dynamic Programming ├── Regex Matching.txt ├── Paths In A Grid │ └── README.md ├── catalan number │ └── catalan.cpp ├── Tiling problem using DP.cpp ├── Climbing_Stairs │ ├── C++ │ │ └── climb.cpp │ └── Python │ │ └── climbing_stairs.py ├── Window Sliding Technique │ ├── WindowSlidingTechnique.md │ └── Python3 │ │ └── MaxSumArray.py ├── kadane algorithm │ ├── kadanealgo.cpp │ ├── kadanealgo │ └── kadanealgo.java ├── unbounded knapsack │ └── c++ │ │ └── unboundedknapsack.cpp ├── optimal strategy of game │ └── osg.cpp ├── maximum sum increasing subsequence │ └── msis.cpp ├── shotestcommonsupersequence.py ├── Rod_cutting_problem │ └── rod_cutting_problem.py ├── matrixchainmultiplication.py ├── Longest Common Subsequence │ └── LCS_bruteForce.cpp ├── LIS │ └── Optimized_longest_Increasing_Subsequence.cpp ├── 0-1 Knapsack │ └── Pyhton │ │ └── 0-1 Knapsack.py ├── Max Product Array │ └── max_product_array.cpp ├── maximum_product_cutting │ └── maximum.cpp └── placing_parentheses.cpp ├── Dijkstra └── Java │ └── routes0.txt ├── Kotlin ├── README.md ├── Bubble_Sort_In_Kotlin.kt ├── Insertion_Sort_In_Kotlin.kt ├── Selection_Sort_In_Kotlin.kt ├── quick_sort_in_kotlin └── merge_sort_in_kotlin.kt ├── Fibonacci Sequence ├── README.ME ├── fibonacci.js ├── fibonacci.py ├── fibonacci.c ├── fibonacci.cpp └── fast-fibonacci.py ├── Searching and Sorting ├── Fibonacci Search │ └── fs.exe ├── Selection Sort │ └── C++ │ │ └── SelectionSort ├── Binary Search │ └── Ruby │ │ └── binary_search.rb ├── Bubble Sort │ ├── Python │ │ └── bubble sort.py │ ├── C++ │ │ └── BubbleSort.cpp │ └── Kotlin │ │ └── BubbleSort.kt ├── Heap Sort │ ├── HeapSort.h │ └── Python │ │ └── heap sort.py ├── Linear Search │ ├── Python │ │ └── linear search.py │ └── Java │ │ └── LinearSearch.java ├── Quick Sort │ └── Python │ │ ├── quicksort_inplace.py │ │ └── quick sort.py ├── Shell Sort │ └── ShellSort.cpp ├── Insertion Sort │ ├── Python │ │ └── Insertion Sort.py │ └── Kotlin │ │ └── InsertionSort.kt ├── Cocktail Sort │ └── Python │ │ └── cocktailSort.py ├── Counting Sort │ └── countingsort.cpp ├── Binary Search.cpp └── Topological Sorting │ └── C │ └── topological.c ├── Sorting Algorithm ├── Heap Sort │ └── Java │ │ └── HeapSort.class ├── Merge Sort │ └── C++ │ │ └── mergesort.exe ├── Quick_sort.py ├── BubbleSort │ ├── BubbleSort.py │ ├── BubbleSort.cpp │ ├── BubbleSort.vb │ └── Bubblesort.C ├── Quick Sort │ ├── Python │ │ └── Quick_sort.py │ ├── C │ │ └── QuickSort.c │ └── C++ │ │ └── Quick_Sort.cpp ├── Selection_sort.py ├── Sort Nearly sorted array ├── Selection Sort │ ├── Python │ │ └── selection_sort.py │ ├── C++ │ │ └── main.cpp │ └── C │ │ └── main.c ├── Counting Sort │ └── CountingSort.cpp ├── Insertion Sort │ └── Java │ │ └── InsertionSort.java ├── radix sort.py ├── Quick_Sort.cpp ├── insertionsort.cpp └── mergeSort.py ├── Greedy Algorithms ├── Dijkstras │ └── Java │ │ └── routes0.txt ├── Kruskal │ └── Java │ │ ├── testFile.csv │ │ └── GraphNode.java └── machineselect.py ├── BIT ├── Power of Two │ ├── IsPowerOfTwo.py │ ├── CheckPowerOfTwo.kt │ ├── CheckPowerOfTwo.c │ ├── powerOfTwo.cpp │ └── powerOfTwo.js ├── ComputeXOR1toN │ └── computeXOR1toN.py └── Maximum Subset XOR │ └── flip.cpp ├── Automaton └── Deterministic Finite Automaton │ ├── example.txt │ ├── __pycache__ │ └── dfa.cpython-36.pyc │ └── main.py ├── LongestCommonSubsequence ├── C++ │ ├── Longest_common_subsequence.cpp │ ├── lcs.cpp │ └── LCS-DP.cpp ├── LCS.java └── longest-common-subsequence.java ├── Operating Systems └── Shortest Job First CPU Scheduling Algorithm │ └── CPP │ ├── README.md │ └── a.out ├── Linked List ├── README.md ├── DoublyLL.cpp ├── sorted_insertion_LL.cpp └── detectLoop.cpp ├── .vs └── cs-algorithms │ └── v16 │ └── ipch │ └── AutoPCH │ └── dc43ad4a5185248e │ └── INSERTIONSORT.ipch ├── Graph Traversal ├── README.md ├── dfs.py ├── BFS │ └── bfs.py └── DFS │ └── dfs_adjMatrix.c ├── .gitignore ├── Go ├── GCDEuclidean.go ├── BubbleSort.go ├── linear_search.go ├── fibonacciSeries.go ├── hammingDistance.go ├── InsertionSort.go ├── BinarySearch.go ├── Kadanes.go └── countinversion.go ├── insert.py ├── implementing stack using python ├── stack-implementtation.py ├── C++ ├── recursion │ ├── random_no_generator.cpp │ ├── fastpower.cpp │ ├── fibonacci.cpp │ ├── CPP - Recursion - Linear Search.cpp │ ├── bubbleSort.cpp │ ├── Tower of Hanoi.cpp │ ├── productOfTwoNo.cpp │ └── QuickSort.cpp ├── BinaryToDecimal.cpp ├── DecimalToBinary.cpp ├── decimal_to_octal.cpp ├── RegexMatching.cpp ├── catalanNumbers.cpp ├── SieveOfEratosthenes.cpp ├── Trapping Rain Water ├── BitwiseOperators.cpp ├── Vector.cpp ├── insertionsort.cpp ├── Bubblesort ├── egg_dropping.cpp ├── euler_totient_func.cpp ├── power.cpp ├── PrimeSeive.cpp ├── FindDuplicate.cpp └── knapsack.cpp ├── .github ├── PULL_REQUEST_TEMPLATE │ └── pull_request_template.md ├── ISSUE_TEMPLATE │ └── -algorithm-.md └── auto-merge.yml ├── N-Queens └── Python │ └── README.me ├── naivestringmatching.py ├── Recursive ├── gcd.py ├── n_choose_k.py └── knapsack_algorithm.py ├── gcd and lcm ├── Math ├── catalan number │ ├── catalan_number.rb │ ├── catalan_number_dynamic.cpp │ ├── catalan_number.scala │ └── catalan_no.cpp ├── Modular Exponentiation │ └── C++ │ │ └── modular_exponentiation.cpp ├── EulerTotientFunction │ └── C++ │ │ └── eulerFunction.cpp ├── Consecutive_Numbers_Sum │ └── consecutive_numbers_sum.cpp ├── Sieve of Eratosthenes │ ├── golang │ │ └── sieveOfErathosthenes.go │ └── PYTHON │ │ └── seiveoferatosthenes.py └── Factorization │ └── trial_division.cpp ├── fibonanci code c ├── allprime.cpp ├── Stack Algorithms ├── Push Implementation using Linked List │ └── Python │ │ └── Push using Linked List.py ├── Balanced Parenthesis Problem │ ├── Python │ │ └── balanced_parenthesis.py │ └── C++ │ │ └── balanced_parenthesis.cpp └── Span Problem │ └── C++ │ └── span.cpp ├── Fibonacci Search ├── Union FInd └── Java │ ├── QuickFindUF.java │ └── QuickUnionUF.java ├── palindrome.cpp.txt ├── Gcd.java ├── searcharray.cpp ├── fibonanci C ├── prime number ├── paranthesesChecker.py ├── Java ├── Graph │ ├── Graph.java │ ├── Node.java │ └── DFS.java └── binarySerach.java ├── Tower Of Hanoi ├── TOH.py ├── TOH.c.txt ├── TOH.java └── TOH.cpp ├── Create File └── CreateFile.vb ├── longestIncreasingSubsequence.cpp ├── Fibonacci Series ├── Fibonacci Numbers ├── Tower of hanoi--C++ └── TowerOfHanoi.cpp ├── selectionsort.py ├── Linear search(Recursively).cpp ├── Fibonacci Numbers using boost library ├── euler-totient-in_python.py ├── Fibonacci Numbers using Dynamic Programming ├── list-operations └── Element-insertion │ └── Python │ └── insertion.py ├── catalan.cpp ├── LIS_in_O(nlogn).cpp ├── MonkeySort └── monkeySort.js ├── Tower of Hanoi - Java.txt ├── euler-totient.c ├── Pattern Searching ├── Naive │ └── Python │ │ └── Naive.py └── RabinKarp │ └── C │ └── Robin_Karp.c ├── Parentheses_Matching.py ├── Tapping Rain Water ├── balanced parentheses.py ├── duplicate_remove.cpp ├── bookclass.cpp ├── Kadane's Algorithm.cpp ├── Tree Traversal ├── DFS │ └── C++ │ │ └── DFS.cpp └── BFS │ └── C++ │ └── BFS.cpp ├── Tree └── Tree Traversal │ ├── DFS │ └── C++ │ │ └── DFS.cpp │ └── BFS │ └── C++ │ └── BFS.cpp ├── Balanced Pranthesis stack problem └── Balanced_paranthesis_optimized.py ├── C ├── dfs.c ├── bubble_sort.c ├── insertion.c └── selection.c ├── modular_exponentiation.cpp ├── Array Reversal.c ├── shell_sort.cpp ├── Graph Algorithms ├── closestpairofpoints.py └── detectcycleingraph.py ├── radix.cpp ├── egg_dropping.cpp ├── longestCommonSubsequence.cpp ├── Longest Common Subsequence ├── shuffle_deck_of_cards.py ├── Balanced-Unbalanced-exp.py ├── Brute Force ├── nut_bolt.cpp ├── sieve.cpp ├── ModernCiphers └── ceaser cipher │ └── ceaser.py ├── Trapping Rain Water ├── stairCaseSearch.cpp ├── Convex HULL └── readme.md ├── doubly linkedList.cpp ├── Shuffle a deck of cards ├── LICENSE ├── Backtracking ├── generate all valid parenthesis │ └── print all parantheses.cpp └── finding all permutations of a string │ └── printing all permutations of a string.cpp ├── quick sort in kotlin ├── diamondpattern.cpp └── MaxProductArray └── Python └── max_product_subarray.py /tree traverse.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Divide and Conquer/Median of Arrays/c++: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Graphs/README: -------------------------------------------------------------------------------- 1 | - `cc.py`: find connected components in an undirected graphs 2 | 3 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /desktop.ini: -------------------------------------------------------------------------------- 1 | [LocalizedFileNames] 2 | insert_element_into_list.py=@insert_element_into_list.py,0 3 | -------------------------------------------------------------------------------- /Shortest Path/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iam-abbas/cs-algorithms/HEAD/Shortest Path/.DS_Store -------------------------------------------------------------------------------- /Calculator/obj/Debug/main.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iam-abbas/cs-algorithms/HEAD/Calculator/obj/Debug/main.o -------------------------------------------------------------------------------- /Graphs/hamiltonian cycle.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iam-abbas/cs-algorithms/HEAD/Graphs/hamiltonian cycle.cpp -------------------------------------------------------------------------------- /Hash_alg/bin/Release/Hash.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iam-abbas/cs-algorithms/HEAD/Hash_alg/bin/Release/Hash.exe -------------------------------------------------------------------------------- /MO's Algorithm/C++/README.md: -------------------------------------------------------------------------------- 1 | This repository contains MO's Algorithm implemented in the C++ programming language. 2 | -------------------------------------------------------------------------------- /Strings/isPalindrome.cpp: -------------------------------------------------------------------------------- 1 | bool isPalindrome(string str){ 2 | return str == string(str.rbegin(),str.rend()); 3 | } 4 | -------------------------------------------------------------------------------- /Python/README.md: -------------------------------------------------------------------------------- 1 | It contains some interesting programs and data structures written in the python programming language. 2 | -------------------------------------------------------------------------------- /CaesarCipher/README.md: -------------------------------------------------------------------------------- 1 | This repository contains programs written in CPP, Javascript, Python to decrypt or encrypt Caesar Cipher 2 | -------------------------------------------------------------------------------- /Calculator/bin/Debug/Calculator.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iam-abbas/cs-algorithms/HEAD/Calculator/bin/Debug/Calculator.exe -------------------------------------------------------------------------------- /Ranking Page/PageRank/graph.txt: -------------------------------------------------------------------------------- 1 | 10 2 | 0 2 3 | 0 4 4 | 0 3 5 | 2 3 6 | 3 1 7 | 4 2 8 | 6 0 9 | 8 7 10 | 9 5 11 | 8 9 12 | -------------------------------------------------------------------------------- /Dynamic Programming/Regex Matching.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iam-abbas/cs-algorithms/HEAD/Dynamic Programming/Regex Matching.txt -------------------------------------------------------------------------------- /Dijkstra/Java/routes0.txt: -------------------------------------------------------------------------------- 1 | A B 5 2 | B C 10 3 | B G 12 4 | G C 5 5 | C D 15 6 | C E 2 7 | D F 4 8 | G E 2 9 | E F 2 10 | A E 3 11 | L M 10 -------------------------------------------------------------------------------- /Kotlin/README.md: -------------------------------------------------------------------------------- 1 | This repository contains programs on Bubble sort, Insertion sort, and Selection sort written in Kotlin programming language 2 | -------------------------------------------------------------------------------- /Fibonacci Sequence/README.ME: -------------------------------------------------------------------------------- 1 | It contains a program which generates Fibonacci Sequence at faster rates, the program is available in Python, C, C++. 2 | -------------------------------------------------------------------------------- /Searching and Sorting/Fibonacci Search/fs.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iam-abbas/cs-algorithms/HEAD/Searching and Sorting/Fibonacci Search/fs.exe -------------------------------------------------------------------------------- /Sorting Algorithm/Heap Sort/Java/HeapSort.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iam-abbas/cs-algorithms/HEAD/Sorting Algorithm/Heap Sort/Java/HeapSort.class -------------------------------------------------------------------------------- /Sorting Algorithm/Merge Sort/C++/mergesort.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iam-abbas/cs-algorithms/HEAD/Sorting Algorithm/Merge Sort/C++/mergesort.exe -------------------------------------------------------------------------------- /Calculator/Calculator.depend: -------------------------------------------------------------------------------- 1 | # depslib dependency file v1.0 2 | 1570949579 source:c:\users\yakov\desktop\codeblocks\calculator\main.cpp 3 | 4 | 5 | -------------------------------------------------------------------------------- /Greedy Algorithms/Dijkstras/Java/routes0.txt: -------------------------------------------------------------------------------- 1 | A B 5 2 | B C 10 3 | B G 12 4 | G C 5 5 | C D 15 6 | C E 2 7 | D F 4 8 | G E 2 9 | E F 2 10 | A E 3 11 | L M 10 -------------------------------------------------------------------------------- /Searching and Sorting/Selection Sort/C++/SelectionSort: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iam-abbas/cs-algorithms/HEAD/Searching and Sorting/Selection Sort/C++/SelectionSort -------------------------------------------------------------------------------- /Strings/pangram.py: -------------------------------------------------------------------------------- 1 | from string import ascii_lowercase 2 | 3 | 4 | def is_pangram(sentence): 5 | return not set(ascii_lowercase) - set(sentence.lower()) 6 | 7 | -------------------------------------------------------------------------------- /BIT/Power of Two/IsPowerOfTwo.py: -------------------------------------------------------------------------------- 1 | number = int(input()) 2 | 3 | isPowerOf2 = number & (number - 1) 4 | 5 | if isPowerOf2 == 0: 6 | print('Yes') 7 | else: 8 | print('No') -------------------------------------------------------------------------------- /Automaton/Deterministic Finite Automaton/example.txt: -------------------------------------------------------------------------------- 1 | ({a, b},{q0, q1, q2, q3, q4}, D, q0, {q3}) 2 | q0, a, q1 3 | q1, b, q2 4 | q2, a, q3 5 | q2, b, q2 6 | q3, a, q4 7 | q4, b, q3 -------------------------------------------------------------------------------- /LongestCommonSubsequence/C++/Longest_common_subsequence.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iam-abbas/cs-algorithms/HEAD/LongestCommonSubsequence/C++/Longest_common_subsequence.cpp -------------------------------------------------------------------------------- /Operating Systems/Shortest Job First CPU Scheduling Algorithm/CPP/README.md: -------------------------------------------------------------------------------- 1 | It is Shortest Job First CPU Scheduling Algorithm written in CPP used in the Operating Systems. 2 | -------------------------------------------------------------------------------- /Linked List/README.md: -------------------------------------------------------------------------------- 1 | This repository contains a list of programs (written in the C++ Programming Language) regarding various operations that are usually performed on the Linked List data structure. -------------------------------------------------------------------------------- /.vs/cs-algorithms/v16/ipch/AutoPCH/dc43ad4a5185248e/INSERTIONSORT.ipch: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iam-abbas/cs-algorithms/HEAD/.vs/cs-algorithms/v16/ipch/AutoPCH/dc43ad4a5185248e/INSERTIONSORT.ipch -------------------------------------------------------------------------------- /Automaton/Deterministic Finite Automaton/__pycache__/dfa.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iam-abbas/cs-algorithms/HEAD/Automaton/Deterministic Finite Automaton/__pycache__/dfa.cpython-36.pyc -------------------------------------------------------------------------------- /Operating Systems/Shortest Job First CPU Scheduling Algorithm/CPP/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iam-abbas/cs-algorithms/HEAD/Operating Systems/Shortest Job First CPU Scheduling Algorithm/CPP/a.out -------------------------------------------------------------------------------- /Strings/isPalindrome.js: -------------------------------------------------------------------------------- 1 | export default function isPalindrome(inputString) { 2 | const reversedString = inputString.split("").reverse().join(""); 3 | return inputString === reversedString; 4 | } 5 | -------------------------------------------------------------------------------- /Fibonacci Sequence/fibonacci.js: -------------------------------------------------------------------------------- 1 | // Recursive implementation 2 | export default function fibonacci(length) { 3 | if (length <= 1) return 1; 4 | 5 | return fibonacci(length - 1) + fibonacci(length - 2); 6 | } 7 | -------------------------------------------------------------------------------- /Graph Traversal/README.md: -------------------------------------------------------------------------------- 1 | #### Run the following command on your terminal (Make sure you cd into the directory where your program files are present) 2 | 3 | To compile : **gcc filename.c** 4 | 5 | To Run : **./a.out** 6 | -------------------------------------------------------------------------------- /Python/.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | .vs/cs-algorithms/v16/Browse.VC.db 3 | .vs/cs-algorithms/v16/Browse.VC.opendb 4 | .vs/ProjectSettings.json 5 | .vs/slnx.sqlite 6 | .vs/cs-algorithms/v16/ipch/AutoPCH/cf84f1c192b8b4da/SIEVEOFERATOSTHENES.ipch 7 | -------------------------------------------------------------------------------- /Strings/README: -------------------------------------------------------------------------------- 1 | - `pangram.py`: Determine if a sentence is a pangram 2 | - `palindrom.rkt`: Find the largest palindrome made from the product of two 3-digit numbers 3 | - `intToEngWords.cpp` : Convert the input number to words 4 | -------------------------------------------------------------------------------- /BIT/Power of Two/CheckPowerOfTwo.kt: -------------------------------------------------------------------------------- 1 | fun main(args: Array){ 2 | var number = readLine()!!.toInt() 3 | var check = number and (number - 1) 4 | if(check == 0){ 5 | print("Yes") 6 | } 7 | else{ 8 | print("No") 9 | } 10 | } -------------------------------------------------------------------------------- /Python/.idea/inspectionProfiles/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | -------------------------------------------------------------------------------- /Dynamic Programming/Paths In A Grid/README.md: -------------------------------------------------------------------------------- 1 | #### Run the following command on your terminal (Make sure you cd into the directory where your program files are present) 2 | 3 | To compile : **g++ -std=c++14 filename.cpp** 4 | 5 | To Run : **./a.out** 6 | -------------------------------------------------------------------------------- /Go/GCDEuclidean.go: -------------------------------------------------------------------------------- 1 | package math 2 | 3 | // GCDEuclidean 4 | func GCDEuclidean(num1, num2 int) int { 5 | for num1 != num2 { 6 | if num1 > num2 { 7 | num1 -= num2 8 | } else { 9 | num2 -= num1 10 | } 11 | } 12 | 13 | return num1 14 | } -------------------------------------------------------------------------------- /BIT/Power of Two/CheckPowerOfTwo.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int number,check; 6 | scanf("%d",&number); 7 | check= number & (number-1); 8 | if(check==0) 9 | printf("YES"); 10 | else 11 | printf("NO"); 12 | } -------------------------------------------------------------------------------- /insert.py: -------------------------------------------------------------------------------- 1 | list1 = [ 9, 2, 8, 4, 0, 1, 34 ] 2 | 3 | # insert 45 at 5th index 4 | list1.insert(4, 45) 5 | print(list1) 6 | 7 | list2 = ['q', 'b', 'u', 'h', 'p'] 8 | 9 | # insert z at the front of the list 10 | list2.insert(0, 'z') 11 | print(list2) 12 | -------------------------------------------------------------------------------- /CaesarCipher/Python/CaesarCipher.py: -------------------------------------------------------------------------------- 1 | letters = input() 2 | rot = int(input()) 3 | for i in range(len(letters)): 4 | print(letters[(i + rot) % len(letters)], end='') 5 | print('\n', letters, sep='') 6 | for i in range(len(letters)): 7 | print(letters[(i - rot) % len(letters)], end='') -------------------------------------------------------------------------------- /BIT/Power of Two/powerOfTwo.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | int number; 3 | int isPowerOfTwo(int number) { 4 | if ((number - 1) & number) { 5 | return 0; 6 | } else { 7 | return 1; 8 | } 9 | } 10 | int main() { 11 | scanf("%d", &number); 12 | printf("%d", isPowerOfTwo(number)); 13 | } -------------------------------------------------------------------------------- /implementing stack using python: -------------------------------------------------------------------------------- 1 | # Python code to demonstrate Implementing 2 | # stack using list 3 | stack = ["Amar", "Akbar", "Anthony"] 4 | stack.append("Ram") 5 | stack.append("Iqbal") 6 | print(stack) 7 | print(stack.pop()) 8 | print(stack) 9 | print(stack.pop()) 10 | print(stack) 11 | -------------------------------------------------------------------------------- /stack-implementtation.py: -------------------------------------------------------------------------------- 1 | # Python code to demonstrate Implementing 2 | # stack using list 3 | stack = ["Amar", "Akbar", "Anthony"] 4 | stack.append("Ram") 5 | stack.append("Iqbal") 6 | print(stack) 7 | print(stack.pop()) 8 | print(stack) 9 | print(stack.pop()) 10 | print(stack) 11 | -------------------------------------------------------------------------------- /Python/.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /C++/recursion/random_no_generator.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | //srand(1); // same output anytime 9 | srand(time(NULL)); // output vary anytime 10 | cout<<"The no is "< 2 | 3 | 4 | 6 | 7 | -------------------------------------------------------------------------------- /Sorting Algorithm/Quick_sort.py: -------------------------------------------------------------------------------- 1 | def Quick_Sort(lista): 2 | if len(lista) <= 1: 3 | return lista 4 | key = lista[0] 5 | equal = [x for x in lista if x == key] 6 | minor = [x for x in lista if x < key] 7 | major = [x for x in lista if x > key] 8 | return Quick_Sort(minor) + equal + Quick_Sort(major) -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE/pull_request_template.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: "[Algorithm]" 3 | about: Base issue template for hacktoberfest 4 | title: "[Algorithm]" 5 | labels: Hacktoberfest 6 | 7 | --- 8 | 9 | # CS - Algorithm 10 | - [ ] I have starred this repository 11 | 12 | - **Algorithm Name:** 13 | 14 | - **Language:** 15 | -------------------------------------------------------------------------------- /Sorting Algorithm/BubbleSort/BubbleSort.py: -------------------------------------------------------------------------------- 1 | def BubbleSort(lst): 2 | lst = list(lst) #copy collection to list 3 | for passesLeft in range(len(lst)-1, 0, -1): 4 | for i in range(passesLeft): 5 | if lst[i] < lst[i + 1]: 6 | lst[i], lst[i + 1] = lst[i + 1], lst[i] 7 | return lst -------------------------------------------------------------------------------- /N-Queens/Python/README.me: -------------------------------------------------------------------------------- 1 | The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. For example, following is a solution for 4 Queen problem. 2 | 3 | { 0, 1, 0, 0} 4 | { 0, 0, 0, 1} 5 | { 1, 0, 0, 0} 6 | { 0, 0, 1, 0} 7 | -------------------------------------------------------------------------------- /Sorting Algorithm/Quick Sort/Python/Quick_sort.py: -------------------------------------------------------------------------------- 1 | def Quick_Sort(lista): 2 | if len(lista) <= 1: 3 | return lista 4 | key = lista[0] 5 | equal = [x for x in lista if x == key] 6 | minor = [x for x in lista if x < key] 7 | major = [x for x in lista if x > key] 8 | return Quick_Sort(minor) + equal + Quick_Sort(major) -------------------------------------------------------------------------------- /Sorting Algorithm/Selection_sort.py: -------------------------------------------------------------------------------- 1 | new_list = input("Enter list: ") 2 | arr = list(map(int, new_list.split(","))) 3 | 4 | for i in range(len(arr)): 5 | pivot = i 6 | for j in range(i,len(arr)): 7 | if arr[j] 2 | using namespace std; 3 | int main() 4 | { 5 | int n; 6 | cin>>n; 7 | int temp=n; 8 | int dec=0; 9 | int t=1; 10 | int base=1; 11 | while(temp) 12 | { 13 | t=temp%10; 14 | dec=dec+t*base; 15 | base=base*2; 16 | temp=temp/10; 17 | 18 | } 19 | cout< arr[i] { 8 | arr[i-1], arr[i] = arr[i], arr[i-1] 9 | swap = true 10 | } 11 | } 12 | if swap == false { 13 | break 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /Go/linear_search.go: -------------------------------------------------------------------------------- 1 | package search 2 | 3 | // LinearSearch returns the index of the given key found on the list. 4 | // It returns a value of -1 if the key doesn't exist 5 | func LinearSearch(list []int, key int) int { 6 | for index, element := range list { 7 | if key == element { 8 | return index 9 | } 10 | } 11 | 12 | return -1 13 | } 14 | -------------------------------------------------------------------------------- /naivestringmatching.py: -------------------------------------------------------------------------------- 1 | def funtion(txt,pat): 2 | n=len(txt) 3 | m=len(pat) 4 | for i in range(n-m+1): 5 | for j in range(m): 6 | if(txt[i+j]!=pat[j]): 7 | break 8 | else: 9 | j+=1 10 | if(j==m): 11 | print("Found at:",i) 12 | 13 | 14 | if __name__ == '__main__': 15 | txt="SouravMondalSM" 16 | pat="SM" 17 | funtion(txt,pat) 18 | -------------------------------------------------------------------------------- /BIT/ComputeXOR1toN/computeXOR1toN.py: -------------------------------------------------------------------------------- 1 | #Direct XOR of all numbers from 1 to n 2 | def computeXOR( n) 3 | 4 | if (n % 4 == 0) : 5 | return n 6 | if (n % 4 == 1) : 7 | return 1 8 | if (n % 4 == 2) : 9 | return n + 1 10 | else : 11 | return 0 12 | 13 | n = input("enter N") 14 | print(computeXOR(n)) 15 | -------------------------------------------------------------------------------- /Recursive/gcd.py: -------------------------------------------------------------------------------- 1 | ''' 2 | The GCD algorithm computes the greatest common divisor of two numbers A and B recursively. 3 | ''' 4 | 5 | def gcd(x, y): 6 | if (y==0): # base case 7 | return x 8 | else: # recursive case 9 | return gcd(y, x%y) 10 | 11 | if __name__ == "__main__": 12 | print (gcd(x=100, y=20)) -------------------------------------------------------------------------------- /Sorting Algorithm/Sort Nearly sorted array: -------------------------------------------------------------------------------- 1 | static void insertionSort(int A[], int size) 2 | { 3 | int i=0, k=0, j=0; 4 | for (i = 1; i < size; i++) 5 | { 6 | k = A[i]; 7 | j = i-1; 8 | while (j >= 0 && A[j] > k) 9 | { 10 | A[j+1] = A[j]; 11 | j = j-1; 12 | } 13 | A[j+1] = k; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Go/fibonacciSeries.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func fib(n int) int { 6 | var sequence = make([]int, n + 1, n + 1) 7 | sequence[0], sequence[1] = 0, 1 8 | 9 | for i := 2; i <= n; i += 1 { 10 | sequence[i] = sequence[i-1] + sequence[i-2] 11 | } 12 | 13 | return sequence[n] 14 | } 15 | 16 | func main() { 17 | fmt.Println(fib(10)) 18 | } 19 | -------------------------------------------------------------------------------- /gcd and lcm: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | long long gcd(int a, int b) 5 | { 6 | if (a == 0) 7 | return b; 8 | return gcd(b % a, a); 9 | } 10 | 11 | int main() 12 | { 13 | long long a, b; 14 | cin>>a>>b; 15 | long long g = gcd(a, b); 16 | cout<<"GCD = "< 2 | using namespace std; 3 | 4 | int fastPower(int a,int b) 5 | { 6 | 7 | if(b==0) 8 | { 9 | return 1; 10 | } 11 | else{ 12 | return a*fastPower(a,b-1); 13 | } 14 | } 15 | 16 | int main() { 17 | int a,b; 18 | cin>>a>>b; 19 | cout<= 0 && arr[j] > val { 9 | arr[j+1] = arr[j] 10 | j = j - 1 11 | } 12 | arr[j + 1] = val 13 | } 14 | } 15 | 16 | func main() { 17 | arr := []int{2, 1, 1, 3} 18 | InsertionSort(arr) 19 | fmt.Println(arr) 20 | } 21 | -------------------------------------------------------------------------------- /Math/catalan number/catalan_number.rb: -------------------------------------------------------------------------------- 1 | def catalan(num) 2 | return 1 if num <= 1 3 | ans = 0 4 | i = 0 5 | 6 | while i < num 7 | first = catalan i 8 | second = catalan num - i - 1 9 | ans += (first * second) 10 | i += 1 11 | end 12 | ans 13 | end 14 | 15 | Integer x = 1 16 | while x <= 10 17 | res = catalan x 18 | puts res 19 | x += 1 20 | end 21 | -------------------------------------------------------------------------------- /Graph Traversal/dfs.py: -------------------------------------------------------------------------------- 1 | def dfs(graph, root, visited = []): 2 | res = [root] 3 | visited.append(root) 4 | for neighbour in graph[root]: 5 | if neighbour not in visited: 6 | res.extend(dfs(graph, neighbour, visited)) 7 | return res 8 | if __name__ == '__main__': 9 | graph = {0: [1,3], 1: [3], 2: [3], 3: [2,4], 4:[]} 10 | print dfs(graph, 0) 11 | -------------------------------------------------------------------------------- /Recursive/n_choose_k.py: -------------------------------------------------------------------------------- 1 | ''' 2 | The N choose K algorithm computes the binomial coefficient C(N, K) 3 | ''' 4 | 5 | def nchoosek(n, k): 6 | if (k == 0) or (k == n): # base case 7 | return 1 8 | else: # recursive case 9 | return nchoosek(n-1, k-1) + nchoosek(n-1, k) 10 | 11 | if __name__ == "__main__": 12 | print (nchoosek(n=5, k=3)) -------------------------------------------------------------------------------- /fibonanci code c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | int i, n, t1 = 0, t2 = 1, nextTerm; 5 | printf("Enter the number of terms: "); 6 | scanf("%d", &n); 7 | printf("Fibonacci Series: "); 8 | for (i = 1; i <= n; ++i) 9 | { 10 | printf("%d, ", t1); 11 | nextTerm = t1 + t2; 12 | t1 = t2; 13 | t2 = nextTerm; 14 | } 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /allprime.cpp: -------------------------------------------------------------------------------- 1 | //PROGRAM TO PRINT FIRST N PRIME NUMBERS 2 | 3 | #include 4 | using namespace std; 5 | int main() 6 | { 7 | int i,n=2,N,j; 8 | cin>>N; 9 | for(i=1;i<=N;i++) 10 | { 11 | for(j=2;j<=n;j++) 12 | { 13 | if(n%i==0) 14 | continue; 15 | } 16 | cout< 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | //the string that will be matched with the regex 9 | string s; 10 | cin >> s; 11 | 12 | if(regex_match(s, regex("(str)(.*)")) 13 | cout << "the entered string contains 'str'"; 14 | else 15 | cout << "there was no match between the entered string and 'str'"; 16 | 17 | return 0; 18 | } 19 | -------------------------------------------------------------------------------- /Stack Algorithms/Push Implementation using Linked List/Python/Push using Linked List.py: -------------------------------------------------------------------------------- 1 | def createStack(): 2 | stack = [] 3 | return stack 4 | 5 | def isEmpty(stack): 6 | return len(stack) == 0 7 | 8 | def push(stack, item): 9 | stack.append(item) 10 | print(item + " pushed to stack ") 11 | 12 | stack = createStack() 13 | push(stack, str(10)) 14 | push(stack, str(20)) 15 | push(stack, str(30)) 16 | -------------------------------------------------------------------------------- /Fibonacci Search: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | int i, n, t1 = 0, t2 = 1, nextTerm; 5 | 6 | printf("Enter the number of terms: "); 7 | scanf("%d", &n); 8 | 9 | printf("Fibonacci Series: "); 10 | 11 | for (i = 1; i <= n; ++i) 12 | { 13 | printf("%d, ", t1); 14 | nextTerm = t1 + t2; 15 | t1 = t2; 16 | t2 = nextTerm; 17 | } 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /Searching and Sorting/Binary Search/Ruby/binary_search.rb: -------------------------------------------------------------------------------- 1 | def binary_search(n, arr) 2 | middle = arr.length / 2 3 | i = 0 4 | j = arr.length - 1 5 | 6 | while i < j 7 | if arr[middle] == n 8 | return true 9 | elsif arr[middle] < n 10 | i = middle + 1 11 | middle = i + j / 2 12 | else 13 | j = middle - 1 14 | middle = i + j / 2 15 | end 16 | end 17 | false 18 | end 19 | -------------------------------------------------------------------------------- /Fibonacci Sequence/fibonacci.py: -------------------------------------------------------------------------------- 1 | # Method for nth fibonacci number using Dynamic Programing 2 | 3 | Fib = [0,1] 4 | 5 | def fibonacci(num): 6 | if num<0: 7 | print("incorrect value!! ") 8 | elif num<=len(Fib): 9 | return Fib[num-1] 10 | else: 11 | temp_fib = fibonacci(num-1)+fibonacci(num-2) 12 | Fib.append(temp_fib) 13 | return temp_fib 14 | 15 | # driver program 16 | 17 | print(fibonacci(5)) 18 | 19 | 20 | -------------------------------------------------------------------------------- /Math/catalan number/catalan_number_dynamic.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | 6 | int main() 7 | { 8 | int n; 9 | cin >> n; 10 | 11 | double cat[100000]; 12 | cat[0] = 1; 13 | cout << cat[0]; 14 | 15 | for (int i = 1; i <= n; i++) 16 | { 17 | cat[i] = 2 * (4 * i + 1) * cat[i - 1] / (i + 2); 18 | cout << cat[i] << endl; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Fibonacci Sequence/fibonacci.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main () { 4 | int term1 = 0 , term2 = 1, i, number, sequence; 5 | 6 | printf("What is the number of terms: "); 7 | scanf("%d",&number); 8 | printf("Fibonacci sequence: "); 9 | 10 | for(i=1; i<=number; i++) { 11 | sequence = (term1 + term2); 12 | printf("%d ", term1); 13 | term1 = term2; 14 | term2 = sequence; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /C++/recursion/fibonacci.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int fibonacci(int n) 6 | { 7 | if(n==0) 8 | return 0; 9 | if(n==1) 10 | return 1; 11 | int smallOutput1 = fibonacci(n-1); 12 | int smallOutput2 = fibonacci(n-2); 13 | return smallOutput1 + smallOutput2; 14 | } 15 | 16 | int main() 17 | { 18 | int n; 19 | cin>>n; 20 | int output = fibonacci(n); 21 | cout< { 2 | if (number === 0) { 3 | return 1; 4 | } 5 | number & (number - 1) === 0; 6 | } 7 | 8 | const readline = require('readline'); 9 | 10 | const rl = readline.createInterface({ 11 | input: process.stdin, 12 | output: process.stdout 13 | }); 14 | 15 | rl.question('Please input a number: ', (answer) => { 16 | console.log(isPowerOfTwo(answer) === 0); 17 | rl.close(); 18 | }); 19 | -------------------------------------------------------------------------------- /Greedy Algorithms/Kruskal/Java/testFile.csv: -------------------------------------------------------------------------------- 1 | Chellcargate|Hamuelland|20 2 | Chellcargate|Dalrayss|85 3 | Dalrayss|Hamuelland|100 4 | Ikmam|Kalvinville|35 5 | Ikmam|Lyhalson|70 6 | Kalvinville|Lyhalson|5 7 | Nevaehgate|Ranaskeep|45 8 | Nevaehgate|Syccvarka|85 9 | Ranaskeep|Syccvarka|100 10 | Hamuelland|Zathysquol|90 11 | Lyhalson|Zathysquol|95 12 | Syccvarka|Zathysquol|20 13 | Ikmam|Ranaskeep|15 14 | Chellcargate|Kalvinville|40 15 | Dalrayss|Nevaehgate|95 16 | -------------------------------------------------------------------------------- /Python/.idea/Python.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 11 | -------------------------------------------------------------------------------- /Union FInd/Java/QuickFindUF.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class QuickFindUF 3 | { 4 | private int id[]; 5 | public QuickFindUF(int N) 6 | { 7 | id=new int[N]; 8 | } 9 | public boolean connected(int p,int q) 10 | { 11 | return id[p]==id[q]; 12 | } 13 | public void union(int p,int q) 14 | { 15 | int pid=id[p]; 16 | int qid=id[q]; 17 | for(int i=0;i 2 | using namespace std; 3 | int main() 4 | { 5 | int n,num,d,rev=0; 6 | cout << "enter the positive number"; 7 | cin >> num; 8 | n=num; 9 | do 10 | { 11 | d=num%10; 12 | rev=(rev*10)+d; 13 | num=num/10; 14 | } 15 | while(num!=0); 16 | cout << "the reverse of the number is:"<< rev << end1; 17 | if(n==rev) 18 | cout << "the number is palindrome"; 19 | else 20 | cout << "the number is not palindrome"; 21 | return 0; 22 | } -------------------------------------------------------------------------------- /Gcd.java: -------------------------------------------------------------------------------- 1 | class Test { 2 | 3 | static int gcd(int a, int b) 4 | { 5 | if (b == 0) 6 | return a; 7 | return gcd(b, a % b); 8 | } 9 | 10 | // Driver method 11 | public static void main(String[] args) 12 | { 13 | Scanner sc=new Scanner(System.in); 14 | int a=sc.nextInt(),b=sc.nextInt(); 15 | System.out.println("GCD of " + a +" and " + b + " is " + gcd(a, b)); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Python/insert_element_into_list.py: -------------------------------------------------------------------------------- 1 | # Python3 program to insert an element into sorted list 2 | 3 | # Function to insert element 4 | def insert(list, n): 5 | 6 | # Searching for the position 7 | for i in range(len(list)): 8 | if list[i] > n: 9 | index = i 10 | break 11 | 12 | # Inserting n in the list 13 | list = list[:i] + [n] + list[i:] 14 | return list 15 | 16 | 17 | list = [1, 2, 4] 18 | n = 3 19 | 20 | print(insert(list, n)) 21 | -------------------------------------------------------------------------------- /C++/catalanNumbers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | unsigned long int catalanDP(unsigned int n) 6 | { 7 | unsigned long int catalan[n+1]; 8 | 9 | catalan[0] = catalan[1] = 1; 10 | for (int i=2; i<=n; i++) 11 | { 12 | catalan[i] = 0; 13 | for (int j=0; j 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | int term1 = 0 , term2 = 1, i, number, sequence; 7 | 8 | cout << "What is the number of terms: "; 9 | cin >> number; 10 | cout << "Fibonacci sequence: "; 11 | 12 | for(i=1; i<=number; i++) { 13 | sequence = (term1 + term2); 14 | cout << term1 << " "; 15 | term1 = term2; 16 | term2 = sequence; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Python/modularMultiplicativeInverse.py: -------------------------------------------------------------------------------- 1 | # Python 3 program to find modular 2 | # inverse of a under modulo m 3 | 4 | # A naive method to find modulor 5 | # multiplicative inverse of 'a' 6 | # under modulo 'm' 7 | def modInverse(a, m) : 8 | a = a % m; 9 | for x in range(1, m) : 10 | if ((a * x) % m == 1) : 11 | return x 12 | return 1 13 | 14 | # Driver Program 15 | a = 3 16 | m = 11 17 | print(modInverse(a, m)) 18 | 19 | -------------------------------------------------------------------------------- /searcharray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | int n; 6 | cout<<"Enter size of the array:"<>n; 8 | int arr[n]; 9 | cout<<"Enter array elements:"<>arr[i]; 12 | int x; 13 | cout<<"Enter number to be found:"<>x; 15 | //search 16 | for(int i=0;i arr[j+1] : 8 | arr[j], arr[j+1] = arr[j+1], arr[j] 9 | arr = [64, 34, 25, 12, 22, 11, 90] 10 | bubbleSort(arr) 11 | print ("Sorted array is:") 12 | for i in range(len(arr)): 13 | print ("%d" %arr[i]), 14 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/-algorithm-.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: "[Algorithm]" 3 | about: Base issue template for hacktoberfest 4 | title: "[Algorithm] - Name" 5 | labels: Hacktoberfest 6 | assignees: '' 7 | 8 | --- 9 | 10 | # CS - Algorithm 11 | - [ ] I have starred this repository 12 | - [ ] This algorithm is not available in the repository currently. 13 | - [ ] If it is, My Algorithm is implemented in a different method. 14 | 15 | ## Information 16 | 17 | - **Algorithm Name:** 18 | 19 | - **Language:** 20 | -------------------------------------------------------------------------------- /Go/BinarySearch.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | arr := []int{1, 2, 3, 4, 5} 7 | fmt.Println(BinarySearch(arr, 5)) 8 | } 9 | 10 | // Returns -1 If element not found 11 | func BinarySearch(arr []int, k int) int { 12 | lo, hi, mid := 0, len(arr)-1, 0 13 | for hi >= lo { 14 | mid = (lo + hi) / 2 15 | if arr[mid] == k { 16 | return mid 17 | } else if arr[mid] > k { 18 | hi = mid - 1 19 | } else { 20 | lo = mid + 1 21 | } 22 | } 23 | return -1 24 | } 25 | -------------------------------------------------------------------------------- /BIT/Maximum Subset XOR/flip.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int countSetBit(int n) 5 | { 6 | int c = 0; 7 | while (n) 8 | { 9 | c += n & 1; 10 | n >>= 1; 11 | } 12 | return c; 13 | } 14 | 15 | int FlippedCount(int a, int b) 16 | { 17 | return countSetBit(a^b); 18 | } 19 | 20 | 21 | int main() 22 | { 23 | int n1 = 14; 24 | int n2 = 50; 25 | cout << FlippedCount(n1, n2)< 2 | using namespace std; 3 | 4 | int linearSearch(int *a,int i,int n,int key) 5 | { 6 | if(i==n) 7 | { 8 | return -1; 9 | } 10 | if(a[i]==key) 11 | { 12 | return i; 13 | } 14 | return linearSearch(a,i+1,n,key); 15 | } 16 | int main() 17 | { 18 | int a[]={1,3,2,5,6,9}; 19 | int n=sizeof(a)/sizeof(int); 20 | int key=5; 21 | cout< 2 | int main() 3 | { 4 | int t1 = 0, t2 = 1, nextTerm = 0, n; 5 | printf("Enter a positive number: "); 6 | scanf("%d", &n); 7 | // displays the first two terms which is always 0 and 1 8 | printf("Fibonacci Series: %d, %d, ", t1, t2); 9 | nextTerm = t1 + t2; 10 | while(nextTerm <= n) 11 | { 12 | printf("%d, ",nextTerm); 13 | t1 = t2; 14 | t2 = nextTerm; 15 | nextTerm = t1 + t2; 16 | } 17 | 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /prime number: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int n, count=0; 7 | cin>>n; 8 | 9 | bool a[n+1]; 10 | a[0] = false; 11 | a[1] = false; 12 | for( int i=2; i y { 9 | return x 10 | } 11 | return y 12 | } 13 | 14 | func Kadane(arr []int64) int64 { 15 | var maxSoFar, maxEnding int64 = 0, 0 16 | for _, x := range arr { 17 | maxEnding = Max(0, maxEnding + x) 18 | maxSoFar = Max(maxSoFar, maxEnding) 19 | } 20 | return maxSoFar 21 | } 22 | 23 | func main() { 24 | arr := []int64{-2, -3, 4, -1, -2, 1, 5, -3} 25 | fmt.Printf("Max contiguous sum is %d", Kadane(arr)) 26 | } 27 | -------------------------------------------------------------------------------- /Graph Traversal/BFS/bfs.py: -------------------------------------------------------------------------------- 1 | import collections 2 | def bfs(graph, root): 3 | visited, queue = [], collections.deque([root]) 4 | visited.append(root) 5 | while queue: 6 | vertex = queue.popleft() 7 | for neighbour in graph[vertex]: 8 | if neighbour not in visited: 9 | visited.append(neighbour) 10 | queue.append(neighbour) 11 | return visited 12 | if __name__ == '__main__': 13 | graph = {0: [1,3], 1: [2], 2: [3], 3: [1,2]} 14 | print bfs(graph, 0) 15 | -------------------------------------------------------------------------------- /Divide and Conquer/Max Subarray Sum/c++/MAXIMUM_SUBARRAY_SUM.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | sumofarray(int arr[], int n) 5 | { 6 | if(n==0) return 0; 7 | int ans=sumofarray(arr+1,n-1); 8 | return arr[0]+ans; 9 | } 10 | 11 | int main() 12 | { 13 | int n;cin>>n; 14 | while(n--) 15 | { 16 | int a; cin>>a; 17 | int arr[a]; 18 | for(int i=0;i<=n;i++) 19 | { 20 | cin>>arr[i]; 21 | cout< 2 | using namespace std; 3 | 4 | 5 | unsigned long int cata(unsigned int n) 6 | { 7 | 8 | if (n <= 1) return 1; 9 | 10 | 11 | unsigned long int result = 0; 12 | for (int i=0; i nodes; 13 | 14 | public Graph() { 15 | nodes = new ArrayList(); 16 | } 17 | 18 | public void addNode(Node node) { 19 | nodes.add(node); 20 | } 21 | 22 | public Node getNode(int i) { 23 | return nodes.get(i); 24 | } 25 | 26 | public List getNodes() { 27 | return nodes; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Tower Of Hanoi/TOH.py: -------------------------------------------------------------------------------- 1 | # Recursive Python function to solve tower of hanoi 2 | 3 | def TowerOfHanoi(n , from_rod, to_rod, aux_rod): 4 | if n == 1: 5 | print "Move disk 1 from rod",from_rod,"to rod",to_rod 6 | return 7 | TowerOfHanoi(n-1, from_rod, aux_rod, to_rod) 8 | print "Move disk",n,"from rod",from_rod,"to rod",to_rod 9 | TowerOfHanoi(n-1, aux_rod, to_rod, from_rod) 10 | 11 | # Driver code 12 | n = 4 13 | TowerOfHanoi(n, 'A', 'C', 'B') 14 | # A, C, B are the name of rods 15 | 16 | # Contributed By Harshit Agrawal 17 | 18 | -------------------------------------------------------------------------------- /Create File/CreateFile.vb: -------------------------------------------------------------------------------- 1 | Imports System.IO 2 | Imports System.Text 3 | 4 | Module Module1 5 | 6 | Sub Main() 7 | Dim path As String = "c:\temp\MyTest.txt" 8 | 9 | ' Creates (or overwrites) the file in the directory "c:\temp\MyTest.txt". 10 | Dim fs As FileStream = File.Create(path) 11 | 12 | ' Add text to the file. 13 | Dim info As Byte() = New UTF8Encoding(True).GetBytes("This is some text in the file.") 14 | fs.Write(info, 0, info.Length) 15 | fs.Close() 16 | End Sub 17 | 18 | End Module -------------------------------------------------------------------------------- /Math/Modular Exponentiation/C++/modular_exponentiation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | // Calculates (a^b) % m 6 | // Time Complexity : O(log (a+b)) aka O(logN) 7 | long long modPow(long long a, long long b, long long m) { 8 | a %= m; 9 | long long result = 1; 10 | while (b > 0) { 11 | if (b & 1) 12 | result = result * a % m; 13 | a = a * a % m; 14 | b >>= 1; 15 | } 16 | return result; 17 | } 18 | 19 | int main() { 20 | cout << modPow(1009, 33, 1000000007) << endl; 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /Math/EulerTotientFunction/C++/eulerFunction.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int phi(int n) { 5 | int result = n; 6 | for (int i = 2; i * i <= n; i++) { 7 | if(n % i == 0) { 8 | while(n % i == 0) 9 | n /= i; 10 | result -= result / i; 11 | } 12 | } 13 | if(n > 1) 14 | result -= result / n; 15 | return result; 16 | } 17 | 18 | int main() 19 | { 20 | int n; 21 | cin >> n; 22 | cout << "The number of coprimes less than n are " << phi(n) << endl; 23 | } 24 | -------------------------------------------------------------------------------- /Python/magic number/magic number.py: -------------------------------------------------------------------------------- 1 | def nthMagicNo(n): 2 | 3 | pow = 1 4 | answer = 0 5 | 6 | # Go through every bit of n 7 | while (n): 8 | 9 | pow = pow*5 10 | 11 | # If last bit of n is set 12 | if (n & 1): 13 | answer += pow 14 | 15 | # proceed to next bit 16 | n >>= 1 # or n = n/2 17 | 18 | return answer 19 | 20 | 21 | # Driver program to test above function 22 | n = 10 23 | print("nth magic number is", nthMagicNo(n)) 24 | 25 | -------------------------------------------------------------------------------- /Python/selectionsort.py: -------------------------------------------------------------------------------- 1 | def selection_sort(a_list): 2 | for i in range(len(a_list)): 3 | min_pos = i 4 | 5 | for j in range(i+1, len(a_list)): 6 | if a_list[min_pos] > a_list[j]: 7 | min_pos = j 8 | 9 | aux = a_list[i] 10 | a_list[i] = a_list[min_pos] 11 | a_list[min_pos] = aux 12 | 13 | return a_list 14 | 15 | 16 | if __name__ == "__main__": 17 | arr = [int(x) for x in input("Enter the array elements : ").split()] 18 | a = selection_sort(arr) 19 | print(a) 20 | -------------------------------------------------------------------------------- /Searching and Sorting/Heap Sort/HeapSort.h: -------------------------------------------------------------------------------- 1 | #ifndef HEAPSORT_HEAPSORT_H_ 2 | #define HEAPSORT_HEAPSORT_H_ 3 | 4 | //Helper macros to access left,right child and parent 5 | #define RIGHT(i) ((i<<1)+2) 6 | #define LEFT(i) ((i<<1)+1) 7 | #define PARENT(i) ((i-1)>>1) 8 | 9 | class HeapSort:{ 10 | 11 | private: 12 | int heapSize; 13 | void maxHeapify(int* arr, int idx); 14 | void buildMaxHeap(int* arr, int size); 15 | public: 16 | HeapSort(); 17 | virtual void sort(int* arr, int size); 18 | virtual ~HeapSort(); 19 | }; 20 | 21 | #endif /* HEAPSORT_HEAPSORT_H_ */ 22 | -------------------------------------------------------------------------------- /Union FInd/Java/QuickUnionUF.java: -------------------------------------------------------------------------------- 1 | public class QuickUnionUF 2 | { 3 | private int[] id; 4 | 5 | public QuickUnionUF(int n) 6 | { 7 | id = new int[N]; 8 | for(int i=0;istring (reverse (string->list str)))) 7 | 8 | (define (palindrome? x) 9 | (equal? (number->string x) (rev-string (number->string x)))) 10 | 11 | (define (largest-palindrome-triplet) 12 | (apply max 13 | (for*/list ([a (in-range 999 100 -1)] 14 | [b (in-range a 100 -1)] 15 | #:when (palindrome? (* a b))) 16 | (* a b)))) 17 | 18 | (largest-palindrome-triplet) 19 | 20 | -------------------------------------------------------------------------------- /longestIncreasingSubsequence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int lis(int arr[], int n) 6 | { 7 | int lis[n]; 8 | lis[0] = 1; 9 | for(int i=0; i arr[j] && lis[j] + 1 > lis[i]) 14 | lis[i] = lis[j] + 1; 15 | } 16 | return lis[n-1]; 17 | } 18 | 19 | int main() 20 | { 21 | int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 }; 22 | int n = sizeof(arr)/sizeof(arr[0]); 23 | printf("Length of lis is %d\n", lis( arr, n ) ); 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /Searching and Sorting/Linear Search/Python/linear search.py: -------------------------------------------------------------------------------- 1 | # Python3 code to linearly search x in arr[]. 2 | # If x is present then return its location, 3 | # otherwise return -1 4 | 5 | def search(arr, n, x): 6 | 7 | for i in range (0, n): 8 | if (arr[i] == x): 9 | return i; 10 | return -1; 11 | 12 | # Driver Code 13 | arr = [ 2, 3, 4, 10, 40 ]; 14 | x = 10; 15 | n = len(arr); 16 | result = search(arr, n, x) 17 | if(result == -1): 18 | print("Element is not present in array") 19 | else: 20 | print("Element is present at index", result); -------------------------------------------------------------------------------- /Fibonacci Series: -------------------------------------------------------------------------------- 1 | class Fibonacci { 2 | static int fib(int n) 3 | { 4 | int f[] = new int[n + 1]; 5 | int i; 6 | f[0] = 0; 7 | 8 | if (n > 0) { 9 | f[1] = 1; 10 | 11 | for (i = 2; i <= n; i++) { 12 | f[i] = f[i - 1] + f[i - 2]; 13 | } 14 | } 15 | 16 | return f[n]; 17 | } 18 | 19 | public static void main(String args[]) 20 | { 21 | Scanner sc=new Scanner(System.in); 22 | int n = sc.nextInt(); 23 | System.out.println(fib(n)); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Python/binary-search.py: -------------------------------------------------------------------------------- 1 | def binary_search(item_list,item): 2 | first = 0 3 | last = len(item_list)-1 4 | print(last) 5 | found = False 6 | while( first<=last and not found): 7 | mid = (first + last)//2 8 | print(mid) 9 | if item_list[mid] == item : 10 | found = True 11 | return found 12 | else: 13 | if item < item_list[mid]: 14 | last = mid - 1 15 | else: 16 | first = mid + 1 17 | 18 | 19 | print(binary_search([1,2,3,5,8], 6)) 20 | print(binary_search([1,2,3,5,8], 5)) 21 | -------------------------------------------------------------------------------- /Fibonacci Numbers: -------------------------------------------------------------------------------- 1 | # include 2 | # include 3 | 4 | using namespace std; 5 | 6 | void input(int &n) 7 | { 8 | cin>>n; 9 | } 10 | 11 | void display(int &c) 12 | { 13 | cout< ' 8 | ) 9 | if (initial_input.lower()=='!exit'): 10 | break 11 | elif (initial_input.lower()=='!automaton'): 12 | auto, rules = read_file() 13 | else: 14 | process_word(initial_input, auto, rules) 15 | else: 16 | print("error in automaton information.\n") 17 | break -------------------------------------------------------------------------------- /Java/binarySerach.java: -------------------------------------------------------------------------------- 1 | public class binarySearch{ 2 | // inputArray contains the data set we are going to search and it should be sorted 3 | //x is the number we are going to find inside inputArray 4 | public static boolean search(int[] inputArray, int x){ 5 | if (x > inputArray[inputArray.length-1] ){ 6 | int mid = inputArray.length/2; 7 | 8 | if (inputArray[mid] == x){ 9 | return true; 10 | }if (inputArray[mid]>x){ 11 | return search(Arrays.copyOfRange(inputArray,0,mid),x); 12 | } 13 | 14 | return search(Arrays.copyOfRange(inputArray,mid,inputArray[inputArray.length-1]),x); 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /Python/BubbleSort.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | def bubble_sort(nums): 3 | # We set swapped to True so the loop looks runs at least once 4 | swapped = True 5 | while swapped: 6 | swapped = False 7 | for i in range(len(nums) - 1): 8 | if nums[i] > nums[i + 1]: 9 | # Swap the elements 10 | nums[i], nums[i + 1] = nums[i + 1], nums[i] 11 | # Set the flag to True so we'll loop again 12 | swapped = True 13 | 14 | 15 | if __name__ == '__main__': 16 | nums = [9, 12, 8, 6, 3] 17 | bubble_sort(nums) 18 | print(nums) 19 | -------------------------------------------------------------------------------- /Tower of hanoi--C++/TowerOfHanoi.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void towerOfHanoi(int n, char sor, char des, char aux) 5 | { 6 | if (n == 1) 7 | { 8 | cout << "Move disk 1 from rod " << sor << " to rod " << des< A[j]: 14 | min_idx = j 15 | 16 | # Swap the found minimum element with 17 | # the first element 18 | A[i], A[min_idx] = A[min_idx], A[i] 19 | 20 | # Driver code to test above 21 | print ("Sorted array") 22 | for i in range(len(A)): 23 | print("%d" %A[i]), 24 | -------------------------------------------------------------------------------- /Python/parenthesisBalancing.py: -------------------------------------------------------------------------------- 1 | 2 | #stack is used to make parenthesis balancing checker 3 | 4 | 5 | def checker(inp): 6 | stre='' 7 | pairs={} 8 | pairs[')']='(' 9 | pairs['}']='{' 10 | pairs[']']='[' 11 | stack=[] 12 | for i in list(inp): 13 | if i==']' or i=='}' or i==')': 14 | len(stack)==0 or stack.pop() != pairs[i] ? return False:pass 15 | else : 16 | stack.push(i) 17 | return True 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | def main(): 27 | inp=str(input("Enter the word:")) 28 | print ( "balanced" if checker(inp) else "un-balanced") 29 | 30 | 31 | 32 | main() 33 | -------------------------------------------------------------------------------- /C++/SieveOfEratosthenes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | void SieveOfEratosthenes(int n) 9 | { 10 | long int i,p; 11 | bool arr[n+1]; 12 | memset(arr,true,sizeof(arr)); 13 | for(i=2;i*i<=n;i++) 14 | { 15 | if(arr[i]==true) 16 | { 17 | for(p=i*i;p<=n;p=p+i) 18 | { 19 | arr[p]=false; 20 | } 21 | } 22 | } 23 | for(i=2;i<=n;i++) 24 | { 25 | if(arr[i]==true) 26 | cout<>x; 33 | SieveOfEratosthenes(x); 34 | getch(); 35 | return (0); 36 | } 37 | -------------------------------------------------------------------------------- /Linear search(Recursively).cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int linearSearch(int *a,int i,int n,int key) 4 | { 5 | // If element is not present then it will return -1 6 | if(i==n) 7 | { 8 | return -1; 9 | } 10 | //If the element is present then it will return the index where the element is present 11 | if(a[i]==key) 12 | { 13 | return i; 14 | } 15 | return linearSearch(a,i+1,n,key); 16 | } 17 | int main() 18 | { 19 | int a[6]={1,3,2,5,6,9}; 20 | int n=sizeof(a)/sizeof(int); 21 | int key = 15; 22 | cout< 3 | 4 | using namespace std; 5 | 6 | int countWays(int n, int m) 7 | { 8 | 9 | int count[n + 1]; 10 | count[0] = 0; 11 | 12 | 13 | for (int i = 1; i <= n; i++) { 14 | 15 | if (i > m) 16 | count[i] = count[i - 1] + count[i - m]; 17 | 18 | 19 | else if (i < m) 20 | count[i] = 1; 21 | 22 | 23 | else 24 | count[i] = 2; 25 | } 26 | 27 | 28 | return count[n]; 29 | } 30 | 31 | 32 | int main() 33 | { 34 | int n = 7, m = 4; 35 | cout << "Number of ways = " 36 | << countWays(n, m); 37 | return 0; 38 | } 39 | 40 | -------------------------------------------------------------------------------- /Dynamic Programming/Climbing_Stairs/C++/climb.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | int count(int n, int m) 5 | { 6 | int stairs[n]; 7 | stairs[0] = 1; stairs[1] = 1; 8 | for (int i=2; i 3 | #include 4 | using big_int = boost::multiprecision::cpp_int; 5 | using namespace std; 6 | 7 | int fibo(int n) 8 | { 9 | 10 | big_int a = 0; 11 | big_int b = 1; 12 | cout <>n; 28 | 29 | fibo(n); 30 | 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /Searching and Sorting/Quick Sort/Python/quicksort_inplace.py: -------------------------------------------------------------------------------- 1 | # Source : https://stackoverflow.com/questions/18262306/quicksort-with-python 2 | # Thanks To alisianoi 3 | 4 | import random 5 | 6 | 7 | def qsort(x, first, last): 8 | if first >= last: 9 | return 10 | 11 | i, j = first, last 12 | pivot = x[random.randint(first, last)] 13 | 14 | while i <= j: 15 | while x[i] < pivot: 16 | i += 1 17 | while x[j] > pivot: 18 | j -= 1 19 | if i <= j: 20 | x[i], x[j] = x[j], x[i] 21 | i, j = i + 1, j - 1 22 | qsort(x, first, j) 23 | qsort(x, i, last) 24 | -------------------------------------------------------------------------------- /euler-totient-in_python.py: -------------------------------------------------------------------------------- 1 | # A simple Python3 program 2 | # to calculate Euler's 3 | # Totient Function 4 | 5 | # Function to return 6 | # gcd of a and b 7 | def gcd(a, b): 8 | 9 | if (a == 0): 10 | return b 11 | return gcd(b % a, a) 12 | 13 | # A simple method to evaluate 14 | # Euler Totient Function 15 | def phi(n): 16 | 17 | result = 1 18 | for i in range(2, n): 19 | if (gcd(i, n) == 1): 20 | result+=1 21 | return result 22 | 23 | # Driver Code 24 | for n in range(1, 11): 25 | print("phi(",n,") = ", 26 | phi(n), sep = "") 27 | 28 | # This code is contributed 29 | # by Smitha 30 | -------------------------------------------------------------------------------- /C++/recursion/bubbleSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void bubbleSort(int a[],int n) 5 | { 6 | //Base Case 7 | if(n==1) 8 | { 9 | return; 10 | } 11 | // Sort 1 element ,and call for remaining n-1 elements 12 | 13 | for(int j=0;j<=n-2;j++) 14 | { 15 | if(a[j]>a[j+1]) 16 | { 17 | swap(a[j],a[j+1]); 18 | } 19 | } 20 | bubbleSort(a,n-1); 21 | } 22 | int main() 23 | { 24 | int a[]={5,4,3,2,1}; 25 | int n=5; 26 | bubbleSort(a,n); 27 | 28 | for(int i=0;i 3 | #include 4 | using big_int = boost::multiprecision::cpp_int; 5 | using namespace std; 6 | 7 | int fibo(int n) 8 | { 9 | 10 | big_int a = 0; 11 | big_int b = 1; 12 | cout <>n; 28 | 29 | fibo(n); 30 | 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /Math/Consecutive_Numbers_Sum/consecutive_numbers_sum.cpp: -------------------------------------------------------------------------------- 1 | // Given a positive integer N, how many ways can we write it as a sum of consecutive positive integers? 2 | 3 | #include 4 | #include 5 | 6 | int consecutiveNumbersSum(int N) { 7 | int res = 0; 8 | double NN = N; 9 | int maxTerms = (int)(sqrt(8 * NN + 1) - 1) / 2; 10 | for (int n = 1; n <= maxTerms; n++) { 11 | int temp = N - (n - 1) * n / 2; 12 | if (temp > 0 && temp % n == 0) res++; 13 | } 14 | return res; 15 | } 16 | 17 | int main() { 18 | int sum = consecutiveNumbersSum(15); 19 | assert(sum == 4); 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /Math/Sieve of Eratosthenes/golang/sieveOfErathosthenes.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | var MAXN int = 1000 6 | 7 | func Sieve() { 8 | prime := make([]bool, MAXN) 9 | for i, _ := range prime { 10 | prime[i] = true 11 | } 12 | for i := 2; i < MAXN; i += 1{ 13 | for j := i; i*j < MAXN; j += 1 { 14 | prime[i*j] = false; 15 | } 16 | } 17 | for i, flag := range prime { 18 | if (flag == true && i > 1) { 19 | fmt.Println(i) 20 | } 21 | } 22 | } 23 | 24 | //execution starts here 25 | 26 | func main(){ 27 | fmt.Println("This program prints all the prime numbers from 2 to MAXN") 28 | Sieve() 29 | } 30 | -------------------------------------------------------------------------------- /list-operations/Element-insertion/Python/insertion.py: -------------------------------------------------------------------------------- 1 | 2 | #this program doesn't use inbuild list functions except append 3 | 4 | def insertion(arr): #inserting an element at a particular index of the list 5 | global n 6 | x = int(input("postion :")) 7 | y = int(input("element :")) 8 | arr.append(arr[-1]) 9 | for i in range(n-1,x,-1): 10 | arr[i] =arr[i-1] 11 | arr[x] = y 12 | n = n+1 #incrementing the list size variable 13 | 14 | 15 | n =int(input('No. of elements : ')) 16 | arr = [] 17 | print("Input the elements of the list\n") 18 | for i in range(n): 19 | x =int(input()) 20 | arr.append(x) 21 | 22 | 23 | insertion(arr) 24 | print(arr) 25 | -------------------------------------------------------------------------------- /Searching and Sorting/Shell Sort/ShellSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void shellSort(int *arr, int n){ 5 | for(int gap=n/2;gap>0;gap/=2){ 6 | for(int i=gap;i=gap && arr[j-gap]>temp;j=j-gap){ 9 | arr[j]=arr[j-gap]; 10 | } 11 | arr[j]=temp; 12 | } 13 | } 14 | } 15 | 16 | int main(){ 17 | int n; cin>>n; 18 | int *arr=new int[n]; 19 | for(int i=0;i>arr[i]; 20 | shellSort(arr,n); 21 | cout<<"After Sorting: "; 22 | for(int i=0;i 3 | using namespace std; 4 | 5 | // A recursive function to find nth catalan number 6 | unsigned long int catalan(unsigned int n) 7 | { 8 | // Base case 9 | if (n <= 1) return 1; 10 | 11 | // catalan(n) is sum of catalan(i)*catalan(n-i-1) 12 | unsigned long int res = 0; 13 | for (int i=0; i 2 | using namespace std; 3 | 4 | //Note that the below code works only for distinct longest increasing subsequence 5 | // If you want also want duplicate elements in LIS then change lower_bound to upper_bound and it will account for duplicates as well 6 | 7 | int main() { 8 | int n; 9 | cin >> n; 10 | vector dp; 11 | 12 | for (int i = 0; i < n; i++) { 13 | int x; 14 | cin >> x; 15 | auto it = lower_bound(dp.begin(), dp.end(), x); 16 | if (it == dp.end()) { 17 | dp.push_back(x); 18 | } else { 19 | *it = x; 20 | } 21 | } 22 | 23 | cout << dp.size() << endl; 24 | } 25 | -------------------------------------------------------------------------------- /Python/QuickSort.py: -------------------------------------------------------------------------------- 1 | def quickSort(arr): 2 | less = [] 3 | pivotList = [] 4 | more = [] 5 | if len(arr) <= 1: 6 | return arr 7 | else: 8 | pivot = arr[0] 9 | for i in arr: 10 | if i < pivot: 11 | less.append(i) 12 | elif i > pivot: 13 | more.append(i) 14 | else: 15 | pivotList.append(i) 16 | less = quickSort(less) 17 | more = quickSort(more) 18 | return less + pivotList + more 19 | 20 | if __name__ == "__main__": 21 | arr=[int(x) for x in input("Enter the array elements : ").split()] 22 | a = quickSort(arr) 23 | print(a) -------------------------------------------------------------------------------- /C++/recursion/Tower of Hanoi.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void towerofHanoi(int n,char src,char dest,char helper) 5 | { 6 | // Base case 7 | if(n==0) 8 | { 9 | return; 10 | } 11 | //Rec case 12 | // First step N-1 disks move from src to helper 13 | 14 | towerofHanoi(n-1,src,helper,dest); 15 | // Shift Nth disk from src to dest 16 | 17 | cout<<"Move "<>n; 27 | towerofHanoi(n,'A','B','C'); 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /MonkeySort/monkeySort.js: -------------------------------------------------------------------------------- 1 | //the worst/best sorting Algorithm 2 | numbers = []; 3 | function fillNumbers() { 4 | for (i = 0; i < 100; i++) { 5 | numbers[i] = Math.random() * 10 6 | } 7 | } 8 | function sort() { 9 | while (!isSorted(numbers)) { 10 | for(i=0;i 2 | using namespace std; 3 | 4 | int maxSubArraySum(int a[], int size) 5 | { 6 | int max_so_far = 0, max_ending_here = 0; 7 | for (int i = 0; i < size; i++) 8 | { 9 | max_ending_here = max_ending_here + a[i]; 10 | if (max_ending_here < 0) 11 | max_ending_here = 0; 12 | else if (max_so_far < max_ending_here) 13 | max_so_far = max_ending_here; 14 | } 15 | return max_so_far; 16 | } 17 | int main() 18 | { 19 | int a[] = {-2, -3, 4, -1, -2, 1, 5, -3}; 20 | int n = sizeof(a)/sizeof(a[0]); 21 | int max_sum = maxSubArraySum(a, n); 22 | cout << "Maximum contiguous sum is " << max_sum; 23 | return 0; 24 | } -------------------------------------------------------------------------------- /Python/power.py: -------------------------------------------------------------------------------- 1 | def power(x, y): 2 | if(y == 0): 3 | return 1 4 | if(y < 0): 5 | n = (1/x) * power(x, (y+1)/2) 6 | return n*n 7 | if(y%2 == 0): 8 | m = power(x, y/2) 9 | return m*m 10 | else: 11 | return x * power(x, y-1) 12 | 13 | def main(): 14 | print("To calculate x^y ...\n") 15 | x = float(input("Please enter x: ")) 16 | y = float(input("Please enter y: ")) 17 | 18 | if(x==0): 19 | if(y > 0): 20 | print(0) 21 | else: 22 | print("x^y is not defined\n") 23 | else: 24 | print(power(x,y)) 25 | exit 26 | 27 | if __name__ == '__main__': 28 | main() -------------------------------------------------------------------------------- /Dynamic Programming/Window Sliding Technique/Python3/MaxSumArray.py: -------------------------------------------------------------------------------- 1 | '''Given an array of integers of size ‘n’. 2 | Our aim is to calculate the maximum sum of ‘k’ 3 | consecutive elements in the array''' 4 | 5 | import sys 6 | INT_MIN = -sys.maxsize -1 7 | 8 | def maxSum(arr, n, k): 9 | 10 | max_sum = INT_MIN ; 11 | 12 | for i in range(n - k + 1): 13 | current_sum = 0; 14 | for j in range(k): 15 | current_sum = current_sum + arr[i + j]; 16 | 17 | max_sum = max(current_sum, max_sum ); 18 | 19 | return max_sum; 20 | 21 | 22 | arr = [1, 4, 2, 10, 2, 23 | 3, 1, 0, 20]; 24 | k = 4; 25 | n = len(arr); 26 | print(maxSum(arr, n, k)); 27 | -------------------------------------------------------------------------------- /Sorting Algorithm/Selection Sort/Python/selection_sort.py: -------------------------------------------------------------------------------- 1 | # Function for selection sort 2 | def selection_sort(array): 3 | for i in range(0, len(array) - 1): 4 | min_index = i 5 | 6 | for j in range(i + 1, len(array)): 7 | if array[j] < array[min_index]: 8 | min_index = j 9 | 10 | array[i], array[min_index] = array[min_index], array[i] 11 | 12 | # Function to print list 13 | def print_list(array): 14 | for i in range(0, len(array)): 15 | print(array[i], end = " ") 16 | 17 | print() 18 | 19 | num = int(input()) 20 | array = [] 21 | for i in range(0, num): 22 | array.append(int(input())) 23 | selection_sort(array) 24 | print_list(array) 25 | -------------------------------------------------------------------------------- /euler-totient.c: -------------------------------------------------------------------------------- 1 | // A simple C program to calculate Euler's Totient Function 2 | #include 3 | 4 | // Function to return gcd of a and b 5 | int gcd(int a, int b) 6 | { 7 | if (a == 0) 8 | return b; 9 | return gcd(b % a, a); 10 | } 11 | 12 | // A simple method to evaluate Euler Totient Function 13 | int phi(unsigned int n) 14 | { 15 | unsigned int result = 1; 16 | for (int i = 2; i < n; i++) 17 | if (gcd(i, n) == 1) 18 | result++; 19 | return result; 20 | } 21 | 22 | // Driver program to test above function 23 | int main() 24 | { 25 | int n; 26 | for (n = 1; n <= 10; n++) 27 | printf("phi(%d) = %d\n", n, phi(n)); 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /Math/Factorization/trial_division.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | // Input = Number to be factorized 6 | // Output = factors 7 | 8 | vector trial_division1(long long n) { 9 | vector factorization; 10 | for (long long d = 2; d * d <= n; d++) { 11 | while (n % d == 0) { 12 | factorization.push_back(d); 13 | n /= d; 14 | } 15 | } 16 | if (n > 1) 17 | factorization.push_back(n); 18 | return factorization; 19 | } 20 | 21 | int main() { 22 | vector factors = trial_division1(55); 23 | for (int factor : factors) { 24 | cout << factor << " "; 25 | } 26 | return 0; 27 | } -------------------------------------------------------------------------------- /Dynamic Programming/unbounded knapsack/c++/unboundedknapsack.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | int uKnapsack(int C, int N, int value[], int weight[]) 6 | { 7 | int Knap[C+1]; 8 | memset(Knap, 0, sizeof Knap); 9 | 10 | int res = 0; 11 | for (int i=0; i<=C; i++) 12 | for (int j=0; j 0) and 14 | (open_list[pos] == stack[len(stack)-1])): 15 | stack.pop() 16 | else: 17 | return "Unbalanced" 18 | if len(stack) == 0: 19 | return "Balanced" 20 | 21 | # Driver code 22 | string = "{[]{()}}" 23 | print(string,"-", check(string)) 24 | 25 | string = "[{}{})(]" 26 | print(string,"-", check(string)) 27 | -------------------------------------------------------------------------------- /Tapping Rain Water: -------------------------------------------------------------------------------- 1 | class Test 2 | { 3 | static int arr[] = new int[]{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}; //Example 4 | 5 | static int findWater(int n) 6 | { 7 | int left[] = new int[n]; 8 | int right[] = new int[n]; 9 | 10 | int water = 0; 11 | left[0] = arr[0]; 12 | for (int i = 1; i < n; i++) 13 | left[i] = Math.max(left[i-1], arr[i]); 14 | right[n-1] = arr[n-1]; 15 | for (int i = n-2; i >= 0; i--) 16 | right[i] = Math.max(right[i+1], arr[i]); 17 | for (int i = 0; i < n; i++) 18 | water += Math.min(left[i],right[i]) - arr[i]; 19 | 20 | return water; 21 | } 22 | 23 | -------------------------------------------------------------------------------- /balanced parentheses.py: -------------------------------------------------------------------------------- 1 | # Python3 code to Check for 2 | # balanced parentheses in an expression 3 | open_list = ["[","{","("] 4 | close_list = ["]","}",")"] 5 | 6 | # Function to check parentheses 7 | def check(myStr): 8 | stack = [] 9 | for i in myStr: 10 | if i in open_list: 11 | stack.append(i) 12 | elif i in close_list: 13 | pos = close_list.index(i) 14 | if ((len(stack) > 0) and 15 | (open_list[pos] == stack[len(stack)-1])): 16 | stack.pop() 17 | else: 18 | return "Unbalanced" 19 | if len(stack) == 0: 20 | return "Balanced" 21 | 22 | # Driver code 23 | string = "{[]{()}}" 24 | print(string,"-", check(string)) 25 | 26 | string = "[{}{})(]" 27 | print(string,"-", check(string)) 28 | -------------------------------------------------------------------------------- /C++/Trapping Rain Water: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int n; 7 | cin>>n; 8 | int arr[n]; 9 | 10 | for(int i = 0 ; i < n ; i++) 11 | cin>>arr[i]; 12 | 13 | int left[n]; 14 | int right[n]; 15 | 16 | left[0]=arr[0]; 17 | 18 | for(int i = 1; i < n ; i++) 19 | { left[i] = max(left[i-1],arr[i]); 20 | 21 | } 22 | right[n-1] = arr[n-1]; 23 | 24 | for(int i = n-2; i>=0; i--) 25 | right[i] = max(right[i+1],arr[i]); 26 | 27 | int water = 0 ; 28 | 29 | for(int i = 0 ; i < n ; i++) 30 | { 31 | water += min(left[i],right[i])-arr[i]; 32 | } 33 | 34 | cout< 2 | #include 3 | char array[100000],pattern[1000]; // max size of string and pattern 4 | int main() 5 | { 6 | int i,j,len_arr,len_pattern; 7 | 8 | scanf("%s",array); 9 | len_arr=strlen(array); 10 | 11 | scanf("%s",pattern); 12 | len_pattern=strlen(pattern); 13 | 14 | for(i=0;i 2 | #include 3 | int main() 4 | { 5 | int arr[10], i, j, k, Size; 6 | 7 | printf("\n Enter size of array :"); 8 | scanf("%d",&Size); 9 | 10 | printf("\n Enter array elements:"); 11 | for (i = 0; i 3 | using namespace std; 4 | 5 | int optimalGame(int a[], int n) 6 | { 7 | 8 | int dp[n][n]; 9 | for (int g = 0; g < n; ++g) { 10 | for (int i = 0, j = g; j < n; ++i, ++j) { 11 | 12 | int x = ((i + 2) <= j) ? dp[i + 2][j] : 0; 13 | int y = ((i + 1) <= (j - 1)) ? dp[i + 1][j - 1] : 0; 14 | int z = (i <= (j - 2)) ? dp[i][j - 2] : 0; 15 | 16 | dp[i][j] = max(a[i] + min(x, y), a[j] + min(y, z)); 17 | } 18 | } 19 | 20 | return dp[0][n - 1]; 21 | } 22 | 23 | int main() 24 | { 25 | int a[] = { 8, 16, 5, 7 }; 26 | int n = sizeof(a) / sizeof(a); 27 | printf("%d\n", optimalGame(a, n)); 28 | 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /C++/BitwiseOperators.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | 6 | //Bitwise operators works on bits instead of the numbers. Cannot directly cout them. Store them in int variable first 7 | 8 | int a,b; 9 | cin >> a >> b; 10 | int c = a & b; //Bitwise AND operator 11 | int d = a | b; //Bitwise OR operator 12 | int e = ~a; //Bitwise NOT operator 13 | int f = a << 1; //Bitwise right shift operator (we remove the left most digit and add 0 at the right most part) 14 | int g = a >> 1; //Bitwise left shift operator (we remove the right most bit and add 0 at the left most part) 15 | int h = a ^ b; //Bitwise XOR operator (XOR's on bits) 16 | cout< 2 | 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | //Program to study vectors and see its different functions use 8 | // vector v; 9 | vector v; 10 | vector arr{ 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; 11 | 12 | sort(arr.begin(), arr.end()); 13 | 14 | cout << "Sorted \n"; 15 | for (int i=0;i>n; 22 | v.push_back(n); 23 | cout< 3 | using namespace std; 4 | 5 | int maxSum(int a[], int N) 6 | { 7 | int i, j, max = 0; 8 | int dp[N]; 9 | 10 | for ( i = 0; i < N; i++ ) 11 | dp[i] = a[i]; 12 | 13 | for ( i = 1; i < N; i++ ) 14 | for ( j = 0; j < i; j++ ) 15 | if (a[i] > a[j] && 16 | dp[i] < dp[j] + a[i]) 17 | dp[i] = dp[j] + a[i]; 18 | 19 | return *max_element(dp, dp+N); 20 | } 21 | 22 | 23 | int main() 24 | { 25 | int arr[] = {1, 100, 6, 4, 105, 2, 3}; 26 | int n = sizeof(arr)/sizeof(arr[0]); 27 | cout << "Sum of elements in the maximum sum increasing " 28 | "subsequence is " << maxSum( arr, n ) << endl; 29 | return 0; 30 | } 31 | 32 | -------------------------------------------------------------------------------- /Searching and Sorting/Bubble Sort/C++/BubbleSort.cpp: -------------------------------------------------------------------------------- 1 | //Coding Bubble Sort Algorithm 2 | #include 3 | using namespace std ; 4 | 5 | void BubbleSort(int arr[] , int n) 6 | { 7 | 8 | 9 | for(int i=0 ; iarr[j+1]) 15 | { 16 | int temp ; 17 | temp=arr[j]; 18 | arr[j]=arr[j+1]; 19 | arr[j+1]=temp ; 20 | } 21 | 22 | } 23 | } 24 | 25 | } 26 | 27 | int main(){ 28 | int n,arr[50] ; 29 | cin >> n ; 30 | 31 | for(int i=0 ; i> arr[i]; 34 | } 35 | 36 | BubbleSort(arr,n); 37 | 38 | for(int i=0 ; i 3 | using namespace std ; 4 | 5 | void BubbleSort(int arr[] , int n) 6 | { 7 | 8 | 9 | for(int i=0 ; iarr[j+1]) 15 | { 16 | int temp ; 17 | temp=arr[j]; //perform swap 18 | arr[j]=arr[j+1]; 19 | arr[j+1]=temp ; 20 | } 21 | 22 | } 23 | } 24 | 25 | } 26 | 27 | int main(){ 28 | int n,arr[50] ; 29 | cin >> n ; 30 | 31 | for(int i=0 ; i> arr[i]; 34 | } 35 | 36 | BubbleSort(arr,n); 37 | 38 | for(int i=0 ; i 2 | using namespace std; 3 | class BOOKX { 4 | private: 5 | char book_name; 6 | char book_author; 7 | int book_price; 8 | int book_edition; 9 | public: 10 | void input() { 11 | cout<<"Book name:"; 12 | cin>>book_name; 13 | cout<>book_author; 16 | cout<>book_price; 19 | cout<>book_edition; 22 | cout< 2 | using namespace std; 3 | int main() 4 | { 5 | int n; 6 | cout<<"Enter the length of the array : "; 7 | cin>>n; 8 | int a[n]; 9 | cout<<"Insert the elements to perform sorting... "<>a[u]; 14 | } 15 | 16 | 17 | int j,key,i; 18 | for (i = 1; i < n; i++) 19 | { 20 | key = a[i]; 21 | j = i - 1; 22 | while (j>=0&& a[j]>key) 23 | { 24 | a[j + 1] = a[j]; 25 | j=j-1; 26 | } 27 | a[j+1]=key; 28 | } 29 | for (i = 0; i < n; i++) 30 | cout< 5 | using namespace std; 6 | int main() 7 | { 8 | int a[100]={0}; 9 | int n; 10 | int cs=0;//cs is the current sum 11 | int ms=0;//ms is the maximum sum 12 | cout<<"Enter the number of elements in the array"; 13 | cin>>n; 14 | for(int i=0;i>a[i]; 17 | } 18 | for(int i=0;i 2 | #include 3 | 4 | void swap(int *x,int *y) 5 | { 6 | int temp=*x; 7 | *x=*y; 8 | *y=temp; 9 | } 10 | int partition(int A[],int l,int h) 11 | { 12 | int pivot=A[l]; 13 | int i=l,j=h; 14 | do 15 | { 16 | do{i++;}while(A[i]<=pivot); 17 | do{j--;}while(A[j]>pivot); 18 | if(i 0) : 14 | 15 | # If y is odd, multiply 16 | # x with result 17 | if ((y & 1) == 1) : 18 | res = (res * x) % p 19 | 20 | # y must be even now 21 | y = y >> 1 # y = y/2 22 | x = (x * x) % p 23 | 24 | return res 25 | 26 | 27 | # Driver Code 28 | 29 | x = 2; y = 5; p = 13 30 | print("Power is ", power(x, y, p)) 31 | -------------------------------------------------------------------------------- /Tree Traversal/DFS/C++/DFS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | bool adj_matrix[101][101]={0}; 5 | bool visited[101]={0}; 6 | int n; 7 | 8 | void DFS(int s) 9 | { 10 | visited[s]=1; 11 | cout<>n; 21 | int m; 22 | cout<<"Enter number of edges: "; 23 | cin>>m; 24 | cout<<"Enter edges starting from source node:\n"; 25 | for(int i=0;i>x>>y; 29 | adj_matrix[x][y]=1; 30 | 31 | } 32 | int s; 33 | cout<<"Re-enter source node"; 34 | cin>>s; 35 | cout<<"DFS with Source "< 2 | using namespace std; 3 | 4 | bool adj_matrix[101][101]={0}; 5 | bool visited[101]={0}; 6 | int n; 7 | 8 | void DFS(int s) 9 | { 10 | visited[s]=1; 11 | cout<>n; 21 | int m; 22 | cout<<"Enter number of edges: "; 23 | cin>>m; 24 | cout<<"Enter edges starting from source node:\n"; 25 | for(int i=0;i>x>>y; 29 | adj_matrix[x][y]=1; 30 | 31 | } 32 | int s; 33 | cout<<"Re-enter source node"; 34 | cin>>s; 35 | cout<<"DFS with Source "< 0) and 14 | (open_list[pos] == stack[len(stack)-1])): 15 | stack.pop() 16 | else: 17 | return "Unbalanced" 18 | if len(stack) == 0: 19 | return "Balanced" 20 | 21 | # Driver code 22 | string = "{[]{()}}" 23 | print(string,"-", check(string)) 24 | 25 | string = "[{}{})(]" 26 | print(string,"-", check(string)) 27 | -------------------------------------------------------------------------------- /C/dfs.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void DFS(int); 4 | int G[10][10],visited[10],n; //n is no of vertices and graph is sorted in array G[10][10] 5 | 6 | void main() 7 | { 8 | int i,j; 9 | printf("Enter number of vertices:"); 10 | 11 | scanf("%d",&n); 12 | 13 | //read the adjecency matrix 14 | printf("\nEnter adjecency matrix of the graph:"); 15 | 16 | for(i=0;i Array(J + 1) Then ' Compare neighboring elements 12 | Temp = Array(J) 13 | Array(J) = Array(J + 1) 14 | Array(J + 1) = Temp 15 | 16 | End If 17 | Next 18 | Next 19 | End Sub 20 | End Module -------------------------------------------------------------------------------- /Sorting Algorithm/Counting Sort/CountingSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | typedef long long ll; 4 | typedef vector vi; 5 | typedef pair pi; 6 | #define F first 7 | #define S second 8 | #define PB push_back 9 | #define MP make_pair 10 | #define REP(i,a,b) for (int i = a; i <= b; i++) 11 | int main(){ 12 | ios::sync_with_stdio(0); 13 | //cin.tie(0); 14 | int SIZE=10,MAX_SIZE=10000; 15 | int arr[10]={5,2,3,1,9,10,10,2,9,19}; 16 | int count[MAX_SIZE]={0}; 17 | for(int i=0;i 4 | using namespace std; 5 | int main() 6 | { 7 | 8 | int n, i, j, temp; 9 | cout<<"Enter total number of elements :"; 10 | cin>>n; 11 | int arr[n]; 12 | cout<<"Enter "<>arr[i]; 16 | } 17 | cout<<"Sorting array using bubble sort technique...\n"; 18 | for(i=0; i<(n-1); i++) 19 | { 20 | for(j=0; j<(n-i-1); j++) 21 | { 22 | if(arr[j]>arr[j+1]) 23 | { 24 | temp=arr[j]; 25 | arr[j]=arr[j+1]; 26 | arr[j+1]=temp; 27 | } 28 | } 29 | } 30 | cout<<"Elements sorted successfully..!!\n"; 31 | cout<<"Sorted list in ascending order :\n"; 32 | for(i=0; i 4 | #include 5 | #include 6 | 7 | void towerOfHanoi(int n, char from_rod, 8 | char to_rod, char aux_rod) 9 | { 10 | if (n == 1) 11 | { 12 | printf("Move disk 1 from rod %c to %c" ,from_rod,to_rod); 13 | printf("\n"); 14 | return; 15 | } 16 | towerOfHanoi(n - 1, from_rod, aux_rod, to_rod); 17 | printf("Move disk %d from rod %c to rod %c",n,from_rod,to_rod); 18 | printf("\n"); 19 | towerOfHanoi(n - 1, aux_rod, to_rod, from_rod); 20 | } 21 | 22 | // Driver code 23 | int main() 24 | { 25 | int n = 4; // Number of disks 26 | towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods 27 | return 0; 28 | } 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /modular_exponentiation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define mod 1000000007 4 | #define ll long long int 5 | #define pb push_back 6 | #define mp make_pair 7 | #define rep(a,b,c) for(int i = a; i < b; i+=c) 8 | 9 | /* Iterative Function to calculate (x^y) in O(log y) */ 10 | int power(int x, unsigned int y) 11 | { 12 | int res = 1; // Initialize result 13 | 14 | while (y > 0) 15 | { 16 | // If y is odd, multiply x with result 17 | if (y & 1) 18 | res = res*x; 19 | // y must be even now 20 | y = y>>1; // y = y/2 21 | x = x*x; // Change x to x^2 22 | } 23 | return res; 24 | } 25 | 26 | int main() 27 | { 28 | int n,m; 29 | cin>>n>>m; 30 | cout< 2 | using namespace std; 3 | int multrecur(int n, int m) 4 | { 5 | if (n > 0 && m < 0) { 6 | return multrecur(m, n); 7 | } 8 | else if (n < 0 && m < 0) { 9 | return multrecur((-1 * n), (-1 * m)); 10 | } 11 | if (n > m) { 12 | return multrecur(m, n); 13 | } 14 | else if (m != 0) { 15 | return n + multrecur(n, m - 1); 16 | } 17 | else { 18 | return 0; 19 | } 20 | } 21 | int main() 22 | { 23 | cout << "10 * 5 = " << multrecur(10, 5) << endl; 24 | cout << "10 * (-5) = " << multrecur(10, -5) << endl; 25 | cout << "(-10) * 5 = " << multrecur(-10, 5) << endl; 26 | cout << "(-10) * (-5) = " << multrecur(-10, -5) << endl; 27 | return 0; 28 | } -------------------------------------------------------------------------------- /Array Reversal.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | int num, *arr, i; 7 | scanf("%d", &num); 8 | arr = (int*) malloc(num * sizeof(int)); 9 | for(i = 0; i < num; i++) { 10 | scanf("%d", arr + i); 11 | } 12 | int* left_ptr = arr; 13 | int* right_ptr; 14 | int temp; 15 | for(i = 0; i < num; i++) { 16 | if(i == num - 1) { 17 | right_ptr = (arr + i); 18 | } 19 | } 20 | while(left_ptr < right_ptr) { 21 | temp = *right_ptr; 22 | *right_ptr = *left_ptr; 23 | *left_ptr = temp; 24 | right_ptr--; 25 | left_ptr++; 26 | } 27 | 28 | for(i = 0; i < num; i++) { 29 | printf("%d ", *(arr + i)); 30 | } 31 | free(arr); 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /Searching and Sorting/Insertion Sort/Python/Insertion Sort.py: -------------------------------------------------------------------------------- 1 | # Python program for implementation of Insertion Sort 2 | # https://www.geeksforgeeks.org/insertion-sort/ 3 | # Function to do insertion sort 4 | def insertionSort(arr): 5 | 6 | # Traverse through 1 to len(arr) 7 | for i in range(1, len(arr)): 8 | 9 | key = arr[i] 10 | 11 | # Move elements of arr[0..i-1], that are 12 | # greater than key, to one position ahead 13 | # of their current position 14 | j = i-1 15 | while j >= 0 and key < arr[j] : 16 | arr[j + 1] = arr[j] 17 | j -= 1 18 | arr[j + 1] = key 19 | 20 | 21 | # Driver code to test above 22 | arr = [12, 11, 13, 5, 6] 23 | insertionSort(arr) 24 | for i in range(len(arr)): 25 | print ("% d" % arr[i]) 26 | 27 | # This code is contributed by Mohit Kumra 28 | -------------------------------------------------------------------------------- /Sorting Algorithm/Selection Sort/C++/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void SelectionSort(int list[], int size) 4 | { 5 | int min_pos; 6 | for(int last_pos = 0; last_pos < size; last_pos++) 7 | { 8 | min_pos = last_pos; 9 | for(int i = last_pos; i < size; i++) 10 | { 11 | if(list[min_pos] > list[i]) min_pos = i; 12 | } 13 | int aux = list[last_pos]; 14 | list[last_pos] = list[min_pos]; 15 | list[min_pos] = aux; 16 | } 17 | } 18 | 19 | void PrintList(int list[], int size) 20 | { 21 | for(int n = 0; n < size; n++) 22 | { 23 | std::cout << list[n] << " " << std::flush; 24 | } 25 | 26 | std::cout << std::endl; 27 | } 28 | 29 | int main() 30 | { 31 | int list[6] {2, 1, 7, 3, 3, 5}; 32 | PrintList(list, 6); 33 | SelectionSort(list, 6); 34 | PrintList(list,6); 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /Python/RadixSort.py: -------------------------------------------------------------------------------- 1 | def radixsort( aList ): 2 | RADIX = 10 3 | maxLength = False 4 | tmp , placement = -1, 1 5 | 6 | while not maxLength: 7 | maxLength = True 8 | # declare and initialize buckets 9 | buckets = [list() for _ in range( RADIX )] 10 | 11 | # split aList between lists 12 | for i in aList: 13 | tmp = i / placement 14 | buckets[int(tmp % RADIX)].append( i ) 15 | if maxLength and tmp > 0: 16 | maxLength = False 17 | 18 | # empty lists into aList array 19 | a = 0 20 | for b in range( RADIX ): 21 | buck = buckets[b] 22 | for i in buck: 23 | aList[a] = i 24 | a += 1 25 | 26 | # move to next digit 27 | placement *= RADIX 28 | 29 | A = [18, 5, 100, 3, 1, 19, 6, 0, 7, 4, 2] 30 | radixsort( A ) 31 | print (A) -------------------------------------------------------------------------------- /Divide and Conquer/majority_element.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | int get_majority_element(vector &a, int left, int right) { 8 | map m; 9 | for(int i=0;i=eq){ 20 | return 1; 21 | } 22 | } 23 | 24 | 25 | 26 | 27 | 28 | 29 | //write your code here 30 | return 0; 31 | } 32 | 33 | int main() { 34 | int n; 35 | cin >> n; 36 | vector a(n); 37 | for (size_t i = 0; i < a.size(); ++i) { 38 | cin >> a[i]; 39 | } 40 | cout << (get_majority_element(a, 0, a.size())) << '\n'; 41 | } 42 | -------------------------------------------------------------------------------- /Linked List/DoublyLL.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | struct node 4 | { 5 | int data; 6 | node* next; 7 | node* prev; 8 | }; 9 | void push(node** head, int data) 10 | { 11 | node* new_node = new node(); 12 | new_node->data = data; 13 | new_node->next = (*head); 14 | new_node->prev = NULL; 15 | if ((*head) != NULL) 16 | (*head)->prev = new_node; 17 | (*head) = new_node; 18 | } 19 | void printList(node* head) 20 | { 21 | while (head != NULL) 22 | { 23 | cout<<" "<data<<" "; 24 | head = head->next; 25 | } 26 | 27 | } 28 | int main() 29 | { 30 | node* head = NULL; 31 | push(&head, 1); 32 | push(&head, 4); 33 | cout << "DLL: "; 34 | printList(head); 35 | return 0; 36 | } 37 | // Output is 38 | // DLL: 4 1 -------------------------------------------------------------------------------- /Tower Of Hanoi/TOH.java: -------------------------------------------------------------------------------- 1 | // Java recursive program to solve tower of hanoi puzzle 2 | 3 | class GFG 4 | { 5 | // Java recursive function to solve tower of hanoi puzzle 6 | static void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) 7 | { 8 | if (n == 1) 9 | { 10 | System.out.println("Move disk 1 from rod " + from_rod + " to rod " + to_rod); 11 | return; 12 | } 13 | towerOfHanoi(n-1, from_rod, aux_rod, to_rod); 14 | System.out.println("Move disk " + n + " from rod " + from_rod + " to rod " + to_rod); 15 | towerOfHanoi(n-1, aux_rod, to_rod, from_rod); 16 | } 17 | 18 | // Driver method 19 | public static void main(String args[]) 20 | { 21 | int n = 4; // Number of disks 22 | towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods 23 | } 24 | } 25 | 26 | -------------------------------------------------------------------------------- /Hash_alg/Nuts_and_Bolt.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | void nutboltmatch(char nuts[], char bolts[], int n) 6 | { 7 | unordered_map hash; 8 | 9 | for (int i = 0; i < n; i++) 10 | hash[nuts[i]] = i; 11 | 12 | for (int i = 0; i < n; i++) 13 | if (hash.find(bolts[i]) != hash.end()) 14 | nuts[i] = bolts[i]; 15 | cout << "matched nuts and bolts are-" << endl; 16 | for (int i = 0; i < n; i++) 17 | cout << nuts[i] << " "; 18 | cout << endl; 19 | for (int i = 0; i < n; i++) 20 | cout << bolts[i] << " "; 21 | } 22 | 23 | int main() 24 | { 25 | char nuts[] = {'@', '#', '$', '%', '^', '&'}; 26 | char bolts[] = {'$', '%', '&', '^', '@', '#'}; 27 | int n = sizeof(nuts) / sizeof(nuts[0]); 28 | nutboltmatch(nuts, bolts, n); 29 | return 0; 30 | } 31 | 32 | -------------------------------------------------------------------------------- /Recursive/knapsack_algorithm.py: -------------------------------------------------------------------------------- 1 | ''' 2 | (0-1 Knapsack) example 3 | The example solves the 0/1 Knapsack Problem: 4 | how we get the maximum value, given our knapsack just can hold a maximum weight of w, 5 | while the value of the i-th item is a1[i], and the weight of the i-th item is a2[i]? 6 | 7 | i = total item 8 | w = total weigh of knapsack can carry 9 | ''' 10 | 11 | # a1: item value 12 | a1 = [100, 70, 50, 10] 13 | 14 | # a2: item weight 15 | a2 = [10, 4, 6, 12] 16 | 17 | def knapsack01(items, weight): 18 | if (w == 0) or (i < 0): 19 | return 0 20 | elif (a2[i] > w): 21 | return knapsack01(i-1, w) 22 | else: 23 | return max(a1[i] + knapsack01(i-1, w-a2[i], knapsack01(i-1, w))) 24 | 25 | if __name__ == "__main__": 26 | i = 3 27 | w = 12 28 | print (knapsack01(items=i, weight=w)) -------------------------------------------------------------------------------- /shell_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define ELEMENT_COUNT 100000 4 | 5 | using namespace std; 6 | 7 | int n, d[ELEMENT_COUNT]; 8 | 9 | void Shell_sort() 10 | { 11 | for (int gc = n >> 1; gc >= 1; gc >>= 1) 12 | { 13 | for (int s = 0; s < gc; s++) 14 | { 15 | for (int i = s; i < n; i += gc) 16 | { 17 | for (int j = i - gc; j >= 0 && d[j] > d[j + gc]; j -= gc) 18 | { 19 | int temp = d[j]; 20 | d[j] = d[j + gc]; 21 | d[j + gc] = temp; 22 | } 23 | } 24 | } 25 | } 26 | } 27 | 28 | int main() 29 | { 30 | scanf("%d", &n); 31 | for (int i = 0; i < n; i++) 32 | { 33 | scanf("%d", &d[i]); 34 | } 35 | Shell_sort(); 36 | for (int i = 0; i < n; i++) 37 | { 38 | printf("%d ", d[i]); 39 | } 40 | return 0; 41 | } 42 | 43 | 44 | -------------------------------------------------------------------------------- /Graph Algorithms/closestpairofpoints.py: -------------------------------------------------------------------------------- 1 | from math import sqrt, pow 2 | 3 | def distance(a, b): 4 | return sqrt(pow(a[0] - b[0],2) + pow(a[1] - b[1],2)) 5 | 6 | def bruteMin(points, current=float("inf")): 7 | if len(points) < 2: return current 8 | else: 9 | head = points[0] 10 | del points[0] 11 | newMin = min([distance(head, x) for x in points]) 12 | newCurrent = min([newMin, current]) 13 | return bruteMin(points, newCurrent) 14 | 15 | def divideMin(points): 16 | half = len(sorted(points))/2 17 | minimum = min([bruteMin(points[:half]), bruteMin(points[half:])]) 18 | nearLine = filter(lambda x: x[0] > half - minimum and x[0] < half + minimum, points) 19 | return min([bruteMin(nearLine), minimum]) 20 | 21 | list1 = [(12,30), (40, 50), (5, 1), (12, 10), (3,4)] 22 | print divideMin(list1) 23 | @ask2sm 24 | -------------------------------------------------------------------------------- /Strings/kmpstringmatching.py: -------------------------------------------------------------------------------- 1 | def KMPSearch(pat, txt): 2 | M = len(pat) 3 | N = len(txt) 4 | lps = [0]*M 5 | j = 0 6 | computeLPSArray(pat, M, lps) 7 | 8 | i = 0 9 | while i < N: 10 | if pat[j] == txt[i]: 11 | i += 1 12 | j += 1 13 | 14 | if j == M: 15 | print ("Found pattern at index " ,(i-j)) 16 | j = lps[j-1] 17 | elif i < N and pat[j] != txt[i]: 18 | if j != 0: 19 | j = lps[j-1] 20 | else: 21 | i += 1 22 | def computeLPSArray(pat, M, lps): 23 | len = 0 24 | lps[0] =0 25 | i = 1 26 | while i < M: 27 | if pat[i]== pat[len]: 28 | len += 1 29 | lps[i] = len 30 | i += 1 31 | else: 32 | if len != 0: 33 | len = lps[len-1] 34 | else: 35 | lps[i] = 0 36 | i += 1 37 | txt = "ABABDABACDABABCABAB" 38 | pat = "ABABCABAB" 39 | KMPSearch(pat, txt) 40 | -------------------------------------------------------------------------------- /radix.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include "generic.h" 6 | #include "radix_sort.h" 7 | 8 | int main() 9 | { 10 | using namespace alg; 11 | const int MAX_ELEMENTS = 10; 12 | uint32_t list[MAX_ELEMENTS]; 13 | 14 | int i = 0; 15 | srand(time(NULL)); 16 | // generate random numbers and fill them to the list 17 | for(i = 0; i < MAX_ELEMENTS; i++ ){ 18 | list[i] = rand()%100; 19 | } 20 | 21 | printf("The list before sorting is:\n"); 22 | printlist(list,MAX_ELEMENTS); 23 | 24 | // sort the list using insertion sort 25 | radix_sort(list, MAX_ELEMENTS); 26 | check_order(list, MAX_ELEMENTS); 27 | 28 | // print the result 29 | printf("The list after sorting using radix sort algorithm:\n"); 30 | printlist(list,MAX_ELEMENTS); 31 | 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /C++/egg_dropping.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | int max(int a, int b) { return (a > b)? a: b; } 6 | 7 | 8 | int eggDrop(int n, int k) 9 | { 10 | 11 | if (k == 1 || k == 0) 12 | return k; 13 | 14 | 15 | if (n == 1) 16 | return k; 17 | 18 | int min = INT_MAX, x, res; 19 | 20 | 21 | for (x = 1; x <= k; x++) 22 | { 23 | res = max(eggDrop(n-1, x-1), eggDrop(n, k-x)); 24 | if (res < min) 25 | min = res; 26 | } 27 | 28 | return min + 1; 29 | } 30 | 31 | 32 | int main() 33 | { 34 | int n = 2, k = 10; 35 | cout << "Minimum number of trials in worst case with " 36 | << n << " eggs and " << k << " floors is " 37 | << eggDrop(n, k) << endl; 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /Searching and Sorting/Quick Sort/Python/quick sort.py: -------------------------------------------------------------------------------- 1 | # Source : https://www.geeksforgeeks.org/python-program-for-quicksort/ 2 | # Thanks To Mohit Kumra 3 | def partition(arr,low,high): 4 | i = ( low-1 ) # index of smaller element 5 | pivot = arr[high] # pivot 6 | for j in range(low , high): 7 | if arr[j] <= pivot: 8 | i = i+1 9 | arr[i],arr[j] = arr[j],arr[i] 10 | arr[i+1],arr[high] = arr[high],arr[i+1] 11 | return ( i+1 ) 12 | def quickSort(arr,low,high): 13 | if low < high: 14 | pi = partition(arr,low,high) 15 | quickSort(arr, low, pi-1) 16 | quickSort(arr, pi+1, high) 17 | arr = [10, 7, 8, 9, 1, 5] 18 | n = len(arr) 19 | quickSort(arr,0,n-1) 20 | print ("Sorted array is:") 21 | for i in range(n): 22 | print ("%d" %arr[i]), 23 | -------------------------------------------------------------------------------- /egg_dropping.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | int max(int a, int b) { return (a > b)? a: b; } 6 | 7 | 8 | int eggDrop(int n, int k) 9 | { 10 | 11 | if (k == 1 || k == 0) 12 | return k; 13 | 14 | 15 | if (n == 1) 16 | return k; 17 | 18 | int min = INT_MAX, x, res; 19 | 20 | 21 | for (x = 1; x <= k; x++) 22 | { 23 | res = max(eggDrop(n-1, x-1), eggDrop(n, k-x)); 24 | if (res < min) 25 | min = res; 26 | } 27 | 28 | return min + 1; 29 | } 30 | 31 | 32 | int main() 33 | { 34 | int n = 2, k = 10; 35 | cout << "Minimum number of trials in worst case with " 36 | << n << " eggs and " << k << " floors is " 37 | << eggDrop(n, k) << endl; 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /Dynamic Programming/shotestcommonsupersequence.py: -------------------------------------------------------------------------------- 1 | # A dynamic programming based python program to find length of the shortest supersequence 2 | 3 | # Returns length of the shortest supersequence of X and Y 4 | def superSeq(X, Y, m, n): 5 | dp = [[0] * (n + 2) for i in range(m + 2)] 6 | 7 | # Fill table in bottom up manner 8 | for i in range(m + 1): 9 | for j in range(n + 1): 10 | 11 | #Below steps follow above recurrence 12 | if (not i): dp[i][j] = j 13 | elif (not j): dp[i][j] = i 14 | 15 | elif (X[i - 1] == Y[j - 1]): 16 | dp[i][j] = 1 + dp[i - 1][j - 1] 17 | 18 | else: dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1]) 19 | 20 | return dp[m][n] 21 | 22 | # Driver Code 23 | X = "AGGTAB" 24 | Y = "GXTXAYB" 25 | print("Length of the shortest supersequence is %d" % superSeq(X, Y, len(X), len(Y))) 26 | -------------------------------------------------------------------------------- /Tower Of Hanoi/TOH.cpp: -------------------------------------------------------------------------------- 1 | // C++ recursive function to 2 | // solve tower of hanoi puzzle 3 | #include 4 | using namespace std; 5 | 6 | void towerOfHanoi(int n, char from_rod, 7 | char to_rod, char aux_rod) 8 | { 9 | if (n == 1) 10 | { 11 | cout << "Move disk 1 from rod " << from_rod << 12 | " to rod " << to_rod< 2 | 3 | using namespace std; 4 | 5 | int lcs(string &X, string &Y, int m, int n) 6 | { 7 | int dp[m+1][n+1]; 8 | for(int i=0; i 2 | #include 3 | #include 4 | 5 | void main() 6 | { 7 | int i,j,n,temp; 8 | int *arr = (int *)malloc(n*sizeof(int)); 9 | clrscr(); 10 | printf("\nEnter size of the array:"); 11 | scanf("%d",&n); 12 | 13 | printf("\nEnter elements of the array:"); 14 | for(i=0;i arr[j+1]) 28 | { 29 | temp = arr[j]; 30 | arr[j] = arr[j+1]; 31 | arr[j+1]= temp; 32 | } 33 | } 34 | } 35 | printf("\nSorted array:"); 36 | for(i=0;i 3 | using namespace std; 4 | 5 | int max(int a, int b); 6 | 7 | /* Returns length of LCS for X[0..m-1], Y[0..n-1] */ 8 | int lcs( char *X, char *Y, int m, int n ) 9 | { 10 | if (m == 0 || n == 0) 11 | return 0; 12 | if (X[m-1] == Y[n-1]) 13 | return 1 + lcs(X, Y, m-1, n-1); 14 | else 15 | return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n)); 16 | } 17 | 18 | /* Utility function to get max of 2 integers */ 19 | int max(int a, int b) 20 | { 21 | return (a > b)? a : b; 22 | } 23 | 24 | /* Driver code */ 25 | int main() 26 | { 27 | char X[] = "AGGTAB"; 28 | char Y[] = "GXTXAYB"; 29 | 30 | int m = strlen(X); 31 | int n = strlen(Y); 32 | 33 | cout<<"Length of LCS is "<< lcs( X, Y, m, n ) ; 34 | 35 | return 0; 36 | } 37 | 38 | // This code is contributed by rathbhupendra 39 | -------------------------------------------------------------------------------- /Searching and Sorting/Bubble Sort/Kotlin/BubbleSort.kt: -------------------------------------------------------------------------------- 1 | import java.util.* 2 | fun bubbleSort(arr:IntArray){ 3 | for(i in 0 until arr.size-1){ 4 | for(j in 0 until arr.size-i-1){ 5 | if(arr[j]>arr[j+1]){ 6 | var temp = arr[j] 7 | arr[j] = arr[j+1] 8 | arr[j+1] = temp 9 | } 10 | } 11 | } 12 | } 13 | fun main(args:Array) { 14 | var scanner = Scanner(System.`in`) 15 | print("enter the size to be sorted ") 16 | var sizeOfList = scanner.nextInt() 17 | val array = IntArray(sizeOfList) 18 | print("start entering values to be sorted ") 19 | for (i in 0 until sizeOfList) { 20 | array[i] = scanner.nextInt(); 21 | } 22 | bubbleSort(array) 23 | for (i in 0 until sizeOfList){ 24 | print(array[i]) 25 | print(" ") 26 | } 27 | } -------------------------------------------------------------------------------- /shuffle_deck_of_cards.py: -------------------------------------------------------------------------------- 1 | # Shuffle a deck of cards 2 | from random import randint 3 | 4 | suits = ['Clubs', 'Diamonds', 'Hearts', 'Spades'] 5 | values = ['Ace', 'King', 'Queen', 'Jack', 'Ten', 'Nine', 'Eight', 'Seven', \ 6 | 'Six', 'Five', 'Four', 'Three', 'Two'] 7 | 8 | def main(): 9 | 10 | # Create deck 11 | deck = [] 12 | for suit in suits: 13 | for value in values: 14 | deck.append("{} of {}".format(value, suit)) 15 | 16 | # shuffle 17 | deckSize = len(deck) 18 | maxCardIdx = deckSize - 1 19 | for cardIdx in range(deckSize): 20 | randIdx = randint(0, maxCardIdx) 21 | deck[cardIdx], deck[randIdx] = deck[randIdx], deck[cardIdx] 22 | 23 | for idx, card in enumerate(deck, 1): 24 | print("{}. {}".format(idx, card)) 25 | 26 | 27 | if __name__ == "__main__": 28 | main() 29 | -------------------------------------------------------------------------------- /Dynamic Programming/Climbing_Stairs/Python/climbing_stairs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | There are n stairs, a person standing at the bottom wants to reach the top. 6 | The person can climb either 1 stair or 2 stairs at a time. 7 | Count the number of ways, the person can reach the top. 8 | 9 | This can be solved with recusive equation 10 | ways(n) = ways(n-1)+ways(n-2) 11 | and base cases 12 | ways(0)=1 13 | ways(n)=0 if n<0 14 | this clearly resembles fibonacci series and can easily be solved in bottom up manner with ways(0)=1, ways(1)=1 15 | """ 16 | 17 | n = int(input('Enter the number of stairs:')) 18 | a = 1 # ways(0) 19 | b = 1 # ways(1) 20 | c = 1 # initial value 21 | for _ in range(n - 1): 22 | c = a + b 23 | a = b 24 | b = c 25 | print('There are {} ways to climb {} stairs'.format(c, n)) 26 | 27 | -------------------------------------------------------------------------------- /Java/Graph/Node.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | /** 5 | * Graph node data structure 6 | * @author rafbel 7 | * @since 2019-10-15 8 | * 9 | */ 10 | public class Node { 11 | 12 | private Character data; 13 | private List adjacencyList; 14 | private Boolean visited; 15 | 16 | public Node(Character data) { 17 | adjacencyList = new ArrayList(); 18 | this.data = data; 19 | this.visited = false; 20 | } 21 | 22 | public void addEdge(Node node) { 23 | adjacencyList.add(node); 24 | } 25 | 26 | public List getAdjacencyList() { 27 | return adjacencyList; 28 | } 29 | 30 | public Character getData() { 31 | return this.data; 32 | } 33 | 34 | public Boolean getVisited() { 35 | return visited; 36 | } 37 | 38 | public void setVisited(Boolean visited) { 39 | this.visited = visited; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Searching and Sorting/Insertion Sort/Kotlin/InsertionSort.kt: -------------------------------------------------------------------------------- 1 | import java.util.* 2 | fun insertionSort(arr:IntArray){ 3 | var i,key,j 4 | for(i in 0 until arr.size-1){ 5 | key = arr[i] 6 | j = i-i 7 | while(j>=0 && arr[j]>key){ 8 | arr[j+1] = arr[j] 9 | j = j-1 10 | } 11 | arr[j+1] = key 12 | } 13 | } 14 | fun main(args:Array) { 15 | var scanner = Scanner(System.`in`) 16 | print("enter the size to be sorted ") 17 | var sizeOfList = scanner.nextInt() 18 | val array = IntArray(sizeOfList) 19 | print("start entering values to be sorted ") 20 | for (i in 0 until sizeOfList) { 21 | array[i] = scanner.nextInt(); 22 | } 23 | insertionSort(array) 24 | for (i in 0 until sizeOfList){ 25 | print(array[i]) 26 | print(" ") 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Stack Algorithms/Balanced Parenthesis Problem/Python/balanced_parenthesis.py: -------------------------------------------------------------------------------- 1 | def balanced(string): 2 | opening_parens = [ '(', '[', '{' ] 3 | closing_parens = [ ')', ']', '}' ] 4 | parens_dict = dict(zip(opening_parens, closing_parens)) 5 | 6 | stack = [] 7 | for char in string: 8 | if char in opening_parens: 9 | stack.append(char) 10 | elif char in closing_parens: 11 | if not stack or char != parens_dict[stack.pop()]: 12 | return False 13 | return not stack 14 | 15 | if __name__ == '__main__': 16 | balanced_expression = '{[()()[]{}((()))]}' 17 | print balanced(balanced_expression) 18 | imbalanced_expression = '{[()()[]{}((()))]}}' 19 | print balanced(imbalanced_expression) 20 | invalid_expression = '{[()()[]{}((()))]}}{' 21 | print balanced(invalid_expression) 22 | -------------------------------------------------------------------------------- /LongestCommonSubsequence/C++/lcs.cpp: -------------------------------------------------------------------------------- 1 | /* A Naive recursive implementation of LCS problem */ 2 | #include 3 | 4 | int max(int a, int b); 5 | 6 | /* Returns length of LCS for X[0..m-1], Y[0..n-1] */ 7 | int lcs(char* X, char* Y, int m, int n) 8 | { 9 | if (m == 0 || n == 0) 10 | return 0; 11 | if (X[m - 1] == Y[n - 1]) 12 | return 1 + lcs(X, Y, m - 1, n - 1); 13 | else 14 | return max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n)); 15 | } 16 | 17 | /* Utility function to get max of 2 integers */ 18 | int max(int a, int b) 19 | { 20 | return (a > b) ? a : b; 21 | } 22 | 23 | /* Driver program to test above function */ 24 | int main() 25 | { 26 | char X[] = "AGGTAB"; 27 | char Y[] = "GXTXAYB"; 28 | 29 | int m = strlen(X); 30 | int n = strlen(Y); 31 | 32 | printf("Length of LCS is %d\n", lcs(X, Y, m, n)); 33 | 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /Stack Algorithms/Balanced Parenthesis Problem/C++/balanced_parenthesis.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | bool balanced(string str){ 5 | stack s; 6 | for(int i=0; i>str; 23 | (balanced(str))?cout<<"Balanced":cout<<"Not Balanced"; 24 | cout<<"\nDo you want to try again?(y/n) "; 25 | cin>>choice; 26 | }while(choice != 'n'); 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /C++/euler_totient_func.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int phi[1000006], prime[1000006]; 5 | void sievephi(int n) 6 | { 7 | int i,j; 8 | 9 | for(i=1; i<=n; i++) phi[i]=i; 10 | 11 | phi[1]=1; 12 | prime[1]=1; 13 | 14 | for(i=2; i<=n; i++) 15 | { 16 | if(!prime[i]) 17 | { 18 | for(j=i;j<=n; j+=i) 19 | { 20 | prime[j+i]=1; 21 | phi[j]=(phi[j]/i)*(i-1); 22 | 23 | } 24 | } 25 | } 26 | } 27 | 28 | 29 | int main() 30 | { 31 | int i,n=10; 32 | sievephi(n); 33 | 34 | for(i=1; i<=n; i++) 35 | if(!prime[i]) 36 | printf("%d ", i); 37 | printf("\n"); 38 | 39 | for(i=1; i<=n; i++) 40 | printf("%d = %d\n", i, phi[i]); 41 | 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /C++/power.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | double power(double x, int y) 6 | { 7 | double n,m; 8 | if(y==0) { // base 9 | return 1; 10 | } 11 | if(y < 0){ // negative 12 | n = (1 / x) * power(x, (y + 1)/2); 13 | return n*n; 14 | } 15 | if(y % 2 == 0) { 16 | m = power(x, y/2); 17 | return m*m; 18 | } else { 19 | return x * power(x, y - 1); 20 | } 21 | } 22 | 23 | int main() 24 | { 25 | cout << "To calculate x^y ..." << endl; 26 | 27 | double x; 28 | int y; 29 | cout << "Please enter x: "; 30 | cin >> x; 31 | cout << "Please enter y: "; 32 | cin >> y; 33 | 34 | if(x == 0) { 35 | if (y > 0) 36 | cout << 0 << endl; 37 | else 38 | cout << "x^y is not defined" < 2 | using namespace std; 3 | 4 | int partition(int *a,int s,int e) 5 | { 6 | int i=s-1; 7 | int j=s; 8 | int pivot=a[e]; 9 | for( ;j=e) 24 | { 25 | return; 26 | } 27 | int p=partition(a,s,e); 28 | quickSort(a,s,p-1); 29 | quickSort(a,p+1,e); 30 | } 31 | int main() 32 | { 33 | int a[]={2,1,5,6,7,5,8}; 34 | int n=sizeof(a)/sizeof(int); 35 | quickSort(a,0,n-1); 36 | for(int i=0;i (topProd * (n + k), bottomProd * k) 10 | } 11 | top / bottom 12 | } 13 | } 14 | 15 | // to test 16 | // var c = catalan(3) 17 | // println(c) 18 | def recursive(n: Int): Int = { 19 | if (n <= 1) 1 20 | else (0 until n).map(i => recursive(i) * recursive(n - i - 1)).sum 21 | } 22 | } 23 | 24 | object Main { 25 | def main(args: Array[String]): Unit = { 26 | for (n <- 0 until 20) { 27 | println(s"${n}: ${Catalan.number(n)}") 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Python/prims_mst.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | from collections import defaultdict 3 | 4 | g = defaultdict(list) # graph 5 | n, m = map(int, raw_input().split(' ')) # number of vertexes and edges 6 | weight = 0 # weight of MST 7 | connected = set([]) # set containing connected vertexes 8 | pq = [] # heap 9 | 10 | for _ in range(m): 11 | u, v, c = map(int, raw_input().split(' ')) 12 | g[u].append((c, v)) 13 | g[v].append((c, u)) 14 | 15 | start = int(raw_input()) 16 | connected.add(start) 17 | 18 | for tup in g[start]: 19 | heapq.heappush(pq, tup) 20 | 21 | while pq: 22 | w, b = heapq.heappop(pq) 23 | if b not in connected: 24 | weight += w 25 | connected.add(b) 26 | 27 | for tup in g[b]: 28 | heapq.heappush(pq, tup) 29 | 30 | print weight -------------------------------------------------------------------------------- /Sorting Algorithm/Insertion Sort/Java/InsertionSort.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Sorts a list of generic Comparables using Insertion Sort 4 | * 5 | */ 6 | public class InsertionSort { 7 | 8 | /** 9 | * Sorts a list of elements that extend comparable using insertion sort 10 | * algorithm 11 | * @param list A list of Comparables to be sorted 12 | */ 13 | public static > void insertionSort (T[] list) 14 | { 15 | int size = list.length; 16 | int outCounter, inCounter; 17 | T temp; 18 | // Sort list[] into increasing order. 19 | for (outCounter = 1; outCounter < size; outCounter++) 20 | { 21 | temp = list[outCounter]; 22 | for (inCounter = outCounter; inCounter > 0 && list[inCounter - 1].compareTo(temp) > 0; inCounter--) 23 | { 24 | list[inCounter] = list[inCounter - 1]; 25 | } 26 | list[inCounter] = temp; 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /C++/PrimeSeive.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void primeSieve(int *p,int n){ 4 | int i; 5 | for(i=2;i<=5000000; i++) 6 | { 7 | p[i]=1; 8 | } 9 | 10 | for(i=2;i<=5000000;i++) 11 | { 12 | if(p[i]==1) 13 | { 14 | 15 | for(int j=i*i;j<=5000000;j+=i) 16 | { 17 | p[j]=0; 18 | } 19 | } 20 | } 21 | p[1]=0; 22 | p[0]=0; 23 | return ; 24 | } 25 | int main() { 26 | int arr[5000001] = {0}; 27 | int n; 28 | cin>>n; 29 | int counter = 0; 30 | primeSieve(arr,n); 31 | for(int i=0;i<=5000000;i++) 32 | { 33 | if(arr[i]==1) 34 | { 35 | counter++; 36 | } 37 | if(counter==n){ 38 | cout << i; 39 | break; 40 | } 41 | } 42 | 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /Kotlin/Bubble_Sort_In_Kotlin.kt: -------------------------------------------------------------------------------- 1 | //Bubble Sort 2 | //Driver function 3 | fun main (args : Array) { 4 | print("Enter the size of the array : ") 5 | var n = readLine()!!.toInt() 6 | var arr = Array(n, {0}) 7 | println("Enter the elements of the array") 8 | for (i in 0 until n) { 9 | arr[i] = readLine()!!.toInt() 10 | } 11 | bubbleSort(arr) 12 | } 13 | 14 | //function for bubble sort 15 | 16 | fun bubbleSort(arr : Array) { 17 | var n = arr.size 18 | var temp : Int 19 | for(i in 0 until n-1) { 20 | for(j in 0 until n-1) { 21 | if (arr[j] > arr[j+1]) { 22 | temp = arr[j] 23 | arr[j] = arr[j+1] 24 | arr[j+1] = temp 25 | } 26 | } 27 | } 28 | for (i in arr) { 29 | print("$i ") 30 | } 31 | } 32 | 33 | //This code is contributed by jatinsachdevame 34 | -------------------------------------------------------------------------------- /Sorting Algorithm/radix sort.py: -------------------------------------------------------------------------------- 1 | def countingSort(array, place): 2 | size = len(array) 3 | output = [0] * size 4 | count = [0] * 10 5 | for i in range(0, size): 6 | index = array[i] // place 7 | count[index % 10] += 1 8 | for i in range(1, 10): 9 | count[i] += count[i - 1] 10 | i = size - 1 11 | while i >= 0: 12 | index = array[i] // place 13 | output[count[index % 10] - 1] = array[i] 14 | count[index % 10] -= 1 15 | i -= 1 16 | for i in range(0, size): 17 | array[i] = output[i] 18 | def radixSort(array): 19 | max_element = max(array) 20 | place = 1 21 | while max_element // place > 0: 22 | countingSort(array, place) 23 | place *= 10 24 | 25 | alist = input('Enter the list of (nonnegative) numbers: ').split() 26 | data = [int(x) for x in alist] 27 | radixSort(data) 28 | print(data) 29 | -------------------------------------------------------------------------------- /Balanced-Unbalanced-exp.py: -------------------------------------------------------------------------------- 1 | def isBalanced(expr): 2 | stack = [] 3 | for char in expr: 4 | if char in ["(", "{", "["]: 5 | stack.append(char) 6 | else: 7 | if not stack: 8 | return False 9 | current_char = stack.pop() 10 | if current_char == '(': 11 | if char != ")": 12 | return False 13 | if current_char == '{': 14 | if char != "}": 15 | return False 16 | if current_char == '[': 17 | if char != "]": 18 | return False 19 | if stack: 20 | return False 21 | return True 22 | 23 | 24 | expr = input("Enter the Expression i.e. {},[],()- Combination of these\n") 25 | if isBalanced(expr): 26 | print("Balanced") 27 | else: 28 | print("Not Balanced") 29 | -------------------------------------------------------------------------------- /C++/FindDuplicate.cpp: -------------------------------------------------------------------------------- 1 | 2 | //Given numbers from 1 to n, find the duplicate number in 0(n) time complexity and O(1) space complexity 3 | 4 | 5 | class Solution { 6 | public: 7 | int findDuplicate(vector& nums) { 8 | //Define an empty set 9 | set con; 10 | set::iterator it; 11 | 12 | //Iterate over the array 13 | for(int i=0;i nums = {1, 2, 3, 7, 5, 6, 7} 28 | 29 | int ret = Solution().findDuplicate(nums); 30 | cout << ret << endl; 31 | 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /Dynamic Programming/Rod_cutting_problem/rod_cutting_problem.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Oct 23 21:49:30 2019 4 | 5 | @author: Lenovo 6 | """ 7 | 8 | INT_MIN = -999999 9 | 10 | # Returns the best obtainable price for a rod of length n and 11 | # price[] as prices of different pieces 12 | def cutRod(price, n): 13 | val = [0 for x in range(n+1)] 14 | val[0] = 0 15 | 16 | # Build the table val[] in bottom up manner and return 17 | # the last entry from the table 18 | for i in range(1, n+1): 19 | max_val = INT_MIN 20 | for j in range(i): 21 | max_val = max(max_val, price[j] + val[i-j-1]) 22 | val[i] = max_val 23 | 24 | return val[n] 25 | 26 | # Driver program to test above functions 27 | arr = [1, 5, 8, 9, 10, 17, 17, 20] 28 | size = len(arr) 29 | print("Maximum Obtainable Value is " + str(cutRod(arr, size))) -------------------------------------------------------------------------------- /Hash_alg/Array_is_subset_of_another_array_or_not: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int n; 7 | cin>>n; 8 | vectorarr(n); 9 | unordered_maphash; 10 | for(int i = 0 ; i < n ; i++) 11 | { 12 | cin>>arr[i]; //input first array 13 | hash[arr[i]]++; //putting elements inside hash 14 | } 15 | int m; 16 | cin>>m; 17 | vectorbrr(m); 18 | 19 | for(int i = 0; i < m ; i++) 20 | cin>>brr[i]; //input second array 21 | 22 | for(int i = 0 ; i < m; i++) 23 | { 24 | if(hash.find(brr[i])==hash.end()) //checking that element of second array is present in hash or not 25 | { 26 | cout<<"No"; 27 | return 0; 28 | } 29 | } 30 | 31 | cout<<"Yes"; 32 | 33 | 34 | } 35 | -------------------------------------------------------------------------------- /Python/EulerTotientFunction.py: -------------------------------------------------------------------------------- 1 | def prime_factors(n): 2 | i = 2 3 | factors = [1] 4 | while i * i <= n: 5 | if n % i: 6 | i += 1 7 | else: 8 | n //= i 9 | factors.append(i) 10 | if n > 1: 11 | factors.append(n) 12 | return factors 13 | 14 | 15 | def is_prime(list): 16 | if len(list) == 2: 17 | return True 18 | else: 19 | return False 20 | 21 | 22 | def prime_powers(): 23 | list = [1, 2, 2, 3, 3] 24 | output_list = [] 25 | for i in range(1, len(list) - 1): 26 | if list[i] == list[i + 1]: 27 | output_list.append(list[i] * list[i + 1]) 28 | print(output_list) 29 | 30 | def 31 | n = int(input("Input Number?")) 32 | factors_n = prime_factors(n) 33 | print(factors_n) 34 | 35 | if is_prime(factors_n): 36 | phi_n = n-1 37 | 38 | 39 | print(phi_n) 40 | 41 | #made some cool changes -------------------------------------------------------------------------------- /Brute Force: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | static const char alphabet[] = 6 | "abcdefghijklmnopqrstuvwxyz" 7 | "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 8 | "0123456789"; 9 | 10 | static const int alphabetSize = sizeof(alphabet) - 1; 11 | 12 | void bruteImpl(char* str, int index, int maxDepth) 13 | { 14 | for (int i = 0; i < alphabetSize; ++i) 15 | { 16 | str[index] = alphabet[i]; 17 | 18 | if (index == maxDepth - 1) printf("%s\n", str); 19 | else bruteImpl(str, index + 1, maxDepth); 20 | } 21 | } 22 | 23 | void bruteSequential(int maxLen) 24 | { 25 | char* buf = malloc(maxLen + 1); 26 | 27 | for (int i = 1; i <= maxLen; ++i) 28 | { 29 | memset(buf, 0, maxLen + 1); 30 | bruteImpl(buf, 0, i); 31 | } 32 | 33 | free(buf); 34 | } 35 | 36 | int main(void) 37 | { 38 | bruteSequential(3); 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /Fibonacci Sequence/fast-fibonacci.py: -------------------------------------------------------------------------------- 1 | def fib(n): 2 | F = [[1, 1], 3 | [1, 0]] 4 | if (n == 0): 5 | return 0 6 | power(F, n - 1) 7 | 8 | return F[0][0] 9 | 10 | def multiply(F, M): 11 | 12 | x = (F[0][0] * M[0][0] + 13 | F[0][1] * M[1][0]) 14 | y = (F[0][0] * M[0][1] + 15 | F[0][1] * M[1][1]) 16 | z = (F[1][0] * M[0][0] + 17 | F[1][1] * M[1][0]) 18 | w = (F[1][0] * M[0][1] + 19 | F[1][1] * M[1][1]) 20 | 21 | F[0][0] = x 22 | F[0][1] = y 23 | F[1][0] = z 24 | F[1][1] = w 25 | 26 | def power(F, n): 27 | 28 | if( n == 0 or n == 1): 29 | return; 30 | M = [[1, 1], 31 | [1, 0]]; 32 | 33 | power(F, n // 2) 34 | multiply(F, F) 35 | 36 | if (n % 2 != 0): 37 | multiply(F, M) 38 | 39 | 40 | n = 11 41 | print(fib(n)) -------------------------------------------------------------------------------- /Searching and Sorting/Cocktail Sort/Python/cocktailSort.py: -------------------------------------------------------------------------------- 1 | def cocktailSort(unsorted): 2 | swapped = True 3 | start = 0 4 | end = len(unsorted) -1 5 | while swapped: 6 | swapped = False 7 | # forward pass 8 | for i in range(start, end): 9 | if unsorted[i] > unsorted[i+1]: 10 | swapped = True 11 | unsorted[i], unsorted[i+1] = unsorted[i+1], unsorted[i] 12 | 13 | end -= 1 14 | 15 | # backward pass 16 | for i in range(end-1, start-1, -1): 17 | if unsorted[i] > unsorted[i+1]: 18 | swapped = True 19 | unsorted[i], unsorted[i+1] = unsorted[i+1], unsorted[i] 20 | 21 | start += 1 22 | print(unsorted) 23 | 24 | 25 | def test(): 26 | arr = [3,4,8,76,45,3,1,0,5,-34, 23] 27 | cocktailSort(arr) 28 | 29 | 30 | if __name__ == "__main__": 31 | test() -------------------------------------------------------------------------------- /nut_bolt.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | void nutboltmatch(char nuts[], char bolts[], int n) 6 | { 7 | unordered_map hash; 8 | 9 | 10 | for (int i = 0; i < n; i++) 11 | hash[nuts[i]] = i; 12 | 13 | 14 | for (int i = 0; i < n; i++) 15 | if (hash.find(bolts[i]) != hash.end()) 16 | nuts[i] = bolts[i]; 17 | 18 | cout << "matched nuts and bolts are-" << endl; 19 | for (int i = 0; i < n; i++) 20 | cout << nuts[i] << " "; 21 | cout << endl; 22 | for (int i = 0; i < n; i++) 23 | cout << bolts[i] << " "; 24 | } 25 | 26 | 27 | int main() 28 | { 29 | char nuts[] = {'@', '#', '$', '%', '^', '&'}; 30 | char bolts[] = {'$', '%', '&', '^', '@', '#'}; 31 | int n = sizeof(nuts) / sizeof(nuts[0]); 32 | nutboltmatch(nuts, bolts, n); 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /sieve.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void SieveOfEratosthenes(int n) 5 | { 6 | // Create a boolean array and initialize the values as true 7 | bool prime[n+1]; 8 | memset(prime, true, sizeof(prime)); 9 | 10 | for (int p=2; p*p<=n; p++) 11 | { 12 | // If prime[p] is not changed, then it is a prime 13 | if (prime[p] == true) 14 | { 15 | //Update multiples 16 | for (int i=p*p; i<=n; i += p) 17 | prime[i] = false; 18 | } 19 | } 20 | 21 | // Print all prime numbers 22 | for (int p=2; p<=n; p++) 23 | if (prime[p]) 24 | cout << p << " "; 25 | } 26 | 27 | // Driver Program 28 | int main() 29 | { 30 | int n = 30; 31 | cout << " Prime Numbers in the range 1 to " << n << endl; 32 | SieveOfEratosthenes(n); 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /ModernCiphers/ceaser cipher/ceaser.py: -------------------------------------------------------------------------------- 1 | S=input('') 2 | N=int(input('')) 3 | enc='' 4 | for i in S: 5 | if(i.isalnum()): 6 | if(ord(i)>=65 and ord(i)<=90): 7 | z=(ord(i)+N) 8 | if(z>90): 9 | while(z>90): 10 | z-=26 11 | enc+=chr(z) 12 | else: 13 | enc+=chr(z) 14 | elif(ord(i)>=97 and ord(i)<=122): 15 | z=(ord(i)+N) 16 | if(z>122): 17 | while(z>122): 18 | z-=26 19 | enc+=chr(z) 20 | else: 21 | enc+=chr(z) 22 | elif(ord(i)>=48 and ord(i)<=57): 23 | z=(ord(i)+N) 24 | if(z>57): 25 | while(z>57): 26 | z-=10 27 | enc+=chr(z) 28 | else: 29 | enc+=chr(z) 30 | else: 31 | enc+=i 32 | print(enc) -------------------------------------------------------------------------------- /Trapping Rain Water: -------------------------------------------------------------------------------- 1 | ///Trapping rain water 2 | #include 3 | using namespace std; 4 | int findWater(int arr[], int n) 5 | { 6 | //Approaching from left side 7 | int left[n]; 8 | 9 | //Approaching from right side 10 | int right[n]; 11 | 12 | // Initialize result 13 | int water = 0; 14 | 15 | 16 | left[0] = arr[0]; 17 | for (int i = 1; i < n; i++) 18 | left[i] = max(left[i-1], arr[i]); 19 | 20 | 21 | right[n-1] = arr[n-1]; 22 | for (int i = n-2; i >= 0; i--) 23 | right[i] = max(right[i+1], arr[i]); 24 | 25 | // Calculate the accumulated water element by element 26 | for (int i = 0; i < n; i++) 27 | water += min(left[i],right[i]) - arr[i]; 28 | 29 | return water; 30 | } 31 | 32 | int main() 33 | { 34 | int arr[] = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}; 35 | int n = sizeof(arr)/sizeof(arr[0]); 36 | cout << "Maximum water that can be accumulated is " 37 | << findWater(arr, n); 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /Dynamic Programming/matrixchainmultiplication.py: -------------------------------------------------------------------------------- 1 | # Dynamic Programming Python implementation of Matrix Chain Multiplication 2 | import sys 3 | 4 | # Matrix Ai has dimension p[i-1] x p[i] for i = 1..n 5 | def MatrixChainOrder(p, n): 6 | 7 | m = [[0 for x in range(n)] for x in range(n)] 8 | 9 | # cost is zero when multiplying one matrix. 10 | for i in range(1, n): 11 | m[i][i] = 0 12 | 13 | # L is chain length. 14 | for L in range(2, n): 15 | for i in range(1, n-L+1): 16 | j = i+L-1 17 | m[i][j] = sys.maxint 18 | for k in range(i, j): 19 | 20 | # q = cost/scalar multiplications 21 | q = m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j] 22 | if q < m[i][j]: 23 | m[i][j] = q 24 | 25 | return m[1][n-1] 26 | 27 | # Driver program to test above function 28 | arr = [1, 2, 3 ,4] 29 | size = len(arr) 30 | 31 | print("Minimum number of multiplications is " + 32 | str(MatrixChainOrder(arr, size))) 33 | -------------------------------------------------------------------------------- /Python/sieveOfEratosthenes.py: -------------------------------------------------------------------------------- 1 | # Python program to print all primes smaller than or equal to 2 | # n using Sieve of Eratosthenes 3 | 4 | def SieveOfEratosthenes(n): 5 | 6 | # Create a boolean array "prime[0..n]" and initialize 7 | # all entries it as true. A value in prime[i] will 8 | # finally be false if i is Not a prime, else true. 9 | prime = [True for i in range(n+1)] 10 | p = 2 11 | while (p * p <= n): 12 | 13 | # If prime[p] is not changed, then it is a prime 14 | if (prime[p] == True): 15 | 16 | # Update all multiples of p 17 | for i in range(p * p, n+1, p): 18 | prime[i] = False 19 | p += 1 20 | 21 | # Print all prime numbers 22 | for p in range(2, n): 23 | if prime[p]: 24 | print p, 25 | 26 | # driver program 27 | if __name__=='__main__': 28 | n = 30 29 | print "Following are the prime numbers smaller", 30 | print "than or equal to", n 31 | SieveOfEratosthenes(n) 32 | -------------------------------------------------------------------------------- /Kotlin/Insertion_Sort_In_Kotlin.kt: -------------------------------------------------------------------------------- 1 | //Driver function 2 | fun main (args : Array) { 3 | print("Enter the size of thev array : ") 4 | var n = readLine()!!.toInt() 5 | var arr = Array(n, {0}) 6 | println("Enter the elements of the array") 7 | for (i in 0 until n) { 8 | arr[i] = readLine()!!.toInt() 9 | } 10 | insertionSort(arr) 11 | } 12 | 13 | //function for insertion sort 14 | 15 | fun insertionSort(arr : Array) { 16 | var n = arr.size 17 | var key : Int 18 | var j : Int 19 | for(i in 1 until n) { 20 | key = arr[i] 21 | j = i-1 22 | while (j>=0 && arr[j] > key) { 23 | if (key 2 | using namespace std; 3 | int stairCaseSearch(int a[][100],int R, int C, int key) 4 | { 5 | int i=0,j=C-1; 6 | while(i=0) 7 | { 8 | if(a[i][j]==key) 9 | { 10 | //cout<<"Found at position "<key) 15 | { 16 | j--; 17 | 18 | } 19 | else 20 | { 21 | i++; 22 | } 23 | 24 | } 25 | //<<"Element not found"; 26 | return 0; 27 | 28 | } 29 | int main() 30 | { 31 | int arr[100][100],R,C,NUM,ch; 32 | cin>>R>>C; 33 | 34 | 35 | 36 | for(int i=0; i>arr[i][j]; 41 | 42 | } 43 | } 44 | cin>>NUM; 45 | ch=stairCaseSearch(arr,R,C,NUM); 46 | cout< 3 | using namespace std; 4 | 5 | int max(int a, int b); 6 | 7 | /* Returns length of LCS for X[0..m-1], Y[0..n-1] */ 8 | int lcs( char *X, char *Y, int m, int n ) 9 | { 10 | if (m == 0 || n == 0) 11 | return 0; 12 | if (X[m-1] == Y[n-1]) 13 | return 1 + lcs(X, Y, m-1, n-1); 14 | else 15 | return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n)); 16 | } 17 | 18 | /* Utility function to get max of 2 integers */ 19 | int max(int a, int b) 20 | { 21 | return (a > b)? a : b; 22 | } 23 | 24 | /* Driver code */ 25 | int main() 26 | { 27 | char X[] = "AGGTAB"; 28 | char Y[] = "GXTXAYB"; 29 | 30 | int m = strlen(X); 31 | int n = strlen(Y); 32 | 33 | cout<<"Length of LCS is "<< lcs( X, Y, m, n ) ; 34 | 35 | return 0; 36 | } 37 | 38 | // This code is contributed by rathbhupendra 39 | -------------------------------------------------------------------------------- /Python/Stack.py: -------------------------------------------------------------------------------- 1 | class Stack: 2 | """Stack implementation in Python. 3 | Usage: 4 | s = Stack() 5 | print(s.is_empty()) 6 | s.push(4) 7 | s.push('dog') 8 | print(s.peek()) 9 | s.push(True) 10 | print(len(s)) 11 | print(s.is_empty()) 12 | s.push(8.4) 13 | print(s.pop()) 14 | print(s.pop()) 15 | print(len(s)) 16 | """ 17 | def __init__(self, items=None): 18 | self.items = [] if not items else items 19 | 20 | def is_empty(self): 21 | return bool(self.items) 22 | 23 | def push(self, item): 24 | self.items.append(item) 25 | 26 | def pop(self): 27 | if len(self.items) == 0: 28 | return None 29 | return self.items.pop() 30 | 31 | def peek(self): 32 | return self.items[len(self.items) - 1] 33 | 34 | def __len__(self): 35 | return len(self.items) 36 | 37 | -------------------------------------------------------------------------------- /Sorting Algorithm/Selection Sort/C/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void selectionSort(int arr[], int size) 5 | { 6 | int count, minIndex, minValue, i; 7 | for(count=0; count Monotone chain algorithm 2 | 3 | Given a set of points, the task is to find the covex hull of the given points. The convex hull is the smallest convex polygon that contains all the points. 4 | 5 | 6 | Examples: 7 | 8 | Input: Points[] = {{0, 3}, {2, 2}, {1, 1}, {2, 1}, {3, 0}, {0, 0}, {3, 3}} 9 | Output: 10 | (0, 0) 11 | (3, 0) 12 | (3, 3) 13 | (0, 3) 14 | 15 | 16 | 17 | Approach--> Monotone chain algorithm constructs the convex hull in O(n * log(n)) time. We have to sort the points first and then calculate the upper and lower hulls in O(n) time. The points will be sorted with respect to x-coordinates (with respect to y-coordinates in case of a tie in x-coordinates), we will then find the left most point and then try to rotate in clockwise direction and find the next point and then repeat the step until we reach the rightmost point and then again rotate in the the clockwise direction and find the lower hull. 18 | 19 | 20 | -------------------------------------------------------------------------------- /Python/z_score_for_detect_outliers.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import numpy as np 3 | 4 | def find_anomalies_z_score(list_data): 5 | outliers = [] 6 | 7 | std_data = np.std(list_data); print('std:', std_data) 8 | mean_data = np.mean(list_data); print('mean:', mean_data) 9 | anomaly_cut_off = std_data * 3; print('anomaly_cut_off:', anomaly_cut_off) 10 | 11 | lower_limit = mean_data - anomaly_cut_off; print('lower_limit', lower_limit) 12 | upper_limit = mean_data + anomaly_cut_off; print('upper_limit', upper_limit) 13 | 14 | for outlier in list_data: 15 | if outlier > upper_limit or outlier < lower_limit: 16 | outliers.append(outlier) 17 | 18 | if len(outliers) == 0: 19 | print('outlier is not found') 20 | 21 | return outliers 22 | 23 | if __name__ == '__main__': 24 | data = 5 * np.random.randn(1000) + 50 25 | result = find_anomalies_z_score(data) 26 | print('outliers : ', result) 27 | -------------------------------------------------------------------------------- /Dynamic Programming/LIS/Optimized_longest_Increasing_Subsequence.cpp: -------------------------------------------------------------------------------- 1 | /* Dynamic Programming C++ implementation of LIS problem */ 2 | #include 3 | using namespace std; 4 | 5 | /* lis() returns the length of the longest increasing 6 | subsequence in arr[] of size n */ 7 | int lis( int arr[], int n ) 8 | { 9 | int lis[n]; 10 | 11 | lis[0] = 1; 12 | 13 | /* Compute optimized LIS values in bottom up manner */ 14 | for (int i = 1; i < n; i++ ) 15 | { 16 | lis[i] = 1; 17 | for (int j = 0; j < i; j++ ) 18 | if ( arr[i] > arr[j] && lis[i] < lis[j] + 1) 19 | lis[i] = lis[j] + 1; 20 | } 21 | 22 | // Return maximum value in lis[] 23 | return *max_element(lis, lis+n); 24 | } 25 | 26 | /* Driver program to test above function */ 27 | int main() 28 | { 29 | int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 }; 30 | int n = sizeof(arr)/sizeof(arr[0]); 31 | printf("Length of lis is %d\n", lis( arr, n ) ); 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /C/bubble_sort.c: -------------------------------------------------------------------------------- 1 | // C program for implementation of Bubble 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 | // A function to implement bubble sort 12 | void bubbleSort(int arr[], int n) 13 | { 14 | int i, j; 15 | for (i = 0; i < n-1; i++) 16 | 17 | // Last i elements are already in place 18 | for (j = 0; j < n-i-1; j++) 19 | if (arr[j] > arr[j+1]) 20 | swap(&arr[j], &arr[j+1]); 21 | } 22 | 23 | /* Function to print an array */ 24 | void printArray(int arr[], int size) 25 | { 26 | int i; 27 | for (i=0; i < size; i++) 28 | printf("%d ", arr[i]); 29 | printf("\n"); 30 | } 31 | 32 | // Driver program to test above functions 33 | int main() 34 | { 35 | int arr[] = {64, 34, 25, 12, 22, 11, 90}; 36 | int n = sizeof(arr)/sizeof(arr[0]); 37 | bubbleSort(arr, n); 38 | printf("Sorted array: \n"); 39 | printArray(arr, n); 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /Searching and Sorting/Heap Sort/Python/heap sort.py: -------------------------------------------------------------------------------- 1 | # Source : https://www.geeksforgeeks.org/python-program-for-heap-sort/ 2 | # Thanks to Mohit Kumra 3 | def heapify(arr, n, i): 4 | largest = i # Initialize largest as root 5 | l = 2 * i + 1 # left = 2*i + 1 6 | r = 2 * i + 2 # right = 2*i + 2 7 | if l < n and arr[i] < arr[l]: 8 | largest = l 9 | if r < n and arr[largest] < arr[r]: 10 | largest = r 11 | if largest != i: 12 | arr[i],arr[largest] = arr[largest],arr[i] # swap 13 | heapify(arr, n, largest) 14 | def heapSort(arr): 15 | n = len(arr) 16 | for i in range(n, -1, -1): 17 | heapify(arr, n, i) 18 | for i in range(n-1, 0, -1): 19 | arr[i], arr[0] = arr[0], arr[i] # swap 20 | heapify(arr, i, 0) 21 | arr = [ 12, 11, 13, 5, 6, 7] 22 | heapSort(arr) 23 | n = len(arr) 24 | print ("Sorted array is") 25 | for i in range(n): 26 | print ("%d" %arr[i]), 27 | -------------------------------------------------------------------------------- /Dynamic Programming/kadane algorithm/kadanealgo.java: -------------------------------------------------------------------------------- 1 | // Java program to print largest contiguous array sum 2 | 3 | import java.io.*; 4 | import java.util.*; 5 | 6 | class Kadane 7 | { 8 | public static void main (String[] args) 9 | { 10 | int [] a = {-2, -3, 4, -1, -2, 1, 5, -3}; 11 | System.out.println("Maximum contiguous sum is " + 12 | maxSubArraySum(a)); 13 | } 14 | 15 | static int maxSubArraySum(int a[]) 16 | { 17 | int size = a.length; 18 | int max_so_far = Integer.MIN_VALUE, max_ending_here = 0; 19 | 20 | for (int i = 0; i < size; i++) 21 | { 22 | max_ending_here = max_ending_here + a[i]; 23 | if (max_so_far < max_ending_here) 24 | max_so_far = max_ending_here; 25 | if (max_ending_here < 0) 26 | max_ending_here = 0; 27 | } 28 | return max_so_far; 29 | } 30 | } -------------------------------------------------------------------------------- /Linked List/sorted_insertion_LL.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | class Node { 4 | 5 | public: 6 | 7 | Node *next; 8 | 9 | int data; 10 | }; 11 | 12 | typedef Node * ListType; 13 | 14 | void insertionSort(ListType &list) { 15 | ListType *p = &list; 16 | 17 | while ( (*p)->next && (*p)->next->data < (*p)->data) 18 | { 19 | ListType node= *p; 20 | 21 | *p=node->next; 22 | 23 | node->next=node->next->next; 24 | 25 | (*p)->next=node; 26 | 27 | p= &(*p)->next; 28 | } 29 | } 30 | 31 | int main() 32 | { 33 | Node *head=0; 34 | 35 | int n; 36 | 37 | while (std::cout << "enter the number ", std::cin >> n) 38 | { 39 | Node *p=new Node; 40 | 41 | p->data=n; 42 | 43 | p->next=head; 44 | head=p; 45 | 46 | insertionSort(head); 47 | 48 | for (p=head; p; p=p->next) 49 | std::cout << p->data << " "; 50 | std::cout << std::endl; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /Dynamic Programming/0-1 Knapsack/Pyhton/0-1 Knapsack.py: -------------------------------------------------------------------------------- 1 | #A naive recursive implementation of 0-1 Knapsack Problem 2 | 3 | # Returns the maximum value that can be put in a knapsack of 4 | # capacity W 5 | def knapSack(W , wt , val , n): 6 | 7 | # Base Case 8 | if n == 0 or W == 0 : 9 | return 0 10 | 11 | # If weight of the nth item is more than Knapsack of capacity 12 | # W, then this item cannot be included in the optimal solution 13 | if (wt[n-1] > W): 14 | return knapSack(W , wt , val , n-1) 15 | 16 | # return the maximum of two cases: 17 | # (1) nth item included 18 | # (2) not included 19 | else: 20 | return max(val[n-1] + knapSack(W-wt[n-1] , wt , val , n-1), 21 | knapSack(W , wt , val , n-1)) 22 | 23 | # end of function knapSack 24 | 25 | # To test above function 26 | val = [60, 100, 120] 27 | wt = [10, 20, 30] 28 | W = 50 29 | n = len(val) 30 | print(knapSack(W , wt , val , n)) -------------------------------------------------------------------------------- /doubly linkedList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // creating struct Node 5 | 6 | struct Node { 7 | int data; 8 | struct Node *prev; 9 | struct Node *next; 10 | }; 11 | struct Node* head = NULL; 12 | 13 | //Inserting new node 14 | 15 | void insert(int newdata) { 16 | struct Node* newnode = (struct Node*) malloc(sizeof(struct Node)); 17 | newnode->data = newdata; 18 | newnode->prev = NULL; 19 | newnode->next = head; 20 | if(head != NULL) 21 | head->prev = newnode ; 22 | head = newnode; 23 | } 24 | //display linked list 25 | 26 | void display() { 27 | struct Node* ptr; 28 | ptr = head; 29 | while(ptr != NULL) { 30 | cout<< ptr->data <<" "; 31 | ptr = ptr->next; 32 | } 33 | } 34 | int main() { 35 | insert(3); 36 | insert(1); 37 | insert(7); 38 | insert(2); 39 | insert(9); 40 | cout<<"The doubly linked list is: "; 41 | display(); 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /C++/knapsack.cpp: -------------------------------------------------------------------------------- 1 | // A Dynamic Programming based solution for 0-1 Knapsack problem 2 | #include 3 | 4 | // A utility function that returns maximum of two integers 5 | int max(int a, int b) { return (a > b)? a : b; } 6 | 7 | // Returns the maximum value that can be put in a knapsack of capacity W 8 | int knapSack(int W, int wt[], int val[], int n) 9 | { 10 | int i, w; 11 | int K[n+1][W+1]; 12 | 13 | // Build table K[][] in bottom up manner 14 | for (i = 0; i <= n; i++) 15 | { 16 | for (w = 0; w <= W; w++) 17 | { 18 | if (i==0 || w==0) 19 | K[i][w] = 0; 20 | else if (wt[i-1] <= w) 21 | K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]); 22 | else 23 | K[i][w] = K[i-1][w]; 24 | } 25 | } 26 | 27 | return K[n][W]; 28 | } 29 | 30 | int main() 31 | { 32 | int val[] = {60, 100, 120}; 33 | int wt[] = {10, 20, 30}; 34 | int W = 50; 35 | int n = sizeof(val)/sizeof(val[0]); 36 | printf("%d", knapSack(W, wt, val, n)); 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /Python/fastfibonacci.py: -------------------------------------------------------------------------------- 1 | # the method relies on the fact that if we multiply matrix [[1,1],[1,0]] with it self n times we get nth fibonacci number at (0,0) 2 | #place 3 | # Fibonacci Series : 0,1,1,2............ 4 | 5 | # function that returns nth with 0 based indexing 6 | 7 | def fastfibonacci(n): 8 | 9 | f = [[1, 1], 10 | [1, 0]] 11 | if (n == 0): 12 | return 0 13 | power(f, n - 1) 14 | 15 | return f[0][0] 16 | 17 | def multiply(f, g): 18 | 19 | a = (f[0][0] * g[0][0] + f[0][1] * g[1][0]) 20 | s = (f[0][0] * g[0][1] + f[0][1] * g[1][1]) 21 | d = (f[1][0] * g[0][0] + f[1][1] * g[1][0]) 22 | h = (f[1][0] * g[0][1] + f[1][1] * g[1][1]) 23 | 24 | f[0][0] = a 25 | f[0][1] = s 26 | f[1][0] = d 27 | f[1][1] = h 28 | 29 | 30 | def power(f, n): 31 | 32 | if( n == 0 or n == 1): 33 | return; 34 | g = [[1, 1], 35 | [1, 0]]; 36 | 37 | power(f, n // 2) 38 | multiply(f, f) 39 | 40 | if (n % 2 != 0): 41 | multiply(f, g) 42 | 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /Shuffle a deck of cards: -------------------------------------------------------------------------------- 1 | // C++ program for shuffling desk of cards. 2 | #include 3 | using namespace std; 4 | 5 | // Function which shuffle and print the array 6 | void shuffle(int card[], int n) 7 | { 8 | // Initialize seed randomly 9 | srand(time(0)); 10 | 11 | for (int i=0; i= 65) && (code <= 90)) 27 | c = String.fromCharCode(((code - 65 + amount) % 26) + 65); 28 | 29 | // Lowercase letters 30 | else if ((code >= 97) && (code <= 122)) 31 | c = String.fromCharCode(((code - 97 + amount) % 26) + 97); 32 | 33 | } 34 | 35 | // Append 36 | output += c; 37 | 38 | } 39 | 40 | // All done! 41 | return output; 42 | } -------------------------------------------------------------------------------- /Dynamic Programming/Max Product Array/max_product_array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: pedrotorres 3 | * @Date: 2019-06-11 22:10:26 4 | * @Last Modified by: pedrotorres 5 | * @Last Modified time: 2019-10-08 11:09:01 6 | */ 7 | 8 | // complexity: O(n) 9 | // description: find maximum product in an array 10 | 11 | #include 12 | 13 | #define EPS 0.0000000001 14 | 15 | using namespace std; 16 | 17 | int main(){ 18 | float array[] = {0.2, 0.9, 0.02, 0.5, 0.1, 0.4, 0.5, 0.5, 0.5, 0.7, 0.00001, 0.8, 0.5}; 19 | int n = sizeof(array) / sizeof(array[0]); 20 | float maxsf, maxeh; 21 | int start, end, s; 22 | 23 | maxsf = 0, maxeh = 1; 24 | start = 0, end = 0; s = 0; 25 | 26 | for (int k = 0; k < n; k++){ 27 | maxeh = maxeh * array[k]; 28 | 29 | if (maxsf < maxeh){ 30 | maxsf = maxeh; 31 | start = s; 32 | end = k; 33 | } 34 | 35 | if (maxeh < 1.0){ 36 | maxeh = 1.0; 37 | s = k + 1; 38 | } 39 | } 40 | 41 | printf("%d %d %.2f\n" ,start, end, maxsf); 42 | 43 | return 0; 44 | } -------------------------------------------------------------------------------- /Divide and Conquer/closestpairofpoints.py: -------------------------------------------------------------------------------- 1 | from math import sqrt, pow 2 | 3 | def distance(a, b): 4 | return sqrt(pow(a[0] - b[0],2) + pow(a[1] - b[1],2)) 5 | 6 | def bruteMin(points, current=float("inf")): 7 | if len(points) < 2: return current 8 | else: 9 | head = points[0] 10 | del points[0] 11 | newMin = min([distance(head, x) for x in points]) 12 | newCurrent = min([newMin, current]) 13 | return bruteMin(points, newCurrent) 14 | 15 | def divideMin(points): 16 | points = sorted(points) 17 | half = len(sorted(points))/2 18 | minimum = min([bruteMin(points[:half]), bruteMin(points[half:])]) 19 | nearLine = filter(lambda x: x[0] > half - minimum and x[0] < half + minimum, points) 20 | return min([bruteMin(nearLine), minimum]) 21 | 22 | list1 = [(12,30), (40, 50), (5, 1), (12, 10), (3,4)] 23 | list2=[(1, 496.5), (12,30), (40, 50), (5, 1), (12, 10), (3,4), (1, 496), (1, 497)] 24 | print "Closest Pair Distance:",divideMin(list1) 25 | print "Closest Pair Distance:",divideMin(list2) 26 | -------------------------------------------------------------------------------- /Sorting Algorithm/Quick_Sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | void main() 4 | { 5 | clrscr(); 6 | int size, arr[50], i, j, temp, index, small, count=0; 7 | cout<<"Enter Array Size : "; 8 | cin>>size; 9 | cout<<"Enter Array Elements : "; 10 | for(i=0; i>arr[i]; 12 | cout<<"Sorting array using selection sort...\n"; 13 | for(i=0; i<(size-1); i++) 14 | { 15 | small = arr[i]; 16 | for(j=(i+1); jarr[j]) 19 | { 20 | small = arr[j]; 21 | count++; 22 | index = j; 23 | } 24 | } 25 | if(count!=0) 26 | { 27 | temp = arr[i]; 28 | arr[i] = small; 29 | arr[index] = temp; 30 | } 31 | count=0; 32 | } 33 | cout<<"Now the Array after sorting is :\n"; 34 | for(i=0; i 2 | using namespace std; 3 | int cost[10][10],i,j,k,n,qu[10],front,rare,v,visit[10],visited[10]; 4 | int main() 5 | { 6 | int m; 7 | cout <<"Enter no of nodes(max 9):"; 8 | cin >> n; 9 | cout <<"Enter no of edges:"; 10 | cin >> m; 11 | cout <<"\nEnter edges starting from source node: \n"; 12 | for(k=1; k<=m; k++) 13 | { 14 | cin >>i>>j; 15 | cost[i][j]=1; 16 | } 17 | cout <<"Re-enter source node to traverse from:"; 18 | cin >>v; 19 | cout <<"Visitied nodes:"; 20 | cout < traverse(Graph graph, int startNodeIndex) { 17 | List traversalList = new ArrayList(); 18 | recurseTraverse(graph.getNode(startNodeIndex), traversalList); 19 | return traversalList; 20 | } 21 | 22 | private static void recurseTraverse(Node currentNode, List traversalList) { 23 | traversalList.add(currentNode); 24 | currentNode.setVisited(true); 25 | 26 | List orderedAdjacentNodes = currentNode.getAdjacencyList(); 27 | orderedAdjacentNodes.sort(Comparator.comparing(Node::getData)); 28 | 29 | for (Node adjacentNode : orderedAdjacentNodes) { 30 | if (!adjacentNode.getVisited()) { 31 | recurseTraverse(adjacentNode, traversalList); 32 | } 33 | } 34 | 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /LongestCommonSubsequence/C++/LCS-DP.cpp: -------------------------------------------------------------------------------- 1 | //Longest Common subsequence 2 | //Refrence: https://www.geeksforgeeks.org/longest-common-subsequence-dp-4/ 3 | #include 4 | using namespace std; 5 | 6 | int max(int a, int b); 7 | 8 | 9 | int lcs( char *X, char *Y, int m, int n ) 10 | { 11 | int L[m + 1][n + 1]; 12 | int i, j; 13 | 14 | for (i = 0; i <= m; i++) 15 | { 16 | for (j = 0; j <= n; j++) 17 | { 18 | if (i == 0 || j == 0) 19 | L[i][j] = 0; 20 | 21 | else if (X[i - 1] == Y[j - 1]) 22 | L[i][j] = L[i - 1][j - 1] + 1; 23 | 24 | else 25 | L[i][j] = max(L[i - 1][j], L[i][j - 1]); 26 | } 27 | } 28 | return L[m][n]; 29 | } 30 | 31 | int max(int a, int b) 32 | { 33 | return (a > b)? a : b; 34 | } 35 | 36 | int main() 37 | { 38 | char X[] = "ABCAAGGTABAB"; 39 | char Y[] = "ZELGGXTXAYB"; 40 | 41 | int m = strlen(X); 42 | int n = strlen(Y); 43 | 44 | cout << "Length of LCS is: " 45 | << lcs( X, Y, m, n ); 46 | 47 | return 0; 48 | } 49 | 50 | -------------------------------------------------------------------------------- /LongestCommonSubsequence/LCS.java: -------------------------------------------------------------------------------- 1 | public class LongestCommonSubsequence { 2 | 3 | /* Returns length of LCS for X[0..m-1], Y[0..n-1] */ 4 | int lcs(char[] X, char[] Y, int m, int n) 5 | { 6 | int L[][] = new int[m + 1][n + 1]; 7 | 8 | /* Following steps build L[m+1][n+1] in bottom up fashion. Note 9 | that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ 10 | for (int i = 0; i <= m; i++) { 11 | for (int j = 0; j <= n; j++) { 12 | if (i == 0 || j == 0) 13 | L[i][j] = 0; 14 | else if (X[i - 1] == Y[j - 1]) 15 | L[i][j] = L[i - 1][j - 1] + 1; 16 | else 17 | L[i][j] = max(L[i - 1][j], L[i][j - 1]); 18 | } 19 | } 20 | return L[m][n]; 21 | } 22 | 23 | /* Utility function to get max of 2 integers */ 24 | int max(int a, int b) 25 | { 26 | return (a > b) ? a : b; 27 | } 28 | 29 | -------------------------------------------------------------------------------- /Tree/Tree Traversal/BFS/C++/BFS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int cost[10][10],i,j,k,n,qu[10],front,rare,v,visit[10],visited[10]; 4 | int main() 5 | { 6 | int m; 7 | cout <<"Enter no of nodes(max 9):"; 8 | cin >> n; 9 | cout <<"Enter no of edges:"; 10 | cin >> m; 11 | cout <<"\nEnter edges starting from source node: \n"; 12 | for(k=1; k<=m; k++) 13 | { 14 | cin >>i>>j; 15 | cost[i][j]=1; 16 | } 17 | cout <<"Re-enter source node to traverse from:"; 18 | cin >>v; 19 | cout <<"Visitied nodes:"; 20 | cout < 2 | #include 3 | void main() 4 | { 5 | clrscr(); 6 | int size, arr[50], i, j, temp, index, small, count=0; 7 | cout<<"Enter Array Size : "; 8 | cin>>size; 9 | cout<<"Enter Array Elements : "; 10 | for(i=0; i>arr[i]; 12 | cout<<"Sorting array using selection sort...\n"; 13 | for(i=0; i<(size-1); i++) 14 | { 15 | small = arr[i]; 16 | for(j=(i+1); jarr[j]) 19 | { 20 | small = arr[j]; 21 | count++; 22 | index = j; 23 | } 24 | } 25 | if(count!=0) 26 | { 27 | temp = arr[i]; 28 | arr[i] = small; 29 | arr[index] = temp; 30 | } 31 | count=0; 32 | } 33 | cout<<"Now the Array after sorting is :\n"; 34 | for(i=0; i 3 | int visit[100]; 4 | void creategraph(); 5 | void dfs(int); 6 | int a[100][100],n; 7 | int main() 8 | { 9 | int i,v,k; 10 | 11 | printf("Enter the number of vertices.."); 12 | scanf("%d",&n); 13 | 14 | creategraph(); 15 | printf("Enter the source vertex..\n"); 16 | scanf("%d",&v); 17 | 18 | printf("The vertices reachable from %d using DFS are..\n",v); 19 | dfs(v); 20 | 21 | } 22 | 23 | void dfs(int v) 24 | { 25 | int w; 26 | visit[v]=1; 27 | printf("%d ",v); 28 | 29 | for(w=1;w<=n;w++) 30 | { 31 | if((a[v][w]==1)&&(visit[w]==0)) 32 | dfs(w); 33 | } 34 | } 35 | 36 | 37 | void creategraph() 38 | { 39 | int i,j; 40 | while(1) 41 | { 42 | printf("Enter the source and the destination vertex.."); 43 | scanf("%d%d",&i,&j); 44 | if((i==0)&&(j==0)) 45 | break; 46 | a[i][j]=1; 47 | } 48 | } -------------------------------------------------------------------------------- /Kotlin/Selection_Sort_In_Kotlin.kt: -------------------------------------------------------------------------------- 1 | //Selection Sort 2 | //Driver function 3 | fun main (args : Array) { 4 | print("Enter the size of the array : ") 5 | var n = readLine()!!.toInt() 6 | var arr = Array(n, {0}) 7 | println("Enter the elements of the array") 8 | for (i in 0 until n) { 9 | arr[i] = readLine()!!.toInt() 10 | } 11 | selectionSort(arr) 12 | } 13 | 14 | //function for selection sort 15 | 16 | fun selectionSort(arr : Array) { 17 | var n = arr.size 18 | var index : Int 19 | var min : Int 20 | for(i in 0 until n-1) { 21 | min = arr[i] 22 | index = i 23 | for(j in i+1 until n) { 24 | if (min > arr[j]) { 25 | min = arr[j] 26 | index = j 27 | } 28 | } 29 | var temp = arr[i] 30 | arr[i] = arr[index] 31 | arr[index] = temp 32 | 33 | } 34 | for (i in arr) { 35 | print("$i ") 36 | } 37 | } 38 | 39 | //This code is contributed by jatinsachdevame 40 | -------------------------------------------------------------------------------- /LongestCommonSubsequence/longest-common-subsequence.java: -------------------------------------------------------------------------------- 1 | public class LongestCommonSubsequence { 2 | 3 | /* Returns length of LCS for X[0..m-1], Y[0..n-1] */ 4 | int lcs(char[] X, char[] Y, int m, int n) 5 | { 6 | int L[][] = new int[m + 1][n + 1]; 7 | 8 | /* Following steps build L[m+1][n+1] in bottom up fashion. Note 9 | that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ 10 | for (int i = 0; i <= m; i++) { 11 | for (int j = 0; j <= n; j++) { 12 | if (i == 0 || j == 0) 13 | L[i][j] = 0; 14 | else if (X[i - 1] == Y[j - 1]) 15 | L[i][j] = L[i - 1][j - 1] + 1; 16 | else 17 | L[i][j] = max(L[i - 1][j], L[i][j - 1]); 18 | } 19 | } 20 | return L[m][n]; 21 | } 22 | 23 | /* Utility function to get max of 2 integers */ 24 | int max(int a, int b) 25 | { 26 | return (a > b) ? a : b; 27 | } 28 | 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2019 iam-abbas 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /Searching and Sorting/Counting Sort/countingsort.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | implementation of counting sort 3 | in this sorting we have restriction on maximum value of array 4 | */ 5 | 6 | #include 7 | using namespace std; 8 | int main() 9 | { 10 | int a,b; 11 | cout<<"enter the length and maximum value\n"; 12 | cin>>a>>b; 13 | int k1[a], k2[a]; 14 | for(int i=0;i>k1[i]; 17 | 18 | } 19 | int l1[b+1]; // creating an extra array for counting frequency of elements 20 | for(int i=0;i=0; i--) 31 | { 32 | k2[l1[k1[i]]]=k1[i]; // puting elements in sorted order 33 | l1[k1[i]]-=1; 34 | } 35 | for(int i=1; i<=a;i++) // printing array 36 | cout< 5 | using namespace std; 6 | #define MAXN 20 7 | 8 | // Function to Calculate value of Binomial Coefficient C(n, k) 9 | long long binomialCoefficient(long long n, long long k) 10 | { 11 | long long result = 1; 12 | 13 | // Since C(n, k) = C(n, n-k) 14 | if (k > n - k) 15 | k = n - k; 16 | 17 | // Calculation of [n*(n-1)*---*(n-k+1)] / [k*(k-1)*---*1] 18 | for (int i = 0; i < k; ++i) 19 | { 20 | result *= (n - i); 21 | result /= (i + 1); 22 | } 23 | 24 | return result; 25 | } 26 | 27 | // A Binomial coefficient based function to find nth catalan 28 | // number in O(n) time 29 | long long catalan_no(long long n) 30 | { 31 | // Calculate value of 2nCn 32 | long long c = binomialCoefficient(2*n, n); 33 | 34 | // return 2nCn/(n+1) 35 | return c/(n+1); 36 | } 37 | 38 | int main() 39 | { 40 | for (int i = 0; i < MAXN; i++) 41 | cout << catalan_no(i) << " "; 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /Dynamic Programming/maximum_product_cutting/maximum.cpp: -------------------------------------------------------------------------------- 1 | // A Naive Recursive method to find maxium product 2 | #include 3 | using namespace std; 4 | 5 | // Utility function to get the maximum of two and three integers 6 | int max(int a, int b) { return (a > b)? a : b;} 7 | int max(int a, int b, int c) { return max(a, max(b, c));} 8 | 9 | // The main function that returns maximum product obtainable 10 | // from a rope of length n 11 | // A Dynamic Programming solution for Max Product Problem 12 | int maxProd(int n) 13 | { 14 | int val[n+1]; 15 | val[0] = val[1] = 0; 16 | 17 | // Build the table val[] in bottom up manner and return 18 | // the last entry from the table 19 | for (int i = 1; i <= n; i++) 20 | { 21 | int max_val = 0; 22 | for (int j = 1; j <= i/2; j++) 23 | max_val = max(max_val, (i-j)*j, j*val[i-j]); 24 | val[i] = max_val; 25 | } 26 | return val[n]; 27 | } 28 | 29 | 30 | /* Driver program to test above functions */ 31 | int main() 32 | { 33 | cout << "Maximum Product is " << maxProd(10); 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /Linked List/detectLoop.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | class Node { 6 | public: 7 | int data; 8 | Node* next; 9 | }; 10 | 11 | void push(Node** head_ref, int new_data) 12 | { 13 | Node* new_node = new Node(); 14 | 15 | new_node->data = new_data; 16 | 17 | new_node->next = (*head_ref); 18 | 19 | (*head_ref) = new_node; 20 | } 21 | 22 | int detectloop(Node* list) 23 | { 24 | Node *slow = list, *fast = list; 25 | 26 | while (slow && fast && fast->next) { 27 | slow = slow->next; 28 | fast = fast->next->next; 29 | if (slow == fast) { 30 | cout << "Loop Exists"; 31 | return 1; 32 | } 33 | } 34 | return 0; 35 | } 36 | 37 | int main() 38 | { 39 | Node* head = NULL; 40 | 41 | push(&head, 20); 42 | push(&head, 4); 43 | push(&head, 15); 44 | push(&head, 10); 45 | 46 | head->next->next->next->next = head; 47 | detectloop(head); 48 | 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /Searching and Sorting/Linear Search/Java/LinearSearch.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | class LinearSearch 3 | { 4 | public static void main(String args[]) 5 | { 6 | int counter, numOfElements, itemToSearch, array[]; 7 | Scanner input = new Scanner(System.in); 8 | System.out.println("Enter number of elements:"); 9 | numOfElements = input.nextInt(); 10 | array = new int[numOfElements]; 11 | System.out.println("Enter elements"); 12 | for (counter = 0; counter < numOfElements; counter++) 13 | array[counter] = input.nextInt(); 14 | System.out.println("Enter the search value:"); 15 | itemToSearch = input.nextInt(); 16 | for (counter = 0; counter < numOfElements; counter++) 17 | { 18 | if (array[counter] == itemToSearch) 19 | { 20 | System.out.println(itemToSearch+" is present at "+(counter+1)); 21 | break; 22 | } 23 | } 24 | if (counter == numOfElements) 25 | System.out.println(itemToSearch + " is not present"); 26 | } 27 | } -------------------------------------------------------------------------------- /Backtracking/generate all valid parenthesis/print all parantheses.cpp: -------------------------------------------------------------------------------- 1 | // C program to Print all combinations 2 | // of balanced parentheses 3 | # include 4 | # define MAX_SIZE 100 5 | 6 | void _printParenthesis(int pos, int n, int open, int close); 7 | 8 | // Wrapper over _printParenthesis() 9 | void printParenthesis(int n) 10 | { 11 | if(n > 0) 12 | _printParenthesis(0, n, 0, 0); 13 | return; 14 | } 15 | 16 | void _printParenthesis(int pos, int n, int open, int close) 17 | { 18 | static char str[MAX_SIZE]; 19 | 20 | if(close == n) 21 | { 22 | printf("%s \n", str); 23 | return; 24 | } 25 | else 26 | { 27 | if(open > close) 28 | { 29 | str[pos] = '}'; 30 | _printParenthesis(pos+1, n, open, close+1); 31 | } 32 | 33 | if(open < n) 34 | { 35 | str[pos] = '{'; 36 | _printParenthesis(pos+1, n, open+1, close); 37 | } 38 | } 39 | } 40 | 41 | // Driver program to test above functions 42 | int main() 43 | { 44 | int n = 3; 45 | printParenthesis(n); 46 | getchar(); 47 | return 0; 48 | } 49 | -------------------------------------------------------------------------------- /Sorting Algorithm/insertionsort.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for insertion sort 2 | #include 3 | using namespace std; 4 | 5 | /* Function to sort an array using insertion sort*/ 6 | void insertionSort(int arr[], int n) 7 | { 8 | int i, key, j; 9 | for (i = 1; i < n; i++) 10 | { 11 | key = arr[i]; 12 | j = i - 1; 13 | 14 | /* Move elements of arr[0..i-1], that are 15 | greater than key, to one position ahead 16 | of their current position */ 17 | while (j >= 0 && arr[j] > key) 18 | { 19 | arr[j + 1] = arr[j]; 20 | j = j - 1; 21 | } 22 | arr[j + 1] = key; 23 | } 24 | } 25 | 26 | // A utility function to print an array of size n 27 | void printArray(int arr[], int n) 28 | { 29 | int i; 30 | for (i = 0; i < n; i++) 31 | cout << arr[i] << " "; 32 | cout << endl; 33 | } 34 | 35 | /* Driver code */ 36 | int main() 37 | { 38 | int arr[] = { 12, 11, 13, 5, 6 }; 39 | int n = sizeof(arr) / sizeof(arr[0]); 40 | 41 | insertionSort(arr, n); 42 | printArray(arr, n); 43 | 44 | return 0; 45 | } 46 | 47 | 48 | -------------------------------------------------------------------------------- /Sorting Algorithm/mergeSort.py: -------------------------------------------------------------------------------- 1 | 2 | def mergeSort(arrInput): 3 | if len(arrInput) > 1: 4 | mid = len(arrInput) // 2 # midpoint of input array 5 | left = arrInput[:mid] # Dividing the left side of elements 6 | right = arrInput[mid:] # Divide into second half 7 | mergeSort(left) # Sorting first half 8 | mergeSort(right) # Sorting second half 9 | i = 0 10 | j = 0 11 | k = 0 12 | # Copy data to temp arrInput left[] and right[] 13 | while i < len(left) and j < len(right): 14 | if left[i] < right[j]: 15 | arrInput[k] = left[i] 16 | i += 1 17 | else: 18 | arrInput[k] = right[j] 19 | j += 1 20 | k += 1 21 | 22 | # Checking if any element was left 23 | while i < len(left): 24 | arrInput[k] = left[i] 25 | i += 1 26 | k += 1 27 | 28 | while j < len(right): 29 | arrInput[k] = right[j] 30 | j += 1 31 | k += 1 32 | -------------------------------------------------------------------------------- /quick sort in kotlin: -------------------------------------------------------------------------------- 1 | fun quick_sort(A: Array, p: Int, r: Int) { 2 | if (p < r) { 3 | var q: Int = partition(A, p, r) 4 | quick_sort(A, p, q - 1) 5 | quick_sort(A, q + 1, r) 6 | 7 | } 8 | } 9 | 10 | fun partition(A: Array, p: Int, r: Int): Int { 11 | var x = A[r] 12 | var i = p - 1 13 | for (j in p until r) { 14 | if (A[j] <= x) { 15 | i++ 16 | exchange(A, i, j) 17 | } 18 | } 19 | exchange(A, i + 1, r) 20 | return i + 1 21 | } 22 | 23 | fun exchange(A: Array, i: Int, j: Int) { 24 | var temp = A[i] 25 | A[i] = A[j] 26 | A[j] = temp 27 | } 28 | 29 | fun main(arg: Array) { 30 | print("Enter no. of elements :") 31 | var n = readLine()!!.toInt() 32 | 33 | println("Enter elements : ") 34 | var A = Array(n, { 0 }) 35 | for (i in 0 until n) 36 | A[i] = readLine()!!.toInt() 37 | 38 | quick_sort(A, 0, A.size - 1) 39 | 40 | println("Sorted array is : ") 41 | for (i in 0 until n) 42 | print("${A[i]} ") 43 | } 44 | -------------------------------------------------------------------------------- /Kotlin/quick_sort_in_kotlin: -------------------------------------------------------------------------------- 1 | fun quick_sort(A: Array, p: Int, r: Int) { 2 | if (p < r) { 3 | var q: Int = partition(A, p, r) 4 | quick_sort(A, p, q - 1) 5 | quick_sort(A, q + 1, r) 6 | 7 | } 8 | } 9 | 10 | fun partition(A: Array, p: Int, r: Int): Int { 11 | var x = A[r] 12 | var i = p - 1 13 | for (j in p until r) { 14 | if (A[j] <= x) { 15 | i++ 16 | exchange(A, i, j) 17 | } 18 | } 19 | exchange(A, i + 1, r) 20 | return i + 1 21 | } 22 | 23 | fun exchange(A: Array, i: Int, j: Int) { 24 | var temp = A[i] 25 | A[i] = A[j] 26 | A[j] = temp 27 | } 28 | 29 | fun main(arg: Array) { 30 | print("Enter no. of elements :") 31 | var n = readLine()!!.toInt() 32 | 33 | println("Enter elements : ") 34 | var A = Array(n, { 0 }) 35 | for (i in 0 until n) 36 | A[i] = readLine()!!.toInt() 37 | 38 | quick_sort(A, 0, A.size - 1) 39 | 40 | println("Sorted array is : ") 41 | for (i in 0 until n) 42 | print("${A[i]} ") 43 | } 44 | -------------------------------------------------------------------------------- /Stack Algorithms/Span Problem/C++/span.cpp: -------------------------------------------------------------------------------- 1 | // Span Problem 2 | // Here we have to find span of every element in an array, i.e number of consecutive elements before that element (including that element also) 3 | // having values less than or equal to value of current element 4 | // Note: Span of every element will be atleast 1 5 | 6 | 7 | #include 8 | #include 9 | using namespace std; 10 | 11 | //function for span problem 12 | void spans(int *a, int n, int *span){ 13 | stack s; 14 | 15 | for(int i = 0; i=a[s.top()]){ 17 | s.pop(); 18 | } 19 | if(s.empty()){ 20 | span[i] = i+1; 21 | s.push(i); 22 | } 23 | else{ 24 | span[i] = i-s.top(); 25 | s.push(i); 26 | } 27 | } 28 | 29 | } 30 | 31 | //testing our span function 32 | int main(){ 33 | int a[] = {9,12,5,13}; 34 | int span[4]; 35 | stack s; 36 | spans(a,4,span); 37 | for(int i = 0 ; i<4; i++) cout< 3 | using namespace std ; 4 | int BinarySearch(int arr[] ,int n , int val ) 5 | { 6 | int start=0 ; 7 | int end=n-1 ; 8 | int mid ; 9 | 10 | 11 | while(start<=end) 12 | { 13 | mid=(start+end)/2 ; 14 | if(val==arr[mid]) 15 | { 16 | return mid ; 17 | } 18 | else if(val > arr[mid]) 19 | { 20 | start=mid+1 ; 21 | 22 | } 23 | else 24 | { 25 | end=mid-1 ; 26 | } 27 | 28 | } 29 | return -1 ; 30 | 31 | } 32 | 33 | int main() 34 | { 35 | int arr[50],n ; 36 | int result ; 37 | cout << "Enter the no. of elements do u want to enter" ; 38 | cin >> n ; 39 | 40 | cout << "Enter the elements that you want to insert in the Array " << endl ; 41 | for(int i=0 ; i> arr[i] ; 44 | } 45 | 46 | cout << "Enter the element that you want to search for in the Array" << endl ; 47 | int val ; 48 | cin >> val ; 49 | 50 | result= BinarySearch(arr,n,val) ; 51 | cout << result << endl ; 52 | 53 | } 54 | -------------------------------------------------------------------------------- /Dynamic Programming/placing_parentheses.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | bool canPartition(vector& nums, int k) 5 | { 6 | int sum0=accumulate(nums.begin(),nums.end(),0); 7 | if(sum0%k) return 0; 8 | //discrete knapsack without repeti 9 | int n=nums.size(); 10 | vector > value(sum0/k+1,vector(n+1)); 11 | for(int i=1;i<=n;i++) 12 | { 13 | int wi=nums[i-1]; 14 | //cout<wi then it use previous value 18 | if(w>=wi) 19 | { 20 | value[w][i]=max(value[w-wi][i-1]+wi,value[w][i-1]); 21 | } 22 | } 23 | } 24 | return value[sum0/k][n]==sum0/k; 25 | } 26 | 27 | int main(int argc, char const *argv[]) 28 | { 29 | int n, k =3; 30 | cin >> n; 31 | vector nums(n); 32 | for (int i = 0; i < n; ++i) 33 | { 34 | cin >> nums[i]; 35 | } 36 | cout << canPartition(nums, k); 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /Graph Algorithms/detectcycleingraph.py: -------------------------------------------------------------------------------- 1 | def DFS(graph, v): 2 | color = [-1] * v 3 | parent = [-1] * v 4 | time = 0 5 | for i in range(v): 6 | if(color[i] == -1): 7 | DFSvisit(graph, v, i, color, parent, time) 8 | print(color) 9 | print(parent) 10 | 11 | def DFSvisit(graph, v, s, color, parent, time): 12 | color[s] = 0 13 | time += 1 14 | for i in range(0,v): 15 | if(graph[s][i]==1): 16 | if(color[i]==0): 17 | print("Cycle detected at:",s) 18 | return 19 | if(graph[s][i] == 1): 20 | if(color[i] == 0): 21 | parent[i] = s 22 | DFSvisit(graph, v, i, color, parent, time) 23 | color[s] = 1 24 | time += 1 25 | 26 | 27 | def main(): 28 | Graph=[[0, 1, 1, 0, 0, 0], 29 | [1, 0, 0, 1, 0, 0], 30 | [0, 0, 1, 0, 0, 0], 31 | [0, 0, 1, 1, 0, 0], 32 | [0, 0, 0, 0, 0, 0], 33 | [0, 0, 0, 0, 0, 1]] 34 | v = len(Graph[0]) 35 | DFS(Graph, v) 36 | 37 | if __name__ == '__main__': 38 | main() 39 | -------------------------------------------------------------------------------- /C/insertion.c: -------------------------------------------------------------------------------- 1 | // C program for insertion sort 2 | #include 3 | #include 4 | 5 | /* Function to sort an array using insertion sort*/ 6 | void insertionSort(int arr[], int n) 7 | { 8 | int i, key, j; 9 | for (i = 1; i < n; i++) { 10 | key = arr[i]; 11 | j = i - 1; 12 | 13 | /* Move elements of arr[0..i-1], that are 14 | greater than key, to one position ahead 15 | of their current position */ 16 | while (j >= 0 && arr[j] > key) { 17 | arr[j + 1] = arr[j]; 18 | j = j - 1; 19 | } 20 | arr[j + 1] = key; 21 | } 22 | } 23 | 24 | // A utility function to print an array of size n 25 | void printArray(int arr[], int n) 26 | { 27 | int i; 28 | for (i = 0; i < n; i++) 29 | printf("%d ", arr[i]); 30 | printf("\n"); 31 | } 32 | 33 | 34 | int main() 35 | { 36 | int arr[] = { 12, 11, 13, 5, 6 }; 37 | int n = sizeof(arr) / sizeof(arr[0]); 38 | 39 | insertionSort(arr, n); 40 | printArray(arr, n); 41 | 42 | return 0; 43 | } -------------------------------------------------------------------------------- /Searching and Sorting/Topological Sorting/C/topological.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(){ 4 | int i,j,k,n,a[10][10],indeg[10],flag[10],count=0; 5 | 6 | printf("Enter the no of vertices:\n"); 7 | scanf("%d",&n); 8 | 9 | printf("Enter the adjacency matrix:\n"); 10 | for(i=0;i 11 | using namespace std; 12 | int main() 13 | { 14 | int n,row,col,k,j; 15 | cin>>n; 16 | row=1,k=1,j=1; 17 | while(row<=n) 18 | { 19 | col=1; 20 | while(col<=n) 21 | { 22 | if(col<=n/2+1-k || col>=n/2+1+k) 23 | cout<<" "; 24 | else 25 | { 26 | cout< 5 | using namespace std; 6 | 7 | 8 | // Function to print permutations of string 9 | // This function takes three parameters: 10 | // 1. String 11 | // 2. Starting index of the string 12 | // 3. Ending index of the string. 13 | void permute(string a, int l, int r) 14 | { 15 | // Base case 16 | if (l == r) 17 | cout< lft { 12 | mid = (rgt + lft) / 2 13 | 14 | invCnt = mergeSort(arr, tmp, lft, mid) 15 | invCnt += mergeSort(arr, tmp, mid+1, rgt) 16 | 17 | invCnt += merge(arr, tmp, lft, mid+1, rgt) 18 | } 19 | 20 | return invCnt 21 | } 22 | 23 | func merge(arr []int, tmp []int, lft, mid, rgt int) int { 24 | i, j, k := lft, mid, lft 25 | invCnt := 0 26 | 27 | for i <= (mid-1) && j <= rgt { 28 | if arr[i] <= arr[j] { 29 | tmp[k] = arr[i] 30 | k++ 31 | i++ 32 | } else { 33 | tmp[k] = arr[j] 34 | k++ 35 | j++ 36 | invCnt += (mid - i) 37 | } 38 | } 39 | 40 | for i <= (mid - 1) { 41 | tmp[k] = arr[i] 42 | i++ 43 | k++ 44 | } 45 | 46 | for j <= rgt { 47 | tmp[k] = arr[j] 48 | k++ 49 | j++ 50 | } 51 | 52 | for i = lft; i <= rgt; i++ { 53 | arr[i] = tmp[i] 54 | } 55 | 56 | return invCnt 57 | } 58 | -------------------------------------------------------------------------------- /Kotlin/merge_sort_in_kotlin.kt: -------------------------------------------------------------------------------- 1 | fun merge(A: Array, p: Int, q: Int, r: Int) { 2 | var left = A.copyOfRange(p, q + 1) 3 | var right = A.copyOfRange(q + 1, r + 1) 4 | var i = 0 5 | var j = 0 6 | 7 | for (k in p..r) { 8 | if ((i <= left.size - 1) && ((j >= right.size) || (left[i] <= right[j]))) { 9 | A[k] = left[i]; 10 | i++; 11 | } else { 12 | A[k] = right[j]; 13 | j++; 14 | } 15 | } 16 | } 17 | 18 | fun merge_sort(A: Array, p: Int, r: Int) { 19 | if (p < r) { 20 | var q = (p + r) / 2 21 | merge_sort(A, p, q) 22 | merge_sort(A, q + 1, r) 23 | merge(A, p, q, r) 24 | } 25 | } 26 | 27 | fun main(arg: Array) { 28 | print("Enter no. of elements :") 29 | var n = readLine()!!.toInt() 30 | 31 | println("Enter elements : ") 32 | var A = Array(n, { 0 }) 33 | for (i in 0 until n) 34 | A[i] = readLine()!!.toInt() 35 | 36 | merge_sort(A, 0, A.size - 1) 37 | 38 | println("Sorted array is : ") 39 | for (i in 0 until n) 40 | print("${A[i]} ") 41 | } 42 | -------------------------------------------------------------------------------- /MaxProductArray/Python/max_product_subarray.py: -------------------------------------------------------------------------------- 1 | def max_subarray_product(arr, n): 2 | max_ending_here = 1 3 | min_ending_here = 1 4 | max_so_far = 1 5 | flag = 0 6 | for i in range(0, n): 7 | if arr[i] > 0: 8 | max_ending_here = max_ending_here * arr[i] 9 | min_ending_here = min(min_ending_here * arr[i], 1) 10 | flag = 1 11 | elif arr[i] == 0: 12 | max_ending_here = 1 13 | min_ending_here = 1 14 | else: 15 | temp = max_ending_here 16 | max_ending_here = max(min_ending_here * arr[i], 1) 17 | min_ending_here = temp * arr[i] 18 | 19 | if max_so_far < max_ending_here: 20 | max_so_far = max_ending_here 21 | if flag == 0 and max_so_far == 1: 22 | return 0 23 | return max_so_far 24 | 25 | 26 | if __name__ == "__main__": 27 | arr = [1, -2, -3, 0, 7, -8, -2] 28 | n = len(arr) 29 | print("Maximum Sub array product is: ", end='') 30 | if n > 0: 31 | ans = max_subarray_product(arr, n) 32 | print(ans, end='') 33 | else: 34 | print(0) 35 | -------------------------------------------------------------------------------- /C/selection.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void swap(int *xp, int *yp) 4 | { 5 | int temp = *xp; 6 | *xp = *yp; 7 | *yp = temp; 8 | } 9 | 10 | void selectionSort(int arr[], int n) 11 | { 12 | int i, j, min_idx; 13 | 14 | // One by one move boundary of unsorted subarray 15 | for (i = 0; i < n-1; i++) 16 | { 17 | // Find the minimum element in unsorted array 18 | min_idx = i; 19 | for (j = i+1; j < n; j++) 20 | if (arr[j] < arr[min_idx]) 21 | min_idx = j; 22 | 23 | // Swap the found minimum element with the first element 24 | swap(&arr[min_idx], &arr[i]); 25 | } 26 | } 27 | 28 | /* Function to print an array */ 29 | void printArray(int arr[], int size) 30 | { 31 | int i; 32 | for (i=0; i < size; i++) 33 | printf("%d ", arr[i]); 34 | printf("\n"); 35 | } 36 | 37 | int main() 38 | { 39 | int arr[] = {64, 25, 12, 22, 11}; 40 | int n = sizeof(arr)/sizeof(arr[0]); 41 | selectionSort(arr, n); 42 | printf("Sorted array: \n"); 43 | printArray(arr, n); 44 | return 0; 45 | } --------------------------------------------------------------------------------