├── Java ├── Recursion │ ├── factorialUsingRecursion.java │ ├── nCr.java │ ├── sumOfNNumbers.java │ ├── countDigitsInANumber.java │ ├── sumOfDigits.java │ ├── euclidGCD.java │ ├── printOneToN.java │ ├── nthFibonacci.java │ ├── binaryExponentiation.java │ ├── printArrayRecursive.java │ ├── checkPalindromeNumber.java │ └── towerOfHanoiMoveCount.java ├── Unit Tests │ ├── README.md │ ├── LeftRotateByOneTest.java │ ├── deleteElementTest.java │ ├── rotateArrayDTimesTest.java │ ├── checkIfArrayIsSortedTest.java │ ├── MoveZerosToEndTest.java │ └── GetLargestElementIndexTest.java ├── Arrays │ ├── LeftRotateByOne.java │ ├── checkIfArrayIsSorted.java │ ├── GetLargestElementIndex.java │ ├── RotateArrayDTimes.java │ ├── insertion.java │ ├── RemoveDuplicatesFromSortedArray.java │ ├── FibonacciSeries.java │ ├── TwoPointerAlgo.java │ └── array_sum.java ├── Miscellaneous │ ├── pow.java │ └── valid_parentheses.java ├── Sorting │ ├── bubbleSort.java │ ├── tim_sort.java │ ├── heapSort.java │ ├── countingSort │ ├── selection_sort.java │ ├── insertion_sort.java │ ├── quick_sort.java │ └── merge_sort.java └── Searching │ ├── ExponentialSearch.java │ ├── binarySearch.java │ └── Interpolation_Search.java ├── JavaScript ├── Searching │ ├── linear_search.js │ └── binary_search.js ├── Unit Tests │ ├── README.md │ ├── bubble_sort_test.js │ ├── binary_search_test.js │ └── insertion_sort_test.js ├── Sorting │ ├── insertion_sort.js │ ├── bubble_sort.js │ ├── selection_sort.js │ ├── radix_sort.js │ ├── merge_sort.js │ └── quick_sort.js ├── Miscellaneous │ └── tower_of_hanoi.js ├── README.md └── Graph Algorithms │ └── bfs.js ├── Python ├── Machine Learning Algorithms │ └── Decision_Tree_Algorithm │ │ └── Screenshot (26).png ├── Unit Tests │ ├── README.md │ ├── next_president_test.py │ └── duplicate_zeros_test.py ├── Miscellaneous │ ├── kadane_algorithm.py │ ├── is_anagram.py │ ├── gcd.py │ ├── next_president.py │ ├── stack.py │ ├── queue.py │ ├── duplicate_zeros.py │ ├── majority_element.py │ ├── prime_upto_n.py │ ├── fibonacci_rec.py │ ├── rotation.py │ └── single_linked_list.py ├── Sorting │ ├── selection_sort.py │ ├── insertion_sort.py │ ├── bubble_sort.py │ ├── quick_sort.py │ └── merge_sort.py ├── Searching │ ├── linear_search.py │ ├── jump_search.py │ ├── interpolation.py │ └── binary_search.py ├── Tree Algorithms │ ├── level_order_traversal.py │ └── balanced_binary_tree_check.py └── Graph Algorithms │ ├── dijkstras.py │ └── breadth_first_search.py ├── Go ├── Unit Tests │ └── README.md ├── Miscellaneous │ └── fibonacci_rec.go ├── Sorting │ ├── bubble_sort.go │ ├── quick_sort.go │ ├── selection_sort.go │ └── radix_sort.go ├── Searching │ └── binary_search.go └── README.md ├── C++ ├── Unit Tests │ └── README.md ├── Math │ ├── fibonacci.cpp │ ├── binary_exponentiation.cpp │ ├── pascal_triangle.cpp │ ├── binary_gcd.cpp │ ├── josephus_problem.cpp │ ├── factorial_20.cpp │ ├── sieve_of_eratosthenes.cpp │ ├── matrix_exponentiation.cpp │ └── nCr_mod_prime.cpp ├── Miscellaneous │ ├── tower_of_hanoi.cpp │ ├── leaders_in_an_array.cpp │ ├── stock_buy_and_sell_problem.cpp │ ├── kadanes_algo.cpp │ ├── trapping_rain_water.cpp │ ├── greedy_money_change_recursive.cpp │ ├── majority_element.cpp │ ├── range_sum_segment_tree.cpp │ └── sjf.cpp ├── Searching │ ├── binary_search.cpp │ ├── linear_search.cpp │ ├── jump_search.cpp │ ├── recursive_linear_search.cpp │ ├── stair_case_search.cpp │ ├── quick_select.cpp │ ├── interpolation_search.cpp │ ├── fibonacci_search.cpp │ ├── exponential_search.cpp │ ├── depth_first_search.cpp │ └── breadth_first_search.cpp ├── Dynamic Programming │ ├── lcs.cpp │ ├── 0-1_knapsack.cpp │ ├── activity_selection_problem.c │ ├── dp_coin_change.cpp │ ├── dp_fibonacci.cpp │ ├── matrix_chain_multiplication.cpp │ └── fractional_knapsack.c ├── Sorting │ ├── insertion_sort.cpp │ ├── selection_sort.cpp │ ├── bucket_sort.cpp │ ├── quick_sort.cpp │ ├── bubble_sort.cpp │ ├── cocktail_sort.cpp │ ├── shell_sort.cpp │ ├── radix_sort.cpp │ ├── counting_sort.cpp │ ├── heap_sort.cpp │ ├── merge_sort.cpp │ └── cycle_sort.cpp ├── Tree Alogrithms │ ├── inorder_traversal.cpp │ ├── preorder_traversal.cpp │ ├── postorder_traversal.cpp │ ├── balanced_binary_tree_check.cpp │ ├── binary_tree_to_doublyLL.cpp │ ├── level_order_traversal.cpp │ ├── binary_tree_from_inorder_preorder.cpp │ └── inverse_binary_tree.cpp ├── Strings │ ├── string_sorting.cpp │ └── kmp_algo.cpp └── Graph Algorithms │ ├── kruskal.cpp │ ├── cycle_in_undirected_graph.cpp │ ├── floyd_warshall.cpp │ ├── cycle_in_directed_graph.cpp │ ├── hamiltonian_path_cycle.cpp │ ├── flood_fill_algorithm.cpp │ ├── min_cost_path_of_graph.cpp │ ├── dijktras.cpp │ └── prim.cpp ├── Dart ├── Unit Tests │ └── README.md ├── Sorting │ ├── selection_sort.dart │ ├── insertion_sort.dart │ ├── bubble_sort.dart │ ├── merge_sort.dart │ └── quick_sort.dart ├── Searching │ ├── linear_search.dart │ ├── binary_search.dart │ ├── interpolation_search.dart │ └── jump_search.dart └── README.md ├── Rust ├── Unit Tests │ └── README.md ├── Searching │ ├── linear_search.rs │ └── binary_search.rs ├── Sorting │ ├── selection_sort.rs │ ├── insertion_sort.rs │ ├── bubble_sort.rs │ └── merge_sort.rs └── README.md ├── Swift ├── Unit Tests │ └── README.md ├── Sorting │ ├── bubble_sort.swift │ └── selection_sort.swift ├── Searching │ └── binary_search.swift └── README.md ├── CONTRIBUTING.md └── LICENSE /Java/Recursion/factorialUsingRecursion.java: -------------------------------------------------------------------------------- 1 | public static int fact(int n) { 2 | if(n == 0) return 1; 3 | return n * fact(n - 1); 4 | } 5 | -------------------------------------------------------------------------------- /Java/Recursion/nCr.java: -------------------------------------------------------------------------------- 1 | public static int nCr(int n,int r) { 2 | if(n == r || r == 0) return 1; 3 | return nCr(n-1, r-1) + nCr(n-1, r); 4 | } 5 | -------------------------------------------------------------------------------- /Java/Recursion/sumOfNNumbers.java: -------------------------------------------------------------------------------- 1 | public static int recursiveSum(int n) { 2 | if(n == 0) return 0; 3 | return n + recursiveSum(n - 1); 4 | } 5 | -------------------------------------------------------------------------------- /Java/Recursion/countDigitsInANumber.java: -------------------------------------------------------------------------------- 1 | public static int countDigits(int n) { 2 | if(n < 10) return 1; 3 | return 1 + countDigits(n / 10); 4 | } 5 | -------------------------------------------------------------------------------- /Java/Recursion/sumOfDigits.java: -------------------------------------------------------------------------------- 1 | public static int sumOfDigits(int n) { 2 | if(n < 10) return n; 3 | return (n % 10) + sumOfDigits(n / 10); 4 | } 5 | -------------------------------------------------------------------------------- /Java/Recursion/euclidGCD.java: -------------------------------------------------------------------------------- 1 | public static int gcd(int a, int b){ 2 | if(a == 0) return b; 3 | if(b == 0) return a; 4 | return gcd(b, a % b); 5 | } 6 | -------------------------------------------------------------------------------- /Java/Recursion/printOneToN.java: -------------------------------------------------------------------------------- 1 | public static void printOneToN(int n) { 2 | if(n == 0) return; 3 | printOneToN(n - 1); 4 | System.out.print(n + " "); 5 | } 6 | -------------------------------------------------------------------------------- /Java/Recursion/nthFibonacci.java: -------------------------------------------------------------------------------- 1 | static long fibonacci(int n) { 2 | if(n == 1) return 1; 3 | if(n == 2) return 1; 4 | return fibonacci(n-1) + fibonacci(n-2); 5 | } 6 | -------------------------------------------------------------------------------- /JavaScript/Searching/linear_search.js: -------------------------------------------------------------------------------- 1 | function linearSearch(arr, val){ 2 | for(var i = 0; i < arr.length; i++){ 3 | if(arr[i] === val) return i; 4 | } 5 | return -1; 6 | } 7 | -------------------------------------------------------------------------------- /Python/Machine Learning Algorithms/Decision_Tree_Algorithm/Screenshot (26).png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aniketsharma00411/algorithmsUse/HEAD/Python/Machine Learning Algorithms/Decision_Tree_Algorithm/Screenshot (26).png -------------------------------------------------------------------------------- /Java/Recursion/binaryExponentiation.java: -------------------------------------------------------------------------------- 1 | static int RecursivePower(int n,int p) { 2 | if (p == 0)return 1; 3 | int res = RecursivePower(n, p / 2); 4 | if (p % 2 != 0) return res * res * n; 5 | else return res * res; 6 | } 7 | -------------------------------------------------------------------------------- /Java/Recursion/printArrayRecursive.java: -------------------------------------------------------------------------------- 1 | // arr[]: input array 2 | // n: size of inout array 3 | public static void printArrayRecursively(int arr[], int n) { 4 | if(n == 0) return; 5 | printArrayRecursively(arr, n - 1); 6 | System.out.print(arr[n - 1] + " "); 7 | } 8 | -------------------------------------------------------------------------------- /Go/Unit Tests/README.md: -------------------------------------------------------------------------------- 1 | # Unit Tests for Go Algorithms 2 | 3 | Unit Tests are needed for programs which are already present. 4 | 5 | Add atlest 5 unit tests per program. 6 | 7 | ### File Naming 8 | 9 | Let there is a program named abcd.go, its Unit Test should be named abcd_test.go 10 | -------------------------------------------------------------------------------- /C++/Unit Tests/README.md: -------------------------------------------------------------------------------- 1 | # Unit Tests for C++ Algorithms 2 | 3 | Unit Tests are needed for programs which are already present. 4 | 5 | Add atlest 5 unit tests per program. 6 | 7 | ### File Naming 8 | 9 | Let there is a program named abcd.cpp, its Unit Test should be named abcd_test.cpp 10 | -------------------------------------------------------------------------------- /Dart/Unit Tests/README.md: -------------------------------------------------------------------------------- 1 | # Unit Tests for Dart Algorithms 2 | 3 | Unit Tests are needed for programs which are already present. 4 | 5 | Add atlest 5 unit tests per program. 6 | 7 | ### File Naming 8 | 9 | Let there is a program named abcd.dart, its Unit Test should be named abcd_test.dart 10 | -------------------------------------------------------------------------------- /Java/Unit Tests/README.md: -------------------------------------------------------------------------------- 1 | # Unit Tests for Java Algorithms 2 | 3 | Unit Tests are needed for programs which are already present. 4 | 5 | Add atlest 5 unit tests per program. 6 | 7 | ### File Naming 8 | 9 | Let there is a program named abcd.java, its Unit Test should be named abcd_test.java 10 | -------------------------------------------------------------------------------- /Python/Unit Tests/README.md: -------------------------------------------------------------------------------- 1 | # Unit Tests for Python Algorithms 2 | 3 | Unit Tests are needed for programs which are already present. 4 | 5 | Add atlest 5 unit tests per program. 6 | 7 | ### File Naming 8 | 9 | Let there is a program named abcd.py, its Unit Test should be named abcd_test.py 10 | -------------------------------------------------------------------------------- /Rust/Unit Tests/README.md: -------------------------------------------------------------------------------- 1 | # Unit Tests for Swift Algorithms 2 | 3 | Unit Tests are needed for programs which are already present. 4 | 5 | Add atlest 5 unit tests per program. 6 | 7 | ### File Naming 8 | 9 | Let there is a program named abcd.rs, its Unit Test should be named abcd_test.rs 10 | -------------------------------------------------------------------------------- /Swift/Unit Tests/README.md: -------------------------------------------------------------------------------- 1 | # Unit Tests for Swift Algorithms 2 | 3 | Unit Tests are needed for programs which are already present. 4 | 5 | Add atlest 5 unit tests per program. 6 | 7 | ### File Naming 8 | 9 | Let there is a program named abcd.swift, its Unit Test should be named abcd_test.swift 10 | -------------------------------------------------------------------------------- /JavaScript/Unit Tests/README.md: -------------------------------------------------------------------------------- 1 | # Unit Tests for JavaScipt Algorithms 2 | 3 | Unit Tests are needed for programs which are already present. 4 | 5 | Add atlest 5 unit tests per program. 6 | 7 | ### File Naming 8 | 9 | Let there is a program named abcd.js, its Unit Test should be named abcd_test.js 10 | -------------------------------------------------------------------------------- /JavaScript/Unit Tests/bubble_sort_test.js: -------------------------------------------------------------------------------- 1 | // test file using jest 2 | 3 | const{ 4 | bubbleSort 5 | } = require("../Sorting/bubble_sort") 6 | 7 | test('Bubble sort of array(1,5,3,6,4) should be array(1,3,4,5,6)', ()=>{ 8 | expect(bubbleSort(Array(1,5,3,6,4))).toEqual(Array(1,3,4,5,6)); 9 | }); 10 | -------------------------------------------------------------------------------- /Java/Arrays/LeftRotateByOne.java: -------------------------------------------------------------------------------- 1 | package Array; 2 | 3 | public class LeftRotateByOne { 4 | 5 | public static void leftRotateByOne(int[] a) { 6 | int temp = a[0]; 7 | int n = a.length; 8 | System.arraycopy(a, 1, a, 0, n - 1); 9 | a[n - 1] = temp; 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /Java/Arrays/checkIfArrayIsSorted.java: -------------------------------------------------------------------------------- 1 | package Array; 2 | 3 | public class checkIfArrayIsSorted { 4 | public static boolean isSorted(int[] a) { 5 | for (int i = 1; i < a.length; i++) { 6 | if (a[i] < a[i - 1]) return false; 7 | } 8 | return true; 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /Java/Recursion/checkPalindromeNumber.java: -------------------------------------------------------------------------------- 1 | static boolean isPalin(int n) { 2 | int res = rev(n, 0); 3 | if(res == n) return true; 4 | else return false; 5 | } 6 | 7 | static int rev(int n, int temp) { 8 | if (n == 0) return temp; 9 | temp = (temp * 10) + (n % 10); 10 | return rev(n / 10, temp); 11 | } 12 | -------------------------------------------------------------------------------- /Java/Arrays/GetLargestElementIndex.java: -------------------------------------------------------------------------------- 1 | package Array; 2 | 3 | public class GetLargestElementIndex { 4 | public static int getLargestElementIndex(int[] a) { 5 | int res = 0; 6 | for (int i = 1; i < a.length; i++) { 7 | if (a[i] > a[res]) res = i; 8 | } 9 | return res; 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /Python/Miscellaneous/kadane_algorithm.py: -------------------------------------------------------------------------------- 1 | def kadane(A): 2 | max_curr= A[0] 3 | max_global = A[0] 4 | for i in range(1,len(A)): 5 | max_curr = max(A[i],max_curr+A[i]) 6 | if(max_curr>max_global): 7 | max_global = max_curr 8 | return max_global 9 | 10 | A = list(map(int,input().split())) 11 | print(kadane(A)) -------------------------------------------------------------------------------- /JavaScript/Sorting/insertion_sort.js: -------------------------------------------------------------------------------- 1 | function insertionSort(arr){ 2 | var currentVal; 3 | for(var i = 1; i < arr.length; i++){ 4 | currentVal = arr[i]; 5 | for(var j = i - 1; j >= 0 && arr[j] > currentVal; j--) { 6 | arr[j+1] = arr[j] 7 | } 8 | arr[j+1] = currentVal; 9 | } 10 | return arr; 11 | } 12 | -------------------------------------------------------------------------------- /Java/Recursion/towerOfHanoiMoveCount.java: -------------------------------------------------------------------------------- 1 | public long toh(int N, int from, int to, int aux) { 2 | long moves = 0L; 3 | if (N >= 1) { 4 | moves += toh(N - 1, from, aux, to); 5 | System.out.println("move disk " + N + " from rod " + from + " to rod " + to); 6 | moves++; 7 | moves += toh(N - 1, aux, to, from); 8 | } 9 | return moves; 10 | } 11 | -------------------------------------------------------------------------------- /Java/Miscellaneous/pow.java: -------------------------------------------------------------------------------- 1 | public static double myPow(double x, int n) { 2 | long N = n; 3 | 4 | if(N < 0) { 5 | x = 1 / x; 6 | N = -N; 7 | } 8 | 9 | double answer = 1; 10 | double product = x; 11 | 12 | for(long i = N; i > 0; i /=2) { 13 | if( (i % 2 == 1) ){ 14 | answer = answer * product; 15 | } 16 | product *= product; 17 | } 18 | 19 | return answer; 20 | } 21 | -------------------------------------------------------------------------------- /Java/Sorting/bubbleSort.java: -------------------------------------------------------------------------------- 1 | public static void bubbleSort(int[] array){ 2 | int len = array.length; 3 | for(int i=0;iarray[j+1]){ 6 | int temp = array[j]; 7 | array[j] = array[j+1]; 8 | array[j+1] = temp; 9 | } 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /Rust/Searching/linear_search.rs: -------------------------------------------------------------------------------- 1 | pub fn linear_search(arr: &[T], target: &T) -> Option 2 | where 3 | T: PartialEq, 4 | { 5 | for (index, item) in arr.iter().enumerate() { 6 | if item == target { 7 | return Some(index); 8 | } 9 | } 10 | None 11 | } 12 | 13 | #[cfg(test)] 14 | mod base { 15 | use super::*; 16 | 17 | base_cases!(linear_search); 18 | } -------------------------------------------------------------------------------- /C++/Math/fibonacci.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author : Karthikeyan_01 3 | * Algo : Fibonacci 4 | */ 5 | 6 | 7 | 8 | #include 9 | 10 | int fib(int n){ 11 | if( n <= 1) 12 | return n; 13 | 14 | return fib(n - 1) + fib(n - 2); 15 | } 16 | 17 | 18 | int main(){ 19 | 20 | int n = 10; 21 | std :: cout << fib(n); 22 | 23 | return 0; 24 | } 25 | 26 | 27 | /* 28 | * Input: 10 29 | * Output: 55 30 | */ 31 | -------------------------------------------------------------------------------- /Swift/Sorting/bubble_sort.swift: -------------------------------------------------------------------------------- 1 | func bubbleSort(_ array: [Int]) -> [Int] 2 | { 3 | var arr = array 4 | for _ in 0...arr.count 5 | { 6 | for 7 | value in 1...arr.count - 1 8 | { 9 | if arr[value-1] > arr[value] 10 | { 11 | let largerValue = arr[value-1] 12 | arr[value-1] = arr[value] 13 | arr[value] = largerValue 14 | } 15 | } 16 | } 17 | print("Sorted\(arr)") 18 | return arr 19 | } 20 | -------------------------------------------------------------------------------- /Python/Miscellaneous/is_anagram.py: -------------------------------------------------------------------------------- 1 | def isAnagram(str1, str2): 2 | if len(str1) != len(str2): 3 | return False 4 | frequency = {} 5 | for val in str1: 6 | if val in frequency: 7 | frequency[val] += 1 8 | else: 9 | frequency[val] = 1 10 | for val in str2: 11 | if val not in frequency or frequency[val] == 0: 12 | return False 13 | else: 14 | frequency[val] -= 1 15 | return True 16 | -------------------------------------------------------------------------------- /Java/Unit Tests/LeftRotateByOneTest.java: -------------------------------------------------------------------------------- 1 | package Array; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | public class LeftRotateByOneTest { 8 | 9 | @Test 10 | public void leftRotateByOne() { 11 | int[] array = new int[]{5,6,7,8,9}; 12 | LeftRotateByOne.leftRotateByOne(array); 13 | int[] expected = new int[]{6,7,8,9,5}; 14 | assertArrayEquals(expected,array); 15 | } 16 | } -------------------------------------------------------------------------------- /Go/Miscellaneous/fibonacci_rec.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "os" 6 | "strconv" 7 | ) 8 | 9 | func main() { 10 | arg := os.Args[1] 11 | 12 | if n, err := strconv.Atoi(arg); err != nil { 13 | log.Fatal(err) 14 | } else { 15 | log.Println(fibonacci(n)) 16 | } 17 | 18 | } 19 | 20 | func fibonacci(num int) int { 21 | if num <= 1 { 22 | return num 23 | } 24 | 25 | return fibonacci(num-1) + fibonacci(num-2) 26 | } 27 | -------------------------------------------------------------------------------- /C++/Miscellaneous/tower_of_hanoi.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void tower(char a,char b,char c,int n) 4 | { 5 | if(n==1) 6 | { 7 | printf("%d disk from %c to %c\n",n,a,c); 8 | return; 9 | } 10 | tower(a,c,b,n-1); 11 | printf("%d disk from %c to %c\n",n,a,c); 12 | tower(b,a,c,n-1); 13 | } 14 | 15 | int main() 16 | { 17 | int n; 18 | printf("Enter number of disks:"); 19 | cin>>n; 20 | tower('a','b','c',n); 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /Java/Unit Tests/deleteElementTest.java: -------------------------------------------------------------------------------- 1 | package Array; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | public class deleteElementTest { 8 | 9 | @Test 10 | public void testdeleteElement() { 11 | int[] array = new int[]{5,6,7,8,9}; 12 | DeleteElement.deleteElement(array,array.length,5); 13 | int[] deletedArray = new int[]{6,7,8,9}; 14 | 15 | assertArrayEquals(deletedArray,array); 16 | } 17 | } -------------------------------------------------------------------------------- /Java/Unit Tests/rotateArrayDTimesTest.java: -------------------------------------------------------------------------------- 1 | package Array; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | public class rotateArrayDTimesTest { 8 | 9 | @Test 10 | public void rotateArr() { 11 | int[] array = new int[]{5,6,7,7,8 , 8,8,9}; 12 | RotateArrayDTimes.rotateArr(array,array.length,1); 13 | int[] expected = new int[]{9,8,8,8,7,7,6,5}; 14 | assertArrayEquals(expected,array); 15 | } 16 | } -------------------------------------------------------------------------------- /JavaScript/Sorting/bubble_sort.js: -------------------------------------------------------------------------------- 1 | function bubbleSort(arr){ 2 | var noSwaps; 3 | for(var i = arr.length; i > 0; i--){ 4 | noSwaps = true; 5 | for(var j = 0; j < i - 1; j++){ 6 | if(arr[j] > arr[j+1]){ 7 | var temp = arr[j]; 8 | arr[j] = arr[j+1]; 9 | arr[j+1] = temp; 10 | noSwaps = false; 11 | } 12 | } 13 | if(noSwaps) break; 14 | } 15 | return arr; 16 | } 17 | 18 | module.exports = { 19 | bubbleSort 20 | } -------------------------------------------------------------------------------- /Dart/Sorting/selection_sort.dart: -------------------------------------------------------------------------------- 1 | void selectSorting(List list) { 2 | if (list == null || list.length == 0) return; 3 | int num = list.length; 4 | int i, steps; 5 | for (steps = 0; steps < num; steps++) { 6 | for (i = steps + 1; i < num; i++) { 7 | if(list[steps] > list[i]) { 8 | change(list, steps, i); 9 | } 10 | } 11 | } 12 | } 13 | 14 | void change(List list, int steps, int i) { 15 | int count = list[steps]; 16 | list[steps] = list[i]; 17 | list[i] = count; 18 | } -------------------------------------------------------------------------------- /JavaScript/Sorting/selection_sort.js: -------------------------------------------------------------------------------- 1 | function selectionSort(arr){ 2 | for(var i = 0; i < arr.length; i++){ 3 | var lowest = i; 4 | for(var j = i+1; j < arr.length; j++){ 5 | if(arr[j] < arr[lowest]){ 6 | lowest = j; 7 | } 8 | } 9 | if(i !== lowest){ 10 | //SWAP! 11 | var temp = arr[i]; 12 | arr[i] = arr[lowest]; 13 | arr[lowest] = temp; 14 | } 15 | } 16 | return arr; 17 | } 18 | -------------------------------------------------------------------------------- /Rust/Sorting/selection_sort.rs: -------------------------------------------------------------------------------- 1 | /// Selection sort.pub fn selection_sort(arr: &mut [i32]) { 2 | let len = arr.len(); 3 | // Rust would skip iteration if lower bound >= upper bound. 4 | // Hence, no need to `len - 1`. 5 | for i in 0..len { 6 | let mut temp = i; 7 | for j in (i + 1)..len { 8 | if arr[temp] > arr[j] { 9 | temp = j; 10 | } 11 | } 12 | arr.swap(i, temp); 13 | } 14 | }#[cfg(test)]mod base { 15 | use super::*; 16 | base_cases!(selection_sort); 17 | } -------------------------------------------------------------------------------- /Java/Arrays/RotateArrayDTimes.java: -------------------------------------------------------------------------------- 1 | package Array; 2 | 3 | public class RotateArrayDTimes { 4 | static private void reverse(int[] a, int i, int j) { 5 | while (i < j) { 6 | int temp = a[i]; 7 | a[i] = a[j]; 8 | a[j] = temp; 9 | i++; 10 | j--; 11 | } 12 | } 13 | 14 | static void rotateArr(int arr[], int d, int n) { 15 | reverse(arr, 0, d - 1); 16 | reverse(arr, d, n - 1); 17 | reverse(arr, 0, n - 1); 18 | } 19 | } -------------------------------------------------------------------------------- /Python/Sorting/selection_sort.py: -------------------------------------------------------------------------------- 1 | def selection_sort(A): 2 | for i in range(len(A)): 3 | 4 | # Find the minimum element in remaining 5 | # unsorted array 6 | min_idx = i 7 | for j in range(i+1, len(A)): 8 | if A[min_idx] > A[j]: 9 | min_idx = j 10 | 11 | # Swap the found minimum element with 12 | # the first element 13 | A[i], A[min_idx] = A[min_idx], A[i] 14 | 15 | return A 16 | 17 | 18 | print(selection_sort(input().split())) 19 | -------------------------------------------------------------------------------- /Swift/Searching/binary_search.swift: -------------------------------------------------------------------------------- 1 | func binarySearch(in numbers: [Int], for value: Int) -> Int? { 2 | var left = 0 3 | var right = numbers.count - 1 4 | 5 | while left <= right { 6 | 7 | let middle = Int(floor(Double(left + right) / 2.0)) 8 | 9 | if numbers[middle] < value { 10 | left = middle + 1 11 | } else if numbers[middle] > value { 12 | right = middle - 1 13 | } else { 14 | return middle 15 | } 16 | } 17 | 18 | return nil 19 | } 20 | -------------------------------------------------------------------------------- /Python/Sorting/insertion_sort.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding: utf-8 3 | 4 | # In[5]: 5 | 6 | 7 | n=int(input("Enter length of array")) 8 | arr = [] 9 | for i in range(1,n+1): 10 | element=int(input()) 11 | arr.append(element) 12 | 13 | for i in range(1, len(arr)): 14 | key = arr[i] 15 | j = i-1 16 | while j >=0 and key < arr[j] : 17 | arr[j+1] = arr[j] 18 | j -= 1 19 | arr[j+1] = key 20 | print ("Sorted array is:") 21 | for i in range(len(arr)): 22 | print ("%d" %arr[i]) 23 | 24 | -------------------------------------------------------------------------------- /JavaScript/Searching/binary_search.js: -------------------------------------------------------------------------------- 1 | function binarySearch(arr, elem) { 2 | var start = 0; 3 | var end = arr.length - 1; 4 | var middle = Math.floor((start + end) / 2); 5 | while(arr[middle] !== elem && start <= end) { 6 | if(elem < arr[middle]){ 7 | end = middle - 1; 8 | } else { 9 | start = middle + 1; 10 | } 11 | middle = Math.floor((start + end) / 2); 12 | } 13 | if(arr[middle] === elem){ 14 | return middle; 15 | } 16 | return -1; 17 | } 18 | 19 | -------------------------------------------------------------------------------- /Python/Miscellaneous/gcd.py: -------------------------------------------------------------------------------- 1 | # An easy way to calculate the Greatest Common Divisor using the Euclidean algorithm. 2 | # Author: @Arthurdw 3 | 4 | 5 | def get_gcd(a: int, b: int) -> int: 6 | """ 7 | Returns the Greatest Common Divisor 8 | 9 | Args: 10 | a (int): Your first number. 11 | b (int): Your second number. 12 | """ 13 | if b == 0: 14 | return a 15 | return get_gcd(b, a % b) 16 | 17 | 18 | if __name__ == "__main__": 19 | print(f"The GCD of 20 and 45 is {get_gcd(20, 45)}") 20 | -------------------------------------------------------------------------------- /Dart/Searching/linear_search.dart: -------------------------------------------------------------------------------- 1 | void main(){ 2 | List arr = [10,20,30,40,50,60,70,80]; //here array is hardcoded for functioning but instead of this we can take the array 3 | int x = 50; // as user input as well 4 | int result = linearSearch(arr, x); 5 | print(result); 6 | } 7 | 8 | 9 | // This is the function with the searching algorithm 10 | linearSearch(List array, int x){ 11 | 12 | for(int i = 0; i< array.length; i++){ 13 | 14 | if(array[i] == x){ 15 | return i; 16 | 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /Java/Arrays/insertion.java: -------------------------------------------------------------------------------- 1 | package Array;/* 2 | 3 | I/P : a[] = {5, 10, 20, _, _} 4 | 5 | element = 7 6 | pos = 2 7 | 8 | O/P : a[] = {5, 7, 10, 20, _} 9 | 10 | */ 11 | public class insertion { 12 | 13 | public static int insert(int[] a, int size, int element, int pos, int capacity) { 14 | if (size == capacity) 15 | return size; 16 | int idx = pos - 1; 17 | for (int i = size - 1; i >= idx; i--) { 18 | a[i + 1] = a[i]; 19 | } 20 | a[idx] = element; 21 | return size + 1; 22 | } 23 | } -------------------------------------------------------------------------------- /Java/Arrays/RemoveDuplicatesFromSortedArray.java: -------------------------------------------------------------------------------- 1 | package Array; 2 | 3 | public class RemoveDuplicatesFromSortedArray { 4 | 5 | public static int removeDuplicateFromSortedArray(int[] a, int n) { 6 | int[] temp = new int[n]; 7 | temp[0] = a[0]; 8 | int res = 1; 9 | for (int i = 1; i < n; i++) { 10 | if (temp[res - 1] != a[i]) { 11 | temp[res] = a[i]; 12 | res++; 13 | } 14 | } 15 | for (int i = 0; i < res; i++) { 16 | a[i] = temp[i]; 17 | } 18 | return res; 19 | } 20 | } -------------------------------------------------------------------------------- /C++/Searching/binary_search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int binarySearch(int arr[], int n, int key){ 6 | int end = n-1; 7 | int start = 0; 8 | 9 | while(start <= end){ 10 | int mid = (start + end)/2; 11 | 12 | if(arr[mid]key) { 16 | end = mid - 1; 17 | } 18 | else { 19 | cout<<"Element found "< a[j]) { 15 | temp = a[i]; 16 | a[i] = a[j]; 17 | a[j] = temp; 18 | } 19 | } 20 | } 21 | System.out.println(a[total - 2]); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /Java/Unit Tests/checkIfArrayIsSortedTest.java: -------------------------------------------------------------------------------- 1 | package Array; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | public class checkIfArrayIsSortedTest { 8 | 9 | @Test 10 | public void isSorted() { 11 | int[] array = new int[]{5,6,7,8,9}; 12 | boolean result = checkIfArrayIsSorted.isSorted(array); 13 | assertTrue(result); 14 | } 15 | 16 | @Test 17 | public void isSortedNOtSorted() { 18 | int[] array = new int[]{10,5,6,7,8,9}; 19 | boolean result = checkIfArrayIsSorted.isSorted(array); 20 | assertFalse(result); 21 | } 22 | 23 | 24 | } -------------------------------------------------------------------------------- /C++/Math/binary_exponentiation.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: karthikeyan rathore 3 | * Binary Exponentiation Algorithm recursive approach 4 | */ 5 | 6 | #include 7 | using namespace std; 8 | 9 | long long bin(long long a , long long b){ 10 | if(b == 0) return 1; 11 | 12 | long long res = bin(a , b/2); 13 | if( b % 2) { 14 | return res * res * a; 15 | } 16 | else return res * res; 17 | } 18 | 19 | int main(){ 20 | long long a = 2 , b = 5; 21 | long long ans = bin(2 , 5); 22 | cout << ans; 23 | } 24 | 25 | 26 | /* 27 | * INPUT : a = 2 , b = 5 ....(2 ^ 5) 28 | * OUTPUT : 32 29 | */ 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /C++/Math/pascal_triangle.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int n = 5; //No. of lines in pascal triangle 6 | int arr[n][n]; 7 | for (int i = 0; i < n; i++) 8 | for (int j = 0; j < n; j++) 9 | arr[i][j] = 0; 10 | 11 | for (int line = 0; line < n; line++) 12 | { 13 | for (int i = 0; i <= line; i++) 14 | { 15 | if (line == i || i == 0) 16 | arr[line][i] = 1; 17 | else 18 | arr[line][i] = arr[line - 1][i - 1] + arr[line - 1][i]; 19 | printf("%d ", arr[line][i]); 20 | } 21 | printf("\n"); 22 | } 23 | } -------------------------------------------------------------------------------- /Go/Sorting/bubble_sort.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | // BubbleSort - Sorts a list via bubble algorithm 6 | func BubbleSort(list []int) { 7 | fmt.Println("Initial list:") 8 | fmt.Println(list) 9 | var aux int 10 | 11 | for i := 0; i < len(list); i++ { 12 | for j := 0; j < len(list)-1; j++ { 13 | if list[j] > list[j+1] { 14 | aux = list[j] 15 | list[j] = list[j+1] 16 | list[j+1] = aux 17 | } 18 | } 19 | } 20 | 21 | fmt.Println("Sorted list:") 22 | fmt.Println(list) 23 | 24 | } 25 | 26 | // Run this as go run bubble_sort/bubble_sort.go 27 | func main() { 28 | list := []int{10, 5, 3, 9, 2, 8, 7, 1, 4, 6} 29 | BubbleSort(list) 30 | } 31 | -------------------------------------------------------------------------------- /C++/Searching/linear_search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int linearSearch(int arr[], int n, int key) { 6 | for (int i = 0;i < n;i++) 7 | if (arr[i] == key)return i; 8 | 9 | return -1; 10 | 11 | } 12 | 13 | int main() { 14 | 15 | int n;cin >> n;//size of the array 16 | int arr[100005]; 17 | for (int i = 0;i < n;i++)cin >> arr[i];//taking input inside the array 18 | int key;cin >> key;//the value which is to be find 19 | int ans = linearSearch(arr, n, key); 20 | if (ans == -1) cout << "Element is not present in array" << endl; 21 | else cout << "Element is present at index " << ans << endl; 22 | 23 | return 0; 24 | 25 | } -------------------------------------------------------------------------------- /Swift/Sorting/selection_sort.swift: -------------------------------------------------------------------------------- 1 | func selectionSort(_ arry: [Int]) -> [Int] { 2 | var arr = arry 3 | // Traverse through all array elements 4 | for iterationIndex in 0 ..< arr.count - 1 { 5 | var minIndex = iterationIndex 6 | 7 | // Find the minimum element in remaining 8 | // unsorted array 9 | for compareIndex in iterationIndex + 1 ..< arr.count { 10 | if arr[compareIndex] < arr[minIndex] { 11 | minIndex = compareIndex 12 | } 13 | } 14 | 15 | // Swap the found minimum element with 16 | // the first element 17 | arr.swapAt(iterationIndex, minIndex) 18 | } 19 | return arr 20 | } 21 | 22 | print(selectionSort([5,4,6,3,2,1])) 23 | 24 | -------------------------------------------------------------------------------- /Java/Unit Tests/MoveZerosToEndTest.java: -------------------------------------------------------------------------------- 1 | package Array; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | public class MoveZerosToEndTest { 8 | 9 | @Test 10 | public void moveZeroToEnd() { 11 | int[] array = new int[]{5,0,0,8,9}; 12 | int[] expected = new int[]{5,8,9,0,0}; 13 | MoveZerosToEnd.moveZeroToEnd(array); 14 | assertArrayEquals(expected,array); 15 | } 16 | 17 | @Test 18 | public void moveZeroToEndSecond() { 19 | int[] array = new int[]{5,8,9}; 20 | int[] expected = new int[]{5,8,9}; 21 | MoveZerosToEnd.moveZeroToEnd(array); 22 | assertArrayEquals(expected,array); 23 | } 24 | 25 | 26 | } -------------------------------------------------------------------------------- /JavaScript/Miscellaneous/tower_of_hanoi.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Tower of hanoi problem 3 | * @param n 4 | * @param srcT 5 | * @param desT 6 | * @param bufferT 7 | */ 8 | function tower(n, srcT, desT, bufferT) { 9 | if (n >= 1) { 10 | 11 | // Move a tower of n-1 to the buffer tower, using the destination tower. 12 | tower(n - 1, srcT, bufferT, desT); 13 | 14 | // Move the remaining disk to the destination tower. 15 | console.log('Move disk from Tower ', srcT, ' to Tower ', desT); 16 | 17 | // Move the tower of `n-1` from the `buffer tower` to the `destination tower` using the `source tower`. 18 | tower(n - 1, bufferT, desT, srcT); 19 | } 20 | return; 21 | } 22 | tower(3, "A", "C", "B"); 23 | -------------------------------------------------------------------------------- /Python/Unit Tests/next_president_test.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Python.next_president import winner 3 | 4 | class Test(unittest.TestCase): 5 | 6 | def test_1(self): 7 | president = winner([1]) 8 | self.assertEqual(1, president) 9 | 10 | def test_2(self): 11 | president = winner([1,1]) 12 | self.assertEqual(1, president) 13 | 14 | def test_3(self): 15 | president = winner([1,2,1]) 16 | self.assertEqual(1, president) 17 | 18 | def test_4(self): 19 | president = winner([16,16,16,16,16,16,11,26,5,3]) 20 | self.assertEqual(16, president) 21 | 22 | def test_5(self): 23 | president = winner([1,2,3,1,1,2,5,1,1]) 24 | self.assertEqual(1, president) 25 | -------------------------------------------------------------------------------- /C++/Math/binary_gcd.cpp: -------------------------------------------------------------------------------- 1 | /* BAAHUBALI7781 */ 2 | 3 | /*This Algorithm calculates Greatest Common Divisor of two non-negative intergers in O((logn)^2) worst time complexity*/ 4 | 5 | #include 6 | using namespace std; 7 | 8 | int bin_gcd(int a,int b) 9 | { 10 | if(a==0) 11 | return b; 12 | if(b==0) 13 | return a; 14 | if(a%2==0 && b%2==0) 15 | return 2*bin_gcd(a/2,b/2); 16 | else if(b%2==0) 17 | return bin_gcd(a,b/2); 18 | else if(a%2==0) 19 | return bin_gcd(a/2,b); 20 | else if(a&1 && b&1 && a>=b) 21 | return bin_gcd((a-b)/2,b); 22 | else 23 | return bin_gcd(a,(b-a)/2); 24 | 25 | 26 | } 27 | int main(){ 28 | int a,b; 29 | cin>>a>>b; 30 | cout< int: # pylint: disable=C0103 10 | """Solution with sorting array NLogN""" 11 | votes = V.copy() 12 | votes.sort() 13 | return votes[(len(votes) // 2)] 14 | 15 | def winner(V: List[int]) -> int: # pylint: disable=C0103 16 | """Solution to problem.""" 17 | return sortingTheArray(V) 18 | 19 | if __name__ == "__main__": 20 | president = winner([48,25,48,49,4,44,48,37,48,22,48,48,48,2,48,48,32,48,6,48]) 21 | print(president) 22 | -------------------------------------------------------------------------------- /C++/Miscellaneous/leaders_in_an_array.cpp: -------------------------------------------------------------------------------- 1 | //Given an array A of positive integers. 2 | //Your task is to find the leaders in the array. 3 | //PS: An element of array is leader if it is greater than or equal to all the elements to its right side. 4 | //Also, the rightmost element is always a leader. 5 | // Time Complexity: O(N). 6 | // Auxiliary Space: O(N). 7 | 8 | #include 9 | #include 10 | using namespace std; 11 | 12 | void leader(int arr[], int n) 13 | { 14 | int curr_ldr = arr[n - 1]; 15 | cout<= 0; i--) 17 | { 18 | if(curr_ldr < arr[i]) 19 | { 20 | curr_ldr = arr[i]; 21 | cout< 7 | using namespace std; 8 | int josephus(int n, int k); 9 | int main() 10 | { 11 | int t; 12 | cin>>t; 13 | while(t--) 14 | { 15 | int n,k; 16 | cin>>n>>k; 17 | cout< arr[j+1]: 17 | arr[j], arr[j+1] = arr[j+1], arr[j] 18 | 19 | 20 | # Driver code to test above 21 | arr = [64, 34, 25, 12, 22, 11, 90] 22 | 23 | bubbleSort(arr) 24 | 25 | print("Sorted array is:") 26 | for i in range(len(arr)): 27 | print("%d" % arr[i]), 28 | -------------------------------------------------------------------------------- /Rust/Searching/binary_search.rs: -------------------------------------------------------------------------------- 1 | pub fn binary_search(arr: &[T], target: &T) -> Result 2 | where 3 | T: PartialOrd, 4 | { 5 | let mut size = arr.len(); 6 | if size == 0 { 7 | return Err(0); 8 | } 9 | let mut base = 0_usize; 10 | 11 | while size > 1 { 12 | // mid: [base..size) 13 | let half = size / 2; 14 | let mid = base + half; 15 | if arr[mid] <= *target { 16 | base = mid 17 | } 18 | size -= half; 19 | } 20 | 21 | if arr[base] == *target { 22 | Ok(base) 23 | } else { 24 | // Return the expected position in the array. 25 | Err(base + (arr[base] < *target) as usize) 26 | } 27 | } 28 | 29 | #[cfg(test)] 30 | mod base { 31 | use super::*; 32 | 33 | sorted_no_duplicate_cases!(binary_search); 34 | } -------------------------------------------------------------------------------- /Python/Miscellaneous/stack.py: -------------------------------------------------------------------------------- 1 | """ 2 | Stack is a LIFO type of structure. the `list` data type in Python allows for an easy implementation of a Stack. 3 | """ 4 | class Stack: 5 | 6 | def __init__(self) -> None: 7 | self.stack = [] 8 | 9 | def push(self, value) -> None: 10 | self.stack.append(value) 11 | 12 | def pop(self): 13 | try: 14 | value = self.stack.pop() 15 | except IndexError: 16 | print('Stack Underflow') 17 | else: 18 | return value 19 | 20 | def peek(self) -> list: 21 | return self.stack 22 | 23 | if __name__ == "__main__": 24 | data = Stack() 25 | data.push(10) 26 | data.push(20) 27 | 28 | print(data.peek()) 29 | 30 | print(data.pop()) 31 | print(data.pop()) 32 | print(data.pop()) 33 | 34 | print(data.peek()) 35 | -------------------------------------------------------------------------------- /Python/Unit Tests/duplicate_zeros_test.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Python.duplicate_zeros import duplicate_zeros 3 | 4 | 5 | class Test(unittest.TestCase): 6 | 7 | def test_1(self): 8 | result = duplicate_zeros([0, 1]) 9 | self.assertEqual([0, 0], result) 10 | 11 | def test_2(self): 12 | result = duplicate_zeros([0, 1, 0]) 13 | self.assertEqual([0, 0, 1], result) 14 | 15 | def test_3(self): 16 | result = duplicate_zeros([1, 0, 2, 3, 0, 4, 5, 0]) 17 | self.assertEqual([1, 0, 0, 2, 3, 0, 0, 4], result) 18 | 19 | def test_4(self): 20 | result = duplicate_zeros([0, 0, 0, 0, 1]) 21 | self.assertEqual([0, 0, 0, 0, 0], result) 22 | 23 | def test_5(self): 24 | result = duplicate_zeros([1, 0, 2, 3, 0, 4, 5, 0]) 25 | self.assertEqual([1, 0, 0, 2, 3, 0, 0, 4], result) 26 | -------------------------------------------------------------------------------- /Java/Arrays/TwoPointerAlgo.java: -------------------------------------------------------------------------------- 1 | package Array; 2 | 3 | import java.util.Arrays; 4 | 5 | public class TwoPointerAlgo { 6 | 7 | public static void main(String[] args) { 8 | int arr[] = {0,-1,3,-4,5,-3,4,1}; 9 | 10 | int n = arr.length; 11 | int x=0,k=0,j=n-1; 12 | 13 | Arrays.sort(arr); 14 | 15 | for(int i=0;i x) { 24 | j--; 25 | }else { 26 | System.out.println(arr[i] + " "+ arr[k]+" "+arr[j]); 27 | k++; 28 | j--; 29 | } 30 | } 31 | } 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /Python/Miscellaneous/queue.py: -------------------------------------------------------------------------------- 1 | """ 2 | Queue is a FIFO type of structure. The `list` data type in Python allows for an easy implementation of a Queue. 3 | """ 4 | class Queue: 5 | 6 | def __init__(self) -> None: 7 | self.queue = [] 8 | 9 | def enqueue(self, value) -> None: 10 | self.queue.append(value) 11 | 12 | def dequeue(self): 13 | try: 14 | value = self.queue.pop(0) 15 | except IndexError: 16 | print('Queue Underflow') 17 | else: 18 | return value 19 | 20 | def peek(self) -> list: 21 | return self.queue 22 | 23 | if __name__ == "__main__": 24 | data = Queue() 25 | data.enqueue(10) 26 | data.enqueue(20) 27 | 28 | print(data.peek()) 29 | 30 | print(data.dequeue()) 31 | print(data.dequeue()) 32 | print(data.dequeue()) 33 | 34 | print(data.peek()) 35 | -------------------------------------------------------------------------------- /Java/Sorting/tim_sort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.Random; 3 | 4 | public class TimSort { 5 | 6 | public static void main(String args[]) 7 | { 8 | System.out.println("Sorting of randomly generated numbers using TIM SORT"); 9 | Random random = new Random(); 10 | int N = 20; 11 | int[] sequence = new int[N]; 12 | 13 | for (int i = 0; i < N; i++) 14 | sequence[i] = Math.abs(random.nextInt(100)); 15 | 16 | System.out.println("\nOriginal Sequence: "); 17 | printSequence(sequence); 18 | 19 | System.out.println("\nSorted Sequence: "); 20 | Arrays.sort(sequence); 21 | printSequence(sequence); 22 | } 23 | 24 | private static void printSequence(int[] sortedSequence) 25 | { 26 | for (int aSortedSequence : sortedSequence) System.out.print(aSortedSequence + " "); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Python/Searching/jump_search.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | def JumpSearch (num_list, value): 4 | length_of_list = len(num_list) 5 | jump = int(math.sqrt(length_of_list)) 6 | left, right = 0, 0 7 | while left < length_of_list and num_list[left] <= value: 8 | right = min(length_of_list - 1, left + jump) 9 | if num_list[left] <= value and num_list[right] >= value: 10 | break 11 | left += jump; 12 | if left >= length_of_list or num_list[left] > value: 13 | return -1 14 | right = min(length_of_list - 1, right) 15 | i = left 16 | while i <= right and num_list[i] <= value: 17 | if num_list[i] == value: 18 | return i 19 | i += 1 20 | return -1 21 | 22 | num_list =[1,2,3,4,5,6,7,8,9] 23 | value = 5 24 | 25 | index =JumpSearch(num_list,value) 26 | 27 | 28 | print(f'The value {value} is at index {index+1} of list {num_list}') -------------------------------------------------------------------------------- /JavaScript/Sorting/radix_sort.js: -------------------------------------------------------------------------------- 1 | function getDigit(num, i) { 2 | return Math.floor(Math.abs(num) / Math.pow(10, i)) % 10; 3 | } 4 | 5 | function digitCount(num) { 6 | if (num === 0) return 1; 7 | return Math.floor(Math.log10(Math.abs(num))) + 1; 8 | } 9 | 10 | function mostDigits(nums) { 11 | let maxDigits = 0; 12 | for (let i = 0; i < nums.length; i++) { 13 | maxDigits = Math.max(maxDigits, digitCount(nums[i])); 14 | } 15 | return maxDigits; 16 | } 17 | 18 | function radixSort(nums){ 19 | let maxDigitCount = mostDigits(nums); 20 | for(let k = 0; k < maxDigitCount; k++){ 21 | let digitBuckets = Array.from({length: 10}, () => []); 22 | for(let i = 0; i < nums.length; i++){ 23 | let digit = getDigit(nums[i],k); 24 | digitBuckets[digit].push(nums[i]); 25 | } 26 | nums = [].concat(...digitBuckets); 27 | } 28 | return nums; 29 | } 30 | -------------------------------------------------------------------------------- /Python/Miscellaneous/duplicate_zeros.py: -------------------------------------------------------------------------------- 1 | """ 2 | # PS02: Duplicating zeros 3 | 4 | Given a list of integers `arr`, modify it such that every 0 appears twice 5 | while maintaining the original list size. Modify the list in place. 6 | """ 7 | 8 | def duplicate_zeros(arr): 9 | """Modifies arr in place duplicating all zeros while maitining the original length.""" 10 | zeroes = 0 11 | iteration = 0 12 | size = len(arr) - 1 13 | 14 | while zeroes + iteration < size: 15 | if arr[iteration] == 0: 16 | zeroes += 1 17 | iteration += 1 18 | 19 | while zeroes: 20 | if arr[size - zeroes] == 0 and zeroes + iteration != size: 21 | arr[size] = 0 22 | size -= 1 23 | zeroes -= 1 24 | arr[size] = arr[size - zeroes] 25 | size -= 1 26 | 27 | return arr 28 | 29 | if __name__ == "__main__": 30 | print(duplicate_zeros([1,0,2,3,0,4,5,0])) -------------------------------------------------------------------------------- /Swift/README.md: -------------------------------------------------------------------------------- 1 |

