├── Search Algorithms ├── Golang │ ├── go.mod │ ├── main.go │ └── linear │ │ └── LinearSearch.go ├── C-CPP │ ├── a.out │ ├── Linear Search.cpp │ ├── LinearSearch.c │ ├── binarysearchusingrecursion.cpp │ ├── Binary_search.c │ ├── BinarySearch.cpp │ ├── jumpSearch.cpp │ ├── LinearSearchSentinelValue.cpp │ ├── LinearSearchSentinelValue.c │ ├── Interpolation_Search.cpp │ ├── exponentialsearch.c │ └── jump_search.c ├── Ruby │ └── LinearSearch.rb ├── Python │ ├── linear_search.py │ ├── RecursiveSearch.py │ ├── binary_search.py │ ├── breath-first-search.py │ ├── ExponentialSearch.py │ ├── InterpolationSearch.py │ ├── jump_search.py │ └── FibonacciSearch.py ├── Kotlin │ ├── LinearSearch.kt │ ├── BinarySearch.kt │ └── InterpolationSearch.kt ├── Java │ ├── LinearSearch.java │ ├── BinarySearch.java │ ├── JumpSearch.java │ └── InterpolationSearch.java ├── Dlang │ ├── linear.d │ └── binary.d └── CSharp │ └── linearSearch.cs ├── .DS_Store ├── Recursion ├── .DS_Store └── nQueen.cpp ├── Levenshtein ├── go.mod ├── levenshtein_test.go ├── levenshtein.go └── go.sum ├── Mathematical Algorithms ├── Java │ ├── Permutation.class │ └── Permutation.java ├── Python │ ├── prime_number_until_n.py │ └── Fibonacci.py ├── power.cpp ├── Kotlin │ └── IsPrime.kt ├── GcdOfArray.py ├── Sieve of Eratosthenes │ └── sieveOfEratosthenes.cpp ├── EuclideanGCD │ ├── euclidean_gcd.c │ ├── euclidean_gcd.py │ └── euclidean_gcd.java └── LcmOfArray.py ├── README.md ├── String Matching ├── matching.py ├── NaiveStringSearch.cpp ├── Rabin-Karp.cpp └── KMP.cpp ├── Wilson's Theorem ├── README.md └── Wilson'sTheorem.py ├── Sorting Algorithms ├── Python │ ├── bubble_sort.py │ ├── bogo_sort.py │ ├── wiggle_sort.py │ ├── quick_sort.py │ ├── topological_sort_in_python.py │ ├── insertion.py │ ├── radix_sort.py │ ├── shell_sort.py │ ├── counting_sort.py │ ├── bucket_sort.py │ ├── ShellSort.py │ └── merge_sort.py ├── php │ ├── selectionsort.php │ ├── Quick_Sort.php │ ├── insertionsort.php │ └── mergesort.php ├── CSharp │ ├── BubbleSort.cs │ └── QuickSort.cs ├── C-CPP │ ├── insertion_sort.cpp │ ├── insertion_sort.c │ ├── quick_sort.cpp │ ├── shell_sort.c │ ├── bubble_sort.cpp │ ├── ShellSort.cpp │ ├── bubble_sort.c │ ├── heap_sort.cpp │ ├── selection_sort.c │ ├── counting_sort.cpp │ ├── selection_sort.cpp │ ├── QuickSort.c │ ├── heap_sort.c │ ├── bogosort.cpp │ ├── bucketsort.cpp │ ├── merge_sort.cpp │ ├── BinaryInsertion.cpp │ ├── merge_sort.c │ └── radix_sort.cpp ├── Swift │ └── bubbleSort.swift ├── GO │ └── bubble_sort.go └── Java │ ├── InsertionSort.java │ ├── SelectionSort.java │ ├── QuickSort.java │ ├── BubbleSort.java │ ├── HeapSort.java │ └── MergeSort.java ├── String Manipulation ├── Python │ ├── check_if_is_palindrome.py │ └── occurence.py ├── pallindrome.cpp ├── cifracesar.c ├── php │ └── palindrome.php ├── led_string.c └── split.cpp ├── Dynamic Programming ├── coin_change.py ├── Golombsequence.cpp ├── cutting-a-rod.php ├── gcd.cpp ├── longestcommonsubsequence.cpp ├── Knapsack.cpp └── n-queen.cpp ├── Greedy Algorithms ├── Kadane's-Algorithm.cpp ├── Activityselection.cpp ├── Fractional-Knapsack.cpp ├── Job Sequencing.cpp ├── Prims.java └── Kruskals.java ├── Binary Tree ├── bst.java ├── BinaryTreeTraversal.cpp └── Binary Tree Traversal.c ├── LICENSE ├── Cryptography Algorithms ├── Cpp │ └── CeaserCipher.cpp └── Python │ └── OneTimePad.py ├── Graph ├── dfs_and_bfs.cpp └── SPATH.C ├── Backtracking ├── SumOfSubsets.cpp ├── mColor.java └── HamiltonianCycles.java ├── CONTRIBUTING.md ├── Contributors.md ├── Graph Algorithms ├── Cycle in undirected Graph.cpp ├── Dijikstras.java ├── Bellman–Ford Algorithm.cpp ├── fleury.cpp ├── Dial's algorithm.cpp └── Boruvka_MST.c └── Huffman_Coding └── Huffman_Coding.cpp /Search Algorithms/Golang/go.mod: -------------------------------------------------------------------------------- 1 | module Golang 2 | 3 | go 1.13 4 | -------------------------------------------------------------------------------- /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memr5/Algorithms/HEAD/.DS_Store -------------------------------------------------------------------------------- /Recursion/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memr5/Algorithms/HEAD/Recursion/.DS_Store -------------------------------------------------------------------------------- /Levenshtein/go.mod: -------------------------------------------------------------------------------- 1 | module Levenshtein 2 | 3 | go 1.13 4 | 5 | require github.com/stretchr/testify v1.4.0 6 | -------------------------------------------------------------------------------- /Search Algorithms/C-CPP/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memr5/Algorithms/HEAD/Search Algorithms/C-CPP/a.out -------------------------------------------------------------------------------- /Mathematical Algorithms/Java/Permutation.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memr5/Algorithms/HEAD/Mathematical Algorithms/Java/Permutation.class -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Algorithms 2 | 3 | Find Various Algorithms in any programming language here 4 | 5 | # To Contribute 6 | * Check [CONTRIBUTING.md](https://github.com/memr5/Algorithms/blob/master/CONTRIBUTING.md) file 7 | -------------------------------------------------------------------------------- /Search Algorithms/Golang/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "Golang/linear" 5 | "fmt" 6 | ) 7 | 8 | func main() { 9 | arr := []int{1, 2, 3, 4, 5} 10 | r := linear.Search(arr, 2) 11 | if r != -1 { 12 | fmt.Println("Found ", r, "!") 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Search Algorithms/Golang/linear/LinearSearch.go: -------------------------------------------------------------------------------- 1 | package linear 2 | 3 | // Search searches v in an given list arr. 4 | func Search(arr []int, v int) int { 5 | for i := 0; i < len(arr); i++ { 6 | if arr[i] == v { 7 | return arr[i] 8 | } 9 | } 10 | return -1 11 | } 12 | -------------------------------------------------------------------------------- /String Matching/matching.py: -------------------------------------------------------------------------------- 1 | sentence = raw_input('Enter the sentence: ') 2 | word = raw_input('Enter the word: ') 3 | 4 | arr = sentence.split() 5 | count = 0 6 | 7 | for temp in arr: 8 | if temp == word: 9 | count += 1 10 | 11 | print('number of matching string: {}'.format(count)) -------------------------------------------------------------------------------- /Search Algorithms/Ruby/LinearSearch.rb: -------------------------------------------------------------------------------- 1 | def linear_search(array, key) 2 | if array.index(key).nil? 3 | return -1 4 | else 5 | return "#{key} at index #{array.index(key)}" 6 | end 7 | end 8 | 9 | 10 | arr = [7, 6, 25, 19, 8, 14, 3, 16, 2, 0] 11 | key = 3 12 | p linear_search(arr, key) 13 | -------------------------------------------------------------------------------- /Wilson's Theorem/README.md: -------------------------------------------------------------------------------- 1 |

Wilson's Theorem

2 |
3 |

Wilson's theorem states that if p is a prime number, then (p-1)! % p = p-1. 4 |
5 | This equation is always true for prime numbers and never true for composite numbers. 6 |
7 | Using Wilson's theorem, this program displays all the prime numbers that are present in a user specified range (inclusive) are displayed.

