├── binary_search ├── clang │ └── Binary_Search.c ├── .DS_Store ├── python │ ├── binarysearch.py │ └── binary_search.py ├── ruby │ └── binary_search.rb ├── javascript │ └── binary_search.js ├── Kotlin │ └── binary_search.kt ├── Go │ └── binary_search.go ├── java │ ├── binary_search.java │ └── BinarySearch2.java └── cpp │ ├── BINARYSE.CPP │ ├── bs.cpp │ └── BinarySearch2.cpp ├── heap_sort ├── python │ └── heap_sort.py ├── .DS_Store ├── cpp │ └── .DS_Store ├── dart │ └── heapSort.dart ├── javascript │ └── heapSort.js ├── c# │ └── heap_sort.cs ├── clang │ └── heap_sort.c └── java │ └── HeapSort.java ├── radix_sort ├── clang │ └── radix_sort.c ├── cpp │ └── radix_sort.cpp ├── python │ └── radix_sort.py ├── php │ └── radix_sort.php.txt └── java │ └── radix_sort.java ├── .DS_Store ├── luhn ├── .DS_Store ├── cpp │ └── luhn.cpp └── python │ └── luhn.py ├── stack ├── .DS_Store ├── ruby │ └── stack.rb ├── python │ └── stack.py ├── cpp │ └── STACK1D.CPP ├── clang │ └── stack.c └── golang │ └── stack.go ├── trees ├── .DS_Store ├── height │ ├── .DS_Store │ ├── python │ │ └── Height.py │ ├── Clang │ │ └── height.c │ └── cpp │ │ └── ht.cpp ├── merkle_tree │ ├── .DS_Store │ └── java │ │ ├── App.java │ │ ├── SHA256Helper.java │ │ └── MerkleTree.java ├── binary_search_tree │ ├── .DS_Store │ ├── Python │ │ └── BST.py │ ├── python │ │ └── Inorder_BST.py │ ├── cpp │ │ └── HeightOfBST.cpp │ └── clang │ │ └── optimal_binary_search.c ├── travelling_salesman │ ├── .DS_Store │ └── clang │ │ └── ts.c └── traversals │ ├── Java │ ├── btree_preorder.java │ ├── btree_level_order │ └── btree_postorder.java │ ├── python │ └── treeTrav.py │ └── javascript │ └── treeTrav.js ├── greedy ├── .DS_Store ├── cpp │ ├── .DS_Store │ └── Knapsack.java ├── java │ └── .DS_Store ├── python │ ├── .DS_Store │ └── knapsack.py ├── knapsack.cpp ├── knapsack.c └── dijsktra │ └── dijsktra.py ├── kruskal └── .DS_Store ├── min_heap └── .DS_Store ├── fibonacci ├── .DS_Store ├── cpp │ ├── .DS_Store │ ├── fibonacci.cpp │ └── fibonacci_explained.cpp ├── python │ ├── .DS_Store │ ├── fibonacci.py │ └── Fibonacci_Series.py ├── golang │ ├── fibonacci.go │ └── fibonacci_test.go ├── clang │ └── fibonacci.c ├── java │ └── fibonacci.java └── c# │ └── fibonacci.cs ├── merge_sort ├── .DS_Store ├── javascript │ └── mergeSort.js ├── golang │ ├── merge_sort_test.go │ └── merge_sort.go ├── python │ └── merge_sort.py ├── clang │ └── merge_sort.c ├── ruby │ └── merge_sort.rb └── java │ └── merge_sort.java ├── quick_sort ├── .DS_Store ├── cpp │ ├── .DS_Store │ ├── Quick_Sort.cpp │ └── quick_sort.cpp ├── php │ └── quick_sort.php.txt ├── ruby │ └── quick_sort.rb ├── haskell │ └── quicksort.hs ├── python │ └── quick_sort.py ├── javascript │ └── quickSort.js ├── clang │ └── quick_sort.c ├── java │ ├── quick_sort.java │ └── QuickSort.java └── c# │ └── QuickSort in c# ├── shell_sort ├── .DS_Store ├── python │ ├── ShellSort.py │ └── shell_Sort.py ├── clang │ └── SHELL.C ├── cpp │ └── shellSort.cpp ├── shell_sort.cs └── java │ └── ShellSort.java ├── wave_sort ├── .DS_Store └── python │ └── waveSort.py ├── bitonic_sort └── .DS_Store ├── bubble_sort ├── .DS_Store ├── clang │ ├── .DS_Store │ └── bubble_sort.c ├── golang │ ├── bubble_sort.go │ └── bubble_sort_test.go ├── Kotlin │ └── bubble_sort.kt ├── dart │ └── bubbleSort.dart ├── java │ ├── OptimizedBubbleSort.java │ └── bubble_sort.java ├── ruby │ └── bubble_sort.rb ├── python │ └── bubble_sort.py ├── c# │ └── bubble_sort.cs └── cpp │ ├── bubble_sort.cpp │ └── BUBBLE_A.CPP ├── bucket_sort ├── .DS_Store ├── Python │ └── bucketSort.py ├── Clang │ └── bucketSort.c ├── CPP │ └── BucketSort.cpp └── Go │ └── bucket_sort.go ├── counting_sort ├── .DS_Store ├── javascript │ └── counting_sort.js ├── Kotlin │ └── counting_sort.kt ├── python │ └── update_counting_sort.py ├── ruby │ └── counting_sort.rb ├── clang │ └── counting_sort.c ├── cpp │ ├── counting_sort.cpp │ └── counting.cpp └── java │ └── counting_sort.java ├── insertion_sort ├── R │ ├── .RData │ └── insretion_sort.r ├── .DS_Store ├── golang │ ├── sort.go │ └── sort_test.go ├── Python │ ├── insertionsort.py │ └── insertion_sort.py ├── javascript │ └── insertions_sort.js ├── cpp │ ├── insertion_sort.cpp │ └── INSERTIO.CPP ├── java │ └── InsertionSort.java ├── c# │ └── C# └── c │ └── insertionSort.c ├── linear_search ├── .DS_Store ├── python │ ├── linear_search.py │ ├── linearsearch.py │ └── linear.py ├── javascript │ └── linear_search.js ├── C │ ├── linear.c │ └── linearsearch.c ├── go │ └── linear_search.go ├── java │ └── Linear.java ├── cpp │ └── linear_search.cpp └── c# │ └── linear_search.cs ├── pisano period ├── .DS_Store ├── python │ └── pisanoPeriod.py └── cpp │ └── PisanoPeriod.cpp ├── selection_sort ├── .DS_Store ├── go │ ├── .DS_Store │ └── selection_sort.go ├── python │ └── SelectionSort.py ├── dart │ └── selectionSoft.dart ├── c# │ └── selection_sort.cs ├── clang │ ├── SELECT.C │ └── SelectionSort.c ├── cpp │ └── selection_sort.cpp └── java │ └── SelectionSort.java ├── egyptian_fractions ├── .DS_Store ├── python │ └── Egyptian Fractions.py └── cpp │ └── egyptF.cpp ├── palindrome_checker ├── .DS_Store ├── java │ ├── .DS_Store │ └── PalindromeChecker.java ├── dart │ └── checkPalinrome.dart ├── javascript │ ├── palindromeC1.js │ └── palindromeC2.js ├── python │ └── Palindrome_checker.py ├── clang │ └── palindrome.c └── cpp │ └── palindrome.cpp ├── tarjan_algorithm ├── .DS_Store └── java │ └── Tarjan.java ├── dynamic_programming ├── .DS_Store ├── ugly_numbers │ ├── .DS_Store │ ├── cpp │ │ └── UglyNos.cpp │ ├── python │ │ └── UglyNos.py │ └── java │ │ └── UglyNos.java ├── longest-inc-subsequence.py ├── painting fence.py ├── permutations.py ├── climbingStairs.py ├── max_product_subarray.py ├── coin-change-problem.py ├── rod-cutting-problem ├── min_coins_change.cpp ├── Min_pts_to_reach_destination.cpp └── longest-common-subsequence.py ├── maximum_contiguous_subarray_sum_kadane's_algorithm ├── .DS_Store └── python │ └── maxsubarraysum.py ├── euclidean_gcd ├── javascript │ └── euclidean_gcd.js ├── clang │ └── euclidean_gcd.c ├── cpp │ └── euclidean_gcd.cpp ├── python │ └── euclidean_gcd.py └── java │ ├── euclidean_gcd_using_recursion.java │ └── euclidean_gcd.java ├── queues ├── javascript │ └── queue.js ├── ruby │ └── queue.rb ├── java │ └── queue.java ├── clang │ └── queue.c └── python │ └── queue.py ├── amount_divisors_of_one_number ├── amount_divisors_of_one_number.py ├── No_of_Divisors.java └── amount_divisors_of_one_number.cpp ├── factorial └── Kotlin │ └── factorial.kt ├── depth_first_search ├── golang │ ├── dfs.go │ └── dfs_test.go ├── python │ └── dfs.py ├── cpp │ └── dfs.cpp └── java │ ├── bst.java │ ├── dfs.java │ └── depthffs.java ├── detect duplicates └── Kotlin │ └── detect_duplicates.kt ├── bogo_sort ├── php │ └── bogosort.php ├── python │ └── bogoSort.py ├── cpp │ └── bogoSort.cpp └── Java │ └── BogoSort.java ├── towers_of_hanoi ├── python │ └── hanoi.py ├── cpp │ └── TowerOfHanoi.cpp ├── javascript │ └── hanoi.js ├── java │ └── Tower.java └── clang │ ├── hanoi.cpp │ └── hanoi.c ├── linkedlist └── python │ ├── FindingLengthOfLinkedList.py │ └── LinkedList.py ├── Newton Rhapson └── kotlin │ └── newton_rhapson.kt ├── breath_first_search ├── cpp │ ├── bfs_tree.cpp │ ├── breadth_first_search.cpp │ └── bfs.cpp └── python │ └── bfs.py ├── interpolation search ├── python │ └── interpolationsearch.py ├── clang │ └── interpolationsearch.c ├── cpp │ └── interpolationsearch.cpp └── java │ └── interpolationsearch.java ├── Secant └── Kotlin │ └── secant.kt ├── disjoint_set └── disjoint_set.java ├── set_operations └── cpp │ └── set_operations.cpp ├── segment-trees └── cpp │ └── segment-tree.cpp └── Contributor.md /binary_search/clang/Binary_Search.c: -------------------------------------------------------------------------------- 1 | //add your code here -------------------------------------------------------------------------------- /heap_sort/python/heap_sort.py: -------------------------------------------------------------------------------- 1 | # add your code here 2 | -------------------------------------------------------------------------------- /radix_sort/clang/radix_sort.c: -------------------------------------------------------------------------------- 1 | //add your code here 2 | 3 | -------------------------------------------------------------------------------- /radix_sort/cpp/radix_sort.cpp: -------------------------------------------------------------------------------- 1 | // add your code here 2 | 3 | -------------------------------------------------------------------------------- /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/.DS_Store -------------------------------------------------------------------------------- /luhn/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/luhn/.DS_Store -------------------------------------------------------------------------------- /stack/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/stack/.DS_Store -------------------------------------------------------------------------------- /trees/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/trees/.DS_Store -------------------------------------------------------------------------------- /greedy/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/greedy/.DS_Store -------------------------------------------------------------------------------- /kruskal/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/kruskal/.DS_Store -------------------------------------------------------------------------------- /min_heap/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/min_heap/.DS_Store -------------------------------------------------------------------------------- /fibonacci/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/fibonacci/.DS_Store -------------------------------------------------------------------------------- /greedy/cpp/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/greedy/cpp/.DS_Store -------------------------------------------------------------------------------- /heap_sort/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/heap_sort/.DS_Store -------------------------------------------------------------------------------- /merge_sort/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/merge_sort/.DS_Store -------------------------------------------------------------------------------- /quick_sort/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/quick_sort/.DS_Store -------------------------------------------------------------------------------- /shell_sort/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/shell_sort/.DS_Store -------------------------------------------------------------------------------- /wave_sort/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/wave_sort/.DS_Store -------------------------------------------------------------------------------- /binary_search/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/binary_search/.DS_Store -------------------------------------------------------------------------------- /bitonic_sort/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/bitonic_sort/.DS_Store -------------------------------------------------------------------------------- /bubble_sort/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/bubble_sort/.DS_Store -------------------------------------------------------------------------------- /bucket_sort/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/bucket_sort/.DS_Store -------------------------------------------------------------------------------- /counting_sort/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/counting_sort/.DS_Store -------------------------------------------------------------------------------- /fibonacci/cpp/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/fibonacci/cpp/.DS_Store -------------------------------------------------------------------------------- /greedy/java/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/greedy/java/.DS_Store -------------------------------------------------------------------------------- /greedy/python/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/greedy/python/.DS_Store -------------------------------------------------------------------------------- /heap_sort/cpp/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/heap_sort/cpp/.DS_Store -------------------------------------------------------------------------------- /insertion_sort/R/.RData: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/insertion_sort/R/.RData -------------------------------------------------------------------------------- /linear_search/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/linear_search/.DS_Store -------------------------------------------------------------------------------- /pisano period/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/pisano period/.DS_Store -------------------------------------------------------------------------------- /trees/height/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/trees/height/.DS_Store -------------------------------------------------------------------------------- /insertion_sort/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/insertion_sort/.DS_Store -------------------------------------------------------------------------------- /quick_sort/cpp/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/quick_sort/cpp/.DS_Store -------------------------------------------------------------------------------- /selection_sort/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/selection_sort/.DS_Store -------------------------------------------------------------------------------- /bubble_sort/clang/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/bubble_sort/clang/.DS_Store -------------------------------------------------------------------------------- /egyptian_fractions/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/egyptian_fractions/.DS_Store -------------------------------------------------------------------------------- /fibonacci/python/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/fibonacci/python/.DS_Store -------------------------------------------------------------------------------- /palindrome_checker/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/palindrome_checker/.DS_Store -------------------------------------------------------------------------------- /selection_sort/go/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/selection_sort/go/.DS_Store -------------------------------------------------------------------------------- /tarjan_algorithm/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/tarjan_algorithm/.DS_Store -------------------------------------------------------------------------------- /trees/merkle_tree/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/trees/merkle_tree/.DS_Store -------------------------------------------------------------------------------- /dynamic_programming/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/dynamic_programming/.DS_Store -------------------------------------------------------------------------------- /palindrome_checker/java/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/palindrome_checker/java/.DS_Store -------------------------------------------------------------------------------- /trees/binary_search_tree/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/trees/binary_search_tree/.DS_Store -------------------------------------------------------------------------------- /trees/travelling_salesman/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/trees/travelling_salesman/.DS_Store -------------------------------------------------------------------------------- /dynamic_programming/ugly_numbers/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/dynamic_programming/ugly_numbers/.DS_Store -------------------------------------------------------------------------------- /quick_sort/php/quick_sort.php.txt: -------------------------------------------------------------------------------- 1 | var app = angular.module("app", []); 2 | app.controller("HelloController", function($scope) { 3 | $scope.message = "Hello, AngularJS"; 4 | }); -------------------------------------------------------------------------------- /maximum_contiguous_subarray_sum_kadane's_algorithm/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fnplus/hacktoberfest-algorithms/HEAD/maximum_contiguous_subarray_sum_kadane's_algorithm/.DS_Store -------------------------------------------------------------------------------- /euclidean_gcd/javascript/euclidean_gcd.js: -------------------------------------------------------------------------------- 1 | function gcd(a, b) { 2 | if (b == 0) 3 | return a; 4 | else 5 | return gcd(b, (a % b)); 6 | } 7 | 8 | console.log(gcd(gcd(203, 91), 77)) -------------------------------------------------------------------------------- /quick_sort/ruby/quick_sort.rb: -------------------------------------------------------------------------------- 1 | def quicksort(list) 2 | return list if list.size <= 1 3 | pivot = list.sample 4 | left, right = list.partition { |e| e < pivot } 5 | quicksort(left) + quicksort(right) 6 | end -------------------------------------------------------------------------------- /fibonacci/golang/fibonacci.go: -------------------------------------------------------------------------------- 1 | package golang 2 | 3 | func fib(n int) []int { 4 | seq := []int{1, 1} 5 | for len(seq) < n { 6 | i := len(seq) 7 | seq = append(seq, seq[i-1]+seq[i-2]) 8 | } 9 | return seq[:n] 10 | } 11 | -------------------------------------------------------------------------------- /insertion_sort/golang/sort.go: -------------------------------------------------------------------------------- 1 | package sort 2 | 3 | func InsertionSort(a []int) []int { 4 | for i := 1; i < len(a); i++ { 5 | n := a[i] 6 | j := i 7 | for j > 0 && a[j-1] > n { 8 | a[j] = a[j-1] 9 | j-- 10 | } 11 | a[j] = n 12 | } 13 | return a 14 | } 15 | -------------------------------------------------------------------------------- /queues/javascript/queue.js: -------------------------------------------------------------------------------- 1 | 2 | class Queue { 3 | constructor() { 4 | this.queue = []; 5 | } 6 | 7 | enqueue(item) { 8 | this.queue.push(item); 9 | } 10 | 11 | dequeue() { 12 | return this.queue.shift(); 13 | } 14 | } 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /amount_divisors_of_one_number/amount_divisors_of_one_number.py: -------------------------------------------------------------------------------- 1 | val = input("Enter your value: ") 2 | print(val) 3 | n=int(val) 4 | i=1 5 | count=0 6 | for i in range(1,n+1): 7 | if(n%i==0): 8 | count=count+1 9 | print("THE AMOUNT OF DIVISORS IS - ") 10 | print(count) 11 | -------------------------------------------------------------------------------- /factorial/Kotlin/factorial.kt: -------------------------------------------------------------------------------- 1 | fun main(args: Array) { 2 | val num = 10 3 | var factorial: Long = 1 4 | for (i in 1..num) { 5 | // factorial = factorial * i; 6 | factorial *= i.toLong() 7 | } 8 | println("Factorial of $num = $factorial") 9 | } 10 | -------------------------------------------------------------------------------- /linear_search/python/linear_search.py: -------------------------------------------------------------------------------- 1 | def search(arr, x): 2 | for i in range(len(arr)): 3 | if arr[i] == x: 4 | return i 5 | return -1 6 | arr=[10,20,3,4] 7 | x=20 8 | print(arr) 9 | if(search(arr,x)==1): 10 | print("Element found") 11 | else: 12 | print("not found") -------------------------------------------------------------------------------- /dynamic_programming/longest-inc-subsequence.py: -------------------------------------------------------------------------------- 1 | def LIS(arr): 2 | dp=[1]*len(arr) 3 | 4 | for i in range(1,len(arr)): 5 | for j in range(0,i): 6 | if(arr[i]>arr[j] and dp[i] [a] -> [a] 2 | quicksort [] = [] 3 | quicksort (x:xs) = smaller xs ++ [x] ++ bigger xs 4 | where 5 | smaller xs = quicksort [x' | x' <- xs, x' <= x] 6 | bigger xs = quicksort [x' | x' <- xs, x' > x] 7 | 8 | -------------------------------------------------------------------------------- /bubble_sort/golang/bubble_sort.go: -------------------------------------------------------------------------------- 1 | package golang 2 | 3 | func bubbleSort(array []int) []int { 4 | for range array { 5 | for i := 0; i < len(array)-1; i++ { 6 | if array[i] > array[i+1] { 7 | temp := array[i] 8 | array[i] = array[i+1] 9 | array[i+1] = temp 10 | } 11 | } 12 | } 13 | return array 14 | } 15 | -------------------------------------------------------------------------------- /palindrome_checker/dart/checkPalinrome.dart: -------------------------------------------------------------------------------- 1 | main() { 2 | print(checkPalindrome('aabaa')); 3 | } 4 | 5 | bool checkPalindrome(String inputString) { 6 | String reverseStr = inputString.split('').reversed.join(); 7 | print(reverseStr); 8 | if (reverseStr == inputString) { 9 | return true; 10 | } 11 | return false; 12 | } 13 | -------------------------------------------------------------------------------- /euclidean_gcd/clang/euclidean_gcd.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int gcd(int a, int b) 4 | { 5 | return b == 0 ? a : gcd(b, a % b); 6 | } 7 | 8 | int main() 9 | { 10 | int a, b; 11 | printf("Inform the vales of a and b: "); 12 | scanf("%d %d", &a, &b); 13 | printf("GCD(%d, %d): %d\n", a, b, gcd(a, b)); 14 | return 0; 15 | } 16 | -------------------------------------------------------------------------------- /fibonacci/cpp/fibonacci.cpp: -------------------------------------------------------------------------------- 1 | // add your code here 2 | #include 3 | using namespace std; 4 | 5 | int fib(int n) 6 | { 7 | if (n <= 1) 8 | return n; 9 | return fib(n-1) + fib(n-2); 10 | } 11 | 12 | int main () 13 | { 14 | int n = 9; 15 | cout << fib(n); 16 | getchar(); 17 | return 0; 18 | } 19 | -------------------------------------------------------------------------------- /depth_first_search/golang/dfs.go: -------------------------------------------------------------------------------- 1 | package dfs 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | ) 7 | 8 | type tree struct { 9 | left *tree 10 | value int 11 | right *tree 12 | } 13 | 14 | func traverse(t *tree, w io.Writer) { 15 | if t == nil { 16 | return 17 | } 18 | 19 | fmt.Fprintf(w, " %d ", t.value) 20 | traverse(t.left, w) 21 | traverse(t.right, w) 22 | } -------------------------------------------------------------------------------- /dynamic_programming/painting fence.py: -------------------------------------------------------------------------------- 1 | def countWays(n, k) : 2 | 3 | total = k 4 | mod = 1000000007 5 | same, diff = 0, k 6 | 7 | for i in range(2, n + 1) : 8 | 9 | same = diff 10 | 11 | diff = total * (k - 1) 12 | diff = diff % mod 13 | 14 | total = (same + diff) % mod 15 | 16 | return total 17 | 18 | n, k = 10, 2 19 | print(countWays(n, k)) 20 | -------------------------------------------------------------------------------- /fibonacci/python/fibonacci.py: -------------------------------------------------------------------------------- 1 | def fib(n): 2 | sequence = [1, 1] 3 | while (len(sequence) < n): 4 | i = len(sequence) 5 | sequence.append( 6 | sequence[i-1] + 7 | sequence[i-2] 8 | ) 9 | 10 | return sequence[:n] 11 | 12 | # fib(2) -> [1, 1] 13 | # fib(5) -> [1, 1, 2, 3, 5] 14 | # fib(10) -> [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] -------------------------------------------------------------------------------- /euclidean_gcd/cpp/euclidean_gcd.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int gcd(int a, int b) 4 | { 5 | return b == 0 ? a : gcd(b, a % b); 6 | } 7 | 8 | using namespace std; 9 | int main() 10 | { 11 | int a, b; 12 | cout << "Inform the vales of a and b: "; 13 | cin >> a; 14 | cin >> b; 15 | cout << "GCD(" << a << ", " << b << "): " << gcd(a, b) << endl; 16 | return 0; 17 | } -------------------------------------------------------------------------------- /wave_sort/python/waveSort.py: -------------------------------------------------------------------------------- 1 | # Prg of WAVE SORT in Python 2 | 3 | def sortInWave(arr, n): 4 | 5 | # Sorting the array 6 | arr.sort() 7 | 8 | # Swapping adjacent elements 9 | for i in range(0, n-1, 2): 10 | arr[i], arr[i+1] = arr[i+1], arr[i] 11 | 12 | 13 | # MAIN 14 | arr = [10, 90, 49, 2, 23] 15 | sortInWave(arr, len(arr)) 16 | for i in range(0, len(arr)): 17 | print(arr[i]) 18 | -------------------------------------------------------------------------------- /insertion_sort/Python/insertionsort.py: -------------------------------------------------------------------------------- 1 | def insertionSort(l): 2 | for i in range(1, len(l)): 3 | key = l[i] 4 | j = i-1 5 | while j >=0 and key < l[j] : 6 | l[j+1] = l[j] 7 | j -= 1 8 | l[j+1] = key 9 | 10 | # TEST YOUR CODE BY CHANGING list l 11 | l = [12, 11, 13, 5, 6] 12 | insertionSort(l) 13 | print (*l) 14 | -------------------------------------------------------------------------------- /egyptian_fractions/python/Egyptian Fractions.py: -------------------------------------------------------------------------------- 1 | import math 2 | x = 2 3 | add = 0 4 | a = int(input("Enter Numerator: ")) 5 | b = int(input("Enter Denomenator: ")) 6 | 7 | c = a/b 8 | temp = c 9 | 10 | print(c) 11 | print("Output: 0") 12 | while(add!=c): 13 | if((1/x)<=temp): 14 | add=add+(1/x) 15 | temp=c-add 16 | print("+1/", x) 17 | x=x+1 18 | 19 | 20 | print(add) 21 | -------------------------------------------------------------------------------- /linear_search/javascript/linear_search.js: -------------------------------------------------------------------------------- 1 | function linearSearch(unOrderedArray,searchElement){ 2 | for(var i=0;i) : Boolean { 2 | with(list) { 3 | for (cursor1 in 0 until size) { 4 | for (cursor2 in 0 until size) { 5 | if (cursor1 != cursor2) { 6 | if (get(cursor1) == get(cursor2)) return true 7 | } 8 | } 9 | } 10 | } 11 | return false 12 | } 13 | -------------------------------------------------------------------------------- /dynamic_programming/permutations.py: -------------------------------------------------------------------------------- 1 | def ListToString(List): 2 | return ''.join(List) 3 | 4 | def permutations(ls, a, b): 5 | if a == b: 6 | print(ListToString(ls)) 7 | else: 8 | for i in range(a , b+1): 9 | ls[a], ls[i] = ls[i], ls[a] 10 | permutations(ls, a+1, b) 11 | ls[a], ls[i] = ls[i], ls[a] 12 | 13 | the_word = input() 14 | n = len(the_word) 15 | a = list(the_word) 16 | permutations(a, 0, n-1) -------------------------------------------------------------------------------- /palindrome_checker/javascript/palindromeC1.js: -------------------------------------------------------------------------------- 1 | // Prg to check if a string is palindrome in JS 2 | 3 | // Using REGEX 4 | 5 | function palindrome(str) { 6 | var re = /[\W_]/g; 7 | var lowRegStr = str.toLowerCase().replace(re, ''); 8 | var reverseStr = lowRegStr.split('').reverse().join(''); 9 | return reverseStr === lowRegStr; 10 | } 11 | 12 | console.log(palindrome("mom")); 13 | console.log(palindrome("1010")); -------------------------------------------------------------------------------- /greedy/python/knapsack.py: -------------------------------------------------------------------------------- 1 | def knapSack(W , wt , val , n): 2 | 3 | if n == 0 or W == 0 : 4 | return 0 5 | 6 | if (wt[n-1] > W): 7 | return knapSack(W , wt , val , n-1) 8 | 9 | else: 10 | return max(val[n-1] + knapSack(W-wt[n-1] , wt , val , n-1), 11 | knapSack(W , wt , val , n-1)) 12 | 13 | val = [60, 100, 120] 14 | wt = [10, 20, 30] 15 | W = 50 16 | n = len(val) 17 | print knapSack(W , wt , val , n) 18 | -------------------------------------------------------------------------------- /linear_search/python/linearsearch.py: -------------------------------------------------------------------------------- 1 | print("Enter the number of elements") 2 | n=int(input()) 3 | l=[0]*n 4 | ans=-1 5 | print("Enter the elements") 6 | for i in range(n): 7 | l[i]=int(input()) 8 | print("Enter the element to search") 9 | k=int(input()) 10 | for i in range(n): 11 | if k==l[i]: 12 | ans=i 13 | if ans==-1: 14 | print ("Element not found") 15 | else: 16 | print("The position of the element is : ") 17 | print(ans+1) 18 | -------------------------------------------------------------------------------- /palindrome_checker/python/Palindrome_checker.py: -------------------------------------------------------------------------------- 1 | word = input("Input \"stop\" to stop\nWhat word would you like to check? \n>") 2 | reverse = word[::-1] 3 | 4 | while (word != "stop"): 5 | 6 | if reverse == word: 7 | print ("This is a palindrome.") 8 | else: 9 | print ("This is not a palindrome.") 10 | 11 | word = input("Input \"stop\" to stop\nWhat word would you like to check? \n>") 12 | reverse = word[::-1] 13 | -------------------------------------------------------------------------------- /euclidean_gcd/python/euclidean_gcd.py: -------------------------------------------------------------------------------- 1 | # Function to return gcd of a and b 2 | 3 | def gcd(num_1, num_2): 4 | if num_1 == 0 : 5 | return num_2 6 | 7 | return gcd(num_2 % num_1, num_1) 8 | 9 | print("Enter the 1st number -- , end='') 10 | num_1 = int(input()) 11 | print("Enter the 2nd number -- , end='') 12 | num_2 = int(input()) 13 | 14 | print("gcd of {} and {} -> ".format(num_1,num_2), gcd(num_1, num_2) ,end='') 15 | -------------------------------------------------------------------------------- /pisano period/python/pisanoPeriod.py: -------------------------------------------------------------------------------- 1 | # Prg to calculate PISANO PERIOD in Python 2 | 3 | 4 | def pisanoPeriod(m): 5 | previous, current = 0, 1 6 | for i in range(0, m * m): 7 | previous, current \ 8 | = current, (previous + current) % m 9 | 10 | # A Pisano Period starts with 01 11 | if (previous == 0 and current == 1): 12 | return i + 1 13 | 14 | 15 | # MAIN 16 | if __name__ == '__main__': 17 | print(pisanoPeriod(235)) 18 | -------------------------------------------------------------------------------- /selection_sort/python/SelectionSort.py: -------------------------------------------------------------------------------- 1 | def sel_sort(A): 2 | for i in range(len(A)): 3 | min_idx = i 4 | for j in range(i+1, len(A)): 5 | if A[min_idx] > A[j]: 6 | min_idx = j 7 | A[i], A[min_idx] = A[min_idx], A[i] 8 | 9 | array = list(map(int, input().split())) 10 | # print(*sel_sort(array), end='') 11 | sel_sort(array) 12 | print("Sorted array is:") 13 | for i in range(len(array)): 14 | print("%d" %array[i]) -------------------------------------------------------------------------------- /linear_search/python/linear.py: -------------------------------------------------------------------------------- 1 | # Python3 code to linearly search x in arr[]. 2 | 3 | def search(arr, n, x): 4 | 5 | for i in range (0, n): 6 | if (arr[i] == x): 7 | return i; 8 | return -1; 9 | 10 | # Driver Code 11 | arr = [ 2, 3, 4, 10, 40 ]; 12 | x = 10; 13 | n = len(arr); 14 | result = search(arr, n, x) 15 | if(result == -1): 16 | print("Element is not present in array") 17 | else: 18 | print("Element is present at index", result); 19 | -------------------------------------------------------------------------------- /dynamic_programming/climbingStairs.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/climbing-stairs/ 2 | 3 | 4 | def climbStairs(A): 5 | if A == 0 or A == 1: 6 | return 1 7 | if A == 2: 8 | return 2 9 | else: 10 | arr = [1, 2] 11 | for i in range(2, A): 12 | curr = arr[i - 2] + arr[i - 1] 13 | arr.append(curr) 14 | return arr[-1] 15 | 16 | 17 | n = int(input("Enter number of stairs :")) 18 | print(climbStairs(n)) 19 | -------------------------------------------------------------------------------- /bogo_sort/php/bogosort.php: -------------------------------------------------------------------------------- 1 | $array[$i]) 10 | { 11 | return false; 12 | } 13 | } 14 | 15 | return true; 16 | } 17 | 18 | 19 | function bogo_sort($list) 20 | { 21 | 22 | while(!issorted($list)) { 23 | shuffle($list); 24 | } 25 | return $list; 26 | 27 | } 28 | -------------------------------------------------------------------------------- /amount_divisors_of_one_number/No_of_Divisors.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class No_of_Divisors 4 | { 5 | public static void main(String[] args) 6 | { 7 | Scanner sc = new Scanner(System.in); 8 | System.out.println("Enter the number: "); 9 | int num = sc.nextInt(); 10 | int i, count=2; 11 | 12 | for(i=2; i<=num/2; i++) 13 | { 14 | if(num%i==0) 15 | count++; 16 | } 17 | 18 | System.out.println("No. of divisors of "+num+" are: "+count); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /palindrome_checker/javascript/palindromeC2.js: -------------------------------------------------------------------------------- 1 | // Prg to check if a string is palindrome in JS 2 | 3 | // Using FOR LOOP 4 | 5 | function palindrome(str) { 6 | var re = /[^A-Za-z0-9]/g; 7 | str = str.toLowerCase().replace(re, ''); 8 | var len = str.length; 9 | for (var i = 0; i < len / 2; i++) { 10 | if (str[i] !== str[len - 1 - i]) { 11 | return false; 12 | } 13 | } 14 | return true; 15 | } 16 | 17 | console.log(palindrome("mom")); 18 | console.log(palindrome("1010")); -------------------------------------------------------------------------------- /amount_divisors_of_one_number/amount_divisors_of_one_number.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main(){ 4 | int n = 20; 5 | map primes; 6 | for(int i = 2;i <= sqrt(n); i++){ /// getting the prime factorization of n 7 | while(n % i == 0){ 8 | primes[i]++; 9 | n/=i; 10 | } 11 | } 12 | if(n != 1)primes[n]++; 13 | int quantity_of_divisors = 1; 14 | for(auto e : primes){ 15 | quantity_of_divisors *= (e.second+1); 16 | } 17 | cout< 2 | using namespace std; 3 | void toh(int n, char first, char second, char third) 4 | { 5 | if (n==1) 6 | { 7 | cout<<"Disk 1: from rod "< 3 | 4 | int search(int arr[], int n, int x) 5 | { 6 | int i; 7 | for (i = 0; i < n; i++) 8 | if (arr[i] == x) 9 | return i; 10 | return -1; 11 | } 12 | 13 | int main(void) 14 | { 15 | int arr[] = { 2, 3, 4, 10, 40 }; 16 | int x = 10; 17 | int n = sizeof(arr) / sizeof(arr[0]); 18 | int result = search(arr, n, x); 19 | (result == -1) ? printf("Element is not present in array") 20 | : printf("Element is present at index %d", 21 | result); 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /bubble_sort/Kotlin/bubble_sort.kt: -------------------------------------------------------------------------------- 1 | fun bubble_sort(list: MutableList) { 2 | val size = list.size 3 | 4 | for (x in 0 until size) { 5 | for (y in x + 1 until size) { 6 | println("\tx=$x, y=$y") 7 | if (list[y] < list[x]) { 8 | list.swap(y, x) 9 | } 10 | } 11 | } 12 | } 13 | 14 | fun MutableList.swap(index1: Int, index2: Int) { 15 | val tmp = this[index1] // 'this' corresponds to the list 16 | this[index1] = this[index2] 17 | this[index2] = tmp 18 | } 19 | -------------------------------------------------------------------------------- /bubble_sort/dart/bubbleSort.dart: -------------------------------------------------------------------------------- 1 | main() { 2 | bubbleSort([173, 657, 1, 0]); 3 | } 4 | 5 | void bubbleSort(List list) { 6 | if (list == null || list.length == 0) return; 7 | 8 | int n = list.length; 9 | int i, step; 10 | for (step = 0; step < n; step++) { 11 | for (i = 0; i < n - step - 1; i++) { 12 | if (list[i] > list[i + 1]) { 13 | swap(list, i); 14 | } 15 | } 16 | } 17 | print(list); 18 | } 19 | 20 | void swap(List list, int i) { 21 | int temp = list[i]; 22 | list[i] = list[i + 1]; 23 | list[i + 1] = temp; 24 | } 25 | -------------------------------------------------------------------------------- /fibonacci/clang/fibonacci.c: -------------------------------------------------------------------------------- 1 | //fibonacci series for n terms 2 | #include 3 | int main() 4 | { 5 | int n, first = 0, second = 1, next, c; 6 | 7 | printf("Enter the number of terms\n"); 8 | scanf("%d", &n); 9 | 10 | printf("First %d terms of Fibonacci series are:\n", n); 11 | 12 | for (c = 0; c < n; c++) 13 | { 14 | if (c <= 1) 15 | next = c; 16 | else 17 | { 18 | next = first + second; 19 | first = second; 20 | second = next; 21 | } 22 | printf("%d\n", next); 23 | } 24 | 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /insertion_sort/R/insretion_sort.r: -------------------------------------------------------------------------------- 1 | #Straight Insertion Sort 2 | 3 | sort.sis <- function(x,z) 4 | { 5 | if(!is.vector(x)) {stop("Parameter must be a vector")} 6 | if(!is.numeric(x)) {stop("Parameter must be a numeric")} 7 | if(!is.numeric(z)) {stop("Parameter must be a numeric")} 8 | n = length(x) 9 | y = numeric(n+1) 10 | 11 | for (i in 1:n) 12 | { 13 | j = i 14 | while (x[j] <= z) 15 | { 16 | y <<- append(x,z, after = j) 17 | j = j + 1 18 | } 19 | } 20 | } 21 | 22 | #Test 23 | x = seq(1:10) 24 | z = 4 25 | sort.sis(x,z) 26 | y -------------------------------------------------------------------------------- /pisano period/cpp/PisanoPeriod.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | long long int A[1000000]; 5 | 6 | long long int findPeriod(long long int m){ 7 | A[0]=0; 8 | A[1]=1; 9 | int i; 10 | for(i=2;i<=m*m;i++){ 11 | A[i] = (A[i-1] + A[i-2])%m; 12 | A[i+1] = (A[i] + A[i-1])%m; 13 | if(A[i]%m == 0 && A[i+1]%m == 1) 14 | break; 15 | } 16 | return i; 17 | } 18 | 19 | int main(){ 20 | long long int n,m,p; 21 | cout<<"Enter a number "; 22 | cin>>m; 23 | p=findPeriod(m); 24 | cout<<"\nThe Pisano Period is "< 0 { 8 | 9 | for i := 0; i < len(numbers); i++ { 10 | 11 | if numbers[i] == item { 12 | return numbers[i] 13 | } 14 | 15 | } 16 | 17 | } 18 | 19 | return -1 20 | } 21 | 22 | func main() { 23 | 24 | numbers := []int{5, 3, 4, 2, 1, 6, 7, 8, 10, 9} 25 | 26 | result := linearSearch(numbers, 7) 27 | 28 | if result != -1 { 29 | fmt.Println("Item", result, "is found!") 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /dynamic_programming/max_product_subarray.py: -------------------------------------------------------------------------------- 1 | def max_product(nums): 2 | n = len(nums) 3 | 4 | ans = nums[0] 5 | maxy = mini = ans 6 | for i in range(1, n): 7 | 8 | if nums[i] < 0: 9 | maxy, mini = mini, maxy 10 | 11 | maxy = max(nums[i], maxy * nums[i]) 12 | mini = min(nums[i], mini * nums[i]) 13 | 14 | ans = max(ans, maxy) 15 | 16 | return ans 17 | 18 | if __name__ == '__main__': 19 | ans = max_product([2, 3, -2, 4]) 20 | assert ans == 6, "Wrong answer" 21 | print(ans) 22 | 23 | -------------------------------------------------------------------------------- /selection_sort/dart/selectionSoft.dart: -------------------------------------------------------------------------------- 1 | main() { 2 | selectionSort([173, 76, 90, 1, 0]); 3 | } 4 | 5 | void selectionSort(List list) { 6 | if (list == null || list.length == 0) return; 7 | int n = list.length; 8 | int i, steps; 9 | for (steps = 0; steps < n; steps++) { 10 | for (i = steps + 1; i < n; i++) { 11 | if(list[steps] > list[i]) { 12 | swap(list, steps, i); 13 | } 14 | } 15 | } 16 | print(list); 17 | } 18 | 19 | void swap(List list, int steps, int i) { 20 | int temp = list[steps]; 21 | list[steps] = list[i]; 22 | list[i] = temp; 23 | } -------------------------------------------------------------------------------- /linkedlist/python/FindingLengthOfLinkedList.py: -------------------------------------------------------------------------------- 1 | import LinkedList 2 | 3 | def checkLength(linkedList): 4 | count = 0 5 | temp = linkedList.head 6 | while(temp != None): 7 | count += 1 8 | temp = temp.next 9 | 10 | return count 11 | 12 | if __name__ == '__main__': 13 | myLinkedList = LinkedList.LinkedList() 14 | for i in range(10): 15 | myLinkedList.insertAtStart(i) 16 | myLinkedList.printLinkedList() 17 | print() 18 | print('Length:', checkLength(myLinkedList)) 19 | 20 | # OUTPUT: 21 | # 9 8 7 6 5 4 3 2 1 0 22 | # Length: 10 -------------------------------------------------------------------------------- /insertion_sort/Python/insertion_sort.py: -------------------------------------------------------------------------------- 1 | # Python program for implementation of Insertion Sort 2 | 3 | # Function to do insertion sort 4 | def insertion_Sort(arr): 5 | 6 | # Traverse through 1 to length of array 7 | for i in range(1, len(arr)): 8 | key = arr[i] 9 | j = i-1 10 | while j >= 0 and key < arr[j] : 11 | arr[j + 1] = arr[j] 12 | j -= 1 13 | arr[j + 1] = key 14 | 15 | # Driver code to test above 16 | arr = [12, 11, 13, 5, 6] 17 | insertion_Sort(arr) 18 | for i in range(len(arr)): 19 | print ("% d" % arr[i]) 20 | -------------------------------------------------------------------------------- /bogo_sort/python/bogoSort.py: -------------------------------------------------------------------------------- 1 | # BOGO SORT in Python 2 | 3 | import random 4 | 5 | def bogoSort(a): 6 | n = len(a) 7 | while (is_sorted(a) == False): 8 | shuffle(a) 9 | 10 | 11 | def is_sorted(a): 12 | n = len(a) 13 | for i in range(0, n-1): 14 | if (a[i] > a[i+1]): 15 | return False 16 | return True 17 | 18 | 19 | def shuffle(a): 20 | n = len(a) 21 | for i in range(0, n): 22 | r = random.randint(0, n-1) 23 | a[i], a[r] = a[r], a[i] 24 | 25 | 26 | # MAIN 27 | a = [5, 4, -3, 2, 1] 28 | bogoSort(a) 29 | print("Sorted array :") 30 | for i in range(len(a)): 31 | print("%d" % a[i], end=" ") 32 | -------------------------------------------------------------------------------- /dynamic_programming/coin-change-problem.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Recurrence Relation : solution[i][j] = solution[i-1][j] + solution[i][j-Sv] 3 | where Sv is the coin of value v being considered 4 | ''' 5 | 6 | def getWays(n, c): 7 | cache=[1]+[0]*(n) 8 | for coin in c: 9 | for i in range(coin,n+1): 10 | cache[i]+=cache[i-coin] 11 | #Enable below line to see how the cache changes 12 | #print(cache) 13 | return(cache[n]) 14 | 15 | 16 | coin_denominations=[2, 5, 3, 6] 17 | total=10 18 | 19 | print("No of Ways to give change for "+str(total)+" units:",getWays(total,coin_denominations)) -------------------------------------------------------------------------------- /palindrome_checker/clang/palindrome.c: -------------------------------------------------------------------------------- 1 | // Prg to check if a string is palindrome in C 2 | 3 | #include 4 | #include 5 | 6 | void isPalindrome(char str[]) 7 | { 8 | int l = 0; 9 | int h = strlen(str) - 1; 10 | 11 | while (h > l) 12 | { 13 | if (str[l++] != str[h--]) 14 | { 15 | printf("%s is Not Palindrome.\n", str); 16 | return; 17 | } 18 | } 19 | printf("%s is Palindrome!\n", str); 20 | } 21 | 22 | 23 | // MAIN 24 | int main() 25 | { 26 | isPalindrome("mom"); 27 | isPalindrome("1011"); 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /towers_of_hanoi/javascript/hanoi.js: -------------------------------------------------------------------------------- 1 | function towerHanoi(disc, src, des, buffer) { 2 | if (disc >= 1) { 3 | 4 | // Move a tower of disc-1 to the buffer, using the destination. 5 | towerHanoi(disc - 1, src, buffer, des); 6 | 7 | // Move the remaining disk to the destination. 8 | console.log('Move disk from tower ', src, ' to tower ', des); 9 | 10 | // Move the tower of `disc-1` from the `buffer` to the `destination` using the `source`. 11 | towerHanoi(disc - 1, buffer, des, src); 12 | } 13 | 14 | return; 15 | } 16 | 17 | towerHanoi(3, "A", "C", "B"); -------------------------------------------------------------------------------- /counting_sort/javascript/counting_sort.js: -------------------------------------------------------------------------------- 1 | var array = prompt("Enter your comma seperated array").split(","); 2 | 3 | alert("Array before sorting: " + array) 4 | 5 | len = array.length; 6 | min = Math.min(...array); 7 | max = Math.max(...array); 8 | 9 | count = []; 10 | 11 | for(i = min; i <= max; i++) { 12 | count[i] = 0; 13 | } 14 | 15 | for(i = 0; i < len; i++) { 16 | count[array[i]]++; 17 | } 18 | 19 | index = 0 20 | 21 | for (i = min; i <= max; i++) { 22 | while (count[i] > 0) { 23 | array[index] = i; 24 | index++; 25 | count[i]--; 26 | } 27 | } 28 | 29 | alert("Array after sorting: " + array); 30 | -------------------------------------------------------------------------------- /queues/ruby/queue.rb: -------------------------------------------------------------------------------- 1 | def enqueue(val,queue) 2 | queue << val 3 | end 4 | 5 | def dequeue(queue) 6 | if queue.empty? == true 7 | "underflow" 8 | else 9 | queue.pop 10 | end 11 | end 12 | 13 | queue = Queue.new 14 | while true 15 | puts "Select Operation(1 or 2)" 16 | puts "1.Enqueue" 17 | puts "2.Dequeue" 18 | inp = Integer(gets) 19 | if inp == 1 20 | puts "Enter value" 21 | val = Integer(gets) 22 | enqueue(val,queue) 23 | elsif inp == 2 24 | val = dequeue(queue) 25 | puts val 26 | break if val == "underflow" 27 | end 28 | end -------------------------------------------------------------------------------- /towers_of_hanoi/java/Tower.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class Tower 3 | { 4 | void tower_Of_Hanoi(int n, char first, char second, char third) 5 | { 6 | if (n==1) 7 | { 8 | System.out.println("Disk 1: from rod "+first+" to rod "+second); 9 | return; 10 | } 11 | tower_Of_Hanoi(n-1, first, third, second); 12 | System.out.println("Disk "+n+": from rod "+first+" to rod "+second); 13 | tower_Of_Hanoi(n-1, third, second, first); 14 | } 15 | void main() 16 | { 17 | int n=3; 18 | tower_Of_Hanoi(n, 'A', 'B', 'C'); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /stack/ruby/stack.rb: -------------------------------------------------------------------------------- 1 | def pushing(val,stack) 2 | stack << val 3 | end 4 | 5 | def poping(stack) 6 | if stack.length == 0 7 | "underflow" 8 | else 9 | stack.pop 10 | end 11 | end 12 | 13 | stack = [] 14 | while true 15 | puts "Select Operation(1 or 2)" 16 | puts "1.Push" 17 | puts "2.Pop" 18 | inp = Integer(gets) 19 | if inp == 1 20 | puts "Enter value" 21 | val = Integer(gets) 22 | pushing(val,stack) 23 | elsif inp == 2 24 | val = poping(stack) 25 | puts val 26 | break if val == "underflow" 27 | end 28 | end -------------------------------------------------------------------------------- /fibonacci/java/fibonacci.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Scanner; 3 | 4 | public class fibo { 5 | 6 | // An optimized version of Fibonacci 7 | public static int fib(int n) { 8 | int a = 0; 9 | int b = 1; 10 | int c = 0; 11 | for (int i = 0; i < n; i++) { 12 | c = a + b; 13 | a = b; 14 | b = c; 15 | } 16 | return c; 17 | } 18 | 19 | public static void main(String[] args) { 20 | Scanner in = new Scanner(System.in); 21 | int a = in.nextInt(); 22 | System.out.println("fib(" + a + ") = " + fib(a)); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /binary_search/python/binarysearch.py: -------------------------------------------------------------------------------- 1 | def binary(l,k): 2 | lb=0 3 | ub=len(l)-1 4 | while ubk: 9 | ub=mid 10 | else: 11 | return(mid) 12 | return -1 13 | 14 | print("Enter the number of elements") 15 | n=int(input()) 16 | l=[0]*n 17 | ans=-1 18 | print("Enter the sorted list of elements") 19 | for i in range(n): 20 | l[i]=int(input()) 21 | print("Enter the element to search") 22 | k=int(input()) 23 | r=0 24 | r=binary(l,k) 25 | if r!=-1: 26 | print("element is present at -") 27 | print(r) 28 | else: 29 | print("not present") 30 | 31 | 32 | -------------------------------------------------------------------------------- /binary_search/ruby/binary_search.rb: -------------------------------------------------------------------------------- 1 | def binary_search (target,ar) 2 | begins = 0 ; ends = ar.length-1 3 | not_found = true 4 | while begins <= ends 5 | mid = (begins + ends)/2 6 | if target > ar[mid] 7 | begins = mid + 1 8 | elsif target < ar[mid] 9 | ends = mid - 1 10 | elsif target == ar[mid] 11 | not_found = false 12 | return "Found at index #{mid}" 13 | break 14 | end 15 | end 16 | return "Doesn't Exists" if not_found == true 17 | end 18 | 19 | ar = [1,2,3,8,31,32,68,78,213,224,564,3211,24453,78674] 20 | print binary_search(564,ar) -------------------------------------------------------------------------------- /linear_search/C/linearsearch.c: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int search(int arr[], int n, int x) 4 | { 5 | int i; 6 | for (i = 0; i < n; i++) 7 | if (arr[i] == x) 8 | return i; 9 | return -1; 10 | } 11 | 12 | int main(void) 13 | { 14 | int arr[] = { 2, 3, 4, 10, 40 }; 15 | int x = 10; 16 | int n = sizeof(arr) / sizeof(arr[0]); 17 | int result = search(arr, n, x); 18 | (result == -1) ? printf("Element is not present in array") 19 | : printf("Element is present at index %d", 20 | result); 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /fibonacci/python/Fibonacci_Series.py: -------------------------------------------------------------------------------- 1 | aString= input("Enter the number of length:") 2 | a=int(aString) 3 | 4 | 5 | def fibonacci1(n): #Fibonacci Series by recursion 6 | if n==1 or n==2: 7 | return 1 8 | return fibonacci1(n-1) + fibonacci1(n-2) 9 | 10 | def fibonacci2(n): #Fibonacci series by Loop 11 | a,b =0, 1 12 | for i in range(n-1): 13 | a,b = b, a+b 14 | return a 15 | 16 | print("Fibonacci Series by recursion") 17 | for i in range(1,a): 18 | print(fibonacci1(i)) 19 | 20 | 21 | 22 | print("\nFibonacci Series by Loop") 23 | for i in range(1,a): 24 | print(fibonacci2(i)) -------------------------------------------------------------------------------- /maximum_contiguous_subarray_sum_kadane's_algorithm/python/maxsubarraysum.py: -------------------------------------------------------------------------------- 1 | import sys 2 | def maximumsum(a,n): 3 | max_so_far = -sys.maxsize 4 | max_till_here = 0 5 | n=len(a) 6 | for i in range(n): 7 | max_till_here+=a[i] 8 | if max_so_far transactions = new ArrayList<>(); 7 | transactions.add("aa"); 8 | transactions.add("bb"); 9 | transactions.add("dd"); 10 | transactions.add("ee"); 11 | 12 | transactions.add("22"); 13 | transactions.add("11"); 14 | transactions.add("44"); 15 | transactions.add("33"); 16 | transactions.add("55"); 17 | 18 | MerkleTree merkleTree = new MerkleTree(transactions); 19 | System.out.println(merkleTree.getMerkleRoot().get(0)); 20 | } 21 | 22 | 23 | 24 | } 25 | -------------------------------------------------------------------------------- /fibonacci/c#/fibonacci.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | public class FibonacciExample 3 | { 4 | public static void Main(string[] args) 5 | { 6 | int n1=0,n2=1,n3,i,number; 7 | Console.Write("Enter the number of elements: "); 8 | number = int.Parse(Console.ReadLine()); 9 | Console.Write(n1+" "+n2+" "); //printing 0 and 1 10 | for(i=2;i= 0 && (unsortedList[j] > tmp); j--) { 7 | //Shift the number 8 | unsortedList[j + 1] = unsortedList[j]; 9 | } 10 | //Insert the copied number at the correct position 11 | //in sorted part. 12 | unsortedList[j + 1] = tmp; 13 | } 14 | } 15 | 16 | var ul = [5, 3, 1, 2, 4]; 17 | insertionSort(ul); 18 | console.log(ul); -------------------------------------------------------------------------------- /binary_search/javascript/binary_search.js: -------------------------------------------------------------------------------- 1 | function binary_search(arr,element){ 2 | var left=0; 3 | var right=arr.length-1; 4 | while(right>=left){ 5 | var mid=Math.floor(left+(right-left)/2); 6 | if(arr[mid]==element) 7 | {return mid;} 8 | if(arr[mid]>element) 9 | { right=mid-1;} 10 | else 11 | {left=mid+1;} 12 | 13 | } 14 | return false; 15 | } 16 | 17 | var arr=[50,100,60,85,25,30,95,158,563,1000,5,9,7]; 18 | var element=60; 19 | //binary search works on a sorted array 20 | 21 | arr.sort((a,b)=>a-b); 22 | binary_search(arr,element)?console.log("Data Found"):console.log("Data Not Found"); -------------------------------------------------------------------------------- /fibonacci/cpp/fibonacci_explained.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int n, t1 = 0, t2 = 1, nextTerm = 0; 6 | cout << "Enter the number of terms: "; 7 | cin >> n; 8 | cout << "Fibonacci Series: "; 9 | for (int i = 1; i <= n; ++i) 10 | { 11 | // Prints the first two terms. 12 | if(i == 0) 13 | { 14 | cout << " " << t1; 15 | } 16 | if(i == 1) 17 | { 18 | cout << t2 << " "; 19 | } 20 | nextTerm = t1 + t2; 21 | t1 = t2; 22 | t2 = nextTerm; 23 | 24 | cout << nextTerm << " "; 25 | } 26 | return 0; 27 | } -------------------------------------------------------------------------------- /insertion_sort/cpp/insertion_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | void main() 4 | { 5 | clrscr(); 6 | int size, arr[50], i, j, temp; 7 | cout<<"Enter Array Size : "; 8 | cin>>size; 9 | cout<<"Enter Array Elements : "; 10 | for(i=0; i>arr[i]; 13 | } 14 | cout<<"Sorting array using selection sort ... \n"; 15 | for(i=1; i=0)) 20 | { 21 | arr[j+1]=arr[j]; 22 | j=j-1; 23 | } 24 | arr[j+1]=temp; 25 | } 26 | cout<<"Array after sorting : \n"; 27 | for(i=0; i a[j+1]) { 14 | int temp = a[j]; 15 | a[j] = a[j+1]; 16 | a[j+1] = temp; 17 | is_sorted = false; 18 | } 19 | } 20 | if(is_sorted) return; 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /bubble_sort/ruby/bubble_sort.rb: -------------------------------------------------------------------------------- 1 | def bub_sort(ar) 2 | i = 0 ; temp = 0 3 | swap_count = 0 4 | while true 5 | while i < ar.length-1 6 | if ar[i] > ar[i+1] 7 | temp = ar[i+1] 8 | ar[i+1] = ar[i] 9 | ar[i] = temp 10 | swap_count += 1 11 | end 12 | i+=1 13 | end 14 | if swap_count == 0 15 | break 16 | else 17 | swap_count = 0 18 | i = 0 19 | end 20 | end 21 | ar 22 | end 23 | 24 | ar = [1,21,3,22,54,12,18,0,19,18,1221,61,64,897,122231] 25 | print "#{bub_sort(ar)}" 26 | -------------------------------------------------------------------------------- /greedy/cpp/Knapsack.java: -------------------------------------------------------------------------------- 1 | class Knapsack 2 | { 3 | 4 | static int max(int a, int b) { return (a > b)? a : b; } 5 | 6 | static int knapSack(int W, int wt[], int val[], int n) 7 | { 8 | if (n == 0 || W == 0) 9 | return 0; 10 | 11 | if (wt[n-1] > W) 12 | return knapSack(W, wt, val, n-1); 13 | 14 | else return max( val[n-1] + knapSack(W-wt[n-1], wt, val, n-1), 15 | knapSack(W, wt, val, n-1) 16 | ); 17 | } 18 | 19 | public static void main(String args[]) 20 | { 21 | int val[] = new int[]{60, 100, 120}; 22 | int wt[] = new int[]{10, 20, 30}; 23 | int W = 50; 24 | int n = val.length; 25 | System.out.println(knapSack(W, wt, val, n)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /linear_search/java/Linear.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | import java.util.Scanner; 4 | 5 | public class Linear 6 | { 7 | static int search(int A[], int M) 8 | { 9 | for(int i=0; i= 0) && (array[i] > key); i--) 22 | { 23 | array[i + 1] = array[i]; 24 | } 25 | array[i + 1] = key; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /binary_search/Kotlin/binary_search.kt: -------------------------------------------------------------------------------- 1 | fun binarySearch(item: String, list: List): Boolean { 2 | // Exit conditions (base cases) 3 | if (list.isEmpty()) { 4 | return false 5 | } 6 | 7 | // Setup probe 8 | val probeIndex = list.size / 2 9 | val probeItem = list[probeIndex] 10 | 11 | // Does the probe match? If not, split and recurse 12 | when { 13 | item == probeItem -> return true 14 | item < probeItem -> return binarySearch(item, 15 | list.subList(0, probeIndex)) 16 | else -> return binarySearch(item, 17 | list.subList(probeIndex + 1, size)) 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /depth_first_search/golang/dfs_test.go: -------------------------------------------------------------------------------- 1 | package dfs 2 | 3 | import ( 4 | "bytes" 5 | "strings" 6 | "testing" 7 | ) 8 | 9 | func TestDFS(t *testing.T) { 10 | t2a := &tree{left: nil, value: 4, right: nil} 11 | t2b := &tree{left: nil, value: 5, right: nil} 12 | 13 | t1a := &tree{left: t2a, value: 2, right: t2b} 14 | t1b := &tree{left: nil, value: 3, right: nil} 15 | 16 | t0 := &tree{left: t1a, value: 1, right: t1b} 17 | 18 | /* Tree 19 | 1 20 | 2 3 21 | 4 5 22 | */ 23 | 24 | var w bytes.Buffer 25 | traverse(t0, &w) 26 | 27 | actual := strings.TrimSpace(w.String()) 28 | expected := "1 2 4 5 3" 29 | 30 | if actual != expected { 31 | t.Errorf("Expected %s but got %s", expected, actual) 32 | } 33 | } -------------------------------------------------------------------------------- /binary_search/Go/binary_search.go: -------------------------------------------------------------------------------- 1 | // Binary Search in Golang 2 | 3 | package main 4 | import "fmt" 5 | 6 | func binarySearch(needle int, haystack []int) bool { 7 | 8 | low := 0 9 | high := len(haystack) - 1 10 | 11 | for low <= high{ 12 | median := (low + high) / 2 13 | 14 | if haystack[median] < needle { 15 | low = median + 1 16 | }else{ 17 | high = median - 1 18 | } 19 | } 20 | 21 | if low == len(haystack) || haystack[low] != needle { 22 | return false 23 | } 24 | 25 | return true 26 | } 27 | 28 | 29 | func main(){ 30 | items := []int{1,2, 9, 20, 31, 45, 63, 70, 100} 31 | fmt.Println(binarySearch(63, items)) 32 | } 33 | -------------------------------------------------------------------------------- /euclidean_gcd/java/euclidean_gcd_using_recursion.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class gcd { 3 | 4 | static int gcd(int x,int y) 5 | { 6 | if(x==0||y==0) 7 | { 8 | return 0; 9 | } 10 | else if(y == x) 11 | { 12 | return x; 13 | } 14 | else if(x>y) 15 | return gcd(x-y,y); 16 | else 17 | return gcd(x,y-x); 18 | 19 | } 20 | 21 | 22 | 23 | public static void main(String[] args) { 24 | Scanner in = new Scanner(System.in); 25 | System.out.println("enter two nos"); 26 | int a = in.nextInt(); 27 | int b = in.nextInt(); 28 | int ans = gcd(a,b); 29 | System.out.println(ans); 30 | 31 | } 32 | 33 | 34 | } -------------------------------------------------------------------------------- /euclidean_gcd/java/euclidean_gcd.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class euclidean_gcd { 4 | 5 | private static int gcd = 0; 6 | private static int count = 0; 7 | 8 | private static int euclideanGcd(int a, int b) { 9 | if(a > b) { 10 | count = b; 11 | } else { 12 | count = a; 13 | } 14 | 15 | for(int j = 1; j < count + 1; j++) { 16 | if(a % j == 0 && b % j == 0) { 17 | gcd = j; 18 | } 19 | } 20 | 21 | return gcd; 22 | } 23 | 24 | public static void main(String[] args) { 25 | Scanner scanner = new Scanner(System.in); 26 | 27 | int a = scanner.nextInt(); 28 | int b = scanner.nextInt(); 29 | 30 | System.out.println(euclideanGcd(a, b)); 31 | 32 | scanner.close(); 33 | } 34 | } -------------------------------------------------------------------------------- /insertion_sort/golang/sort_test.go: -------------------------------------------------------------------------------- 1 | package sort 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestInsertionSort(t *testing.T) { 9 | testCases := []struct { 10 | in []int 11 | exp []int 12 | }{ 13 | { 14 | in: []int{1, 2, 3, 4, 5}, 15 | exp: []int{1, 2, 3, 4, 5}, 16 | }, 17 | { 18 | in: []int{1, 2, 1, 5, 4}, 19 | exp: []int{1, 1, 2, 4, 5}, 20 | }, 21 | { 22 | in: []int{5, 4, 3, 2, 1}, 23 | exp: []int{1, 2, 3, 4, 5}, 24 | }, 25 | } 26 | for _, tC := range testCases { 27 | t.Run("", func(t *testing.T) { 28 | actual := InsertionSort(tC.in) 29 | if !reflect.DeepEqual(actual, tC.exp) { 30 | t.Errorf("expected %v but got %v", tC.exp, tC.in) 31 | } 32 | }) 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /linear_search/cpp/linear_search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int arr[100]; 6 | int i=0; 7 | int n=0; 8 | int flag=0; 9 | int size=0; 10 | int p=0; 11 | cout<<"Enter size of array "<>size; 13 | cout<<"Enter Elements of the array "<>arr[i]; 17 | } 18 | cout<<"Enter the number to be found "; 19 | cin>>n; 20 | for(i=0; i 5 | using namespace std; 6 | 7 | void hanoi_tower(char peg1, char peg2, char peg3, int n) 8 | { 9 | if( n <= 0) 10 | cout << "\n Illegal entry "; 11 | 12 | if(n == 1) 13 | cout << "\n Move Disk from %c to %c", peg1, peg3; 14 | else 15 | { 16 | hanoi_tower(peg1, peg3, peg2, n-1); 17 | hanoi_tower(peg1, peg2, peg3, 1); 18 | hanoi_tower(peg2, peg1, peg3, n-1); 19 | } 20 | } 21 | 22 | /* main function */ 23 | 24 | int main() 25 | { 26 | int n; 27 | cout << "\n Input the number of disc: "; 28 | cin >> n; 29 | cout << "\n Tower of Hanoi for %d DISC", n; 30 | hanoi_tower('X', 'Y', 'Z', n); 31 | 32 | return 0; 33 | } -------------------------------------------------------------------------------- /binary_search/java/binary_search.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Returns index of value in values array or -1 if array doesn't contain specified element 3 | * @param values array with integers to search in 4 | * @param value integer value to search in values 5 | * @param start first index of array to search in 6 | * @param end last index of array to search in 7 | */ 8 | public int binary_search(int [] values, int value, int start, int end) { 9 | if(end >= 1) { 10 | int middle = (start+end)/2; 11 | if(values[middle] == value) 12 | return middle; 13 | 14 | if (values[middle] > value) 15 | return binary_search(values, value, start, middle-1); 16 | else 17 | return binary_search(values, value, middle+1, end); 18 | } 19 | 20 | return -1; 21 | } 22 | -------------------------------------------------------------------------------- /Newton Rhapson/kotlin/newton_rhapson.kt: -------------------------------------------------------------------------------- 1 | import java.lang.Math.pow 2 | import kotlin.math.abs 3 | import kotlin.math.cos 4 | import kotlin.math.sin 5 | 6 | fun main() { 7 | var p0 = 0.5 8 | var tolerance = 0.00001 9 | var p : Double = 0.0 10 | 11 | print("Enter maximum number of iterations: ") 12 | var iteration : Int = readLine()!!.toInt() 13 | var i = 1 14 | while (i < iteration){ 15 | p = p0 - (cos(p0) - p0) / (-sin(p0) - 1) 16 | if (abs(p - p0) < tolerance){ 17 | println("Procedure Completed Successfully. \n Solution is (X = $p0") 18 | }else{ 19 | println("Method failed after iteration number $p0 \n Procedure completed unsuccessfully") 20 | } 21 | p0 = p 22 | i++ 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /palindrome_checker/cpp/palindrome.cpp: -------------------------------------------------------------------------------- 1 | // Prg to check if a string is palindrome in C++ 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | void isPalindrome(char og[]) 8 | { 9 | char rev[100]; 10 | /* Reversing the string */ 11 | int i, n = strlen(og); 12 | for (i = 0; i < n; i++) 13 | { 14 | rev[n - 1 - i] = og[i]; 15 | } 16 | 17 | if (strcmp(og, rev) == 0) /* Comparing input string with the reverse string */ 18 | cout << "The string is a palindrome!\n"; 19 | else 20 | cout << "The string is not a palindrome.\n"; 21 | } 22 | 23 | 24 | // MAIN 25 | int main() 26 | { 27 | char og[100]; 28 | cout << "Enter the string : "; 29 | cin >> og; 30 | isPalindrome(og); 31 | return 0; 32 | } -------------------------------------------------------------------------------- /counting_sort/Kotlin/counting_sort.kt: -------------------------------------------------------------------------------- 1 | fun counting_sort(list: MutableList) { 2 | // Create temp array to count the # occurrences of each value in the list 3 | // - The index of the countingArray maps to values of items in the list 4 | // - countingArray[index] maps to # occurrences of that value 5 | val countingArray = IntArray(if (list.max() == null) 0 else list.max()!! + 1) 6 | for (item in list) countingArray[item]++ 7 | 8 | // Regenerate the list using the countingArray 9 | var cursor = 0 10 | for (index in 0 until countingArray.size) { 11 | val value = index 12 | val numberOfOccurrences = countingArray[index] 13 | if (numberOfOccurrences > 0) 14 | repeat(numberOfOccurrences) {list[cursor++] = value} 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /bubble_sort/golang/bubble_sort_test.go: -------------------------------------------------------------------------------- 1 | package golang 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func Test_bubbleSort(t *testing.T) { 9 | type args struct { 10 | array []int 11 | } 12 | tests := []struct { 13 | name string 14 | args args 15 | want []int 16 | }{ 17 | { 18 | name: "Simple test case", 19 | args: args{array: []int{1, 2, 1, 4, 3}}, 20 | want: []int{1, 1, 2, 3, 4}, 21 | }, 22 | { 23 | name: "Passing an empty array", 24 | args: args{array: []int{}}, 25 | want: []int{}, 26 | }, 27 | } 28 | for _, tt := range tests { 29 | t.Run(tt.name, func(t *testing.T) { 30 | if got := bubbleSort(tt.args.array); !reflect.DeepEqual(got, tt.want) { 31 | t.Errorf("bubbleSort() = %v, want %v", got, tt.want) 32 | } 33 | }) 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /counting_sort/python/update_counting_sort.py: -------------------------------------------------------------------------------- 1 | """ Sorting Technique -- Counting Sort 2 | Input -- A range(Max element in the seq. of array + 1) and a sequence of n numbers 3 | Output -- Reordered into a definite sequence {Ascending(HERE)} 4 | 5 | Time Complexity :- 6 | Worst Case - O(N^2) 7 | Best Case - O(N + RANGE) """ 8 | 9 | print("Enter Range -- ",end='') 10 | Range = int(input()) 11 | arr = list(map(int, input().split())) 12 | buckets = [0]*Range 13 | sortedIndex = 0 14 | 15 | for i in arr : 16 | buckets[i] += 1 17 | for index in range(len(buckets)) : 18 | while buckets[index] > 0 : 19 | arr[sortedIndex] = index 20 | sortedIndex += 1 21 | buckets[index] -= 1 22 | print("Sorted Output -- ", end='') 23 | print(' '.join([str(x) for x in arr])) 24 | -------------------------------------------------------------------------------- /depth_first_search/python/dfs.py: -------------------------------------------------------------------------------- 1 | # Python3 program to print DFS traversal 2 | from collections import defaultdict 3 | 4 | class Graph: 5 | 6 | def __init__(self): 7 | 8 | self.graph = defaultdict(list) 9 | 10 | def addEdge(self, u, v): 11 | self.graph[u].append(v) 12 | 13 | def DFSUtil(self, v, visited): 14 | visited[v] = True 15 | print(v, end = ' ') 16 | for i in self.graph[v]: 17 | if visited[i] == False: 18 | self.DFSUtil(i, visited) 19 | 20 | def DFS(self, v): 21 | visited = [False] * (len(self.graph)) 22 | self.DFSUtil(v, visited) 23 | 24 | 25 | # Driver code 26 | g = Graph() 27 | g.addEdge(0, 1) 28 | g.addEdge(0, 2) 29 | g.addEdge(1, 2) 30 | g.addEdge(2, 0) 31 | g.addEdge(2, 3) 32 | g.addEdge(3, 3) 33 | 34 | print("Following is DFS from (starting from vertex 2)") 35 | g.DFS(2) 36 | -------------------------------------------------------------------------------- /towers_of_hanoi/clang/hanoi.c: -------------------------------------------------------------------------------- 1 | /* Tower of Hanoi problem*/ 2 | /* HANOI.C */ 3 | 4 | # include 5 | 6 | void hanoi_tower(char , char , char , int ); 7 | 8 | /* Definition of the Tower Of Hanoi generator function */ 9 | 10 | void hanoi_tower(char peg1, char peg2, char peg3, int n) 11 | { 12 | if( n <= 0) 13 | printf("\n Illegal entry "); 14 | 15 | if(n == 1) 16 | printf("\n Move Disk from %c to %c", peg1, peg3); 17 | else 18 | { 19 | hanoi_tower(peg1, peg3, peg2, n-1); 20 | hanoi_tower(peg1, peg2, peg3, 1); 21 | hanoi_tower(peg2, peg1, peg3, n-1); 22 | } 23 | } 24 | 25 | /* main function */ 26 | 27 | int main() 28 | { 29 | int n; 30 | printf("\n Input the number of disc: "); 31 | scanf("%d", &n); 32 | printf("\n Tower of Hanoi for %d DISC", n); 33 | hanoi_tower('X', 'Y', 'Z', n); 34 | 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /fibonacci/golang/fibonacci_test.go: -------------------------------------------------------------------------------- 1 | package golang 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func Test_fib(t *testing.T) { 9 | type args struct { 10 | n int 11 | } 12 | tests := []struct { 13 | name string 14 | args args 15 | want []int 16 | }{ 17 | { 18 | name: "Passing 0 as the args", 19 | args: args{n: 0}, 20 | want: []int{}, 21 | }, 22 | { 23 | name: "Passign legit number", 24 | args: args{n: 2}, 25 | want: []int{1, 1}, 26 | }, 27 | { 28 | name: "Passign legit number", 29 | args: args{n: 5}, 30 | want: []int{1, 1, 2, 3, 5}, 31 | }, 32 | } 33 | for _, tt := range tests { 34 | t.Run(tt.name, func(t *testing.T) { 35 | if got := fib(tt.args.n); !reflect.DeepEqual(got, tt.want) { 36 | t.Errorf("fib() = %v, want %v", got, tt.want) 37 | } 38 | }) 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /shell_sort/python/ShellSort.py: -------------------------------------------------------------------------------- 1 | def gaps(size): 2 | # uses the gap sequence 2^k - 1: 1, 3, 7, 15, 31, ... 3 | length = size.bit_length() 4 | for k in range(length - 1, 0, -1): 5 | yield 2 ** k - 1 6 | 7 | 8 | def shell_sort(alist): 9 | def insertion_sort_with_gap(gap): 10 | for i in range(gap, len(alist)): 11 | temp = alist[i] 12 | j = i - gap 13 | while (j >= 0 and temp < alist[j]): 14 | alist[j + gap] = alist[j] 15 | j = j - gap 16 | alist[j + gap] = temp 17 | 18 | for g in gaps(len(alist)): 19 | insertion_sort_with_gap(g) 20 | 21 | 22 | alist = input('Enter the list of numbers: ').split() 23 | alist = [int(x) for x in alist] 24 | shell_sort(alist) 25 | print('Sorted list using Shell Sort Algorithm: ', end='') 26 | print(alist) -------------------------------------------------------------------------------- /breath_first_search/cpp/bfs_tree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Node 5 | { 6 | public: 7 | Node *left; 8 | Node *right; 9 | int data; 10 | Node(int k) 11 | { 12 | this->data=k; 13 | left=NULL; 14 | right=NULL; 15 | } 16 | Node() 17 | { 18 | } 19 | }; 20 | 21 | 22 | int bfs(Node *head) 23 | { 24 | queue q; 25 | Node *temp=head; 26 | while(temp!=NULL) 27 | { 28 | cout<data<<" "; 29 | if(temp->left) 30 | q.push(temp->left); 31 | if(temp->right) 32 | q.push(temp->right); 33 | temp=q.front(); 34 | q.pop(); 35 | } 36 | } 37 | 38 | int main() 39 | { 40 | Node *head=new Node(1); 41 | head->left=new Node(2); 42 | head->right=new Node(3); 43 | head->left->left=new Node(4); 44 | head->left->right=new Node(5); 45 | head->right->right=new Node(6); 46 | bfs(head); 47 | return 0; 48 | } 49 | -------------------------------------------------------------------------------- /interpolation search/python/interpolationsearch.py: -------------------------------------------------------------------------------- 1 | def interpolationSearch(arr, n, x): 2 | lo = 0 3 | hi = (n - 1) 4 | while lo <= hi and x >= arr[lo] and x <= arr[hi]: 5 | if lo == hi: 6 | if arr[lo] == x: 7 | return lo; 8 | return -1; 9 | pos = lo + int(((float(hi - lo) / ( arr[hi] - arr[lo])) * ( x - arr[lo]))) 10 | if arr[pos] == x: 11 | return pos 12 | if arr[pos] < x: 13 | lo = pos + 1; 14 | else: 15 | hi = pos - 1; 16 | 17 | return -1 18 | 19 | arr = [10, 12, 13, 16, 18, 19, 20, 21,22, 23, 24, 33, 35, 42, 47] 20 | n = len(arr) 21 | 22 | x = 18 # 23 | index = interpolationSearch(arr, n, x) 24 | 25 | if index != -1: 26 | print "Element found at index",index 27 | else: 28 | print "Element not found" 29 | -------------------------------------------------------------------------------- /quick_sort/python/quick_sort.py: -------------------------------------------------------------------------------- 1 | """ Created by SubCoder1 on 15-Oct-18. 2 | 3 | Sorting Technique -- Quick Sort 4 | Input -- A sequence of n numbers 5 | Output -- Reordered into a definite sequence {Ascending(HERE)} 6 | 7 | Time Complexity :- 8 | Worst Case - O(N^2) 9 | Best Case - O(NLogN) """ 10 | 11 | def q_sort(array) : 12 | if len(array) > 0 : 13 | left = list() ; right = list() ; equal = list() 14 | pivot = array[0] 15 | for element in array : 16 | if element < pivot : left.append(element) 17 | elif element > pivot : right.append(element) 18 | else : equal.append(element) 19 | return q_sort(left) + equal + q_sort(right) 20 | else : 21 | return array 22 | 23 | array = list(map(int, input().split())) 24 | print(*q_sort(array), end='') 25 | -------------------------------------------------------------------------------- /Secant/Kotlin/secant.kt: -------------------------------------------------------------------------------- 1 | import kotlin.math.abs 2 | import kotlin.math.cos 3 | 4 | fun main() { 5 | var p0 = 0.5 6 | var p1 : Double = (22.0/7.0) / 4 7 | var iterations : Int; 8 | var tolerance = 0.00001 9 | var p : Double 10 | 11 | print("Enter number of iterations: ") 12 | iterations = readLine()!!.toInt() 13 | 14 | var i = 2 15 | var q0 = cos(p0) - p0 16 | var q1 = cos(p1) - p1 17 | 18 | while (i < iterations){ 19 | p = p1 - (q1 * (p1 - q0)) / (q1 - q0) 20 | if ( abs(p - p1) < tolerance){ 21 | println("Procedure Completed Successfully") 22 | 23 | }else{ 24 | println("Method failed after $iterations iterations \n Procedure Completed Successfully") 25 | } 26 | i++ 27 | p0 = p1 28 | q0 = q1 29 | p1 = p 30 | q1 = cos(p) - p 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /shell_sort/python/shell_Sort.py: -------------------------------------------------------------------------------- 1 | # Prg of SHELL SORT in Python 2 | 3 | 4 | def shellSort(arr): 5 | 6 | # Start with a big gap, then reduce the gap 7 | n = len(arr) 8 | gap = n//2 9 | 10 | while gap > 0: 11 | 12 | for i in range(gap, n): 13 | 14 | # add a[i] to the elements that have been gap sorted 15 | # save a[i] in temp and make a hole at position i 16 | temp = arr[i] 17 | 18 | # shift earlier gap-sorted elements up until the correct 19 | # location for a[i] is found 20 | j = i 21 | while j >= gap and arr[j-gap] > temp: 22 | arr[j] = arr[j-gap] 23 | j -= gap 24 | 25 | # put temp (the original a[i]) in its correct location 26 | arr[j] = temp 27 | gap //= 2 28 | 29 | 30 | # MAIN 31 | arr = [5, 4, -3, 2, 1] 32 | n = len(arr) 33 | 34 | shellSort(arr) 35 | 36 | print("\nArray after sorting: ") 37 | for i in range(n): 38 | print(arr[i], end=" ") -------------------------------------------------------------------------------- /binary_search/python/binary_search.py: -------------------------------------------------------------------------------- 1 | class BST: 2 | def __init__(self, val=None): 3 | self.left = None 4 | self.right = None 5 | self.val = val 6 | 7 | def __str__(self): 8 | return "[%s, %s, %s]" % (self.left, str(self.val), self.right) 9 | 10 | def isEmpty(self): 11 | return self.left == self.right == self.val == None 12 | 13 | def insert(self, val): 14 | if self.isEmpty(): 15 | self.val = val 16 | elif val < self.val: 17 | if self.left is None: 18 | self.left = BST(val) 19 | else: 20 | self.left.insert(val) 21 | else: 22 | if self.right is None: 23 | self.right = BST(val) 24 | else: 25 | self.right.insert(val) 26 | 27 | a = BST(1) 28 | a.insert(2) 29 | a.insert(3) 30 | a.insert(0) 31 | print (a) -------------------------------------------------------------------------------- /bubble_sort/python/bubble_sort.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | from __future__ import print_function 3 | 4 | 5 | def bubble_sort(collection): 6 | length = len(collection) 7 | for i in range(length): 8 | swapped = False 9 | for j in range(length-1): 10 | if collection[j] > collection[j+1]: 11 | swapped = True 12 | collection[j], collection[j+1] = collection[j+1], collection[j] 13 | if not swapped: break # Stop iteration if the collection is sorted. 14 | return collection 15 | 16 | 17 | if __name__ == '__main__': 18 | try: 19 | raw_input # Python 2 20 | except NameError: 21 | raw_input = input # Python 3 22 | 23 | user_input = raw_input('Enter numbers separated by a comma:\n').strip() 24 | unsorted = [int(item) for item in user_input.split(',')] 25 | print(bubble_sort(unsorted)) 26 | -------------------------------------------------------------------------------- /breath_first_search/python/bfs.py: -------------------------------------------------------------------------------- 1 | # Python3 Program to print BFS traversal 2 | 3 | from collections import defaultdict 4 | 5 | class Graph: 6 | 7 | def __init__(self): 8 | self.graph = defaultdict(list) 9 | 10 | def addEdge(self,u,v): 11 | self.graph[u].append(v) 12 | 13 | def BFS(self, s): 14 | visited = [False] * (len(self.graph)) 15 | queue = [] 16 | queue.append(s) 17 | visited[s] = True 18 | 19 | while queue: 20 | s = queue.pop(0) 21 | print (s, end = " ") 22 | for i in self.graph[s]: 23 | if visited[i] == False: 24 | queue.append(i) 25 | visited[i] = True 26 | 27 | # Driver code 28 | g = Graph() 29 | g.addEdge(0, 1) 30 | g.addEdge(0, 2) 31 | g.addEdge(1, 2) 32 | g.addEdge(2, 0) 33 | g.addEdge(2, 3) 34 | g.addEdge(3, 3) 35 | 36 | print ("Following is Breadth First Traversal" 37 | " (starting from vertex 2)") 38 | g.BFS(2) 39 | -------------------------------------------------------------------------------- /bogo_sort/cpp/bogoSort.cpp: -------------------------------------------------------------------------------- 1 | // BOGO SORT in C++ 2 | 3 | #include 4 | using namespace std; 5 | 6 | 7 | bool isSorted(int a[], int n) 8 | { 9 | while (--n > 1) 10 | if (a[n] < a[n - 1]) 11 | return false; 12 | return true; 13 | } 14 | 15 | 16 | void shuffle(int a[], int n) 17 | { 18 | for (int i = 0; i < n; i++) 19 | swap(a[i], a[rand() % n]); 20 | } 21 | 22 | 23 | void bogosort(int a[], int n) 24 | { 25 | while (!isSorted(a, n)) 26 | shuffle(a, n); 27 | } 28 | 29 | 30 | void printArray(int a[], int n) 31 | { 32 | for (int i = 0; i < n; i++) 33 | printf("%d ", a[i]); 34 | printf("\n"); 35 | } 36 | 37 | 38 | // MAIN 39 | int main() 40 | { 41 | int a[] = {5, 4, 2, 1, 3}; 42 | int n = sizeof a / sizeof a[0]; 43 | bogosort(a, n); 44 | printf("Sorted array :\n"); 45 | printArray(a, n); 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /merge_sort/javascript/mergeSort.js: -------------------------------------------------------------------------------- 1 | const list = [5, 4, -3, 2, 1] 2 | 3 | const mergeSort = (list) => { 4 | if (list.length <= 1) return list; 5 | const middle = list.length / 2; 6 | const left = list.slice(0, middle); 7 | const right = list.slice(middle, list.length); 8 | return merge(mergeSort(left), mergeSort(right)); 9 | } 10 | 11 | const merge = (left, right) => { 12 | var result = []; 13 | while (left.length || right.length) { 14 | if (left.length && right.length) { 15 | if (left[0] < right[0]) { 16 | result.push(left.shift()) 17 | } else { 18 | result.push(right.shift()) 19 | } 20 | } else if (left.length) { 21 | result.push(left.shift()) 22 | } else { 23 | result.push(right.shift()) 24 | } 25 | } 26 | return result; 27 | } 28 | 29 | console.log(mergeSort(list)) -------------------------------------------------------------------------------- /palindrome_checker/java/PalindromeChecker.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class PalindromeChecker { 4 | 5 | public static void main(String...strings) { 6 | // Input 7 | Scanner scanner = new Scanner(System.in); 8 | 9 | // Print output 10 | if (isPalindrome(scanner.next())) { 11 | System.out.println("This is a palindrome."); 12 | } else { 13 | System.out.println("This is not a palindrome."); 14 | } 15 | 16 | scanner.close(); 17 | } 18 | 19 | static boolean isPalindrome(String s) { 20 | char[] arr = s.toCharArray(); 21 | for (int i = 0; i < arr.length / 2; i++) { 22 | String left = Character.toString(arr[i]); 23 | String right = Character.toString(arr[arr.length - 1 - i]); 24 | if (!left.equalsIgnoreCase(right)) { 25 | return false; 26 | } 27 | } 28 | 29 | return true; 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /heap_sort/dart/heapSort.dart: -------------------------------------------------------------------------------- 1 | void heap(List list, int n, int i) { 2 | int largest = i; 3 | int l = 2*i + 1; 4 | int r = 2*i + 2; 5 | 6 | if (l < n && list[l] > list[largest]) { 7 | largest = l; 8 | } 9 | 10 | if (r < n && list[r] > list[largest]) { 11 | largest = r; 12 | } 13 | 14 | if (largest != i) { 15 | swapList(list, i, largest); 16 | heap(list, n, largest); 17 | } 18 | } 19 | 20 | void swapList(List list, int i, int largest) { 21 | int swap = list[i]; 22 | list[i] = list[largest]; 23 | list[largest] = swap; 24 | } 25 | 26 | void heapSort(List list){ 27 | int n = list.length; 28 | for (int i = (n ~/ 2 ) ; i >= 0; i--){ 29 | heap(list, n, i); 30 | } 31 | 32 | for (int i = n-1; i>=0; i--) { 33 | swap(list, i); 34 | heap(list, i, 0); 35 | } 36 | } 37 | 38 | void swap(List list, int i) { 39 | int temp = list[0]; 40 | list[0] = list[i]; 41 | list[i] = temp; 42 | } -------------------------------------------------------------------------------- /trees/height/python/Height.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding: utf-8 3 | 4 | # In[9]: 5 | 6 | 7 | class Node: 8 | 9 | # Constructor to create a new node 10 | def __init__(self, data): 11 | self.data = data 12 | self.left = None 13 | self.right = None 14 | 15 | def height(node): 16 | if node is None: 17 | return 0 ; 18 | 19 | else : 20 | left_height = height(node.left) 21 | right_height = height(node.right) 22 | 23 | # Use the larger one 24 | if (left_height > right_height): 25 | return left_height+1 26 | else: 27 | return right_height+1 28 | 29 | # Driver code 30 | root = Node(1) 31 | root.left = Node(2) 32 | root.right = Node(3) 33 | root.left.left = Node(4) 34 | root.left.right = Node(5) 35 | 36 | print ("Height of tree is %d" %(height(root))) 37 | 38 | 39 | # In[ ]: 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /trees/height/Clang/height.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | typedef struct s_node { 4 | int data; 5 | struct s_node* left; 6 | struct s_node* right; 7 | } Node; 8 | 9 | int height(Node* node) { 10 | if(node == NULL) { 11 | return 0; 12 | } 13 | int heightLeft = height(node->left); 14 | int heightRight = height(node->right); 15 | 16 | if(heightLeft > heightRight) { 17 | return heightLeft + 1; 18 | } 19 | return heightRight + 1; 20 | } 21 | 22 | 23 | int main(void) { 24 | Node left_left = {4, NULL, NULL}; 25 | Node left_right = {5, NULL, NULL}; 26 | Node left = {2, &left_left, &left_right}; 27 | Node right = {3, NULL, NULL}; 28 | Node root = {1, &left, &right}; 29 | 30 | // Tree Structure is as follows: 31 | // 1 32 | // 🡧 🡦 33 | // 2 3 34 | // 🡧 🡦 35 | // 4 5 36 | // Height = 3 37 | 38 | printf("Height of tree is %d", height(&root)); 39 | } 40 | -------------------------------------------------------------------------------- /merge_sort/golang/merge_sort_test.go: -------------------------------------------------------------------------------- 1 | package golang 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func Test_mergeSort(t *testing.T) { 9 | type args struct { 10 | array []int 11 | } 12 | tests := []struct { 13 | name string 14 | args args 15 | want []int 16 | }{ 17 | { 18 | name: "Simple test case 1", 19 | args: args{array: []int{1, 2, 1, 4, 3}}, 20 | want: []int{1, 1, 2, 3, 4}, 21 | }, 22 | { 23 | name: "Simple test case 2", 24 | args: args{array: []int{90, 30, 5, 3, 15, 1, 2}}, 25 | want: []int{1, 2, 3, 5, 15, 30, 90}, 26 | }, 27 | { 28 | name: "Passing an empty array", 29 | args: args{array: []int{}}, 30 | want: []int{}, 31 | }, 32 | } 33 | for _, tt := range tests { 34 | t.Run(tt.name, func(t *testing.T) { 35 | if got := mergeSort(tt.args.array); !reflect.DeepEqual(got, tt.want) { 36 | t.Errorf("mergeSort() = %v, want %v", got, tt.want) 37 | } 38 | }) 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /trees/merkle_tree/java/SHA256Helper.java: -------------------------------------------------------------------------------- 1 | package blockchain; 2 | 3 | import java.security.MessageDigest; 4 | 5 | public class SHA256Helper { 6 | public static String hash(String data){ 7 | try { 8 | MessageDigest digest = MessageDigest.getInstance("SHA-256"); 9 | byte[] hash = digest.digest(data.getBytes("UTF-8")); 10 | 11 | // TO Hexadecimal value. 12 | StringBuffer hexadecimalString = new StringBuffer(); 13 | 14 | for (int i = 0; i = 0 and b[j] > up: 9 | b[j + 1] = b[j] 10 | j -= 1 11 | b[j + 1] = up 12 | return b 13 | 14 | 15 | def bucketSort(x): 16 | arr = [] 17 | slot_num = 10 # 10 here refers 10 slots; each slot's size being 0.1 18 | for i in range(slot_num): 19 | arr.append([]) 20 | 21 | # Putting array elements in different buckets 22 | for j in x: 23 | index_b = int(slot_num * j) 24 | arr[index_b].append(j) 25 | 26 | # Sorting individual buckets 27 | for i in range(slot_num): 28 | arr[i] = insertionSort(arr[i]) 29 | 30 | # Concatenating the result 31 | k = 0 32 | for i in range(slot_num): 33 | for j in range(len(arr[i])): 34 | x[k] = arr[i][j] 35 | k += 1 36 | return x 37 | 38 | 39 | # MAIN 40 | x = [0.5, 0.4, 0.3, 0.2, 0.1] 41 | print("Sorted Array is :") 42 | print(bucketSort(x)) -------------------------------------------------------------------------------- /quick_sort/javascript/quickSort.js: -------------------------------------------------------------------------------- 1 | /* Function to sort using Quick Sort */ 2 | function quickSort(origArray) { 3 | if (origArray.length <= 1) { 4 | return origArray; 5 | } else { 6 | 7 | var left = []; 8 | var right = []; 9 | var newArray = []; 10 | var pivot = origArray.pop(); 11 | var length = origArray.length; 12 | 13 | for (var i = 0; i < length; i++) { 14 | if (origArray[i] <= pivot) { 15 | left.push(origArray[i]); 16 | } else { 17 | right.push(origArray[i]); 18 | } 19 | } 20 | 21 | return newArray.concat(quickSort(left), pivot, quickSort(right)); 22 | } 23 | } 24 | 25 | /* preDefined Array */ 26 | var myArr = [5, 4, -3, 2, 1]; 27 | 28 | /* Printing the Array */ 29 | console.log("Original array: " + myArr); 30 | var sortedArray = quickSort(myArr); // calling the function 31 | console.log("Sorted array: " + sortedArray); -------------------------------------------------------------------------------- /selection_sort/c#/selection_sort.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | public class Example { 3 | static void Main(string[] args) { 4 | int[] arr = new int[10] { 56, 1, 99, 67, 89, 23, 44, 12, 78, 34 }; 5 | int n = 10; 6 | Console.WriteLine("Selection sort"); 7 | Console.Write("Initial array is: "); 8 | for (int i = 0; i < n; i++) { 9 | Console.Write(arr[i] + " "); 10 | } 11 | int temp, smallest; 12 | for (int i = 0; i < n - 1; i++) { 13 | smallest = i; 14 | for (int j = i + 1; j < n; j++) { 15 | if (arr[j] < arr[smallest]) { 16 | smallest = j; 17 | } 18 | } 19 | temp = arr[smallest]; 20 | arr[smallest] = arr[i]; 21 | arr[i] = temp; 22 | } 23 | Console.WriteLine(); 24 | Console.Write("Sorted array is: "); 25 | for (int i = 0; i < n; i++) { 26 | Console.Write(arr[i] + " "); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /luhn/cpp/luhn.cpp: -------------------------------------------------------------------------------- 1 | // Prg of LUHN ALGO in C++ 2 | 3 | #include 4 | using namespace std; 5 | 6 | 7 | bool checkLuhn(const string &cardNo) 8 | { 9 | int nDigits = cardNo.length(); 10 | 11 | int nSum = 0, isSecond = false; 12 | for (int i = nDigits - 1; i >= 0; i--) 13 | { 14 | 15 | int d = cardNo[i] - '0'; 16 | 17 | if (isSecond == true) 18 | d = d * 2; 19 | 20 | /* Adding the two digits to handle 21 | cases that make double digit number 22 | after doubling */ 23 | nSum += d / 10; 24 | nSum += d % 10; 25 | 26 | isSecond = !isSecond; 27 | } 28 | return (nSum % 10 == 0); 29 | } 30 | 31 | 32 | // MAIN 33 | int main() 34 | { 35 | string cardNo = "79927398713"; 36 | if (checkLuhn(cardNo)) 37 | printf("This is a valid identification number."); 38 | else 39 | printf("This is not a valid identification number."); 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /binary_search/cpp/BINARYSE.CPP: -------------------------------------------------------------------------------- 1 | #include"header.cpp" 2 | 3 | int Binarysearch(int a[],int n,int e) 4 | { 5 | int beg=0,end=n-1,mid=0; 6 | while(beg<=end) 7 | { 8 | mid=(beg+end)/2; 9 | if(a[mid]==e) 10 | return mid; 11 | else if(a[mid]>n; 42 | cout<<"Enter elements of array"; 43 | for(int i=0;i>x[i]; 45 | cout<<"Enter element to be searched"; 46 | cin>>e; 47 | bubblesort(x,n); 48 | 49 | int k=Binarysearch(x,n,e); 50 | if(k>=0) 51 | cout<<"Element found at position- "< 2 | void swap(int *a,int *b) 3 | { 4 | int temp=*a; 5 | *a=*b; 6 | *b=temp; 7 | } 8 | int partition(int a[],int low,int high) 9 | { 10 | int pivot = a[high]; 11 | int i = low-1; 12 | for(int j=low;j<=high-1;j++) 13 | { 14 | if(a[j]<=pivot) 15 | { 16 | i++; 17 | swap(&a[i],&a[j]); 18 | } 19 | } 20 | swap(&a[i+1],&a[high]); 21 | return i+1; 22 | } 23 | void quickSort(int a[],int low,int high) 24 | { 25 | if(low 2 | using namespace std; 3 | 4 | int knapSack(int W, int *wt, int *val, int n) { 5 | int K[n+1][W+1]; 6 | for (int i = 0; i <= n; i++) { 7 | for (int j = 0; j <= W; j++) { 8 | if (i==0 || j==0) 9 | K[i][j] = 0; 10 | else if (wt[i-1] <= j) 11 | K[i][j] = max(val[i-1] + K[i-1][j-wt[i-1]], K[i-1][j]); 12 | else 13 | K[i][j] = K[i-1][j]; 14 | } 15 | } 16 | return K[n][W]; 17 | } 18 | 19 | 20 | int main() { 21 | int n; 22 | cout << "\nNumber of items\t:\t"; 23 | cin >> n; 24 | int val[n] , wt[n]; 25 | for ( int i = 0 ;i < n;i++) { 26 | cout << "\nEnter weight and its value for " << (i+1) << "\n"; 27 | cin >> wt[i]; 28 | cin >> val[i]; 29 | } 30 | int w; 31 | cout << "\nEnter capacity of knapsack\t:\t"; 32 | cin >> w; 33 | cout << "\nThe Result is\t:\t" << knapSack(w, wt, val, n) << endl; 34 | return 0; 35 | } -------------------------------------------------------------------------------- /trees/traversals/Java/btree_level_order: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | class Solution { 11 | public List> levelOrder(TreeNode root) { 12 | List> ans = new ArrayList<>(); 13 | if(root == null) return ans; 14 | 15 | Queue qu = new LinkedList<>(); 16 | qu.add(root); 17 | while(!qu.isEmpty()){ 18 | List temp = new ArrayList<>(); 19 | int size = qu.size(); 20 | for(int i = 0; i < size; i++){ 21 | TreeNode curr = qu.remove(); 22 | temp.add(curr.val); 23 | if(curr.left != null) qu.add(curr.left); 24 | if(curr.right != null) qu.add(curr.right); 25 | } 26 | ans.add(temp); 27 | } 28 | return ans; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /bubble_sort/c#/bubble_sort.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | public class Bubble_Sort 3 | { 4 | public static void Main(string[] args) 5 | { 6 | int[] a = { 3, 0, 2, 5, -1, 4, 1 }; 7 | int t; 8 | Console.WriteLine("Original array :"); 9 | foreach (int aa in a) 10 | Console.Write(aa + " "); 11 | for (int p = 0; p <= a.Length - 2; p++) 12 | { 13 | for (int i = 0; i <= a.Length - 2; i++) 14 | { 15 | if (a[i] > a[i + 1]) 16 | { 17 | t = a[i + 1]; 18 | a[i + 1] = a[i]; 19 | a[i] = t; 20 | } 21 | } 22 | } 23 | Console.WriteLine("\n"+"Sorted array :"); 24 | foreach (int aa in a) 25 | Console.Write(aa + " "); 26 | Console.Write("\n"); 27 | 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /bogo_sort/Java/BogoSort.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class BogoSort{ 4 | 5 | private static final Random generator = new Random(); 6 | 7 | public static void bogoSort(int[] array) { 8 | while (!isSorted(array)) { 9 | for (int i = 0; i < array.length; i++){ 10 | int randomPosition = generator.nextInt(array.length); 11 | int temp = array[i]; 12 | array[i] = array[randomPosition]; 13 | array[randomPosition] = temp; 14 | } 15 | } 16 | } 17 | 18 | private static boolean isSorted(int[] array) { 19 | for (int i = 1; i < array.length; i++){ 20 | if (array[i] < array[i - 1]) { 21 | return false; 22 | } 23 | } 24 | return true; 25 | } 26 | 27 | public static void main(String[] args) { 28 | int [] array = {5,3,0,2,4,1,0,5,2,3,1,4}; 29 | System.out.println("Before: " + Arrays.toString(array)); 30 | bogoSort(array); 31 | System.out.println("After: " + Arrays.toString(array)); 32 | } 33 | } -------------------------------------------------------------------------------- /bubble_sort/clang/bubble_sort.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void print(int arr[], int size) 5 | { 6 | int i; 7 | for (i=0; i < size; i++) 8 | printf("%d ", arr[i]); 9 | } 10 | 11 | void swap(int *x, int *y) 12 | { 13 | int temp = *x; 14 | *x = *y; 15 | *y = temp; 16 | } 17 | 18 | void bubbleSort(int arr[], int size) 19 | { 20 | bool haveSwapped; 21 | int i, j = 0; 22 | 23 | do 24 | { 25 | haveSwapped = false; 26 | for (i = 0; i < size - j - 1; i++) 27 | { 28 | if (arr[i] > arr[i+1]) 29 | { 30 | swap(&arr[i], &arr[i+1]); 31 | haveSwapped = true; 32 | } 33 | } 34 | j++; 35 | } while (haveSwapped); 36 | } 37 | 38 | int main() 39 | { 40 | int arr[] = {7, 6, 5, 4, 3, 2, 1}; 41 | int n = sizeof(arr)/sizeof(arr[0]); 42 | bubbleSort(arr, n); 43 | printf("Sorted array: \n"); 44 | print(arr, n); 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /bubble_sort/cpp/bubble_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void swap(int& x, int & y){ 4 | // Swap without using extra variable 5 | x = x + y; 6 | y = x - y; 7 | x = x - y; 8 | } 9 | 10 | void bubblesort(int a_size, int *a) { 11 | bool swapped = true; //variable to let us know if we have made a swap 12 | int j = 0; 13 | while(swapped) { 14 | swapped = false; 15 | j++; 16 | for(int i=0; i a[i + 1]){ 18 | swap(a[i], a[i + 1]); 19 | swapped = true; 20 | } //if out of order, swap 21 | } 22 | } //loop breaks when a full pass through array without a single swap, meaning the array is sorted 23 | } 24 | 25 | void print_array(int a_size, int *a) { 26 | for(int i=0; i= 0 && flag != 1; ) { 16 | if (val < arr[j]) { 17 | arr[j + 1] = arr[j]; 18 | j--; 19 | arr[j + 1] = val; 20 | } 21 | else flag = 1; 22 | } 23 | } 24 | Console.Write("\nSorted Array is: "); 25 | for (i = 0; i < n; i++) { 26 | Console.Write(arr[i] + " "); 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /bubble_sort/cpp/BUBBLE_A.CPP: -------------------------------------------------------------------------------- 1 | #include"header.cpp" 2 | void bubblesort(int x[],int n) 3 | { 4 | int temp=0,i=0,j=0; 5 | for(i=0;ix[j]) 27 | { 28 | temp=x[j]; 29 | x[j]=x[j+1]; 30 | x[j+1]=temp; 31 | } 32 | } 33 | } 34 | } 35 | 36 | 37 | void main() 38 | { 39 | clrscr(); 40 | int a[100],n=0; 41 | cout<<"Enter number of elements in array"; 42 | cin>>n; 43 | cout<<"Enter the elements"; 44 | for(int i=0;i>a[i]; 46 | cout<<"The old array is\n"; 47 | for(i=0;i transactions; 7 | public MerkleTree(List transactions) { 8 | this.transactions=transactions; 9 | } 10 | 11 | public List getMerkleRoot(){ 12 | return construct(this.transactions); 13 | } 14 | 15 | private List construct (List transactions){ 16 | 17 | if(transactions.size() ==1) return transactions; 18 | 19 | List updatedList = new ArrayList<>(); 20 | 21 | for(int i=0; i 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Node 7 | { 8 | public: 9 | int data; 10 | Node *left; 11 | Node *right; 12 | }; 13 | 14 | Node *newNode(int data) 15 | { 16 | Node *node = new Node(); 17 | node->data = data; 18 | node->left = NULL; 19 | 20 | node->right = NULL; 21 | return (node); 22 | } 23 | 24 | void DFS(Node *root) 25 | { 26 | if (root == NULL) 27 | return; 28 | stack s; 29 | s.push(root); 30 | while (!s.empty()) 31 | { 32 | Node *temp = s.top(); 33 | cout << temp->data << " "; 34 | s.pop(); 35 | if (temp->left != NULL) 36 | s.push(temp->left); 37 | if (temp->right != NULL) 38 | s.push(temp->right); 39 | }; 40 | }; 41 | 42 | int main() 43 | { 44 | Node *root = newNode(4); 45 | root->left = newNode(2); 46 | root->right = newNode(5); 47 | root->left->left = newNode(1); 48 | root->left->right = newNode(3); 49 | DFS(root); 50 | return 0; 51 | }; 52 | -------------------------------------------------------------------------------- /stack/cpp/STACK1D.CPP: -------------------------------------------------------------------------------- 1 | #include 2 | #define MAX 10 3 | using namespace std; 4 | int stac[MAX]; 5 | int top=-1; 6 | 7 | void push(int e) 8 | { 9 | if (top==MAX-1) 10 | { 11 | cout<<"Stack overflow"; 12 | //getch(); 13 | return; 14 | } 15 | top++; 16 | stac[top]=e; 17 | } 18 | 19 | int pop() 20 | { 21 | if (top==-1) 22 | { 23 | cout<<"Stack underflow"; 24 | //getch(); 25 | return(0); 26 | } 27 | int c=stac[top]; 28 | top--; 29 | return c; 30 | } 31 | 32 | void traverse() 33 | { 34 | if (top==-1) 35 | { 36 | cout<<"Stack underflow"; 37 | //getch(); 38 | return; 39 | } 40 | for(int i=top;i>=0;i--) 41 | cout<>ch; 51 | switch(ch) 52 | { 53 | case 1: 54 | cout<<"Enter a number"; 55 | cin>>e; 56 | push(e); 57 | break; 58 | case 2: 59 | pop(); 60 | break; 61 | case 3: 62 | traverse(); 63 | break; 64 | case 4: 65 | return 0; 66 | } 67 | }while(1); 68 | //getch(); 69 | } 70 | -------------------------------------------------------------------------------- /trees/height/cpp/ht.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Node 5 | { 6 | public: 7 | Node *left; 8 | Node *right; 9 | int data; 10 | Node(int k) 11 | { 12 | this->data=k; 13 | left=NULL; 14 | right=NULL; 15 | } 16 | Node() 17 | { 18 | } 19 | }; 20 | 21 | int ht(Node *root) 22 | { 23 | Node *temp=new Node(); 24 | queue q; 25 | q.push(root); 26 | int h=0,c=0; 27 | while(1) 28 | { 29 | c=q.size(); 30 | if(c==0) 31 | return h; 32 | else 33 | h++; 34 | while(c>0) 35 | { 36 | temp=q.front(); 37 | if(temp->left) 38 | q.push(temp->left); 39 | if(temp->right) 40 | q.push(temp->right); 41 | q.pop(); 42 | c--; 43 | } 44 | 45 | } 46 | } 47 | 48 | int main() 49 | { 50 | Node *head=new Node(1); 51 | head->left=new Node(2); 52 | head->right=new Node(3); 53 | head->left->left=new Node(4); 54 | head->left->right=new Node(5); 55 | head->right->right=new Node(6); 56 | head->right->right->left=new Node(10); 57 | cout< 2 | using namespace std; 3 | void insertionsort(int x[],int n) 4 | { 5 | int temp=0,i=0,j=0; 6 | for(i=1;i=0) 11 | { 12 | x[j+1]=x[j]; 13 | j--; 14 | } 15 | x[j+1]=temp; 16 | } 17 | } 18 | 19 | void insertionsort1(int x[],int n) 20 | { 21 | int temp=0,i=0,j=0; 22 | for(i=1;ix[j]&&j>=0) 27 | { 28 | x[j+1]=x[j]; 29 | j--; 30 | } 31 | x[j+1]=temp; 32 | } 33 | } 34 | 35 | 36 | int main() 37 | { 38 | //clrscr(); 39 | int a[100],n=0,i=0; 40 | cout<<"Enter number of elements in array"; 41 | cin>>n; 42 | cout<<"Enter the elements"; 43 | for(int i=0;i>a[i]; 45 | cout<<"The old array is\n"; 46 | for(i=0;i 5 | #include 6 | 7 | /* function implements selection sort */ 8 | void selection_sort(int list[], int n) 9 | { 10 | int temp, current, j, k=0; 11 | 12 | for (current = 0; current < n; current++) 13 | { 14 | for (j = current + 1; j < n; j++) 15 | if (list[current] > list[j]) 16 | { 17 | temp = list[current]; 18 | list[current] = list[j]; 19 | list[j] = temp; 20 | } 21 | printf("\n Step : %d :", (current+1)); 22 | for(k=0; k 2 | 3 | int interpolationSearch(int arr[], int n, int x) 4 | { 5 | 6 | int lo = 0, hi = (n - 1); 7 | while (lo <= hi && x >= arr[lo] && x <= arr[hi]) 8 | { 9 | if (lo == hi){ 10 | if (arr[lo] == x) return lo; 11 | return -1; 12 | } 13 | 14 | int pos = lo + (((double)(hi-lo)/(arr[hi]-arr[lo]))*(x - arr[lo])); 15 | 16 | if (arr[pos] == x) 17 | return pos; 18 | 19 | if (arr[pos] < x) 20 | lo = pos + 1; 21 | else 22 | hi = pos - 1; 23 | } 24 | return -1; 25 | } 26 | int main() 27 | { 28 | int arr[] = {10, 12, 13, 16, 18, 19, 20, 21, 22, 23, 29 | 24, 33, 35, 42, 47}; 30 | int n = sizeof(arr)/sizeof(arr[0]); 31 | 32 | int x = 18; 33 | int index = interpolationSearch(arr, n, x); 34 | 35 | 36 | if (index != -1) 37 | printf("Element found at index %d", index); 38 | else 39 | printf("Element not found."); 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /depth_first_search/java/bst.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | public class bst 3 | { 4 | 5 | public void depthFirstSearch(Node root) 6 | { 7 | if(root == null) 8 | { 9 | return; 10 | } 11 | 12 | Stack Stack = new Stack(); 13 | Stack.push(root); 14 | 15 | while(!Stack.isEmpty()) 16 | { 17 | Node node = Stack.peek(); 18 | System.out.print(node.data + " "); 19 | Stack.pop(); 20 | if(node.right != null) 21 | { 22 | Stack.push(node.right); 23 | } 24 | if(node.left != null) 25 | { 26 | Stack.push(node.left); 27 | } 28 | } 29 | } 30 | 31 | public static void main(String args[]) 32 | { 33 | 34 | 35 | 36 | 37 | Node root = new Node(4); 38 | root.left = new Node(2); 39 | root.right = new Node(5); 40 | root.left.left = new Node(1); 41 | root.left.right = new Node(3); 42 | 43 | 44 | bst dfs = new bst(); 45 | dfs.depthFirstSearch(root); 46 | } 47 | } 48 | 49 | class Node 50 | { 51 | int data; 52 | Node left; 53 | Node right; 54 | 55 | Node(int value) { 56 | data = value; 57 | left = right = null; 58 | } 59 | } -------------------------------------------------------------------------------- /stack/clang/stack.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct Node { 4 | int data; 5 | struct Node *next; 6 | } *Top; 7 | 8 | struct Node *CreateNode(int data) { 9 | struct Node *newNode; 10 | newNode->data = data; 11 | newNode->next = NULL; 12 | return newNode; 13 | } 14 | 15 | void Push(struct Node *node) { 16 | node->next = Top; 17 | Top = node; 18 | } 19 | 20 | struct Node *Pop() { 21 | struct Node *popped = Top; 22 | Top = Top->next; 23 | return popped; 24 | } 25 | 26 | void DisplayStack() { 27 | struct Node *currentNode = Top; 28 | while(currentNode != NULL) { 29 | printf("%d -> ", currentNode->data); 30 | currentNode = currentNode->next; 31 | } 32 | printf("base\n"); 33 | } 34 | 35 | int main() { 36 | Top = NULL; 37 | 38 | Push(CreateNode(1)); 39 | Push(CreateNode(2)); 40 | Push(CreateNode(3)); 41 | Push(CreateNode(4)); 42 | 43 | DisplayStack(); 44 | 45 | Pop(); 46 | DisplayStack(); 47 | Pop(); 48 | DisplayStack(); 49 | 50 | return 0; 51 | } 52 | 53 | // Output: 54 | // 4 -> 3 -> 2 -> 1 -> base 55 | // 3 -> 2 -> 1 -> base 56 | // 2 -> 1 -> base -------------------------------------------------------------------------------- /selection_sort/cpp/selection_sort.cpp: -------------------------------------------------------------------------------- 1 | 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 | } 49 | -------------------------------------------------------------------------------- /counting_sort/ruby/counting_sort.rb: -------------------------------------------------------------------------------- 1 | # Created by Ankur Pandey (Github - AnkDos) 2 | def max(ar) 3 | i = 0 4 | max = ar[i] 5 | while i < ar.length 6 | if max < ar[i] 7 | max = ar[i] 8 | end 9 | i += 1 10 | end 11 | max 12 | end 13 | 14 | def count(element,ar) 15 | count = 0 16 | ar.each{ 17 | |x| 18 | if element == x 19 | count+=1 20 | end 21 | } 22 | count 23 | end 24 | 25 | def counting_sort(ar, max = max(ar)) 26 | new_arr = [] 27 | sorted_array = [] 28 | i = 0 29 | while i <= max 30 | new_arr << count(i,ar) 31 | i+=1 32 | end 33 | i = 0 34 | while i < new_arr.length 35 | if i == 0 36 | else 37 | new_arr[i] = new_arr[i]+new_arr[i-1] 38 | end 39 | i+=1 40 | end 41 | i = 0 42 | while i < ar.length 43 | sorted_array[new_arr[ar[i]]] = ar[i] 44 | new_arr[ar[i]] -= 1 45 | i+=1 46 | end 47 | sorted_array[1...sorted_array.length] 48 | end 49 | 50 | ar = [231,11,2123,22121,12,2,13,23,21,2,43,2233,1,2,0] 51 | print counting_sort(ar) -------------------------------------------------------------------------------- /merge_sort/python/merge_sort.py: -------------------------------------------------------------------------------- 1 | def mergeSort(nlist): 2 | print("Splitting ",nlist) 3 | if len(nlist)>1: 4 | mid = len(nlist)//2 5 | lefthalf = nlist[:mid] 6 | righthalf = nlist[mid:] 7 | 8 | mergeSort(lefthalf) 9 | mergeSort(righthalf) 10 | i=j=k=0 11 | while i < len(lefthalf) and j < len(righthalf): 12 | if lefthalf[i] < righthalf[j]: 13 | nlist[k]=lefthalf[i] 14 | i=i+1 15 | else: 16 | nlist[k]=righthalf[j] 17 | j=j+1 18 | k=k+1 19 | #for remaining elements in lefthalf(if any) 20 | while i < len(lefthalf): 21 | nlist[k]=lefthalf[i] 22 | i=i+1 23 | k=k+1 24 | ##for remaining elements in righthalf(if any) 25 | while j < len(righthalf): 26 | nlist[k]=righthalf[j] 27 | j=j+1 28 | k=k+1 29 | print("Merging ",nlist) 30 | 31 | print("Unsorted Input -- ,end='') 32 | nlist = list(map(int, input().split())) 33 | mergeSort(nlist) 34 | print("Sorted Output -- , end='') 35 | print(nlist) 36 | -------------------------------------------------------------------------------- /quick_sort/cpp/Quick_Sort.cpp: -------------------------------------------------------------------------------- 1 | //partitioning algorithm 2 | int partition(int* A,int low, int high) 3 | { 4 | int pivot,temp,i; 5 | pivot=A[high]; 6 | i=low-1; 7 | for(int j=low;j<=high-1;j++) 8 | { 9 | if(A[j]<=pivot) 10 | { 11 | i++; 12 | temp=A[j]; 13 | A[j]=A[i]; 14 | A[i]=temp; 15 | } 16 | } 17 | temp=A[i+1]; 18 | A[i+1]=A[high]; 19 | A[high]=temp; 20 | return i+1; 21 | } 22 | 23 | 24 | //recursive function quicksort 25 | void quickSort(int* A, int low, int high) 26 | { 27 | int temp,pivot,i,j,mid; 28 | if(low> n; 44 | A=new int(n); 45 | cout << " enter space separated array elements : "; 46 | for(i=0;i> A[i]; 49 | } 50 | quickSort(A,0,n-1); 51 | cout << "sorted array is : "; 52 | for(i=0;i> n; 44 | A=new int(n); 45 | cout << " enter space separated array elements : "; 46 | for(i=0;i> A[i]; 49 | } 50 | quickSort(A,0,n-1); 51 | cout << "sorted array is : "; 52 | for(i=0;i 2 | 3 | /* Counting sort function */ 4 | void counting_sort(int A[], int k, int n) 5 | { 6 | int i, j; 7 | int B[n], C[k]; 8 | for (i = 0; i <= k; i++) 9 | C[i] = 0; 10 | for (j = 1; j <= n; j++) 11 | C[A[j]] = C[A[j]] + 1; 12 | for (i = 1; i <= k; i++) 13 | C[i] = C[i] + C[i-1]; 14 | for (j = n; j >= 1; j--) 15 | { 16 | B[C[A[j]]] = A[j]; 17 | C[A[j]] = C[A[j]] - 1; 18 | } 19 | printf("The Sorted array is : "); 20 | for (i = 1; i <= n; i++) 21 | printf("%d ", B[i]); 22 | } 23 | /* End of counting_sort() */ 24 | 25 | /* The main() begins */ 26 | int main() 27 | { 28 | int n, max = 0, i; 29 | printf("Enter the number of input : "); 30 | scanf("%d", &n); 31 | int Arr[n]; 32 | printf("\nEnter the elements to be sorted :\n"); 33 | for (i = 1; i <= n; i++) 34 | { 35 | printf("Array[%d] : ",i); 36 | scanf("%d", &Arr[i]); 37 | if (Arr[i] > max) { 38 | max = Arr[i]; 39 | } 40 | } 41 | counting_sort(Arr, max, n); 42 | printf("\n"); 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /egyptian_fractions/cpp/egyptF.cpp: -------------------------------------------------------------------------------- 1 | // Egyptian Fraction in C++ 2 | 3 | 4 | #include 5 | using namespace std; 6 | 7 | void printEgyptian(int nr, int dr) 8 | { 9 | if (dr == 0 || nr == 0) 10 | return; 11 | 12 | // If numerator divides denominator 13 | if (dr % nr == 0) 14 | { 15 | cout << "1/" << dr / nr; 16 | return; 17 | } 18 | 19 | // If denominator divides numerator 20 | if (nr % dr == 0) 21 | { 22 | cout << nr / dr; 23 | return; 24 | } 25 | 26 | // If numerator is greater than denominator 27 | if (nr > dr) 28 | { 29 | cout << nr / dr << " + "; 30 | printEgyptian(nr % dr, dr); 31 | return; 32 | } 33 | 34 | // the default path 35 | int n = dr / nr + 1; 36 | cout << "1/" << n << " + "; 37 | 38 | // Recur for remaining 39 | printEgyptian(nr * n - dr, dr * n); 40 | } 41 | 42 | 43 | // MAIN 44 | int main() 45 | { 46 | int nr, dr; 47 | cout << "Enter numerator and denominator: \n"; 48 | cin >> nr >> dr; 49 | cout << "Egyptian Fraction Representation is: \n "; 50 | printEgyptian(nr, dr); 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /merge_sort/clang/merge_sort.c: -------------------------------------------------------------------------------- 1 | #include 2 | void merge(int a[],int l,int m,int r) 3 | { 4 | int i,j,k,n1,n2; 5 | n1=m-l+1; 6 | n2=r-m; 7 | int L[n1],R[n2]; 8 | for(i=0;i 8 | #include 9 | #include 10 | using namespace std; 11 | 12 | 13 | int rodCut(vector price,int n){ 14 | 15 | vectorval(n+1,INT_MIN); //max value of rod for each length. 16 | val[0]=0; // value of rod of length zero is zero/\. 17 | 18 | for(int i=1;i<=n;i++){ 19 | for(int j=0;j>n; 31 | cout< prices(n,0); 33 | 34 | for(int i=0;i>x; 38 | cout< 2 | using namespace std; 3 | int interpolationSearch(int arr[], int n, int x) 4 | { 5 | int lo = 0, hi = (n - 1); 6 | while (lo <= hi && x >= arr[lo] && x <= arr[hi]) 7 | { 8 | if (lo == hi) 9 | { 10 | if (arr[lo] == x) return lo; 11 | return -1; 12 | } 13 | 14 | int pos = lo + (((double)(hi - lo) / 15 | (arr[hi] - arr[lo])) * (x - arr[lo])); 16 | 17 | if (arr[pos] == x) 18 | return pos; 19 | 20 | if (arr[pos] < x) 21 | lo = pos + 1; 22 | 23 | else 24 | hi = pos - 1; 25 | } 26 | return -1; 27 | } 28 | 29 | int main() 30 | { 31 | int arr[] = {10, 12, 13, 16, 18, 19, 20, 21, 32 | 22, 23, 24, 33, 35, 42, 47}; 33 | int n = sizeof(arr)/sizeof(arr[0]); 34 | 35 | int x = 18; 36 | int index = interpolationSearch(arr, n, x); 37 | if (index != -1) 38 | cout << "Element found at index " << index; 39 | else 40 | cout << "Element not found."; 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /insertion_sort/c/insertionSort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | /* Function to sort an array using insertion sort*/ 4 | void insertionSort(int arr[], int n) 5 | { 6 | int i, key, j; 7 | for (i = 1; i < n; i++) 8 | { 9 | key = arr[i]; 10 | j = i - 1; 11 | 12 | /* Move elements of arr[0..i-1], that are 13 | greater than key, to one position ahead 14 | of their current position */ 15 | while (j >= 0 && arr[j] > key) 16 | { 17 | arr[j + 1] = arr[j]; 18 | j = j - 1; 19 | } 20 | arr[j + 1] = key; 21 | } 22 | } 23 | 24 | // Function to print the array of size n 25 | void printArray(int arr[], int n) 26 | { 27 | int i; 28 | for (i = 0; i < n; i++) 29 | printf("%d ", arr[i]); 30 | printf("\n"); 31 | } 32 | 33 | 34 | int main() 35 | { 36 | int n, i; 37 | printf("Enter the size of the array: "); 38 | scanf("%d", &n); 39 | int arr[n]; 40 | printf("Enter the elements in the array: "); 41 | for(i=0; i 4 | 5 | int getMax(int array[], int size) 6 | { 7 | int max = array[0]; 8 | for (int i = 1; i < size; i++) 9 | if (array[i] > max) 10 | max = array[i]; 11 | return max; 12 | } 13 | 14 | void bucketSort(int array[], int size) 15 | { 16 | int bucket[10]; 17 | const int max = getMax(array, size); 18 | for (int i = 0; i <= max; i++) 19 | { 20 | bucket[i] = 0; 21 | } 22 | for (int i = 0; i < size; i++) 23 | { 24 | bucket[array[i]]++; 25 | } 26 | for (int i = 0, j = 0; i <= max; i++) 27 | { 28 | while (bucket[i] > 0) 29 | { 30 | array[j++] = i; 31 | bucket[i]--; 32 | } 33 | } 34 | } 35 | 36 | void printArray(int array[], int size) 37 | { 38 | for (int i = 0; i < size; ++i) 39 | { 40 | printf("%d ", array[i]); 41 | } 42 | printf("\n"); 43 | } 44 | 45 | int main() 46 | { 47 | int data[] = {5, 4, 3, 2, 1}; 48 | int size = sizeof(data) / sizeof(data[0]); 49 | bucketSort(data, size); 50 | printf("Sorted array is: \n"); 51 | printArray(data, size); 52 | } -------------------------------------------------------------------------------- /selection_sort/java/SelectionSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.Random; 3 | 4 | public class SelectionSort { 5 | 6 | public static > void sort(AnyType[] array, boolean creciente) { 7 | if (array == null) { return; } 8 | 9 | for (int i = 0; i < array.length - 1; i++) { 10 | AnyType val = array[i]; 11 | int indexVal = i; 12 | for (int j = i + 1; j < array.length; j++) { 13 | if (array[j].compareTo(val) == (creciente ? -1 : 1)) { 14 | val = array[j]; 15 | indexVal = j; 16 | } 17 | } 18 | if (indexVal != i) { 19 | array[indexVal] = array[i]; 20 | array[i] = val; 21 | } 22 | } 23 | } 24 | 25 | public static void main(String[] args) { 26 | final int LEN = 15; 27 | final int MAX_RANDOM = 100; 28 | final Integer[] ar = new Integer[LEN]; 29 | Random rnd = new Random(); 30 | for (int i = 0; i < LEN; i++) { 31 | ar[i] = new Integer(rnd.nextInt(MAX_RANDOM)); 32 | } 33 | System.out.println(Arrays.toString(ar)); 34 | 35 | sort(ar, true); 36 | System.out.println(Arrays.toString(ar)); 37 | sort(ar, false); 38 | System.out.println(Arrays.toString(ar)); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /breath_first_search/cpp/breadth_first_search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Node 7 | { 8 | public: 9 | int data; 10 | Node *left; 11 | Node *right; 12 | }; 13 | 14 | Node *newNode(int data) 15 | { 16 | Node *node = new Node(); 17 | node->data = data; 18 | node->left = NULL; 19 | node->right = NULL; 20 | return (node); 21 | }; 22 | 23 | void BFS(Node *root) 24 | { 25 | if (root == NULL) 26 | return; 27 | queue q; 28 | q.push(root); 29 | while (!q.empty()) 30 | { 31 | Node *node = q.front(); 32 | cout << node->data; 33 | q.pop(); 34 | if (node->left != NULL) 35 | q.push(node->left); 36 | if (node->right != NULL) 37 | q.push(node->right); 38 | }; 39 | } 40 | 41 | int main() 42 | { 43 | Node *root = newNode(1); 44 | root->left = newNode(2); 45 | root->right = newNode(3); 46 | root->left->left = newNode(4); 47 | root->left->right = newNode(5); 48 | // Created a basic tree and then applied BFS 49 | //BFS is basically traversal over same depth elements 50 | BFS(root); 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /quick_sort/c#/QuickSort in c#: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | class GFG { 4 | 5 | static int partition(int []arr, int low, 6 | int high) 7 | { 8 | int pivot = arr[high]; 9 | 10 | int i = (low - 1); 11 | for (int j = low; j < high; j++) 12 | { 13 | if (arr[j] <= pivot) 14 | { 15 | i++; 16 | 17 | int temp = arr[i]; 18 | arr[i] = arr[j]; 19 | arr[j] = temp; 20 | } 21 | } 22 | 23 | int temp1 = arr[i+1]; 24 | arr[i+1] = arr[high]; 25 | arr[high] = temp1; 26 | 27 | return i+1; 28 | } 29 | 30 | static void quickSort(int []arr, int low, int high) 31 | { 32 | if (low < high) 33 | { 34 | 35 | int pi = partition(arr, low, high); 36 | 37 | quickSort(arr, low, pi-1); 38 | quickSort(arr, pi+1, high); 39 | } 40 | } 41 | 42 | static void printArray(int []arr, int n) 43 | { 44 | for (int i = 0; i < n; ++i) 45 | Console.Write(arr[i] + " "); 46 | 47 | Console.WriteLine(); 48 | } 49 | 50 | public static void Main() 51 | { 52 | int []arr = {10, 7, 8, 9, 1, 5}; 53 | int n = arr.Length; 54 | quickSort(arr, 0, n-1); 55 | Console.WriteLine("sorted array "); 56 | printArray(arr, n); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /binary_search/cpp/bs.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to implement recursive Binary Search 2 | #include 3 | using namespace std; 4 | 5 | // A recursive binary search function. It returns 6 | // location of x in given array arr[l..r] is present, 7 | // otherwise -1 8 | int binarySearch(int arr[], int l, int r, int x) 9 | { 10 | if (r >= l) { 11 | int mid = l + (r - l) / 2; 12 | 13 | // If the element is present at the middle 14 | // itself 15 | if (arr[mid] == x) 16 | return mid; 17 | 18 | // If element is smaller than mid, then 19 | // it can only be present in left subarray 20 | if (arr[mid] > x) 21 | return binarySearch(arr, l, mid - 1, x); 22 | 23 | // Else the element can only be present 24 | // in right subarray 25 | return binarySearch(arr, mid + 1, r, x); 26 | } 27 | 28 | // We reach here when element is not 29 | // present in array 30 | return -1; 31 | } 32 | 33 | int main(void) 34 | { 35 | int arr[] = { 2, 3, 4, 10, 40 }; 36 | int x = 10; 37 | int n = sizeof(arr) / sizeof(arr[0]); 38 | int result = binarySearch(arr, 0, n - 1, x); 39 | (result == -1) ? cout << "Element is not present in array" 40 | : cout << "Element is present at index " << result; 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /heap_sort/javascript/heapSort.js: -------------------------------------------------------------------------------- 1 | // Prg of HEAP SORT using JS 2 | 3 | 4 | // Creating MaxHeap 5 | function maxHeap(input, i) { 6 | const left = 2 * i + 1 7 | const right = 2 * i + 2 8 | let max = i 9 | 10 | if (left < arrLength && input[left] > input[max]) { 11 | max = left 12 | } 13 | 14 | if (right < arrLength && input[right] > input[max]) { 15 | max = right 16 | } 17 | 18 | if (max != i) { 19 | swap(input, i, max) 20 | maxHeap(input, max) 21 | } 22 | } 23 | 24 | 25 | // Swapping Function 26 | function swap(input, indexA, indexB) { 27 | const temp = input[indexA] 28 | 29 | input[indexA] = input[indexB] 30 | input[indexB] = temp 31 | } 32 | 33 | 34 | // Sorting Function 35 | function heapSort(input) { 36 | arrLength = input.length 37 | 38 | for (let i = Math.floor(arrLength / 2); i >= 0; i -= 1) { 39 | maxHeap(input, i) 40 | } 41 | 42 | for (i = input.length - 1; i > 0; i--) { 43 | swap(input, 0, i) 44 | arrLength-- 45 | 46 | maxHeap(input, 0) 47 | } 48 | return 49 | } 50 | 51 | 52 | // MAIN 53 | const list = [5, 4, -3, 2, 1] 54 | const sorted = heapSort(list) 55 | console.log(list) -------------------------------------------------------------------------------- /trees/binary_search_tree/Python/BST.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding: utf-8 3 | 4 | # In[5]: 5 | 6 | 7 | class Node: 8 | def __init__(self,key): 9 | self.left = None 10 | self.right = None 11 | self.val = key 12 | 13 | # insert a new node with the given key 14 | def insert(root,node): 15 | if root is None: 16 | root = node 17 | else: 18 | if root.val < node.val: 19 | if root.right is None: 20 | root.right = node 21 | else: 22 | insert(root.right, node) 23 | else: 24 | if root.left is None: 25 | root.left = node 26 | else: 27 | insert(root.left, node) 28 | 29 | # inorder tree traversal 30 | def inorder(root): 31 | if root: 32 | inorder(root.left) 33 | print(root.val) 34 | inorder(root.right) 35 | 36 | 37 | #Driver code 38 | r = Node(5) 39 | insert(r,Node(3)) 40 | insert(r,Node(2)) 41 | insert(r,Node(4)) 42 | insert(r,Node(7)) 43 | insert(r,Node(6)) 44 | insert(r,Node(8)) 45 | 46 | # Print inoder traversal of the BST 47 | inorder(r) 48 | 49 | 50 | # In[ ]: 51 | 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /quick_sort/java/QuickSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Comparator; 2 | import java.util.Random; 3 | public class Quicksort { 4 | public static final Random RND = new Random(); 5 | private void swap(Object[] array, int i, int j) { 6 | Object tmp = array[i]; 7 | array[i] = array[j]; 8 | array[j] = tmp; 9 | } 10 | private int partition(Object[] array, int begin, int end, Comparator cmp) { 11 | int index = begin + RND.nextInt(end - begin + 1); 12 | Object pivot = array[index]; 13 | swap(array, index, end); 14 | for (int i = index = begin; i < end; ++ i) { 15 | if (cmp.compare(array[i], pivot) <= 0) { 16 | swap(array, index++, i); 17 | } } 18 | swap(array, index, end); 19 | return (index); 20 | } 21 | private void qsort(Object[] array, int begin, int end, Comparator cmp) { 22 | if (end > begin) { 23 | int index = partition(array, begin, end, cmp); 24 | qsort(array, begin, index - 1, cmp); 25 | qsort(array, index + 1, end, cmp); 26 | } } 27 | public void sort(Object[] array, Comparator cmp) { 28 | qsort(array, 0, array.length - 1, cmp); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /disjoint_set/disjoint_set.java: -------------------------------------------------------------------------------- 1 | Estructura de datos para modelar una colección de conjuntos disyuntos. 2 | Permite determinar de manera eficiente a que conjunto pertenece un elemento, 3 | si dos elementos se encuentran en un mismo conjunto y unir dos conjuntos disyuntos en un uno. 4 | 5 | static class dsu { 6 | int[] par, sz; 7 | int size; //Cantidad de conjuntos 8 | 9 | dsu(int n) { 10 | size = n; 11 | par = new int[n]; 12 | sz = new int[n]; 13 | for (int i = 0; i < n; i++) { 14 | par[i] = i; 15 | sz[i] = 1; 16 | } 17 | } 18 | //Busca el nodo representativo del conjunto de u 19 | int find(int u) { 20 | return par[u] == u ? u : (par[u] = find(par[u])); 21 | } 22 | //Une los conjuntos de u y v 23 | void unite(int u, int v) { 24 | if ((u = find(u)) == (v = find(v))) return; 25 | if (sz[u] > sz[v]){ 26 | int aux = u; 27 | u = v; 28 | v = aux; 29 | } 30 | par[u] = v; 31 | sz[v] += sz[u]; 32 | size--; 33 | } 34 | //Retorna la cantidad de elementos del conjunto de u 35 | int count(int u) { 36 | return sz[find(u)]; 37 | } 38 | }; -------------------------------------------------------------------------------- /radix_sort/python/radix_sort.py: -------------------------------------------------------------------------------- 1 | # add your code here 2 | 3 | def r_sort(alist, base=10): 4 | if alist == []: 5 | return 6 | 7 | def k_fac(digit, base): 8 | def key(alist, index): 9 | return ((alist[index]//(base**digit)) % base) 10 | return key 11 | largest = max(alist) 12 | exp = 0 13 | while base**exp <= largest: 14 | alist = counting_sort(alist, base - 1, k_fac(exp, base)) 15 | exp = exp + 1 16 | return alist 17 | 18 | def counting_sort(alist, largest, key): 19 | c = [0]*(largest + 1) 20 | for i in range(len(alist)): 21 | c[key(alist, i)] = c[key(alist, i)] + 1 22 | 23 | # Find the last index for each element 24 | c[0] = c[0] - 1 # to decrement each element for zero-based indexing 25 | for i in range(1, largest + 1): 26 | c[i] = c[i] + c[i - 1] 27 | 28 | result = [None]*len(alist) 29 | for i in range(len(alist) - 1, -1, -1): 30 | result[c[key(alist, i)]] = alist[i] 31 | c[key(alist, i)] = c[key(alist, i)] - 1 32 | 33 | return result 34 | 35 | alist = input('Enter the list of (nonnegative) numbers: ').split() 36 | alist = [int(x) for x in alist] 37 | sorted_list = r_sort(alist) 38 | print('Sorted list: ', end='') 39 | print(sorted_list) 40 | -------------------------------------------------------------------------------- /interpolation search/java/interpolationsearch.java: -------------------------------------------------------------------------------- 1 | class Test 2 | { 3 | static int arr[] = new int[]{10, 12, 13, 16, 18, 19, 20, 21, 22, 23, 24, 33, 35, 42, 47}; 4 | 5 | 6 | static int interpolationSearch(int x) 7 | { 8 | int lo = 0, hi = (arr.length - 1); 9 | while (lo <= hi && x >= arr[lo] && x <= arr[hi]) 10 | { 11 | 12 | if (lo == hi) 13 | { 14 | if (arr[lo] == x) return lo; 15 | return -1; 16 | } 17 | 18 | int pos = lo + (((hi-lo) / (arr[hi]-arr[lo]))*(x - arr[lo])); 19 | 20 | if (arr[pos] == x) 21 | return pos; 22 | if (arr[pos] < x) 23 | lo = pos + 1; 24 | else 25 | hi = pos - 1; 26 | } 27 | return -1; 28 | } 29 | 30 | public static void main(String[] args) 31 | { 32 | int x = 18; 33 | int index = interpolationSearch(x); 34 | 35 | 36 | if (index != -1) 37 | System.out.println("Element found at index " + index); 38 | else 39 | System.out.println("Element not found."); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /dynamic_programming/ugly_numbers/cpp/UglyNos.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find n'th Ugly number 2 | # include 3 | using namespace std; 4 | 5 | /* Function to get the nth ugly number*/ 6 | unsigned getNthUglyNo(unsigned n) 7 | { 8 | unsigned ugly[n]; // To store ugly numbers 9 | unsigned i2 = 0, i3 = 0, i5 = 0; 10 | unsigned next_multiple_of_2 = 2; 11 | unsigned next_multiple_of_3 = 3; 12 | unsigned next_multiple_of_5 = 5; 13 | unsigned next_ugly_no = 1; 14 | 15 | ugly[0] = 1; 16 | for (int i=1; i adj[]; 11 | 12 | Graph(int v) 13 | { 14 | V = v; 15 | adj = new LinkedList[v]; 16 | for (int i=0; i i = adj[v].listIterator(); 31 | while (i.hasNext()) 32 | { 33 | int n = i.next(); 34 | if (!visited[n]) 35 | DFSUtil(n, visited); 36 | } 37 | } 38 | 39 | void DFS(int v) 40 | { 41 | boolean visited[] = new boolean[V]; 42 | DFSUtil(v, visited); 43 | } 44 | 45 | public static void main(String args[]) 46 | { 47 | Graph g = new Graph(4); 48 | 49 | g.addEdge(0, 1); 50 | g.addEdge(0, 2); 51 | g.addEdge(1, 2); 52 | g.addEdge(2, 0); 53 | g.addEdge(2, 3); 54 | g.addEdge(3, 3); 55 | 56 | System.out.println("Following is Depth First Traversal "+ 57 | "(starting from vertex 2)"); 58 | 59 | g.DFS(2); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /shell_sort/clang/SHELL.C: -------------------------------------------------------------------------------- 1 | /* shell.c */ 2 | /* shell sort */ 3 | 4 | #include 5 | #include 6 | void display(int *, int ); 7 | void shell_sort(int *, int ); 8 | 9 | /* function for shell sort */ 10 | void shell_sort(int list[], int n) 11 | { 12 | int temp, gap, i, swap=0; 13 | 14 | gap = n / 2; 15 | 16 | do { 17 | do { 18 | swap = 0; 19 | 20 | for (i = 0; i < n - gap; i++) 21 | if (list[i] > list[i + gap]) 22 | { 23 | temp = list[i]; 24 | list[i] = list[i + gap]; 25 | list[i + gap] = temp; 26 | swap = 1; 27 | } 28 | printf("\n List after pass \n"); 29 | display(list, n); 30 | } while (swap); 31 | } while (gap = gap / 2); 32 | } 33 | /* Output Function */ 34 | void display(int list[], int n) 35 | { 36 | int k; 37 | for(k = 0; k < n; k++) 38 | printf(" %d ", list[k]); 39 | } 40 | 41 | int main(void) 42 | { 43 | int list[50], i, n; 44 | printf("\n Input Number of Data Elements: "); 45 | scanf("%d", &n); 46 | printf("\n Randomly Generated Unsorted list is as follows \n"); 47 | 48 | for (i = 0; i < n; i++) 49 | { 50 | list[i] = rand() % 100; 51 | printf(" %d", list[i]); 52 | } 53 | shell_sort(list, n); 54 | 55 | printf("\n Sorted list is as follows \n"); 56 | 57 | for (i = 0; i < n; i++) 58 | printf("%d ", list[i]); 59 | return 0; 60 | } 61 | 62 | -------------------------------------------------------------------------------- /set_operations/cpp/set_operations.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define n 100 4 | class intset{ 5 | int set[n]; 6 | public: 7 | intset(){ 8 | for(int i=0;i 4 | using namespace std; 5 | 6 | 7 | int shellSort(int arr[], int n) 8 | { 9 | // Start with a big gap, then reduce the gap 10 | for (int gap = n / 2; gap > 0; gap /= 2) 11 | { 12 | for (int i = gap; i < n; i += 1) 13 | { 14 | /* add a[i] to the elements that have been gap sorted 15 | save a[i] in temp and make a hole at position i */ 16 | int temp = arr[i]; 17 | 18 | /* shift earlier gap-sorted elements up until the correct 19 | location for a[i] is found */ 20 | int j; 21 | for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) 22 | arr[j] = arr[j - gap]; 23 | 24 | // put temp (the original a[i]) in its correct location 25 | arr[j] = temp; 26 | } 27 | } 28 | return 0; 29 | } 30 | 31 | 32 | void printArray(int arr[], int n) 33 | { 34 | for (int i = 0; i < n; i++) 35 | cout << arr[i] << " "; 36 | } 37 | 38 | 39 | // MAIN 40 | int main() 41 | { 42 | int arr[] = {5, 4, -3, 2, 1}, i; 43 | int n = sizeof(arr) / sizeof(arr[0]); 44 | 45 | shellSort(arr, n); 46 | 47 | cout << "\nArray after sorting: \n"; 48 | printArray(arr, n); 49 | 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /shell_sort/shell_sort.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | namespace ShellSortDemo { 3 | public class Example { 4 | static void shellSort(int[] arr, int n) { 5 | int i, j, pos, temp; 6 | pos = 3; 7 | while (pos > 0) { 8 | for (i = 0; i < n; i++) { 9 | j = i; 10 | temp = arr[i]; 11 | while ((j >= pos) && (arr[j - pos] > temp)) { 12 | arr[j] = arr[j - pos]; 13 | j = j - pos; 14 | } 15 | arr[j] = temp; 16 | } 17 | if (pos / 2 != 0) 18 | pos = pos / 2; 19 | else if (pos == 1) 20 | pos = 0; 21 | else 22 | pos = 1; 23 | } 24 | } 25 | static void Main(string[] args) { 26 | int[] arr = new int[] { 56, 12, 99, 32, 1, 95, 25, 5, 100, 84 }; 27 | int n = arr.Length; 28 | int i; 29 | Console.WriteLine("Shell Sort"); 30 | Console.Write("Initial array is: "); 31 | for (i = 0; i < n; i++) { 32 | Console.Write(arr[i] + " "); 33 | } 34 | shellSort(arr, n); 35 | Console.Write("\nSorted Array is: "); 36 | for (i = 0; i < n; i++) { 37 | Console.Write(arr[i] + " "); 38 | } 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /trees/travelling_salesman/clang/ts.c: -------------------------------------------------------------------------------- 1 | //Travelling sales man problem 2 | //Contributor's algorithm. Anything smaller than this is aprreciated. If so feel free to make commits. 3 | 4 | #include 5 | 6 | int a[10][10], visited[10], n, cost = 0; 7 | int least(int); 8 | void mincost(int city) { 9 | int i, ncity; 10 | visited[city] = 1; 11 | printf("%d-->", city + 1); 12 | ncity = least(city); 13 | if (ncity == 999) { 14 | ncity = 0; 15 | printf("%d", ncity + 1); 16 | cost += a[city][ncity]; 17 | return; 18 | } 19 | mincost(ncity); 20 | } 21 | int least(int c) { 22 | int i, nc = 999; 23 | int min = 999, kmin; 24 | for (i = 0; i < n; i++) { 25 | if ((a[c][i] != 0) && (visited[i] == 0)) 26 | if (a[c][i] < min) { 27 | min = a[i][0] + a[c][i]; 28 | kmin = a[c][i]; 29 | nc = i; 30 | } 31 | } 32 | if (min != 999) 33 | cost += kmin; 34 | return nc; 35 | } 36 | int main() { 37 | int i, j; 38 | printf("Enter the number of cities:"); 39 | scanf("%d", & n); 40 | for (i = 0; i < n; i++) { 41 | printf("\n Enter elements of row %d:\n", i + 1); 42 | for (j = 0; j < n; j++) 43 | scanf("%d", & a[i][j]); 44 | visited[i] = 0; 45 | } 46 | printf("\n\n The path is:\n\n"); 47 | mincost(0); 48 | printf("\n\n Minimum Cost: %d", cost); 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /trees/traversals/python/treeTrav.py: -------------------------------------------------------------------------------- 1 | # Prg for tree traversals 2 | 3 | # Class for a node in binary tree 4 | class Node: 5 | def __init__(self, key): 6 | self.left = None 7 | self.right = None 8 | self.value = key 9 | 10 | 11 | # INORDER Traversal 12 | def printInorder(root): 13 | 14 | if root: 15 | 16 | printInorder(root.left) # recur on left child 17 | print(root.value) # print value 18 | printInorder(root.right) # recur on right child 19 | 20 | 21 | # POSTORDER Traversal 22 | def printPostorder(root): 23 | 24 | if root: 25 | 26 | printPostorder(root.left) # recur on left child 27 | printPostorder(root.right) # print value 28 | print(root.value) # recur on right child 29 | 30 | 31 | # PREORDER Traversal 32 | def printPreorder(root): 33 | 34 | if root: 35 | 36 | print(root.value) # recur on left child 37 | printPreorder(root.left) # print value 38 | printPreorder(root.right) # recur on right child 39 | 40 | 41 | # MAIN 42 | root = Node(1) 43 | root.left = Node(2) 44 | root.right = Node(3) 45 | root.left.left = Node(4) 46 | root.left.right = Node(5) 47 | print("Preorder traversal of the binary tree is: ") 48 | printPreorder(root) 49 | 50 | print("\nInorder traversal of the binary tree is: ") 51 | printInorder(root) 52 | 53 | print("\nPostorder traversal of the binary tree is: ") 54 | printPostorder(root) 55 | -------------------------------------------------------------------------------- /radix_sort/php/radix_sort.php.txt: -------------------------------------------------------------------------------- 1 | $longest) { 13 | $longest = $el; 14 | } 15 | array_push($queues[$el % 10], $el); 16 | } 17 | // Queues are dequeued back into original elements. 18 | $i = 0; 19 | foreach ($queues as $key => $q) { 20 | while (!empty($queues[$key])) { 21 | $elements[$i++] = array_shift($queues[$key]); 22 | } 23 | } 24 | // Remaining iterations are determined based on longest digits element. 25 | $it = strlen($longest) - 1; 26 | $d = 10; 27 | while ($it--) { 28 | foreach ($elements as $el) { 29 | array_push($queues[floor($el/$d) % 10], $el); 30 | } 31 | $i = 0; 32 | foreach ($queues as $key => $q) { 33 | while (!empty($queues[$key])) { 34 | $elements[$i++] = array_shift($queues[$key]); 35 | } 36 | } 37 | $d *= 10; 38 | } 39 | } 40 | // Example usage: 41 | $a = array(170, 45, 75, 90, 802, 24, 2, 66); 42 | print_r($a); 43 | radix_sort($a); 44 | print_r($a); 45 | ?> 46 | -------------------------------------------------------------------------------- /tarjan_algorithm/java/Tarjan.java: -------------------------------------------------------------------------------- 1 | Given a directed graph find the strongly connected components (SCC). 2 | 3 | static final int MAX = 100005; //Maximum amount of nodes 4 | static ArrayList g[] = new ArrayList[MAX]; //Adjacency list 5 | static boolean[] vis = new boolean[MAX]; //Check the visited nodes 6 | static Stack st = new Stack(); 7 | static int[] low = new int[MAX]; 8 | static int[] num = new int[MAX]; 9 | static int compOf[] = new int[MAX]; //Stores the component to which each node belongs 10 | static int cantSCC; //Amount of strongly connected components 11 | static int N, M, cont; //Amount of nodes and edges 12 | 13 | static void tarjan(int u) { 14 | low[u] = num[u] = cont++; 15 | st.push(u); 16 | vis[u] = true; 17 | 18 | for (int v : g[u]) { 19 | if (num[v] == -1) 20 | tarjan(v); 21 | if (vis[v]) 22 | low[u] = Math.min(low[u], low[v]); 23 | } 24 | 25 | if (low[u] == num[u]) { 26 | while (true) { 27 | int v = st.pop(); 28 | vis[v] = false; 29 | compOf[v] = cantSCC; 30 | if (u == v) break; 31 | } 32 | cantSCC++; 33 | } 34 | } 35 | 36 | static void init() { 37 | cont = cantSCC = 0; 38 | for (int i = 0; i <= N; i++) { 39 | g[i].clear(); 40 | num[i] = -1; 41 | } 42 | } -------------------------------------------------------------------------------- /queues/java/queue.java: -------------------------------------------------------------------------------- 1 | // add your code here : 2 | public class Queue { 3 | Node first; 4 | Node last; 5 | 6 | public Queue(){} 7 | 8 | void enqueue(Object item){ 9 | Node t = new Node(item); 10 | if(first == null && last == null){ 11 | first = last = t; 12 | t.next = null; 13 | } 14 | else { 15 | last.next = t; 16 | last = t; 17 | } 18 | } 19 | 20 | Object dequeue(){ 21 | if(first != null){ 22 | Object item = first.data; 23 | first = first.next; 24 | return item; 25 | } 26 | return null; 27 | } 28 | 29 | void displayAll(){ 30 | while(first != null){ 31 | System.out.println(first.data); 32 | first = first.next; 33 | } 34 | } 35 | 36 | public static void main(String[] args){ 37 | Queue q = new Queue(); 38 | q.enqueue(1); 39 | q.enqueue(2); 40 | q.enqueue(3); 41 | q.enqueue(4); 42 | q.enqueue(5); 43 | 44 | // System.out.print(q.dequeue()); 45 | // System.out.print(q.dequeue()); 46 | 47 | q.displayAll(); 48 | 49 | } 50 | } 51 | class Node { 52 | Object data; 53 | Node next; 54 | 55 | public Node(Object item){ 56 | this.data = item; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /trees/binary_search_tree/cpp/HeightOfBST.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Node 5 | { 6 | int data; 7 | struct Node*left = NULL; 8 | struct Node*right = NULL; 9 | }; 10 | 11 | long int height(Node*root) 12 | { 13 | if(root == NULL) 14 | return 0; 15 | if(root->left == NULL && root->right == NULL) 16 | return 1; 17 | 18 | long int left = height(root->left); 19 | long int right = height(root->right); 20 | return 1 + max(left, right); 21 | } 22 | 23 | Node*addNode(Node*root, long int val) 24 | { 25 | if(root == NULL) 26 | { 27 | root = (Node*)malloc(sizeof(Node)); 28 | root->data = val; 29 | root->left = NULL; 30 | root->right = NULL; 31 | return root; 32 | } 33 | 34 | if(val < root->data) 35 | { 36 | root->left = addNode(root->left, val); 37 | } 38 | else 39 | { 40 | root->right = addNode(root->right, val); 41 | } 42 | return root; 43 | } 44 | 45 | Node* createTree() 46 | { 47 | long int n, tmpData; 48 | Node*root = NULL; 49 | cout<<"Enter the number of nodes"<>n; 51 | while(n!=0) 52 | { 53 | cin>>tmpData; 54 | root = addNode(root, tmpData); 55 | n-=1; 56 | } 57 | return root; 58 | } 59 | 60 | int main() 61 | { 62 | Node*root = createTree(); 63 | 64 | cout<seg; 2 | #define ZERO 0 // define the zero value,its 0 for sum,1 for product 3 | void merge(const int &a,const int &b,int &c) 4 | { 5 | c=max(a,b); 6 | c=min(a,b); 7 | c=a+b; 8 | c=__gcd(a,b); // use any of merge method 9 | } 10 | void build(int pos,int ss,int se,vector&a) 11 | { 12 | if(pos==0) 13 | seg.resize(4*(se+1)+1); 14 | if(ss==se) 15 | { 16 | seg[pos]=a[ss]; 17 | return; 18 | } 19 | int mid=(ss+se)/2; 20 | build(2*pos+1,ss,mid); 21 | build(2*pos+2,mid+1,se); 22 | merge(seg[2*pos+1],seg[2*pos+2],seg[pos]) 23 | } 24 | int query(int pos,int ss,int se,int l,int r) 25 | { 26 | if(l>se || r < ss) 27 | return ZERO; 28 | if(ss >=l && se<=r) 29 | return seg[pos]; 30 | int mid=(ss+se)/2; 31 | int q1=query(2*pos+1,ss,mid,l,r); 32 | int q2=query(2*pos+2,mid+1,se,l,r); 33 | int ans;merge(q1,q2,ans); 34 | return ans; 35 | } 36 | void update(int pos,int ss,int se,int index,int value) 37 | { 38 | if(index se) 39 | return ; 40 | if(ss==se) 41 | { 42 | seg[pos]=value; 43 | return ; 44 | } 45 | int mid=(ss+se)/2; 46 | update(2*pos+1,ss,mid,index,value); 47 | update(2*pos+2,mid+1,se,index,value); 48 | merge(seg[2*pos+1],seg[2*pos+2],seg[pos]); 49 | } 50 | 51 | -------------------------------------------------------------------------------- /dynamic_programming/min_coins_change.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int test,n,amount; 6 | cin>>test; 7 | while(test--){ 8 | cin>>amount>>n; 9 | int coin[n]; 10 | for(int i=0;i>coin[i]; 12 | int am = amount+1; 13 | int a[n][am]; 14 | 15 | for(int i=0;i 3 | using namespace std; 4 | 5 | // A recursive binary search function. It returns 6 | // location of x in given array arr[l..r] is present, 7 | // otherwise -1 8 | int binarySearch(int arr[], int l, int r, int x) 9 | { 10 | if (r >= l) { 11 | int mid = l + (r - l) / 2; 12 | 13 | // If the element is present at the middle 14 | // itself 15 | if (arr[mid] == x) 16 | return mid; 17 | 18 | // If element is smaller than mid, then 19 | // it can only be present in left subarray 20 | if (arr[mid] > x) 21 | return binarySearch(arr, l, mid - 1, x); 22 | 23 | // Else the element can only be present 24 | // in right subarray 25 | return binarySearch(arr, mid + 1, r, x); 26 | } 27 | 28 | // We reach here when element is not 29 | // present in array 30 | return -1; 31 | } 32 | 33 | int main(void) 34 | { 35 | int arr[] = { 2, 3, 4, 10, 40 }; 36 | int x = 10; 37 | int n = sizeof(arr) / sizeof(arr[0]); 38 | int result = binarySearch(arr, 0, n - 1, x); 39 | (result == -1) ? cout << "Element is not present in array" 40 | : cout << "Element is present at index " << result; 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /selection_sort/clang/SelectionSort.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | 4 | 5 | void swap(int *xp, int *yp) 6 | 7 | { 8 | int temp = *xp; 9 | 10 | *xp = *yp; 11 | 12 | *yp = temp; 13 | } 14 | 15 | 16 | void selectionSort(int arr[], int n) 17 | 18 | { 19 | int i, j, min_idx; 20 | 21 | // One by one move boundary of unsorted subarray 22 | 23 | for (i = 0; i < n-1; i++) 24 | 25 | { 26 | // Find the minimum element in unsorted array 27 | 28 | min_idx = i; 29 | 30 | for (j = i+1; j < n; j++) 31 | 32 | { if (arr[j] < arr[min_idx]) 33 | 34 | min_idx = j; 35 | } 36 | 37 | // Swap the found minimum element with the first element 38 | 39 | swap(&arr[min_idx], &arr[i]); 40 | 41 | } 42 | 43 | } 44 | 45 | 46 | /* Function to print an array */ 47 | 48 | void printArray(int arr[], int size) 49 | 50 | { 51 | int i; 52 | 53 | for (i=0; i < size; i++) 54 | 55 | printf("%d ", arr[i]); 56 | 57 | printf("\n"); 58 | } 59 | 60 | 61 | // Driver program to test above functions 62 | 63 | int main() 64 | 65 | { 66 | int arr[] = {26, 5, 11, 22, 1}; 67 | 68 | int n = sizeof(arr)/sizeof(arr[0]); 69 | 70 | selectionSort(arr, n); 71 | 72 | printf("Sorted array: \n"); 73 | 74 | printArray(arr, n); 75 | 76 | return 0; 77 | 78 | } -------------------------------------------------------------------------------- /bucket_sort/CPP/BucketSort.cpp: -------------------------------------------------------------------------------- 1 | // Bucket sort 2 | // Time complexity is O(n) on average if all numbers are uniformly distributed 3 | 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | // Function to sort arr[] of size n using bucket sort 10 | void bucketSort(float arr[], int n) 11 | { 12 | // 1) Create n empty buckets 13 | vector b[n]; 14 | 15 | // 2) Put array elements in different buckets 16 | for (int i=0; i 17 | #include 18 | #include 19 | #include 20 | 21 | using namespace std::chrono; 22 | using namespace std; 23 | 24 | int main(){ 25 | int inpt; 26 | vector store; 27 | vector:: iterator it; 28 | 29 | cout << "Unsorted Input -- "; 30 | while(cin.peek() != '\n'){ 31 | cin >> inpt; 32 | store.push_back(inpt); 33 | } 34 | 35 | auto start = high_resolution_clock::now(); 36 | 37 | it = max_element(store.begin(), store.end()); 38 | int range = *it; 39 | vector aux(range, 0); 40 | 41 | for(auto i: store){ aux[i-1]+=1; } 42 | 43 | cout << "Sorted Output -- "; 44 | for(int i = 0; i < range; i++){ 45 | for(int j = 1; j <= aux[i]; j++){ 46 | cout << i+1 << " "; 47 | } 48 | } 49 | 50 | auto end = high_resolution_clock::now(); 51 | 52 | cout << "Time Elapsed -- " << duration_cast(end - start).count() << " microS.\n"; 53 | 54 | } -------------------------------------------------------------------------------- /merge_sort/ruby/merge_sort.rb: -------------------------------------------------------------------------------- 1 | class MergeSortAlgorithm 2 | # Break's the array down into two numbers (number A and number B) and sorts them. 3 | def sort(numbers) 4 | if numbers.size <= 1 5 | return numbers 6 | end 7 | 8 | array_size = numbers.size 9 | half_of_size = (array_size / 2).round 10 | 11 | left_array = numbers.take(half_of_size) 12 | right_array = numbers.drop(half_of_size) 13 | 14 | sorted_left_array = sort(left_array) 15 | sorted_right_array = sort(right_array) 16 | 17 | merge(sorted_left_array, sorted_right_array) 18 | end 19 | 20 | # This then creates a new array, loops through the left/right arrays and places the lowest number into the array. 21 | def merge(left_array, right_array) 22 | if right_array.empty? 23 | return left_array # We have nothing to compare. Left wins. 24 | end 25 | 26 | if left_array.empty? 27 | return right_array # We have nothing to compare. Right wins. 28 | end 29 | 30 | smallest_number = if left_array.first <= right_array.first 31 | left_array.shift 32 | else 33 | right_array.shift 34 | end 35 | 36 | # We keep doing it until the left or right array is empty. 37 | recursive = merge(left_array, right_array) 38 | 39 | # Okay, either left or right array are empty at this point. So we have a result. 40 | [smallest_number].concat(recursive) 41 | end 42 | end 43 | -------------------------------------------------------------------------------- /depth_first_search/java/depthffs.java: -------------------------------------------------------------------------------- 1 | 2 | import java.io.*; 3 | import java.util.*; 4 | 5 | 6 | 7 | class Graph 8 | { 9 | private int V; // No. of vertices 10 | 11 | 12 | private LinkedList adj[]; 13 | 14 | 15 | Graph(int v) 16 | { 17 | V = v; 18 | adj = new LinkedList[v]; 19 | for (int i=0; i i = adj[v].listIterator(); 37 | while (i.hasNext()) 38 | { 39 | int n = i.next(); 40 | if (!visited[n]) 41 | DFSUtil(n, visited); 42 | } 43 | } 44 | 45 | 46 | void DFS(int v) 47 | { 48 | // Mark all the vertices as not visited(set as 49 | // false by default in java) 50 | boolean visited[] = new boolean[V]; 51 | 52 | 53 | DFSUtil(v, visited); 54 | } 55 | 56 | public static void main(String args[]) 57 | { 58 | Graph g = new Graph(4); 59 | 60 | g.addEdge(0, 1); 61 | g.addEdge(0, 2); 62 | g.addEdge(1, 2); 63 | g.addEdge(2, 0); 64 | g.addEdge(2, 3); 65 | g.addEdge(3, 3); 66 | 67 | System.out.println("Following is Depth First Traversal "+ 68 | "(starting from vertex 2)"); 69 | 70 | g.DFS(2); 71 | } 72 | } 73 | 74 | -------------------------------------------------------------------------------- /linear_search/c#/linear_search.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace forgetCode 4 | { 5 | class Program 6 | { 7 | public static void Main() 8 | { 9 | int[] a = new int[100]; 10 | Console.WriteLine("Enter number of elements you want to hold in the array ?"); 11 | string s = Console.ReadLine(); 12 | int x = Int32.Parse(s); 13 | Console.WriteLine("-------------------------"); 14 | Console.WriteLine("\n Enter array elements \n"); 15 | for (int i = 0; i < x; i++) 16 | { 17 | string s1 = Console.ReadLine(); 18 | a[i] = Int32.Parse(s1); 19 | } 20 | Console.WriteLine("-------------------------"); 21 | Console.WriteLine("Enter Search element\n"); 22 | string s3 = Console.ReadLine(); 23 | int x2 = Int32.Parse(s3); 24 | for (int i = 0; i < x; i++) 25 | { 26 | if (a[i] == x2) 27 | { 28 | Console.WriteLine("-------------------------"); 29 | Console.WriteLine("Search successful"); 30 | Console.WriteLine("Element {0} found at location {1}\n", x2, i + 1); 31 | return; 32 | } 33 | } 34 | Console.WriteLine("Search unsuccessful"); 35 | } 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /dynamic_programming/Min_pts_to_reach_destination.cpp: -------------------------------------------------------------------------------- 1 | // Problem statement, I/O formats clearly explained: https://practice.geeksforgeeks.org/problems/minimum-points-to-reach-destination/0 2 | 3 | #include 4 | using namespace std; 5 | 6 | int mini=INT_MAX,**arr; 7 | 8 | // arr is the main dp matrix 9 | 10 | void count(int r,int c,int cr,int cc,int csum,int locmin){ 11 | 12 | int newsum = csum+arr[cr][cc]; 13 | if(cr==r-1 && cc==c-1) 14 | mini = min(mini,min(locmin,newsum)>0?1:(1-min(locmin,newsum))); 15 | 16 | else if(cr>test; 31 | while(test--){ 32 | mini=INT_MAX; 33 | cin>>r>>c; 34 | arr = (int **)malloc(r * sizeof(int *)); 35 | for (int i=0; i>arr[i][j]; 40 | count(r,c,0,0,0,INT_MAX); 41 | cout<< mini << endl; 42 | 43 | } 44 | return 0; 45 | } 46 | 47 | -------------------------------------------------------------------------------- /dynamic_programming/ugly_numbers/java/UglyNos.java: -------------------------------------------------------------------------------- 1 | // Java program to find nth ugly number 2 | import java.lang.Math; 3 | 4 | class UglyNumber 5 | { 6 | /* Function to get the nth ugly number*/ 7 | int getNthUglyNo(int n) 8 | { 9 | int ugly[] = new int[n]; // To store ugly numbers 10 | int i2 = 0, i3 = 0, i5 = 0; 11 | int next_multiple_of_2 = 2; 12 | int next_multiple_of_3 = 3; 13 | int next_multiple_of_5 = 5; 14 | int next_ugly_no = 1; 15 | 16 | ugly[0] = 1; 17 | 18 | for(int i = 1; i < n; i++) 19 | { 20 | next_ugly_no = Math.min(next_multiple_of_2, 21 | Math.min(next_multiple_of_3, 22 | next_multiple_of_5)); 23 | 24 | ugly[i] = next_ugly_no; 25 | if (next_ugly_no == next_multiple_of_2) 26 | { 27 | i2 = i2+1; 28 | next_multiple_of_2 = ugly[i2]*2; 29 | } 30 | if (next_ugly_no == next_multiple_of_3) 31 | { 32 | i3 = i3+1; 33 | next_multiple_of_3 = ugly[i3]*3; 34 | } 35 | if (next_ugly_no == next_multiple_of_5) 36 | { 37 | i5 = i5+1; 38 | next_multiple_of_5 = ugly[i5]*5; 39 | } 40 | } /*End of for loop (i=1; i 2 | #include 3 | 4 | #define MAX 5 5 | 6 | struct Queue 7 | { 8 | int data[MAX]; 9 | int front,rear; 10 | }; 11 | 12 | int retrieve(struct Queue *q) 13 | { 14 | int item; 15 | if(q->front==-1 && q->rear==-1) 16 | { 17 | printf("\nUnderflow"); 18 | return INT_MIN; 19 | } 20 | else if(q->front==q->rear && q->front!=-1) 21 | { 22 | item=q->data[q->front]; 23 | q->front=q->rear=-1; 24 | return item; 25 | } 26 | else 27 | return q->data[q->front++]; 28 | 29 | } 30 | void insert(struct Queue *q,int item) 31 | { 32 | if(q->rear==MAX-1) 33 | { 34 | printf("\nOverflow"); 35 | return; 36 | } 37 | q->front=0; 38 | q->rear++; 39 | q->data[q->rear]=item; 40 | printf("\nElement inserted successfully..:)"); 41 | } 42 | 43 | 44 | int main() 45 | { 46 | int choice; 47 | struct Queue q; 48 | q.front=q.rear=-1; 49 | while(1) 50 | { 51 | printf("\n1. Insert\n2. Retrieve\n3. Exit"); 52 | printf("\nEnter choice:"); 53 | scanf("%d",&choice); 54 | switch(choice) 55 | { 56 | case 1: int item; 57 | printf("\nEnter the element you want to insert:"); 58 | scanf("%d",&item); 59 | insert(&q,item); 60 | 61 | break; 62 | case 2: item=retrieve(&q); 63 | if(item!=INT_MIN) 64 | printf("\n%d deleted",item); 65 | break; 66 | case 3: return 0; 67 | default: printf("WRONG INPUT!!!!!!"); 68 | } 69 | } 70 | return 0; 71 | } 72 | -------------------------------------------------------------------------------- /greedy/knapsack.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | int w[20], p[20], r[20], temp, cap, n, i, j; 5 | printf("\nEnter the no. of objects:- "); 6 | scanf("%d", &n); 7 | printf("\nEnter the wts and profits of each object:- "); 8 | for (i = 0; i < n; i++) { 9 | printf("For item no %d\n", i); 10 | scanf("%d %d", &w[i], &p[i]); 11 | } 12 | printf("\nEnter the capacity:\n "); 13 | scanf("%d", &cap); 14 | for (i = 0; i < n; i++) { 15 | r[i] = p[i] / w[i]; 16 | } 17 | for (i = 0; i < n; i++) { 18 | for (j = i + 1; j < n; j++) { 19 | if (r[i] < r[j]) { 20 | temp = r[j]; 21 | r[j] = r[i]; 22 | r[i] = temp; 23 | 24 | temp = w[j]; 25 | w[j] = w[i]; 26 | w[i] = temp; 27 | 28 | temp = p[j]; 29 | p[j] = p[i]; 30 | p[i] = temp; 31 | } 32 | } 33 | } 34 | knap(n, w, p, cap); 35 | return(0); 36 | } 37 | void knap(int n, int w[], int p[], int cap) { 38 | int i, j, u= cap, x[20], tp = 0; 39 | for (i = 0; i < n; i++) 40 | x[i] = 0; 41 | for (i = 0; i < n; i++) { 42 | if (w[i] > u) 43 | break; 44 | else { 45 | x[i] = 1; 46 | tp = tp + p[i]; 47 | u = u - w[i]; 48 | } 49 | } 50 | if (i < n) 51 | x[i] = u / w[i]; 52 | tp = tp + (x[i] * p[i]); 53 | printf("\nTotal profit is:- %d", tp); 54 | } 55 | -------------------------------------------------------------------------------- /stack/golang/stack.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | // Node represents one entity in the stack 8 | type Node struct { 9 | Data int 10 | Next *Node 11 | } 12 | 13 | // Top is the base of the stack. Points to nil 14 | var Top *Node 15 | 16 | // CreateNode creates a node for a give data value 17 | func CreateNode(data int) *Node { 18 | return &Node{Data: data} 19 | } 20 | 21 | // Push points the given node to the current top node. And declares 22 | // the current node as the top node 23 | func Push(node *Node) { 24 | node.Next = Top 25 | Top = node 26 | } 27 | 28 | // Pop returns the top node and removes it from the stack and 29 | // declares the next node as the top node 30 | func Pop() *Node { 31 | popped := Top 32 | Top = Top.Next 33 | return popped 34 | } 35 | 36 | // DisplayStack traverses through the stack and displays the value 37 | // of each Node 38 | func DisplayStack() { 39 | currentNode := Top 40 | for currentNode != nil { 41 | fmt.Printf("%d -> ", currentNode.Data) 42 | currentNode = currentNode.Next 43 | } 44 | fmt.Println("base") 45 | } 46 | 47 | func main() { 48 | Top = nil 49 | 50 | Push(CreateNode(1)) 51 | Push(CreateNode(2)) 52 | Push(CreateNode(3)) 53 | Push(CreateNode(4)) 54 | 55 | DisplayStack() 56 | 57 | Pop() 58 | DisplayStack() 59 | Pop() 60 | DisplayStack() 61 | } 62 | 63 | // Output: 64 | // 4 -> 3 -> 2 -> 1 -> base 65 | // 3 -> 2 -> 1 -> base 66 | // 2 -> 1 -> base 67 | -------------------------------------------------------------------------------- /dynamic_programming/longest-common-subsequence.py: -------------------------------------------------------------------------------- 1 | """ 2 | A subsequence is a sequence that can be derived from another 3 | sequence by deleting some or no elements without changing the 4 | order of the remaining elements. 5 | 6 | For example, 'abd' is a subsequence of 'abcd' whereas 'adc' is not 7 | 8 | Given 2 strings containing lowercase english alphabets, find the length 9 | of the Longest Common Subsequence (L.C.S.). 10 | 11 | Example: 12 | Input: 'abcdgh' 13 | 'aedfhr' 14 | Output: 3 15 | 16 | Explanation: The longest subsequence common to both the string is "adh" 17 | 18 | Time Complexity : O(M*N) 19 | Space Complexity : O(M*N), where M and N are the lengths of the 1st and 2nd string 20 | respectively. 21 | 22 | """ 23 | 24 | 25 | def longest_common_subsequence(s1, s2): 26 | """ 27 | :param s1: string 28 | :param s2: string 29 | :return: int 30 | """ 31 | m = len(s1) 32 | n = len(s2) 33 | 34 | dp = [[0] * (n + 1) for i in range(m + 1)] 35 | """ 36 | dp[i][j] : contains length of LCS of s1[0..i-1] and s2[0..j-1] 37 | """ 38 | 39 | for i in range(m + 1): 40 | for j in range(n + 1): 41 | if i == 0 or j == 0: 42 | dp[i][j] = 0 43 | elif s1[i - 1] == s2[j - 1]: 44 | dp[i][j] = dp[i - 1][j - 1] + 1 45 | else: 46 | dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) 47 | 48 | return dp[m][n] 49 | -------------------------------------------------------------------------------- /Contributor.md: -------------------------------------------------------------------------------- 1 | # HacktoberFest2018 2 | 3 | This is a repo created to remember the Hacktober Fest organized by Github, DigitalOcean and Twilio. 4 | 5 | ![Hacktober Logo ](https://raw.githubusercontent.com/asangam/HacktoberFest2018/master/hacktober_log.png) 6 | 7 | ### Please Enter your details and be part of the HacktoberFest2018 8 | 9 | - [Your Name](http://yourgithuburl) | [Your School/Uni](https://www.youruniurl/) 10 | - [Saurav Jaiswal](https://github.com/sauravjaiswalsj) | [Sathyabama Institute of Science and Technology](http://www.sathyabama.ac.in/) 11 | - [Foxxy](https://github.com/foxxydev) | ["Aurel Vlaicu" University of Arad](http://www.uav.ro) 12 | - [Tejas Tank](https://github.com/majordwarf) | [Thakur College of Science and Commerce](http://tcsc.org.in/) 13 | - [Sayan Mondal](https://github.com/sayanmondal2098) | [Techno India University , West Bengal](http://technoindiauniversity.ac.in) 14 | - [Ema Fazillah](https://github.com/emafazillah) | [No school](https://twitter.com/hashtag/noschool?lang=en) 15 | - [Shubham Verma](https://github.com/shubhamvrm) | [Jamia Millia Islamia](https://www.jmi.ac.in) 16 | - [Abhinav Akhil](https://github.com/abhinavakhil) 17 | 18 | _Please follow the github Markdown format strictly else PR request might get neglected._ 19 | _Change the demo details and enter your details there, make sure to leave a demo markdown code there for other as it was before._ 20 | 21 | - [Be a part of HacktoberFest2018](https://hacktoberfest.digitalocean.com/) 22 | -------------------------------------------------------------------------------- /binary_search/java/BinarySearch2.java: -------------------------------------------------------------------------------- 1 | // Java implementation of iterative Binary Search 2 | class BinarySearch { 3 | // Returns index of x if it is present in arr[], 4 | // else return -1 5 | int binarySearch(int arr[], int l, int r, int x) 6 | { 7 | while (l <= r) { 8 | int mid = l + (r - l) / 2; 9 | 10 | // Check if x is present at mid 11 | if (arr[mid] == x) 12 | return mid; 13 | 14 | // If x is smaller, ignore right half 15 | if (arr[mid] > x) 16 | return binarySearch(arr, l, mid-1, x); 17 | 18 | // If x greater, ignore left half 19 | else 20 | return binarySearch(arr, mid+1, r, x); 21 | } 22 | 23 | // if we reach here, then element was 24 | // not present 25 | return -1; 26 | } 27 | 28 | // Driver method to test above 29 | public static void main(String args[]) 30 | { 31 | BinarySearch ob = new BinarySearch(); 32 | int arr[] = { 2, 3, 4, 10, 40 }; 33 | int n = arr.length; 34 | int x = 10; //this is the number to be searched 35 | int result = ob.binarySearch(arr, 0, n-1, x); 36 | if (result == -1) 37 | System.out.println("Element not present"); 38 | else 39 | System.out.println("Element found at " 40 | + "index " + result); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /bucket_sort/Go/bucket_sort.go: -------------------------------------------------------------------------------- 1 | // Bucket sort in Golang 2 | 3 | package main 4 | 5 | import ( 6 | "fmt" 7 | "os" 8 | "strconv" 9 | ) 10 | 11 | func insertionSort(array []float64) { 12 | for i := 0; i < len(array); i++ { 13 | temp := array[i] 14 | j := i - 1 15 | for ; j >= 0 && array[j] > temp; j-- { 16 | array[j+1] = array[j] 17 | } 18 | array[j+1] = temp 19 | } 20 | } 21 | 22 | func bucketSort(array []float64, bucketSize int) []float64 { 23 | var max, min float64 24 | for _, n := range array { 25 | if n < min { 26 | min = n 27 | } 28 | if n > max { 29 | max = n 30 | } 31 | } 32 | nBuckets := int(max-min)/bucketSize + 1 33 | buckets := make([][]float64, nBuckets) 34 | for i := 0; i < nBuckets; i++ { 35 | buckets[i] = make([]float64, 0) 36 | } 37 | 38 | for _, n := range array { 39 | idx := int(n-min) / bucketSize 40 | buckets[idx] = append(buckets[idx], n) 41 | } 42 | 43 | sorted := make([]float64, 0) 44 | for _, bucket := range buckets { 45 | if len(bucket) > 0 { 46 | insertionSort(bucket) 47 | sorted = append(sorted, bucket...) 48 | } 49 | } 50 | 51 | return sorted 52 | } 53 | 54 | func main() { 55 | 56 | array := []float64{4, 1, 1, 3, 2, 2, 7, -6, 0} 57 | for _, arg := range os.Args[1:] { 58 | if n, err := strconv.ParseFloat(arg, 64); err == nil { 59 | array = append(array, n) 60 | } 61 | } 62 | fmt.Printf("Before Bucket Sort %v\n", array) 63 | array = bucketSort(array, 5) 64 | fmt.Printf("After Bucket Sort %v\n", array) 65 | } 66 | -------------------------------------------------------------------------------- /greedy/dijsktra/dijsktra.py: -------------------------------------------------------------------------------- 1 | # Python program for Dijkstra's single 2 | 3 | import sys 4 | 5 | class Graph(): 6 | 7 | def __init__(self, vertices): 8 | self.V = vertices 9 | self.graph = [[0 for column in range(vertices)] 10 | for row in range(vertices)] 11 | 12 | def printSolution(self, dist): 13 | print "Vertex \tDistance from Source" 14 | for node in range(self.V): 15 | print node, "\t", dist[node] 16 | def minDistance(self, dist, sptSet): 17 | min = sys.maxint 18 | for v in range(self.V): 19 | if dist[v] < min and sptSet[v] == False: 20 | min = dist[v] 21 | min_index = v 22 | 23 | return min_index 24 | def dijkstra(self, src): 25 | 26 | dist = [sys.maxint] * self.V 27 | dist[src] = 0 28 | sptSet = [False] * self.V 29 | 30 | for cout in range(self.V): 31 | u = self.minDistance(dist, sptSet) 32 | sptSet[u] = True 33 | for v in range(self.V): 34 | if self.graph[u][v] > 0 and sptSet[v] == False and dist[v] > dist[u] + self.graph[u][v]: 35 | dist[v] = dist[u] + self.graph[u][v] 36 | 37 | self.printSolution(dist) 38 | 39 | # Driver program 40 | g = Graph(9) 41 | g.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0], 42 | [4, 0, 8, 0, 0, 0, 0, 11, 0], 43 | [0, 8, 0, 7, 0, 4, 0, 0, 2], 44 | [0, 0, 7, 0, 9, 14, 0, 0, 0], 45 | [0, 0, 0, 9, 0, 10, 0, 0, 0], 46 | [0, 0, 4, 14, 10, 0, 2, 0, 0], 47 | [0, 0, 0, 0, 0, 2, 0, 1, 6], 48 | [8, 11, 0, 0, 0, 0, 1, 0, 7], 49 | [0, 0, 2, 0, 0, 0, 6, 7, 0] 50 | ]; 51 | 52 | g.dijkstra(0); 53 | 54 | 55 | -------------------------------------------------------------------------------- /heap_sort/c#/heap_sort.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | namespace HeapSortDemo { 3 | public class example { 4 | static void heapSort(int[] arr, int n) { 5 | for (int i = n / 2 - 1; i >= 0; i--) 6 | heapify(arr, n, i); 7 | for (int i = n-1; i>=0; i--) { 8 | int temp = arr[0]; 9 | arr[0] = arr[i]; 10 | arr[i] = temp; 11 | heapify(arr, i, 0); 12 | } 13 | } 14 | static void heapify(int[] arr, int n, int i) { 15 | int largest = i; 16 | int left = 2*i + 1; 17 | int right = 2*i + 2; 18 | if (left < n && arr[left] > arr[largest]) 19 | largest = left; 20 | if (right < n && arr[right] > arr[largest]) 21 | largest = right; 22 | if (largest != i) { 23 | int swap = arr[i]; 24 | arr[i] = arr[largest]; 25 | arr[largest] = swap; 26 | heapify(arr, n, largest); 27 | } 28 | } 29 | public static void Main() { 30 | int[] arr = {55, 25, 89, 34, 12, 19, 78, 95, 1, 100}; 31 | int n = 10, i; 32 | Console.WriteLine("Heap Sort"); 33 | Console.Write("Initial array is: "); 34 | for (i = 0; i < n; i++) { 35 | Console.Write(arr[i] + " "); 36 | } 37 | heapSort(arr, 10); 38 | Console.Write("\nSorted Array is: "); 39 | for (i = 0; i < n; i++) { 40 | Console.Write(arr[i] + " "); 41 | } 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /breath_first_search/cpp/bfs.cpp: -------------------------------------------------------------------------------- 1 | // Program to print BFS traversal from a given 2 | // source vertex. BFS(int s) traverses vertices 3 | // reachable from s. 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | // This class represents a directed graph using 10 | class Graph 11 | { 12 | int V; 13 | list *adj; 14 | public: 15 | Graph(int V); 16 | void addEdge(int v, int w); 17 | void BFS(int s); 18 | }; 19 | 20 | Graph::Graph(int V) 21 | { 22 | this->V = V; 23 | adj = new list[V]; 24 | } 25 | 26 | void Graph::addEdge(int v, int w) 27 | { 28 | adj[v].push_back(w); 29 | } 30 | 31 | void Graph::BFS(int s) 32 | { 33 | bool *visited = new bool[V]; 34 | for(int i = 0; i < V; i++) 35 | visited[i] = false; 36 | list queue; 37 | visited[s] = true; 38 | queue.push_back(s); 39 | list::iterator i; 40 | 41 | while(!queue.empty()) 42 | { 43 | s = queue.front(); 44 | cout << s << " "; 45 | queue.pop_front(); 46 | for (i = adj[s].begin(); i != adj[s].end(); ++i) 47 | { 48 | if (!visited[*i]) 49 | { 50 | visited[*i] = true; 51 | queue.push_back(*i); 52 | } 53 | } 54 | } 55 | } 56 | 57 | // Driver program 58 | int main() 59 | { 60 | Graph g(4); 61 | g.addEdge(0, 1); 62 | g.addEdge(0, 2); 63 | g.addEdge(1, 2); 64 | g.addEdge(2, 0); 65 | g.addEdge(2, 3); 66 | g.addEdge(3, 3); 67 | 68 | cout << "Following is Breadth First Traversal " 69 | << "(starting from vertex 2) \n"; 70 | g.BFS(2); 71 | 72 | return 0; 73 | } 74 | -------------------------------------------------------------------------------- /linkedlist/python/LinkedList.py: -------------------------------------------------------------------------------- 1 | #Python program to search for an element in a linked list using recursion 2 | class Node: 3 | def __init__(self, data): 4 | self.data = data 5 | self.next = None 6 | 7 | 8 | class LinkedList: 9 | def __init__(self): 10 | self.head = None 11 | self.last_node = None 12 | 13 | def append(self, data): 14 | if self.last_node is None: 15 | self.head = Node(data) 16 | self.last_node = self.head 17 | else: 18 | self.last_node.next = Node(data) 19 | self.last_node = self.last_node.next 20 | 21 | def display(self): 22 | current = self.head 23 | while current is not None: 24 | print(current.data, end=' ') 25 | current = current.next 26 | 27 | def find_index(self, key): 28 | return self.find_index_helper(key, 0, self.head) 29 | 30 | def find_index_helper(self, key, start, node): 31 | if node is None: 32 | return -1 33 | 34 | if node.data == key: 35 | return start 36 | else: 37 | return self.find_index_helper(key, start + 1, node.next) 38 | 39 | 40 | a_llist = LinkedList() 41 | for data in [3, 5, 0, 10, 7]: 42 | a_llist.append(data) 43 | print('The linked list: ', end='') 44 | a_llist.display() 45 | print() 46 | 47 | key = int(input('What data item would you like to search for? ')) 48 | index = a_llist.find_index(key) 49 | if index == -1: 50 | print(str(key) + ' was not found.') 51 | else: 52 | print(str(key) + ' is at index ' + str(index) + '.') -------------------------------------------------------------------------------- /trees/traversals/javascript/treeTrav.js: -------------------------------------------------------------------------------- 1 | // Prg for tree traversals in JS 2 | 3 | function Node(data) { 4 | this.data = data; 5 | this.left = null; 6 | this.right = null; 7 | } 8 | 9 | // Creating Nodes 10 | var root = new Node(1); 11 | var n1 = new Node(2); 12 | var n2 = new Node(3); 13 | var n3 = new Node(4); 14 | var n4 = new Node(5); 15 | 16 | // Setting Children 17 | root.left = n1; 18 | root.right = n2; 19 | n1.left = n3; 20 | n1.right = n4; 21 | 22 | 23 | // PREORDER Traversal 24 | function pre_order(root, nodes) { 25 | console.log(root.data); 26 | if (root && root.left) { 27 | pre_order(root.left, nodes); 28 | } 29 | if (root && root.right) { 30 | pre_order(root.right, nodes); 31 | } 32 | return nodes; 33 | } 34 | 35 | 36 | // INORDER Traversal 37 | function in_order(root, nodes) { 38 | if (root && root.left) { 39 | in_order(root.left, nodes); 40 | } 41 | console.log(root.data); 42 | if (root && root.right) { 43 | in_order(root.right, nodes); 44 | } 45 | return nodes; 46 | } 47 | 48 | 49 | // POSTORDER Traversal 50 | function post_order(root, nodes) { 51 | if (root && root.left) { 52 | post_order(root.left, nodes); 53 | } 54 | if (root && root.right) { 55 | post_order(root.right, nodes); 56 | } 57 | console.log(root.data); 58 | return nodes; 59 | } 60 | 61 | 62 | // MAIN 63 | console.log("InOrder Traversal: ") 64 | in_order(root, []); 65 | 66 | console.log("PreOrder Traversal: ") 67 | pre_order(root, []); 68 | 69 | console.log("PostOrder Traversal: ") 70 | post_order(root, []); -------------------------------------------------------------------------------- /queues/python/queue.py: -------------------------------------------------------------------------------- 1 | class Queue: 2 | def __init__(self): 3 | self.queue = [] 4 | 5 | # Return true if the queue is empty false otherwise 6 | def isEmpty(self): 7 | return self.queue == [] 8 | 9 | # Add item to the beginning of the queue 10 | def enqueue(self, item): 11 | self.queue.insert(0,item) 12 | print(str(item) + " has been enqueued.") 13 | 14 | # Remove and return the first item in the queue if not empty 15 | def dequeue(self): 16 | try: 17 | print(str(self.queue[-1]) + " has been dequeued.") 18 | return self.queue.pop() 19 | except IndexError: 20 | print("Can't dequeue from an empty queue.") 21 | 22 | # Return the front element of the queue if it exists 23 | def front(self): 24 | try: 25 | print(str(self.queue[-1]) + " is in the front.") 26 | return self.queue[-1] 27 | except: 28 | print("Queue is empty. Nothing is in the front.") 29 | 30 | # Return the number of items in the queue 31 | def length(self): 32 | return len(self.queue) 33 | 34 | # Print the contents of the queue 35 | def print(self): 36 | print(self.queue) 37 | 38 | # Dequeue all items from the queue 39 | def clear(self): 40 | while not self.isEmpty(): 41 | self.dequeue() 42 | print("The queue is clear.") 43 | 44 | 45 | def main(): 46 | my_queue = Queue() 47 | my_queue.front() 48 | my_queue.enqueue(5) 49 | my_queue.dequeue() 50 | my_queue.dequeue() 51 | my_queue.enqueue(3) 52 | my_queue.enqueue(8) 53 | my_queue.print() 54 | my_queue.front() 55 | my_queue.enqueue(2) 56 | my_queue.enqueue(4) 57 | my_queue.print() 58 | my_queue.clear() 59 | 60 | if __name__ == "__main__": 61 | main() -------------------------------------------------------------------------------- /trees/binary_search_tree/clang/optimal_binary_search.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void main() { 4 | int w[100][100], c[100][100], r[100][100], p[100], q[100], temp = 0, min, min1, n, i, j, k, b; 5 | printf("enter the number of elements:"); 6 | scanf("%d", & n); 7 | printf("\n"); 8 | for (i = 1; i <= n; i++) { 9 | printf("enter the elements of %d:", i); 10 | scanf("%d", & p[i]); 11 | } 12 | printf("\n"); 13 | for (i = 0; i <= n; i++) { 14 | printf("enter the probability of %d:", i); 15 | scanf("%d", & q[i]); 16 | } 17 | printf("w\t\tC\t\tR\n"); 18 | for (i = 0; i <= n; i++) { 19 | for (j = 0; j < n; j++) { 20 | if (i == j) { 21 | w[i][j] = q[i]; 22 | c[i][j] = 0; 23 | r[i][j] = 0; 24 | printf("W[%d][%d]:%d\tc[%d][%d]:%d\tr[%d][%d]:%d\n", i, j, w[i][j], i, j, c[i][j], i, j, r[i][j]); 25 | } 26 | } 27 | } 28 | printf("\n"); 29 | for (b = 0; b < n; b++) { 30 | for (i = 0, j = b + 1; j < n + 1 && i < n + 1; j++, i++) { 31 | if (i != j && i < j) { 32 | w[i][j] = p[j] + q[j] + w[i][j - 1]; 33 | min = 30000; 34 | for (k = i + 1; k <= j; k++) { 35 | min1 = c[i][k - 1] + c[k][j] + w[i][j]; 36 | if (min > min1) { 37 | min = min1; 38 | temp = k; 39 | } 40 | } 41 | c[i][j] = min; 42 | r[i][j] = temp; 43 | } 44 | printf("W[%d][%d]:%d\tc[%d][%d]:%d\tr[%d][%d]:%d\n", i, j, w[i][j], i, j, c[i][j], i, j, r[i][j]); 45 | } 46 | printf("\n"); 47 | } 48 | printf("minimum cost=%d\n", c[0][n]); 49 | printf("Root=%d\n", r[0][n]); 50 | } -------------------------------------------------------------------------------- /heap_sort/clang/heap_sort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int heap[10], n, i, j, c, root, temp; 6 | 7 | printf("\nEnter no of elements :"); 8 | scanf("%d", &n); 9 | printf("\nEnter the elements : \n"); 10 | for (i = 0; i < n; i++){ 11 | printf("Heap[%d] : ",i+1); 12 | scanf("%d", &heap[i]); 13 | } 14 | for (i = 1; i < n; i++) 15 | { 16 | c = i; 17 | do 18 | { 19 | root = (c - 1) / 2; 20 | if (heap[root] < heap[c]) /* creating MAX heap array */ 21 | { 22 | temp = heap[root]; 23 | heap[root] = heap[c]; 24 | heap[c] = temp; 25 | } 26 | c = root; 27 | } while (c != 0); 28 | } 29 | 30 | for (j = n - 1; j >= 0; j--) 31 | { 32 | temp = heap[0]; 33 | heap[0] = heap[j]; /* swap max element with rightmost leaf element */ 34 | heap[j] = temp; 35 | root = 0; 36 | do 37 | { 38 | c = 2 * root + 1; /* left node of root element */ 39 | if ((heap[c] < heap[c + 1]) && c < j-1) 40 | c++; 41 | if (heap[root]max) 11 | max=arr[i]; 12 | return max; 13 | } 14 | 15 | static void countSort(int arr[], int n, int exp){ 16 | int output[]=new int[n]; 17 | int count[]=new int[10]; 18 | Arrays.fill(count,0); 19 | 20 | for(int i=0;i= 0;i--) { 27 | output[count[(arr[i]/exp)%10]-1]=arr[i]; 28 | count[(arr[i]/exp)%10]--; 29 | } 30 | 31 | for(int i=0;i0;exp*= 10) 38 | countSort(arr,n,exp); 39 | } 40 | 41 | public static void main (String[] args) { 42 | Scanner in=new Scanner(System.in); 43 | int size=in.nextInt(); 44 | int arr[]=new int[size]; 45 | for(int i=0;i= 0; i--) 8 | heapify(arr, unsortedArray, i); 9 | 10 | for (int i = unsortedArray-1; i >= 0; i--) 11 | { 12 | int temp = arr[0]; 13 | arr[0] = arr[i]; 14 | arr[i] = temp; 15 | 16 | heapify(arr, i, 0); 17 | } 18 | } 19 | 20 | void heapify(int arr[], int n, int i) 21 | { 22 | int largest = i; 23 | int left = 2*i + 1; 24 | int right = 2*i + 2; 25 | 26 | if (left < n && arr[left] > arr[largest]) 27 | largest = left; 28 | 29 | if (right < n && arr[right] > arr[largest]) 30 | largest = right; 31 | 32 | if (largest != i) 33 | { 34 | int swap = arr[i]; 35 | arr[i] = arr[largest]; 36 | arr[largest] = swap; 37 | 38 | heapify(arr, n, largest); 39 | } 40 | } 41 | 42 | static void printArray(int arr[]) 43 | { 44 | int unsortedArray = arr.length; 45 | for (int i = 0; i < unsortedArray; i++) { 46 | System.out.print(arr[i] + " "); 47 | } 48 | } 49 | 50 | public static void main(String args[]) 51 | { 52 | int arr[] = {12, 15, 13, 5, 14, 11, 6, 7, 1, 8, 4}; 53 | 54 | HeapSort ob = new HeapSort(); 55 | ob.sort(arr); 56 | 57 | System.out.println("The array got heap sorted:"); 58 | printArray(arr); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /counting_sort/cpp/counting.cpp: -------------------------------------------------------------------------------- 1 | // C++ Program for counting sort 2 | #include 3 | #include 4 | using namespace std; 5 | #define RANGE 255 6 | 7 | // The main function that sort 8 | // the given string arr[] in 9 | // alphabatical order 10 | void countSort(char arr[]) 11 | { 12 | // The output character array 13 | // that will have sorted arr 14 | char output[strlen(arr)]; 15 | 16 | // Create a count array to store count of inidividul 17 | // characters and initialize count array as 0 18 | int count[RANGE + 1], i; 19 | memset(count, 0, sizeof(count)); 20 | 21 | // Store count of each character 22 | for(i = 0; arr[i]; ++i) 23 | ++count[arr[i]]; 24 | 25 | // Change count[i] so that count[i] now contains actual 26 | // position of this character in output array 27 | for (i = 1; i <= RANGE; ++i) 28 | count[i] += count[i-1]; 29 | 30 | // Build the output character array 31 | for (i = 0; arr[i]; ++i) 32 | { 33 | output[count[arr[i]]-1] = arr[i]; 34 | --count[arr[i]]; 35 | } 36 | 37 | /* 38 | For Stable algorithm 39 | for (i = sizeof(arr)-1; i>=0; --i) 40 | { 41 | output[count[arr[i]]-1] = arr[i]; 42 | --count[arr[i]]; 43 | } 44 | 45 | For Logic : See implementation 46 | */ 47 | 48 | // Copy the output array to arr, so that arr now 49 | // contains sorted characters 50 | for (i = 0; arr[i]; ++i) 51 | arr[i] = output[i]; 52 | } 53 | 54 | // Driver code 55 | int main() 56 | { 57 | char arr[] = "geeksforgeeks"; 58 | 59 | countSort(arr); 60 | 61 | cout<< "Sorted character array is " << arr; 62 | return 0; 63 | } 64 | 65 | // This code is contributed by rathbhupendra 66 | -------------------------------------------------------------------------------- /merge_sort/java/merge_sort.java: -------------------------------------------------------------------------------- 1 | public class MergeSort { 2 | private static int[] exArray; 3 | public static void sort(int[] arrayToSort){ 4 | exArray = new int[arrayToSort.length]; 5 | mergeSort(arrayToSort,0,arrayToSort.length-1); 6 | } 7 | 8 | private static void mergeSort(int[]array,int leftIndex,int rightIndex){ 9 | if(leftIndex= 0; i--) { 29 | output[count[arr[i]]-1] = arr[i]; 30 | count[arr[i]]--; 31 | } 32 | 33 | // Copy the output array to arr, so that arr now 34 | // contains sorted characters 35 | for (int i = 0; i < n; ++i) { 36 | arr[i] = output[i]; 37 | } 38 | 39 | } 40 | 41 | public static void main(String args[]) throws UnsupportedEncodingException { 42 | counting_sort ob = new counting_sort(); 43 | 44 | Scanner scanner = new Scanner(System.in); 45 | 46 | String input = scanner.next(); 47 | char[] arr = input.toCharArray(); 48 | 49 | ob.sort(arr); 50 | 51 | System.out.print("Sorted character array is "); 52 | for (int i = 0; i < arr.length; i++) { 53 | System.out.print(arr[i]); 54 | } 55 | 56 | scanner.close(); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /shell_sort/java/ShellSort.java: -------------------------------------------------------------------------------- 1 | // Java implementation of ShellSort 2 | class ShellSort 3 | { 4 | /* An utility function to print array of size n*/ 5 | static void printArray(int arr[]) 6 | { 7 | int n = arr.length; 8 | for (int i=0; i 0; gap /= 2) 20 | { 21 | // Do a gapped insertion sort for this gap size. 22 | // The first gap elements a[0..gap-1] are already 23 | // in gapped order keep adding one more element 24 | // until the entire array is gap sorted 25 | for (int i = gap; i < n; i += 1) 26 | { 27 | // add a[i] to the elements that have been gap 28 | // sorted save a[i] in temp and make a hole at 29 | // position i 30 | int temp = arr[i]; 31 | 32 | // shift earlier gap-sorted elements up until 33 | // the correct location for a[i] is found 34 | int j; 35 | for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) 36 | arr[j] = arr[j - gap]; 37 | 38 | // put temp (the original a[i]) in its correct 39 | // location 40 | arr[j] = temp; 41 | } 42 | } 43 | return 0; 44 | } 45 | 46 | // Driver method 47 | public static void main(String args[]) 48 | { 49 | int arr[] = {12, 34, 54, 2, 3}; 50 | System.out.println("Array before sorting"); 51 | printArray(arr); 52 | 53 | ShellSort ob = new ShellSort(); 54 | ob.sort(arr); 55 | 56 | System.out.println("Array after sorting"); 57 | printArray(arr); 58 | } 59 | } 60 | --------------------------------------------------------------------------------