Swift


2 | 3 |

4 | 5 | ## Table of Contents 6 | 7 | - [Searching](#searching) 8 | - [Sorting](#sorting) 9 | - [Unit Tests](#unit-tests) 10 | 11 | 12 | 13 | ## Searching 14 | 15 | - [Binary Search](https://github.com/aniketsharma00411/algorithmsUse/blob/master/Swift/Searching/binary_search.swift) 16 | 17 | 18 | 19 | ## Sorting 20 | 21 | - [Selection Sort](https://github.com/aniketsharma00411/algorithmsUse/blob/master/Swift/Sorting/selection_sort.swift) 22 | 23 | - [Bubble Sort](https://github.com/aniketsharma00411/algorithmsUse/blob/master/Swift/Sorting/bubble_sort.swift) 24 | 25 | 26 | ## Unit Tests 27 | 28 | -- 29 | -------------------------------------------------------------------------------- /Dart/Sorting/insertion_sort.dart: -------------------------------------------------------------------------------- 1 | //Title:Insertion sort 2 | // Author:ShivamVerma 3 | // Email:shivamthegreat.sv@gmail.com 4 | 5 | 6 | void insertionSort(List 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 | /* Driver code */ 27 | int main() 28 | { 29 | List arr = [ 12, 11, 13, 5, 6 ]; 30 | int n = arr.length; 31 | 32 | insertionSort(arr, n); 33 | 34 | for (int i = 0; i < n; i++) 35 | print("${arr[i]} "); 36 | 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /Python/Miscellaneous/majority_element.py: -------------------------------------------------------------------------------- 1 | """ 2 | input: list of elements (comparable by ==) 3 | output: the majority element of the list (if exists) 4 | A majority element is a member which occurs at least n/2 times in the list of length n 5 | """ 6 | 7 | def isMajorityElement(l, e): 8 | cnt = l.count(e) 9 | return cnt > len(l) // 2 10 | 11 | def vote(l): 12 | best = 0 13 | cnt = 1 14 | for i in range(1, len(l)): 15 | if l[i] == l[best]: 16 | cnt += 1 17 | else: 18 | cnt -= 1 19 | if cnt == 0: 20 | best = i 21 | cnt = 1 22 | return l[best] 23 | 24 | l = [2,3,1,4,5,6,3,2,5,6,4,6,3,2,3,4,4,3,2,1,2,2,3] 25 | l = [2,3,2,2,5,6,2,2,5,6,2,6,3,2,2,4,2,3,2,1,2,2,3] 26 | best = vote(l) 27 | if isMajorityElement(l, best): 28 | print("Majority element is", best) 29 | else: 30 | print("There is no majority element") 31 | -------------------------------------------------------------------------------- /C++/Searching/jump_search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int jumpSearch(int arr[], int x, int n) 5 | { 6 | int step = sqrt(n); 7 | int prev = 0; 8 | while (arr[min(step, n)-1] < x) 9 | { 10 | prev = step; 11 | step += sqrt(n); 12 | if (prev >= n) 13 | return -1; 14 | } 15 | 16 | while (arr[prev] < x) 17 | { 18 | prev++; 19 | if (prev == min(step, n)) 20 | return -1; 21 | } 22 | if (arr[prev] == x) 23 | return prev; 24 | 25 | return -1; 26 | } 27 | 28 | int main() 29 | { 30 | int arr[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 31 | 34, 55, 89, 144, 233, 377, 610 }; 32 | int x = 55; 33 | int n = sizeof(arr) / sizeof(arr[0]); 34 | int index = jumpSearch(arr, x, n); 35 | 36 | cout << "\nNumber " << x << " is at index " << index; 37 | return 0; 38 | } -------------------------------------------------------------------------------- /JavaScript/Unit Tests/binary_search_test.js: -------------------------------------------------------------------------------- 1 | const {binarySearch} = require('../Searching/binary_search'); 2 | 3 | test('#1: binary search of element 2 in an empty array should be -1', () => { 4 | expect(binarySearch(Array(), 2)).toEqual(-1); 5 | }); 6 | 7 | test('#2: binary search of element 2 in an sorted odd array should be -1', () => { 8 | expect(binarySearch(Array(1,3,5,7,9))).toEqual(-1); 9 | }); 10 | 11 | test('#3: binary search of element 2 in an sorted even array(2,4,6,8,10) should be 0', () => { 12 | expect(binarySearch(Array(2,4,6,8,10), 2)).toEqual(0); 13 | }); 14 | 15 | test('#4: binary search of element 5 in an sorted even array(4,7,5,9,10,11,12) should be 2', () => { 16 | expect(binarySearch(Array(4,7,5,9,10,11,12), 5)).toEqual(2); 17 | }); 18 | 19 | test('#5: binary search of element 26 in an sorted even array(20,22,24,19,26) should be 4', () => { 20 | expect(binarySearch(Array(20,22,24,19,26), 26)).toEqual(4); 21 | }); 22 | -------------------------------------------------------------------------------- /Java/Sorting/heapSort.java: -------------------------------------------------------------------------------- 1 | public class HeapSort{ 2 | public void sort(int array[]){ 3 | int len=array.length; 4 | for(int i=len/2-1;i>=0;i--) 5 | heapify(array,len,i); 6 | 7 | for(int i=len-1;i>0;i--){ 8 | int temp = array[0]; 9 | array[0] = array[i]; 10 | array[i] = temp; 11 | 12 | heapify(array,i,0); 13 | } 14 | } 15 | 16 | public void heapify(int array[], int len, int i) 17 | { 18 | int largest = i; 19 | int l = 2*i + 1; 20 | int r = 2*i + 2; 21 | 22 | if (l < len && array[l] > array[largest]) 23 | largest = l; 24 | 25 | if (r < len && array[r] > array[largest]) 26 | largest = r; 27 | 28 | if (largest != i) { 29 | int swap = array[i]; 30 | array[i] = array[largest]; 31 | array[largest] = swap; 32 | 33 | heapify(array, len, largest); 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /C++/Dynamic Programming/lcs.cpp: -------------------------------------------------------------------------------- 1 | //LCS - Longest Common Subsequence 2 | //Time Complexity: O(nm) 3 | 4 | #include 5 | #include 6 | #include 7 | #define MAXN 1010 8 | 9 | using namespace std; 10 | 11 | int memo[MAXN][MAXN], s1[MAXN], s2[MAXN]; 12 | 13 | int lcs(int a, int b){ 14 | if(memo[a][b] != - 1) return memo[a][b]; 15 | 16 | if(a == 0 || b == 0) return memo[a][b] = 0; 17 | 18 | if(s1[a] == s2[b]) return memo[a][b] = 1 + lcs(a-1, b-1); 19 | 20 | return memo[a][b] = max(lcs(a-1, b), lcs(a, b-1)); 21 | 22 | } 23 | 24 | int main(){ 25 | cin.tie(NULL); 26 | cout.tie(NULL); 27 | ios::sync_with_stdio(0); 28 | int n, m; 29 | 30 | memset(memo, -1, sizeof(memo)); 31 | cin >> n >> m; 32 | for(int i = 1; i <= n; i++){ 33 | cin >> s1[i]; 34 | } 35 | for(int i = 1; i <= m; i++){ 36 | cin >> s2[i]; 37 | } 38 | 39 | int len_lcs = lcs(n, m); 40 | cout << len_lcs << endl; 41 | return 0; 42 | } -------------------------------------------------------------------------------- /C++/Miscellaneous/stock_buy_and_sell_problem.cpp: -------------------------------------------------------------------------------- 1 | //The cost of stock on each day is given in an array A[] of size N. 2 | //Find all the days on which you buy and sell the stock so that in between those days your profit is maximum. 3 | // Time Complexity : O(N) 4 | 5 | #include 6 | using namespace std; 7 | void StockBuySell(int price[], int n) 8 | { 9 | if (n == 1) 10 | return; 11 | int i = 0; 12 | while (i < n - 1) 13 | { 14 | while ((i < n - 1) && (price[i + 1] <= price[i])) 15 | i++; 16 | if (i == n - 1) 17 | break; 18 | int buy = i++; 19 | while ((i < n) && (price[i] >= price[i - 1])) 20 | i++; 21 | int sell = i - 1; 22 | cout<<"Buy on day: "< 7 | using namespace std; 8 | int kadanesAlgo(int *a, int n){ 9 | int global_sum=a[0], currsum=a[0]; 10 | for(int i=1;iglobal_sum){ 15 | global_sum= currsum; 16 | } 17 | } 18 | return global_sum; 19 | } 20 | int main() { 21 | int n; 22 | cin>>n; 23 | int a[n]; 24 | for(int j=0;j>a[j]; 26 | } 27 | int ans= kadane(a,n); 28 | cout< array = [5, 1, 4, 2, 8]; 3 | // We Can take the array as an input also , rather than declaring it here. 4 | // See the Algorithm in bubleSort Function 5 | List sortedarray = bubbleSort(array); 6 | print(sortedarray); 7 | } 8 | 9 | // Sorting is done here 10 | bubbleSort(List array) { 11 | int lengthOfArray = array.length; 12 | for (int i = 0; i < lengthOfArray - 1; i++) { 13 | print('Index i at pos: ${i}'); 14 | for (int j = 0; j < lengthOfArray - i - 1; j++) { 15 | 16 | print('Loop:${i}'); 17 | print('index i and j at pos: ${i} & ${j}'); 18 | 19 | if (array[j] > array[j + 1]) { 20 | // Swapping using temporary variable temp 21 | 22 | 23 | int temp = array[j]; 24 | array[j] = array[j + 1]; 25 | array[j + 1] = temp; 26 | 27 | print( 28 | 'Element at pos j and j+1 after swap: ${array[j]} & ${array[j + 1]}'); 29 | } 30 | } 31 | } 32 | return (array); 33 | } -------------------------------------------------------------------------------- /Java/Sorting/countingSort: -------------------------------------------------------------------------------- 1 | /** Counting sort **/ 2 | public static void sort(int[] arr) { 3 | int n = arr.length; 4 | if (n == 0) 5 | return; 6 | /** find min and ax values**/ 7 | int max = arr[0], min = arr[0]; 8 | for (int i = 1; i < n; i++) { 9 | if (arr[i] > max) 10 | max = arr[i]; 11 | if (arr[i] < min) 12 | min = arr[i]; 13 | } 14 | int range = max - min + 1; 15 | 16 | int[] count = new int[range]; 17 | /** Count Frequency of each element**/ 18 | for (int i = 0; i < n; i++) 19 | count[arr[i] - min]++; 20 | /** Indice sum **/ 21 | for (int i = 1; i < range; i++) 22 | count[i] += count[i - 1]; 23 | /** Restructure orginal array based based on sum count**/ 24 | int j = 0; 25 | for (int i = 0; i < range; i++) 26 | while (j < count[i]) 27 | arr[j++] = i + min; 28 | } 29 | -------------------------------------------------------------------------------- /JavaScript/Unit Tests/insertion_sort_test.js: -------------------------------------------------------------------------------- 1 | const {insertionSort} = require("../Sorting/insertion_sort.js"); 2 | test('#1: insertion sort of array(5,4,3,2,1) should be array(1,2,3,4,5)', () => { 3 | expect(insertionSort(Array(5,4,3,2,1))).toEqual(Array(1,2,3,4,5)); 4 | }); 5 | 6 | test('#2: insertion sort of array(10,6,200,1,50) should be array(1,6,10,50,200)', () => { 7 | expect(insertionSort(Array(10,6,200,1,50))).toEqual(Array(1,6,10,50,200)); 8 | }); 9 | 10 | test('#3: insertion sort of array(20,22,24,19,26) should be array(19,20,22,24,26)', () => { 11 | expect(insertionSort(Array(20,22,24,19,26))).toEqual(Array(19,20,22,24,26)); 12 | }); 13 | 14 | test('#4: insertion sort of array(1,2,3,4,5) should be array(1,2,3,4,5)', () => { 15 | expect(insertionSort(Array(1,2,3,4,5))).toEqual(Array(1,2,3,4,5)); 16 | }); 17 | 18 | test('#5: insertion sort of array(50,35,60,44,55) should be array(35,44,50,55,60)', () => { 19 | expect(insertionSort(Array(50,35,60,44,55))).toEqual(Array(35,44,50,55,60)); 20 | }); 21 | 22 | -------------------------------------------------------------------------------- /Go/Sorting/selection_sort.go: -------------------------------------------------------------------------------- 1 | // Selection Sort in Golang 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | "math/rand" 7 | "time" 8 | ) 9 | 10 | func main() { 11 | 12 | slice := generateSlice(20) 13 | fmt.Println("\n--- Unsorted --- \n\n", slice) 14 | selectionsort(slice) 15 | fmt.Println("\n--- Sorted ---\n\n", slice, "\n") 16 | } 17 | 18 | // Generates a slice of size, size filled with random numbers 19 | func generateSlice(size int) []int { 20 | 21 | slice := make([]int, size, size) 22 | rand.Seed(time.Now().UnixNano()) 23 | for i := 0; i < size; i++ { 24 | slice[i] = rand.Intn(999) - rand.Intn(999) 25 | } 26 | return slice 27 | } 28 | 29 | func selectionsort(items []int) { 30 | var n = len(items) 31 | for i := 0; i < n; i++ { 32 | var minIdx = i 33 | for j := i; j < n; j++ { 34 | if items[j] < items[minIdx] { 35 | minIdx = j 36 | } 37 | } 38 | items[i], items[minIdx] = items[minIdx], items[i] 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /C++/Searching/recursive_linear_search.cpp: -------------------------------------------------------------------------------- 1 | // Recursive C++ program 2 | // to search x in array 3 | #include 4 | 5 | using namespace std; 6 | 7 | // Recursive function to 8 | // search x in arr[l..r] 9 | int recSearch(int arr[], int l, 10 | int r, int x) 11 | { 12 | if (r < l) 13 | return -1; 14 | if (arr[l] == x) 15 | return l; 16 | if (arr[r] == x) 17 | return r; 18 | return recSearch(arr, l + 1, 19 | r - 1, x); 20 | } 21 | 22 | // Driver Code 23 | int main() 24 | { 25 | cout<<"Enter size of array \n"; 26 | int n; 27 | cin>>n; 28 | int arr[n]; 29 | cout<<"Enter array elements"; 30 | for(int i=0;i>arr[i]; 33 | } 34 | int x; 35 | cout<<"Enter the Element you want to search\n"; 36 | cin>>x; 37 | 38 | int index = recSearch(arr, 0, n - 1, x); 39 | if (index != -1) 40 | cout << "Element " << x 41 | << " is present at index " 42 | << index; 43 | else 44 | cout << "Element" << x 45 | << " is not present" ; 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /C++/Sorting/insertion_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* Function to sort an array using insertion sort*/ 5 | void insertionSort(int arr[], int n) 6 | { 7 | int i, key, j; 8 | for (i = 1; i < n; i++) 9 | { 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 | { 18 | arr[j + 1] = arr[j]; 19 | j = j - 1; 20 | } 21 | arr[j + 1] = key; 22 | } 23 | } 24 | 25 | // A utility function to print an array of size n 26 | void printArray(int arr[], int n) 27 | { 28 | int i; 29 | for (i = 0; i < n; i++) 30 | cout << arr[i] << " "; 31 | cout << endl; 32 | } 33 | 34 | /* Driver code */ 35 | int main() 36 | { 37 | int n; 38 | cin >> n; 39 | int arr[n]; 40 | for (int i = 0; i < n; i++) 41 | { 42 | cin >> arr[i]; 43 | } 44 | 45 | insertionSort(arr, n); 46 | printArray(arr, n); 47 | 48 | return 0; 49 | } -------------------------------------------------------------------------------- /Python/Miscellaneous/prime_upto_n.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python program to print all primes smaller than or equal to n using Sieve of Eratosthenes 3 | """ 4 | 5 | 6 | def SieveOfEratosthenes(n): 7 | # Create a boolean array "prime[0..n]" and initialize 8 | # all entries it as true. A value in prime[i] will 9 | # finally be false if i is Not a prime, else true. 10 | prime = [True for i in range(n+1)] 11 | p = 2 12 | while (p * p <= n): 13 | 14 | # If prime[p] is not changed, then it is a prime 15 | if (prime[p] == True): 16 | 17 | # Update all multiples of p 18 | for i in range(p * p, n+1, p): 19 | prime[i] = False 20 | p += 1 21 | 22 | # Print all prime numbers 23 | for p in range(2, n+1): 24 | if prime[p]: 25 | print(p) 26 | 27 | 28 | # driver program 29 | if __name__ == '__main__': 30 | n = int(input("Enter the value of n ")) 31 | print("Following are the prime numbers smaller") 32 | print("than or equal to ", n) 33 | SieveOfEratosthenes(n) 34 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contribution Guidelines 2 | 3 | Welcome to [algorithmsUse](https://github.com/aniketsharma00411/algorithmsUse)! Before sending your pull requests, make sure you read the complete guideleines. If you still have any doubts, feel free to create an issue or [contact us](https://github.com/aniketsharma00411). 4 | 5 | ## Contributing 6 | 7 | **Add any Algorithm** which is not already present in its respective Programming Language directory. If you don't find your favorite programming language's directory, feel free to create it. 8 | 9 | **Update** the **main README** and the **respective language's README** with your program's name. These README are used for reference to check which algorithms are present. 10 | 11 | **Improving README and/or comments** are also appreciated. 12 | 13 | **Proper Tests** for already present algorithms are also highly welcome. 14 | 15 | ## Coding Style 16 | 17 | - Make sure you follow the **standard coding style** of the language you are using. 18 | 19 | - Stricly use snake_case (underscore_separated) in your file_name. 20 | -------------------------------------------------------------------------------- /Python/Searching/interpolation.py: -------------------------------------------------------------------------------- 1 | #Interpolation search algorithm 2 | def interpolationSearch(A, x): 3 | 4 | # search space is A[left..right] 5 | (left, right) = (0, len(A) - 1) 6 | 7 | while A[right] != A[left] and A[left] <= x <= A[right]: 8 | 9 | # estimate mid 10 | mid = left + (x - A[left]) * (right - left) // (A[right] - A[left]) 11 | 12 | # key value is found 13 | if x == A[mid]: 14 | return mid 15 | 16 | # discard all elements in the right search space 17 | # including the mid element 18 | elif x < A[mid]: 19 | right = mid - 1 20 | 21 | # discard all elements in the left search space 22 | # including the mid element 23 | else: 24 | left = mid + 1 25 | 26 | # if key is found 27 | if x == A[left]: 28 | return left 29 | 30 | # x doesn't exist in the list 31 | return -1 32 | 33 | 34 | if __name__ == '__main__': 35 | 36 | A = [2, 5, 6, 8, 9, 10] 37 | key = 5 38 | 39 | index = interpolationSearch(A, key) 40 | 41 | if index != -1: 42 | print("Element found at index", index) 43 | else: 44 | print("Element found not in the list") -------------------------------------------------------------------------------- /Dart/Searching/binary_search.dart: -------------------------------------------------------------------------------- 1 | 2 | // main function 3 | void main() { 4 | List arr = [0, 1, 3, 4, 5, 8, 9, 22]; 5 | int userValue = 3; 6 | int min = 0; 7 | int max = arr.length - 1; 8 | //Here a hard-coded array is used instead of this we can even take array as an input and search an inputted element 9 | binarySearchAlgo(arr, userValue, min, max); 10 | 11 | } 12 | 13 | binarySearchAlgo(List arr, int userValue, int min, int max) { 14 | if (max >= min) { 15 | 16 | // If the element is present at the middle 17 | int mid = ((max + min) / 2).floor(); 18 | if (userValue == arr[mid]) { 19 | print('your item is at index: ${mid}'); 20 | } 21 | 22 | // If element is bigger than mid, then 23 | // it can only be present in right subarray 24 | 25 | else if (userValue > arr[mid]) { 26 | binarySearchAlgo(arr, userValue, mid + 1, max); 27 | } 28 | // Else the element can only be present 29 | // in right subarray 30 | 31 | else { 32 | binarySearchAlgo(arr, userValue, min, mid - 1); 33 | } 34 | } 35 | return null; 36 | } -------------------------------------------------------------------------------- /Java/Searching/ExponentialSearch.java: -------------------------------------------------------------------------------- 1 | // Java program to find an element x in a 2 | // sorted array using Exponential search. 3 | 4 | import java.util.Arrays; 5 | 6 | class exponentialSearch 7 | { 8 | // Returns position of first occurrence of 9 | // x in array 10 | static int exponentialSearch(int arr[], 11 | int n, int x) 12 | { 13 | // If x is present at firt location itself 14 | if (arr[0] == x) 15 | return 0; 16 | 17 | // Find range for binary search by 18 | // repeated doubling 19 | int i = 1; 20 | while (i < n && arr[i] <= x) 21 | i = i*2; 22 | 23 | // Call binary search for the found range. 24 | return Arrays.binarySearch(arr, i/2, 25 | Math.min(i, n), x); 26 | } 27 | 28 | // Driver code 29 | public static void main(String args[]) 30 | { 31 | int arr[] = {2, 3, 4, 10, 40}; 32 | int x = 10; 33 | int result = exponentialSearch(arr, arr.length, x); 34 | 35 | System.out.println((result < 0) ? 36 | "Element is not present in array" : 37 | "Element is present at index " + 38 | result); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Java/Sorting/selection_sort.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Scanner; 3 | 4 | public class selectSort { 5 | public static void main(String[] args) { 6 | Scanner sc = new Scanner(System.in); 7 | int len = sc.nextInt(); 8 | int [] arr = new int[len]; 9 | 10 | for(int i=0;i 2 | #include 3 | 4 | using namespace std; 5 | 6 | typedef struct node{ 7 | node* right; 8 | node* left; 9 | int val; 10 | }node; 11 | 12 | //inorder traversal left -> root -> right 13 | //recursive 14 | 15 | node* createNode(int data){ 16 | node* newNode = new node(); 17 | newNode -> right = NULL; 18 | newNode -> left = NULL; 19 | newNode -> val = data; 20 | return newNode; 21 | } 22 | 23 | void inorderTraversal(node* root){ 24 | if(root == NULL) 25 | return; 26 | 27 | inorderTraversal(root -> left); 28 | cout< val<<" "; 29 | inorderTraversal(root -> right); 30 | } 31 | 32 | int main(){ 33 | 34 | node* root = NULL; 35 | root = createNode(5); 36 | root -> left = createNode(3); 37 | root -> left -> left = createNode(1); 38 | root -> left -> right = createNode(4); 39 | 40 | root -> right = createNode(7); 41 | root -> right -> right = createNode(9); 42 | root -> right -> left = createNode(6); 43 | 44 | inorderTraversal(root); 45 | 46 | return 0; 47 | } -------------------------------------------------------------------------------- /Rust/Sorting/insertion_sort.rs: -------------------------------------------------------------------------------- 1 | /// Insertion sort. 2 | 3 | pub fn insertion_sort(arr: &mut [i32]) { 4 | for i in 1..arr.len() { 5 | let mut j = i; 6 | while j > 0 && arr[j - 1] > arr[j] { 7 | arr.swap(j - 1, j); 8 | j -= 1; 9 | } 10 | } 11 | } 12 | 13 | /// Binary insertion sort. 14 | 15 | /// Binary insertion sort is a insertion sort variant that utilizes binary 16 | 17 | /// search to reduce comparisons in a normal insertion sort. 18 | 19 | pub fn binary_insertion_sort(arr: &mut [i32]) { 20 | for i in 1..arr.len() { 21 | let val = arr[i]; 22 | let mut j = i; 23 | let pos = arr[..i].binary_search(&val).unwrap_or_else(|pos| pos); 24 | // Swap all elements until specific position. 25 | while j > pos { 26 | arr.swap(j - 1, j); 27 | j -= 1; 28 | } 29 | } 30 | } 31 | 32 | #[cfg(test)] 33 | 34 | mod base { 35 | use super::*; 36 | base_cases!(insertion_sort); 37 | } 38 | 39 | #[cfg(test)] 40 | 41 | mod binary_insertion { 42 | use super::*; 43 | base_cases!(binary_insertion_sort); 44 | } -------------------------------------------------------------------------------- /C++/Tree Alogrithms/preorder_traversal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | typedef struct node{ 7 | node* right; 8 | node* left; 9 | int val; 10 | }node; 11 | 12 | //inorder traversal root -> left -> right 13 | //recursive 14 | 15 | node* createNode(int data){ 16 | node* newNode = new node(); 17 | newNode -> right = NULL; 18 | newNode -> left = NULL; 19 | newNode -> val = data; 20 | return newNode; 21 | } 22 | 23 | void preorderTraversal(node* root){ 24 | if(root == NULL) 25 | return; 26 | 27 | cout< val<<" "; 28 | preorderTraversal(root -> left); 29 | preorderTraversal(root -> right); 30 | } 31 | 32 | int main(){ 33 | 34 | node* root = NULL; 35 | root = createNode(5); 36 | root -> left = createNode(3); 37 | root -> left -> left = createNode(1); 38 | root -> left -> right = createNode(4); 39 | 40 | root -> right = createNode(7); 41 | root -> right -> right = createNode(9); 42 | root -> right -> left = createNode(6); 43 | 44 | preorderTraversal(root); 45 | 46 | return 0; 47 | } -------------------------------------------------------------------------------- /C++/Sorting/selection_sort.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for implementation of selection sort 2 | #include 3 | using namespace std; 4 | 5 | void swap(int *xp, int *yp) 6 | { 7 | int temp = *xp; 8 | *xp = *yp; 9 | *yp = temp; 10 | } 11 | 12 | void selectionSort(int arr[], int n) 13 | { 14 | int i, j, min_idx; 15 | 16 | // One by one move boundary of unsorted subarray 17 | for (i = 0; i < n-1; i++) 18 | { 19 | // Find the minimum element in unsorted array 20 | min_idx = i; 21 | for (j = i+1; j < n; j++) 22 | if (arr[j] < arr[min_idx]) 23 | min_idx = j; 24 | 25 | // Swap the found minimum element with the first element 26 | swap(&arr[min_idx], &arr[i]); 27 | } 28 | } 29 | 30 | /* Function to print an array */ 31 | void printArray(int arr[], int size) 32 | { 33 | int i; 34 | for (i = 0; i < size; i++) 35 | cout << arr[i] << " "; 36 | cout << endl; 37 | } 38 | 39 | // Driver program to test above functions 40 | int main() 41 | { 42 | int arr[] = {64, 25, 12, 22, 11}; 43 | int n = sizeof(arr)/sizeof(arr[0]); 44 | selectionSort(arr, n); 45 | cout << "Sorted array: \n"; 46 | printArray(arr, n); 47 | return 0; 48 | } -------------------------------------------------------------------------------- /C++/Tree Alogrithms/postorder_traversal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | typedef struct node{ 7 | node* right; 8 | node* left; 9 | int val; 10 | }node; 11 | 12 | //inorder traversal left -> right -> root 13 | //recursive 14 | 15 | node* createNode(int data){ 16 | node* newNode = new node(); 17 | newNode -> right = NULL; 18 | newNode -> left = NULL; 19 | newNode -> val = data; 20 | return newNode; 21 | } 22 | 23 | void postorderTraversal(node* root){ 24 | if(root == NULL) 25 | return; 26 | 27 | postorderTraversal(root -> left); 28 | postorderTraversal(root -> right); 29 | cout< val<<" "; 30 | } 31 | 32 | int main(){ 33 | 34 | node* root = NULL; 35 | root = createNode(5); 36 | root -> left = createNode(3); 37 | root -> left -> left = createNode(1); 38 | root -> left -> right = createNode(4); 39 | 40 | root -> right = createNode(7); 41 | root -> right -> right = createNode(9); 42 | root -> right -> left = createNode(6); 43 | 44 | postorderTraversal(root); 45 | 46 | return 0; 47 | } -------------------------------------------------------------------------------- /C++/Sorting/bucket_sort.cpp: -------------------------------------------------------------------------------- 1 | // Bucket sort in C++ programming 2 | 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | // Function to sort arr[] of size n using bucket sort 9 | void bucketSort(float arr[], int n) 10 | { 11 | // 1) Create n empty buckets 12 | vector b[n]; 13 | 14 | // 2) Put array elements in different buckets 15 | for (int i = 0; i < n; i++) { 16 | int bi = n * arr[i]; // Index in bucket 17 | b[bi].push_back(arr[i]); 18 | } 19 | 20 | // 3) Sort individual buckets 21 | for (int i = 0; i < n; i++) 22 | sort(b[i].begin(), b[i].end()); 23 | 24 | // 4) Concatenate all buckets into arr[] 25 | int index = 0; 26 | for (int i = 0; i < n; i++) 27 | for (int j = 0; j < b[i].size(); j++) 28 | arr[index++] = b[i][j]; 29 | } 30 | 31 | /* Driver program to test above function */ 32 | int main() 33 | { 34 | float arr[] = { 0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434 }; 35 | int n = sizeof(arr) / sizeof(arr[0]); 36 | bucketSort(arr, n); 37 | 38 | cout << "Sorted array is \n"; 39 | for (int i = 0; i < n; i++) 40 | cout << arr[i] << " "; 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /JavaScript/Sorting/merge_sort.js: -------------------------------------------------------------------------------- 1 | function mergeSort(list) { 2 | // Getting the half part of the list 3 | let half = list.length / 2; 4 | if (list.length < 2) { 5 | return list; 6 | } 7 | 8 | // Getting the left part of the list, by default the other part will be the right 9 | const left = list.splice(0, half); 10 | 11 | // Call merge function and mergeSort recursively to solve the sorting 12 | return merge(mergeSort(left), mergeSort(list)); 13 | } 14 | 15 | function merge(left, right) { 16 | 17 | let list = []; 18 | 19 | // Main loop through the left and right parts to merge them sorted 20 | while (left.length && right.length) { 21 | // Execute the comparison statement 22 | if (left[0] < right [0]) { 23 | list.push(left.shift()); 24 | } else { 25 | list.push(right.shift()); 26 | } 27 | } 28 | 29 | // Return the list sorted and merged with the rest operator. 30 | return [...list, ...left, ...right]; 31 | } 32 | 33 | 34 | const array = [4, 7, 2, 3, 6, 8, 0, 3, 2, 7, 56, 23, 12, 43]; 35 | 36 | console.log(mergeSort(array)); 37 | -------------------------------------------------------------------------------- /C++/Miscellaneous/trapping_rain_water.cpp: -------------------------------------------------------------------------------- 1 | //Given an array arr[] of N non-negative integers representing the height of blocks at index i as Ai where the width of each block is 1. 2 | //Compute how much water can be trapped in between blocks after raining. 3 | //The structure is like below: 4 | // | | 5 | // |_| 6 | //We can trap 2 units of water in the middle gap. 7 | 8 | //Time Complexity: O(N). 9 | 10 | #include 11 | #include 12 | using namespace std; 13 | 14 | int getWater(int arr[], int n) 15 | { 16 | int res = 0; 17 | for(int i = 1; i < n - 1; i++) 18 | { 19 | int res = 0; 20 | int lMax[n]; 21 | int rMax[n]; 22 | lMax[0] = arr[0]; 23 | 24 | for(int i = 1; i < n; i++) 25 | lMax[i] = max(arr[i], lMax[i - 1]); 26 | rMax[n - 1] = arr[n - 1]; 27 | 28 | for(int i = n - 2; i >= 0; i--) 29 | rMax[i] = max(arr[i], rMax[i + 1]); 30 | 31 | for(int i = 1; i < n - 1; i++) 32 | res = res + (min(lMax[i], rMax[i]) - arr[i]); 33 | return res; 34 | } 35 | return res; 36 | } 37 | int main() 38 | { 39 | 40 | int arr[] = {5, 0, 6, 2, 3}, n = 5; 41 | cout<= low: 8 | 9 | mid = (high + low) // 2 10 | 11 | # If element is present at the middle itself 12 | if arr[mid] == x: 13 | return mid 14 | 15 | # If element is smaller than mid, then it can only 16 | # be present in left subarray 17 | elif arr[mid] > x: 18 | return binary_search(arr, low, mid - 1, x) 19 | 20 | # Else the element can only be present in right subarray 21 | else: 22 | return binary_search(arr, mid + 1, high, x) 23 | 24 | else: 25 | # Element is not present in the array 26 | return -1 27 | 28 | # Test array 29 | arr = [ 2, 3, 4, 10, 40 ] 30 | x = 10 31 | 32 | # Function call 33 | result = binary_search(arr, 0, len(arr)-1, x) 34 | 35 | if result != -1: 36 | print("Element is present at index", str(result)) 37 | else: 38 | print("Element is not present in array") -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Aniket Sharma 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Python/Tree Algorithms/level_order_traversal.py: -------------------------------------------------------------------------------- 1 | # Python program for implementation of Level Order Traversal 2 | 3 | # Structure of a node 4 | class Node: 5 | def __init__(self ,key): 6 | self.data = key 7 | self.left = None 8 | self.right = None 9 | 10 | # print level order traversal 11 | def printLevelOrder(root): 12 | if root is None: 13 | return 14 | # create an empty node_queue for Level order Traversal 15 | node_queue = [] 16 | node_queue.append(root) 17 | 18 | #print Front of the queue and pop it from the queue 19 | while(len(node_queue) > 0): 20 | print (node_queue[0].data) 21 | node = node_queue.pop(0) 22 | 23 | # Enqueue left child 24 | if node.left is not None: 25 | node_queue.append(node.left) 26 | 27 | # Enqueue right child 28 | if node.right is not None: 29 | node_queue.append(node.right) 30 | 31 | root = Node(1) 32 | root.left = Node(2) 33 | root.right = Node(3) 34 | root.left.left = Node(4) 35 | root.left.right = Node(5) 36 | 37 | print ("Binary tree's level order traversal is :") 38 | printLevelOrder(root) 39 | -------------------------------------------------------------------------------- /Python/Sorting/quick_sort.py: -------------------------------------------------------------------------------- 1 | 2 | ''' 3 | Copyright [2020] [Anoop Bhat] 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | Unless required by applicable law or agreed to in writing, software 9 | distributed under the License is distributed on an "AS IS" BASIS, 10 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | See the License for the specific language governing permissions and 12 | limitations under the License. 13 | ''' 14 | 15 | def quick_sort(sequence): 16 | 17 | lenght = len(sequence) 18 | if lenght <= 1: 19 | return sequence 20 | else: 21 | pivot = sequence.pop() 22 | 23 | items_lower = [] 24 | items_larger = [] 25 | 26 | for item in sequence: 27 | if item < pivot: 28 | items_lower.append(item) 29 | else: 30 | items_larger.append(item) 31 | 32 | 33 | return quick_sort(items_lower) + [pivot] + quick_sort(items_larger) 34 | 35 | print(quick_sort([5,4,2,1,7,9,3,1])) 36 | 37 | 38 | -------------------------------------------------------------------------------- /Python/Miscellaneous/fibonacci_rec.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | from sys import argv #going to be using this for light argparsing 3 | ''' 4 | The fibonacci sequence is a sequence that starts at 0, then 1. 5 | The next number is always the sum of the previous 2, for example: 6 | 7 | 0, 1, 1, 2, 3, 5, 8, 13 and so on... 8 | 9 | This script will let the user get the nth term of this sequence. 10 | ''' 11 | 12 | def fib(number): 13 | if number == 1: 14 | return 0 15 | elif number == 2: 16 | return 1 17 | else: 18 | return fib(number-1) + fib(number-2) 19 | 20 | ''' 21 | Explanation: 22 | 23 | The fib function works using recursion. Recursion put simply, is when a function calls() itself. 24 | 25 | If the number passed to the function is greater than 2, it will return fib(number-1) + fib(number-2) 26 | ''' 27 | 28 | if len(argv) < 2 or int(argv[-1]) == 0: 29 | #argv is a variable that just holds all the arguments passed to the system. 30 | #we want at least one extra so we only print this message if argv is less than 2 :) 31 | print("Usage: ./Fibonacci.py ") 32 | exit() 33 | else: 34 | n = fib(int(argv[1])) 35 | print(n) -------------------------------------------------------------------------------- /Rust/Sorting/bubble_sort.rs: -------------------------------------------------------------------------------- 1 | /// Bubble sort 2 | 3 | pub fn bubble_sort(arr: &mut [i32]) { 4 | let mut swapped = true; 5 | while swapped { 6 | // No swap means array is sorted. 7 | swapped = false; 8 | for i in 1..arr.len() { 9 | if arr[i - 1] > arr[i] { 10 | arr.swap(i - 1, i); 11 | swapped = true 12 | } 13 | } 14 | } 15 | } 16 | 17 | /// Optimized bubble sort 18 | 19 | /// Memorize last swapped index to avoid unnecessary check. 20 | 21 | pub fn bubble_sort_optimized(arr: &mut [i32]) { 22 | let mut new_len: usize; 23 | let mut len = arr.len(); 24 | loop { 25 | new_len = 0; 26 | for i in 1..len { 27 | if arr[i - 1] > arr[i] { 28 | arr.swap(i - 1, i); 29 | new_len = i; 30 | } 31 | } 32 | if new_len == 0 { 33 | break; 34 | } 35 | len = new_len; 36 | } 37 | } 38 | 39 | #[cfg(test)] 40 | mod base { 41 | use super::*; 42 | base_cases!(bubble_sort); 43 | } 44 | 45 | #[cfg(test)] 46 | mod optimized { 47 | use super::*; 48 | base_cases!(bubble_sort_optimized); 49 | } -------------------------------------------------------------------------------- /C++/Miscellaneous/greedy_money_change_recursive.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int indian_currency[] = {1, 2, 5, 10, 20, 50, 100, 200, 500, 2000}; 7 | int n = sizeof(indian_currency) / sizeof(int); 8 | 9 | bool compare(int a, int b) 10 | { 11 | return a <= b; 12 | } 13 | 14 | // Binary Search + Recursion + STL 15 | void count_notes(int money, vector &v) 16 | { 17 | 18 | if (money == 0) 19 | { 20 | return; 21 | } 22 | 23 | int idx = lower_bound(indian_currency, indian_currency + n, money, compare) - indian_currency - 1; 24 | int m = indian_currency[idx]; 25 | v.push_back(m); 26 | 27 | //Recursive Call 28 | count_notes(money - m, v); 29 | } 30 | int main() 31 | { 32 | //Indian Coin Change 33 | int money; 34 | cin >> money; 35 | 36 | // Money Change 37 | vector v; 38 | 39 | //Make a Recursive Call 40 | count_notes(money, v); 41 | 42 | // For Each Loop 43 | for (int note : v) 44 | { 45 | cout << note << " + "; 46 | } 47 | cout << "0" << endl; 48 | 49 | cout << v.size() << " notes needed!" << endl; 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /C++/Sorting/quick_sort.cpp: -------------------------------------------------------------------------------- 1 | /* C implementation QuickSort */ 2 | #include 3 | 4 | void swap(int *a, int *b) 5 | { 6 | int t = *a; 7 | *a = *b; 8 | *b = t; 9 | } 10 | int partition(int arr[], int low, int high) 11 | { 12 | int pivot = arr[high]; 13 | int i = (low - 1); 14 | 15 | for (int j = low; j <= high - 1; j++) 16 | { 17 | if (arr[j] < pivot) 18 | { 19 | i++; 20 | swap(&arr[i], &arr[j]); 21 | } 22 | } 23 | swap(&arr[i + 1], &arr[high]); 24 | return (i + 1); 25 | } 26 | void quickSort(int arr[], int low, int high) 27 | { 28 | if (low < high) 29 | { 30 | int pi = partition(arr, low, high); 31 | quickSort(arr, low, pi - 1); 32 | quickSort(arr, pi + 1, high); 33 | } 34 | } 35 | 36 | void printArray(int arr[], int size) 37 | { 38 | int i; 39 | for (i = 0; i < size; i++) 40 | printf("%d ", arr[i]); 41 | printf("\n"); 42 | } 43 | 44 | int main() 45 | { 46 | int arr[] = {10, 7, 8, 9, 1, 5}; 47 | int n = sizeof(arr) / sizeof(arr[0]); 48 | quickSort(arr, 0, n - 1); 49 | printf("Sorted array: \n"); 50 | printArray(arr, n); 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /C++/Tree Alogrithms/balanced_binary_tree_check.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | /* 6 | Worst case time complexity: O(n) 7 | Auxiliary space complexity: O(h); where h = height of binary tree 8 | */ 9 | 10 | 11 | struct Node { 12 | int data; 13 | Node *left; 14 | Node *right; 15 | 16 | Node(int value) { 17 | data = value; 18 | left = NULL; 19 | right = NULL; 20 | } 21 | }; 22 | 23 | 24 | int isBalanced(Node *root) { 25 | if (root == NULL) return 0; 26 | 27 | int leftHeight = isBalanced(root->left); 28 | if (leftHeight == -1) return -1; 29 | 30 | int rightHeight = isBalanced(root->right); 31 | if (rightHeight == -1) return -1; 32 | 33 | if (abs(leftHeight - rightHeight) > 1) return -1; 34 | else return 1 + max(leftHeight, rightHeight); 35 | } 36 | 37 | 38 | int main() { 39 | Node *root = new Node(10); 40 | // left 41 | root->left = new Node(20); 42 | root->left->left = new Node(30); 43 | root->left->right = new Node(40); 44 | // right 45 | root->right = new Node(50); 46 | root->right->right = new Node(60); 47 | 48 | cout << "Entered tree is balanced? " 49 | << (isBalanced(root) != -1 ? "true" : "false") 50 | << "\n"; 51 | 52 | return 0; 53 | } -------------------------------------------------------------------------------- /Java/Arrays/array_sum.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.math.*; 3 | import java.text.*; 4 | import java.util.*; 5 | import java.util.regex.*; 6 | 7 | public class Solution { 8 | 9 | 10 | static int simpleArraySum(int[] ar) { 11 | int sum=0; 12 | for(int i=0;i 9 | 10 | using namespace std; 11 | const int N = 1000; 12 | int weight[N]; 13 | int value[N]; 14 | int dp[N][N]; 15 | int n, m; 16 | 17 | int knapsack(int i = 0, int c = m) { 18 | 19 | if (i == n || c == 0) 20 | return 0; 21 | if (~dp[i][c]) 22 | return dp[i][c]; 23 | int choice1 = 0, choice2 = 0; 24 | 25 | if (weight[i] <= c) { 26 | choice1 = value[i] + knapsack(i + 1, c - weight[i]); 27 | } 28 | choice2 = knapsack(i + 1, c); 29 | return dp[i][c] = max(choice1, choice2); 30 | 31 | } 32 | 33 | int main() { 34 | 35 | 36 | 37 | ios::sync_with_stdio(false); 38 | cin.tie(0); 39 | cout.tie(0); 40 | memset(dp,-1,sizeof dp); 41 | cin >> n >> m; 42 | for (int i = 0; i < n; ++i) 43 | cin >> value[i]; 44 | for (int i = 0; i < n; ++i) 45 | cin >> weight[i]; 46 | 47 | cout << knapsack() << endl; 48 | 49 | 50 | } 51 | -------------------------------------------------------------------------------- /C++/Math/factorial_20.cpp: -------------------------------------------------------------------------------- 1 | //Program to calculate factorial of integers greater than 20 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | vector arr; 7 | void fact(int); 8 | int main() 9 | { 10 | int n; 11 | cout << "Enter Number: "; 12 | cin >> n; 13 | arr.clear(); 14 | arr.push_back(1); 15 | fact(n); 16 | for (int i = 0; i < arr.size(); i++) 17 | { 18 | cout << arr[arr.size() - i - 1]; 19 | } 20 | cout << endl; 21 | return 0; 22 | } 23 | 24 | void fact(int n) 25 | { 26 | if (n != 1) 27 | { 28 | int carry = 0, test; 29 | for (int i = 0; i < arr.size(); i++) 30 | { 31 | test = ((n * arr[i]) + carry) % 10; 32 | carry = ((n * arr[i]) + carry) / 10; 33 | arr[i] = test; 34 | } 35 | if (carry != 0) 36 | { 37 | if (carry < 10) 38 | { 39 | arr.push_back(carry); 40 | } 41 | else 42 | { 43 | arr.push_back(carry % 10); 44 | arr.push_back(carry / 10); 45 | } 46 | } 47 | fact(n - 1); 48 | } 49 | } -------------------------------------------------------------------------------- /Java/Miscellaneous/valid_parentheses.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.LinkedList; 3 | 4 | public class valid_parentheses { 5 | 6 | 7 | /** 8 | * Determine if the input string is valid. 9 | * An input string is valid if: 10 | * Open brackets must be closed by the same type of brackets. 11 | * Open brackets must be closed in the correct order.* 12 | * @param s String 13 | */ 14 | boolean isValid(String s) { 15 | if(s.length() % 2 != 0) 16 | return false; 17 | 18 | LinkedList stack = new LinkedList<>(); 19 | 20 | char [] arrayChar = s.toCharArray(); 21 | 22 | for (char c : arrayChar) { 23 | 24 | if(c == '(' || c == '[' || c == '{' ){ 25 | stack.push(c); 26 | }else if(c == ')' && !stack.isEmpty() && stack.peek() == '(' ){ 27 | stack.pop(); 28 | }else if(c == ']' && !stack.isEmpty() && stack.peek() == '[' ){ 29 | stack.pop(); 30 | }else if(c == '}' && !stack.isEmpty() && stack.peek() == '{' ){ 31 | stack.pop(); 32 | } 33 | 34 | } 35 | 36 | return stack.isEmpty(); 37 | } 38 | 39 | } -------------------------------------------------------------------------------- /Java/Sorting/insertion_sort.java: -------------------------------------------------------------------------------- 1 | public class InsertionSort { 2 | 3 | /** 4 | * Time Complexity: O(n*2) 5 | * Auxiliary Space: O(1) 6 | * Boundary Cases: Insertion sort takes maximum time to sort if elements are sorted in reverse order. And it takes minimum time (Order of n) when elements are already sorted. 7 | * Stable: Yes 8 | * Optimisation - Binary Insertion Sort 9 | * 10 | * @param array 11 | */ 12 | static void insertionSort(int array[]) { 13 | int n = array.length; 14 | for (int i = 1; i < n; i++) { 15 | int elem = array[i]; 16 | int j = i - 1; 17 | while (j >= 0 && array[j] > elem) { 18 | array[j + 1] = array[j]; 19 | j--; 20 | } 21 | array[j + 1] = elem; 22 | } 23 | } 24 | 25 | static void insertionSortRecursive(int array[], int n) { 26 | if (n == 0 || n == 1) 27 | return; 28 | insertionSortRecursive(array, n - 1); 29 | int elem = array[n - 1]; 30 | int j = n - 2; 31 | while (j >= 0 && array[j] > elem) { 32 | array[j + 1] = array[j]; 33 | j--; 34 | } 35 | array[j + 1] = elem; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /C++/Sorting/bubble_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | void swap(int *a, int *b) 6 | { 7 | int temp = *a; 8 | *a = *b; 9 | *b = temp; 10 | } 11 | 12 | void BubbleSort(int arr[], int n) 13 | { 14 | for (int i = 0; i < n - 1; i++) 15 | { 16 | bool swapped = false; 17 | for (int j = 0; j < n - 1; j++) 18 | { 19 | if (arr[j] > arr[j + 1]) 20 | { 21 | swap(&arr[j], &arr[j + 1]); 22 | swapped = true; 23 | } 24 | } 25 | if (!swapped) 26 | break; 27 | } 28 | } 29 | 30 | void printArray(int arr[], int x) 31 | { 32 | for (int i = 0; i < x; i++) 33 | cout << arr[i] << " "; 34 | cout << endl; 35 | } 36 | 37 | int main() 38 | { 39 | int n; 40 | cout << "Enter size of array: "; 41 | cin >> n; 42 | int my_arr[n]; 43 | 44 | cout << "Start entering " << n << " numbers now.."; 45 | 46 | for (int i = 0; i < n; i++) 47 | cin >> my_arr[i]; 48 | 49 | cout << "Array before sorting is: "; 50 | printArray(my_arr, n); 51 | BubbleSort(my_arr, n); 52 | cout << "Array after sorting is: "; 53 | printArray(my_arr, n); 54 | } -------------------------------------------------------------------------------- /Python/Miscellaneous/rotation.py: -------------------------------------------------------------------------------- 1 | # Binary Search based Python3 2 | # program to find number of 3 | # rotations in a sorted and 4 | # rotated array. 5 | 6 | # Returns count of rotations for 7 | # an array which is first sorted 8 | # in ascending order, then rotated 9 | def countRotations(arr,low, high): 10 | 11 | # This condition is needed to 12 | # handle the case when array 13 | # is not rotated at all 14 | if (high < low): 15 | return 0 16 | 17 | # If there is only one 18 | # element left 19 | if (high == low): 20 | return low 21 | 22 | # Find mid 23 | # (low + high)/2 24 | mid = low + (high - low)/2; 25 | mid = int(mid) 26 | 27 | # Check if element (mid+1) is 28 | # minimum element. Consider 29 | # the cases like {3, 4, 5, 1, 2} 30 | if (mid < high and arr[mid+1] < arr[mid]): 31 | return (mid+1) 32 | 33 | # Check if mid itself is 34 | # minimum element 35 | if (mid > low and arr[mid] < arr[mid - 1]): 36 | return mid 37 | 38 | # Decide whether we need to go 39 | # to left half or right half 40 | if (arr[high] > arr[mid]): 41 | return countRotations(arr, low, mid-1); 42 | 43 | return countRotations(arr, mid+1, high) -------------------------------------------------------------------------------- /Rust/README.md: -------------------------------------------------------------------------------- 1 |