8 | -------------------------------------------------------------------------------- /Search Algorithms/Python/linear_search.py: -------------------------------------------------------------------------------- 1 | def linear_search(lst,key): 2 | flag = 0 3 | for i in lst: 4 | if i == key: 5 | print("Found at position {}".format(lst.index(i)+1)) 6 | flag = flag+1 7 | if flag == 0: 8 | print("Not Found") 9 | 10 | 11 | # Driver Code 12 | my_list = [1,5,3,4] 13 | linear_search(my_list,5) 14 | linear_search(my_list,2) 15 | 16 | 17 | -------------------------------------------------------------------------------- /Search Algorithms/Kotlin/LinearSearch.kt: -------------------------------------------------------------------------------- 1 | fun linearSearch(arr: IntArray, key: Int) { 2 | for (i in arr.indices) if (arr[i] == key) { 3 | println("$key found at position $i") 4 | return 5 | } 6 | println("$key not found") 7 | } 8 | 9 | fun main(args: Array) { 10 | val arr = intArrayOf(9, 3, 1, 4, 5) 11 | linearSearch(arr, 4) 12 | linearSearch(arr, 2) 13 | } 14 | 15 | -------------------------------------------------------------------------------- /Mathematical Algorithms/Python/prime_number_until_n.py: -------------------------------------------------------------------------------- 1 | #Vincent Druesne 2 | #Give you all the prime number until n 3 | 4 | 5 | n = int(input("Enter n : ")) 6 | result = [] 7 | 8 | for i in range(1,n+1): 9 | test = True 10 | for j in range(2,i): 11 | if(i % j == 0): 12 | test = False 13 | if(not test): 14 | break 15 | if(test): 16 | result.append(i) 17 | 18 | print(result) 19 | -------------------------------------------------------------------------------- /Sorting Algorithms/Python/bubble_sort.py: -------------------------------------------------------------------------------- 1 | 2 | def bubble_sort(a): 3 | """Bubble sort""" 4 | 5 | for _ in range(len(a)): 6 | for i in range(1, len(a)): 7 | if a[i] < a[i-1]: 8 | temp = a[i] 9 | a[i] = a[i-1] 10 | a[i-1] = temp 11 | 12 | if __name__ == '__main__': 13 | arr = [10, 4, 8, 4, 9, 3, 0] 14 | print(arr) 15 | bubble_sort(arr) 16 | print(arr) -------------------------------------------------------------------------------- /Mathematical Algorithms/Python/Fibonacci.py: -------------------------------------------------------------------------------- 1 | amount_of_terms = int(input('How many terms of Fibonacci sequence do you want?: ')) 2 | i = 0 3 | fibo = [] 4 | 5 | 6 | while i < amount_of_terms: 7 | if i == 0: term = 0 8 | elif i == 1: term = 1 9 | elif i == 2: term = 1 10 | else: 11 | term = fibo[i-1]+fibo[i-2] 12 | 13 | fibo.append(term) 14 | i += 1 15 | 16 | for k in fibo: 17 | print (k, end = ' ') 18 | -------------------------------------------------------------------------------- /Mathematical Algorithms/power.cpp: -------------------------------------------------------------------------------- 1 | // C++ Program for finding power of a number in log N time 2 | #include 3 | using namespace std; 4 | 5 | int power(int x,int n) 6 | { 7 | int result=1; 8 | while(n) 9 | { 10 | if(n % 2 == 1) 11 | result *= x; 12 | x *= x; 13 | n /= 2; 14 | } 15 | return result; 16 | } 17 | 18 | int main(){ 19 | cout< arr[j]) 10 | { 11 | temp = arr[i]; 12 | arr[i] = arr[j]; 13 | arr[j] = temp; 14 | } 15 | } 16 | } 17 | return arr; 18 | } 19 | -------------------------------------------------------------------------------- /String Matching/NaiveStringSearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | string s; 6 | string n; 7 | cin>>s>>n; 8 | int z=s.length()-n.length(); 9 | for(int i=0;i<=z;i++) 10 | { 11 | int count=0; 12 | for(int j=0;j=0: 7 | if string[i] != " ": 8 | stack.append(string[i]) 9 | i=i-1 10 | 11 | stringBackwards = "" 12 | for i in range(len(string)): 13 | stringBackwards = stringBackwards+stack[i] 14 | 15 | if string == stringBackwards: 16 | print("is palindrome") 17 | else: 18 | print("isnt palindrome") 19 | 20 | input("Press enter to exit") -------------------------------------------------------------------------------- /Search Algorithms/Python/RecursiveSearch.py: -------------------------------------------------------------------------------- 1 | # Recursive function to search x in arr[l..r] 2 | def recSearch( arr, l, r, x): 3 | if r < l: 4 | return -1 5 | if arr[l] == x: 6 | return l 7 | if arr[r] == x: 8 | return r 9 | return recSearch(arr, l+1, r-1, x) 10 | 11 | # Driver Code 12 | arr = [12, 34, 54, 2, 3] 13 | n = len(arr) 14 | x = 3 15 | index = recSearch(arr, 0, n-1, x) 16 | if index != -1: 17 | print "Element", x,"is present at index %d" %(index) 18 | else: 19 | print "Element %d is not present" %(x) 20 | 21 | -------------------------------------------------------------------------------- /Sorting Algorithms/Python/bogo_sort.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def bogoSort(x): 4 | n = len(x) 5 | while (isSorted(x) == False): 6 | shuffle(x) 7 | 8 | def isSorted(x): 9 | n = len(x) 10 | for i in range(0, n-1): 11 | if (x[i] > x[i+1]): 12 | return False 13 | return True 14 | 15 | def shuffle(x): 16 | n = len(x) 17 | for i in range(0,n): 18 | r = random.randint(0,n-1) 19 | x[i], x[r] = x[r], x[i] 20 | 21 | #Driver code 22 | x = [4, 2, 3, 33, 12, 1, 20, 21] 23 | bogoSort(x) 24 | for i in range(len(x)): 25 | print("%d" %x[i]) 26 | -------------------------------------------------------------------------------- /Sorting Algorithms/C-CPP/insertion_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void InsertionSort(int a[],int n){ 5 | for(int i=1;i0){ 8 | int temp=a[j]; 9 | a[j]=a[j-1]; 10 | a[j-1]=temp; 11 | --j; 12 | } 13 | } 14 | } 15 | 16 | int main(){ 17 | int a[]={12, 11, 13, 5, 6}; 18 | 19 | InsertionSort(a,5); 20 | 21 | for(int i=0;i<5;i++){ 22 | cout< nums[2] < nums[3].... 3 | Next Align the snippet in provided order. 4 | 5 | Credits: @Neilblaze, @keon 6 | """ 7 | 8 | def wiggle_sort(nums): 9 | for i in range(len(nums)): 10 | if (i % 2 == 1) == (nums[i-1] > nums[i]): 11 | nums[i-1], nums[i] = nums[i], nums[i-1] 12 | 13 | if __name__ == "__main__": 14 | array = [3, 5, 2, 1, 6, 4] 15 | 16 | print(array) 17 | wiggle_sort(array) 18 | print(array) 19 | -------------------------------------------------------------------------------- /Search Algorithms/C-CPP/Linear Search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 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 n,x; 16 | cin>>n; 17 | int arr[n]; 18 | for(int i=0;i>arr[i]; 20 | int result=search(arr,n,x); 21 | if(result==-1) 22 | { 23 | cout<<"element not found"; 24 | } 25 | else 26 | cout<<"element found:"<) { 4 | 5 | var n: Int 6 | var p = 1 7 | var i = 2 8 | var sc = Scanner(System.`in`) 9 | 10 | print("Enter a Number :") 11 | n = sc.nextInt() 12 | 13 | while (i < n) { 14 | if (n % i == 0) { 15 | p = 0 16 | break 17 | } 18 | i++ 19 | } 20 | 21 | if (p == 1) { 22 | println("Number is prime :$n") 23 | } else { 24 | println("The number is not prime :$n") 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /String Manipulation/pallindrome.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int main() 5 | { 6 | char str1[20], str2[20]; 7 | int i, j, len = 0, flag = 0; 8 | cout << "Enter the string : "; 9 | cin.getline(str1,20); 10 | len = strlen(str1) - 1; 11 | for (i = len, j = 0; i >= 0 ; i--, j++) 12 | str2[j] = str1[i]; 13 | if (strcmp(str1, str2)) 14 | flag = 1; 15 | if (flag == 1) 16 | cout << str1 << " is not a palindrome"; 17 | else 18 | cout << str1 << " is a palindrome"; 19 | return 0; 20 | } -------------------------------------------------------------------------------- /Search Algorithms/Python/binary_search.py: -------------------------------------------------------------------------------- 1 | # Binary Search in python 2 | def binarySearch(arr, l, r ,value): 3 | while l <= r: 4 | mid = (l + r) / 2 5 | 6 | if value == arr[mid]: 7 | return mid 8 | 9 | elif arr[mid] > value: 10 | r = mid - 1 11 | 12 | else: 13 | l = mid + 1 14 | 15 | return -1 16 | 17 | arr = [5,10,12,14,17,18,19] 18 | length = len(arr) 19 | value = 17 20 | index = binarySearch(arr, 0, length - 1, value) 21 | if index == -1: 22 | print("Not in array") 23 | else: 24 | print("Found at position %d" % index) 25 | -------------------------------------------------------------------------------- /String Manipulation/cifracesar.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(){ 5 | 6 | int mist, repeat, num, i = 1, j; 7 | char letter[50]; 8 | 9 | printf("Type one number and one phrase"); 10 | scanf("%d", &mist); 11 | 12 | while(i <= mist){ 13 | scanf("%s", letter); 14 | scanf("%d", &num); 15 | 16 | for(j = 0; j < strlen(letter); j++){ 17 | if(letter[j] < 'A' + num){ 18 | letter[j] = 'Z' - num + (letter[j] - 'A') + 1; 19 | }else{ 20 | letter[j] -= num; 21 | } 22 | } 23 | 24 | i++; 25 | printf("%s\n", letter); 26 | } 27 | 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /Mathematical Algorithms/GcdOfArray.py: -------------------------------------------------------------------------------- 1 | # GCD of more than two (or array) numbers 2 | 3 | # Function implements the Euclidian algorithm to find H.C.F. of two number 4 | def find_gcd(x, y): 5 | while(y): 6 | x, y = y, x % y 7 | return x 8 | 9 | # Sample Case 10 | l = [2, 4, 6, 8, 16] 11 | 12 | # initialisation of gcd of first 2 numbers 13 | num1 = l[0] 14 | num2 = l[1] 15 | gcd = find_gcd(num1, num2) 16 | 17 | # building over the initially calculated gcd iteratively 18 | for i in range(2, len(l)): 19 | gcd = find_gcd(gcd, l[i]) 20 | 21 | # final output 22 | print(gcd) -------------------------------------------------------------------------------- /Levenshtein/levenshtein_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | func TestMin(t *testing.T) { 10 | assert.Equal(t, 1, min(1, 2, 3)) 11 | } 12 | 13 | func TestLevenshtein(t *testing.T) { 14 | assert.Equal(t, 1, Levenshtein("", "a")) 15 | assert.Equal(t, 1, Levenshtein("a", "")) 16 | assert.Equal(t, 2, Levenshtein("", "ab")) 17 | assert.Equal(t, 2, Levenshtein("ab", "")) 18 | 19 | assert.Equal(t, 1, Levenshtein("a", "b")) 20 | assert.Equal(t, 1, Levenshtein("ab", "b")) 21 | assert.Equal(t, 1, Levenshtein("a", "ab")) 22 | assert.Equal(t, 3, Levenshtein("kitten", "sitting")) 23 | } 24 | -------------------------------------------------------------------------------- /Sorting Algorithms/Python/quick_sort.py: -------------------------------------------------------------------------------- 1 | def quick_sort(a): #a is a list of numbers 2 | if(len(a)<=1): 3 | return(a) 4 | mid=a[len(a)//2] 5 | left=[x for x in a if xmid] 8 | return(quick_sort(left)+middle+quick_sort(right)) 9 | 10 | 11 | if(__name__=='__main__'): 12 | arr=[] 13 | n=input('Enter the number of elements') 14 | print("Enter the elements") 15 | for i in range(int(n)): 16 | arr.append(int(input())) 17 | print("Before sorting") 18 | print(arr) 19 | arr=quick_sort(arr) 20 | print("After sorting") 21 | print(arr) 22 | -------------------------------------------------------------------------------- /Sorting Algorithms/Swift/bubbleSort.swift: -------------------------------------------------------------------------------- 1 | func swap(Arr: inout [Int], x: Int, y: Int) { 2 | let temp = Arr[x] 3 | Arr[x] = Arr[y] 4 | Arr[y] = temp 5 | } 6 | 7 | func bubbleSort(Arr: inout [Int]) { 8 | for _ in 0 ..< Arr.count { 9 | for i in 0 ..< Arr.count - 1 { 10 | if Arr[i] > Arr[i+1] { 11 | swap(Arr: &Arr, x: i, y: i+1) 12 | } 13 | } 14 | } 15 | } 16 | 17 | let unsortedIntegers = [5, 8, 3, 4, -1, 3, 8, 32423423] 18 | var sortedIntegers = unsortedIntegers 19 | bubbleSort(Arr: &sortedIntegers) 20 | 21 | print("Unsorted Integers: \(unsortedIntegers)") 22 | print("Sorted Integers: \(sortedIntegers)") 23 | -------------------------------------------------------------------------------- /Dynamic Programming/coin_change.py: -------------------------------------------------------------------------------- 1 | 2 | def coin_change(n, coins): 3 | """Finds minimum change for n""" 4 | 5 | min_coins = [0] * (n+1) 6 | 7 | for i in range(1, n+1): 8 | if i in coins: 9 | min_coins[i] = 1 10 | else: 11 | possible = [] 12 | for c in coins: 13 | if i - c > 0: 14 | possible.append(1 + min_coins[i - c]) 15 | min_coins[i] = min(possible) 16 | 17 | return min_coins[n] 18 | 19 | 20 | if __name__ == "__main__": 21 | n = 35 22 | coins = [1, 5, 10] 23 | 24 | print(f"n={n}, coins={coins}") 25 | print(f"{coin_change(n, coins)} coin(s)") 26 | -------------------------------------------------------------------------------- /Levenshtein/levenshtein.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func min(v1 int, vn ...int) (m int) { 4 | m = v1 5 | for i := 0; i < len(vn); i++ { 6 | if vn[i] < m { 7 | m = vn[i] 8 | } 9 | } 10 | return 11 | } 12 | 13 | // Levenshtein calculates the Levenshtein distance between the two input strings 14 | func Levenshtein(a, b string) int { 15 | if len(a) == 0 { 16 | return len(b) 17 | } 18 | 19 | if len(b) == 0 { 20 | return len(a) 21 | } 22 | 23 | var c = 0 24 | if a[len(a)-1] != b[len(b)-1] { 25 | c = 1 26 | } 27 | 28 | return min( 29 | Levenshtein(a[:len(a)-1], b)+1, 30 | Levenshtein(a, b[:len(b)-1])+1, 31 | Levenshtein(a[:len(a)-1], b[:len(b)-1])+c, 32 | ) 33 | } 34 | -------------------------------------------------------------------------------- /Sorting Algorithms/C-CPP/insertion_sort.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void insertion_sort(int a[], int n){ 5 | int i, j, key; 6 | for (j = 1;j < n; j++) 7 | { 8 | key = a[j]; 9 | i = j - 1; 10 | while (i >= 0 && a[i] > key){ //for decreasing order, use a[i]key. 11 | a[i+1] = a[i]; 12 | i--; 13 | } 14 | a[i+1] = key; 15 | } 16 | } 17 | 18 | int main(){ 19 | 20 | int a[] ={5, 3, 7, 2, 1}; 21 | int n = sizeof(a)/sizeof(a[0]); 22 | 23 | insertion_sort(a, n); 24 | 25 | for(int i = 0; i < n; i++){ 26 | printf("%d ", a[i]); 27 | } 28 | printf("\n"); 29 | return 0; 30 | } 31 | //Time complexity: O(n^2) 32 | -------------------------------------------------------------------------------- /String Manipulation/php/palindrome.php: -------------------------------------------------------------------------------- 1 | 30 | -------------------------------------------------------------------------------- /Search Algorithms/Python/breath-first-search.py: -------------------------------------------------------------------------------- 1 | # Author:- Vinod Patidar 2 | # GitHub:- vinodpatidar123 3 | 4 | from collections import deque 5 | 6 | def bfs(tree,root): 7 | visited = [] 8 | connected = [] 9 | # visited.append(root) 10 | connected.append(root) 11 | while connected: 12 | node = connected.pop(0) 13 | if node <= len(tree.keys()): 14 | for nextnode in tree[node]: 15 | connected.append(nextnode) 16 | visited.append(node) 17 | else: 18 | visited.append(node) 19 | print("Visited : ",visited) 20 | print("Connected :",connected) 21 | tree = {1:[2,3,4],2:[5,6],3:[7,8],4:[9]} 22 | output = bfs(tree,1) -------------------------------------------------------------------------------- /Sorting Algorithms/php/Quick_Sort.php: -------------------------------------------------------------------------------- 1 | $pivot) 17 | { 18 | $gt[] = $val; 19 | } 20 | } 21 | return array_merge(quick_sort($loe),array($pivot_key=>$pivot),quick_sort($gt)); 22 | } 23 | 24 | $my_array = array(3, 0, 2, 5, -1, 4, 1); 25 | echo 'Original Array : '.implode(',',$my_array).'\n'; 26 | $my_array = quick_sort($my_array); 27 | echo 'Sorted Array : '.implode(',',$my_array); 28 | ?> -------------------------------------------------------------------------------- /Greedy Algorithms/Kadane's-Algorithm.cpp: -------------------------------------------------------------------------------- 1 | // Kadane's Algorithm to find largest sum contigous subarray 2 | #include 3 | using namespace std; 4 | 5 | int kadane(int arr[], int n){ 6 | int maxSoFar = INT_MIN; 7 | int maxEndingHere = 0; 8 | for(int i = 0; i < n; i++){ 9 | maxEndingHere = maxEndingHere + arr[i]; 10 | if(maxSoFar < maxEndingHere) 11 | maxSoFar = maxEndingHere; 12 | if(maxEndingHere < 0) 13 | maxEndingHere = 0; 14 | } 15 | return maxSoFar; 16 | } 17 | 18 | int main(){ 19 | int n = 10; 20 | int arr[] ={5, -9, 3, -4, 1, 4, 4, -10, 12, 13}; 21 | int sum = kadane(arr, n); 22 | cout<<"Largest Sum = "<0): 7 | total *= x 8 | x -= 1 9 | return(total) 10 | 11 | def wilson(x): 12 | if(factorial(x-1)%x==(x-1) and x!=1): 13 | return(1) 14 | else: 15 | return(0) 16 | 17 | def main(): 18 | a = input("Enter the range in which prime numbers are to be printed. \nEnter a,b for the range [a,b], where a and b are two integers. \n") 19 | b = a.split(",") 20 | c = int(b[0]) 21 | d = int(b[1]) 22 | print("\nThe prime numbers in the inclusive range [{0},{1}] are as follows.".format(c,d)) 23 | for i in range(c,d+1): 24 | if(wilson(i)==1): 25 | print(i) 26 | 27 | main() -------------------------------------------------------------------------------- /Sorting Algorithms/C-CPP/quick_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void swap(int *a,int *b) 4 | { 5 | int p=*a; 6 | *a=*b; 7 | *b=p; 8 | } 9 | int partition(int h,int l,int s[]) 10 | { 11 | int pivot=s[h]; 12 | int i=l-1; 13 | for(int j=l;j<=h-1;j++) 14 | { 15 | if (s[j]<=pivot) 16 | { 17 | /* code */ 18 | i++; 19 | swap(&s[i],&s[j]); 20 | } 21 | } 22 | swap(&s[i+1],&s[h]); 23 | return (i+1); 24 | } 25 | void quicksort(int l,int h,int k[]) 26 | { 27 | if(l 2 | 3 | void shellsort(int size, int *arr) { 4 | // start with a big gap and reduce it 5 | for (int gap = size/2; gap > 0; gap = gap/2) { 6 | for (int i = gap; i < size; i = i+1) { 7 | int temp = arr[i]; 8 | 9 | int j; 10 | // shifting elements until the location for arr[i] is found 11 | for (j = i; j >= gap && arr[j-gap] > temp; j = j-gap) { 12 | arr[j] = arr[j-gap]; 13 | } 14 | arr[j] = temp; 15 | } 16 | } 17 | } 18 | 19 | int main() { 20 | int arr_size = 6; 21 | int arr[6] = {10, 9, 8, 7, 6, 5 }; 22 | shellsort(arr_size, arr); 23 | 24 | for (int i = 0; i < arr_size; i++) { 25 | printf("%d ", arr[i]); 26 | } 27 | printf("\n"); 28 | 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /Sorting Algorithms/Python/topological_sort_in_python.py: -------------------------------------------------------------------------------- 1 | # topological_sort_in_python 2 | 3 | def iterative_dfs_improved(graph, start): 4 | seen = set() # efficient set to look up nodes in 5 | path = [] # there was no good reason for this to be an argument in your code 6 | q = [start] 7 | while q: 8 | v = q.pop() # no reason not to pop from the end, where it's fast 9 | if v not in seen: 10 | seen.add(v) 11 | path.append(v) 12 | q.extend(graph[v]) # this will add the nodes in a slightly different order 13 | # if you want the same order, use reversed(graph[v]) 14 | 15 | return path 16 | 17 | 18 | # added file topological-sorting, in python 19 | -------------------------------------------------------------------------------- /Search Algorithms/Java/BinarySearch.java: -------------------------------------------------------------------------------- 1 | public class BinarySearch { 2 | public static void main(String args[]) { 3 | int a[] = {1, 5, 3, 4, 2}; 4 | 5 | System.out.println("Searching for 3:"); 6 | int i = binary_search(a, 3); 7 | System.out.println(i < 0 ? "Not found" : "Found at index" + i); 8 | 9 | System.out.println("Searching for 99:"); 10 | binary_search(a, 99); 11 | System.out.println(i < 0 ? "Not found" : "Found at index" + i); 12 | } 13 | 14 | static void binary_search(int a[], k) { 15 | int min = 0, max = a.length; 16 | 17 | while (min < max) { 18 | int mid = (min + max) / 2; 19 | 20 | if (a[mid] < k) min = mid + 1; 21 | else if (a[mid] > k) min = mid - 1; 22 | else return mid; 23 | } 24 | return -1; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Dynamic Programming/Golombsequence.cpp: -------------------------------------------------------------------------------- 1 | // C++ Program to find first 2 | // n terms of Golomb sequence. 3 | #include 4 | using namespace std; 5 | 6 | // Return the nth element 7 | // of Golomb sequence 8 | int findGolomb(int n) 9 | { 10 | // base case 11 | if (n == 1) 12 | return 1; 13 | 14 | // Recursive Step 15 | return 1 + findGolomb(n - 16 | findGolomb(findGolomb(n - 1))); 17 | } 18 | 19 | // Print the first n 20 | // term of Golomb Sequence 21 | void printGolomb(int n) 22 | { 23 | // Finding first n 24 | // terms of Golomb Sequence. 25 | for (int i = 1; i <= n; i++) 26 | cout << findGolomb(i) << " "; 27 | } 28 | 29 | // Driver Code 30 | int main() 31 | { 32 | int n = 9; 33 | printGolomb(n); 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /Search Algorithms/C-CPP/LinearSearch.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int search(int arr[], int n, int x) //Function for linear search 4 | { 5 | int i; 6 | for (i = 0; i < n; i++) 7 | if (arr[i] == x) 8 | return i+1; 9 | return -1; 10 | } 11 | int main(void) 12 | { 13 | int n,x,i; 14 | printf("\nEnter the number of elements:- "); 15 | scanf("%d",&n); 16 | int arr[n]; 17 | printf("\nEnter the elements:- "); 18 | for( i=0;i 3 | using namespace std; 4 | 5 | vector sieve(int n) 6 | { 7 | vector prime; 8 | bool isprime[n]; 9 | for(int p = 2; p < n; p++) 10 | isprime[p] = true; 11 | 12 | for (int p = 2; p * p < n; p++) 13 | { 14 | if (isprime[p] == true) 15 | { 16 | for (int i = p*p; i <= n; i += p) 17 | isprime[i] = false; 18 | } 19 | } 20 | for (int p = 2; p <= n; p++) 21 | if (isprime[p] == true){ 22 | prime.push_back(p); 23 | } 24 | return prime; 25 | } 26 | 27 | int main(){ 28 | int n = 100000; 29 | vector prime; 30 | prime = sieve(n); 31 | for(auto p: prime) 32 | cout< 2 | using namespace std; 3 | int binarysearch(int a[],int f,int l,int find) 4 | { 5 | if(l>=f) 6 | { 7 | int mid=f+(l-f)/2; 8 | if(a[mid]==find) 9 | { 10 | return mid; 11 | 12 | } 13 | if(a[mid]>find) 14 | { 15 | return binarysearch(a,f,mid-1,find); 16 | } 17 | return binarysearch(a,mid+1,l,find); 18 | } 19 | return -1; 20 | } 21 | int main() 22 | { 23 | int n; 24 | cin>>n; 25 | int a[n]; 26 | for(int i=0;i>a[i]; 29 | } 30 | int find; 31 | cin>>find; 32 | int f,l; 33 | f=0; 34 | l=n-1; 35 | int result=binarysearch(a,f,l,find); 36 | if(result==-1) 37 | { 38 | cout<<"Not Found"; 39 | } 40 | else 41 | { 42 | cout<<"Found at "< 2 | using namespace std; 3 | 4 | void swap(int *xp, int *yp) 5 | { 6 | int temp = *xp; 7 | *xp = *yp; 8 | *yp = temp; 9 | } 10 | 11 | 12 | void bubbleSort(int arr[], int n) 13 | { 14 | int i, j; 15 | for (i = 0; i < n-1; i++) 16 | 17 | 18 | for (j = 0; j < n-i-1; j++) 19 | if (arr[j] > arr[j+1]) 20 | swap(&arr[j], &arr[j+1]); 21 | } 22 | 23 | 24 | void printArray(int arr[], int size) 25 | { 26 | int i; 27 | for (i = 0; i < size; i++) 28 | cout << arr[i] << " "; 29 | cout << endl; 30 | } 31 | 32 | 33 | int main() 34 | { 35 | int arr[] = {64, 34, 25, 12, 22, 11, 90}; 36 | int n = sizeof(arr)/sizeof(arr[0]); 37 | bubbleSort(arr, n); 38 | cout<<"Sorted array: \n"; 39 | printArray(arr, n); 40 | return 0; 41 | } 42 | 43 | -------------------------------------------------------------------------------- /Sorting Algorithms/GO/bubble_sort.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func bubbleSort(numbers []int) []int { 6 | if numbers != nil && len(numbers) > 0 { 7 | for i := 0; i < len(numbers); i++ { 8 | for j := 0; j < len(numbers); j++ { 9 | if numbers[i] < numbers[j] { 10 | temp := numbers[i] 11 | numbers[i] = numbers[j] 12 | numbers[j] = temp 13 | } 14 | } 15 | } 16 | } else { 17 | fmt.Println("Empty or Null Array") 18 | } 19 | return numbers 20 | } 21 | 22 | // main function 23 | func main() { 24 | 25 | fmt.Println("Bubble Sort \n") 26 | 27 | // creating an integer array with values 28 | numbers := []int{4, 2, 1, 5, 3} 29 | 30 | fmt.Println("Before Sorting:", numbers) 31 | 32 | // calling the bubbleSort function 33 | numbers = bubbleSort(numbers) 34 | 35 | fmt.Println("\nAfter Sorting:", numbers) 36 | } 37 | -------------------------------------------------------------------------------- /Sorting Algorithms/C-CPP/ShellSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void shellSort(int a[],int n) 5 | for (int gap = n / 2; gap > 0; gap /= 2) { 6 | for (int i = gap; i < n; i += 1) { 7 | int temp = a[i]; 8 | int j; 9 | for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) 10 | a[j] = a[j - gap]; 11 | a[j] = temp; 12 | } 13 | } 14 | } 15 | 16 | void display(int a[], int n) 17 | { 18 | for (int i = 0; i < n; i++) 19 | cout << a[i] << " "; 20 | cout << "\n"; 21 | } 22 | 23 | int main(){ 24 | 25 | int a[] = { 92, 50, 28, 43 }; 26 | int n = sizeof(a) / sizeof(arr[0]); 27 | 28 | cout << "Array before sorting: \n"; 29 | display(a, n); 30 | 31 | shellSort(a, n); 32 | 33 | cout << "Array after sorting: \n"; 34 | display(a, n); 35 | 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /Sorting Algorithms/Python/insertion.py: -------------------------------------------------------------------------------- 1 | # Python program for implementation of Insertion Sort 2 | 3 | # Function to do insertion sort 4 | def insertionSort(arr): 5 | 6 | # Traverse through 1 to len(arr) 7 | for i in range(1, len(arr)): 8 | 9 | key = arr[i] 10 | 11 | # Move elements of arr[0..i-1], that are 12 | # greater than key, to one position ahead 13 | # of their current position 14 | j = i-1 15 | while j >=0 and key < arr[j] : 16 | arr[j+1] = arr[j] 17 | j -= 1 18 | arr[j+1] = key 19 | 20 | 21 | # Driver code to test above 22 | arr = [12, 11, 13, 5, 6] 23 | insertionSort(arr) 24 | print ("Sorted array is:") 25 | for i in range(len(arr)): 26 | print ("%d" %arr[i]) 27 | 28 | 29 | ###output 30 | 31 | 5 32 | 6 33 | 11 34 | 12 35 | 13 36 | -------------------------------------------------------------------------------- /Sorting Algorithms/C-CPP/bubble_sort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void bbSort(int arr[], int N) //Function for Bubble Sorting 4 | { 5 | int i, j, aux; 6 | for (i = 1; i < N; i++) 7 | for (j = 0; j < N - 1; j++) { 8 | if (arr[j] > arr[j + 1]) { 9 | aux = arr[j]; 10 | arr[j] = arr[j + 1]; 11 | arr[j + 1] = aux; 12 | } 13 | } 14 | } 15 | 16 | int main() 17 | { 18 | int N, aux; 19 | printf("\nEnter the number of elements= "); 20 | scanf(" %d", &N); 21 | int arr[N]; 22 | printf("\nEnter the elements= "); 23 | for(int i = 0; i < N; i++) 24 | { 25 | scanf(" %d", &aux); 26 | arr[i] = aux; 27 | } 28 | bbSort(arr, N); 29 | printf("\nThe sorted elements= \n"); 30 | for(int i = 0; i < N; i++) 31 | { 32 | printf("\n%d", arr[i]); 33 | } 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /Sorting Algorithms/Python/radix_sort.py: -------------------------------------------------------------------------------- 1 | def radix_sort(array, base=10): 2 | """ 3 | Fuction to sort using radix sort algorithm 4 | . 5 | 6 | :param array: A list of elements to sort. 7 | :param base: Integer number to represent base number 8 | """ 9 | maxLen = len(str(max(array))) 10 | 11 | for i in range(maxLen): 12 | digit_ref = [[] for _ in range(base)] 13 | for num in array: 14 | digit_ref[(num // base ** i) % base].append(num) 15 | array = [] 16 | for section in digit_ref: 17 | array.extend(section) 18 | return array 19 | 20 | 21 | def main(): 22 | array = [6, 5, 4, 3, 2, 1] 23 | print('Sorted element using Radix Sort: {}'.format( 24 | ' '.join(map(str, radix_sort(array))))) 25 | 26 | 27 | if __name__ == '__main__': 28 | main() 29 | -------------------------------------------------------------------------------- /Sorting Algorithms/Python/shell_sort.py: -------------------------------------------------------------------------------- 1 | def shell_sort(arr): 2 | """ 3 | Fuction to sort using Shell Sort 4 | . 5 | :param arr: A list of element to sort 6 | """ 7 | 8 | gap = int((len(arr)/2)) 9 | while gap > 0: 10 | for i in range(gap, len(arr)): 11 | temp = arr[i] 12 | j = i 13 | while j >= gap and arr[j - gap] > temp: 14 | arr[j] = arr[j-gap] 15 | j -= gap 16 | 17 | arr[j] = temp 18 | 19 | gap /= 2 20 | gap = int(gap) 21 | 22 | return arr 23 | 24 | 25 | def main(): 26 | arr = [15, 12, 36, 63, 96] 27 | sorted_arr = shell_sort(arr) 28 | print('Sorted element using Shell Sort: {}'.format( 29 | ' '.join(map(str, shell_sort(arr))))) 30 | 31 | 32 | if __name__ == '__main__': 33 | main() 34 | -------------------------------------------------------------------------------- /Levenshtein/go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= 2 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 3 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 4 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 5 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 6 | github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= 7 | github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= 8 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 9 | gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= 10 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 11 | -------------------------------------------------------------------------------- /Search Algorithms/Java/JumpSearch.java: -------------------------------------------------------------------------------- 1 | public class JumpSearch{ 2 | public static void main(String args[]){ 3 | int arr[] = {3,5,7,2,6,1,8,4,9}; 4 | int x = 8; 5 | 6 | int contain = jumpSearch(x, arr); 7 | System.out.println("Contain in index: "+contain); 8 | } 9 | 10 | public static int jumpSearch(int x, int arr[]){ 11 | int step = (int) Math.floor(Math.sqrt(arr.length)); 12 | 13 | int prev = 0; 14 | while(arr[Math.min(step, arr.length)-1] < x){ 15 | prev = step; 16 | step += (int) Math.floor(Math.sqrt(arr.length)); 17 | 18 | if(prev >= arr.length) return -1; 19 | } 20 | 21 | while(arr[prev] < x){ 22 | prev++; 23 | if(prev == Math.min(step, arr.length)) return -1; 24 | } 25 | 26 | if(arr[prev] == x) return prev; 27 | return -1; 28 | } 29 | } -------------------------------------------------------------------------------- /Sorting Algorithms/php/insertionsort.php: -------------------------------------------------------------------------------- 1 | = 0 && $arr[$j] > $key) 17 | { 18 | $arr[$j + 1] = $arr[$j]; 19 | $j = $j - 1; 20 | } 21 | 22 | $arr[$j + 1] = $key; 23 | } 24 | } 25 | 26 | // A utility function to 27 | // print an array of size n 28 | function printArray(&$arr, $n) 29 | { 30 | for ($i = 0; $i < $n; $i++) 31 | echo $arr[$i]." "; 32 | echo "\n"; 33 | } 34 | 35 | // Driver Code 36 | $arr = array(12, 11, 13, 5, 6); 37 | $n = sizeof($arr); 38 | insertionSort($arr, $n); 39 | printArray($arr, $n); 40 | 41 | 42 | ?> 43 | -------------------------------------------------------------------------------- /Search Algorithms/C-CPP/Binary_search.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int arr[50],i,n,x,flag=0,first,last,mid; 6 | 7 | printf("Enter size of array:"); 8 | scanf("%d",&n); 9 | printf("\nEnter array element(ascending order)\n"); 10 | 11 | for(i=0;iarr[mid]) 30 | first=mid+1; 31 | else 32 | last=mid-1; 33 | } 34 | 35 | if(flag==1) 36 | printf("\nElement found at position %d",mid+1); 37 | else 38 | printf("\nElement not found"); 39 | 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /Sorting Algorithms/C-CPP/heap_sort.cpp: -------------------------------------------------------------------------------- 1 | void orderHeap(int *vet, int i, int f) { 2 | int aux = vet[i]; 3 | int j = i * 2 + 1; 4 | while(j <= f) { 5 | if(j < f) { 6 | if(vet[j] < vet[j + 1]) { 7 | ++j; 8 | } 9 | } 10 | if(aux < vet[j] { 11 | vet[i] = vet[j]; 12 | i = j; 13 | j = 2* i + 1; 14 | } else { 15 | j = f + 1; 16 | } 17 | } 18 | vet[i] = aux; 19 | } 20 | 21 | void heapSort(int *vet, int N) { 22 | int i, aux; 23 | for(i = (N - 1) / 2; i >= 0; i--) { 24 | orderHeap(vet, i, N - 1); 25 | } 26 | for(i = N - 1; i >= 1; i--) { 27 | aux = vet[0]; 28 | vet[0] = vet[i]; 29 | vet[i] = aux; 30 | orderHeap(vet, 0, i - 1); 31 | } 32 | } 33 | 34 | int main(int argc, char** argv) { 35 | int vet[7] = {40, 90, 20, 10, 50, 70, 80}; 36 | heapSort(vet 7); 37 | for( int i = 0; i < 7; i++) { 38 | count< 2 | #include 3 | 4 | int main(){ 5 | 6 | int i, j, soma = 0, num; 7 | char led[1000]; 8 | 9 | printf("Number of LEDs\n"); 10 | scanf("%d", &num); 11 | 12 | printf("Leds:\n"); 13 | for(i = 0; i < num; i++){ 14 | scanf("%s", led); 15 | for(j = 0; j < strlen(led); j++){ 16 | if(led[j] == '1'){ 17 | soma += 2; 18 | }else if(led[j] == '2'){ 19 | soma += 5; 20 | }else if(led[j] == '3'){ 21 | soma += 5; 22 | }else if(led[j] == '4'){ 23 | soma += 4; 24 | }else if(led[j] == '5'){ 25 | soma += 5; 26 | }else if(led[j] == '6'){ 27 | soma += 6; 28 | }else if(led[j] == '7'){ 29 | soma += 3; 30 | }else if(led[j] == '8'){ 31 | soma += 7; 32 | }else if(led[j] == '9'){ 33 | soma += 6; 34 | }else if(led[j] == '0'){ 35 | soma += 6; 36 | } 37 | } 38 | 39 | printf("%d leds\n", soma); 40 | soma = 0; 41 | } 42 | 43 | return 0; 44 | } -------------------------------------------------------------------------------- /Search Algorithms/C-CPP/BinarySearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void BinarySearch(int arr[],int n,int item) //Function for Binary Search 4 | { 5 | int beg=0,mid,end,count=0; 6 | end=n-1; 7 | while(beg!=end) 8 | { 9 | mid=(beg+end)/2; 10 | if(arr[mid]==item) 11 | { 12 | cout<<"\nItem found. Index is= "<item) 21 | { 22 | end=mid-1; 23 | } 24 | } 25 | if(count==0) 26 | { 27 | cout<<"\nItem not found."; 28 | } 29 | } 30 | int main() 31 | { 32 | int n,item; 33 | cout<<"\nEnter the number of elements you want you enter= "; 34 | cin>>n; 35 | int a[n]; 36 | cout<<"\nEnter the array elements(in ascending order)="; 37 | for(int i=0;i>a[i]; 40 | } 41 | cout<<"\nEnter the element to be searched= "; 42 | cin>>item; 43 | BinarySearch(a,n,item); 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /String Manipulation/Python/occurence.py: -------------------------------------------------------------------------------- 1 | # Count the number of occurences in a string given by the user after a prompt. 2 | # Attain the user input and store into a global variable 3 | print("Enter the text you would like to count: ") 4 | 5 | # initialize the variable input to save the text. 6 | words = input() 7 | 8 | # this will record the input for the newly created variable "words" 9 | print(words) 10 | 11 | # Create a dictionary to store the string 12 | collection = {} 13 | 14 | # Use a for loop for the characters input by the user, including whitespace (this is case sensitive) 15 | for i in words: 16 | if i in collection: 17 | collection[i] +=1 18 | else: 19 | collection[i] =1 20 | 21 | # print results, use a newline break to keep the dictionary on a seperate line of the message. 22 | print("Count of all the characters in your text were the following: \n " 23 | + str(collection)) -------------------------------------------------------------------------------- /Sorting Algorithms/C-CPP/selection_sort.c: -------------------------------------------------------------------------------- 1 | /* 2 | // Sample code to perform I/O: 3 | #include 4 | 5 | int main(){ 6 | int num; 7 | scanf("%d", &num); // Reading input from STDIN 8 | printf("Input number is %d.\n", num); // Writing output to STDOUT 9 | } 10 | 11 | // Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail 12 | */ 13 | 14 | // Write your code here 15 | #include 16 | int main(){ 17 | int n,x,i,min,j,tv; 18 | char temp; 19 | scanf("%d %d",&n,&x); 20 | int a[n]; 21 | for(i=0;ia[i]){ 29 | min=i; 30 | } 31 | } 32 | tv=a[j]; 33 | a[j]=a[min]; 34 | a[min]=tv; 35 | j++; 36 | } 37 | for(i=0;i 2 | using namespace std; 3 | 4 | void Count_Sort(int a[],int n,int k){ 5 | int freq[k+1]={0}; 6 | 7 | for(int i=0;i>n; 26 | int a[n],maxi=-1; 27 | cout<<"Enter space separated +ev integers here: "; 28 | for(int i=0;i>a[i]; 30 | if(maxi> List.binarySearch(element: T?, fromIndex: Int = 0, toIndex: Int = size): Int { 2 | 3 | var begin = fromIndex 4 | var end = toIndex - 1 5 | 6 | while (begin <= end) { 7 | val mid = (begin + end) / 2 8 | val midVal = get(mid) 9 | val compare = compareValues(midVal, element) 10 | 11 | when { 12 | compare < 0 -> begin = mid + 1 13 | compare > 0 -> end = mid - 1 14 | else -> return mid 15 | } 16 | } 17 | return -1; 18 | } 19 | 20 | 21 | 22 | fun main(args: Array) { 23 | val arr = intArrayOf(3, 2, 5, 9, 1).sorted() 24 | val testOne = 2 25 | val testTwo = 9 26 | 27 | val a = arr.binarySearch(testOne) 28 | println(if (a < 0) "$testOne not found" else "$testOne found at index $a") 29 | 30 | val b = arr.binarySearch(testTwo) 31 | println(if (b < 0) "$testTwo not found" else "$testTwo found at index $b") 32 | } -------------------------------------------------------------------------------- /Search Algorithms/C-CPP/jumpSearch.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to implement Jump Search 2 | 3 | #include 4 | using namespace std; 5 | 6 | int jumpSearch(int arr[], int x, int n) 7 | { 8 | int step = sqrt(n); 9 | int prev = 0; 10 | while (arr[min(step, n)-1] < x) 11 | { 12 | prev = step; 13 | step += sqrt(n); 14 | if (prev >= n) 15 | return -1; 16 | } 17 | while (arr[prev] < x) 18 | { 19 | prev++; 20 | if (prev == min(step, n)) 21 | return -1; 22 | } 23 | if (arr[prev] == x) 24 | return prev; 25 | 26 | return -1; 27 | } 28 | 29 | // Main function 30 | int main() 31 | { 32 | int n; 33 | cout << "Enter the number of elements :" << endl; 34 | cin >> n; 35 | int arr[n]; 36 | cout << "Enter elements :" << endl; 37 | for(int i=0; i> arr[i]; 39 | int key = 0; 40 | cout << "Enter Key to be found : " << endl; 41 | cin >> key; 42 | int index = jumpSearch(arr, key, n); 43 | cout << "\nNumber " << key << " is at index " << index; 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /Search Algorithms/Python/ExponentialSearch.py: -------------------------------------------------------------------------------- 1 | 2 | def binarySearch( arr, l, r, x): 3 | if r >= l: 4 | mid = l + ( r-l ) / 2 5 | 6 | # If the element is present at 7 | # the middle itself 8 | if arr[mid] == x: 9 | return mid 10 | 11 | 12 | if arr[mid] > x: 13 | return binarySearch(arr, l, 14 | mid - 1, x) 15 | 16 | 17 | return binarySearch(arr, mid + 1, r, x) 18 | 19 | # We reach here if the element is not present 20 | return -1 21 | 22 | 23 | def exponentialSearch(arr, n, x): 24 | 25 | if arr[0] == x: 26 | return 0 27 | 28 | 29 | i = 1 30 | while i < n and arr[i] <= x: 31 | i = i * 2 32 | 33 | # Call binary search for the found range 34 | return binarySearch( arr, i / 2, 35 | min(i, n), x) 36 | 37 | 38 | # Driver Code 39 | arr = [2, 3, 4, 10, 40] 40 | n = len(arr) 41 | x = 10 42 | result = exponentialSearch(arr, n, x) 43 | if result == -1: 44 | print "Element not found in thye array" 45 | else: 46 | print "Element is present at index %d" %(result) 47 | 48 | -------------------------------------------------------------------------------- /String Matching/Rabin-Karp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | string s,n; 6 | cin>>s>>n; 7 | int q=101; 8 | int d=256; 9 | int p=0,t=0,count=0; 10 | int h=1; 11 | int z=s.length()-n.length(); 12 | cout< 38 | -------------------------------------------------------------------------------- /String Manipulation/split.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | /** Gets a string and separe through a separator _sep and returns into a 7 | * std::vector */ 8 | std::vector split(std::string _str, char _sep) { 9 | std::vector v; 10 | int begin = 0; 11 | for (int i=0 ; i < _str.size() ; i++){ 12 | if (_str[i] == _sep) { 13 | v.push_back( _str.substr(begin, i-begin) ); 14 | begin = i+1; 15 | } 16 | } 17 | v.push_back(_str.substr(begin, _str.size())); 18 | return v; 19 | }; 20 | 21 | 22 | 23 | int main() { 24 | 25 | string str1 = "name.midname.lastname"; 26 | vector vecStr1 = split(str1, '.'); 27 | for (string& s : vecStr1) { 28 | cout << s << endl; 29 | } 30 | 31 | cout << endl; 32 | string str2 = "myname@emailservice.com"; 33 | 34 | vector vecStr2 = split(str2, '@'); 35 | for (string& s : vecStr2) { 36 | cout << s << endl; 37 | } 38 | 39 | return 0; 40 | } -------------------------------------------------------------------------------- /Sorting Algorithms/C-CPP/selection_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | //The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) 3 | // from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array. 4 | 5 | //1) The subarray which is already sorted. 6 | //2) Remaining subarray which is unsorted. 7 | 8 | //In every iteration of selection sort, 9 | //the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray. 10 | using namespace std; 11 | 12 | void SelectionSort(int a[],int n){ 13 | int x=0; 14 | for(int i=0;ia[j]){ 17 | x=j; 18 | } 19 | } 20 | int temp=a[i]; 21 | a[i]=a[x]; 22 | a[x]=temp; 23 | } 24 | } 25 | 26 | int main(){ 27 | int a[]={64,22,25,12,11}; 28 | 29 | SelectionSort(a,5); 30 | 31 | for(int i=0;i<5;i++){ 32 | cout<= arr[lo] and x <= arr[hi]: 9 | if lo == hi: 10 | if arr[lo] == x: 11 | return lo; 12 | return -1; 13 | 14 | 15 | pos = lo + int(((float(hi - lo) / 16 | ( arr[hi] - arr[lo])) * ( x - arr[lo]))) 17 | 18 | # Condition of target found 19 | if arr[pos] == x: 20 | return pos 21 | 22 | # If x is larger, x is in upper part 23 | if arr[pos] < x: 24 | lo = pos + 1; 25 | 26 | # If x is smaller, x is in lower part 27 | else: 28 | hi = pos - 1; 29 | 30 | return -1 31 | 32 | # Driver Code 33 | # Array of items oin which search will be conducted 34 | arr = [10, 12, 13, 16, 18, 19, 20, 21, \ 35 | 22, 23, 24, 33, 35, 42, 47] 36 | n = len(arr) 37 | 38 | x = 18 # Element to be searched 39 | index = interpolationSearch(arr, n, x) 40 | 41 | if index != -1: 42 | print "Element found at index",index 43 | else: 44 | print "Element not found" 45 | 46 | -------------------------------------------------------------------------------- /Binary Tree/bst.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class Node 3 | { 4 | int data; 5 | Node left; 6 | Node right; 7 | Node(int data) 8 | { 9 | this.data=data; 10 | this.left=null; 11 | this.right=null; 12 | } 13 | } 14 | class bst 15 | { 16 | public static void main(String args[]) 17 | { 18 | Scanner in=new Scanner(System.in); 19 | int i,j,n; 20 | n=in.nextInt(); 21 | Node node=null; 22 | for(i=0;i=x) 36 | { 37 | if(node.left!=null) 38 | insert(node.left,x); 39 | else 40 | node.left=new Node(x); 41 | } 42 | else 43 | { 44 | if(node.right!=null) 45 | insert(node.right,x); 46 | else 47 | node.right=new Node(x); 48 | } 49 | } 50 | static void inorder(Node node) 51 | { 52 | if(node==null) 53 | return; 54 | inorder(node.left); 55 | System.out.print(node.data+" "); 56 | inorder(node.right); 57 | } 58 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Meet Ranoliya 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Search Algorithms/C-CPP/LinearSearchSentinelValue.cpp: -------------------------------------------------------------------------------- 1 | //Linear research with a flag value that interrupts research until the value is found. 2 | #include 3 | #define ELEMENTS 10 4 | using namespace std; 5 | 6 | bool research(int numSearch, int arr[]); 7 | 8 | int main(){ 9 | 10 | int array[ELEMENTS] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 11 | int i; 12 | int search; 13 | bool found; 14 | 15 | cout << "Array: "; 16 | for(i=0; i> search; 21 | 22 | found = research(search, array); 23 | 24 | if(found) 25 | cout << "The element is in the array." << endl; 26 | else 27 | cout << "Element not in the array." << endl; 28 | 29 | return 0; 30 | } 31 | 32 | bool research(int numSearch, int arr[]){ 33 | 34 | bool found = false; 35 | int i; 36 | 37 | for (i=0; found == false && i 3 | #include 4 | #include 5 | #define ELEMENTS 10 6 | 7 | bool research(int numSearch, int arr[]); 8 | 9 | int main(){ 10 | 11 | int array[ELEMENTS] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 12 | int i; 13 | int search; 14 | bool found; 15 | 16 | printf("Array: "); 17 | for(i=0; i 2 | void quicksort(int number[25],int first,int last){ 3 | int i, j, pivot, temp; 4 | 5 | if(firstnumber[pivot]) 14 | j--; 15 | if(i 2 | using namespace std; 3 | struct node { 4 | int data; 5 | struct node *left; 6 | struct node *right; 7 | }; 8 | struct node *createNode(int val) { 9 | struct node *temp = (struct node *)malloc(sizeof(struct node)); 10 | temp->data = val; 11 | temp->left = temp->right = NULL; 12 | return temp; 13 | } 14 | void inorder(struct node *root) { 15 | if (root != NULL) { 16 | inorder(root->left); 17 | cout<data<<" "; 18 | inorder(root->right); 19 | } 20 | } 21 | struct node* insertNode(struct node* node, int val) { 22 | if (node == NULL) return createNode(val); 23 | if (val < node->data) 24 | node->left = insertNode(node->left, val); 25 | else if (val > node->data) 26 | node->right = insertNode(node->right, val); 27 | return node; 28 | } 29 | int main() { 30 | struct node *root = NULL; 31 | root = insertNode(root, 4); 32 | insertNode(root, 5); 33 | insertNode(root, 2); 34 | insertNode(root, 9); 35 | insertNode(root, 1); 36 | insertNode(root, 3); 37 | cout<<"In-Order traversal of the Binary Search Tree is: "; 38 | inorder(root); 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /Search Algorithms/CSharp/linearSearch.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Rextester 4 | { 5 | public class Program 6 | { 7 | public static void Main(string[] args) 8 | { 9 | 10 | Console.WriteLine("Enter size of array:"); 11 | String sizeString = Console.ReadLine(); 12 | int size = int.Parse(sizeString); 13 | int[] array = new int[size]; 14 | 15 | Console.WriteLine("Enter elements"); 16 | for(int i = 0; i < size; i++){ 17 | String elementString = Console.ReadLine(); 18 | int element = int.Parse(elementString); 19 | array[i] = element; 20 | } 21 | 22 | Console.WriteLine("Enter item to search:"); 23 | String itemString = Console.ReadLine(); 24 | int item = int.Parse(itemString); 25 | 26 | search(array, item); 27 | 28 | } 29 | 30 | public static void search(int[] array, int element){ 31 | int i = 0; 32 | while((i < array.Length)&&(array[i] != element)){ 33 | i+=1; 34 | } 35 | if(i > array.Length-1){ 36 | Console.WriteLine("Element not found"); 37 | } 38 | else{ 39 | Console.WriteLine("Element found. Index : [ " + i + " ]"); 40 | } 41 | 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /Mathematical Algorithms/EuclideanGCD/euclidean_gcd.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | /* 4 | Calculates GCD of two numbers a & b using the division-based Euclidean Algorithm 5 | */ 6 | int gcd_div(int a , int b) { 7 | while (b != 0) { 8 | int temp = b; 9 | b = a % b; 10 | a = temp; 11 | } 12 | return a; 13 | } 14 | 15 | /* 16 | Calculates GCD of two numbers a & b using the recursive-based Euclidean Algorithm 17 | */ 18 | int gcd_rec(int a, int b) { 19 | if (a == 0) 20 | return b; 21 | return gcd_rec(b % a, a); 22 | } 23 | 24 | /* 25 | Calculates GCD of two numbers a & b using the Recursive-based Extended Euclidean Algorithm 26 | */ 27 | int gcd_extended(int a, int b, int *x, int *y) { 28 | if (a == 0) { 29 | *x = 0; 30 | *y = 1; 31 | return b; 32 | } 33 | int x1, y1; 34 | int result = gcd_extended(b % a, a, &x1, &y1); 35 | *x = y1 - (b / a) * x1; 36 | *y = x1; 37 | return result; 38 | } 39 | 40 | // Main Method 41 | int main() { 42 | int a = 20, b = 30, x, y; 43 | printf("Division: GCD(%d, %d) = %d\n", a, b, gcd_div(a, b)); 44 | 45 | printf("Recursive: GCD(%d, %d) = %d\n", a, b, gcd_rec(a, b)); 46 | 47 | int gcd_ext = gcd_extended(a, b, &x, &y); 48 | printf("Extended: GCD(%d, %d) = %d\n", a, b, gcd_ext); 49 | } 50 | -------------------------------------------------------------------------------- /Mathematical Algorithms/LcmOfArray.py: -------------------------------------------------------------------------------- 1 | # find LCM of n elements 2 | 3 | # Base Function to find LCM of given 2 numbers 4 | def find_lcm(num1, num2): 5 | 6 | # num - numerator and den - denominator 7 | 8 | if(num1>num2): 9 | num = num1 10 | den = num2 11 | else: 12 | num = num2 13 | den = num1 14 | 15 | # rem - remainder 16 | rem = num % den 17 | 18 | # Iteratively re-evaluation of arguments num, den, rem till rem == 0 19 | while(rem != 0): 20 | num = den 21 | den = rem 22 | rem = num % den 23 | 24 | # when rem == 0, resultant den => GCD 25 | gcd = den 26 | 27 | # Property of GCD*LCM = num1*num2 28 | lcm = int(int(num1 * num2)/int(gcd)) 29 | 30 | return lcm 31 | 32 | # sample Case 33 | l = [2, 7, 3, 9, 4] 34 | 35 | # initalisation of LCM of first 2 elements (Driver Code) 36 | num1 = l[0] 37 | num2 = l[1] 38 | 39 | lcm = find_lcm(num1, num2) 40 | 41 | # Iteratively Builting over the previously calculated LCM of first 2 elements of array 42 | for i in range(2, len(l)): 43 | lcm = find_lcm(lcm, l[i]) 44 | 45 | # Final LCM of the Array 46 | print(lcm) -------------------------------------------------------------------------------- /Search Algorithms/Python/jump_search.py: -------------------------------------------------------------------------------- 1 | # Python3 code to implement Jump Search 2 | import math 3 | 4 | def jumpSearch( arr , x , n ): 5 | 6 | # Finding block size to be jumped 7 | step = math.sqrt(n) 8 | 9 | # Finding the block where element is 10 | # present (if it is present) 11 | prev = 0 12 | while arr[int(min(step, n)-1)] < x: 13 | prev = step 14 | step += math.sqrt(n) 15 | if prev >= n: 16 | return -1 17 | 18 | # Doing a linear search for x in 19 | # block beginning with prev. 20 | while arr[int(prev)] < x: 21 | prev += 1 22 | 23 | # If we reached next block or end 24 | # of array, element is not present. 25 | if prev == min(step, n): 26 | return -1 27 | 28 | # If element is found 29 | if arr[int(prev)] == x: 30 | return prev 31 | 32 | return -1 33 | 34 | arr = [] 35 | inp = input("Enter the array: ") 36 | inp = list(inp.split()) 37 | arr = list(map(int, inp)) 38 | x = int(input("Enter the element you want to search: ")) 39 | n = len(arr) 40 | 41 | # Find the index of 'x' using Jump Search 42 | index = jumpSearch(arr, x, n) 43 | 44 | # Print the index where 'x' is located 45 | print("Number" , x, "is at index" ,"%.0f"%index) 46 | 47 | -------------------------------------------------------------------------------- /Sorting Algorithms/Java/InsertionSort.java: -------------------------------------------------------------------------------- 1 | public class InsertionSort { 2 | public static void main(String[] args) { 3 | //My array of values 4 | int[] arr = new int[]{9, 8, 13, 2, 5, 22, 1315, 13, 4}; 5 | System.out.println("Array before sorting: "); 6 | printArray(arr); 7 | 8 | insertionSortMethod(arr); 9 | System.out.println("Array after sorting: "); 10 | printArray(arr); 11 | } 12 | 13 | public static void printArray(int[] arr) { 14 | for (int i = 0; i < arr.length; i++) { 15 | System.out.print("Index " + i + " ="); 16 | System.out.print(arr[i] + "\t"); 17 | } 18 | System.out.println("\n"); 19 | 20 | } 21 | 22 | 23 | public static void insertionSortMethod(int[] array) { 24 | for (int i = 1; i < array.length; i++) { 25 | int current = array[i]; 26 | int j = i - 1; 27 | while(j >= 0 && current < array[j]) { 28 | array[j+1] = array[j]; 29 | j--; 30 | } 31 | // at this point we've exited, so j is either -1 32 | // or it's at the first element where current >= a[j] 33 | array[j+1] = current; 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /Search Algorithms/Kotlin/InterpolationSearch.kt: -------------------------------------------------------------------------------- 1 | fun interpolationSearch(arr: IntArray, item: Int): Int { 2 | var hi = arr.size - 1 3 | var lo = 0 4 | while (item >= arr[lo] && item <= arr[hi] && lo <= hi) { 5 | val probe = 6 | lo + (hi - lo) * (item - arr[lo]) / (arr[hi] - arr[lo]) 7 | if (hi == lo) { 8 | return if (arr[lo] == item) { 9 | lo 10 | } else { 11 | -1 12 | } 13 | } 14 | if (arr[probe] == item) { 15 | return probe 16 | } 17 | if (arr[probe] < item) { 18 | lo = probe + 1 19 | } else { 20 | hi = probe - 1 21 | } 22 | } 23 | return -1 24 | } 25 | 26 | 27 | fun main(args: Array) { 28 | var arr = intArrayOf( 29 | 2, 3, 5, 6, 8, 11, 15, 19, 21, 24, 30 | 28, 31, 44, 55, 76 31 | ) 32 | val x = 31 33 | val xIndex = interpolationSearch(arr, x) 34 | 35 | if (xIndex != -1) println("Item $x found at index $xIndex") else println("Element $x not found.") 36 | 37 | val y = 1 38 | val yIndex = interpolationSearch(arr, y) 39 | 40 | if (yIndex != -1) println("Item $x found at index $yIndex") else println("Element $x not found.") 41 | } 42 | -------------------------------------------------------------------------------- /Sorting Algorithms/Java/SelectionSort.java: -------------------------------------------------------------------------------- 1 | public class SelectionSort { 2 | public static void main(String[] args) { 3 | //My array of values 4 | int[] arr = new int[]{9, 8, 13, 2, 5, 22, 1315, 13, 4}; 5 | System.out.println("Array before sorting: "); 6 | printArray(arr); 7 | 8 | selectionSortMethod(arr); 9 | System.out.println("Array after sorting: "); 10 | printArray(arr); 11 | } 12 | 13 | public static void printArray(int[] arr) { 14 | for (int i = 0; i < arr.length; i++) { 15 | System.out.print("Index " + i + " ="); 16 | System.out.print(arr[i] + "\t"); 17 | } 18 | System.out.println("\n"); 19 | 20 | } 21 | 22 | 23 | public static void selectionSortMethod(int[] array) { 24 | for (int i = 0; i < array.length; i++) { 25 | int min = array[i]; 26 | int minId = i; 27 | for (int j = i+1; j < array.length; j++) { 28 | if (array[j] < min) { 29 | min = array[j]; 30 | minId = j; 31 | } 32 | } 33 | // swapping 34 | int temp = array[i]; 35 | array[i] = min; 36 | array[minId] = temp; 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /Sorting Algorithms/C-CPP/heap_sort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void create(int []); 4 | void down_adjust(int [],int); 5 | 6 | void main() 7 | { 8 | int heap[30],n,i,last,temp; 9 | printf("Enter no. of elements:"); 10 | scanf("%d",&n); 11 | printf("\nEnter elements:"); 12 | for(i=1;i<=n;i++) 13 | scanf("%d",&heap[i]); 14 | 15 | //create a heap 16 | heap[0]=n; 17 | create(heap); 18 | 19 | //sorting 20 | while(heap[0] > 1) 21 | { 22 | //swap heap[1] and heap[last] 23 | last=heap[0]; 24 | temp=heap[1]; 25 | heap[1]=heap[last]; 26 | heap[last]=temp; 27 | heap[0]--; 28 | down_adjust(heap,1); 29 | } 30 | 31 | //print sorted data 32 | printf("\nArray after sorting:\n"); 33 | for(i=1;i<=n;i++) 34 | printf("%d ",heap[i]); 35 | } 36 | 37 | void create(int heap[]) 38 | { 39 | int i,n; 40 | n=heap[0]; //no. of elements 41 | for(i=n/2;i>=1;i--) 42 | down_adjust(heap,i); 43 | } 44 | 45 | void down_adjust(int heap[],int i) 46 | { 47 | int j,temp,n,flag=1; 48 | n=heap[0]; 49 | 50 | while(2*i<=n && flag==1) 51 | { 52 | j=2*i; //j points to left child 53 | if(j+1<=n && heap[j+1] > heap[j]) 54 | j=j+1; 55 | if(heap[i] > heap[j]) 56 | flag=0; 57 | else 58 | { 59 | temp=heap[i]; 60 | heap[i]=heap[j]; 61 | heap[j]=temp; 62 | i=j; 63 | } 64 | } 65 | } -------------------------------------------------------------------------------- /Sorting Algorithms/C-CPP/bogosort.cpp: -------------------------------------------------------------------------------- 1 | // C++ implementation of Bogo Sort 2 | #include 3 | using namespace std; 4 | 5 | // To check if array is sorted or not 6 | bool isSorted(int a[], int n) 7 | { 8 | for(int i=0; i a[i+1]) 10 | return false; 11 | } 12 | return true; 13 | } 14 | 15 | // To generate permuatation of the array 16 | void shuffle(int a[], int n){ 17 | for (int i=0; i < n; i++) 18 | swap(a[i], a[rand()%n]); 19 | } 20 | 21 | // Sorts array a[0..n-1] using Bogo sort 22 | void bogosort(int a[], int n){ 23 | // if array is not sorted then shuffle 24 | // the array again 25 | while (!isSorted(a, n)) 26 | shuffle(a, n); 27 | } 28 | 29 | // prints the array 30 | void printArray(int a[], int n) 31 | { 32 | for (int i=0; i> n; 42 | int a[n]; 43 | cout << "Please enter the elements of the array which will be sorted: \n"; 44 | for(int i=0; i> a[i]; 45 | bogosort(a, n); 46 | printf("Here is the sorted array :\n"); 47 | printArray(a,n); 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /Cryptography Algorithms/Cpp/CeaserCipher.cpp: -------------------------------------------------------------------------------- 1 | // A cpp program to demonstrate Ceaser Cipher algorithm 2 | 3 | #include 4 | using namespace std; 5 | 6 | string ceaserCipher(string input, int key){ 7 | int len = input.length(); 8 | string encrypt = ""; 9 | for(int i=0;i>input; 33 | int key; 34 | cout<<"Enter key : "; 35 | cin>>key; 36 | encrypt = ceaserCipher(input, key); 37 | cout<<"Encrypted String is : "< 5 | 6 | // Prints a maximum set of activities that can be done by a single 7 | // person, one at a time. 8 | // n --> Total number of activities 9 | // s[] --> An array that contains start time of all activities 10 | // f[] --> An array that contains finish time of all activities 11 | void printMaxActivities(int s[], int f[], int n) 12 | { 13 | int i, j; 14 | 15 | printf ("Following activities are selected n"); 16 | 17 | // The first activity always gets selected 18 | i = 0; 19 | printf("%d ", i); 20 | 21 | // Consider rest of the activities 22 | for (j = 1; j < n; j++) 23 | { 24 | // If this activity has start time greater than or 25 | // equal to the finish time of previously selected 26 | // activity, then select it 27 | if (s[j] >= f[i]) 28 | { 29 | printf ("%d ", j); 30 | i = j; 31 | } 32 | } 33 | } 34 | 35 | // driver program to test above function 36 | int main() 37 | { 38 | int s[] = {1, 3, 0, 5, 8, 5}; 39 | int f[] = {2, 4, 6, 7, 9, 9}; 40 | int n = sizeof(s)/sizeof(s[0]); 41 | printMaxActivities(s, f, n); 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /Sorting Algorithms/C-CPP/bucketsort.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to sort an array using bucket sort 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | // Function to sort arr[] of size n using bucket sort 8 | void bucketSort(float arr[], int n) 9 | { 10 | // 1) Create n empty buckets 11 | vector b[n]; 12 | 13 | // 2) Put array elements in different buckets 14 | for (int i=0; i>arr[i]; 37 | } 38 | int n = sizeof(arr)/sizeof(arr[0]); 39 | bucketSort(arr, n); 40 | 41 | cout << "Sorted array is \n"; 42 | for (int i=0; i 3 | 4 | using std::cin; 5 | using std::cout; 6 | 7 | int gcd_naive(int a, int b) { 8 | int current_gcd = 1; 9 | for (int d = 2; d <= a && d <= b; d++) { 10 | if (a % d == 0 && b % d == 0) { 11 | if (d > current_gcd) { 12 | current_gcd = d; 13 | } 14 | } 15 | } 16 | return current_gcd; 17 | } 18 | 19 | int euclid_gcd(int a, int b) { 20 | int divisor = a >= b ? a : b; 21 | int dividend = a <= b ? a : b; 22 | while (divisor != 0) { 23 | int remainder = dividend % divisor; 24 | dividend = divisor; 25 | divisor = remainder; 26 | } 27 | return dividend; 28 | } 29 | 30 | int main() { 31 | int a, b; 32 | // while (true) { 33 | // a = rand() % 1000 + 2; 34 | // b = rand() % 1000 + 2; 35 | // cout << "Numbers: " << a << ' ' << b << "\n"; 36 | 37 | // long res1 = gcd_naive(a, b); 38 | // long res2 = euclid_gcd(a, b); 39 | // if (res1 != res2) { 40 | // cout << "Wrong answer: " << res1 << ' ' << res2 << "\n"; 41 | // break; 42 | // } 43 | // else { 44 | // cout << "OK\n"; 45 | // } 46 | // } 47 | std::cin >> a >> b; 48 | std::cout << euclid_gcd(a, b) << std::endl; 49 | return 0; 50 | } -------------------------------------------------------------------------------- /Dynamic Programming/longestcommonsubsequence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int max(int a,int b){ 4 | if(a>b){ 5 | return a; 6 | 7 | } 8 | else{ 9 | return b; 10 | } 11 | } 12 | void lcs( string X, string Y, int m, int n ) 13 | { 14 | int L[m+1][n+1]; 15 | 16 | 17 | for (int i=0; i<=m; i++) 18 | { 19 | for (int j=0; j<=n; j++) 20 | { 21 | if (i == 0 || j == 0) 22 | L[i][j] = 0; 23 | else if (X[i-1] == Y[j-1]) 24 | L[i][j] = L[i-1][j-1] + 1; 25 | else 26 | L[i][j] = max(L[i-1][j], L[i][j-1]); 27 | } 28 | } 29 | 30 | 31 | int index = L[m][n]; 32 | 33 | 34 | char lcs[index+1]; 35 | lcs[index] = '\0'; 36 | 37 | 38 | int i = m, j = n; 39 | while (i > 0 && j > 0) 40 | { 41 | 42 | if (X[i-1] == Y[j-1]) 43 | { 44 | lcs[index-1] = X[i-1]; 45 | i--; j--; index--; 46 | } 47 | 48 | 49 | else if (L[i-1][j] > L[i][j-1]) 50 | i--; 51 | else 52 | j--; 53 | } 54 | 55 | 56 | cout << lcs<<"\n"; 57 | } 58 | int main(){ 59 | string s1,s2; 60 | cin>>s1>>s2; 61 | int m=s1.length(); 62 | int n=s2.length(); 63 | lcs(s1,s2,m,n); 64 | } -------------------------------------------------------------------------------- /Search Algorithms/C-CPP/Interpolation_Search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int interpolationSearch(int array[], int start, int end, int key) { 4 | int dist, valRange, indexRange, estimate; 5 | float fraction; 6 | while(start <= end && key >= array[start] && key <= array[end]) { 7 | dist = key - array[start]; 8 | valRange = array[end] - array[start]; //range of value 9 | fraction = dist / valRange; 10 | indexRange = end - start; 11 | estimate = start + (fraction * indexRange); //estimated position of the key 12 | if(array[estimate] == key) 13 | return estimate; 14 | if(array[estimate] < key) 15 | start = estimate +1; 16 | else 17 | end = estimate - 1; 18 | } 19 | return -1; 20 | } 21 | int main() { 22 | int n, searchKey, loc; 23 | cout << "Enter number of items: "; 24 | cin >> n; 25 | int arr[n]; //create an array of size n 26 | cout << "Enter items: " << endl; 27 | for(int i = 0; i< n; i++) { 28 | cin >> arr[i]; 29 | } 30 | cout << "Enter search key to search in the list: "; 31 | cin >> searchKey; 32 | if((loc = interpolationSearch(arr, 0, n-1, searchKey)) >= 0) 33 | cout << "Item found at location: " << loc << endl; 34 | else 35 | cout << "Item is not found in the list." << endl; 36 | } 37 | -------------------------------------------------------------------------------- /Dynamic Programming/Knapsack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | /* 6 | Iterative top-down implementation of the 0-1 Knapsack problem 7 | */ 8 | 9 | int main() { 10 | int capacity, n_items, weight, benefit, max_benefit = 0; 11 | 12 | std::cin >> capacity >> n_items; 13 | 14 | // DP array that stores the benefit associated with the knapsack of capacity 'i' 15 | std::vector knapsack(capacity + 1, -1); 16 | 17 | // Associates 0 to the knapsack with no capacity 18 | knapsack[0]=0; 19 | 20 | // Iterative execution of combining each of the n items using exactly one of each 21 | for (int i = 0; i < n_items; i++) { 22 | std::cin >> weight >> benefit; 23 | 24 | // Check which of the "possible" knapsacks can store the i-th item 25 | for (int j = capacity - weight; j >= 0; j--) { 26 | if (knapsack[j] != -1) { 27 | /* Stores the maximum of adding an item on the smaller knapsack 28 | and the previously filled knapsack in its respective position*/ 29 | knapsack[j + weight] = std::max(knapsack[j] + benefit, knapsack[j + weight]); 30 | } 31 | } 32 | } 33 | 34 | // Iterate one last time on the array to find the maximum possible benefit 35 | for (int j = 1; j <= capacity; j++) { 36 | max_benefit = std::max(max_benefit, knapsack[j]); 37 | } 38 | 39 | std::cout << max_benefit << std::endl; 40 | } -------------------------------------------------------------------------------- /Search Algorithms/C-CPP/exponentialsearch.c: -------------------------------------------------------------------------------- 1 | //u have to enter sorted array or have to sort by any method convinient to you 2 | #include 3 | #include 4 | int min(int x,int y) 5 | { 6 | if(x>y) 7 | return x; 8 | else 9 | return y; 10 | } 11 | 12 | int binarysearch(int *a,int l,int r,int value) 13 | { 14 | int j=-1; 15 | int mid=(r+l)/2; 16 | if(a[mid]==value) 17 | { 18 | j=mid; 19 | } 20 | else if(value. 5 | 6 | :param arr: A list of number to sort 7 | :param digit: The digit we want to sort by 8 | :param radix: The base of the number system 9 | :return result: The sorted list of given arr list 10 | """ 11 | 12 | arr_len = len(arr) 13 | count = [0]*radix # counts the number of occurences of each digit in arr 14 | result = [0]*arr_len 15 | 16 | def _digit_find(num, digit, radix): 17 | return int((num / radix ** digit) % radix) 18 | 19 | for i in range(arr_len): 20 | digit_of_arr_i = _digit_find(arr[i], digit, radix) 21 | count[digit_of_arr_i] += 1 22 | 23 | for j in range(1, radix): 24 | count[j] += count[j-1] 25 | 26 | for m in range(arr_len-1, -1, -1): 27 | digit_of_arr_i = _digit_find(arr[m], digit, radix) 28 | count[digit_of_arr_i] -= 1 29 | result[count[digit_of_arr_i]] = arr[m] 30 | 31 | return result 32 | 33 | 34 | def main(): 35 | arr = [6, 5, 4, 3, 2, 1] 36 | print('Sorted element using Counting Sort: {}'.format( 37 | ' '.join(map(str, counting_sort(arr, 0))))) 38 | 39 | 40 | if __name__ == '__main__': 41 | main() 42 | -------------------------------------------------------------------------------- /Sorting Algorithms/C-CPP/merge_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | #define MAXSIZE 100 5 | 6 | void Merge(int a[],int l1,int h1,int l2,int h2){ 7 | int i=0,j,low=l1; 8 | int b[MAXSIZE]; 9 | 10 | while( l1<=h1 && l2<=h2 ){ 11 | if(a[l1]>n; 46 | int a[n]; 47 | cout<<"Enter all elements separated: " 48 | for(int i=0;i>a[i]; 50 | } 51 | cout<<"Befor Sorting: "; 52 | 53 | for(int i=0;i 1): 19 | 20 | # Check if fibMm2 is a valid location 21 | i = min(offset+fibMMm2, n-1) 22 | 23 | # If x is greater than the value at 24 | # index fibMm2, cut the subarray array 25 | # from offset to i 26 | if (arr[i] < x): 27 | fibM = fibMMm1 28 | fibMMm1 = fibMMm2 29 | fibMMm2 = fibM - fibMMm1 30 | offset = i 31 | 32 | # If x is greater than the value at 33 | # index fibMm2, cut the subarray 34 | # after i+1 35 | elif (arr[i] > x): 36 | fibM = fibMMm2 37 | fibMMm1 = fibMMm1 - fibMMm2 38 | fibMMm2 = fibM - fibMMm1 39 | 40 | # element found. return index 41 | else : 42 | return i 43 | 44 | # comparing the last element with x */ 45 | if(fibMMm1 and arr[offset+1] == x): 46 | return offset+1; 47 | 48 | # element not found. return -1 49 | return -1 50 | 51 | # Driver Code 52 | arr = [10, 22, 35, 40, 45, 50, 53 | 80, 82, 85, 90, 100] 54 | n = len(arr) 55 | x = 85 56 | print("Found at index:", 57 | fibMonaccianSearch(arr, x, n)) 58 | 59 | -------------------------------------------------------------------------------- /Search Algorithms/Java/InterpolationSearch.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Scanner; 3 | 4 | public class Main { 5 | 6 | public static void main(String[] args) { 7 | 8 | int length, ele; 9 | Scanner scanner = new Scanner(System.in); 10 | 11 | System.out.print("Enter number of elements: "); 12 | length = scanner.nextInt(); 13 | 14 | int arr[]=new int[length]; 15 | System.out.println("Enter elements: "); 16 | 17 | for(int i=0;i= val) { 37 | 38 | mid = lo + ((val - nums[lo]) * (hi - lo)) / (nums[hi] - nums[lo]); 39 | if (nums[mid] < val) { 40 | lo = mid + 1; 41 | 42 | } else if (nums[mid] > val) { 43 | hi = mid - 1; 44 | 45 | } else return mid; 46 | } 47 | 48 | if (nums[lo] == val) return lo; 49 | 50 | return -1; 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /Sorting Algorithms/Python/bucket_sort.py: -------------------------------------------------------------------------------- 1 | # Python program to sort array 2 | # of elements using Bucket Sort 3 | 4 | # Insertion sort algo 5 | def ins_sort_algorithm(elem): 6 | for i in range(1, len(elem)): 7 | j = i-1 8 | inc = elem[i] 9 | while j >= 0 and elem[j] > inc: 10 | elem[j+1] = elem[j] 11 | j -= 1 12 | elem[j+1] = inc 13 | return elem 14 | 15 | # Bucket sort algo 16 | def bucket_sort_algorithm(val_list): 17 | temp = [] 18 | slot = 8 # customizable 19 | # add empty lists to temp(_arr) 20 | for i in range(slot): 21 | temp.append([]) 22 | # Computing 23 | for j in val_list: 24 | index_b = int(slot * j) 25 | temp[index_b].append(j) 26 | 27 | for i in range(slot): 28 | temp[i] = ins_sort_algorithm(temp[i]) 29 | 30 | k = 0 31 | for i in range(slot): 32 | for j in range(len(temp[i])): 33 | val_list[k] = temp[i][j] 34 | k += 1 35 | return val_list 36 | 37 | # Driver Function 38 | elem_li = [0.1290, 0.2523, 0.0001, 0.91, 0.454, 0.978, 0.01, 0.66] 39 | # Original 40 | print("Before Sorting: ") 41 | print(elem_li) 42 | # Result 43 | print("Result(post-Bucket Sort): ") 44 | print(bucket_sort_algorithm(elem_li)) 45 | 46 | # Expected Outcome: 47 | # ---------------- 48 | # Before Sorting: 49 | # [0.129, 0.2523, 0.0001, 0.91, 0.454, 0.978, 0.01, 0.66] 50 | # Result(post-Bucket Sort): 51 | # [0.0001, 0.01, 0.129, 0.2523, 0.454, 0.66, 0.91, 0.978] -------------------------------------------------------------------------------- /Search Algorithms/Dlang/binary.d: -------------------------------------------------------------------------------- 1 | /* 2 | binary search must receive an ordered array! 3 | */ 4 | int binarySearch( int[] haystack, int needle ) 5 | { 6 | size_t start = 0; 7 | size_t end = haystack.length; 8 | while( start < end) 9 | { 10 | size_t index = (start + end ) / 2; 11 | if( haystack[index] == needle ) return index; 12 | if( needle > haystack[index] ) 13 | start = index + 1; 14 | else 15 | end = index; 16 | } 17 | return -1; 18 | } 19 | 20 | void main() 21 | { 22 | import std.random : uniform; 23 | import std.stdio : writeln, readln; 24 | import std.conv : to; 25 | import std.string : strip; 26 | import std.algorithm : sort; 27 | import std.array : array; 28 | 29 | int[] haystack; 30 | 31 | size_t haystack_size = 100; 32 | size_t rnd_low_bound = 0; 33 | size_t rnd_high_bound = 100; 34 | 35 | haystack.length = haystack_size; 36 | 37 | //fill array randomly 38 | foreach(index ; 0 .. haystack_size) 39 | { 40 | haystack[index] = cast(int) uniform(rnd_low_bound, rnd_high_bound); 41 | } 42 | 43 | //choose needle 44 | writeln("Choose a integer value between ", rnd_low_bound, " and ", rnd_high_bound , " :"); 45 | int needle = readln().strip.to!int; 46 | 47 | haystack = haystack.sort.array; 48 | 49 | int result = binarySearch( haystack, needle ); 50 | 51 | if( result == -1 ){ 52 | writeln("The value was not found!"); 53 | } else { 54 | writeln("The first occurence of the value are in the ", result, " position of the array"); 55 | } 56 | 57 | writeln("Array Values:"); 58 | writeln(haystack); 59 | } -------------------------------------------------------------------------------- /Sorting Algorithms/php/mergesort.php: -------------------------------------------------------------------------------- 1 | 0 || count(right) > 0){ 40 | if(count($left) > 0 && count(right) > 0){ 41 | if($left[0] <= $right[0]){ 42 | $result[] = array_shift($left); 43 | } else { 44 | $result[] = array_shift($right); 45 | } 46 | } elseif (count($left) > 0){ 47 | $result[] = array_shift($left); 48 | } elseif (count($right) > 0){ 49 | $result[] = array_shift($right); 50 | } 51 | } 52 | 53 | print_array($result);exit; 54 | 55 | return $result; 56 | } 57 | 58 | function print_array($array){ 59 | echo "
";
60 |     print_r($array);
61 |     echo "
"; 62 | echo "
"; 63 | } 64 | 65 | ? 66 | -------------------------------------------------------------------------------- /Greedy Algorithms/Fractional-Knapsack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | int main() { 6 | 7 | std::cout << "Enter number of objects available = "; 8 | int n; 9 | std::cin>>n; 10 | 11 | std::cout << "Enter Value and Weight of all objects:" << '\n'; 12 | std::vector > v(n); 13 | for(int i=0;i>v[i].first; 16 | std::cout<<"Weight["<>v[i].second; 18 | } 19 | 20 | std::cout<<"Enter Capacity of Bag : "; 21 | double W; 22 | std::cin>>W; 23 | 24 | std::vector > valbwe(n); //value by weight 25 | for(int i=0;i Selected(n,false); 32 | double profit=0; 33 | for(int i=0;i0){ 35 | if(W>v[valbwe[i].second].second){ 36 | profit+=v[valbwe[i].second].first; 37 | W-=v[valbwe[i].second].second; 38 | } 39 | else{ 40 | profit+=(v[valbwe[i].second].first * (W))/v[valbwe[i].second].second; 41 | W = 0; 42 | } 43 | Selected[valbwe[i].second] = true; 44 | } 45 | else{ 46 | break; 47 | } 48 | } 49 | 50 | std::cout << "Selected Objects :" << '\n'; 51 | for(int i=0;i> permute(int[] arr){ 12 | List> list = new ArrayList<>(); 13 | int[] index = new int[arr.length]; 14 | int n = index.length; 15 | int fact = 1; 16 | 17 | for(int i=0; i()); 24 | } 25 | 26 | int listIndex = fact-1; 27 | list.set(listIndex, toList(arr)); 28 | listIndex--; 29 | 30 | int i = 0; 31 | while(i < n){ 32 | if(index[i] < i){ 33 | int j = i%2 == 0 ? 0: index[i]; 34 | 35 | int temp = arr[j]; 36 | arr[j] = arr[i]; 37 | arr[i] = temp; 38 | list.set(listIndex, toList(arr)); 39 | listIndex--; 40 | index[i]++; 41 | i = 0; 42 | }else{ 43 | index[i] = 0; 44 | i++; 45 | } 46 | } 47 | return list; 48 | } 49 | 50 | public static List toList(int[] arr){ 51 | List list = new ArrayList<>(); 52 | for(int i=arr.length-1; i>=0; i--){ 53 | list.add(arr[i]); 54 | } 55 | return list; 56 | } 57 | } -------------------------------------------------------------------------------- /Dynamic Programming/n-queen.cpp: -------------------------------------------------------------------------------- 1 | #define N 4 2 | #include 3 | #include 4 | void printSolution(int board[N][N]) 5 | { 6 | for (int i = 0; i < N; i++) { 7 | for (int j = 0; j < N; j++) 8 | printf(" %d ", board[i][j]); 9 | printf("\n"); 10 | } 11 | } 12 | 13 | bool isSafe(int board[N][N], int row, int col) 14 | { 15 | int i, j; 16 | 17 | for (i = 0; i < col; i++) 18 | if (board[row][i]) 19 | return false; 20 | for (i = row, j = col; i >= 0 && j >= 0; i--, j--) 21 | if (board[i][j]) 22 | return false; 23 | for (i = row, j = col; j >= 0 && i < N; i++, j--) 24 | if (board[i][j]) 25 | return false; 26 | 27 | return true; 28 | } 29 | bool solveNQUtil(int board[N][N], int col) 30 | { 31 | if (col >= N) 32 | return true; 33 | for (int i = 0; i < N; i++) { 34 | if (isSafe(board, i, col)) { 35 | board[i][col] = 1; 36 | if (solveNQUtil(board, col + 1)) 37 | return true; 38 | board[i][col] = 0; // BACKTRACK 39 | } 40 | } 41 | return false; 42 | } 43 | bool solveNQ() 44 | { 45 | int board[N][N] = { { 0, 0, 0, 0 }, 46 | { 0, 0, 0, 0 }, 47 | { 0, 0, 0, 0 }, 48 | { 0, 0, 0, 0 } }; 49 | 50 | if (solveNQUtil(board, 0) == false) { 51 | printf("Solution does not exist"); 52 | return false; 53 | } 54 | 55 | printSolution(board); 56 | return true; 57 | } 58 | int main() 59 | { 60 | solveNQ(); 61 | return 0; 62 | } -------------------------------------------------------------------------------- /Graph/dfs_and_bfs.cpp: -------------------------------------------------------------------------------- 1 | // LANGUAGE: C++ 2 | // ENV: gcc 3 | //AUTHOR: Proma Roy 4 | //GITHUB: https://github.com/promaroy 5 | 6 | 7 | // implementing a undirected graph data structure using adjacency list and traversals... 8 | 9 | #include 10 | using namespace std; 11 | vector v[6]; //an array of vectors to store the nodes connected to a node... 12 | int vis[6]={0}; // a hash array to keep track of the nodes which are already visited 13 | queue q;//to implement bfs.. 14 | int level[6]={0}; 15 | void add_edge(int a,int b)// function to add an edge 16 | { 17 | v[a].push_back(b); 18 | v[b].push_back(a); 19 | } 20 | void dfs(int in)//function to run dfs traversal 21 | { 22 | vis[in]=1; 23 | cout< 2 | 3 | using namespace std; 4 | 5 | void BinaryInsertion(int *v, int n) 6 | { 7 | int i,j,temp,medio,izq,der; 8 | for (j = 1; j < n; j++) 9 | { 10 | //Se declaran las variables de comparacion y la auxiliar para desplazar los valores ordenados 11 | temp=v[j]; 12 | izq=0; 13 | der = j-1; 14 | //Se busca la posición de la inserción de forma binaria 15 | while (izq <= der) 16 | { 17 | medio = (int) ((izq + der)/2); 18 | if (temp <= v[medio]) 19 | der = medio-1; 20 | else 21 | izq = medio+1; 22 | } 23 | //Los elementos ya ordenados de desplazan a la derecha(final) 24 | for (i = j-1; i>= izq; i--) 25 | v[i+1] = v[i]; 26 | v[izq] = temp; 27 | } 28 | } 29 | 30 | void mostrarDatos(int v[],int lim){//Se muestran los datos del vector 31 | int contador=1; 32 | for (int i = 0; i < lim; i++){ 33 | cout<<"Valor del elemento No."<>n; 44 | /*Declaración del vector a ordenar*/ 45 | int v[n]; 46 | 47 | //Rellenado de vector 48 | for (int i = 0; i < n; i++){ 49 | cout<<"Ingrese el elemento: "; 50 | cin>>x; 51 | v[i]=x; 52 | } 53 | 54 | 55 | cout<<"Valores no ordenados"< 5 | #include 6 | 7 | 8 | void merge(int arr[], int l, int m, int r) 9 | { 10 | int i, j, k; 11 | int n1 = m - l + 1; 12 | int n2 = r - m; 13 | 14 | int L[n1], R[n2]; 15 | for (i = 0; i < n1; i++) 16 | L[i] = arr[l + i]; 17 | for (j = 0; j < n2; j++) 18 | R[j] = arr[m + 1 + j]; 19 | 20 | i = 0; 21 | j = 0; 22 | k = l; 23 | while (i < n1 && j < n2) 24 | { 25 | if (L[i] <= R[j]) 26 | { 27 | arr[k] = L[i]; 28 | i++; 29 | } 30 | else 31 | { 32 | arr[k] = R[j]; 33 | j++; 34 | } 35 | k++; 36 | } 37 | 38 | while (i < n1) 39 | { 40 | arr[k] = L[i]; 41 | i++; 42 | k++; 43 | } 44 | 45 | 46 | while (j < n2) 47 | { 48 | arr[k] = R[j]; 49 | j++; 50 | k++; 51 | } 52 | } 53 | 54 | 55 | void mergeSort(int arr[], int l, int r) 56 | { 57 | if (l < r) 58 | { 59 | int m = l + (r - l) / 2; 60 | 61 | mergeSort(arr, l, m); 62 | mergeSort(arr, m + 1, r); 63 | 64 | merge(arr, l, m, r); 65 | } 66 | } 67 | 68 | void printArray(int A[], int size) 69 | { 70 | int i; 71 | for (i = 0; i < size; i++) 72 | printf("%d ", A[i]); 73 | printf("\n"); 74 | } 75 | 76 | int main() 77 | { 78 | int arr[] = {12, 11, 13, 5, 6, 7}; 79 | int arr_size = sizeof(arr) / sizeof(arr[0]); 80 | 81 | printf("Given array is \n"); 82 | printArray(arr, arr_size); 83 | 84 | mergeSort(arr, 0, arr_size - 1); 85 | 86 | printf("\nSorted array is \n"); 87 | printArray(arr, arr_size); 88 | return 0; 89 | } -------------------------------------------------------------------------------- /Sorting Algorithms/Python/ShellSort.py: -------------------------------------------------------------------------------- 1 | ##Shell sort 2 | **It is an in-place comparison sort.** 3 | ***This algorithm is based on sorting pairs of elements far apart from each other, by progressively reducing the gap between elements to be compared. Starting with far apart elements, algorithm moves some out-of-place elements into position faster than a simple nearest neighbor exchange.*** 4 | ###Time complexity 5 | **The running time of Shellsort is heavily dependent on the gap sequence it uses.** 6 | -Worst complexity: Depends on gap sequence 7 | -Average complexity: n*log(n)^2 or n^(3/2) 8 | -Best complexity: n 9 | 10 | ##Python Code implementation of Shell sort 11 | 12 | >def shellSort(arr): 13 | > # start with large gap and then reduce it to smaller one 14 | >n=len(arr) 15 | >gap=n/2 16 | 17 | > # perform gapped insertion sort for this gap size. 18 | > # The first gapped elements are already in Gap 19 | > # Order keep adding till the end of array 20 | > # is gap sorted 21 | 22 | > while gap>0: 23 | > for j in range(gap,n): 24 | > # add a[j] to the elements that have been gap sorted 25 | > # then,save a[j] in temp and make a hole at position j 26 | > temp=arr[j] 27 | 28 | > # shift earlier gap-sorted elements up until the correct location for a[j] is found 29 | 30 | > k=j 31 | > while k >= gap and arr[k-gap] >temp: 32 | >arr[k] = arr[k-gap] 33 | > k -= gap 34 | 35 | > # put temp (the original a[j]) in its correct location 36 | > arr[k] = temp 37 | >gap /= 2 38 | 39 | > #main program 40 | > arr = [ 12, 34, 54, 2, 3] 41 | 42 | >n = len(arr) 43 | >print ("Array before sorting:") 44 | >for i in range(n): 45 | >print(arr[i]), 46 | 47 | >shellSort(arr) 48 | 49 | >print ("\nArray after sorting:") 50 | >for i in range(n): 51 | >print(arr[i]) 52 | 53 | ##thanks for reading! 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /Backtracking/SumOfSubsets.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define ARRAYSIZE(a) (sizeof(a))/(sizeof(a[0])) 5 | 6 | static int total_nodes; 7 | // prints subset found 8 | void printSubset(int A[], int size) 9 | { 10 | for(int i = 0; i < size; i++) 11 | { 12 | printf("%*d", 5, A[i]); 13 | } 14 | 15 | printf("n"); 16 | } 17 | 18 | // inputs 19 | // s - set vector 20 | // t - tuplet vector 21 | // s_size - set size 22 | // t_size - tuplet size so far 23 | // sum - sum so far 24 | // ite - nodes count 25 | // target_sum - sum to be found 26 | void subset_sum(int s[], int t[], 27 | int s_size, int t_size, 28 | int sum, int ite, 29 | int const target_sum) 30 | { 31 | total_nodes++; 32 | if( target_sum == sum ) 33 | { 34 | // We found subset 35 | printSubset(t, t_size); 36 | // Exclude previously added item and consider next candidate 37 | subset_sum(s, t, s_size, t_size-1, sum - s[ite], ite + 1, target_sum); 38 | return; 39 | } 40 | else 41 | { 42 | // generate nodes along the breadth 43 | for( int i = ite; i < s_size; i++ ) 44 | { 45 | t[t_size] = s[i]; 46 | // consider next level node (along depth) 47 | subset_sum(s, t, s_size, t_size + 1, sum + s[i], i + 1, target_sum); 48 | } 49 | } 50 | } 51 | 52 | // Wrapper to print subsets that sum to target_sum 53 | // input is weights vector and target_sum 54 | void generateSubsets(int s[], int size, int target_sum) 55 | { 56 | int *tuplet_vector = (int *)malloc(size * sizeof(int)); 57 | 58 | subset_sum(s, tuplet_vector, size, 0, 0, 0, target_sum); 59 | 60 | free(tuplet_vector); 61 | } 62 | 63 | int main() 64 | { 65 | int weights[] = {10, 7, 5, 18, 12, 20, 15}; 66 | int size = ARRAYSIZE(weights); 67 | 68 | generateSubsets(weights, size, 35); 69 | printf("Nodes generated %dn", total_nodes); 70 | return 0; 71 | } 72 | -------------------------------------------------------------------------------- /Greedy Algorithms/Job Sequencing.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct JOB{ 5 | 6 | char job; 7 | int dline; 8 | int profit; 9 | }; 10 | 11 | bool comparision(JOB a,JOB b){ 12 | return (a.profit>b.profit); 13 | } 14 | 15 | void job_Sequencing(struct JOB a[],int n){ 16 | 17 | sort(a,a+n,comparision); //max to min Profit 18 | 19 | //Finding max deadline => MAX Size of output Array 20 | 21 | int max_deadline=0; 22 | for(int i=0;imax_deadline){ 24 | max_deadline=a[i].dline; 25 | } 26 | } 27 | //cout<=1){ 44 | output[x]=a[i].job; 45 | } 46 | } 47 | } 48 | 49 | for(int i=1;i<=max_deadline;i++){ 50 | if(output[i]!='?'){ 51 | cout<>n; 60 | struct JOB a[n]; 61 | cout<<"Enter Job names: "; 62 | for(int i=0;i>a[i].job; 64 | } 65 | cout<<"Enter Deadline For Each Job: "; 66 | for(int i=0;i>a[i].dline; 68 | } 69 | cout<<"Enter Profit For Each Job: "; 70 | for(int i=0;i>a[i].profit; 72 | } 73 | 74 | job_Sequencing(a,n); 75 | 76 | return 0; 77 | } 78 | -------------------------------------------------------------------------------- /Sorting Algorithms/CSharp/QuickSort.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace QuickSort 4 | { 5 | class Program 6 | { 7 | static void Main(string[] args) 8 | { 9 | Console.WriteLine("Quick sort"); 10 | 11 | int[] array = new int[10] { 50, 10, 70, 100, 20, 60, 80, 30, 40, 90 }; 12 | 13 | Console.WriteLine("Array before sort:"); 14 | for (int i = 0; i < array.Length; i++) 15 | { 16 | Console.WriteLine(array[i]); 17 | } 18 | 19 | QuickSort(array, 0, array.Length - 1); 20 | 21 | Console.WriteLine("Array after sort:"); 22 | for (int i = 0; i < array.Length; i++) 23 | { 24 | Console.WriteLine(array[i]); 25 | } 26 | } 27 | 28 | private static void QuickSort(int[] array, int start, int end) 29 | { 30 | if (start < end) 31 | { 32 | int i = Partition(array, start, end); 33 | QuickSort(array, start, i - 1); 34 | QuickSort(array, i + 1, end); 35 | } 36 | } 37 | 38 | private static int Partition(int[] array, int start, int end) 39 | { 40 | int temp; 41 | int p = array[end]; 42 | int i = start - 1; 43 | 44 | for (int j = start; j <= end - 1; j++) 45 | { 46 | if (array[j] <= p) 47 | { 48 | i++; 49 | temp = array[i]; 50 | array[i] = array[j]; 51 | array[j] = temp; 52 | } 53 | } 54 | 55 | temp = array[i + 1]; 56 | array[i + 1] = array[end]; 57 | array[end] = temp; 58 | 59 | return i + 1; 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Hacktoberfest'19 2 | Hacktoberfest® is open to everyone in our global community. Whether you’re a developer, student learning to code, event host, or company of any size, you can help drive growth of open source and make positive contributions to an ever-growing community. All backgrounds and skill levels are encouraged to complete the challenge. 3 | 4 | * Hacktoberfest is open to everyone in our global community! 5 | * Pull requests can be made in any GitHub-hosted repositories/projects. 6 | * Sign up anytime between October 1 and October 31. 7 | 8 | ## Support open source and earn a limited edition T-shirt! 9 | ### Rules 10 | To qualify for the official limited edition Hacktoberfest shirt, you must register and make four pull requests (PRs) between October 1-31 (in any time zone). 11 | PRs can be made to any public repo on GitHub, not only the ones with issues labeled **Hacktoberfest**. 12 | If a maintainer reports your pull request as spam or behavior not in line with the project’s code of conduct, you will be ineligible to participate. 13 | This year, the first 50,000 participants who successfully complete the challenge will earn a T-shirt. 14 | 15 | Read more about [participation details](https://hacktoberfest.digitalocean.com/details). 16 | 17 | ## Guidelines to Contribute here 18 | ### Follow these steps to make your first pull request 19 | 20 | * Fork this repository 21 | * Clone your forked repository to your local machine 22 | * Add any **Algorithm** (any language) in its respective folder (ex. Bubble sort in Sorting Algorithms) 23 | (If folder is not there you can create one) 24 | * Add your name in Contributors.md file 25 | * Then create a pull request 26 | * Congratulations!! You have successfully created your pull request. 27 | * Check your progress here (https://hacktoberfest.digitalocean.com/profile) 28 | * Wait for the T-Shirt 29 | -------------------------------------------------------------------------------- /Sorting Algorithms/Python/merge_sort.py: -------------------------------------------------------------------------------- 1 | # Python program for implementation of MergeSort 2 | 3 | # Merges two subarrays of arr[]. 4 | # First subarray is arr[l..m] 5 | # Second subarray is arr[m+1..r] 6 | def merge(arr, l, m, r): 7 | n1 = m - l + 1 8 | n2 = r- m 9 | 10 | # create temp arrays 11 | L = [0] * (n1) 12 | R = [0] * (n2) 13 | 14 | # Copy data to temp arrays L[] and R[] 15 | for i in range(0 , n1): 16 | L[i] = arr[l + i] 17 | 18 | for j in range(0 , n2): 19 | R[j] = arr[m + 1 + j] 20 | 21 | # Merge the temp arrays back into arr[l..r] 22 | i = 0 # Initial index of first subarray 23 | j = 0 # Initial index of second subarray 24 | k = l # Initial index of merged subarray 25 | 26 | while i < n1 and j < n2 : 27 | if L[i] <= R[j]: 28 | arr[k] = L[i] 29 | i += 1 30 | else: 31 | arr[k] = R[j] 32 | j += 1 33 | k += 1 34 | 35 | # Copy the remaining elements of L[], if there 36 | # are any 37 | while i < n1: 38 | arr[k] = L[i] 39 | i += 1 40 | k += 1 41 | 42 | # Copy the remaining elements of R[], if there 43 | # are any 44 | while j < n2: 45 | arr[k] = R[j] 46 | j += 1 47 | k += 1 48 | 49 | # l is for left index and r is right index of the 50 | # sub-array of arr to be sorted 51 | def mergeSort(arr,l,r): 52 | if l < r: 53 | 54 | # Same as (l+r)/2, but avoids overflow for 55 | # large l and h 56 | m = (l+(r-1))//2 57 | 58 | # Sort first and second halves 59 | mergeSort(arr, l, m) 60 | mergeSort(arr, m+1, r) 61 | merge(arr, l, m, r) 62 | 63 | 64 | arr = [] 65 | inp = input("Enter the array: ") 66 | inp = list(inp.split()) 67 | arr = list(map(int, inp)) 68 | n = len(arr) 69 | #funtion call 70 | mergeSort(arr,0,n-1) 71 | #printing the sorted 72 | print("\nSorted array is: ", *arr) 73 | 74 | 75 | -------------------------------------------------------------------------------- /Sorting Algorithms/Java/QuickSort.java: -------------------------------------------------------------------------------- 1 | public class QuickSort { 2 | public static void main(String[] args) { 3 | int i; 4 | int[] arr={90,23,101,45,65,23,67,89,34,23}; 5 | quickSort(arr, 0, 9); 6 | System.out.println("\n The sorted array is: \n"); 7 | for(i=0;i<10;i++) 8 | System.out.println(arr[i]); 9 | } 10 | public static int partition(int a[], int beg, int end) 11 | { 12 | 13 | int left, right, temp, loc, flag; 14 | loc = left = beg; 15 | right = end; 16 | flag = 0; 17 | while(flag != 1) 18 | { 19 | while((a[loc] <= a[right]) && (loc!=right)) 20 | right--; 21 | if(loc==right) 22 | flag =1; 23 | elseif(a[loc]>a[right]) 24 | { 25 | temp = a[loc]; 26 | a[loc] = a[right]; 27 | a[right] = temp; 28 | loc = right; 29 | } 30 | if(flag!=1) 31 | { 32 | while((a[loc] >= a[left]) && (loc!=left)) 33 | left++; 34 | if(loc==left) 35 | flag =1; 36 | elseif(a[loc] Index 1 swapping happens. 16 | * Step 2 : Index 1 and Index 2 gets selected. If Index 1 > Index2 swapping happens. 17 | * So after each iteration is completed you see the largest value among all of them in the right most conner 18 | * 19 | * In the inner for loop j < n-i . The reason is after the 1st iteration is completed automatically the right side gets the highest value. 20 | * No need to check it again. 21 | * 22 | * */ 23 | for (int i = 0; i < n - 1; i++) { 24 | for (int j = 0; j < n - i - 1; j++) { 25 | if (arr[j] > arr[j + 1]) { 26 | // swap arr[j+1] and arr[i] 27 | int temp = arr[j]; 28 | arr[j] = arr[j + 1]; 29 | arr[j + 1] = temp; 30 | } 31 | } 32 | System.out.println("Array after " + (i + 1) + " iterations"); 33 | printArray(arr); 34 | } 35 | System.out.println("Array after sorting: "); 36 | printArray(arr); 37 | } 38 | 39 | public static void printArray(int[] arr) { 40 | for (int i = 0; i < arr.length; i++) { 41 | System.out.print("Index " + i + " ="); 42 | System.out.print(arr[i] + "\t"); 43 | } 44 | System.out.println("\n"); 45 | 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Mathematical Algorithms/EuclideanGCD/euclidean_gcd.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | 4 | public class euclidean_gcd { 5 | 6 | /* 7 | * Calculates GCD of two numbers a & b using the division-based 8 | * Euclidean Algorithm 9 | */ 10 | public static long euclideanGcdDivision(long x, long y) { 11 | while(y != 0) { 12 | long temp =y; 13 | y=x%y; 14 | x=temp; 15 | } 16 | return x; 17 | } 18 | 19 | /* 20 | * Calculates GCD of two numbers a & b using the Recursive-based 21 | * Euclidean Algorithm 22 | */ 23 | public static long euclideanGcdRecursive(long x, long y) { 24 | if (x == 0) 25 | return y; 26 | return euclideanGcdRecursive(y%x, x); 27 | } 28 | 29 | /* 30 | * Calculates GCD of two numbers a & b using the Recursive-based Extended 31 | * Euclidean Algorithm 32 | */ 33 | public void extendedGcd(long a, long b) { 34 | long gcd_rec = euclideanGcdRecursive(a,b); 35 | System.out.println("Extended_Recursive: GCD of " +a+ " & " +b+ " is : " +gcd_rec); 36 | long x = 0, y = 1, Prev_x = 1, Prev_y = 0, temp; 37 | while (b != 0) { 38 | long q = a / b; 39 | long r = a % b; 40 | a = b; 41 | b = r; 42 | temp = x; 43 | x = Prev_x - q * x; 44 | Prev_x = temp; 45 | temp = y; 46 | y = Prev_y - q * y; 47 | Prev_y = temp; 48 | } 49 | System.out.println("Roots x : "+ Prev_x +" y :"+ Prev_y); 50 | } 51 | 52 | public static void main (String[] args) { 53 | long a = 20; 54 | long b = 30; 55 | 56 | long gcd_div = euclideanGcdDivision(a, b); 57 | System.out.println("Division: GCD of " +a+ " & " +b+ " is : " + gcd_div); 58 | 59 | long gcd_rec = euclideanGcdRecursive(a, b); 60 | System.out.println("Recursive: GCD of " +a+ " & " +b+ " is : " + gcd_rec); 61 | 62 | euclidean_gcd obj = new euclidean_gcd(); 63 | obj.extendedGcd(a, b); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /Sorting Algorithms/Java/HeapSort.java: -------------------------------------------------------------------------------- 1 | public class HeapSort { 2 | public static void main(String[] args) { 3 | //My array of values 4 | int[] arr = new int[]{9, 8, 13, 2, 5, 22, 1315, 13, 4}; 5 | System.out.println("Array before sorting: "); 6 | printArray(arr); 7 | 8 | heapSortMethod(arr); 9 | System.out.println("Array after sorting: "); 10 | printArray(arr); 11 | } 12 | 13 | public static void printArray(int[] arr) { 14 | for (int i = 0; i < arr.length; i++) { 15 | System.out.print("Index " + i + " ="); 16 | System.out.print(arr[i] + "\t"); 17 | } 18 | System.out.println("\n"); 19 | 20 | } 21 | 22 | 23 | static void heapify(int[] array, int length, int i) { 24 | int leftChild = 2*i+1; 25 | int rightChild = 2*i+2; 26 | int largest = i; 27 | 28 | // if the left child is larger than parent 29 | if (leftChild < length && array[leftChild] > array[largest]) { 30 | largest = leftChild; 31 | } 32 | 33 | // if the right child is larger than parent 34 | if (rightChild < length && array[rightChild] > array[largest]) { 35 | largest = rightChild; 36 | } 37 | 38 | // if a swap needs to occur 39 | if (largest != i) { 40 | int temp = array[i]; 41 | array[i] = array[largest]; 42 | array[largest] = temp; 43 | heapify(array, length, largest); 44 | } 45 | } 46 | 47 | public static void heapSortMethod(int[] array) { 48 | if (array.length == 0) return; 49 | 50 | // Building the heap 51 | int length = array.length; 52 | // we're going from the first non-leaf to the root 53 | for (int i = length / 2-1; i >= 0; i--) 54 | heapify(array, length, i); 55 | 56 | for (int i = length-1; i >= 0; i--) { 57 | int temp = array[0]; 58 | array[0] = array[i]; 59 | array[i] = temp; 60 | 61 | heapify(array, i, 0); 62 | } 63 | } 64 | } -------------------------------------------------------------------------------- /Graph Algorithms/Cycle in undirected Graph.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | // Class for an undirected graph 7 | class Graph 8 | { 9 | int V; 10 | list *adj; 11 | bool isCyclicUtil(int v, bool visited[], int parent); 12 | public: 13 | Graph(int V); 14 | void addEdge(int v, int w); 15 | bool isCyclic(); 16 | 17 | Graph::Graph(int V) 18 | { 19 | this->V = V; 20 | adj = new list[V]; 21 | } 22 | 23 | void Graph::addEdge(int v, int w) 24 | { 25 | adj[v].push_back(w); // Add w to v’s list. 26 | adj[w].push_back(v); // Add v to w’s list. 27 | } 28 | 29 | // A recursive function that uses visited[] and parent to detect 30 | // cycle in subgraph reachable from vertex v. 31 | bool Graph::isCyclicUtil(int v, bool visited[], int parent) 32 | { 33 | 34 | visited[v] = true; 35 | 36 | list::iterator i; 37 | for (i = adj[v].begin(); i != adj[v].end(); ++i) 38 | { t 39 | if (!visited[*i]) 40 | { 41 | if (isCyclicUtil(*i, visited, v)) 42 | return true; 43 | } 44 | 45 | else if (*i != parent) 46 | return true; 47 | } 48 | return false; 49 | } 50 | 51 | bool Graph::isCyclic() 52 | { 53 | bool *visited = new bool[V]; 54 | for (int i = 0; i < V; i++) 55 | visited[i] = false; 56 | 57 | for (int u = 0; u < V; u++) 58 | if (!visited[u]) 59 | if (isCyclicUtil(u, visited, -1)) 60 | return true; 61 | 62 | return false; 63 | } 64 | 65 | // Driver program to test above functions 66 | int main() 67 | { 68 | Graph g1(5); 69 | g1.addEdge(1, 0); 70 | g1.addEdge(0, 2); 71 | g1.addEdge(2, 1); 72 | g1.addEdge(0, 3); 73 | g1.addEdge(3, 4); 74 | g1.isCyclic()? cout << "Graph contains cycle\n": 75 | cout << "Graph doesn't contain cycle\n"; 76 | 77 | Graph g2(3); 78 | g2.addEdge(0, 1); 79 | g2.addEdge(1, 2); 80 | g2.isCyclic()? cout << "Graph contains cycle\n": 81 | cout << "Graph doesn't contain cycle\n"; 82 | 83 | return 0; 84 | } 85 | -------------------------------------------------------------------------------- /Graph/SPATH.C: -------------------------------------------------------------------------------- 1 | /* SHORTEST PATH */ 2 | /* SPATH.C */ 3 | 4 | # include 5 | # define size 10 6 | # define infinity 9999 7 | 8 | int a[size][size]; 9 | int m[size][size]; 10 | int i,k,j; 11 | int n; 12 | 13 | void Input (); 14 | void Short (); 15 | void Output (); 16 | 17 | /* Input function */ 18 | 19 | void Input() 20 | { 21 | printf("\n Input the number of vetices: "); 22 | scanf("%d", &n); 23 | printf("\n Input adjacency matrix\n"); 24 | for (i = 0; i < n; i++) 25 | { 26 | for (j = 0; j < n; j++) 27 | { 28 | scanf("%d", &a[i][j]); 29 | } 30 | printf("\n"); 31 | } 32 | printf("\n Adjacency matrix \n"); 33 | for ( i = 0; i < n; i++) 34 | { 35 | for ( j = 0; j < n; j++) 36 | { 37 | printf(" %i", a[i][j]); 38 | } 39 | printf("\n"); 40 | } 41 | } 42 | 43 | /* Output function */ 44 | 45 | void Output() 46 | { 47 | for ( i = 0; i < n; i++) 48 | { 49 | for ( j = 0; j < n; j++) 50 | { 51 | printf(" %d", m[i][j]); 52 | } 53 | printf("\n"); 54 | } 55 | } 56 | 57 | /* Shortest path function */ 58 | 59 | void Short () 60 | { 61 | /* Initialization of matrix m */ 62 | 63 | for ( i = 0; i < n; i++) 64 | { 65 | for ( j = 0; j < n; j++) 66 | { 67 | if (a[i][j] == 0) 68 | m[i][j] = infinity; 69 | else 70 | m[i][j] = a[i][j]; 71 | } 72 | } 73 | printf("\n Adjacency matrix after replacing zeros by very large value"); 74 | Output(); 75 | 76 | /* Shortest path evaluation start from here */ 77 | 78 | for ( k = 0; k < n; k++) 79 | { 80 | for ( i = 0; i < n; i++) 81 | { 82 | for ( j = 0; j < n; j++) 83 | { 84 | if ( m [i][j] <= m [i][k] + m [k][j] ) 85 | m [i][j] = m [i][j]; 86 | else 87 | m [i][j] = m[i][k] + m [k][j]; 88 | } 89 | } 90 | printf("\n STEP %d \n", k); 91 | Output(); 92 | } 93 | } 94 | 95 | /* Function main */ 96 | 97 | int main() 98 | { 99 | Input(); 100 | Short(); 101 | printf("\n Shortest path matrix is as follows\n"); 102 | Output(); 103 | } 104 | 105 | -------------------------------------------------------------------------------- /Sorting Algorithms/C-CPP/radix_sort.cpp: -------------------------------------------------------------------------------- 1 | // C++ implementation of Radix Sort 2 | #include 3 | using namespace std; 4 | 5 | // A utility function to get maximum value in arr[] 6 | int getMax(int arr[], int n) 7 | { 8 | int mx = arr[0]; 9 | for (int i = 1; i < n; i++) 10 | if (arr[i] > mx) 11 | mx = arr[i]; 12 | return mx; 13 | } 14 | 15 | // A function to do counting sort of arr[] according to 16 | // the digit represented by exp. 17 | void countSort(int arr[], int n, int exp) 18 | { 19 | int output[n]; // output array 20 | int i, count[10] = {0}; 21 | 22 | // Store count of occurrences in count[] 23 | for (i = 0; i < n; i++) 24 | count[ (arr[i]/exp)%10 ]++; 25 | 26 | // Change count[i] so that count[i] now contains actual 27 | // position of this digit in output[] 28 | for (i = 1; i < 10; i++) 29 | count[i] += count[i - 1]; 30 | 31 | // Build the output array 32 | for (i = n - 1; i >= 0; i--) 33 | { 34 | output[count[ (arr[i]/exp)%10 ] - 1] = arr[i]; 35 | count[ (arr[i]/exp)%10 ]--; 36 | } 37 | 38 | // Copy the output array to arr[], so that arr[] now 39 | // contains sorted numbers according to current digit 40 | for (i = 0; i < n; i++) 41 | arr[i] = output[i]; 42 | } 43 | 44 | // The main function to that sorts arr[] of size n using 45 | // Radix Sort 46 | void radixsort(int arr[], int n) 47 | { 48 | // Find the maximum number to know number of digits 49 | int m = getMax(arr, n); 50 | 51 | // Do counting sort for every digit. Note that instead 52 | // of passing digit number, exp is passed. exp is 10^i 53 | // where i is current digit number 54 | for (int exp = 1; m/exp > 0; exp *= 10) 55 | countSort(arr, n, exp); 56 | } 57 | 58 | // A utility function to print an array 59 | void print(int arr[], int n) 60 | { 61 | for (int i = 0; i < n; i++) 62 | cout << arr[i] << " "; 63 | } 64 | 65 | // Driver program to test above functions 66 | int main() 67 | { 68 | int arr[] = {170, 45, 75, 90, 802, 24, 2, 66}; 69 | int n = sizeof(arr)/sizeof(arr[0]); 70 | radixsort(arr, n); 71 | print(arr, n); 72 | return 0; 73 | } 74 | -------------------------------------------------------------------------------- /Recursion/nQueen.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | char board[30][30]; 6 | 7 | void printBoard(char arr[][30], int n) { 8 | for (int r = 0; r < n; ++r) { 9 | for (int c = 0; c < n; ++c) { 10 | cout << arr[r][c] << " " ; 11 | } 12 | cout << endl; 13 | } 14 | } 15 | 16 | void initialiseBoard(int n) { 17 | for (int r = 0; r < n; ++r) { 18 | for (int c = 0; c < n; ++c) { 19 | board[r][c] = 'X'; 20 | } 21 | } 22 | } 23 | 24 | bool canPlace(char board[][30], int N, int x, int y) 25 | { 26 | //check the row if aqueen already exists 27 | for (int r = 0; r < N; ++r) 28 | { 29 | if (board[r][y] == 'Q') 30 | return false; 31 | } 32 | 33 | int rInc[] = { -1, +1, +1, -1}; 34 | int cInc[] = { -1, +1, -1, +1}; 35 | //check diagonal if queen already exists 36 | for (int dir = 0; dir < 4; ++dir) 37 | { 38 | int rowAdd = rInc[dir]; 39 | int colAdd = cInc[dir]; 40 | int r = x + rowAdd; 41 | int c = y + colAdd; 42 | //check that r c is within the board 43 | while (r >= 0 && r < N && c >= 0 && c < N) 44 | { 45 | if (board[r][c] == 'Q') 46 | return false; 47 | r = r + rowAdd; 48 | c = c + colAdd; 49 | } 50 | } 51 | return true; 52 | } 53 | 54 | bool nqueen(int r, int n) 55 | { 56 | if (r == n)//base case if all queens are placed 57 | { 58 | return true; 59 | } 60 | //for every column, use hit and trial by placing a queen in the each cell of curr Row 61 | for (int c = 0; c < n; ++c) 62 | { 63 | int x = r; 64 | int y = c; 65 | //check if queen can be placed on board[i][c] 66 | if (canPlace(board, n, x, y)==true) 67 | { 68 | board[x][y] = 'Q'; //place queen in each column 69 | bool isSuccessful = nqueen(r + 1, n); //recursion to place rest of queens 70 | if (isSuccessful == true) 71 | return true; 72 | board[x][y] = 'X'; //else unmark the cell or backtrack 73 | } 74 | } 75 | return false; //if queen cannot be placed in any row in this column then return false 76 | } 77 | 78 | int main() 79 | { 80 | int n; 81 | cin >> n; 82 | 83 | initialiseBoard(n);//initialse all the board with X 84 | bool isSuccessful = nqueen(0, n); 85 | 86 | if (isSuccessful) printBoard(board, n); 87 | else cout << "Sorry man! You need to have a larger board!\n"; 88 | 89 | return 0; 90 | } 91 | -------------------------------------------------------------------------------- /Binary Tree/Binary Tree Traversal.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | typedef struct cell{ 5 | int elem; 6 | struct cell * left; 7 | struct cell * right; 8 | }*Tree; 9 | 10 | void initTree(Tree *T); 11 | void insertTree(Tree *T, int elem); 12 | void displayInOrder(Tree T); 13 | void displayPreOrder(Tree T); 14 | void displayPostOrder(Tree T); 15 | void deleteTree(Tree *T, int elem); 16 | 17 | int main(void){ 18 | 19 | Tree T; 20 | initTree(&T); 21 | 22 | insertTree(&T, 50); 23 | insertTree(&T, 30); 24 | insertTree(&T, 20); 25 | insertTree(&T, 40); 26 | insertTree(&T, 70); 27 | insertTree(&T, 60); 28 | insertTree(&T, 80); 29 | 30 | 31 | printf("In Order: \n"); 32 | displayInOrder(T); 33 | 34 | printf("\n\nPre Order: \n"); 35 | displayPreOrder(T); 36 | 37 | printf("\n\nPost Order: \n"); 38 | displayPostOrder(T); 39 | 40 | // deleteTree(&T, 50); 41 | // printf("In Order: \n"); 42 | // displayInOrder(T); 43 | return 0; 44 | } 45 | 46 | void initTree(Tree *T){ 47 | *T = NULL; 48 | } 49 | 50 | void insertTree(Tree *T, int elem){ 51 | Tree temp, *trav; 52 | for(trav = T; *trav!=NULL && (*trav)->elem!=elem;){ 53 | trav = ((*trav)->elem < elem)? &(*trav)->right : &(*trav)->left; 54 | } 55 | 56 | if(*trav == NULL){ 57 | temp = (Tree)malloc(sizeof(struct cell)); 58 | if(temp!=NULL){ 59 | temp->elem = elem; 60 | temp->left = temp->right = NULL; 61 | *trav = temp; 62 | } 63 | } 64 | } 65 | 66 | 67 | void displayInOrder(Tree T){ 68 | if(T!=NULL){ 69 | displayInOrder(T->left); 70 | printf("\n%d\n", T->elem); 71 | displayInOrder(T->right); 72 | } 73 | } 74 | 75 | void displayPreOrder(Tree T){ 76 | if(T!=NULL){ 77 | printf("\n%d\n", T->elem); 78 | displayPreOrder(T->left); 79 | displayPreOrder(T->right); 80 | } 81 | } 82 | 83 | void displayPostOrder(Tree T){ 84 | if(T!=NULL){ 85 | displayPostOrder(T->left); 86 | displayPostOrder(T->right); 87 | printf("\n%d\n", T->elem); 88 | } 89 | } 90 | 91 | void deleteTree(Tree *T, int elem){ 92 | Tree *trav, temp; 93 | for (trav = T; *trav != NULL && (*trav)->elem != elem; ){ 94 | if ((*trav)->elem > elem) { 95 | trav = &(*trav)-> left; 96 | } else { 97 | trav = &(*trav)-> right; 98 | } 99 | // trav = ((*trav)->elem > elem ) ? &(*trav)-> left : &(*trav)-> right 100 | } 101 | 102 | if (*trav != NULL) { 103 | temp = *trav; 104 | if ((*trav)->right == NULL) { 105 | *trav = (*trav)->left; 106 | } else if ((*trav)->left == NULL) { 107 | *trav = (*trav)->right; 108 | } else if ((*trav)->right != NULL && (*trav)->left != NULL){ 109 | for (trav = &(*trav)->left; (*trav)->right != NULL; trav = &(*trav)->right) {} 110 | temp->elem = (*trav)->elem; 111 | temp = *trav; 112 | *trav = temp->left; 113 | } 114 | free(temp); 115 | } 116 | 117 | } 118 | -------------------------------------------------------------------------------- /Backtracking/mColor.java: -------------------------------------------------------------------------------- 1 | /* Java program for solution of M Coloring problem 2 | using backtracking */ 3 | public class mColoringProblem { 4 | final int V = 4; 5 | int color[]; 6 | 7 | /* A utility function to check if the current 8 | color assignment is safe for vertex v */ 9 | boolean isSafe(int v, int graph[][], int color[], 10 | int c) 11 | { 12 | for (int i = 0; i < V; i++) 13 | if (graph[v][i] == 1 && c == color[i]) 14 | return false; 15 | return true; 16 | } 17 | 18 | /* A recursive utility function to solve m 19 | coloring problem */ 20 | boolean graphColoringUtil(int graph[][], int m, 21 | int color[], int v) 22 | { 23 | /* base case: If all vertices are assigned 24 | a color then return true */ 25 | if (v == V) 26 | return true; 27 | 28 | /* Consider this vertex v and try different 29 | colors */ 30 | for (int c = 1; c <= m; c++) 31 | { 32 | /* Check if assignment of color c to v 33 | is fine*/ 34 | if (isSafe(v, graph, color, c)) 35 | { 36 | color[v] = c; 37 | 38 | /* recur to assign colors to rest 39 | of the vertices */ 40 | if (graphColoringUtil(graph, m, 41 | color, v + 1)) 42 | return true; 43 | 44 | /* If assigning color c doesn't lead 45 | to a solution then remove it */ 46 | color[v] = 0; 47 | } 48 | } 49 | 50 | /* If no color can be assigned to this vertex 51 | then return false */ 52 | return false; 53 | } 54 | 55 | /* This function solves the m Coloring problem using 56 | Backtracking. It mainly uses graphColoringUtil() 57 | to solve the problem. It returns false if the m 58 | colors cannot be assigned, otherwise return true 59 | and prints assignments of colors to all vertices. 60 | Please note that there may be more than one 61 | solutions, this function prints one of the 62 | feasible solutions.*/ 63 | boolean graphColoring(int graph[][], int m) 64 | { 65 | // Initialize all color values as 0. This 66 | // initialization is needed correct functioning 67 | // of isSafe() 68 | color = new int[V]; 69 | for (int i = 0; i < V; i++) 70 | color[i] = 0; 71 | 72 | // Call graphColoringUtil() for vertex 0 73 | if (!graphColoringUtil(graph, m, color, 0)) 74 | { 75 | System.out.println("Solution does not exist"); 76 | return false; 77 | } 78 | 79 | // Print the solution 80 | printSolution(color); 81 | return true; 82 | } 83 | 84 | /* A utility function to print solution */ 85 | void printSolution(int color[]) 86 | { 87 | System.out.println("Solution Exists: Following" + 88 | " are the assigned colors"); 89 | for (int i = 0; i < V; i++) 90 | System.out.print(" " + color[i] + " "); 91 | System.out.println(); 92 | } 93 | 94 | // driver program to test above function 95 | public static void main(String args[]) 96 | { 97 | mColoringProblem Coloring = new mColoringProblem(); 98 | /* Create following graph and test whether it is 99 | 3 colorable 100 | (3)---(2) 101 | | / | 102 | | / | 103 | | / | 104 | (0)---(1) 105 | */ 106 | int graph[][] = {{0, 1, 1, 1}, 107 | {1, 0, 1, 0}, 108 | {1, 1, 0, 1}, 109 | {1, 0, 1, 0}, 110 | }; 111 | int m = 3; // Number of colors 112 | Coloring.graphColoring(graph, m); 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /Sorting Algorithms/Java/MergeSort.java: -------------------------------------------------------------------------------- 1 | public class MergeSort{ 2 | 3 | public static void main(String[] args){ 4 | int[] arr = new int[]{9,8,13,2,5,22,1315,13,4}; 5 | System.out.println("Array before sorting: "); 6 | for(int i = 0; i < arr.length; i++){ 7 | System.out.print(arr[i] + " "); 8 | } 9 | System.out.println(""); 10 | mergeSort(arr); 11 | System.out.println("Array after sorting: "); 12 | for(int i = 0; i < arr.length; i++){ 13 | System.out.print(arr[i]+" "); 14 | } 15 | System.out.println(""); 16 | 17 | } 18 | 19 | // Feed initial array into a helper function that calls real MergeSort (through Overloading) 20 | public static void mergeSort(int[] arr){ 21 | mergeSort(arr, new int[arr.length], 0, arr.length-1); 22 | } 23 | 24 | public static void mergeSort(int[] arr, int[] temp, int start, int end){ 25 | // Once each element is isolated, return to start actually sorting 26 | if(start >= end){ 27 | return; 28 | } 29 | 30 | // Calculate Middle Index 31 | int middle = (start+end) / 2; 32 | 33 | // Make a recursive call to use mergeSort on the first half of array 34 | mergeSort(arr, temp, start, middle); 35 | 36 | // Make a recursive call to use mergeSort on the second half of array 37 | mergeSort(arr, temp, middle+1, end); 38 | 39 | // Call mergeHalves to merge the two together 40 | mergeHalves(arr, temp, start, end); 41 | } 42 | 43 | // Helper method that does the heavy lifting of sorting halves 44 | public static void mergeHalves(int[] arr, int[] temp, int leftStart, int rightEnd){ 45 | 46 | // Calculate the end of the first array, and the start of the second array 47 | int leftEnd = (rightEnd + leftStart)/2; 48 | int rightStart = leftEnd+1; 49 | 50 | // Calculate the overall size of the merged subarray 51 | int size = rightEnd-leftStart + 1; 52 | 53 | // Initialize pointers for each index 54 | int left = leftStart; 55 | int right = rightStart; 56 | int index = leftStart; 57 | 58 | // While the pointers for right and left subarrays haven't hit their end, 59 | // Compare the values 60 | while(left <= leftEnd && right <= rightEnd){ 61 | 62 | // If the left index is smaller than the right index, set the temp index to that value and increment left 63 | // Otherwise, do the same with right. After both, increment index. 64 | if(arr[left] <= arr[right]){ 65 | temp[index] = arr[left]; 66 | left++; 67 | } else { 68 | temp[index] = arr[right]; 69 | right++; 70 | } 71 | index++; 72 | } 73 | 74 | // Java library function for copying parts of an array into another 75 | // Out of the two following calls, ONLY ONE will take effect since 76 | // one the pointers should have reached it's end 77 | System.arraycopy(arr, left, temp, index, leftEnd-left+1); 78 | System.arraycopy(arr, right, temp, index, rightEnd-right+1); 79 | 80 | // Copy the values from the temp array into the original. 81 | System.arraycopy(temp, leftStart, arr, leftStart, size); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /Cryptography Algorithms/Python/OneTimePad.py: -------------------------------------------------------------------------------- 1 | import string 2 | import random 3 | 4 | key = '' 5 | encrypted_text = [] 6 | bin_key = [] 7 | 8 | def bin_to_str(binary): 9 | binary = str(binary) 10 | character = '' 11 | char = '' 12 | size = len(binary) 13 | k = 1 14 | for j in binary: 15 | if j != ' ': 16 | character += j 17 | if k == size: 18 | char += chr(int(character, 2)) 19 | else: 20 | char += chr(int(character, 2)) 21 | character = '' 22 | k += 1 23 | return char 24 | 25 | def str_to_bin(string): 26 | binary = '' 27 | for i in string: 28 | binary += bin(ord(i))[2::] + ' ' 29 | return binary 30 | 31 | def print_layout_name(name): 32 | print("\n+==================================================================+") 33 | print(" ",name,"\n+==================================================================+") 34 | 35 | def print_menu(): 36 | print_layout_name("ONE-TIME PAD") 37 | print("\n 1 - Encrypt\n 2 - Decrypt\n 0 - Exit\n") 38 | 39 | def generator_key(size): 40 | return ''.join(random.choice(string.ascii_letters) for x in range(size)) 41 | 42 | def select_option(option): 43 | if option == 1: 44 | encrypt() 45 | if option == 2: 46 | decrypt() 47 | if option == 0: 48 | exit(0) 49 | 50 | def encrypt_with_a_key(key, text): 51 | bits_key = key.split(' ') 52 | bits_text = text.split(' ') 53 | del(bits_key[-1]) 54 | del(bits_text[-1]) 55 | result = [] 56 | for i in range(len(bits_text)): 57 | result.append( str( bin( int(bits_text[i],2) ^ int(bits_key[i],2) )[2::] ) ) 58 | return result 59 | 60 | def encrypt(): 61 | global key, binary_key, encrypted_text, bin_key 62 | plain_text = str(input(" Enter the plain text: ")) 63 | binary_text = str_to_bin(plain_text) 64 | key = generator_key(len(plain_text)) 65 | print("\n Key: ", key) 66 | binary_key = str_to_bin(key) 67 | print("\n Binary Key: ", binary_key) 68 | encrypted_text = encrypt_with_a_key(binary_key, binary_text) 69 | bin_key = binary_key.split(' ') 70 | del(bin_key[-1]) 71 | print("\n Encrypted Message: ", encrypted_text) 72 | 73 | def decrypt(): 74 | global key, bin_key, encrypted_text 75 | plain_text = [] 76 | decrypted_text = [] 77 | if(key != ''): 78 | print("\n Binary Plain Text: ", end="") 79 | for i in range( len(encrypted_text) ): 80 | decrypted_text.append( bin( int(bin_key[i],2) ^ int(encrypted_text[i],2) )[2::] ) 81 | print(decrypted_text[i], " " ,end="") 82 | print("\n\n Decrypted Message: ", end="") 83 | for j in range(len(decrypted_text)): 84 | plain_text.append( bin_to_str( decrypted_text[j] )) 85 | print(plain_text[j], end="" ) 86 | print("\n") 87 | else: 88 | print("\n No keys stored in memory") 89 | 90 | def main(): 91 | print_menu() 92 | option = int(input(" Select an option: ")) 93 | select_option(option) 94 | while(option != 0): 95 | print_menu() 96 | option = int(input(" Select an option: ")) 97 | select_option(option) 98 | 99 | main() 100 | -------------------------------------------------------------------------------- /Greedy Algorithms/Prims.java: -------------------------------------------------------------------------------- 1 | // A Java program for Prim's Minimum Spanning Tree (MST) algorithm. 2 | // The program is for adjacency matrix representation of the graph 3 | 4 | import java.util.*; 5 | import java.lang.*; 6 | import java.io.*; 7 | 8 | class MST { 9 | // Number of vertices in the graph 10 | private static final int V = 5; 11 | 12 | // A utility function to find the vertex with minimum key 13 | // value, from the set of vertices not yet included in MST 14 | int minKey(int key[], Boolean mstSet[]) 15 | { 16 | // Initialize min value 17 | int min = Integer.MAX_VALUE, min_index = -1; 18 | 19 | for (int v = 0; v < V; v++) 20 | if (mstSet[v] == false && key[v] < min) { 21 | min = key[v]; 22 | min_index = v; 23 | } 24 | 25 | return min_index; 26 | } 27 | 28 | // A utility function to print the constructed MST stored in 29 | // parent[] 30 | void printMST(int parent[], int graph[][]) 31 | { 32 | System.out.println("Edge \tWeight"); 33 | for (int i = 1; i < V; i++) 34 | System.out.println(parent[i] + " - " + i + "\t" + graph[i][parent[i]]); 35 | } 36 | 37 | // Function to construct and print MST for a graph represented 38 | // using adjacency matrix representation 39 | void primMST(int graph[][]) 40 | { 41 | // Array to store constructed MST 42 | int parent[] = new int[V]; 43 | 44 | // Key values used to pick minimum weight edge in cut 45 | int key[] = new int[V]; 46 | 47 | // To represent set of vertices not yet included in MST 48 | Boolean mstSet[] = new Boolean[V]; 49 | 50 | // Initialize all keys as INFINITE 51 | for (int i = 0; i < V; i++) { 52 | key[i] = Integer.MAX_VALUE; 53 | mstSet[i] = false; 54 | } 55 | 56 | // Always include first 1st vertex in MST. 57 | key[0] = 0; // Make key 0 so that this vertex is 58 | // picked as first vertex 59 | parent[0] = -1; // First node is always root of MST 60 | 61 | // The MST will have V vertices 62 | for (int count = 0; count < V - 1; count++) { 63 | // Pick thd minimum key vertex from the set of vertices 64 | // not yet included in MST 65 | int u = minKey(key, mstSet); 66 | 67 | // Add the picked vertex to the MST Set 68 | mstSet[u] = true; 69 | 70 | // Update key value and parent index of the adjacent 71 | // vertices of the picked vertex. Consider only those 72 | // vertices which are not yet included in MST 73 | for (int v = 0; v < V; v++) 74 | 75 | // graph[u][v] is non zero only for adjacent vertices of m 76 | // mstSet[v] is false for vertices not yet included in MST 77 | // Update the key only if graph[u][v] is smaller than key[v] 78 | if (graph[u][v] != 0 && mstSet[v] == false && graph[u][v] < key[v]) { 79 | parent[v] = u; 80 | key[v] = graph[u][v]; 81 | } 82 | } 83 | 84 | // print the constructed MST 85 | printMST(parent, graph); 86 | } 87 | 88 | public static void main(String[] args) 89 | { 90 | /* Let us create the following graph 91 | 2 3 92 | (0)--(1)--(2) 93 | | / \ | 94 | 6| 8/ \5 |7 95 | | / \ | 96 | (3)-------(4) 97 | 9 */ 98 | MST t = new MST(); 99 | int graph[][] = new int[][] { { 0, 2, 0, 6, 0 }, 100 | { 2, 0, 3, 8, 5 }, 101 | { 0, 3, 0, 0, 7 }, 102 | { 6, 8, 0, 0, 9 }, 103 | { 0, 5, 7, 9, 0 } }; 104 | 105 | // Print the solution 106 | t.primMST(graph); 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /Graph Algorithms/Dijikstras.java: -------------------------------------------------------------------------------- 1 | // Java implementation of Dijkstra's Algorithm 2 | // using Priority Queue 3 | import java.util.*; 4 | public class DPQ { 5 | private int dist[]; 6 | private Set settled; 7 | private PriorityQueue pq; 8 | private int V; // Number of vertices 9 | List > adj; 10 | 11 | public DPQ(int V) 12 | { 13 | this.V = V; 14 | dist = new int[V]; 15 | settled = new HashSet(); 16 | pq = new PriorityQueue(V, new Node()); 17 | } 18 | 19 | // Function for Dijkstra's Algorithm 20 | public void dijkstra(List > adj, int src) 21 | { 22 | this.adj = adj; 23 | 24 | for (int i = 0; i < V; i++) 25 | dist[i] = Integer.MAX_VALUE; 26 | 27 | // Add source node to the priority queue 28 | pq.add(new Node(src, 0)); 29 | 30 | // Distance to the source is 0 31 | dist[src] = 0; 32 | while (settled.size() != V) { 33 | 34 | // remove the minimum distance node 35 | // from the priority queue 36 | int u = pq.remove().node; 37 | 38 | // adding the node whose distance is 39 | // finalized 40 | settled.add(u); 41 | 42 | e_Neighbours(u); 43 | } 44 | } 45 | 46 | // Function to process all the neighbours 47 | // of the passed node 48 | private void e_Neighbours(int u) 49 | { 50 | int edgeDistance = -1; 51 | int newDistance = -1; 52 | 53 | // All the neighbors of v 54 | for (int i = 0; i < adj.get(u).size(); i++) { 55 | Node v = adj.get(u).get(i); 56 | 57 | // If current node hasn't already been processed 58 | if (!settled.contains(v.node)) { 59 | edgeDistance = v.cost; 60 | newDistance = dist[u] + edgeDistance; 61 | 62 | // If new distance is cheaper in cost 63 | if (newDistance < dist[v.node]) 64 | dist[v.node] = newDistance; 65 | 66 | // Add the current node to the queue 67 | pq.add(new Node(v.node, dist[v.node])); 68 | } 69 | } 70 | } 71 | 72 | // Driver code 73 | public static void main(String arg[]) 74 | { 75 | int V = 5; 76 | int source = 0; 77 | 78 | // Adjacency list representation of the 79 | // connected edges 80 | List > adj = new ArrayList >(); 81 | 82 | // Initialize list for every node 83 | for (int i = 0; i < V; i++) { 84 | List item = new ArrayList(); 85 | adj.add(item); 86 | } 87 | 88 | // Inputs for the DPQ graph 89 | adj.get(0).add(new Node(1, 9)); 90 | adj.get(0).add(new Node(2, 6)); 91 | adj.get(0).add(new Node(3, 5)); 92 | adj.get(0).add(new Node(4, 3)); 93 | 94 | adj.get(2).add(new Node(1, 2)); 95 | adj.get(2).add(new Node(3, 4)); 96 | 97 | // Calculate the single source shortest path 98 | DPQ dpq = new DPQ(V); 99 | dpq.dijkstra(adj, source); 100 | 101 | // Print the shortest path to all the nodes 102 | // from the source node 103 | System.out.println("The shorted path from node :"); 104 | for (int i = 0; i < dpq.dist.length; i++) 105 | System.out.println(source + " to " + i + " is " 106 | + dpq.dist[i]); 107 | } 108 | } 109 | 110 | // Class to represent a node in the graph 111 | class Node implements Comparator { 112 | public int node; 113 | public int cost; 114 | 115 | public Node() 116 | { 117 | } 118 | 119 | public Node(int node, int cost) 120 | { 121 | this.node = node; 122 | this.cost = cost; 123 | } 124 | 125 | @Override 126 | public int compare(Node node1, Node node2) 127 | { 128 | if (node1.cost < node2.cost) 129 | return -1; 130 | if (node1.cost > node2.cost) 131 | return 1; 132 | return 0; 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /Search Algorithms/C-CPP/jump_search.c: -------------------------------------------------------------------------------- 1 | //u have to enter sorted array or have to sort by any method convinient to you 2 | #include 3 | #include 4 | #include 5 | 6 | int jumpsearch(int *a,int n,int x) 7 | { 8 | int temp,j=-1; 9 | int jumpstep=sqrt(n);//step to be jumped to serach a number 10 | while(a[jumpstep-1]n) 14 | {break;} 15 | } 16 | temp=jumpstep; 17 | jumpstep-=sqrt(n); 18 | while(a[temp-1]!=x) 19 | { 20 | temp--; 21 | if(temp==jumpstep) 22 | break; 23 | } 24 | if(a[temp-1]==x) 25 | { 26 | j=temp-1;//u have to enter sorted array or have to sort by any method convinient to you 27 | #include 28 | #include 29 | #include 30 | 31 | int jumpsearch(int *a,int n,int x) 32 | { 33 | int temp,j=-1; 34 | int jumpstep=sqrt(n);//step to be jumped to serach a number 35 | while(a[jumpstep-1]n) 39 | {break;} 40 | } 41 | temp=jumpstep; 42 | jumpstep-=sqrt(n); 43 | while(a[temp-1]!=x) 44 | { 45 | temp--; 46 | if(temp==jumpstep) 47 | break; 48 | }//u have to enter sorted array or have to sort by any method convinient to you 49 | #include 50 | #include 51 | #include 52 | 53 | int jumpsearch(int *a,int n,int x) 54 | { 55 | int temp,j=-1; 56 | int jumpstep=sqrt(n);//step to be jumped to serach a number 57 | while(a[jumpstep-1]n) 61 | {break;} 62 | } 63 | temp=jumpstep; 64 | jumpstep-=sqrt(n); 65 | while(a[temp-1]!=x) 66 | { 67 | temp--; 68 | if(temp==jumpstep) 69 | break; 70 | } 71 | if(a[temp-1]==x) 72 | { 73 | j=temp-1; 74 | } 75 | return j; 76 | } 77 | 78 | void main() 79 | { 80 | int *a,n,i,j; 81 | printf("how many number u want to enter :\n"); 82 | scanf("%d",&n); 83 | a=(int *)malloc(sizeof(int)*n); 84 | printf("enter numbers:\n"); 85 | for(i=0;i 2 | 3 | 4 | struct Edge { 5 | int src, dest, weight; 6 | }; 7 | 8 | 9 | struct Graph { 10 | // V-> Number of vertices, E-> Number of edges 11 | int V, E; 12 | 13 | 14 | struct Edge* edge; 15 | }; 16 | 17 | 18 | struct Graph* createGraph(int V, int E) 19 | { 20 | struct Graph* graph = new Graph; 21 | graph->V = V; 22 | graph->E = E; 23 | graph->edge = new Edge[E]; 24 | return graph; 25 | } 26 | 27 | 28 | void printArr(int dist[], int n) 29 | { 30 | printf("Vertex Distance from Source\n"); 31 | for (int i = 0; i < n; ++i) 32 | printf("%d \t\t %d\n", i, dist[i]); 33 | } 34 | 35 | // The main function that finds shortest distances from src to 36 | // all other vertices using Bellman-Ford algorithm. The function 37 | // also detects negative weight cycle 38 | void BellmanFord(struct Graph* graph, int src) 39 | { 40 | int V = graph->V; 41 | int E = graph->E; 42 | int dist[V]; 43 | 44 | // Step 1: Initialize distances from src to all other vertices 45 | // as INFINITE 46 | for (int i = 0; i < V; i++) 47 | dist[i] = INT_MAX; 48 | dist[src] = 0; 49 | 50 | // Step 2: Relax all edges |V| - 1 times. A simple shortest 51 | // path from src to any other vertex can have at-most |V| - 1 52 | // edges 53 | for (int i = 1; i <= V - 1; i++) { 54 | for (int j = 0; j < E; j++) { 55 | int u = graph->edge[j].src; 56 | int v = graph->edge[j].dest; 57 | int weight = graph->edge[j].weight; 58 | if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) 59 | dist[v] = dist[u] + weight; 60 | } 61 | } 62 | 63 | // Step 3: check for negative-weight cycles. The above step 64 | // guarantees shortest distances if graph doesn't contain 65 | // negative weight cycle. If we get a shorter path, then there 66 | // is a cycle. 67 | for (int i = 0; i < E; i++) { 68 | int u = graph->edge[i].src; 69 | int v = graph->edge[i].dest; 70 | int weight = graph->edge[i].weight; 71 | if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) { 72 | printf("Graph contains negative weight cycle"); 73 | return; // If negative cycle is detected, simply return 74 | } 75 | } 76 | 77 | printArr(dist, V); 78 | 79 | return; 80 | } 81 | 82 | // Driver program to test above functions 83 | int main() 84 | { 85 | 86 | int V = 5; // Number of vertices in graph 87 | int E = 8; // Number of edges in graph 88 | struct Graph* graph = createGraph(V, E); 89 | 90 | 91 | graph->edge[0].src = 0; 92 | graph->edge[0].dest = 1; 93 | graph->edge[0].weight = -1; 94 | 95 | 96 | graph->edge[1].src = 0; 97 | graph->edge[1].dest = 2; 98 | graph->edge[1].weight = 4; 99 | 100 | 101 | graph->edge[2].src = 1; 102 | graph->edge[2].dest = 2; 103 | graph->edge[2].weight = 3; 104 | 105 | 106 | graph->edge[3].src = 1; 107 | graph->edge[3].dest = 3; 108 | graph->edge[3].weight = 2; 109 | 110 | 111 | graph->edge[4].src = 1; 112 | graph->edge[4].dest = 4; 113 | graph->edge[4].weight = 2; 114 | 115 | 116 | graph->edge[5].src = 3; 117 | graph->edge[5].dest = 2; 118 | graph->edge[5].weight = 5; 119 | 120 | 121 | graph->edge[6].src = 3; 122 | graph->edge[6].dest = 1; 123 | graph->edge[6].weight = 1; 124 | 125 | 126 | graph->edge[7].src = 4; 127 | graph->edge[7].dest = 3; 128 | graph->edge[7].weight = -3; 129 | 130 | BellmanFord(graph, 0); 131 | 132 | return 0; 133 | } 134 | -------------------------------------------------------------------------------- /Graph Algorithms/fleury.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | Input example: 6 | 5 7 | 0 1 1 1 1 8 | 1 0 1 1 0 9 | 1 1 0 1 0 10 | 1 1 1 0 1 11 | 1 0 0 1 0 12 | */ 13 | 14 | struct Graph{ 15 | int vert; 16 | int ** adjMatrix; 17 | }; 18 | 19 | Graph readGraph(); 20 | void showGraph(Graph* graph); 21 | int findStartVert(Graph* graph); 22 | void fleury(Graph* graph); 23 | void eulerPath(Graph* graph, int start); 24 | int isValidNextEdge(Graph* graph, int u,int v); 25 | void removeEdge(Graph* graph, int u,int v); 26 | void addEdge(Graph* graph, int u,int v); 27 | int dfsCount(Graph* graph,int u, int visited[]); 28 | void showPath(); 29 | vector path; 30 | 31 | int main(){ 32 | Graph graph = readGraph(); 33 | showGraph(&graph); 34 | fleury(&graph); 35 | showPath(); 36 | } 37 | 38 | Graph readGraph(){ 39 | Graph graph; 40 | int vert; 41 | cin >> vert; 42 | int ** matrix =new int*[vert]; 43 | for(int i=0; ivert<vert; i++){ 59 | for(int j=0; jvert; j++){ 60 | cout<< graph->adjMatrix[i][j]; 61 | } 62 | cout<"; 72 | } 73 | cout<vert ;i++){ 85 | if(graph->adjMatrix[vert][i]!=0 && isValidNextEdge(graph,vert,i)==1){ 86 | path.push_back(i); 87 | removeEdge(graph,vert,i); 88 | eulerPath(graph,i); 89 | } 90 | } 91 | } 92 | 93 | int isValidNextEdge(Graph* graph, int u,int v){ 94 | int degree=0; 95 | for(int i=0; i< graph->vert; i++){ 96 | if(graph->adjMatrix[u][i]==1) 97 | degree++; 98 | } 99 | if(degree == 1) 100 | return 1; 101 | 102 | int visited[graph->vert]; 103 | memset(visited,0,sizeof(visited)); 104 | for(int j=0;j<5;j++){ 105 | } 106 | int count1 = dfsCount(graph,u,visited); 107 | 108 | removeEdge(graph,u,v); 109 | memset(visited,0,sizeof(visited)); 110 | int count2 = dfsCount(graph,u,visited); 111 | addEdge(graph,u,v); 112 | 113 | if(count1 > count2) 114 | return 0; 115 | return 1; 116 | 117 | } 118 | 119 | int findStartVert(Graph* graph){ 120 | int cur = 0; 121 | for(int i=0; i< graph->vert; i++){ 122 | int degree=0; 123 | for(int j=0; j< graph->vert; j++){ 124 | if(graph->adjMatrix[i][j]==1) 125 | degree++; 126 | } 127 | if(degree%2!=0) 128 | return i; 129 | } 130 | return 0; 131 | } 132 | 133 | void removeEdge(Graph* graph, int u,int v){ 134 | graph->adjMatrix[u][v] = 0; 135 | graph->adjMatrix[v][u] = 0; 136 | } 137 | 138 | void addEdge(Graph* graph, int u,int v){ 139 | graph->adjMatrix[u][v] = 1; 140 | graph->adjMatrix[v][u] = 1; 141 | } 142 | 143 | int dfsCount(Graph* graph, int u, int visited[]){ 144 | visited[u] = 1; 145 | int count =1; 146 | for(int j=0;j<5;j++){ 147 | } 148 | for(int i=0; i< graph->vert; i++){ 149 | if(graph->adjMatrix[i][u]==1 && visited[i]==0) 150 | count += dfsCount(graph, i, visited); 151 | } 152 | return count; 153 | 154 | } 155 | -------------------------------------------------------------------------------- /Huffman_Coding/Huffman_Coding.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include //For pair<> 3 | #include 4 | #include //For Sorting 5 | #include 6 | #include 7 | 8 | struct TreeNode{ 9 | char c; //character 10 | int freq; //frequency 11 | int val; //Value: either 0 or 1 according to the node is left or right child 12 | bool leaf; //True if node is leaf node 13 | struct TreeNode* parent; //Pointer to parent node 14 | struct TreeNode* right; //Pointer to right child 15 | struct TreeNode* left; //Pointer to left child 16 | }; 17 | 18 | bool MyFunction(TreeNode* t1,TreeNode* t2){ //User-Defined Function to sort TreeNodes in descending order... 19 | return t1->freq > t2->freq ; //...according to it's Frequency 20 | } 21 | 22 | int main() { 23 | 24 | std::cout << "Enter Sentence to encode : "; 25 | std::string s; 26 | std::getline(std::cin,s); 27 | 28 | std::map Frequency; //Map<> to count Frequency of Characters in String 29 | std::vector Characters; //To store unique Characters in String 30 | 31 | for(int i=0;i New Character hence we will add it to 33 | Characters.push_back(s[i]); //"Character vector" which stores unique Characters 34 | } 35 | ++Frequency[s[i]]; 36 | } 37 | 38 | std::vector Cnf; //Vector to store TreeNode pointers 39 | 40 | for(int i=0;ic = Characters[i]; 43 | temp->freq = Frequency[Characters[i]]; 44 | temp->leaf = true; 45 | Cnf.push_back(temp); 46 | } 47 | 48 | sort(Cnf.begin(),Cnf.end(),MyFunction); //Sorting according to frequency of characters 49 | 50 | std::vector ref; //Vector to store all leaf nodes, so we can generate codes for them at last 51 | 52 | while(Cnf.size()!=1){ 53 | 54 | struct TreeNode* t1 = Cnf.back(); //Extracting two nodes with less frequency 55 | Cnf.pop_back(); 56 | struct TreeNode* t2 = Cnf.back(); 57 | Cnf.pop_back(); 58 | 59 | struct TreeNode* nw = new TreeNode; 60 | 61 | if(t1->freq < t2->freq){ //Assign value=0 to minimum frequency node and make it left child of 62 | nw->right = t2; //newly created node 63 | t2->val = 1; //Assign value=1 to other node and make it right child of newly created node 64 | nw->left = t1; 65 | t1->val = 0; 66 | } 67 | else{ 68 | nw->right = t1; 69 | t1->val = 1; 70 | nw->left = t2; 71 | t2->val = 0; 72 | } 73 | 74 | nw->leaf = false; 75 | nw->freq = t1->freq + t2->freq; 76 | nw->parent = NULL; 77 | 78 | t1->parent = t2->parent = nw; 79 | 80 | if(t1->leaf){ //Store leaf nodes in "Ref Vector" 81 | ref.push_back(t1); 82 | } 83 | if(t2->leaf){ 84 | ref.push_back(t2); 85 | } 86 | 87 | Cnf.push_back(nw); 88 | sort(Cnf.begin(),Cnf.end(),MyFunction); 89 | } 90 | 91 | std::cout << "Huffman Codes : " << '\n'; //Display Codes of all leaf nodes 92 | while(ref.size()){ 93 | struct TreeNode* temp = ref.back(); 94 | ref.pop_back(); 95 | std::cout << "\nChar : " << temp->c << "\nFrequency : "<< temp->freq << "\nCode : "; 96 | std::string s = ""; 97 | while(temp->parent!=NULL){ 98 | s += temp->val + '0'; 99 | temp = temp->parent; 100 | } 101 | reverse(s.begin(),s.end()); 102 | std::cout << s << '\n'; 103 | std::cout<<"\n"; 104 | } 105 | return 0; 106 | } 107 | -------------------------------------------------------------------------------- /Graph Algorithms/Dial's algorithm.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | # define INF 0x3f3f3f3f 5 | 6 | class Graph 7 | { 8 | int V; // No. of vertices 9 | 10 | 11 | list< pair > *adj; 12 | 13 | public: 14 | Graph(int V); // Constructor 15 | 16 | 17 | void addEdge(int u, int v, int w); 18 | 19 | 20 | void shortestPath(int s, int W); 21 | }; 22 | 23 | // Allocates memory for adjacency list 24 | Graph::Graph(int V) 25 | { 26 | this->V = V; 27 | adj = new list< pair >[V]; 28 | } 29 | 30 | // adds edge between u and v of weight w 31 | void Graph::addEdge(int u, int v, int w) 32 | { 33 | adj[u].push_back(make_pair(v, w)); 34 | adj[v].push_back(make_pair(u, w)); 35 | } 36 | 37 | // Prints shortest paths from src to all other vertices. 38 | // W is the maximum weight of an edge 39 | void Graph::shortestPath(int src, int W) 40 | { 41 | vector::iterator> > dist(V); 42 | 43 | // Initialize all distances as infinite (INF) 44 | for (int i = 0; i < V; i++) 45 | dist[i].first = INF; 46 | 47 | // Create buckets B[]. 48 | // B[i] keep vertex of distance label i 49 | list B[W * V + 1]; 50 | 51 | B[0].push_back(src); 52 | dist[src].first = 0; 53 | 54 | // 55 | int idx = 0; 56 | while (1) 57 | { 58 | // Go sequentially through buckets till one non-empty 59 | // bucket is found 60 | while (B[idx].size() == 0 && idx < W*V) 61 | idx++; 62 | 63 | // If all buckets are empty, we are done. 64 | if (idx == W * V) 65 | break; 66 | 67 | // Take top vertex from bucket and pop it 68 | int u = B[idx].front(); 69 | B[idx].pop_front(); 70 | 71 | // Process all adjacents of extracted vertex 'u' and 72 | // update their distanced if required. 73 | for (auto i = adj[u].begin(); i != adj[u].end(); ++i) 74 | { 75 | int v = (*i).first; 76 | int weight = (*i).second; 77 | 78 | int du = dist[u].first; 79 | int dv = dist[v].first; 80 | 81 | // If there is shorted path to v through u. 82 | if (dv > du + weight) 83 | { 84 | // If dv is not INF then it must be in B[dv] 85 | // bucket, so erase its entry using iterator 86 | // in O(1) 87 | if (dv != INF) 88 | B[dv].erase(dist[v].second); 89 | 90 | // updating the distance 91 | dist[v].first = du + weight; 92 | dv = dist[v].first; 93 | 94 | // pushing vertex v into updated distance's bucket 95 | B[dv].push_front(v); 96 | 97 | // storing updated iterator in dist[v].second 98 | dist[v].second = B[dv].begin(); 99 | } 100 | } 101 | } 102 | 103 | // Print shortest distances stored in dist[] 104 | printf("Vertex Distance from Source\n"); 105 | for (int i = 0; i < V; ++i) 106 | printf("%d %d\n", i, dist[i].first); 107 | } 108 | 109 | // Driver program to test methods of graph class 110 | int main() 111 | { 112 | // create the graph given in above fugure 113 | int V = 9; 114 | Graph g(V); 115 | 116 | // making above shown graph 117 | g.addEdge(0, 1, 4); 118 | g.addEdge(0, 7, 8); 119 | g.addEdge(1, 2, 8); 120 | g.addEdge(1, 7, 11); 121 | g.addEdge(2, 3, 7); 122 | g.addEdge(2, 8, 2); 123 | g.addEdge(2, 5, 4); 124 | g.addEdge(3, 4, 9); 125 | g.addEdge(3, 5, 14); 126 | g.addEdge(4, 5, 10); 127 | g.addEdge(5, 6, 2); 128 | g.addEdge(6, 7, 1); 129 | g.addEdge(6, 8, 6); 130 | g.addEdge(7, 8, 7); 131 | 132 | // maximum weighted edge - 14 133 | g.shortestPath(0, 14); 134 | 135 | return 0; 136 | } 137 | -------------------------------------------------------------------------------- /Backtracking/HamiltonianCycles.java: -------------------------------------------------------------------------------- 1 | /* Java program for solution of Hamiltonian Cycle problem 2 | using backtracking */ 3 | class HamiltonianCycle 4 | { 5 | final int V = 5; 6 | int path[]; 7 | 8 | /* A utility function to check if the vertex v can be 9 | added at index 'pos'in the Hamiltonian Cycle 10 | constructed so far (stored in 'path[]') */ 11 | boolean isSafe(int v, int graph[][], int path[], int pos) 12 | { 13 | /* Check if this vertex is an adjacent vertex of 14 | the previously added vertex. */ 15 | if (graph[path[pos - 1]][v] == 0) 16 | return false; 17 | 18 | /* Check if the vertex has already been included. 19 | This step can be optimized by creating an array 20 | of size V */ 21 | for (int i = 0; i < pos; i++) 22 | if (path[i] == v) 23 | return false; 24 | 25 | return true; 26 | } 27 | 28 | /* A recursive utility function to solve hamiltonian 29 | cycle problem */ 30 | boolean hamCycleUtil(int graph[][], int path[], int pos) 31 | { 32 | /* base case: If all vertices are included in 33 | Hamiltonian Cycle */ 34 | if (pos == V) 35 | { 36 | // And if there is an edge from the last included 37 | // vertex to the first vertex 38 | if (graph[path[pos - 1]][path[0]] == 1) 39 | return true; 40 | else 41 | return false; 42 | } 43 | 44 | // Try different vertices as a next candidate in 45 | // Hamiltonian Cycle. We don't try for 0 as we 46 | // included 0 as starting point in hamCycle() 47 | for (int v = 1; v < V; v++) 48 | { 49 | /* Check if this vertex can be added to Hamiltonian 50 | Cycle */ 51 | if (isSafe(v, graph, path, pos)) 52 | { 53 | path[pos] = v; 54 | 55 | /* recur to construct rest of the path */ 56 | if (hamCycleUtil(graph, path, pos + 1) == true) 57 | return true; 58 | 59 | /* If adding vertex v doesn't lead to a solution, 60 | then remove it */ 61 | path[pos] = -1; 62 | } 63 | } 64 | 65 | /* If no vertex can be added to Hamiltonian Cycle 66 | constructed so far, then return false */ 67 | return false; 68 | } 69 | 70 | /* This function solves the Hamiltonian Cycle problem using 71 | Backtracking. It mainly uses hamCycleUtil() to solve the 72 | problem. It returns false if there is no Hamiltonian Cycle 73 | possible, otherwise return true and prints the path. 74 | Please note that there may be more than one solutions, 75 | this function prints one of the feasible solutions. */ 76 | int hamCycle(int graph[][]) 77 | { 78 | path = new int[V]; 79 | for (int i = 0; i < V; i++) 80 | path[i] = -1; 81 | 82 | /* Let us put vertex 0 as the first vertex in the path. 83 | If there is a Hamiltonian Cycle, then the path can be 84 | started from any point of the cycle as the graph is 85 | undirected */ 86 | path[0] = 0; 87 | if (hamCycleUtil(graph, path, 1) == false) 88 | { 89 | System.out.println("\nSolution does not exist"); 90 | return 0; 91 | } 92 | 93 | printSolution(path); 94 | return 1; 95 | } 96 | 97 | /* A utility function to print solution */ 98 | void printSolution(int path[]) 99 | { 100 | System.out.println("Solution Exists: Following" + 101 | " is one Hamiltonian Cycle"); 102 | for (int i = 0; i < V; i++) 103 | System.out.print(" " + path[i] + " "); 104 | 105 | // Let us print the first vertex again to show the 106 | // complete cycle 107 | System.out.println(" " + path[0] + " "); 108 | } 109 | 110 | // driver program to test above function 111 | public static void main(String args[]) 112 | { 113 | HamiltonianCycle hamiltonian = 114 | new HamiltonianCycle(); 115 | /* Let us create the following graph 116 | (0)--(1)--(2) 117 | | / \ | 118 | | / \ | 119 | | / \ | 120 | (3)-------(4) */ 121 | int graph1[][] = {{0, 1, 0, 1, 0}, 122 | {1, 0, 1, 1, 1}, 123 | {0, 1, 0, 0, 1}, 124 | {1, 1, 0, 0, 1}, 125 | {0, 1, 1, 1, 0}, 126 | }; 127 | 128 | // Print the solution 129 | hamiltonian.hamCycle(graph1); 130 | 131 | /* Let us create the following graph 132 | (0)--(1)--(2) 133 | | / \ | 134 | | / \ | 135 | | / \ | 136 | (3) (4) */ 137 | int graph2[][] = {{0, 1, 0, 1, 0}, 138 | {1, 0, 1, 1, 1}, 139 | {0, 1, 0, 0, 1}, 140 | {1, 1, 0, 0, 0}, 141 | {0, 1, 1, 0, 0}, 142 | }; 143 | 144 | // Print the solution 145 | hamiltonian.hamCycle(graph2); 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /Greedy Algorithms/Kruskals.java: -------------------------------------------------------------------------------- 1 | // Java program for Kruskal's algorithm to find Minimum 2 | // Spanning Tree of a given connected, undirected and 3 | // weighted graph 4 | import java.util.*; 5 | import java.lang.*; 6 | import java.io.*; 7 | 8 | class Graph 9 | { 10 | // A class to represent a graph edge 11 | class Edge implements Comparable 12 | { 13 | int src, dest, weight; 14 | 15 | // Comparator function used for sorting edges 16 | // based on their weight 17 | public int compareTo(Edge compareEdge) 18 | { 19 | return this.weight-compareEdge.weight; 20 | } 21 | }; 22 | 23 | // A class to represent a subset for union-find 24 | class subset 25 | { 26 | int parent, rank; 27 | }; 28 | 29 | int V, E; // V-> no. of vertices & E->no.of edges 30 | Edge edge[]; // collection of all edges 31 | 32 | // Creates a graph with V vertices and E edges 33 | Graph(int v, int e) 34 | { 35 | V = v; 36 | E = e; 37 | edge = new Edge[E]; 38 | for (int i=0; i subsets[yroot].rank) 65 | subsets[yroot].parent = xroot; 66 | 67 | // If ranks are same, then make one as root and increment 68 | // its rank by one 69 | else 70 | { 71 | subsets[yroot].parent = xroot; 72 | subsets[xroot].rank++; 73 | } 74 | } 75 | 76 | // The main function to construct MST using Kruskal's algorithm 77 | void KruskalMST() 78 | { 79 | Edge result[] = new Edge[V]; // Tnis will store the resultant MST 80 | int e = 0; // An index variable, used for result[] 81 | int i = 0; // An index variable, used for sorted edges 82 | for (i=0; i 2 | 3 | 4 | struct Edge 5 | { 6 | int src, dest, weight; 7 | }; 8 | 9 | 10 | struct Graph 11 | { 12 | // V-> Number of vertices, E-> Number of edges 13 | int V, E; 14 | 15 | Edge* edge; 16 | }; 17 | 18 | // A structure to represent a subset for union-find 19 | struct subset 20 | { 21 | int parent; 22 | int rank; 23 | }; 24 | 25 | int find(struct subset subsets[], int i); 26 | void Union(struct subset subsets[], int x, int y); 27 | 28 | // The main function for MST using Boruvka's algorithm 29 | void boruvkaMST(struct Graph* graph) 30 | { 31 | // Get data of given graph 32 | int V = graph->V, E = graph->E; 33 | Edge *edge = graph->edge; 34 | 35 | // Allocate memory for creating V subsets. 36 | struct subset *subsets = new subset[V]; 37 | 38 | // An array to store index of the cheapest edge of 39 | // subset. The stored index for indexing array 'edge[]' 40 | int *cheapest = new int[V]; 41 | 42 | // Create V subsets with single elements 43 | for (int v = 0; v < V; ++v) 44 | { 45 | subsets[v].parent = v; 46 | subsets[v].rank = 0; 47 | cheapest[v] = -1; 48 | } 49 | 50 | int numTrees = V; 51 | int MSTweight = 0; 52 | 53 | // Keep combining components (or sets) until all 54 | // compnentes are not combined into single MST. 55 | while (numTrees > 1) 56 | { 57 | // Everytime initialize cheapest array 58 | for (int v = 0; v < V; ++v) 59 | { 60 | cheapest[v] = -1; 61 | } 62 | 63 | // Traverse through all edges and update 64 | // cheapest of every component 65 | for (int i=0; i edge[i].weight) 83 | cheapest[set1] = i; 84 | 85 | if (cheapest[set2] == -1 || 86 | edge[cheapest[set2]].weight > edge[i].weight) 87 | cheapest[set2] = i; 88 | } 89 | } 90 | 91 | // Consider the above picked cheapest edges and add them 92 | // to MST 93 | for (int i=0; iV = V; 123 | graph->E = E; 124 | graph->edge = new Edge[E]; 125 | return graph; 126 | } 127 | 128 | // A utility function to find set of an element i 129 | // (uses path compression technique) 130 | int find(struct subset subsets[], int i) 131 | { 132 | // find root and make root as parent of i 133 | // (path compression) 134 | if (subsets[i].parent != i) 135 | subsets[i].parent = 136 | find(subsets, subsets[i].parent); 137 | 138 | return subsets[i].parent; 139 | } 140 | 141 | // A function that does union of two sets of x and y 142 | // (uses union by rank) 143 | void Union(struct subset subsets[], int x, int y) 144 | { 145 | int xroot = find(subsets, x); 146 | int yroot = find(subsets, y); 147 | 148 | // Attach smaller rank tree under root of high 149 | // rank tree (Union by Rank) 150 | if (subsets[xroot].rank < subsets[yroot].rank) 151 | subsets[xroot].parent = yroot; 152 | else if (subsets[xroot].rank > subsets[yroot].rank) 153 | subsets[yroot].parent = xroot; 154 | 155 | // If ranks are same, then make one as root and 156 | // increment its rank by one 157 | else 158 | { 159 | subsets[yroot].parent = xroot; 160 | subsets[xroot].rank++; 161 | } 162 | } 163 | 164 | // Driver program to test above functions 165 | int main() 166 | { 167 | int V = 4; // Number of vertices in graph 168 | int E = 5; // Number of edges in graph 169 | struct Graph* graph = createGraph(V, E); 170 | 171 | 172 | 173 | graph->edge[0].src = 0; 174 | graph->edge[0].dest = 1; 175 | graph->edge[0].weight = 10; 176 | graph->edge[1].src = 0; 177 | graph->edge[1].dest = 2; 178 | graph->edge[1].weight = 6; 179 | 180 | 181 | graph->edge[2].src = 0; 182 | graph->edge[2].dest = 3; 183 | graph->edge[2].weight = 5; 184 | graph->edge[3].src = 1; 185 | graph->edge[3].dest = 3; 186 | graph->edge[3].weight = 15; 187 | 188 | graph->edge[4].src = 2; 189 | graph->edge[4].dest = 3; 190 | graph->edge[4].weight = 4; 191 | 192 | boruvkaMST(graph); 193 | 194 | return 0; 195 | } 196 | --------------------------------------------------------------------------------