Rust


2 | 3 |

4 | 5 | ## Table of Contents 6 | 7 | - [Searching](#searching) 8 | - [Sorting](#sorting) 9 | - [Unit Tests](#unit-tests) 10 | 11 | 12 | 13 | ## Searching 14 | 15 | - [Binary Search](https://github.com/aniketsharma00411/algorithmsUse/blob/master/Rust/Searching/binary_search.rs) 16 | 17 | - [Linear Search](https://github.com/aniketsharma00411/algorithmsUse/blob/master/Rust/Searching/linear_search.rs) 18 | 19 | 20 | 21 | ## Sorting 22 | 23 | - [Bubble Sort](https://github.com/aniketsharma00411/algorithmsUse/blob/master/Rust/Sorting/bubble_sort.rs) 24 | 25 | - [Insertion Sort](https://github.com/aniketsharma00411/algorithmsUse/blob/master/Rust/Sorting/insertion_sort.rs) 26 | 27 | - [Merge Sort](https://github.com/aniketsharma00411/algorithmsUse/blob/master/Rust/Sorting/merge_sort.rs) 28 | 29 | - [Selection Sort](https://github.com/aniketsharma00411/algorithmsUse/blob/master/Rust/Sorting/selection_sort.rs) 30 | 31 | 32 | 33 | ## Unit Tests 34 | 35 | -- 36 | -------------------------------------------------------------------------------- /C++/Tree Alogrithms/binary_tree_to_doublyLL.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | struct Node { 6 | int data; 7 | Node* left; 8 | Node* right; 9 | 10 | Node(int value) { 11 | data = value; 12 | left = NULL; 13 | right = NULL; 14 | } 15 | }; 16 | 17 | 18 | void printDoublyLL(Node *head) { 19 | for (Node *itr = head; itr != NULL; itr = itr->right) { 20 | cout << itr->data << " "; 21 | } 22 | cout << "\n"; 23 | } 24 | 25 | 26 | Node *prevNode = NULL; 27 | Node *BT2DLL(Node *root) { 28 | if (root == NULL) { 29 | return root; 30 | } 31 | 32 | Node *head = BT2DLL(root->left); 33 | if (prevNode == NULL) { 34 | // Make sure that left most element is head 35 | head = root; 36 | } else { 37 | // prev is set, point current's left as prev 38 | root->left = prevNode; 39 | prevNode->right = root; 40 | } 41 | prevNode = root; 42 | BT2DLL(root->right); 43 | 44 | return head; 45 | } 46 | 47 | 48 | int main() { 49 | Node *root = new Node(10); 50 | // left 51 | root->left = new Node(20); 52 | root->left->left = new Node(30); 53 | root->left->right = new Node(40); 54 | // right 55 | root->right = new Node(50); 56 | root->right->right = new Node(60); 57 | 58 | Node *doublyLL = BT2DLL(root); 59 | printDoublyLL(doublyLL); 60 | 61 | return 0; 62 | } 63 | -------------------------------------------------------------------------------- /C++/Strings/string_sorting.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int main() 5 | { 6 | string strng; 7 | getline(cin, strng); 8 | char character[strng.length()]; 9 | strcpy(character, strng.c_str()); 10 | for (int iterator_1 = 0; iterator_1 < strng.length() - 1; iterator_1++) 11 | { 12 | if (character[iterator_1] >= char(33) && character[iterator_1] <= char(57)) 13 | { 14 | cout << "invalid string"; 15 | 16 | return 0; 17 | } 18 | } 19 | for (int iterator_2 = 0; iterator_2 < strng.length() - 1; iterator_2++) 20 | { 21 | for (int iterator_3 = 0; iterator_3 < strng.length() - iterator_2 - 1; iterator_3++) 22 | { 23 | 24 | if (character[iterator_3] > character[iterator_3 + 1]) 25 | { 26 | int reference = character[iterator_3]; 27 | character[iterator_3] = character[iterator_3 + 1]; 28 | character[iterator_3 + 1] = reference; 29 | } 30 | } 31 | } 32 | for (int iterator_4 = 0; iterator_4 < strng.length(); iterator_4++) 33 | { 34 | 35 | cout << character[iterator_4]; 36 | } 37 | } -------------------------------------------------------------------------------- /Go/Searching/binary_search.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | // BNode - Node for the tree where value is the current number, left and right are the tree sides 6 | type BNode struct { 7 | Value int 8 | Left *BNode 9 | Right *BNode 10 | } 11 | 12 | // Tree - The implementation of a binary search on a tree 13 | func Tree(current *BNode, value int) bool { 14 | if current == nil { 15 | return false 16 | } 17 | 18 | if current.Value == value { 19 | return true 20 | } else if current.Value > value { 21 | return Tree(current.Left, value) 22 | } 23 | 24 | return Tree(current.Right, value) 25 | } 26 | 27 | // List - Binary search through a list 28 | func List(list []int, value int) int { 29 | var start = 0 30 | var end int = len(list) - 1 31 | 32 | for start <= end { 33 | mid := end + start/2 34 | if list[mid] == value { 35 | fmt.Println("Found value!") 36 | return 0 37 | } else if list[mid] < value { 38 | start = mid + 1 39 | } else { 40 | end = mid - 1 41 | } 42 | } 43 | 44 | fmt.Println("Not found!") 45 | return 0 46 | } 47 | 48 | // Run this as go run go/binary_search/lucasguiss_binary_search.go 49 | func main() { 50 | list := []int{93, 42, 34, 64, 26, 67, 23, 1, 4, 60} 51 | var value int 52 | fmt.Println("Insert a value: ") 53 | fmt.Scanf("%d", &value) 54 | List(list, value) 55 | } 56 | -------------------------------------------------------------------------------- /Go/Sorting/radix_sort.go: -------------------------------------------------------------------------------- 1 | // Radix sort is the best algorithm to largest data :) 2 | package main 3 | 4 | import ( 5 | "bytes" 6 | "encoding/binary" 7 | "fmt" 8 | ) 9 | 10 | const limitDigit = 4 11 | const maxBitSize = -1 << 31 12 | 13 | func main() { 14 | 15 | var testData = []int32{43, 26, 4, -57, 456, 72, -57, 24, 6, 725, 62, -2, -457, 144, 444, 44, 284, 5, 7, -2, -26, 63, -4, 654, 7, -171, 45, 27, -525, -16, -27, 5} 16 | fmt.Println("Original data: ", testData) 17 | RadiSort(testData) 18 | fmt.Println("Result:", testData) 19 | } 20 | 21 | func RadiSort(testData []int32) { 22 | buff := bytes.NewBuffer(nil) 23 | data := make([][]byte, len(testData)) 24 | for i, e := range testData { 25 | binary.Write(buff, binary.LittleEndian, e^maxBitSize) 26 | aux := make([]byte, limitDigit) 27 | buff.Read(aux) 28 | data[i] = aux 29 | } 30 | sortCountReg := make([][][]byte, 256) 31 | for i := 0; i < limitDigit; i++ { 32 | for _, b := range data { 33 | sortCountReg[b[i]] = append(sortCountReg[b[i]], b) 34 | } 35 | j := 0 36 | for ky, bs := range sortCountReg { 37 | copy(data[j:], bs) 38 | j += len(bs) 39 | sortCountReg[ky] = bs[:0] 40 | } 41 | } 42 | var w int32 43 | for i, b := range data { 44 | buff.Write(b) 45 | binary.Read(buff, binary.LittleEndian, &w) 46 | testData[i] = w ^ maxBitSize 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Dart/Sorting/merge_sort.dart: -------------------------------------------------------------------------------- 1 | void mergeSorting(List list, int leftIndex, int middleIndex, int rightIndex) { 2 | int leftSize = middleIndex - leftIndex + 1; 3 | int rightSize = rightIndex - middleIndex; 4 | 5 | List leftList = new List(leftSize); 6 | List rightList = new List(rightSize); 7 | 8 | for (int i = 0; i < leftSize; i++) leftList[i] = list[leftIndex + i]; 9 | for (int j = 0; j < rightSize; j++) rightList[j] = list[middleIndex + j + 1]; 10 | 11 | int i = 0; 12 | int j = 0; 13 | int k = leftIndex; 14 | 15 | while (i < leftSize && j < rightSize) { 16 | if (leftList[i] <= rightList[j]) { 17 | list[k] = leftList[i]; 18 | i++; 19 | } else { 20 | list[k] = rightList[j]; 21 | j++; 22 | } 23 | k++; 24 | } 25 | 26 | while (i < leftSize) { 27 | list[k] = leftList[i]; 28 | i++; 29 | k++; 30 | } 31 | 32 | while (j < rightSize) { 33 | list[k] = rightList[j]; 34 | j++; 35 | k++; 36 | } 37 | } 38 | 39 | void mergeSort(List list, int leftIndex, int rightIndex) { 40 | if (leftIndex < rightIndex) { 41 | int middleIndex = (rightIndex + leftIndex) ~/2; 42 | 43 | mergeSort(list, leftIndex, middleIndex); 44 | mergeSort(list, middleIndex + 1, rightIndex); 45 | 46 | mergeSorting(list, leftIndex, middleIndex, rightIndex); //merging here! 47 | } 48 | } -------------------------------------------------------------------------------- /Go/README.md: -------------------------------------------------------------------------------- 1 |

Go


2 | 3 |

4 | 5 | ## Table of Contents 6 | 7 | - [Searching](#searching) 8 | - [Sorting](#sorting) 9 | - [Miscellaneous](#others) 10 | - [Unit Tests](#unit-tests) 11 | 12 | 13 | 14 | ## Searching 15 | 16 | - [Binary Search](https://github.com/aniketsharma00411/algorithmsUse/blob/master/Go/Searching/binary_search.go) 17 | 18 | 19 | 20 | ## Sorting 21 | 22 | - [Bubble Sort](https://github.com/aniketsharma00411/algorithmsUse/blob/master/Go/Sorting/bubble_sort.go) 23 | 24 | - [Quick Sort](https://github.com/aniketsharma00411/algorithmsUse/blob/master/Go/Sorting/quick_sort.go) 25 | 26 | - [Radix Sort](https://github.com/aniketsharma00411/algorithmsUse/blob/master/Go/Sorting/radix_sort.go) 27 | 28 | - [Selection Sort](https://github.com/aniketsharma00411/algorithmsUse/blob/master/Go/Sorting/selection_sort.go) 29 | 30 | 31 | ## Miscellaneous 32 | 33 | - [Fibonacci Recursive](https://github.com/aniketsharma00411/algorithmsUse/blob/master/Go/Miscellaneous/fibonacci_rec.go) 34 | 35 | 36 | 37 | ## Unit Tests 38 | 39 | -- 40 | -------------------------------------------------------------------------------- /C++/Tree Alogrithms/level_order_traversal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | typedef struct node{ 7 | node* right; 8 | node* left; 9 | int val; 10 | }node; 11 | 12 | //inorder traversal root -> left -> right 13 | //recursive 14 | 15 | node* createNode(int data){ 16 | node* newNode = new node(); 17 | newNode -> right = NULL; 18 | newNode -> left = NULL; 19 | newNode -> val = data; 20 | return newNode; 21 | } 22 | 23 | 24 | void levelorderTraversal(node* root){ 25 | if(root == NULL) 26 | return; 27 | 28 | queue q; 29 | q.push(root); 30 | 31 | while(q.size() > 0){ 32 | node* front = q.front(); 33 | q.pop(); 34 | cout<val<<" "; 35 | 36 | if(front -> left) 37 | q.push(front -> left); 38 | if(front -> right) 39 | q.push(front -> right); 40 | } 41 | } 42 | 43 | 44 | int main(){ 45 | 46 | node* root = NULL; 47 | root = createNode(5); 48 | root -> left = createNode(3); 49 | root -> left -> left = createNode(1); 50 | root -> left -> right = createNode(4); 51 | 52 | root -> right = createNode(7); 53 | root -> right -> right = createNode(9); 54 | root -> right -> left = createNode(6); 55 | 56 | levelorderTraversal(root); 57 | 58 | return 0; 59 | } -------------------------------------------------------------------------------- /C++/Miscellaneous/majority_element.cpp: -------------------------------------------------------------------------------- 1 | //moores voting algorithm to find majority element in an array 2 | //contributed by devanshi katyal 3 | #include 4 | 5 | using namespace std; 6 | int findCanditate(int a[], int s) 7 | { 8 | int maj_index = 0, count = 1; 9 | for (int i = 1; i < s; i++) 10 | { 11 | if (a[maj_index] == a[i]) 12 | count++; 13 | else 14 | count--; 15 | if (count == 0) 16 | { 17 | maj_index = i; 18 | count = 1; 19 | } 20 | } 21 | return a[maj_index]; 22 | } 23 | bool ismajority(int a[], int size, int cand) 24 | { 25 | int co = 0; 26 | for (int i = 0; i < size; i++) 27 | { 28 | if (a[i] == cand) 29 | { 30 | co++; 31 | } 32 | } 33 | if (co > (size / 2)) 34 | return true; 35 | else 36 | return false; 37 | } 38 | int main() 39 | { 40 | int n = 0; 41 | int a[n]; 42 | cout << "Enter the size of array" << endl; 43 | cin >> n; 44 | cout << "Enter the array" << endl; 45 | for (int i = 0; i < n; i++) 46 | { 47 | cin >> a[i]; 48 | } 49 | int cand = findCanditate(a, n); 50 | if (ismajority(a, n, cand)) 51 | cout << cand << " is the majority element"; 52 | else 53 | cout << " no majority element"; 54 | return 0; 55 | } 56 | -------------------------------------------------------------------------------- /Python/Tree Algorithms/balanced_binary_tree_check.py: -------------------------------------------------------------------------------- 1 | # Python program for implementation of Balanced Binary Tree Check 2 | 3 | class Node: 4 | def __init__(self, data): 5 | self.data = data 6 | self.left = None 7 | self.right = None 8 | 9 | # compute tree's height 10 | def height(root): 11 | if root is None: 12 | return 0 13 | return max(height(root.left), height(root.right)) + 1 14 | 15 | def isBalanced(root): 16 | # For a None tree balance 17 | if root is None: 18 | return True 19 | 20 | # compute left root height 21 | left_height = height(root.left) 22 | # compute right root height 23 | right_height = height(root.right) 24 | 25 | # if the left height and right height of tree is more than 1, then the tree is not balanced 26 | if (abs(leftheight - rightheight) <= 1) and isBalanced(root.left) is True 27 | 28 | # if the right subtree is not balanced, this tree is not balanced then also 29 | and isBalanced( root.right) is True: 30 | return True 31 | return False 32 | 33 | root = Node(1) 34 | root.left = Node(2) 35 | root.right = Node(3) 36 | root.left.left = Node(4) 37 | root.left.right = Node(5) 38 | root.left.left.left = Node(8) 39 | 40 | print("Is the given tree balanced? ") 41 | result = "True" if isBalanced(root) else "False" 42 | print(result) 43 | -------------------------------------------------------------------------------- /C++/Dynamic Programming/activity_selection_problem.c: -------------------------------------------------------------------------------- 1 | #include 2 | #define MAX 20 3 | 4 | int n; 5 | 6 | struct activity 7 | { 8 | int index; 9 | int s; 10 | int f; 11 | }A[MAX],temp; 12 | 13 | void activity_selector() 14 | { 15 | int i=0,j; 16 | printf("A%d ",A[i].index); 17 | for(j=1;j= A[i].f) 20 | { 21 | printf("A%d ",A[j].index+1); 22 | i = j; 23 | } 24 | } 25 | } 26 | 27 | void input_activity() 28 | { 29 | int i; 30 | for(i=0;i 2 | using namespace std; 3 | 4 | 5 | void cocktailSort(int a[], int n) { // array and number of elemmets inside. 6 | bool swapped = true; 7 | int start = 0; 8 | int end = n - 1; 9 | 10 | while (swapped) { 11 | swapped = false; // reset since it may be true from previous iteration 12 | 13 | // First loop- left to right 14 | for (int i = start; i < end; i++) { 15 | if (a[i] > a[i + 1]) { 16 | swap(a[i], a[i + 1]); // built in function in std namespace 17 | swapped = true; 18 | } 19 | } 20 | if (!swapped) { // if nothing moves store array 21 | break; 22 | } else{ 23 | swapped = false; // reset flag 24 | } 25 | 26 | // Second loop- right to left 27 | for (int i = end - 1; i >= start; --i) { 28 | if (a[i] > a[i + 1]) { 29 | swap(a[i], a[i + 1]); 30 | swapped = true; 31 | } 32 | } 33 | // increase the starting point so it stays in bounds 34 | ++start; 35 | } 36 | } 37 | 38 | void printArr(int a[], int n) { 39 | for (int i = 0; i < n; i++) { 40 | cout << a[i] << ' '; 41 | } 42 | } 43 | 44 | 45 | 46 | int main() { 47 | int arr[] = { 7, 2, 3, 2, 9, 0, 0, 10}; 48 | int n = sizeof(arr) / sizeof(arr[0]); 49 | cocktailSort(arr, n); // array and numb or elements 50 | cout << "Sorted array: " << endl; 51 | printArr(arr, n); 52 | return 0; 53 | } -------------------------------------------------------------------------------- /JavaScript/Sorting/quick_sort.js: -------------------------------------------------------------------------------- 1 | var items = [5, 3, 7, 6, 2, 9]; 2 | function swap(items, leftIndex, rightIndex) { 3 | var temp = items[leftIndex]; 4 | items[leftIndex] = items[rightIndex]; 5 | items[rightIndex] = temp; 6 | } 7 | function partition(items, left, right) { 8 | var pivot = items[Math.floor((right + left) / 2)], //middle element 9 | i = left, //left pointer 10 | j = right; //right pointer 11 | while (i <= j) { 12 | while (items[i] < pivot) { 13 | i++; 14 | } 15 | while (items[j] > pivot) { 16 | j--; 17 | } 18 | if (i <= j) { 19 | swap(items, i, j); //sawpping two elements 20 | i++; 21 | j--; 22 | } 23 | } 24 | return i; 25 | } 26 | 27 | function quickSort(items, left, right) { 28 | var index; 29 | if (items.length > 1) { 30 | index = partition(items, left, right); //index returned from partition 31 | if (left < index - 1) { //more elements on the left side of the pivot 32 | quickSort(items, left, index - 1); 33 | } 34 | if (index < right) { //more elements on the right side of the pivot 35 | quickSort(items, index, right); 36 | } 37 | } 38 | return items; 39 | } 40 | var sortedArray = quickSort(items, 0, items.length - 1); 41 | console.log(sortedArray); //prints [2,3,5,6,7,9] 42 | -------------------------------------------------------------------------------- /C++/Math/sieve_of_eratosthenes.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to print all primes smaller than or equal to 2 | // n using Sieve of Eratosthenes 3 | 4 | #include 5 | using namespace std; 6 | 7 | void SieveOfEratosthenes(int n) 8 | { 9 | // Create a boolean array "prime[0..n]" and initialize 10 | // all entries it as true. A value in prime[i] will 11 | // finally be false if i is Not a prime, else true. 12 | bool prime[n+1]; 13 | memset(prime, true, sizeof(prime)); 14 | 15 | for (int p=2; p*p<=n; p++) 16 | { 17 | // If prime[p] is not changed, then it is a prime 18 | if (prime[p] == true) 19 | { 20 | // Update all multiples of p greater than or 21 | // equal to the square of it 22 | // numbers which are multiple of p and are 23 | // less than p^2 are already been marked. 24 | for (int i=p*p; i<=n; i += p) 25 | prime[i] = false; 26 | } 27 | } 28 | 29 | // Print all prime numbers 30 | for (int p=2; p<=n; p++) 31 | if (prime[p]) 32 | cout << p << " "; 33 | } 34 | 35 | // Driver Program to test above function 36 | int main() 37 | { 38 | int n = 30; 39 | cout << "Following are the prime numbers smaller " 40 | << " than or equal to " << n << endl; 41 | SieveOfEratosthenes(n); 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /C++/Dynamic Programming/dp_coin_change.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution 5 | { 6 | public: 7 | int ans; 8 | 9 | int solve(vector &coins, int n, int cnt, vector &dp) 10 | { 11 | if (n == 0) 12 | { 13 | return 0; 14 | } 15 | 16 | if (dp[n] != -1) 17 | { 18 | return dp[n]; 19 | } 20 | int ans = INT_MAX; 21 | for (int i = 0; i < coins.size(); i++) 22 | { 23 | if (coins[i] > n) 24 | { 25 | continue; 26 | } 27 | int val = solve(coins, n - coins[i], cnt + 1, dp); 28 | if (val < ans) 29 | { 30 | ans = val; 31 | } 32 | } 33 | if (ans != INT_MAX) 34 | { 35 | ans = ans + 1; 36 | } 37 | dp[n] = ans; 38 | return dp[n]; 39 | } 40 | 41 | int coinChange(vector &coins, int amount) 42 | { 43 | if (amount == 0) 44 | { 45 | return 0; 46 | } 47 | ans = INT_MAX; 48 | vector dp; 49 | for (int i = 0; i <= amount; i++) 50 | { 51 | dp.push_back(-1); 52 | } 53 | solve(coins, amount, 0, dp); 54 | if (dp[amount] == INT_MAX) 55 | { 56 | return -1; 57 | } 58 | return dp[amount]; 59 | } 60 | }; 61 | -------------------------------------------------------------------------------- /Dart/Searching/interpolation_search.dart: -------------------------------------------------------------------------------- 1 | // If x is present in arr[0..n-1], then returns 2 | // index of it, else returns -1. 3 | int interpolationSearch(List arr, int lo, int hi, int x) { 4 | int pos; 5 | // Since array is sorted, an element present 6 | // in array must be in range defined by corner 7 | if (lo <= hi && x >= arr[lo] && x <= arr[hi]) { 8 | // Probing the position with keeping 9 | // uniform distribution in mind. 10 | pos = (lo + (((hi - lo).toDouble() / (arr[hi] - arr[lo])) * (x - arr[lo]))) 11 | .toInt(); 12 | 13 | // Condition of target found 14 | if (arr[pos] == x) return pos; 15 | 16 | // If x is larger, x is in right sub array 17 | if (arr[pos] < x) return interpolationSearch(arr, pos + 1, hi, x); 18 | 19 | // If x is smaller, x is in left sub array 20 | if (arr[pos] > x) return interpolationSearch(arr, lo, pos - 1, x); 21 | } 22 | return -1; 23 | } 24 | 25 | // Driver Code 26 | int main() { 27 | // Array of items on which search will 28 | // be conducted. 29 | List arr = [10, 12, 13, 16, 18, 19, 20, 21, 22, 23, 24, 33, 35, 42, 47]; 30 | 31 | int n = arr.length; 32 | 33 | // Element to be searched 34 | int x = 18; 35 | int index = interpolationSearch(arr, 0, n - 1, x); 36 | 37 | // If element was found 38 | if (index != -1) 39 | print("Element found at index $index"); 40 | else 41 | print("Element not found"); 42 | 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /C++/Dynamic Programming/dp_fibonacci.cpp: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Author: Ahmed Elsisy 4 | * Date: 23/10/2020 5 | * Description: Given N and M , returns Nth fibonacci number modulus positive number M 6 | * 7 | * Memory: O(N) 8 | * Time: O(N) using dynamic programming for pre-processing and O(1) for query nth fibonacci number 9 | * Status: stress-tested for n <= 500000 (accepted on https://www.spoj.com/problems/FIBEZ/) 10 | */ 11 | 12 | 13 | class fibonacci_dp{ 14 | private: 15 | vector fib; 16 | int mod; 17 | int add_mod(int x , int y){ // returns (x+y) % mod 18 | return (1ll * x + y) % mod; 19 | } 20 | void pre_process(){ // bottom-up dynamic programming fib(n) = (fib(n-1) + fib(n-2)) % mod 21 | int n = (int)fib.size(); 22 | if(n >= 1)fib[0] = 1; 23 | if(n >= 2)fib[1] = 1; 24 | for(int i = 2 ; i < n ; ++i) { 25 | fib[i] = add_mod(fib[i - 1], fib[i - 2]); 26 | } 27 | } 28 | public: 29 | fibonacci_dp(int maximum_N , int M){ // initialized 30 | mod = M; 31 | fib.resize(maximum_N + 1); 32 | pre_process(); 33 | } 34 | int fibonacci(int n){ // returns nth fibonacci number 35 | return fib[n]; 36 | } 37 | }; 38 | 39 | 40 | /* 41 | * fib(0) = 0 42 | * fib(1) = 1 43 | * fib(2) = 1 44 | * fib(3) = 2 45 | * fib(4) = 3 46 | * fib(5) = 5 47 | * fib(6) = 8 48 | * fib(7) = 13 49 | * fib(8) = 21 50 | * fib(9) = 34 51 | * fib(10) = 55 52 | */ -------------------------------------------------------------------------------- /Dart/Searching/jump_search.dart: -------------------------------------------------------------------------------- 1 | //Name: Shivam Verma 2 | 3 | 4 | import 'dart:math'; 5 | int jumpSearch(List arr, int x, int n) 6 | { 7 | // Finding block size to be jumped 8 | double step = sqrt(n); 9 | 10 | // Finding the block where element is 11 | // present (if it is present) 12 | double prev = 0; 13 | while (arr[min(step, n)-1] < x) 14 | { 15 | prev = step; 16 | step += sqrt(n); 17 | if (prev >= n) 18 | return -1; 19 | } 20 | 21 | // Doing a linear search for x in block 22 | // beginning with prev. 23 | while (arr[prev.toInt()] < x) 24 | { 25 | prev++; 26 | 27 | // If we reached next block or end of 28 | // array, element is not present. 29 | if (prev == min(step, n)) 30 | return -1; 31 | } 32 | // If element is found 33 | if (arr[prev.toInt()] == x) 34 | return prev.toInt(); 35 | 36 | return -1; 37 | } 38 | 39 | // Driver program to test function 40 | int main() 41 | { 42 | List arr = [0, 1, 1, 2, 3, 5, 8, 13, 21, 43 | 34, 55, 89, 144, 233, 377, 610 ]; 44 | int x = 55; 45 | int n = arr.length; 46 | 47 | // Find the index of 'x' using Jump Search 48 | int index = jumpSearch(arr, x, n); 49 | 50 | // Print the index where 'x' is located 51 | print("\nNumber $x is at index $index"); 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /Python/Sorting/merge_sort.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | ''' 3 | Author : Karthikeyan_01 4 | Algo : Merge Sort 5 | Time Comp : O(n logn) 6 | ''' 7 | 8 | 9 | def merge(a , L , mid , R): 10 | n1 = mid - L + 1 11 | n2 = R - mid 12 | 13 | k = L 14 | 15 | Left = [0] * (n1) 16 | Right= [0] * (n2) 17 | 18 | for i in range(0 , n1): 19 | Left[i] = a[i+L] 20 | 21 | for j in range(0 , n2): 22 | Right[j] = a[j + mid + 1] 23 | 24 | i = 0 25 | j = 0 26 | while i < n1 and j < n2: 27 | if Left[i] <= Right[j]: 28 | a[k] = Left[i] 29 | k += 1 30 | i += 1 31 | else: 32 | a[k] = Right[j] 33 | k += 1 34 | j += 1 35 | 36 | while i < n1: 37 | a[k] = Left[i] 38 | i += 1 39 | k += 1 40 | while j < n2: 41 | a[k] = Right[j] 42 | j += 1 43 | k += 1 44 | 45 | 46 | 47 | def mergesort(a , L , R): 48 | if L < R: 49 | mid = (L + R)//2 50 | mergesort(a , L , mid) 51 | mergesort(a , mid + 1 , R) 52 | merge(a , L , mid , R) 53 | 54 | 55 | if __name__ == '__main__': 56 | a = [ 2 , 7 , 3 , 5 , 4 , 1] 57 | n = len(a) 58 | print("Array Before Sorting") 59 | for i in a: 60 | print(i , end = ' ') 61 | 62 | 63 | mergesort(a , 0 , n - 1) 64 | 65 | print('\n') 66 | print("Array After Sorting") 67 | for i in a: 68 | print(i , end=' ') 69 | 70 | 71 | 72 | -------------------------------------------------------------------------------- /C++/Dynamic Programming/matrix_chain_multiplication.cpp: -------------------------------------------------------------------------------- 1 | //Given a sequence of matrices, find the most efficient way 2 | //to multiply these matrices together. The problem is not 3 | //actually to perform the multiplications, but merely to decide 4 | //in which order to perform the multiplications. 5 | 6 | 7 | #include 8 | 9 | using namespace std; 10 | 11 | const int N = 1000; 12 | int dp[N][N]; 13 | 14 | int MatrixChainMulitiplication(int p[], int i, int j) 15 | { 16 | if (i == j) 17 | return 0; 18 | 19 | if (~dp[i][j]) 20 | return dp[i][j]; 21 | int k; 22 | int min = INT_MAX; 23 | int count; 24 | 25 | // place parenthesis at different places 26 | // between first and last matrix, recursively 27 | // calculate count of multiplications for 28 | // each parenthesis placement and return the 29 | // minimum count 30 | for (k = i; k < j; k++) 31 | { 32 | count = MatrixChainMulitiplication(p, i, k) 33 | + MatrixChainMulitiplication(p, k + 1, j) 34 | + p[i - 1] * p[k] * p[j]; 35 | 36 | if (count < min) 37 | min = count; 38 | } 39 | 40 | // Return minimum count 41 | return dp[i][j] = min; 42 | } 43 | 44 | 45 | 46 | int main() 47 | { 48 | memset(dp,-1,sizeof dp); 49 | int arr[] = { 1, 2, 3, 4 }; 50 | int n = sizeof(arr) / sizeof(arr[0]); 51 | 52 | cout << "Minimum number of multiplications is " 53 | << MatrixChainMulitiplication(arr,1, n - 1); 54 | } 55 | -------------------------------------------------------------------------------- /C++/Searching/stair_case_search.cpp: -------------------------------------------------------------------------------- 1 | //stair case search is applied on the sorted matrix 2 | //example - 1 2 3 3 | // 4 5 6 4 | // 7 8 9 5 | #include 6 | using namespace std; 7 | int main() { 8 | int m, n; 9 | int i, j; 10 | cout << "Enter the no. of rows and columns" << endl; 11 | //Taking input the number of rows and columns 12 | cin >> m >> n; 13 | int a[m][n]; 14 | cout << "Enter the elements of the matrix:" << "\n"; 15 | //taking input the elements of the matrix 16 | for ( i = 0; i < m; i++) { 17 | for (j = 0; j < n; j++) { 18 | cin >> a[i][j]; 19 | 20 | } 21 | } 22 | cout << "Enter the no. to be searched" << endl; 23 | int x; 24 | cin >> x; 25 | i = 0; 26 | j = n - 1; 27 | int pass = 0; 28 | //Initailly we will check the last element of every row if its smaller than the required 29 | //number we will keep on decrementing in the last column. 30 | //else we will traverse the row where the last element is greaterthan the required number. 31 | while (i < m && j < n) { 32 | if (a[i][j] == x) { 33 | pass = 1; 34 | break; 35 | } 36 | else if (x < a[i][j]) { 37 | j--; 38 | 39 | } 40 | else { 41 | i++; 42 | } 43 | } 44 | if (pass == 1) 45 | cout << "No. found at row = " << i + 1 << " & " << "column = " << j + 1 << endl; 46 | return 0; 47 | } -------------------------------------------------------------------------------- /C++/Sorting/shell_sort.cpp: -------------------------------------------------------------------------------- 1 | // Shell sort in C++ programming 2 | //Time complexity of shellsort is O(n2). 3 | 4 | #include 5 | using namespace std; 6 | 7 | /* function to sort arr using shellSort */ 8 | int shellSort(int arr[], int n) 9 | { 10 | // Start with a big gap, then reduce the gap 11 | for (int gap = n/2; gap > 0; gap /= 2) 12 | { 13 | // Do a gapped insertion sort for this gap size. 14 | // The first gap elements a[0..gap-1] are already in gapped order 15 | // keep adding one more element until the entire array is 16 | // gap sorted 17 | for (int i = gap; i < n; i += 1) 18 | { 19 | // add a[i] to the elements that have been gap sorted 20 | // save a[i] in temp and make a hole at position i 21 | int temp = arr[i]; 22 | 23 | // shift earlier gap-sorted elements up until the correct 24 | // location for a[i] is found 25 | int j; 26 | for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) 27 | arr[j] = arr[j - gap]; 28 | 29 | // put temp (the original a[i]) in its correct location 30 | arr[j] = temp; 31 | } 32 | } 33 | return 0; 34 | } 35 | 36 | void printArray(int arr[], int n) 37 | { 38 | for (int i=0; i 2 | using namespace std; 3 | 4 | 5 | /* 6 | Worst case time complexity: O(n2) 7 | Average case time complexity: O(n) 8 | 9 | If random pivot is used in lomutoPartition, 10 | even in worst case, time complexity is O(n) 11 | */ 12 | 13 | 14 | int lomutoPartition(int arr[], int low, int high) { 15 | int pivot = arr[high]; 16 | int i = low - 1; 17 | 18 | for (int j = low; j <= high - 1; ++j) { 19 | if (arr[j] < pivot) { 20 | ++i; 21 | swap(arr[i], arr[j]); 22 | } 23 | } 24 | swap(arr[i + 1], arr[high]); 25 | return (i + 1); 26 | } 27 | 28 | 29 | int kthSmallest(int arr[], int arrSize, int k) { 30 | int low = 0; 31 | int high = arrSize - 1; 32 | 33 | while (low <= high) { 34 | int partitionIndex = lomutoPartition(arr, low, high); 35 | 36 | if (partitionIndex == k - 1) { 37 | return partitionIndex; 38 | } else if (partitionIndex > k - 1) { 39 | high = partitionIndex - 1; 40 | } else { 41 | low = partitionIndex + 1; 42 | } 43 | } 44 | 45 | return -1; 46 | } 47 | 48 | 49 | int main() { 50 | int arrSize; 51 | cout << "Enter size of array: "; 52 | cin >> arrSize; 53 | 54 | int arr[arrSize]; 55 | cout << "Enter elements of array: "; 56 | for (int i = 0; i < arrSize; ++i) { 57 | cin >> arr[i]; 58 | } 59 | 60 | int k; 61 | cout << "Which smallest th number do you want to find? "; 62 | cin >> k; 63 | 64 | cout << k 65 | << "th smallest number is: " 66 | << arr[kthSmallest(arr, arrSize, k)] 67 | << "\n"; 68 | 69 | return 0; 70 | } 71 | -------------------------------------------------------------------------------- /C++/Searching/interpolation_search.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to implement interpolation search 2 | #include 3 | using namespace std; 4 | 5 | // If x is present in arr[0..n-1], then returns 6 | // index of it, else returns -1. 7 | int interpolationSearch(int arr[], int n, int x) 8 | { 9 | // Find indexes of two corners 10 | int lo = 0, hi = (n - 1); 11 | 12 | // Since array is sorted, an element present 13 | // in array must be in range defined by corner 14 | while (lo <= hi && x >= arr[lo] && x <= arr[hi]) 15 | { 16 | if (lo == hi) 17 | { 18 | if (arr[lo] == x) return lo; 19 | return -1; 20 | } 21 | // Probing the position with keeping 22 | // uniform distribution in mind. 23 | int pos = lo + (((double)(hi - lo) / 24 | (arr[hi] - arr[lo])) * (x - arr[lo])); 25 | 26 | // Condition of target found 27 | if (arr[pos] == x) 28 | return pos; 29 | 30 | // If x is larger, x is in upper part 31 | if (arr[pos] < x) 32 | lo = pos + 1; 33 | 34 | // If x is smaller, x is in the lower part 35 | else 36 | hi = pos - 1; 37 | } 38 | return -1; 39 | } 40 | 41 | // Driver Code 42 | int main() 43 | { 44 | // Array of items on which search will 45 | // be conducted. 46 | int arr[] = {10, 12, 13, 16, 18, 19, 20, 21, 22, 23, 24, 33, 35, 42, 47}; 47 | int n = sizeof(arr)/sizeof(arr[0]); 48 | 49 | int x = 18; // Element to be searched 50 | int index = interpolationSearch(arr, n, x); 51 | 52 | // If element was found 53 | if (index != -1) 54 | cout << "Element found at index " << index; 55 | else 56 | cout << "Element not found."; 57 | return 0; 58 | } -------------------------------------------------------------------------------- /Python/Graph Algorithms/dijkstras.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import math 4 | 5 | def Dijkstras(graph, start, goal): 6 | unseenNodes = graph 7 | predecessor = {} 8 | shortest_distance = {} 9 | path = [] 10 | infinty = math.inf 11 | 12 | for node in unseenNodes: 13 | shortest_distance[node] = infinty 14 | shortest_distance[start] = 0 15 | 16 | while unseenNodes: 17 | minNode = None 18 | for node in unseenNodes: 19 | if minNode is None: 20 | minNode = node 21 | 22 | elif shortest_distance[node] < shortest_distance[minNode]: 23 | minNode = node 24 | 25 | for chilNode,weight in graph[minNode].items(): 26 | if weight + shortest_distance[minNode] < shortest_distance[chilNode]: 27 | shortest_distance[chilNode] = weight + shortest_distance[minNode] 28 | predecessor[chilNode] = minNode 29 | 30 | unseenNodes.pop(minNode) 31 | 32 | 33 | currenNode = goal 34 | while currenNode != start: 35 | try: 36 | path.insert(0,currenNode) 37 | 38 | currenNode = predecessor[currenNode] 39 | except KeyError: 40 | print('path not found') 41 | break 42 | 43 | path.insert(0,start) 44 | 45 | if shortest_distance[goal] != infinty: 46 | print('The shortest distance is ' + str(shortest_distance[goal])) 47 | print('And the path is ' + str(path)) 48 | 49 | 50 | graph = {'a':{'b':10,'c':3},'b':{'c':1,'d':2},'c':{'b':4,'d':8,'e':2},'d':{'e':7},'e':{'d':9}} 51 | Dijkstras(graph, 'a', 'd') 52 | 53 | -------------------------------------------------------------------------------- /C++/Searching/fibonacci_search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | 6 | int min(int x, int y) { return (x<=y)? x : y; } 7 | 8 | 9 | int fibMonaccianSearch(int arr[], int x, int n) 10 | { 11 | 12 | int fibMMm2 = 0; 13 | int fibMMm1 = 1; 14 | int fibM = fibMMm2 + fibMMm1; 15 | 16 | 17 | while (fibM < n) 18 | { 19 | fibMMm2 = fibMMm1; 20 | fibMMm1 = fibM; 21 | fibM = fibMMm2 + fibMMm1; 22 | } 23 | 24 | int offset = -1; 25 | 26 | 27 | while (fibM > 1) 28 | { 29 | 30 | int i = min(offset+fibMMm2, n-1); 31 | 32 | 33 | if (arr[i] < x) 34 | { 35 | fibM = fibMMm1; 36 | fibMMm1 = fibMMm2; 37 | fibMMm2 = fibM - fibMMm1; 38 | offset = i; 39 | } 40 | 41 | 42 | else if (arr[i] > x) 43 | { 44 | fibM = fibMMm2; 45 | fibMMm1 = fibMMm1 - fibMMm2; 46 | fibMMm2 = fibM - fibMMm1; 47 | } 48 | 49 | else return i; 50 | } 51 | 52 | 53 | if(fibMMm1 && arr[offset+1]==x)return offset+1; 54 | 55 | 56 | return -1; 57 | } 58 | 59 | 60 | int main(void) 61 | { 62 | int n; 63 | cout<<"Enter the size of array: "; 64 | cin>>n; 65 | int arr[n]; 66 | cout<<"Enter the elements in array: "; 67 | for(int i=0;i>arr[i]; 70 | } 71 | int x = 0; 72 | cout<<"Enter the element you want to search in the array using Fibonacci search: "; 73 | cin>>x; 74 | int ind=fibMonaccianSearch(arr, x, n); 75 | cout<<"Found at index: "<Dart
2 | 3 |

4 | 5 | ## Table of Contents 6 | 7 | - [Searching](#searching) 8 | - [Sorting](#sorting) 9 | - [Unit Tests](#unit-tests) 10 | 11 | 12 | 13 | ## Searching 14 | 15 | - [Binary Search](https://github.com/aniketsharma00411/algorithmsUse/blob/master/Dart/Searching/binary_search.dart) 16 | 17 | - [Interpolation Search](https://github.com/aniketsharma00411/algorithmsUse/blob/master/Dart/Searching/interpolation_search.dart) 18 | 19 | - [Jump Search](https://github.com/aniketsharma00411/algorithmsUse/blob/master/Dart/Searching/jump_search.dart) 20 | 21 | - [Linear Search](https://github.com/aniketsharma00411/algorithmsUse/blob/master/Dart/Searching/linear_search.dart) 22 | 23 | 24 | 25 | ## Sorting 26 | 27 | - [Bubble Sort](https://github.com/aniketsharma00411/algorithmsUse/blob/master/Dart/Sorting/bubble_sort.dart) 28 | 29 | - [Insertion Sort](https://github.com/aniketsharma00411/algorithmsUse/blob/master/Dart/Sorting/insertion_sort.dart) 30 | 31 | - [Merge Sort](https://github.com/aniketsharma00411/algorithmsUse/blob/master/Dart/Sorting/merge_sort.dart) 32 | 33 | - [Selection Sort](https://github.com/aniketsharma00411/algorithmsUse/blob/master/Dart/Sorting/selection_sort.dart) 34 | 35 | - [Quick Sort](https://github.com/aniketsharma00411/algorithmsUse/blob/master/Dart/Sorting/quick_sort.dart) 36 | 37 | 38 | 39 | ## Unit Tests 40 | 41 | -- 42 | -------------------------------------------------------------------------------- /C++/Sorting/radix_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | void PrintArray(vector &arr) 9 | { 10 | for (int ele : arr) 11 | cout << ele << " "; 12 | cout << endl; 13 | } 14 | 15 | int getMax(vector &arr) 16 | { 17 | int mx = arr[0]; 18 | for (int i = 1; i < arr.size(); i++) 19 | mx = max(mx, arr[i]); 20 | return mx; 21 | } 22 | 23 | void countSort(vector &arr, int exp) 24 | { 25 | vector output(arr.size(), 0); 26 | int i, count[10] = {0}; 27 | 28 | for (i = 0; i < arr.size(); i++) 29 | count[(arr[i] / exp) % 10]++; 30 | 31 | for (i = 1; i < 10; i++) 32 | count[i] += count[i - 1]; 33 | 34 | for (i = arr.size() - 1; i >= 0; i--) 35 | { 36 | output[count[(arr[i] / exp) % 10] - 1] = arr[i]; 37 | count[(arr[i] / exp) % 10]--; 38 | } 39 | 40 | for (i = 0; i < arr.size(); i++) 41 | arr[i] = output[i]; 42 | } 43 | 44 | void RadixSort(vector &arr) 45 | { 46 | int m = getMax(arr); 47 | for (int exp = 1; m / exp > 0; exp *= 10) 48 | countSort(arr, exp); 49 | } 50 | 51 | int main(int args, char **argv) 52 | { 53 | int n; 54 | cout << "Enter size of Array:"; 55 | cin >> n; 56 | 57 | vector arr(n, 0); 58 | 59 | for (int i = 0; i < n; i++) 60 | arr[i] = (rand() % 10000) + 1; //Creates a array with Randomly generated Integers upto 10000 61 | 62 | cout << "Initial Array:" << endl; 63 | PrintArray(arr); 64 | 65 | RadixSort(arr); 66 | 67 | cout << "Array after sorting:" << endl; 68 | PrintArray(arr); 69 | 70 | } -------------------------------------------------------------------------------- /Java/Searching/Interpolation_Search.java: -------------------------------------------------------------------------------- 1 | // Java program to implement interpolation search 2 | 3 | class Interpolation 4 | { 5 | // Array of items on which search will 6 | // be conducted. 7 | static int arr[] = new int[]{10, 12, 13, 16, 18, 19, 20, 21, 22, 23, 8 | 24, 33, 35, 42, 47}; 9 | 10 | // If x is present in arr[0..n-1], then returns 11 | // index of it, else returns -1. 12 | static int interpolationSearch(int x) 13 | { 14 | // Find indexes of two corners 15 | int lo = 0, hi = (arr.length - 1); 16 | 17 | // Since array is sorted, an element present 18 | // in array must be in range defined by corner 19 | while (lo <= hi && x >= arr[lo] && x <= arr[hi]) 20 | { 21 | 22 | if (lo == hi) 23 | { 24 | if (arr[lo] == x) return lo; 25 | return -1; 26 | } 27 | 28 | // Probing the position with keeping 29 | // uniform distribution in mind. 30 | 31 | int pos = lo + (((hi-lo) / 32 | (arr[hi]-arr[lo]))*(x - arr[lo])); 33 | 34 | // Condition of target found 35 | if (arr[pos] == x) 36 | return pos; 37 | 38 | // If x is larger, x is in upper part 39 | if (arr[pos] < x) 40 | lo = pos + 1; 41 | 42 | // If x is smaller, x is in the lower part 43 | else 44 | hi = pos - 1; 45 | } 46 | return -1; 47 | } 48 | 49 | // Driver method 50 | public static void main(String[] args) 51 | { 52 | int x = 18; // Element to be searched 53 | int index = interpolationSearch(x); 54 | 55 | // If element was found 56 | if (index != -1) 57 | System.out.println("Element found at index " + index); 58 | else 59 | System.out.println("Element not found."); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /C++/Miscellaneous/range_sum_segment_tree.cpp: -------------------------------------------------------------------------------- 1 | // Point update and range query using segment tree 2 | 3 | #include 4 | using namespace std; 5 | #define N 100005 6 | 7 | // Vector to store segment tree values 8 | vector st(N); 9 | 10 | // Building the segment tree using the given vector v 11 | void build_st(int node, int beg, int end, vector v) 12 | { 13 | if(beg == end) 14 | { 15 | st[node] = v[beg]; 16 | return; 17 | } 18 | int mid = beg + (end - beg) / 2; 19 | build_st(2*node+1, beg, mid, v); 20 | build_st(2*node+2, mid + 1, end, v); 21 | st[node] = st[2*node+1] + st[2*node+2]; 22 | } 23 | 24 | // Updating the element at index pos to value x 25 | void update(int node, int beg, int end, int pos, int x) 26 | { 27 | if(beg == end) 28 | { 29 | st[node] = x; 30 | return; 31 | } 32 | int mid = beg + (end-beg)/2; 33 | if(pos<=mid) 34 | update(2*node+1,beg,mid,pos,x); 35 | else 36 | update(2*node+2,mid+1,end,pos,x); 37 | st[node] = st[2*node+1] + st[2*node+2]; 38 | } 39 | 40 | // Range query to sum the elements present between ql to qr 41 | int query(int node, int beg, int end, int ql, int qr) 42 | { 43 | if(beg>qr || end=ql && end<=qr) 46 | return st[node]; 47 | int mid = beg + (end-beg)/2; 48 | return query(2*node+1,beg,mid,ql,qr) + query(2*node+2,mid+1,end,ql,qr); 49 | } 50 | 51 | int main() 52 | { 53 | // Input 54 | vector v {1,2,3,4,5}; 55 | 56 | int n = (int)v.size(); 57 | build_st(0,0,n-1,v); // Building the segment tree 58 | cout< 4 | #include 5 | 6 | using namespace std; 7 | 8 | struct t_edge{ 9 | int dis; 10 | int x, y; 11 | }; 12 | 13 | bool comp(t_edge a, t_edge b){ return a.dis < b.dis; } 14 | 15 | //-------------------- 16 | #define MAXN 50500 17 | #define MAXM 200200 18 | 19 | int n, m; // number of nodes and edges 20 | t_edge edges[MAXM]; 21 | 22 | // for the union find 23 | int father[MAXN]; 24 | 25 | // the tree 26 | t_edge mst[MAXM]; 27 | //-------------------- 28 | 29 | // union find functions 30 | int find(int x){ 31 | if(father[x] == x) return x; 32 | return father[x] = find(father[x]); 33 | } 34 | 35 | void join(int a, int b){ 36 | 37 | a = find(a); 38 | b = find(b); 39 | 40 | father[a] = b; 41 | 42 | } 43 | 44 | 45 | int main(){ 46 | 47 | // input 48 | cin >> n >> m; 49 | 50 | for(int i = 1;i <= m;i++) 51 | cin >> edges[i].x >> edges[i].y >> edges[i].dis; 52 | 53 | 54 | // initialize parents to union-find 55 | for(int i = 1;i <= n;i++) father[i] = i; 56 | 57 | // order ther edges 58 | sort(edges+1, edges+m+1, comp); 59 | 60 | int size = 0; 61 | for(int i = 1;i <= m;i++){ 62 | 63 | if( find(edges[i].x) != find(edges[i].y) ){ //if they are in separate components 64 | join(edges[i].x, edges[i].y); 65 | 66 | mst[++size] = edges[i]; 67 | } 68 | 69 | } 70 | 71 | // print the MST 72 | for(int i = 1;i < n;i++){ 73 | cout << mst[i].x << " " << mst[i].y << " " << mst[i].dis << "\n"; 74 | } 75 | 76 | return 0; 77 | } -------------------------------------------------------------------------------- /Dart/Sorting/quick_sort.dart: -------------------------------------------------------------------------------- 1 | /* This function takes last element as pivot, places 2 | the pivot element at its correct position in sorted 3 | array, and places all smaller (smaller than pivot) 4 | to left of pivot and all greater elements to right 5 | of pivot */ 6 | int partition(List arr, int low, int high) { 7 | int pivot = arr[high]; // pivot 8 | int i = (low - 1); // Index of smaller element 9 | int temp; 10 | 11 | for (int j = low; j <= high - 1; j++) { 12 | // If current element is smaller than the pivot 13 | if (arr[j] < pivot) { 14 | i++; // increment index of smaller element 15 | 16 | temp = arr[i]; 17 | arr[i] = arr[j]; 18 | arr[j] = temp; 19 | } 20 | } 21 | temp = arr[i + 1]; 22 | arr[i + 1] = arr[high]; 23 | arr[high] = temp; 24 | return (i + 1); 25 | } 26 | 27 | /* The main function that implements QuickSort 28 | arr[] --> Array to be sorted, 29 | low --> Starting index, 30 | high --> Ending index */ 31 | void quickSort(List arr, int low, int high) { 32 | if (low < high) { 33 | /* pi is partitioning index, arr[p] is now 34 | at right place */ 35 | int pi = partition(arr, low, high); 36 | 37 | // Separately sort elements before 38 | // partition and after partition 39 | quickSort(arr, low, pi - 1); 40 | quickSort(arr, pi + 1, high); 41 | } 42 | } 43 | 44 | /* Function to print an array */ 45 | void printArray(List arr) { 46 | int i; 47 | int size = arr.length; 48 | for (i = 0; i < size; i++) print("${arr[i]} "); 49 | print("\n"); 50 | } 51 | 52 | // Driver Code 53 | int main() { 54 | List arr = [10, 7, 8, 9, 1, 5]; 55 | int n = arr.length; 56 | quickSort(arr, 0, n - 1); 57 | print("Sorted array: \n"); 58 | printArray(arr); 59 | return 0; 60 | } 61 | -------------------------------------------------------------------------------- /C++/Dynamic Programming/fractional_knapsack.c: -------------------------------------------------------------------------------- 1 | #include 2 | #define MAX 10 3 | 4 | int n,W; 5 | double x[MAX]; 6 | 7 | struct knapsack 8 | { 9 | int v; 10 | int w; 11 | }K[MAX],temp; 12 | 13 | void fractional_knapsack() 14 | { 15 | int weight = 0; 16 | int i=0; 17 | while(weight + K[i].w <= W) 18 | { 19 | x[i] = 1; 20 | weight = weight + K[i].w; 21 | i++; 22 | } 23 | x[i] = (double)(W-weight)/K[i].w; 24 | 25 | } 26 | 27 | double calc() 28 | { 29 | double val = 0; 30 | int i; 31 | for(i=0;i r2) 63 | { 64 | max = j; 65 | } 66 | } 67 | temp = K[i]; 68 | K[i] = K[max]; 69 | K[max] = temp; 70 | } 71 | } 72 | 73 | 74 | 75 | void main() 76 | { 77 | int i; 78 | printf("Enter number of items:"); 79 | scanf("%d",&n); 80 | input_data(); 81 | printf("Enter the knapsack capacity:"); 82 | scanf("%d",&W); 83 | for(i=0;i 4 | using namespace std; 5 | 6 | void countSort(int array[], int size) { 7 | // The size of count must be at least the (max+1) but 8 | // we cannot assign declare it as int count(max+1) in C++ as 9 | // it does not support dynamic memory allocation. 10 | // So, its size is provided statically. 11 | int output[10]; 12 | int count[10]; 13 | int max = array[0]; 14 | 15 | // Find the largest element of the array 16 | for (int i = 1; i < size; i++) { 17 | if (array[i] > max) 18 | max = array[i]; 19 | } 20 | 21 | // Initialize count array with all zeros. 22 | for (int i = 0; i <= max; ++i) { 23 | count[i] = 0; 24 | } 25 | 26 | // Store the count of each element 27 | for (int i = 0; i < size; i++) { 28 | count[array[i]]++; 29 | } 30 | 31 | // Store the cummulative count of each array 32 | for (int i = 1; i <= max; i++) { 33 | count[i] += count[i - 1]; 34 | } 35 | 36 | // Find the index of each element of the original array in count array, and 37 | // place the elements in output array 38 | for (int i = size - 1; i >= 0; i--) { 39 | output[count[array[i]] - 1] = array[i]; 40 | count[array[i]]--; 41 | } 42 | 43 | // Copy the sorted elements into original array 44 | for (int i = 0; i < size; i++) { 45 | array[i] = output[i]; 46 | } 47 | } 48 | 49 | // Function to print an array 50 | void printArray(int array[], int size) { 51 | for (int i = 0; i < size; i++) 52 | cout << array[i] << " "; 53 | cout << endl; 54 | } 55 | 56 | // Driver code 57 | int main() { 58 | int array[] = {4, 2, 2, 8, 3, 3, 1}; 59 | int n = sizeof(array) / sizeof(array[0]); 60 | countSort(array, n); 61 | printArray(array, n); 62 | } -------------------------------------------------------------------------------- /C++/Graph Algorithms/cycle_in_undirected_graph.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | given an undirected graph, check whether the undirected graph has cycle 3 | */ 4 | 5 | #include 6 | #include 7 | 8 | using namespace std; 9 | 10 | class Graph{ 11 | 12 | int V; 13 | list *adj; 14 | bool isCyclicUtil(int v, bool visited[], int parent); 15 | 16 | 17 | public: 18 | Graph(int V); 19 | void addEdge(int v, int w); 20 | bool isCyclic(); 21 | }; 22 | 23 | Graph::Graph(int V){ 24 | this -> V = V; 25 | adj = new list[V]; 26 | } 27 | 28 | void Graph::addEdge(int v, int w){ 29 | adj[v].push_back(w); 30 | adj[w].push_back(v); 31 | } 32 | 33 | bool Graph::isCyclicUtil(int v, bool visited[], int parent){ 34 | visited[v] = true; 35 | 36 | list::iterator it; 37 | 38 | for(it = adj[v].begin(); it != adj[v].end(); it++){ 39 | if(!visited[*it]){ 40 | if(isCyclicUtil(*it, visited, v)) 41 | return true; 42 | } 43 | 44 | else if(*it != parent) { 45 | return true; 46 | } 47 | } 48 | return false; 49 | } 50 | 51 | bool Graph::isCyclic(){ 52 | bool *visited = new bool[V]; 53 | for(int i = 0; i < V; i++){ 54 | visited[i] = false; 55 | } 56 | 57 | for(int u = 0; u < V; u++){ 58 | if(!visited[u]){ 59 | if(isCyclicUtil(u, visited, -1)) 60 | return true; 61 | } 62 | } 63 | return false; 64 | } 65 | 66 | int main(){ 67 | Graph g1(5); 68 | g1.addEdge(1, 0); 69 | g1.addEdge(0, 2); 70 | g1.addEdge(2, 1); 71 | g1.addEdge(0, 3); 72 | g1.addEdge(3, 4); 73 | 74 | if(g1.isCyclic()){ 75 | cout<<"graph has cycle\n"; 76 | } 77 | else{ 78 | cout<<"graph has no cycle\n"; 79 | } 80 | return 0; 81 | } 82 | -------------------------------------------------------------------------------- /C++/Sorting/heap_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // To heapify a subtree rooted with node i which is 5 | // Heapify:- A process which helps regaining heap properties in tree after removal 6 | void heapify(int A[], int n, int i) 7 | { 8 | int largest = i; // Initialize largest as root 9 | int left_child = 2 * i + 1; // left = 2*i + 1 10 | int right_child = 2 * i + 2; // right = 2*i + 2 11 | 12 | // If left child is larger than root 13 | if (left_child < n && A[left_child] > A[largest]) 14 | largest = left_child; 15 | 16 | // If right child is larger than largest so far 17 | if (right_child < n && A[right_child] > A[largest]) 18 | largest = right_child; 19 | 20 | // If largest is not root 21 | if (largest != i) { 22 | swap(A[i], A[largest]); 23 | 24 | // Recursively heapify the affected sub-tree 25 | heapify(A, n, largest); 26 | } 27 | } 28 | 29 | // main function to do heap sort 30 | void heap_sort(int A[], int n) 31 | { 32 | // Build heap (rearrange array) 33 | for (int i = n / 2 - 1; i >= 0; i--) 34 | heapify(A, n, i); 35 | 36 | // One by one extract an element from heap 37 | for (int i = n - 1; i >= 0; i--) { 38 | // Move current root to end 39 | swap(A[0], A[i]); 40 | 41 | // call max heapify on the reduced heap 42 | heapify(A, i, 0); 43 | } 44 | } 45 | 46 | /* A function to print sorted Array */ 47 | void printArray(int A[], int n) 48 | { 49 | for (int i = 0; i < n; ++i) 50 | cout << A[i] << " "; 51 | cout << "\n"; 52 | } 53 | 54 | // Driver program 55 | int main() 56 | { 57 | int A[] = { 22, 19, 3, 25, 26, 7 }; // array to be sorted 58 | int n = sizeof(A) / sizeof(A[0]); // n is size of array 59 | 60 | heap_sort(A, n); 61 | 62 | cout << "Sorted array is \n"; 63 | printArray(A, n); 64 | } -------------------------------------------------------------------------------- /C++/Graph Algorithms/floyd_warshall.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | #define INF 99999 5 | #define V 4 6 | void printSolution(int dist[][V]); 7 | 8 | // All-pairs shortest path problem using Floyd Warshall algorithm 9 | void floydWarshall (int graph[][V]) 10 | { 11 | int dist[V][V], i, j, k; 12 | for (i = 0; i < V; i++) 13 | for (j = 0; j < V; j++) 14 | dist[i][j] = graph[i][j]; 15 | 16 | for (k = 0; k < V; k++) 17 | { 18 | // Select all vertices as source one by one 19 | for (i = 0; i < V; i++) 20 | { 21 | // Select all vertices as destination for the above picked source 22 | for (j = 0; j < V; j++) 23 | { 24 | // If vertex k is an intermediate edge on the shortest path from i to j, then update the value of dist[i][j] 25 | if (dist[i][k] + dist[k][j] < dist[i][j]) 26 | dist[i][j] = dist[i][k] + dist[k][j]; 27 | } 28 | } 29 | } 30 | 31 | printSolution(dist); 32 | } 33 | 34 | void printSolution(int dist[][V]) 35 | { 36 | cout<<"Shortest distances between every pair of vertices \n"; 37 | for (int i = 0; i < V; i++) 38 | { 39 | for (int j = 0; j < V; j++) 40 | { 41 | if (dist[i][j] == INF) 42 | cout<<"INF"<<" "; 43 | else 44 | cout< 5 | #include 6 | 7 | using namespace std; 8 | 9 | class Graph { 10 | int V; 11 | list *adj; 12 | bool isCyclicUtil(int v, bool visited[], bool* rs); 13 | 14 | public: 15 | Graph(int V); 16 | void addEdge(int v, int w); 17 | bool isCyclic(); 18 | }; 19 | 20 | Graph::Graph(int V){ 21 | this -> V = V; 22 | adj = new list [V]; 23 | } 24 | 25 | void Graph::addEdge(int v, int w){ 26 | adj[v].push_back(w); 27 | } 28 | 29 | bool Graph::isCyclicUtil(int v, bool visited[], bool* rs){ 30 | if(visited[v] == false){ 31 | visited[v] = true; 32 | rs[v] = true; 33 | 34 | list::iterator it; 35 | 36 | for(it = adj[v].begin(); it != adj[v].end(); it++){ 37 | if(!visited[*it] && isCyclicUtil(*it, visited, rs)) 38 | return true; 39 | else if(rs[*it]) 40 | return true; 41 | } 42 | } 43 | rs[v] = false; 44 | return false; 45 | } 46 | 47 | bool Graph::isCyclic(){ 48 | bool* visited = new bool[V]; 49 | bool* rs = new bool[V]; 50 | 51 | for(int i = 0; i < V; i++){ 52 | visited[i] = false; 53 | rs[i] = false; 54 | } 55 | 56 | for(int i = 0; i < V; i++){ 57 | if(isCyclicUtil(i, visited, rs)) 58 | return true; 59 | return false; 60 | } 61 | } 62 | 63 | int main(){ 64 | Graph g(4); 65 | g.addEdge(0, 1); 66 | g.addEdge(0, 2); 67 | g.addEdge(1, 2); 68 | g.addEdge(2, 0); 69 | g.addEdge(2, 3); 70 | g.addEdge(3, 3); 71 | 72 | if(g.isCyclic()) 73 | cout<<"This graph has cycle\n"; 74 | else 75 | { 76 | cout<<"this graph doesn't contain a cycle\n"; 77 | } 78 | return 0; 79 | } 80 | -------------------------------------------------------------------------------- /C++/Tree Alogrithms/binary_tree_from_inorder_preorder.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | struct Node { 6 | int data; 7 | Node* left; 8 | Node* right; 9 | 10 | Node(int value) { 11 | data = value; 12 | left = NULL; 13 | right = NULL; 14 | } 15 | }; 16 | 17 | 18 | void printLevelWithLine(Node *root) { 19 | if (root == NULL) { 20 | return; 21 | } 22 | queue q; 23 | 24 | q.push(root); 25 | while (!q.empty()) { 26 | int count = q.size(); 27 | for (int i = 0; i < count; ++i) { 28 | Node *curr = q.front(); 29 | q.pop(); 30 | cout << curr->data << " "; 31 | if (curr->left != NULL) { 32 | q.push(curr->left); 33 | } 34 | if (curr->right != NULL) { 35 | q.push(curr->right); 36 | } 37 | } 38 | cout << "\n"; 39 | } 40 | } 41 | 42 | 43 | int preIndex = 0; 44 | Node *binTreeInPre(int in[], int pre[], int indexStart, int indexEnd) { 45 | if (indexStart > indexEnd) { 46 | return NULL; 47 | } 48 | Node *root = new Node(pre[preIndex++]); 49 | 50 | int inIndex; 51 | // Can be replaced by hashmap for reducing time complexity 52 | for (int i = indexStart; i <= indexEnd; ++i) { 53 | if (in[i] == root->data) { 54 | inIndex = i; 55 | break; 56 | } 57 | } 58 | 59 | root->left = binTreeInPre(in, pre, indexStart, inIndex - 1); 60 | root->right = binTreeInPre(in, pre, inIndex + 1, indexEnd); 61 | 62 | return root; 63 | } 64 | 65 | 66 | int main() { 67 | int tSize; 68 | cout << "Enter size of tree: "; 69 | cin >> tSize; 70 | 71 | int in[tSize]; 72 | cout << "Enter inorder values: "; 73 | for (int i = 0; i < tSize; ++i) { 74 | cin >> in[i]; 75 | } 76 | 77 | int pre[tSize]; 78 | cout << "Enter preorder values: "; 79 | for (int i = 0; i < tSize; ++i) { 80 | cin >> pre[i]; 81 | } 82 | 83 | Node *root = binTreeInPre(in, pre, 0, tSize - 1); 84 | printLevelWithLine(root); 85 | 86 | return 0; 87 | } 88 | -------------------------------------------------------------------------------- /Python/Graph Algorithms/breadth_first_search.py: -------------------------------------------------------------------------------- 1 | # Python3 Program to print BFS traversal 2 | # from a given source vertex. BFS(int s) 3 | # traverses vertices reachable from s. 4 | from collections import defaultdict 5 | 6 | # This class represents a directed graph 7 | # using adjacency list representation 8 | class Graph: 9 | 10 | # Constructor 11 | def __init__(self): 12 | 13 | # default dictionary to store graph 14 | self.graph = defaultdict(list) 15 | 16 | # function to add an edge to graph 17 | def addEdge(self,u,v): 18 | self.graph[u].append(v) 19 | 20 | # Function to print a BFS of graph 21 | def BFS(self, s): 22 | 23 | # Mark all the vertices as not visited 24 | visited = [False] * (len(self.graph)) 25 | 26 | # Create a queue for BFS 27 | queue = [] 28 | 29 | # Mark the source node as 30 | # visited and enqueue it 31 | queue.append(s) 32 | visited[s] = True 33 | 34 | while queue: 35 | 36 | # Dequeue a vertex from 37 | # queue and print it 38 | s = queue.pop(0) 39 | print (s, end = " ") 40 | 41 | # Get all adjacent vertices of the 42 | # dequeued vertex s. If a adjacent 43 | # has not been visited, then mark it 44 | # visited and enqueue it 45 | for i in self.graph[s]: 46 | if visited[i] == False: 47 | queue.append(i) 48 | visited[i] = True 49 | 50 | # Driver code 51 | 52 | # Create a graph given in 53 | # the above diagram 54 | g = Graph() 55 | g.addEdge(0, 1) 56 | g.addEdge(0, 2) 57 | g.addEdge(1, 2) 58 | g.addEdge(2, 0) 59 | g.addEdge(2, 3) 60 | g.addEdge(3, 3) 61 | 62 | print ("Following is Breadth First Traversal" 63 | " (starting from vertex 2)") 64 | g.BFS(2) -------------------------------------------------------------------------------- /C++/Sorting/merge_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | void merge(int arr[], int l, int m, int r) 5 | { 6 | int i, j, k; 7 | int n1 = m - l + 1; 8 | int n2 = r - m; 9 | 10 | 11 | int L[n1], R[n2]; 12 | 13 | 14 | for (i = 0; i < n1; i++) 15 | L[i] = arr[l + i]; 16 | for (j = 0; j < n2; j++) 17 | R[j] = arr[m + 1+ j]; 18 | 19 | 20 | i = 0; 21 | j = 0; 22 | k = l; 23 | while (i < n1 && j < n2) 24 | { 25 | if (L[i] <= R[j]) 26 | { 27 | arr[k] = L[i]; 28 | i++; 29 | } 30 | else 31 | { 32 | arr[k] = R[j]; 33 | j++; 34 | } 35 | k++; 36 | } 37 | 38 | 39 | while (i < n1) 40 | { 41 | arr[k] = L[i]; 42 | i++; 43 | k++; 44 | } 45 | 46 | 47 | while (j < n2) 48 | { 49 | arr[k] = R[j]; 50 | j++; 51 | k++; 52 | } 53 | } 54 | 55 | 56 | void mergeSort(int arr[], int l, int r) 57 | { 58 | if (l < r) 59 | { 60 | 61 | int m = l+(r-l)/2; 62 | 63 | mergeSort(arr, l, m); 64 | mergeSort(arr, m+1, r); 65 | 66 | merge(arr, l, m, r); 67 | } 68 | } 69 | 70 | 71 | void print(int A[], int size) 72 | { 73 | int i; 74 | for (i=0; i < size; i++) 75 | cout< 4 | using namespace std; 5 | 6 | int binarySearch(int arr[], int, int, int); 7 | 8 | // Returns position of first occurrence of 9 | // x in array 10 | int exponentialSearch(int arr[], int n, int x) 11 | { 12 | // If x is present at firt location itself 13 | if (arr[0] == x) 14 | return 0; 15 | 16 | // Find range for binary search by 17 | // repeated doubling 18 | int i = 1; 19 | while (i < n && arr[i] <= x) 20 | i = i*2; 21 | 22 | // Call binary search for the found range. 23 | return binarySearch(arr, i/2, min(i, n), x); 24 | } 25 | 26 | // A recursive binary search function. It returns 27 | // location of x in given array arr[l..r] is 28 | // present, otherwise -1 29 | int binarySearch(int arr[], int l, int r, int x) 30 | { 31 | if (r >= l) 32 | { 33 | int mid = l + (r - l)/2; 34 | 35 | // If the element is present at the middle 36 | // itself 37 | if (arr[mid] == x) 38 | return mid; 39 | 40 | // If element is smaller than mid, then it 41 | // can only be present n left subarray 42 | if (arr[mid] > x) 43 | return binarySearch(arr, l, mid-1, x); 44 | 45 | // Else the element can only be present 46 | // in right subarray 47 | return binarySearch(arr, mid+1, r, x); 48 | } 49 | 50 | // We reach here when element is not present 51 | // in array 52 | return -1; 53 | } 54 | 55 | // Driver code 56 | int main(void) 57 | { cout<<"Enter size of array\n"; 58 | int n; 59 | cin>>n; 60 | int arr[n]; 61 | cout<<"Enter array elements"; 62 | for(int i=0;i>arr[i]; 65 | } 66 | int x; 67 | cout<<"Enter the Element you want to search\n"; 68 | cin>>x; 69 | int result = exponentialSearch(arr, n, x); 70 | (result == -1)? printf("Element is not present in array"): printf("Element is present at index %d",result); 71 | return 0; 72 | } 73 | -------------------------------------------------------------------------------- /JavaScript/README.md: -------------------------------------------------------------------------------- 1 |

JavaScript


2 | 3 |

4 | 5 | ## Table of Contents 6 | 7 | - [Graph Algorithms](#graph) 8 | - [Searching](#searching) 9 | - [Sorting](#sorting) 10 | - [Miscellaneous](#others) 11 | - [Unit Tests](#unit-tests) 12 | 13 | 14 | 15 | ## Graph Algorithms 16 | 17 | - [Breadth First Search](https://github.com/aniketsharma00411/algorithmsUse/blob/master/JavaScript/Sorting/bfs.js) 18 | 19 | 20 | 21 | ## Searching 22 | 23 | - [Binary Search](https://github.com/aniketsharma00411/algorithmsUse/blob/master/JavaScript/Searching/binary_search.js) 24 | 25 | - [Linear Search](https://github.com/aniketsharma00411/algorithmsUse/blob/master/JavaScript/Searching/linear_search.js) 26 | 27 | 28 | 29 | ## Sorting 30 | 31 | - [Bubble Sort](https://github.com/aniketsharma00411/algorithmsUse/blob/master/JavaScript/Sorting/bubble_sort.js) 32 | 33 | - [Insertion Sort](https://github.com/aniketsharma00411/algorithmsUse/blob/master/JavaScript/Sorting/insertion_sort.js) 34 | 35 | - [Merge Sort](https://github.com/aniketsharma00411/algorithmsUse/blob/master/JavaScript/Sorting/merge_sort.js) 36 | 37 | - [Quick Sort](https://github.com/aniketsharma00411/algorithmsUse/blob/master/JavaScript/Sorting/quick_sort.js) 38 | 39 | - [Radix Sort](https://github.com/aniketsharma00411/algorithmsUse/blob/master/JavaScript/Sorting/radix_sort.js) 40 | 41 | - [Selection Sort](https://github.com/aniketsharma00411/algorithmsUse/blob/master/JavaScript/Sorting/selection_sort.js) 42 | 43 | 44 | 45 | ## Miscellaneous 46 | - [Tower of Hanoi](https://github.com/aniketsharma00411/algorithmsUse/blob/master/JavaScript/Miscellaneous/tower_of_hanoi.js) 47 | 48 | 49 | 50 | ## Unit Tests 51 | 52 | -- 53 | -------------------------------------------------------------------------------- /Java/Sorting/quick_sort.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Scanner; 3 | 4 | public class quickSort { 5 | 6 | static void quick(int left , int right){ 7 | if(left>=right){ 8 | return; 9 | } 10 | // considering median/ mid value as pivot value 11 | int pivot = arr[(left+right)/2]; 12 | // here index is the will always return the updated index if swap occurs 13 | int index = part(left,right,pivot); 14 | // here the left-sub part will go for recursion 15 | quick(left,index-1); 16 | // here the right-sub part will go for recursion 17 | quick(index,right); 18 | 19 | } 20 | 21 | private static int part(int left, int right, int pivot) { 22 | while(left <= right){ 23 | // it will traverse array from front 24 | while(arr[left] < pivot){ 25 | left++; 26 | } 27 | // it will traverse array from the rear 28 | while(arr[right] > pivot){ 29 | right--; 30 | } 31 | // if front has element bigger than pivot and rear has element smaller than pivot then swap both 32 | if(left<=right){ 33 | swap(left ,right); 34 | left++; 35 | right--; 36 | } 37 | } 38 | return left; 39 | } 40 | 41 | private static void swap(int left, int right) { 42 | int temp = arr[left]; 43 | arr[left] = arr[right]; 44 | arr[right] = temp; 45 | } 46 | 47 | static void printEle(){ 48 | for(int a: arr) { 49 | System.out.print(a+", "); 50 | }System.out.println(); 51 | } 52 | 53 | 54 | static int [] arr; 55 | 56 | public static void main(String[] args) { 57 | Scanner sc = new Scanner(System.in); 58 | int n = sc.nextInt(); 59 | arr = new int[n]; 60 | for(int i=0;i 6 | using namespace std; 7 | 8 | // Function sort the array using Cycle sort 9 | void cycleSort(int arr[], int n) 10 | { 11 | // count number of memory writes 12 | int writes = 0; 13 | 14 | // traverse array elements and put it to on 15 | // the right place 16 | for (int cycle_start = 0; cycle_start <= n - 2; cycle_start++) 17 | { 18 | // initialize item as starting point 19 | int item = arr[cycle_start]; 20 | 21 | // Find position where we put the item. We basically 22 | // count all smaller elements on right side of item. 23 | int pos = cycle_start; 24 | for (int i = cycle_start + 1; i < n; i++) 25 | if (arr[i] < item) 26 | pos++; 27 | 28 | // If item is already in correct position 29 | if (pos == cycle_start) 30 | continue; 31 | 32 | // ignore all duplicate elements 33 | while (item == arr[pos]) 34 | pos += 1; 35 | 36 | // put the item to it's right position 37 | if (pos != cycle_start) 38 | { 39 | swap(item, arr[pos]); 40 | writes++; 41 | } 42 | 43 | // Rotate rest of the cycle 44 | while (pos != cycle_start) 45 | { 46 | pos = cycle_start; 47 | 48 | // Find position where we put the element 49 | for (int i = cycle_start + 1; i < n; i++) 50 | if (arr[i] < item) 51 | pos += 1; 52 | 53 | // ignore all duplicate elements 54 | while (item == arr[pos]) 55 | pos += 1; 56 | 57 | // put the item to it's right position 58 | if (item != arr[pos]) 59 | { 60 | swap(item, arr[pos]); 61 | writes++; 62 | } 63 | } 64 | } 65 | 66 | // Number of memory writes or swaps 67 | // cout << writes << endl ; 68 | } 69 | 70 | // Driver program to test above function 71 | int main() 72 | { 73 | int arr[] = { 1, 8, 3, 9, 10, 10, 2, 4 }; 74 | int n = sizeof(arr) / sizeof(arr[0]); 75 | cycleSort(arr, n); 76 | 77 | cout << "After sort : " << endl; 78 | for (int i = 0; i < n; i++) 79 | cout << arr[i] << " "; 80 | return 0; 81 | } 82 | -------------------------------------------------------------------------------- /C++/Math/matrix_exponentiation.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find value of f(n) where f(n) 2 | // is defined as 3 | // F(n) = F(n-1) + F(n-2) + F(n-3), n >= 3 4 | // Base Cases : 5 | // F(0) = 0, F(1) = 1, F(2) = 1 6 | #include 7 | #define ll long long 8 | using namespace std; 9 | 10 | // A utility function to multiply two matrices 11 | // a[][] and b[][]. Multiplication result is 12 | // stored back in b[][] 13 | void multiply(ll a[3][3], ll b[3][3]) 14 | { 15 | // Creating an auxiliary matrix to store elements 16 | // of the multiplication matrix 17 | ll mul[3][3]; 18 | for (ll i = 0; i < 3; i++) 19 | { 20 | for (ll j = 0; j < 3; j++) 21 | { 22 | mul[i][j] = 0; 23 | for (ll k = 0; k < 3; k++) 24 | mul[i][j] += a[i][k]*b[k][j]; 25 | } 26 | } 27 | 28 | // storing the multiplication result in a[][] 29 | for (ll i=0; i<3; i++) 30 | for (ll j=0; j<3; j++) 31 | a[i][j] = mul[i][j]; // Updating our matrix 32 | } 33 | 34 | // Function to compute F raise to power n-2. 35 | ll power(ll F[3][3], ll n) 36 | { 37 | ll M[3][3] = {{1,1,1}, {1,0,0}, {0,1,0}}; 38 | 39 | // Multiply it with initial values i.e with 40 | // F(0) = 0, F(1) = 1, F(2) = 1 41 | if (n==1) 42 | return F[0][0] + F[0][1]; 43 | 44 | power(F, n/2); 45 | 46 | multiply(F, F); 47 | 48 | if (n%2 != 0) 49 | multiply(F, M); 50 | 51 | // Multiply it with initial values i.e with 52 | // F(0) = 0, F(1) = 1, F(2) = 1 53 | return F[0][0] + F[0][1] ; 54 | } 55 | 56 | // Return n'th term of a series defined using below 57 | // recurrence relation. 58 | // f(n) is defined as 59 | // f(n) = f(n-1) + f(n-2) + f(n-3), n>=3 60 | // Base Cases : 61 | // f(0) = 0, f(1) = 1, f(2) = 1 62 | ll findNthTerm(ll n) 63 | { 64 | 65 | ll F[3][3] = {{1,1,1}, {1,0,0}, {0,1,0}} ; 66 | 67 | //Base cases 68 | if(n==0) 69 | return 0; 70 | if(n==1 || n==2) 71 | return 1; 72 | 73 | return power(F, n-2); 74 | } 75 | 76 | int main() 77 | { 78 | ll n = 10; 79 | cout << "F(10) is " << findNthTerm(n); 80 | return 0; 81 | } -------------------------------------------------------------------------------- /C++/Tree Alogrithms/inverse_binary_tree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | typedef struct node 6 | { 7 | int val; 8 | node* left; 9 | node* right; 10 | }node; 11 | 12 | /* Helper function that allocates a new node with 13 | the given data and NULL left and right pointers. */ 14 | node* createNode(int data){ 15 | node* newNode = new node(); 16 | newNode -> right = NULL; 17 | newNode -> left = NULL; 18 | newNode -> val = data; 19 | return newNode; 20 | } 21 | 22 | 23 | /* Change a tree so that the roles of the left and 24 | right pointers are swapped at every node. 25 | 26 | So the tree... 27 | 4 28 | / \ 29 | 2 5 30 | / \ 31 | 1 3 32 | 33 | is changed to... 34 | 4 35 | / \ 36 | 5 2 37 | / \ 38 | 3 1 39 | */ 40 | void mirror(node* root) 41 | { 42 | if (root == NULL) 43 | return; 44 | else 45 | { 46 | node* temp; 47 | 48 | /* do the subtrees */ 49 | mirror(root->left); 50 | mirror(root->right); 51 | 52 | /* swap the pointers in this node */ 53 | temp = root->left; 54 | root->left = root->right; 55 | root->right = temp; 56 | } 57 | } 58 | 59 | /* Helper function to print 60 | Inorder traversal.*/ 61 | void inOrder(node* root) 62 | { 63 | if ( root == NULL) 64 | return; 65 | 66 | inOrder(root->left); 67 | cout << root -> val << " "; 68 | inOrder(root->right); 69 | } 70 | 71 | 72 | // Driver Code 73 | int main() 74 | { 75 | node *root = createNode(1); 76 | root->left = createNode(2); 77 | root->right = createNode(3); 78 | root->left->left = createNode(4); 79 | root->left->right = createNode(5); 80 | 81 | /* Print inorder traversal of the input tree */ 82 | cout << "Inorder traversal of the constructed" 83 | << " tree is" << endl; 84 | inOrder(root); 85 | 86 | /* Convert tree to its mirror */ 87 | mirror(root); 88 | 89 | /* Print inorder traversal of the mirror tree */ 90 | cout << "\nInorder traversal of the mirror tree" 91 | << " is \n"; 92 | inOrder(root); 93 | 94 | return 0; 95 | } -------------------------------------------------------------------------------- /JavaScript/Graph Algorithms/bfs.js: -------------------------------------------------------------------------------- 1 | /* Graphs: Breadth-first search */ 2 | //this function will output a object of key value pair where key is the node and value is the distance from the root node. 3 | function bfs(graph, root) { 4 | var nodesLen = {};//this object is used to store the distances to the root node 5 | 6 | for (var i = 0; i < graph.length; i++) { 7 | nodesLen[i] = Infinity; 8 | } 9 | //set all distances at infinity,incase if a node is not reachable from root node 10 | nodesLen[root] = 0; //distances from root node to root node is zero 11 | 12 | var queue = [root]; //queue to keep in track of nodes to visit 13 | var current; //current node we are traversing 14 | 15 | while (queue.length != 0)//keep traversing the nodes until no more node in the queue is left to traverse 16 | { 17 | current = queue.shift();//poping of the node from queue to traverse 18 | 19 | var curConnected = graph[current];//store all the nodes connected to the current node,at beginning is root node 20 | var neighborIdx = []; //to store the list of nodes connected to current node 21 | var idx = curConnected.indexOf(1); // find the first node connected to the current node from curconnected array and store it in idx. 1 means connected.If there is no connection indexOf return -1 22 | while (idx != -1)// if indexOf doesn't return -1 23 | { 24 | neighborIdx.push(idx); 25 | idx = curConnected.indexOf(1, idx + 1); //look for the next connected node 26 | } 27 | 28 | for (var j = 0; j < neighborIdx.length; j++) { 29 | if (nodesLen[neighborIdx[j]] == Infinity) //initially its infinity 30 | { 31 | nodesLen[neighborIdx[j]] = nodesLen[current] + 1;//set the distance 32 | queue.push(neighborIdx[j]); //push the neighbouring nodes to the queue to visit them next 33 | } 34 | } 35 | } 36 | return nodesLen; 37 | }; 38 | 39 | var exBFSGraph = [ 40 | [0, 1, 1, 1, 0], 41 | [0, 0, 1, 0, 0], 42 | [1, 1, 0, 0, 0], 43 | [0, 0, 0, 1, 0], 44 | [0, 1, 0, 0, 0] 45 | ]; 46 | 47 | console.log(bfs(exBFSGraph, 1));//sending 1 as root node to bfs function. Trying to find how far every node is from the node 1 -------------------------------------------------------------------------------- /C++/Math/nCr_mod_prime.cpp: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Author: Ahmed Elsisy 4 | * Date: 20/10/2020 5 | * Description: Given N and R returns N choose R (how many ways to choose R elements from N elements) 6 | * using pre-processing factorials and inverse of factorials and answering nCr in O(1), just pass to the constructor 7 | * maximum N you will query for and prime number as a mod 8 | * 9 | * Memory: O(N) 10 | * Time: O(N) for pre-processing factorials and O(1) for answering query nCr(N,R) 11 | * Status: stress-tested for n <= 200000 12 | */ 13 | class nCr_mod{ 14 | private: 15 | vector factorial; // (i!) % mod for all i less than max_n 16 | vector inverse_factorial; // (1 / (i!)) % mod for all i less than max_n 17 | int mod , max_n; 18 | int multiply_mod(int x , int y){ // returns x*y % mod 19 | return (1LL * (x % mod) * (y % mod)) % mod; 20 | } 21 | int power_mod(int x , int y){ // returns x^y % mod 22 | if(y == 0)return 1; 23 | if(y % 2 == 1)return multiply_mod(x , power_mod(x , y - 1)); 24 | int r = power_mod(x , y / 2); 25 | return multiply_mod(r , r); 26 | } 27 | void pre_process() { // pre-processing factorial,inverse_factorial vectors by their values 28 | factorial.resize(max_n); 29 | inverse_factorial.resize(max_n); 30 | factorial[0] = inverse_factorial[0] = 1; 31 | for (int i = 1; i < max_n; ++i) 32 | factorial[i] = multiply_mod(i % mod, factorial[i - 1]); 33 | 34 | inverse_factorial[max_n - 1] = power_mod(factorial[max_n - 1], mod - 2); 35 | for (int i = max_n - 2; i >= 0; --i) 36 | inverse_factorial[i] = multiply_mod(inverse_factorial[i + 1], (i + 1) % mod); 37 | } 38 | public: 39 | nCr_mod(int maximum_N , int prime_mod){ 40 | mod = prime_mod; 41 | max_n = maximum_N + 1; 42 | pre_process(); 43 | } 44 | int nCr(int N , int R){ // returns nCr (how many ways to choose R objects from N objects) which is equal to (N! / ((N - R)! * R!) 45 | if(R < 0 || R > N)return 0; 46 | int value = multiply_mod(factorial[N] , inverse_factorial[R]); 47 | return multiply_mod(value , inverse_factorial[N - R]); 48 | } 49 | }; 50 | 51 | /* 52 | * input: nCr(5,3) 53 | * output: 10 54 | * nCr(5,3) = 5! / (2! * 3!) = 10 55 | */ -------------------------------------------------------------------------------- /C++/Searching/depth_first_search.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to print DFS traversal from 2 | // a given vertex in a given graph 3 | #include 4 | using namespace std; 5 | 6 | // Graph class represents a directed graph 7 | // using adjacency list representation 8 | class Graph 9 | { 10 | int V; // No. of vertices 11 | 12 | // Pointer to an array containing 13 | // adjacency lists 14 | list *adj; 15 | 16 | // A recursive function used by DFS 17 | void DFSUtil(int v, bool visited[]); 18 | public: 19 | Graph(int V); // Constructor 20 | 21 | // function to add an edge to graph 22 | void addEdge(int v, int w); 23 | 24 | // DFS traversal of the vertices 25 | // reachable from v 26 | void DFS(int v); 27 | }; 28 | 29 | Graph::Graph(int V) 30 | { 31 | this->V = V; 32 | adj = new list[V]; 33 | } 34 | 35 | void Graph::addEdge(int v, int w) 36 | { 37 | adj[v].push_back(w); // Add w to v’s list. 38 | } 39 | 40 | void Graph::DFSUtil(int v, bool visited[]) 41 | { 42 | // Mark the current node as visited and 43 | // print it 44 | visited[v] = true; 45 | cout << v << " "; 46 | 47 | // Recur for all the vertices adjacent 48 | // to this vertex 49 | list::iterator i; 50 | for (i = adj[v].begin(); i != adj[v].end(); ++i) 51 | if (!visited[*i]) 52 | DFSUtil(*i, visited); 53 | } 54 | 55 | // DFS traversal of the vertices reachable from v. 56 | // It uses recursive DFSUtil() 57 | void Graph::DFS(int v) 58 | { 59 | // Mark all the vertices as not visited 60 | bool *visited = new bool[V]; 61 | for (int i = 0; i < V; i++) 62 | visited[i] = false; 63 | 64 | // Call the recursive helper function 65 | // to print DFS traversal 66 | DFSUtil(v, visited); 67 | } 68 | 69 | 70 | int main() 71 | { 72 | 73 | 74 | int n=100,ch=1; 75 | cout<<"Enter n.o of vertices\n"; 76 | cin>>n; 77 | Graph g(n); 78 | do 79 | { int a,b; 80 | cout<<"Enter 2 vertices between which you want to add edge\n"; 81 | cin>>a>>b; 82 | g.addEdge(a,b); 83 | cout<<"You want to add new edge press 1 \n"; 84 | cin>>ch; 85 | } 86 | while(ch==1); 87 | int dfs_node; 88 | cout<<"Enter DFS starting vertex"; 89 | cin>>dfs_node; 90 | cout << "Following is Depth First Traversal " 91 | << "(starting from vertex "< 7 | #define N 15 // default size for 15 to init the array to zeros 8 | int main(){ 9 | int i,j,k,t,t1,bt[N]={0},at[N]={0},tat[N]={0},wt[N]={0},ct[N]={0}; 10 | int n,tBT=0,time=0, swap; 11 | float sumtat=0,sumwt=0; 12 | 13 | printf("Enter total process: "); 14 | scanf("%d",&n); 15 | 16 | for(i=0;i at[j]){ 29 | t = at[i]; 30 | t1 = bt[i]; 31 | at[i] = at[j]; 32 | bt[i] = bt[j]; 33 | at[j] = t; 34 | bt[j] = t1; 35 | } 36 | } 37 | } 38 | 39 | k=1; 40 | //checking burst time and sorting 41 | for(j=0;j=at[i] && bt[i] 5 | #include 6 | 7 | using namespace std; 8 | 9 | // This class represents a directed graph using 10 | // adjacency list representation 11 | class Graph 12 | { 13 | int V; // No. of vertices 14 | 15 | // Pointer to an array containing adjacency 16 | // lists 17 | list *adj; 18 | public: 19 | Graph(int V); // Constructor 20 | 21 | // function to add an edge to graph 22 | void addEdge(int v, int w); 23 | 24 | // prints BFS traversal from a given source s 25 | void BFS(int s); 26 | }; 27 | 28 | Graph::Graph(int V) 29 | { 30 | this->V = V; 31 | adj = new list[V]; 32 | } 33 | 34 | void Graph::addEdge(int v, int w) 35 | { 36 | adj[v].push_back(w); // Add w to v’s list. 37 | } 38 | 39 | void Graph::BFS(int s) 40 | { 41 | // Mark all the vertices as not visited 42 | bool *visited = new bool[V]; 43 | for(int i = 0; i < V; i++) 44 | visited[i] = false; 45 | 46 | // Create a queue for BFS 47 | list queue; 48 | 49 | // Mark the current node as visited and enqueue it 50 | visited[s] = true; 51 | queue.push_back(s); 52 | 53 | // 'i' will be used to get all adjacent 54 | // vertices of a vertex 55 | list::iterator i; 56 | 57 | while(!queue.empty()) 58 | { 59 | // Dequeue a vertex from queue and print it 60 | s = queue.front(); 61 | cout << s << " "; 62 | queue.pop_front(); 63 | 64 | // Get all adjacent vertices of the dequeued 65 | // vertex s. If a adjacent has not been visited, 66 | // then mark it visited and enqueue it 67 | for (i = adj[s].begin(); i != adj[s].end(); ++i) 68 | { 69 | if (!visited[*i]) 70 | { 71 | visited[*i] = true; 72 | queue.push_back(*i); 73 | } 74 | } 75 | } 76 | } 77 | 78 | // Driver program to test methods of graph class 79 | int main() 80 | { 81 | 82 | 83 | int n=100,ch=1; 84 | cout<<"Enter n.o of vertices\n"; 85 | cin>>n; 86 | Graph g(n); 87 | do 88 | { int a,b; 89 | cout<<"Enter 2 vertices between which you want to add edge\n"; 90 | cin>>a>>b; 91 | g.addEdge(a,b); 92 | cout<<"You want to add new edge press 1\n"; 93 | cin>>ch; 94 | } 95 | while(ch==1); 96 | int bfs_node; 97 | cout<<"Enter BFS starting vertex"; 98 | cin>>bfs_node; 99 | cout << "Following is Breadth First Traversal " 100 | << "(starting from vertex "< 2 | using namespace std; 3 | 4 | // This algorithm is very useful for coding interviews. 5 | // This algorithm can can solve the searching problem in O(n+m) time, 6 | // where length of the pattern to be search is n and the string in which 7 | // it has to be search is of length m. 8 | 9 | // How it works: 10 | 11 | // Let us assume that a string s has to be searched in t. 12 | // Now we build an array where we store the length of proper suffix 13 | // ending at every index where the suffix is also equal to prefix. 14 | 15 | // Let us assume that we have a string such as s+"#"+t, where # is just a delimeter. 16 | // So further if we get a length of suffix at any position in t where the suffix 17 | // is equal to prefix. Then we have found a pattern of s in t with position beginning at 18 | // pos - s.length() where pos is the last position where last character of s matched. 19 | 20 | 21 | 22 | // Implementation begins: 23 | // creating the suffix length array for s 24 | vector KMPpreprocessing (string s) { 25 | int n = s.length(); 26 | // creating a vector to store the length of suffix which is also a prefix with 27 | // respect to the very beginning of string s 28 | vector P(n); 29 | // first position should be always assigned 0 30 | P[0]=0; 31 | for (int i=1; i 0 && s[i] != s[j]) 36 | j = P[j-1]; 37 | if (P[i] == P[j]) ++j; 38 | P[i] = j; 39 | } 40 | return P; 41 | } 42 | 43 | // Function for string searching 44 | void KMPSearching(string s, string t) 45 | { 46 | // The vector which will get the suffix length 47 | // which is also a prefix. 48 | vector v = KMPpreprocessing(s); 49 | int m = s.length(); 50 | int n = t.length(); 51 | 52 | int i = 0; // index for t 53 | int j = 0; // index for s 54 | while (i < t.length()) { 55 | if (s[j] == t[i]) { 56 | j++; 57 | i++; 58 | } 59 | 60 | if (j == m) { 61 | printf("Found the pattern at index: %d ", i - j); 62 | j = v[j - 1]; 63 | } 64 | 65 | // mismatch after j matches 66 | else if (i < n && s[j] != t[i]) { 67 | // Do not match v[0..v[j-1]] characters, 68 | // they will match anyway 69 | if (j != 0) 70 | j = v[j - 1]; 71 | else 72 | i = i + 1; 73 | } 74 | } 75 | } 76 | 77 | int main(){ 78 | // sample inputs 79 | string t = "I Love HacktoberFest2020"; 80 | string s = "Love"; 81 | KMPSearching(s,t); 82 | return 0; 83 | } -------------------------------------------------------------------------------- /C++/Graph Algorithms/hamiltonian_path_cycle.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | HAMILTONIAN PATH AND CYCLE: 3 | 4 | A Hamiltonian path, is a path in an undirected or directed graph that visits each vertex exactly once. 5 | Given an undirected graph the task is to check if a Hamiltonian path is present in it or not. 6 | 7 | **** Difference between Hamiltonian Path And Hamiltonian Cycle 8 | 9 | In Hamiltonian Cycle every vertex must be traversed exactly once without the edges being repeated. Starting and ending vertices must be same. 10 | In Hamiltonian Path every vertex must be traversed exactly once without the edges being repeated. Starting and ending vertices may be different. 11 | 12 | */ 13 | 14 | #include 15 | using namespace std; 16 | 17 | //isSafe function to check the path and position is valid or not 18 | bool isSafe(int **graph, int v, int path[], int pos, int V) 19 | { 20 | 21 | if (graph[path[pos - 1]][v] == 0) 22 | return false; 23 | 24 | for (int i = 0; i < pos; i++) 25 | { 26 | if (path[i] == v) 27 | return false; 28 | } 29 | 30 | return true; 31 | } 32 | 33 | //Hamiltonian Path function 34 | bool Hamilton(int **graph, int path[], int pos, int V) 35 | { 36 | 37 | if (pos == V) 38 | return true; 39 | 40 | for (int v = 0; v < V; v++) 41 | { 42 | if (isSafe(graph, v, path, pos, V)) 43 | { 44 | path[pos] = v; 45 | if (Hamilton(graph, path, pos + 1, V)) 46 | return true; 47 | path[pos] = -1; 48 | } 49 | } 50 | 51 | return false; 52 | } 53 | 54 | //Hamiltonian Cycle function 55 | void HamiltonCycle(int **graph, int V) 56 | { 57 | 58 | //path array to check if the same path is not visited again 59 | int path[V]; 60 | memset(path, -1, sizeof(path)); 61 | 62 | for (int i = 0; i < V; i++) 63 | { 64 | path[0] = i; 65 | 66 | if (Hamilton(graph, path, 1, V)) 67 | { 68 | cout << 1; 69 | return; 70 | } 71 | } 72 | 73 | cout << 0; 74 | return; 75 | } 76 | 77 | //main function 78 | int main() 79 | { 80 | 81 | //vertex : no of vertices and edges = no of edges 82 | int vertex, edges; 83 | 84 | //input vertex and edges 85 | cin >> vertex >> edges; 86 | 87 | int **graph = new int *[vertex]; 88 | 89 | for (int i = 0; i < vertex; i++) 90 | graph[i] = new int[vertex]; 91 | 92 | for (int i = 0; i < edges; i++) 93 | { 94 | 95 | int x, y; 96 | cin >> x >> y; 97 | graph[x - 1][y - 1] = 1; 98 | graph[y - 1][x - 1] = 1; 99 | } 100 | 101 | HamiltonCycle(graph, vertex); 102 | 103 | cout << endl; 104 | 105 | return 0; 106 | } 107 | -------------------------------------------------------------------------------- /Rust/Sorting/merge_sort.rs: -------------------------------------------------------------------------------- 1 | /// Mergesort. 2 | 3 | /// - Top-down 4 | 5 | /// - Recursive 6 | 7 | pub fn mergesort(arr: &mut [i32]) { 8 | let mid = arr.len() / 2; 9 | if mid == 0 { 10 | return; 11 | } 12 | 13 | mergesort(&mut arr[..mid]); 14 | mergesort(&mut arr[mid..]); 15 | 16 | // Create an array to store intermediate result. 17 | let mut ret = arr.to_vec(); 18 | 19 | // Merge the two piles. 20 | merge(&arr[..mid], &arr[mid..], &mut ret[..]); 21 | 22 | // Copy back the result back to original array. 23 | arr.copy_from_slice(&ret); 24 | } 25 | 26 | /// Mergesort bottom-up version. 27 | 28 | /// - Buttom-up (for array-based data structure) 29 | 30 | /// - Iterative 31 | pub fn mergesort_bottom_up(arr: &mut [i32]) { 32 | let mut width = 1; 33 | // Create an array to store intermediate result. 34 | let mut ret = arr.to_vec(); 35 | let len = arr.len(); 36 | 37 | while width < len { 38 | let mut i = 0; 39 | while i < len { 40 | // Check to avoid upper bound and middle index out of bound. 41 | let upper = ::std::cmp::min(i + 2 * width, len); 42 | let mid = ::std::cmp::min(i + width, len); 43 | 44 | merge(&arr[i..mid], &arr[mid..upper], &mut ret[i..upper]); 45 | 46 | // Copy the merged result back to original array. 47 | arr[i..upper].copy_from_slice(&ret[i..upper]); 48 | 49 | // Increase start index to merge next two subsequences. 50 | i += 2 * width; 51 | } 52 | width *= 2; 53 | } 54 | } 55 | 56 | /// Merge helper. 57 | 58 | /// * `arr1` - Left pile to sort. 59 | 60 | /// * `arr2` - Right pile to sort. 61 | 62 | /// * `ret` - Result array to return 63 | 64 | fn merge(arr1: &[i32], arr2: &[i32], ret: &mut [i32]) { 65 | let mut left = 0; // Head of left pile. 66 | let mut right = 0; // Head of right pile. 67 | let mut index = 0; 68 | 69 | // Compare element and insert back to result array. 70 | while left < arr1.len() && right < arr2.len() { 71 | if arr1[left] <= arr2[right] { 72 | ret[index] = arr1[left]; 73 | index += 1; 74 | left += 1; 75 | } else { 76 | ret[index] = arr2[right]; 77 | index += 1; 78 | right += 1; 79 | } 80 | } 81 | 82 | // Copy the reset elements to returned array. 83 | // `memcpy` may be more performant than for-loop assignment. 84 | if left < arr1.len() { 85 | ret[index..].copy_from_slice(&arr1[left..]); 86 | } 87 | if right < arr2.len() { 88 | ret[index..].copy_from_slice(&arr2[right..]); 89 | } 90 | } 91 | 92 | #[cfg(test)] 93 | 94 | mod base { 95 | use super::*; 96 | base_cases!(mergesort); 97 | } 98 | 99 | #[cfg(test)] 100 | 101 | mod bottom_up { 102 | use super::*; 103 | base_cases!(mergesort_bottom_up); 104 | } -------------------------------------------------------------------------------- /C++/Graph Algorithms/flood_fill_algorithm.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | FLOOD FILL ALGORITHM : 3 | TIME COMPLEXITY : O(n^2) 4 | 5 | Given a 2D screen arr[][] where each arr[i][j] is an integer representing the colour of that pixel, also given the location of a pixel (X, Y) and a colour C, 6 | the task is to replace the colour of the given pixel and all the adjacent same-coloured pixels with the given colour. 7 | 8 | Example: 9 | 10 | Input: arr[][] = { 11 | {1, 1, 1, 1, 1, 1, 1, 1}, 12 | {1, 1, 1, 1, 1, 1, 0, 0}, 13 | {1, 0, 0, 1, 1, 0, 1, 1}, 14 | {1, 2, 2, 2, 2, 0, 1, 0}, 15 | {1, 1, 1, 2, 2, 0, 1, 0}, 16 | {1, 1, 1, 2, 2, 2, 2, 0}, 17 | {1, 1, 1, 1, 1, 2, 1, 1}, 18 | {1, 1, 1, 1, 1, 2, 2, 1}} 19 | X = 4, Y = 4, C = 3 20 | Output: 21 | 1 1 1 1 1 1 1 1 22 | 1 1 1 1 1 1 0 0 23 | 1 0 0 1 1 0 1 1 24 | 1 3 3 3 3 0 1 0 25 | 1 1 1 3 3 0 1 0 26 | 1 1 1 3 3 3 3 0 27 | 1 1 1 1 1 3 1 1 28 | 1 1 1 1 1 3 3 1 29 | Explanation: 30 | The values in the given 2D screen indicate colours of the pixels. X and Y are coordinates of the brush, C is the colour that should replace the previous colour 31 | on screen[X][Y] and all surrounding pixels with the same colour. Hence all the 2 are replaced with 3. 32 | */ 33 | 34 | #include 35 | using namespace std; 36 | 37 | //check is for checking that if moving direction is valid or not 38 | bool check(int i, int j, int n, int m, vector> visit) 39 | { 40 | if (i < 0 || j < 0 || i >= n || j >= m || visit[i][j] == true) 41 | return false; 42 | return true; 43 | } 44 | 45 | //flood fill algorithm is implmented using dfs algorithms 46 | void dfs(vector> &a, int i, int j, int pix, int k, int n, int m, vector> &visit) 47 | { 48 | if (check(i, j, n, m, visit) && a[i][j] == pix) 49 | { 50 | a[i][j] = k; 51 | visit[i][j] = true; 52 | dfs(a, i - 1, j, pix, k, n, m, visit); 53 | dfs(a, i + 1, j, pix, k, n, m, visit); 54 | dfs(a, i, j + 1, pix, k, n, m, visit); 55 | dfs(a, i, j - 1, pix, k, n, m, visit); 56 | } 57 | } 58 | 59 | int main() 60 | { 61 | int n, m, isrc, jsrc, k; 62 | 63 | //n,m are rows and column of matrix a 64 | cin >> n >> m; 65 | 66 | vector> a(n, vector(m, 0)); 67 | 68 | //visited matrix to check of the vertes is previuosly visited or not 69 | vector> visit(n, vector(m, false)); 70 | 71 | for (int i = 0; i < n; i++) 72 | { 73 | for (int j = 0; j < m; j++) 74 | { 75 | cin >> a[i][j]; 76 | } 77 | } 78 | 79 | //isrc , jsrc are sourc element indices 80 | // k is the value with whch the pixel to be replaced 81 | cin >> isrc >> jsrc >> k; 82 | 83 | //dfs algorithm 84 | dfs(a, isrc, jsrc, a[isrc][jsrc], k, n, m, visit); 85 | 86 | //printing the resultant matrix 87 | for (int i = 0; i < n; i++) 88 | { 89 | for (int j = 0; j < m; j++) 90 | { 91 | cout << a[i][j] << " "; 92 | } 93 | cout << endl; 94 | } 95 | cout << endl; 96 | } 97 | -------------------------------------------------------------------------------- /C++/Graph Algorithms/min_cost_path_of_graph.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Minimum Cost Path in given graph: 4 | 5 | TIME COMPLEXITY : O(n^2) 6 | 7 | Given a square grid of size N, each cell of which contains integer cost which represents a cost to traverse through that cell, 8 | we need to find a path from top left cell to bottom right cell by which total cost incurred is minimum. 9 | You can move in 4 directions : up, down, left an right. 10 | 11 | output a single integer depecting the minimum cost to reach the destination. 12 | 13 | Example: 14 | 15 | Grid is: 16 | 31, 100, 65, 12, 18, 17 | 10, 13, 47, 157, 6, 18 | 100. 113, 174, 11, 33, 19 | 88, 124, 41, 20, 140, 20 | 99, 32, 111, 41, 20 21 | A cost grid is given in below diagram, minimum 22 | cost to reach bottom right from top left 23 | is 327 (31 + 10 + 13 + 47 + 65 + 12 + 18 + 6 + 33 + 11 + 20 + 41 + 20) 24 | 25 | */ 26 | 27 | #include 28 | using namespace std; 29 | 30 | //valid directions to move in 31 | int rowN[] = {-1,1,0,0}; 32 | int colN[] = {0,0,1,-1}; 33 | 34 | 35 | //min Cost path in a graph 36 | int minCostPath(int **graph, int **dist, int n) 37 | { 38 | //queue 39 | queue> q; 40 | 41 | dist[0][0] = graph[0][0]; 42 | q.push({0,0}); 43 | 44 | while(!q.empty()) 45 | { 46 | pair p = q.front(); 47 | 48 | int a = p.first; 49 | int b = p.second; 50 | q.pop(); 51 | 52 | for(int i=0;i<4;i++) 53 | { 54 | int x = a + rowN[i]; 55 | int y = b + colN[i]; 56 | 57 | if(x>=0 && x=0 && ydist[a][b]+graph[x][y]) 58 | { 59 | dist[x][y] = dist[a][b] + graph[x][y]; 60 | q.push({x,y}); 61 | } 62 | } 63 | 64 | } 65 | //return the min cost to reach from top left [0][0] to bottom right [n-1][n-1] 66 | return dist[n-1][n-1]; 67 | } 68 | 69 | //main function 70 | int main() 71 | { 72 | //n is dimensions of graph matrix 73 | int n; 74 | cin>>n; 75 | 76 | //graph matrix with cost 77 | int **graph=new int*[n]; 78 | 79 | //input matrix 80 | for(int i=0;i>graph[i][j]; 86 | } 87 | } 88 | 89 | //distance matrix to store the min cost to reach any node in graph 90 | int **dist=new int*[n]; 91 | 92 | for(int i = 0; i 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | template 8 | class Graph 9 | { 10 | unordered_map>> adjList; 11 | public: 12 | void addEdge(t u,t v,int dist,bool biDir=true) 13 | { 14 | adjList[u].push_back(make_pair(v,dist)); 15 | if(biDir) 16 | { 17 | adjList[v].push_back(make_pair(u,dist)); 18 | } 19 | } 20 | void printAdj() 21 | { 22 | for(auto x:adjList) 23 | { 24 | cout<"; 25 | for(auto y:x.second) 26 | { 27 | cout<<" "<dist; 35 | for(auto x:adjList) 36 | { 37 | dist[x.first] = INT_MAX; 38 | } 39 | //the dist(int) is kept first because set sorts o the basis of first element in case 40 | //of a pair 41 | set>s; 42 | dist[src] = 0; 43 | s.insert(make_pair(0,src)); 44 | while(!s.empty()) 45 | { 46 | auto p = *(s.begin()); 47 | t node = p.second; 48 | int child_dist = p.first; 49 | s.erase(s.begin()); 50 | //iterate over neighbour of current node 51 | for(auto x:adjList[node]) 52 | { 53 | if(child_dist + x.secondg; 79 | g.addEdge(1,2,1); 80 | g.addEdge(1,3,4); 81 | g.addEdge(2,3,1); 82 | g.addEdge(3,4,2); 83 | g.addEdge(1,4,7); 84 | g.printAdj(); 85 | g.Dijsktrassssp(1);*/ 86 | Graphg; 87 | g.addEdge("Amritsar","Delhi",1); 88 | g.addEdge("Amritsar","Jaipur",4); 89 | g.addEdge("Jaipur","Delhi",2); 90 | g.addEdge("Jaipur","Mumbai",8); 91 | g.addEdge("Mumbai","Bhopal",3); 92 | g.addEdge("Bhopal","Agra",2); 93 | g.addEdge("Agra","Delhi",1); 94 | //g.printAdj(); 95 | g.Dijsktrassssp("Amritsar"); 96 | return 0; 97 | } -------------------------------------------------------------------------------- /C++/Graph Algorithms/prim.cpp: -------------------------------------------------------------------------------- 1 | // Minimum Spanning Tree (MST) - Prim 2 | // Time Complexity: O(MlogN) 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | using namespace std; 9 | 10 | typedef pair pii; 11 | //--------------------- 12 | #define MAXN 10100 13 | // As there is no Infinite on the computer, we will use a very large number 14 | #define INFINITY 999999999 15 | 16 | int n, m; // number of nodes and edges 17 | int dist[MAXN]; // distances to font 18 | int processed[MAXN]; // if the node was processed 19 | vector neighbors[MAXN]; //The first element of pair is the distance and the second the node 20 | //--------------------- 21 | 22 | int Prim(){ 23 | 24 | for(int i = 1;i <= n;i++) dist[i] = INFINITY; // we define all distances as infinite, except for S = 1. 25 | dist[1] = 0; // Thus, we guarantee that the first selected node will be 1 itself. 26 | 27 | priority_queue< pii, vector, greater > queue; // Created a priority queue where the smallest is at the top. 28 | queue.push( pii(dist[1], 1) ); // As you can see, we put the first element as the distance from the 29 | // node in the Minimum Generation Tree and the second as the vertex itself 30 | 31 | while(true){ // run "endlessly" 32 | 33 | int actual = -1; 34 | 35 | // we select the nearest node 36 | while(!queue.empty()){ 37 | 38 | int current = queue.top().second; 39 | queue.pop(); 40 | 41 | if(!processed[current]){ // we can use this node because it hasn't been processed yet 42 | actual = current; 43 | break; 44 | } 45 | 46 | // if not, we keep looking 47 | } 48 | 49 | if(actual == -1) break; // if not found anyone, it's the end of the algorithm 50 | 51 | processed[actual] = true; // we mark to not go back to this node 52 | 53 | //now, we'll try to update the distances 54 | for(int i = 0;i < (int)neighbors[actual].size();i++){ 55 | 56 | int distV = neighbors[actual][i].first; 57 | int current = neighbors[actual][i].second; 58 | 59 | // The new possible distance is distV. 60 | // We compare this with dist[current]. 61 | // However, it is important to check if the current node has not been processed yet 62 | 63 | if( dist[current] > distV && !processed[current]){ // we see if it is worth using the actual node 64 | dist[current] = distV; // update the distance 65 | queue.push( pii(dist[current], current) ); // add to the priority queue 66 | } 67 | } 68 | } 69 | 70 | int tree_cost = 0; 71 | for(int i = 1;i <= n;i++) tree_cost += dist[i]; 72 | 73 | return tree_cost; 74 | } 75 | 76 | int main(){ 77 | 78 | cin >> n >> m; 79 | 80 | for(int i = 1;i <= m;i++){ 81 | 82 | int x, y, weight; 83 | cin >> x >> y >> weight; 84 | 85 | neighbors[x].push_back( pii(weight, y) ); 86 | neighbors[y].push_back( pii(weight, x) ); 87 | } 88 | 89 | cout << Prim() << endl; // print the answer 90 | 91 | return 0; 92 | } 93 | --------------------------------------------------------------------------------