├── .github ├── CODEOWNERS ├── ISSUE_TEMPLATE │ ├── algorithm.md │ └── data-structure.md ├── PULL_REQUEST_TEMPLATE │ └── pull_request_template.md └── labeler.yml ├── .gitignore ├── Algorithms ├── Backtracking │ ├── C++ │ │ ├── N-Queen.cpp │ │ └── sudoko.cpp │ └── Python │ │ └── N-Queen.py ├── BigIntegerFactorials.cpp ├── Bubblesort │ ├── Java │ │ └── BubbleSort.java │ ├── Kotlin │ │ └── BubbleSort.kt │ ├── c++ │ │ └── bubblesort.cpp │ ├── c │ │ └── bubblesort.c │ ├── javascript │ │ └── bubblesort.js │ ├── kotlin │ │ └── BubbleSort.kt │ └── python │ │ ├── bubbleSort.py │ │ └── bubblesort.py ├── Dijkstra │ └── C++ │ │ └── Dijkstra.cpp ├── Dynamic Programming │ ├── C++ │ │ ├── AssemblyLineScheduling.cpp │ │ ├── MATMUL.CPP │ │ ├── Maximum_Subarray_Sum.cpp │ │ ├── house_thief.cpp │ │ └── lis.cpp │ ├── Java │ │ └── BoxStacking.java │ ├── c++ │ │ ├── coin_change.cpp │ │ ├── cutting_a_rod.cpp │ │ ├── edit-distance.cpp │ │ ├── gold_mine.cpp │ │ ├── lcs.cpp │ │ └── staircase.cpp │ └── python │ │ ├── coin_change.py │ │ ├── dp_subsetsum.py │ │ ├── edit_distance.py │ │ └── longestcommonsubseq.py ├── Extended-Euclidean │ └── c++ │ │ └── algo.cpp ├── Floyd-Warshall │ └── C++ │ │ └── Floyd-Warshall.cpp ├── Graphs │ └── cpp │ │ ├── articulationPoint.cpp │ │ ├── bridges.cpp │ │ └── maxFlowFordFulkerson.cpp ├── Greedy │ └── cpp │ │ └── fractionalKnapsack.cpp ├── Heapsort │ └── C │ │ └── heapsort.c ├── KMP │ └── C++ │ │ └── kmp.cpp ├── KnapSack │ └── cpp │ │ └── 01knapsack_recursion.cpp ├── KthSmallest │ └── java │ │ └── KthSmallestElement.java ├── Mergesort │ ├── C │ │ └── mergesort.c │ ├── c++ │ │ └── mergesort.cpp │ ├── erlang │ │ └── mergesort.erl │ ├── java │ │ ├── MergeSort.java │ │ └── mergesort.java │ └── python │ │ └── mergesort.py ├── Quicksort │ ├── Python │ │ └── naive_quicksort.py │ ├── c++ │ │ └── quicksort.cpp │ └── python │ │ └── quick_sort.py ├── Recursion │ └── coinchange │ │ └── c++ │ │ └── coin_change_rec.cpp ├── SOM │ └── python │ │ └── som.py ├── Search │ ├── C++ │ │ ├── Binary search.cpp │ │ ├── Linear_search.cpp │ │ ├── fibonacci_search.cpp │ │ ├── interpolation_search.cpp │ │ └── ternarySearch.cpp │ ├── Java │ │ ├── BinarySearch.java │ │ ├── LinearSearch.java │ │ ├── ReadMe.md │ │ └── TernarySearch.java │ ├── JavaScript │ │ ├── BinarySearch.js │ │ └── ReadMe.md │ ├── Python │ │ ├── BinarySearch.py │ │ └── LinearSearch.py │ ├── c++ │ │ └── binary_search.cpp │ └── c │ │ ├── binary_search.c │ │ └── linear_search.c ├── Seive-Of-Eratosthenes │ └── c++ │ │ └── seive.cpp ├── SelectionSort │ ├── c │ │ └── selection.cpp │ ├── java │ │ └── selectionsort.java │ ├── python │ │ └── selectionsort.py │ └── rust │ │ └── SelectionSort.rs ├── Sort │ ├── C++ │ │ ├── BucketSort.cpp │ │ └── heapsort.cpp │ ├── c │ │ └── bubble_sort.c │ ├── cpp │ │ ├── bubbleSort.cpp │ │ ├── bucketsort.cpp │ │ ├── countingsort.cpp │ │ ├── insertion_sort.cpp │ │ └── radixsort.cpp │ └── python │ │ ├── heapsort.py │ │ └── quicksort.py ├── Sudoku_Solver │ ├── cpp │ │ └── sudoku_solver.cpp │ └── java │ │ └── Sudoku.java ├── TowerOfHanoi │ └── cpp │ │ └── towerOfHanoi.cpp ├── TowerOfHanoiOptimised │ └── Java │ │ └── TowerOfHanoi.java ├── Word Boggle │ ├── Problem_Description.md │ └── WORD_BOGGLE.java ├── bfs_dfs │ ├── C++ │ │ └── ShortestPathInAMatrix.cpp │ ├── javascript │ │ └── bfs_dfs.js │ └── python │ │ └── bfs_dfs.py ├── binary_expo.cpp ├── bogosort │ ├── C++ │ │ └── bogosort.cpp │ ├── README.md │ └── java │ │ └── bogosort.java ├── fast_expo.c ├── graph │ └── c++ │ │ └── Kruskal MST in C++.cpp ├── knapsack │ └── c++ │ │ └── knapsack.cpp ├── next_greater_element.cpp └── ratInMazeAllPaths.py ├── Data Structures ├── AVL Tree │ └── Python │ │ └── avl_tree.py ├── Binary Search Tree Traversal │ ├── Inorder │ │ └── Inorder.py │ ├── Postorder │ │ └── Postorder.py │ └── Preorder │ │ └── Preorder.py ├── Binary Search Tree │ └── c++ │ │ └── bst.cpp ├── Binary Tree │ ├── C++ │ │ └── NodesBetweenTwoLevels.cpp │ ├── Java │ │ └── binary_tree.java │ ├── c │ │ ├── bt.c │ │ └── traversal.c │ └── python │ │ └── binary_tree.py ├── Bloom Filter │ └── Python │ │ └── bloom_filter.py ├── Circular_Queue │ └── C │ │ └── circularqueue.c ├── Fenwick Tree │ └── cpp │ │ └── fenwick_tree.cpp ├── Graphs │ └── cpp │ │ ├── articulationPoint.cpp │ │ ├── bridges.cpp │ │ └── maxFlowFordFulkerson.cpp ├── HashTable │ ├── Java │ │ ├── HashTable.java │ │ └── ReadMe.md │ └── cpp │ │ ├── README.md │ │ └── hash_table.cpp ├── Linked List │ ├── C │ │ ├── linked_list.c │ │ ├── linked_list_basics.c │ │ └── operations_on_linked_list │ ├── Java │ │ ├── CircularLinkedList.java │ │ ├── DoubleEndedLinkedList.java │ │ └── ReadMe.md │ ├── Javascript │ │ └── doubly_circular_linked_list.js │ ├── c++ │ │ ├── DoubleCircularLinkedList.cpp │ │ ├── DoublyLinkedList.cpp │ │ ├── SingleCircularLinkedList.cpp │ │ ├── SinglyLinkedList.cpp │ │ └── a.out │ ├── cpp │ │ └── linked_list.cpp │ └── python │ │ └── linked_list.py ├── Queue │ ├── C │ │ └── queue.c │ └── c++ │ │ └── queue.cpp ├── ReadMe.md ├── Stack │ ├── Python │ │ ├── README.md │ │ └── stack.py │ ├── c │ │ └── stack using array.c │ ├── cpp │ │ ├── .gitignore │ │ ├── README.md │ │ └── stack.cpp │ └── java │ │ ├── README.md │ │ └── Stack.java ├── Trie │ └── C++ │ │ └── Trie.cpp ├── UnionFind │ └── java │ │ ├── README.md │ │ └── UnionFind.java └── heap │ └── cpp │ └── binary_heap.cpp ├── LICENSE └── README.md /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @frextrite @AmritK10 @grufelous 2 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/algorithm.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Algorithm 3 | about: Implementing an algorithm? Tell us more about it here before working on it. 4 | title: "[Algo]" 5 | labels: Hacktoberfest 6 | assignees: '' 7 | 8 | --- 9 | 10 | # Algorithm 11 | 12 | - [ ] I have gone through the repository and made sure this algorithm has not been implemented 13 | 14 | ## Information about my new algorithm 15 | 16 | - **Algorithm Name:** 17 | 18 | - **Programming Language:** 19 | 20 | - **Time complexity:** 21 | 22 | 23 | **Is this your first contribution to this repository?** 24 | Yes 25 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/data-structure.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Data Structure 3 | about: Implementing a Data Structure? Tell us more about it here before working on 4 | it. 5 | title: "[DS]" 6 | labels: Hacktoberfest 7 | assignees: '' 8 | 9 | --- 10 | 11 | # Data Structure 12 | 13 | - [ ] I have gone through the repository and made sure this data structure has not been implemented 14 | 15 | ## Information about my new data structure 16 | 17 | - **Data Structure:** 18 | 19 | - **Programming Language:** 20 | 21 | 22 | **Is this your first contribution to this repository?** 23 | Yes 24 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE/pull_request_template.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## Checklist 4 | 5 | - [ ] I have read the contribution guidelines and my code is in accordance with the guidelines 6 | - [ ] I have implemented an Algorithm 7 | - [ ] I have implemented a Data structure 8 | 9 | Closes # . 10 | 11 | -------------------------------------------------------------------------------- /.github/labeler.yml: -------------------------------------------------------------------------------- 1 | Hacktoberfest: 2 | - Algorithms/**/* 3 | - Algorithms/* 4 | - Data Structures/**/* 5 | - Data Structures/* 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | #Mac File System Log 2 | .DS_Store 3 | 4 | # Logs 5 | logs 6 | *.log 7 | npm-debug.log* 8 | yarn-debug.log* 9 | yarn-error.log* 10 | 11 | # Runtime data 12 | pids 13 | *.pid 14 | *.seed 15 | *.pid.lock 16 | 17 | # Directory for instrumented libs generated by jscoverage/JSCover 18 | lib-cov 19 | 20 | # Coverage directory used by tools like istanbul 21 | coverage 22 | 23 | # nyc test coverage 24 | .nyc_output 25 | 26 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 27 | .grunt 28 | 29 | # Bower dependency directory (https://bower.io/) 30 | bower_components 31 | 32 | # node-waf configuration 33 | .lock-wscript 34 | 35 | # Compiled binary addons (https://nodejs.org/api/addons.html) 36 | build/Release 37 | 38 | # Dependency directories 39 | node_modules/ 40 | jspm_packages/ 41 | 42 | # TypeScript v1 declaration files 43 | typings/ 44 | 45 | # Optional npm cache directory 46 | .npm 47 | 48 | # Optional eslint cache 49 | .eslintcache 50 | 51 | # Optional REPL history 52 | .node_repl_history 53 | 54 | # Output of 'npm pack' 55 | *.tgz 56 | 57 | # Yarn Integrity file 58 | .yarn-integrity 59 | 60 | # dotenv environment variables file 61 | .env 62 | 63 | # next.js build output 64 | .next 65 | -------------------------------------------------------------------------------- /Algorithms/Backtracking/C++/N-Queen.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | #define N 5 5 | 6 | void printBoard(int board[N][N]){ 7 | for(int i=0;i=0 && j>=0;i--,j--) 20 | if(board[i][j]) 21 | return false; 22 | 23 | for(int i=row,j=col;j>=0 && i=N) 32 | return true; 33 | 34 | for(int i=0;i 3 | using namespace std; 4 | #define UNASSIGNED 0 5 | #define N 9 6 | bool FindUnassignedLocation(int grid[N][N], 7 | int &row, int &col); 8 | 9 | bool isSafe(int grid[N][N], int row, 10 | int col, int num); 11 | 12 | bool SolveSudoku(int grid[N][N]) 13 | { 14 | int row, col; 15 | if (!FindUnassignedLocation(grid, row, col)) 16 | return true; 17 | for (int num = 1; num <= 9; num++) 18 | { 19 | if (isSafe(grid, row, col, num)) 20 | { 21 | grid[row][col] = num; 22 | if (SolveSudoku(grid)) 23 | return true; 24 | grid[row][col] = UNASSIGNED; 25 | } 26 | } 27 | return false; 28 | } 29 | 30 | bool FindUnassignedLocation(int grid[N][N], 31 | int &row, int &col) 32 | { 33 | for (row = 0; row < N; row++) 34 | for (col = 0; col < N; col++) 35 | if (grid[row][col] == UNASSIGNED) 36 | return true; 37 | return false; 38 | } 39 | 40 | 41 | bool UsedInRow(int grid[N][N], int row, int num) 42 | { 43 | for (int col = 0; col < N; col++) 44 | if (grid[row][col] == num) 45 | return true; 46 | return false; 47 | } 48 | 49 | 50 | bool UsedInCol(int grid[N][N], int col, int num) 51 | { 52 | for (int row = 0; row < N; row++) 53 | if (grid[row][col] == num) 54 | return true; 55 | return false; 56 | } 57 | 58 | 59 | bool UsedInBox(int grid[N][N], int boxStartRow, 60 | int boxStartCol, int num) 61 | { 62 | for (int row = 0; row < 3; row++) 63 | for (int col = 0; col < 3; col++) 64 | if (grid[row + boxStartRow] 65 | [col + boxStartCol] == num) 66 | return true; 67 | return false; 68 | } 69 | 70 | 71 | bool isSafe(int grid[N][N], int row, 72 | int col, int num) 73 | { 74 | return !UsedInRow(grid, row, num) && 75 | !UsedInCol(grid, col, num) && 76 | !UsedInBox(grid, row - row % 3 , 77 | col - col % 3, num) && 78 | grid[row][col] == UNASSIGNED; 79 | } 80 | 81 | 82 | void printGrid(int grid[N][N]) 83 | { 84 | for (int row = 0; row < N; row++) 85 | { 86 | for (int col = 0; col < N; col++) 87 | cout << grid[row][col] << " "; 88 | cout << endl; 89 | } 90 | } 91 | 92 | 93 | int main() 94 | { 95 | 96 | int grid[N][N] = {{3, 0, 6, 5, 0, 8, 4, 0, 0}, 97 | {5, 2, 0, 0, 0, 0, 0, 0, 0}, 98 | {0, 8, 7, 0, 0, 0, 0, 3, 1}, 99 | {0, 0, 3, 0, 1, 0, 0, 8, 0}, 100 | {9, 0, 0, 8, 6, 3, 0, 0, 5}, 101 | {0, 5, 0, 0, 9, 0, 6, 0, 0}, 102 | {1, 3, 0, 0, 0, 0, 2, 5, 0}, 103 | {0, 0, 0, 0, 0, 0, 0, 7, 4}, 104 | {0, 0, 5, 2, 0, 6, 3, 0, 0}}; 105 | if (SolveSudoku(grid) == true) 106 | printGrid(grid); 107 | else 108 | cout << "No solution exists"; 109 | 110 | return 0; 111 | } 112 | 113 | 114 | -------------------------------------------------------------------------------- /Algorithms/Backtracking/Python/N-Queen.py: -------------------------------------------------------------------------------- 1 | def printBoard(board): 2 | num=len(board) 3 | for i in range(num): 4 | for j in range(num): 5 | print(board[i][j],end=' ') 6 | print() 7 | 8 | def isValid(board,row,col): 9 | num=len(board) 10 | 11 | for i in range(col): 12 | if board[row][i]: 13 | return False 14 | i=row 15 | j=col 16 | while i>=0 and j>=0: 17 | if board[i][j]: 18 | return False 19 | i-=1 20 | j-=1 21 | 22 | i=row 23 | j=col 24 | while j>=0 and i< num: 25 | if board[i][j]: 26 | return False 27 | i+=1 28 | j-=1 29 | 30 | return True 31 | 32 | def solveNQueen(board,col): 33 | num=len(board) 34 | 35 | if col>=num: 36 | return True 37 | 38 | for i in range(num): 39 | if isValid(board,i,col): 40 | board[i][col] = 1 41 | if solveNQueen(board,col+1): 42 | return True 43 | board[i][col]=0 44 | 45 | return False 46 | 47 | def checkSolution(num): 48 | board=[] 49 | for i in range(num): 50 | temp=[] 51 | for j in range(num): 52 | temp.append(0) 53 | board.append(temp) 54 | if not(solveNQueen(board,0)): 55 | print("Solution does not exist") 56 | return False 57 | printBoard(board) 58 | return True 59 | 60 | print("Enter board dimension (Row num): ",end=' ') 61 | checkSolution(int(input())) -------------------------------------------------------------------------------- /Algorithms/BigIntegerFactorials.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define MAX 500 3 | using namespace std; 4 | int multiply(int x, int res[], int res_size); 5 | void extraLongFactorials(int n) { 6 | int res[MAX]; 7 | res[0] = 1; 8 | int res_size = 1; 9 | for (int x=2; x<=n; x++) 10 | res_size = multiply(x, res, res_size); 11 | for (int i=res_size-1; i>=0; i--) 12 | cout << res[i]; 13 | } 14 | int multiply(int x, int res[], int res_size) 15 | { 16 | int carry = 0; 17 | for (int i=0; i> n; 36 | cin.ignore(numeric_limits::max(), '\n'); 37 | extraLongFactorials(n); 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /Algorithms/Bubblesort/Java/BubbleSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | public class BubbleSort { 3 | public static void main(String []args) { 4 | int n, i, j, swapflag=1,temp; 5 | Scanner in = new Scanner(System. in); 6 | System. out. println("Input number of integers to sort"); 7 | n = in. nextInt(); 8 | int a[] = new int[n]; 9 | System.out.println("Enter " + n + " integers"); 10 | 11 | for(i=0;ia[j+1]){ 19 | temp=a[j]; 20 | a[j]=a[j+1]; 21 | a[j+1]=temp; 22 | swapflag=1; 23 | } 24 | } 25 | } 26 | } 27 | 28 | System.out.println("Sorted array is"); 29 | 30 | for(i=0;iarr[j+1]){ 6 | var temp = arr[j] 7 | arr[j] = arr[j+1] 8 | arr[j+1] = temp 9 | } 10 | } 11 | } 12 | } 13 | fun main(args:Array) { 14 | var scanner = Scanner(System.`in`) 15 | print("enter the size to be sorted ") 16 | var sizeOfList = scanner.nextInt() 17 | val array = IntArray(sizeOfList) 18 | print("start entering values to be sorted ") 19 | for (i in 0 until sizeOfList) { 20 | array[i] = scanner.nextInt(); 21 | } 22 | bubbleSort(array) 23 | for (i in 0 until sizeOfList){ 24 | print(array[i]) 25 | print(" ") 26 | } 27 | } -------------------------------------------------------------------------------- /Algorithms/Bubblesort/c++/bubblesort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int a[50],n,i,j,temp; 8 | cout<<"Enter the size of array: "; 9 | cin>>n; 10 | cout<<"Enter the array elements: "; 11 | 12 | for(i=0;i>a[i]; 14 | 15 | for(i=1;ia[j+1]) 19 | { 20 | temp=a[j]; 21 | a[j]=a[j+1]; 22 | a[j+1]=temp; 23 | } 24 | } 25 | 26 | cout<<"Array after bubble sort:"; 27 | for(i=0;i 2 | #include 3 | 4 | 5 | 6 | int * bubblesort(int size, int *array){ 7 | int i, j, aux; 8 | for(i=0;i array[j + 1]) { 7 | let aux = array[j]; 8 | array[j] = array[j+1]; 9 | array[j + 1] = aux; 10 | } 11 | } 12 | } 13 | return array; 14 | } 15 | 16 | console.log(bubble([1,8,7,3,3,9,2,3,7,6,4,5,5])); -------------------------------------------------------------------------------- /Algorithms/Bubblesort/kotlin/BubbleSort.kt: -------------------------------------------------------------------------------- 1 | class DummyBubbleSort { 2 | 3 | private fun sortArray(numbers: Array) { 4 | for (currentPosition in 0 until (numbers.size - 1)) { 5 | if (numbers[currentPosition] > numbers[currentPosition + 1]) { 6 | val tmp = numbers[currentPosition] 7 | numbers[currentPosition] = numbers[currentPosition + 1] 8 | numbers[currentPosition + 1] = tmp 9 | } 10 | } 11 | } 12 | 13 | fun main(args: Array) { 14 | val numbers = arrayOf(69, 42, 666, 1, 969, 23, 6, 2, 0, 87) 15 | sortArray(numbers) 16 | numbers.forEach(::print) 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Algorithms/Bubblesort/python/bubbleSort.py: -------------------------------------------------------------------------------- 1 | #Bubble sort for an that is given. 2 | 3 | def bubbleSort(A): 4 | n = len(A) 5 | 6 | for i in range(n): 7 | for j in range(0, n-i-1): 8 | if A[j] > A[j+1] : 9 | A[i], A[j+1] = A[j+1], A[j] 10 | 11 | A = [9, 7, 1, 5, 12, 99, 21, 22, 101] 12 | 13 | bubbleSort(A) 14 | 15 | print ("Sorted array: ") 16 | for i in range(len(A)): 17 | print ("%d" %A[i]), 18 | -------------------------------------------------------------------------------- /Algorithms/Bubblesort/python/bubblesort.py: -------------------------------------------------------------------------------- 1 | #Bubble sort for an that is given. 2 | 3 | def bubbleSort(A): 4 | n = len(A) 5 | 6 | for i in range(n): 7 | for j in range(0, n-i-1): 8 | if A[j] > A[j+1] : 9 | A[i], A[j+1] = A[j+1], A[j] 10 | 11 | A = [9, 7, 1, 5, 12, 99, 21, 22, 101] 12 | 13 | bubbleSort(A) 14 | 15 | print ("Sorted array: ") 16 | for i in range(len(A)): 17 | print ("%d" %A[i]), 18 | -------------------------------------------------------------------------------- /Algorithms/Dijkstra/C++/Dijkstra.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | # define INF 0x3f3f3f3f 4 | 5 | typedef pair iPair; 6 | 7 | void addEdge(vector > adj[], int u, 8 | int v, int wt) 9 | { 10 | adj[u].push_back(make_pair(v, wt)); 11 | adj[v].push_back(make_pair(u, wt)); 12 | } 13 | 14 | void shortestPath(vector > adj[], int V, int src) 15 | { 16 | priority_queue< iPair, vector , greater > pq; 17 | 18 | vector dist(V, INF); 19 | 20 | pq.push(make_pair(0, src)); 21 | dist[src] = 0; 22 | 23 | while (!pq.empty()) 24 | { 25 | int u = pq.top().second; 26 | pq.pop(); 27 | 28 | for (auto x : adj[u]) 29 | { 30 | int v = x.first; 31 | int weight = x.second; 32 | if (dist[v] > dist[u] + weight) 33 | { 34 | 35 | dist[v] = dist[u] + weight; 36 | pq.push(make_pair(dist[v], v)); 37 | } 38 | } 39 | } 40 | printf("Vertex \t Distance from Source\n"); 41 | for (int i = 0; i < V; ++i) 42 | printf("%d \t\t %d\n", i, dist[i]); 43 | } 44 | 45 | int main() 46 | { 47 | int V = 9; 48 | vector adj[V]; 49 | 50 | addEdge(adj, 0, 1, 4); 51 | addEdge(adj, 0, 7, 8); 52 | addEdge(adj, 1, 2, 8); 53 | addEdge(adj, 1, 7, 11); 54 | addEdge(adj, 2, 3, 7); 55 | addEdge(adj, 2, 8, 2); 56 | addEdge(adj, 2, 5, 4); 57 | addEdge(adj, 3, 4, 9); 58 | addEdge(adj, 3, 5, 14); 59 | addEdge(adj, 4, 5, 10); 60 | addEdge(adj, 5, 6, 2); 61 | addEdge(adj, 6, 7, 1); 62 | addEdge(adj, 6, 8, 6); 63 | addEdge(adj, 7, 8, 7); 64 | 65 | shortestPath(adj, V, 0); 66 | 67 | return 0; 68 | } 69 | -------------------------------------------------------------------------------- /Algorithms/Dynamic Programming/C++/AssemblyLineScheduling.cpp: -------------------------------------------------------------------------------- 1 | // A C++ program to find minimum possible 2 | // time by the car chassis to complete 3 | #include 4 | using namespace std; 5 | #define NUM_LINE 2 6 | #define NUM_STATION 4 7 | 8 | // Utility function to find minimum of two numbers 9 | int min(int a, int b) 10 | { 11 | return a < b ? a : b; 12 | } 13 | 14 | int carAssembly(int a[][NUM_STATION], 15 | int t[][NUM_STATION], 16 | int *e, int *x) 17 | { 18 | int T1[NUM_STATION], T2[NUM_STATION], i; 19 | 20 | // time taken to leave first station in line 1 21 | T1[0] = e[0] + a[0][0]; 22 | 23 | // time taken to leave first station in line 2 24 | T2[0] = e[1] + a[1][0]; 25 | 26 | // Fill tables T1[] and T2[] using the 27 | // above given recursive relations 28 | for (i = 1; i < NUM_STATION; ++i) 29 | { 30 | T1[i] = min(T1[i - 1] + a[0][i], 31 | T2[i - 1] + t[1][i] + a[0][i]); 32 | T2[i] = min(T2[i - 1] + a[1][i], 33 | T1[i - 1] + t[0][i] + a[1][i]); 34 | } 35 | 36 | // Consider exit times and retutn minimum 37 | return min(T1[NUM_STATION - 1] + x[0], 38 | T2[NUM_STATION - 1] + x[1]); 39 | } 40 | 41 | // Driver Code 42 | int main() 43 | { 44 | int a[][NUM_STATION] = {{4, 5, 3, 2}, 45 | {2, 10, 1, 4}}; 46 | int t[][NUM_STATION] = {{0, 7, 4, 5}, 47 | {0, 9, 2, 8}}; 48 | int e[] = {10, 12}, x[] = {18, 7}; 49 | 50 | cout << carAssembly(a, t, e, x); 51 | 52 | return 0; 53 | } 54 | 55 | is code is contributed by rathbhupendra 56 | -------------------------------------------------------------------------------- /Algorithms/Dynamic Programming/C++/MATMUL.CPP: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | void main() 5 | { 6 | int r1,c1,r2,c2; 7 | clrscr(); 8 | cout<<"Enter the number of rows and columns for matrix 1:"<>r1; 10 | cin>>c1; 11 | int mat1[10][10]; 12 | int i,j,k; 13 | int flag; 14 | 15 | cout<<"Enter the elements of first matrix:"<>mat1[i][j]; 21 | } 22 | } 23 | cout<<"Enter the number of rows and columns for the second matrix"<>r2; 25 | cin>>c2; 26 | int mat[10][10]; 27 | cout<<"Enter the elements of the second matrix:"<>mat[k][l]; 33 | } 34 | } 35 | int output[10][10]; 36 | if(c1==r2) 37 | { 38 | flag=1; 39 | for(i=0;i 2 | using namespace std; 3 | //This is Kadane's Algorithm for maximum Subarray Sum 4 | int maxSubArraySum(int a[], int array_size) 5 | { 6 | int global_max_sum = INT_MIN, local_max_sum = 0; 7 | 8 | for (int i = 0; i < array_size; i++) 9 | { 10 | local_max_sum = local_max_sum + a[i]; 11 | if (global_max_sum < local_max_sum ) 12 | global_max_sum = local_max_sum; 13 | 14 | if (local_max_sum < 0) 15 | local_max_sum = 0; 16 | } 17 | return global_max_sum; 18 | } 19 | 20 | int main() { 21 | 22 | int a[] = {-1,-2,-5,1,4,6,-5,-3,11}; 23 | int array_size = sizeof(a)/sizeof(a[0]); 24 | int max_sum = maxSubArraySum(a, array_size); 25 | cout << "Maximum contiguous subarray sum is " << max_sum; 26 | return 0; 27 | } -------------------------------------------------------------------------------- /Algorithms/Dynamic Programming/C++/house_thief.cpp: -------------------------------------------------------------------------------- 1 | /*A thief wants to loot houses and knows the amount of money in each house. 2 | He cannot loot two consecutive houses.The following program returns the maximum amount of money he can loot.*/ 3 | //Time complexity: O(n^2); Constraints: 1 <= n <= 10^4 4 | #include 5 | using namespace std; 6 | 7 | int getMaxMoney(int arr[], int n){ 8 | int i; 9 | int arr2[n+3]; 10 | if(n<3){ 11 | if(n==1){ 12 | return arr[0]; 13 | }else{ 14 | return max(arr[0],arr[1]); 15 | } 16 | } 17 | arr2[0]=arr[0]; 18 | arr2[1]=arr[1]; 19 | for(i=2;i 2 | using namespace std; 3 | 4 | int lis( int arr[], int n ) 5 | { 6 | int lis[n]; 7 | 8 | lis[0] = 1; 9 | 10 | for (int i = 1; i < n; i++ ) 11 | { 12 | lis[i] = 1; 13 | for (int j = 0; j < i; j++ ) 14 | if ( arr[i] > arr[j] && lis[i] < lis[j] + 1) 15 | lis[i] = lis[j] + 1; 16 | } 17 | 18 | return *max_element(lis, lis+n); 19 | } 20 | 21 | int main() 22 | { 23 | int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 }; 24 | int n = sizeof(arr)/sizeof(arr[0]); 25 | printf("Length of lis is %d\n", lis( arr, n ) ); 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /Algorithms/Dynamic Programming/Java/BoxStacking.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public static int maxHeight(int height[], int width[], int length[], int n) 4 | { 5 | List boxes = getBoxes(n, length, width, height); 6 | // System.out.println(boxes); 7 | // printBoxes(boxes); 8 | int[] table = new int[boxes.size()]; 9 | for (int i=0; i getBoxes(int n, int[] l, int[] w, int[] h){ 27 | List boxes = new ArrayList<>(); 28 | for (int i=0; i(){ 34 | public int compare(Node box1, Node box2){ 35 | if (box1.length*box1.width >= box2.length*box2.width) 36 | return -1; 37 | else 38 | return 1; 39 | } 40 | }); 41 | return boxes; 42 | } 43 | 44 | static void printBoxes(List boxes){ 45 | for (Node box: boxes){ 46 | System.out.println(box.length + " " + box.width + " " + box.height); 47 | } 48 | } 49 | 50 | static void printTable(int[] table){ 51 | for (int num: table){ 52 | System.out.print(num + " "); 53 | } 54 | System.out.println(); 55 | } 56 | 57 | static class Node{ 58 | int length, width, height; 59 | Node(int l, int w, int h){ 60 | this.length = Math.max(l, w); 61 | this.width = Math.min(l, w); 62 | this.height = h; 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /Algorithms/Dynamic Programming/c++/coin_change.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | 6 | long long int count( long long int S[], long long int m, long long int n ) 7 | { 8 | int table[m+1][n+1]; 9 | memset(table, 0, sizeof(table)); 10 | 11 | for(long long int i=0;i<=m;i++) 12 | { 13 | table[i][0] = 1; 14 | } 15 | for(long long int i=1;i<=m;i++) 16 | { 17 | 18 | for(long long int j=1;j<=n;j++) 19 | { 20 | if(S[i-1]>j) 21 | { 22 | table[i][j]=table[i-1][j]; 23 | 24 | } 25 | 26 | else 27 | { 28 | table[i][j]=table[i-1][j]+table[i][j-S[i-1]]; 29 | } 30 | 31 | } 32 | } 33 | 34 | // for(int i=0;i<=m;i++){ 35 | // for(int j=0;j<=n;j++){ 36 | // cout<>t; 46 | while(t--){ 47 | cin>>m; 48 | long long int S[m]; 49 | for(i=0;i>S[i]; 51 | cin>>n; 52 | cout< 2 | #include 3 | 4 | // A utility function to get the maximum of two integers 5 | int max(int a, int b) { return (a > b)? a : b;} 6 | 7 | /* Returns the best obtainable price for a rod of length n and 8 | price[] as prices of different pieces */ 9 | int cutRod(int price[], int n) 10 | { 11 | if (n <= 0) 12 | return 0; 13 | int max_val = INT_MIN; 14 | 15 | // Recursively cut the rod in different pieces and compare different 16 | // configurations 17 | for (int i = 0; i 20 | using namespace std; 21 | 22 | int main() 23 | { 24 | string str1("geek"),str2("geesk"); 25 | 26 | int l1=str1.length(); 27 | int l2=str2.length(); 28 | 29 | 30 | //str1 as column 31 | //str2 as row 32 | int matrix[l2+1][l1+1]; 33 | 34 | for(int row=0;row<=l2;row++) 35 | { 36 | for(int col=0;col<=l1;col++) 37 | { 38 | //to make null to string 39 | if(row==0) 40 | matrix[row][col]=col; 41 | 42 | else if(col==0) 43 | matrix[row][col]=row; 44 | 45 | //if the characters match then skip 46 | //match then keep as diagonal 47 | else if(str1[col-1]==str2[row-1]) 48 | matrix[row][col]=matrix[row-1][col-1]; 49 | 50 | else 51 | //not match 1+min(left,top,diagonal) 52 | matrix[row][col]=1+min(matrix[row-1][col],min(matrix[row][col-1],matrix[row-1][col-1])); 53 | } 54 | } 55 | cout< 3 | using namespace std; 4 | 5 | const int MAX = 100; 6 | 7 | // Returns maximum amount of gold that can be collected 8 | // when journey started from first column and moves 9 | // allowed are right, right-up and right-down 10 | int getMaxGold(int gold[][MAX], int m, int n) 11 | { 12 | // Create a table for storing intermediate results 13 | // and initialize all cells to 0. The first row of 14 | // goldMineTable gives the maximum gold that the miner 15 | // can collect when starts that row 16 | int goldTable[m][n]; 17 | memset(goldTable, 0, sizeof(goldTable)); 18 | 19 | for (int col=n-1; col>=0; col--) 20 | { 21 | for (int row=0; row) 24 | int right = (col==n-1)? 0: goldTable[row][col+1]; 25 | 26 | // Gold collected on going to the cell to right up (/) 27 | int right_up = (row==0 || col==n-1)? 0: 28 | goldTable[row-1][col+1]; 29 | 30 | // Gold collected on going to the cell to right down (\) 31 | int right_down = (row==m-1 || col==n-1)? 0: 32 | goldTable[row+1][col+1]; 33 | 34 | // Max gold collected from taking either of the 35 | // above 3 paths 36 | goldTable[row][col] = gold[row][col] + 37 | max(right, max(right_up, right_down)); 38 | 39 | } 40 | } 41 | 42 | // The max amount of gold collected will be the max 43 | // value in first column of all rows 44 | int res = goldTable[0][0]; 45 | for (int i=1; i 2 | using namespace std; 3 | 4 | int max(int a, int b); 5 | 6 | /* Returns length of LCS for X[0..m-1], Y[0..n-1] */ 7 | int lcs( char *X, char *Y, int m, int n ) 8 | { 9 | if (m == 0 || n == 0) 10 | return 0; 11 | if (X[m-1] == Y[n-1]) 12 | return 1 + lcs(X, Y, m-1, n-1); 13 | else 14 | return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n)); 15 | } 16 | 17 | /* Utility function to get max of 2 integers */ 18 | int max(int a, int b) 19 | { 20 | return (a > b)? a : b; 21 | } 22 | 23 | /* Driver code */ 24 | int main() 25 | { 26 | char X[] = "AGGTAB"; 27 | char Y[] = "GXTXAYB"; 28 | 29 | int m = strlen(X); 30 | int n = strlen(Y); 31 | 32 | cout<<"Length of LCS is "<< lcs( X, Y, m, n ) ; 33 | 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /Algorithms/Dynamic Programming/c++/staircase.cpp: -------------------------------------------------------------------------------- 1 | /*A child is running up a staircase with n steps and can hop either 1 step,2 steps or 3 steps at a time. 2 | Implementing a recursive method to count total number of ways the child can run up the stairs.*/ 3 | //Time complexity: O(n); Constraints: n <= 70 4 | #include 5 | using namespace std; 6 | 7 | long staircase(int n){ 8 | int i; 9 | long arr[n+4]; 10 | arr[0] = 1; 11 | arr[1] = 1; 12 | arr[2] = 2; 13 | if(n<3){ 14 | return arr[n]; 15 | } 16 | for(i=3;i<=n;i++){ 17 | arr[i]=arr[i-1]+arr[i-2]+arr[i-3]; 18 | }return arr[n]; 19 | } 20 | 21 | /* Driver program to test above functions */ 22 | int main(){ 23 | cout< i: break 11 | dp[i] = min(dp[i], 1 + dp[i - coin]) 12 | if dp[amount] > amount: 13 | return -1 14 | return dp[amount] 15 | 16 | if __name__ == '__main__': 17 | coins = input('Coins: ') 18 | coins = list(map(int, coins.split())) 19 | for i in range(3): 20 | amount = int(input('Amount: ')) 21 | print(coinChange(coins, amount)) 22 | -------------------------------------------------------------------------------- /Algorithms/Dynamic Programming/python/dp_subsetsum.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | def subsum(array, goal: int) -> bool: 4 | # True as empty list has sum = 0 5 | if goal == 0: 6 | return True 7 | n = len(array) 8 | # Columns = 1 + goal 9 | # Rows = 1 + n 10 | dp = [[False for i in range (1 + goal)] for j in range(1 + n)] 11 | # dp[i][j] => True if there is a subset of array[0:j] with sum = i 12 | for i in range(1 + n): 13 | # base case: goal = 0 => True 14 | dp[i][0] = True 15 | # 1 <= j <= goal 16 | for j in range(1, 1 + goal): 17 | if j < array[i - 1]: 18 | dp[i][j] = dp[i - 1][j] 19 | else: 20 | dp[i][j] = dp[i - 1][j] or dp[i - 1][j - array[i - 1]] 21 | return dp[n][goal] 22 | 23 | array = [1,2,3,4] 24 | print(array) 25 | goal = int(input('n: ')) 26 | print(subsum(array, goal)) 27 | -------------------------------------------------------------------------------- /Algorithms/Dynamic Programming/python/edit_distance.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | def edit_distance(s1: str, s2: str) -> int: 4 | n = len(s1) 5 | m = len(s2) 6 | edit = [[None for i in range(1 + m)] for j in range(1 + n)] 7 | for i in range(1 + m): 8 | edit[0][i] = i 9 | for i in range(1, 1 + n): 10 | edit[i][0] = i 11 | for j in range(1, 1 + m): 12 | replace = edit[i-1][j-1] 13 | insert = 1 + edit[i][j - 1] 14 | delete = 1 + edit[i - 1][j] 15 | if not (s1[i - 1] == s2[j - 1]): 16 | replace += 1 17 | edit[i][j] = min(insert, delete, replace) 18 | return edit[n][m] 19 | 20 | if __name__ == '__main__': 21 | s1 = input('s1: ') 22 | s2 = input('s2: ') 23 | print(edit_distance(s1, s2)) 24 | -------------------------------------------------------------------------------- /Algorithms/Dynamic Programming/python/longestcommonsubseq.py: -------------------------------------------------------------------------------- 1 | def lcs(X, Y, m, n): 2 | L = [[0 for x in range(n+1)] for x in range(m+1)] 3 | 4 | # Following steps build L[m+1][n+1] in bottom up fashion. Note 5 | # that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] 6 | for i in range(m+1): 7 | for j in range(n+1): 8 | if i == 0 or j == 0: 9 | L[i][j] = 0 10 | elif X[i-1] == Y[j-1]: 11 | L[i][j] = L[i-1][j-1] + 1 12 | else: 13 | L[i][j] = max(L[i-1][j], L[i][j-1]) 14 | 15 | # Following code is used to print LCS 16 | index = L[m][n] 17 | 18 | # Create a character array to store the lcs string 19 | lcs = [""] * (index+1) 20 | lcs[index] = "" 21 | 22 | # Start from the right-most-bottom-most corner and 23 | # one by one store characters in lcs[] 24 | i = m 25 | j = n 26 | while i > 0 and j > 0: 27 | 28 | # If current character in X[] and Y are same, then 29 | # current character is part of LCS 30 | if X[i-1] == Y[j-1]: 31 | lcs[index-1] = X[i-1] 32 | i-=1 33 | j-=1 34 | index-=1 35 | 36 | # If not same, then find the larger of two and 37 | # go in the direction of larger value 38 | elif L[i-1][j] > L[i][j-1]: 39 | i-=1 40 | else: 41 | j-=1 42 | 43 | print ("LCS of " + X + " and " + Y + " is " + "".join(lcs)) 44 | 45 | # Driver program 46 | X = input("Enter first string") 47 | Y = input("Enter second string") 48 | m = len(X) 49 | n = len(Y) 50 | lcs(X, Y, m, n) -------------------------------------------------------------------------------- /Algorithms/Extended-Euclidean/c++/algo.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int gcdExtended(int a, int b, int *x, int *y) 5 | { 6 | // Base Case 7 | if (a == 0) 8 | { 9 | *x = 0; 10 | *y = 1; 11 | return b; 12 | } 13 | 14 | int x1, y1; // To store results of recursive call 15 | int gcd = gcdExtended(b%a, a, &x1, &y1); 16 | 17 | // Update x and y using results of 18 | // recursive call 19 | *x = y1 - (b/a) * x1; 20 | *y = x1; 21 | 22 | return gcd; 23 | } 24 | 25 | // Driver Code 26 | int main() 27 | { 28 | int x, y, a = 35, b = 15; 29 | int g = gcdExtended(a, b, &x, &y); 30 | cout << "GCD(" << a << ", " << b 31 | << ") = " << g << endl; 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /Algorithms/Floyd-Warshall/C++/Floyd-Warshall.cpp: -------------------------------------------------------------------------------- 1 | Time Complexity: O(n^3) 2 | Space Complexity: O(n^2) 3 | 4 | #include 5 | using namespace std; 6 | int main() 7 | { 8 | int n,m; // n-> Number of Vertices, m-> Number of unidirectional edges (u->v is not the same as v-> u) 9 | cin>>n>>m; 10 | int AdjList[n][n]; // Adjlist-> Adjacency list 11 | for(int i=0;i>u>>v>>x; // edge from u to v (0 based indexing) with edge cost x; 29 | AdjList[u][v]=x; 30 | } 31 | 32 | // Floyd-Warshall Algorithm 33 | for(int k=0;k 44 | using namespace std; 45 | // error shows 2 is ap 46 | class ArticulationPair 47 | { 48 | public: 49 | 50 | int vert; 51 | int disc; 52 | int low; 53 | bool isAP; 54 | bool processed; 55 | int parent=-1; 56 | }; 57 | //static int graph[n][n]; 58 | //static ArticulationPair result[n]; 59 | 60 | void DFT(int time,int currv,int **graph,ArticulationPair *result[],int n) 61 | { 62 | result[currv]->processed=true; 63 | result[currv]->disc=time; 64 | result[currv]->low=time; 65 | 66 | int rootChildCounter=0; 67 | 68 | for(int i=0;iprocessed==false) 76 | { 77 | rootChildCounter++; 78 | result[i]->parent=currv; 79 | DFT(time+1,i,graph,result,n); 80 | result[currv]->low=min(result[currv]->low,result[i]->low); 81 | 82 | if(result[currv]->parent!=-1) 83 | { 84 | if(result[currv]->disc<=result[i]->low) 85 | { 86 | result[currv]->isAP=new bool; 87 | result[currv]->isAP=true; 88 | } 89 | } 90 | else 91 | { 92 | if(rootChildCounter > 1) 93 | { 94 | result[currv]->isAP=new bool; 95 | result[currv]->isAP=true; 96 | } 97 | } 98 | 99 | } 100 | else if(result[currv]->parent!=i) 101 | { 102 | result[currv]->low=min(result[currv]->low,result[i]->disc); 103 | } 104 | 105 | } 106 | 107 | } 108 | 109 | int main() 110 | { 111 | int n,m; 112 | cin>>n; 113 | cin>>m; 114 | 115 | int **graph=new int*[n]; 116 | for(int i=0;i>x; 125 | cin>>y; 126 | graph[x][y]=1; 127 | graph[y][x]=1; 128 | } 129 | 130 | for(int i=0;ivert=i; 134 | } 135 | 136 | for(int i=0;iprocessed==true){ 139 | continue; 140 | } 141 | DFT(0,i,graph,result,n); 142 | } 143 | 144 | vector ap; 145 | for(int i=0;ivert<<" --> "<isAP<isAP==true) 149 | { 150 | ap.push_back(result[i]->vert); 151 | } 152 | } 153 | 154 | for(int i=0;iisAP; 158 | 159 | 160 | 161 | return 0; 162 | } 163 | -------------------------------------------------------------------------------- /Algorithms/Graphs/cpp/bridges.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class bridge 5 | { 6 | public: 7 | 8 | int a; 9 | int b; 10 | }; 11 | class ArticulationPair 12 | { 13 | public: 14 | 15 | int vert; 16 | int disc; 17 | int low; 18 | bool isAP; 19 | bool processed; 20 | int parent=-1; 21 | }; 22 | //static int graph[n][n]; 23 | //static ArticulationPair result[n]; 24 | 25 | void DFT(int time,int currv,int **graph,ArticulationPair *result[],int n,vector &bv) 26 | { 27 | result[currv]->processed=true; 28 | result[currv]->disc=result[currv]->low=time; 29 | 30 | int rootChildCounter=0; 31 | 32 | for(int i=0;iprocessed==false) 40 | { 41 | // rootChildCounter++; 42 | result[i]->parent=currv; 43 | DFT(time+1,i,graph,result,n,bv); 44 | result[currv]->low=min(result[currv]->low,result[i]->low); 45 | 46 | 47 | if(result[currv]->disclow) 48 | { 49 | //result[currv]->isAP=true; 50 | bridge br; 51 | br.a=currv; 52 | br.b=i; 53 | bv.push_back(br); 54 | 55 | } 56 | 57 | 58 | 59 | } 60 | else if(result[currv]->parent!=i) 61 | { 62 | result[currv]->low=min(result[currv]->low,result[i]->disc); 63 | } 64 | 65 | } 66 | 67 | } 68 | 69 | int main() 70 | { 71 | int n,m; 72 | cin>>n; 73 | cin>>m; 74 | 75 | int **graph=new int*[n]; 76 | for(int i=0;i bv; 82 | 83 | for(int i=0;i>x; 87 | cin>>y; 88 | graph[x][y]=1; 89 | graph[y][x]=1; 90 | } 91 | 92 | for(int i=0;ivert=i; 96 | } 97 | 98 | for(int i=0;iprocessed==true){ 101 | continue; 102 | } 103 | DFT(0,i,graph,result,n,bv); 104 | } 105 | 106 | vector ap; 107 | for(int i=0;ivert<<" --> "<isAP<isAP==true) 111 | { 112 | ap.push_back(result[i]->vert); 113 | } 114 | } 115 | 116 | // for(int i=0;iisAP; 120 | 121 | vector::iterator vi; 122 | for(vi=bv.begin();vi!=bv.end();vi++) 123 | { 124 | cout<<(*vi).a<<"--"<<(*vi).b< 2 | using namespace std; 3 | static int flow=0; 4 | static int minCapacity=INT_MAX; 5 | /* 6 | static map> dag; //directed acyclic graph 7 | static int flow=0; 8 | static map processed; 9 | static int minCapacity=INT_MAX; 10 | */ 11 | int hasPath(string v1name,string v2name,int mCap,map > &dag,map &processed) 12 | { 13 | processed[v1name]=true; 14 | 15 | if(v1name==v2name) 16 | { 17 | flow+=mCap; 18 | return mCap; 19 | } 20 | 21 | map nbrs=dag[v1name]; 22 | map::iterator mi; 23 | map::iterator mi2; 24 | for(mi=nbrs.begin();mi!=nbrs.end();mi++){ 25 | // cout<first<second; 26 | } 27 | 28 | for(mi=nbrs.begin();mi!=nbrs.end();mi++) 29 | { 30 | // cout<<"test1"<first=processed.find(mi->first); 33 | /* if(processed.find(mi->first)!=processed.end()){ 34 | continue; 35 | }*/ 36 | if(processed.find(mi->first)==processed.end() && dag[v1name][mi->first]>0) 37 | { 38 | 39 | 40 | int cap=dag[v1name][mi->first]; 41 | int revcap=dag[mi->first][v1name]; 42 | //cout<<"test2"<first,v2name,min(cap,mCap),dag,processed); 44 | 45 | if(localMCap!=-1) 46 | { 47 | // cout<<"test3"<first]=cap-localMCap; 49 | dag[mi->first][v1name]=revcap+localMCap; 50 | return localMCap; 51 | } 52 | 53 | 54 | } 55 | // mi++; 56 | } 57 | 58 | return -1; 59 | } 60 | 61 | int main() 62 | { 63 | map > dag; //directed acyclic graph 64 | // static int flow=0; 65 | // static map processed; 66 | 67 | 68 | //vces 69 | /*dag["S"]=new map<0>; 70 | dag["A"]=new map; 71 | dag["B"]=new map; 72 | dag["C"]=new map; 73 | dag["D"]=new map; 74 | dag["T"]=new map;*/ 75 | 76 | //edges 77 | 78 | dag["S"]["A"]=10; 79 | dag["A"]["S"]=0; 80 | 81 | dag["S"]["C"]=8; 82 | dag["C"]["S"]=0; 83 | 84 | dag["A"]["C"]=2; 85 | dag["C"]["A"]=0; 86 | 87 | dag["C"]["D"]=10; 88 | dag["D"]["C"]=0; 89 | 90 | dag["A"]["B"]=5; 91 | dag["B"]["A"]=0; 92 | 93 | dag["D"]["B"]=8; 94 | dag["B"]["D"]=0; 95 | 96 | dag["B"]["T"]=7; 97 | dag["T"]["B"]=0; 98 | 99 | dag["D"]["T"]=10; 100 | dag["T"]["D"]=0; 101 | 102 | 103 | //ford fulkerson 104 | while(true) 105 | { 106 | //processed=new map(); 107 | map processed; 108 | int localMCap=hasPath("S","T",INT_MAX,dag,processed); 109 | if(localMCap==-1) 110 | { 111 | break; 112 | } 113 | } 114 | 115 | cout< 2 | using namespace std; 3 | 4 | void swap(int &a,int &b){ 5 | int temp=a; 6 | a=b; 7 | b=temp; 8 | } 9 | 10 | void knapsack(int n,int m,int w[],float x[]){ 11 | int u =m,i; 12 | for(i=0;iu) 14 | break; 15 | else{ 16 | x[i]=1; 17 | u -=w[i]; 18 | } 19 | } 20 | if(i<=n){ 21 | x[i] = ((u*1.0)/(w[i]*1.0)); 22 | } 23 | } 24 | 25 | int main(){ 26 | int n,m; 27 | cout<<"Enter the number of objects"; 28 | cin>>n; 29 | int p[n],w[n]; 30 | float r[n]={0.0}; 31 | float x[n]={0.0}; 32 | cout<<"Enter the profits of the objects"; 33 | for(int i=0;i>p[i]; 35 | } 36 | cout<<"Enter the weights of the objects"; 37 | for(int i=0;i>w[i]; 39 | } 40 | for(int i=0;i>m; 63 | knapsack(n,m,w,x); 64 | float profit = 0.0; 65 | for(int i=0;i 2 | #include 3 | 4 | void swap(int *a, int *b){ 5 | int aux; 6 | aux = *a; 7 | *a = *b; 8 | *b = aux; 9 | return; 10 | } 11 | 12 | int *heapify(int *arr, int n, int i){ 13 | int largest = i; 14 | int l = 2*i + 1; 15 | int r = 2*i + 2; 16 | 17 | if (l < n && arr[l] > arr[largest]) 18 | largest = 1; 19 | 20 | if (r < n && arr[r] > arr[largest]) 21 | largest = r; 22 | 23 | if (largest != i){ 24 | swap(&arr[i], &arr[largest]); 25 | arr = heapify(arr, n, largest); 26 | } 27 | 28 | return arr; 29 | } 30 | 31 | int * heapsort(int size, int *array){ 32 | int i, j; 33 | for ( i = size / 2 - 1; i >= 0; i--){ 34 | array = heapify(array, size, i); 35 | } 36 | 37 | for(i = size-1; i>=0; i--){ 38 | swap(&array[0], &array[i]); 39 | array = heapify(array, i, 0); 40 | } 41 | 42 | return array; 43 | } 44 | 45 | void printArray(int size, int *array){ 46 | int i; 47 | 48 | if(size == 0){ 49 | printf("Your array has no elements :(\n"); 50 | return; 51 | } 52 | 53 | printf("Ordered array: |"); 54 | for(i=0;i 12 | using namespace std; 13 | 14 | vector kmp(string txt, string pat) 15 | { 16 | string s = pat + '$' + txt; 17 | int n = s.length(), l = pat.length(); 18 | vector LPS(n, 0); 19 | int k = 0; 20 | 21 | /* Building LPS Array */ 22 | for(int i = 1; i < n; ++i) 23 | { 24 | while(k > 0 && s[i] != s[k]) 25 | { 26 | k = LPS[k-1]; 27 | } 28 | if (s[i] == s[k]) 29 | ++k; 30 | LPS[i] = k; 31 | } 32 | /* Searching for pattern and storing occurences in vector i.e the index where pattern ends */ 33 | vector pos; 34 | for(int i = 0; i < n; ++i) 35 | { 36 | if (LPS[i] == l) 37 | { 38 | pos.push_back(i-l-1); 39 | } 40 | } 41 | return pos; 42 | } 43 | 44 | int main() 45 | { 46 | string text,pattern; 47 | cin>>text>>pattern; 48 | vector ans=kmp(text,pattern); 49 | for(auto y:ans) 50 | { 51 | cout< 2 | using namespace std; 3 | 4 | // A utility function that returns maximum of two integers 5 | int max(int a, int b) { return (a > b)? a : b; } 6 | 7 | // Returns the maximum value that 8 | // can be put in a knapsack of capacity W 9 | int knapSack(int W, int wt[], int val[], int n) 10 | { 11 | 12 | // Base Case 13 | if (n == 0 || W == 0) 14 | return 0; 15 | 16 | // If weight of the nth item is more 17 | // than Knapsack capacity W, then 18 | // this item cannot be included 19 | // in the optimal solution 20 | if (wt[n-1] > W) 21 | return knapSack(W, wt, val, n-1); 22 | 23 | // Return the maximum of two cases: 24 | // (1) nth item included 25 | // (2) not included 26 | else return max( val[n-1] + knapSack(W-wt[n-1], wt, val, n-1), 27 | knapSack(W, wt, val, n-1) ); 28 | } 29 | 30 | // Driver code 31 | int main() 32 | { 33 | int val[] = {60, 100, 120}; 34 | int wt[] = {10, 20, 30}; 35 | int W = 50; 36 | int n = sizeof(val)/sizeof(val[0]); 37 | cout< RandomisedSelect 9 | Time Complexity: O(n) 10 | */ 11 | 12 | //FUNCTION TO FIND Kth SMALLEST 13 | public static int KthSmallest(int a[],int low,int high,int k){ 14 | 15 | if(k > 0 && k <= high-low+1){ 16 | int partition = randomPartition(a,low,high); 17 | int size = partition-low+1; 18 | 19 | //Check if it's the required answer 20 | if(k == size) 21 | return a[partition]; 22 | 23 | else if(k < size) 24 | return KthSmallest(a, low, partition-1, k); 25 | 26 | else 27 | return KthSmallest(a, partition+1, high, k-size); 28 | } 29 | //Case of failure 30 | return Integer.MIN_VALUE; 31 | } 32 | 33 | 34 | //TO GENERATE RANDOM NO. AND SWAP WITH LAST ELEMENT OF ARRAY 35 | private static int randomPartition(int[] arr, int low, int high) { 36 | int size = high - low +1; 37 | int random = (int)(Math.random()) * (size-1); 38 | swap(arr, low+random, high); 39 | return partition(arr, low, high); 40 | } 41 | 42 | 43 | 44 | //PARTITION THE ARRAY AROUND PIVOT 45 | public static int partition(int arr[],int low,int high){ 46 | //Taking last element of array as pivot 47 | int pivot = arr[high]; 48 | int i = low; 49 | 50 | for(int j = low; j <= high-1; j++){ 51 | 52 | if(arr[j] <= pivot){ 53 | //SWAP arr[i] and arr[j] 54 | swap(arr, i, j); 55 | i++; 56 | } 57 | } 58 | swap(arr, i, high); 59 | return i; 60 | } 61 | 62 | 63 | public static void RandomSwap(int[] arr, int low, int high) { 64 | 65 | Random random = new Random(); 66 | int i = random.nextInt(high-low) + low; 67 | swap(arr,i,high); 68 | } 69 | 70 | 71 | 72 | //UTILITY FUNCTION TO SWAP 73 | public static void swap(int[] arr, int i, int j) { 74 | int temp; 75 | temp=arr[i]; 76 | arr[i]=arr[j]; 77 | arr[j]=temp; 78 | } 79 | 80 | 81 | //MAIN METHOD 82 | public static void main(String[] args) { 83 | Scanner sc = new Scanner(System.in); 84 | 85 | System.out.print("Enter Size of Array: "); 86 | int n = sc.nextInt(); 87 | 88 | System.out.print("Enter the Array: "); 89 | int arr[] = new int[n]; 90 | for(int i = 0;i < n; i++) 91 | arr[i] = sc.nextInt(); 92 | 93 | System.out.print("Enter Value of K : "); 94 | int k = sc.nextInt(); 95 | 96 | //Input ends 97 | sc.close(); 98 | 99 | int answer = KthSmallest(arr,0,arr.length-1,k); 100 | if(answer == Integer.MIN_VALUE) 101 | System.out.println("Invalid Input!!"); 102 | else 103 | System.out.println("Kth smallest element is : "+answer); 104 | } 105 | 106 | } 107 | -------------------------------------------------------------------------------- /Algorithms/Mergesort/C/mergesort.c: -------------------------------------------------------------------------------- 1 | /* 2 | a[] is the array, p is starting index, that is 0, 3 | and r is the last index of array. 4 | */ 5 | 6 | #include 7 | 8 | // lets take a[5] = {32, 45, 67, 2, 7} as the array to be sorted. 9 | 10 | // merge sort function 11 | void mergeSort(int a[], int p, int r) 12 | { 13 | int q; 14 | if(p < r) 15 | { 16 | q = (p + r) / 2; 17 | mergeSort(a, p, q); 18 | mergeSort(a, q+1, r); 19 | merge(a, p, q, r); 20 | } 21 | } 22 | 23 | // function to merge the subarrays 24 | void merge(int a[], int p, int q, int r) 25 | { 26 | int b[5]; //same size of a[] 27 | int i, j, k; 28 | k = 0; 29 | i = p; 30 | j = q + 1; 31 | while(i <= q && j <= r) 32 | { 33 | if(a[i] < a[j]) 34 | { 35 | b[k++] = a[i++]; // same as b[k]=a[i]; k++; i++; 36 | } 37 | else 38 | { 39 | b[k++] = a[j++]; 40 | } 41 | } 42 | 43 | while(i <= q) 44 | { 45 | b[k++] = a[i++]; 46 | } 47 | 48 | while(j <= r) 49 | { 50 | b[k++] = a[j++]; 51 | } 52 | 53 | for(i=r; i >= p; i--) 54 | { 55 | a[i] = b[--k]; // copying back the sorted list to a[] 56 | } 57 | } 58 | 59 | // function to print the array 60 | void printArray(int a[], int size) 61 | { 62 | int i; 63 | for (i=0; i < size; i++) 64 | { 65 | printf("%d ", a[i]); 66 | } 67 | printf("\n"); 68 | } 69 | 70 | int main() 71 | { 72 | int arr[] = {32, 45, 67, 2, 7}; 73 | int len = sizeof(arr)/sizeof(arr[0]); 74 | 75 | printf("Given array: \n"); 76 | printArray(arr, len); 77 | 78 | // calling merge sort 79 | mergeSort(arr, 0, len - 1); 80 | 81 | printf("\nSorted array: \n"); 82 | printArray(arr, len); 83 | return 0; 84 | } 85 | -------------------------------------------------------------------------------- /Algorithms/Mergesort/c++/mergesort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | //the copy function copies the source elements from the 7 | //index l to the index r, setting all in the destiny, from the k index; 8 | void copy(int destiny[],int k,int source[],int l, int r){ 9 | for(int i=l;i<=r;i++) 10 | destiny[k++] = source[i]; 11 | } 12 | 13 | //merge the b and c arrays and put on the a array based from the smallers of both b and c arrays 14 | void merge(int b[],int c[],int a[],int p, int q){ 15 | int i,j,k; 16 | i=j=k=0; 17 | while(i

1){ 36 | int b[n/2],c[n/2+1]; 37 | copy(b,0,a, 0, n/2-1); 38 | copy(c,0,a, n/2, n-1); 39 | mergesort(b,n/2); 40 | mergesort(c,ceil(n/2.0)); 41 | merge(b,c,a,n/2,ceil(n/2.0)); 42 | } 43 | } 44 | 45 | //testing 46 | int main() { 47 | int vet[9]={5,7,1,4,3,6,9,8,2}; 48 | mergesort(vet,9); 49 | for(int i=0;i<9;i++) cout << vet[i] << " "; 50 | } -------------------------------------------------------------------------------- /Algorithms/Mergesort/erlang/mergesort.erl: -------------------------------------------------------------------------------- 1 | -module(mergesort). 2 | -export([merge_sort/1]). 3 | 4 | merge_sort(UnsortedList) when length(UnsortedList) =< 1 -> UnsortedList; 5 | merge_sort(UnsortedList) -> 6 | Half = length(UnsortedList) div 2, 7 | {Left, Right} = lists:split(Half, UnsortedList), 8 | lists:merge(merge_sort(Left), merge_sort(Right)). 9 | -------------------------------------------------------------------------------- /Algorithms/Mergesort/java/MergeSort.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public static class MergeSort { 4 | 5 | public static ArrayList mergeSort(ArrayList a) { 6 | int mid = (a.size() - 1) / 2; 7 | ArrayList half1; 8 | ArrayList half2; 9 | if (a.size() == 1 || a.size() == 0) { 10 | return a; 11 | } else { 12 | 13 | half1 = new ArrayList(a.subList(0, mid)); 14 | half2 = new ArrayList(a.subList(mid, a.size() - 1)); 15 | 16 | return merge(mergeSort(half1), mergeSort(half2)); 17 | } 18 | } 19 | 20 | @SuppressWarnings("unchecked") 21 | public static ArrayList merge(ArrayList listA, ArrayList listB){ 22 | ArrayList merged = new ArrayList(); 23 | ArrayList list1 = (ArrayList) listA.clone(); 24 | ArrayList list2 = (ArrayList) listB.clone(); 25 | while(list1.size() > 0 && list2.size() > 0) { 26 | if(list1.get(0) > list2.get(0)) { 27 | merged.add(list2.get(0)); 28 | list2.remove(0); 29 | } else if(list2.get(0) > list1.get(0)) { 30 | merged.add(list1.get(0)); 31 | list1.remove(0); 32 | } else { 33 | merged.add(list1.get(0)); 34 | merged.add(list2.get(0)); 35 | list1.remove(0); 36 | list2.remove(0); 37 | } 38 | } 39 | 40 | if(list1.size() == 0) { 41 | for(Integer e : list2) { 42 | merged.add(e); 43 | } 44 | } else if (list2.size() == 0) { 45 | for(Integer e : list1) { 46 | merged.add(e); 47 | } 48 | } 49 | 50 | 51 | 52 | return merged; 53 | 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /Algorithms/Mergesort/java/mergesort.java: -------------------------------------------------------------------------------- 1 | public class mergesort{ 2 | 3 | private int[] sort(int[] array, int front, int half, int back){ 4 | int arr[] = array; 5 | int sub1[] = new int[half-front+1]; 6 | int sub2[] = new int[back-half]; 7 | int s1ind, s2ind, ogind; 8 | for(s1ind = 0; s1ind < sub1.length; s1ind++) 9 | sub1[s1ind] = arr[front+s1ind]; 10 | for(s2ind = 0; s2ind < sub2.length; s2ind++) 11 | sub2[s2ind] = arr[half+s2ind+1]; 12 | s1ind = s2ind = 0; 13 | ogind = front; 14 | while(s1ind < sub1.length && s2ind < sub2.length){ 15 | if(sub1[s1ind] < sub2[s2ind]) 16 | arr[ogind] = sub1[s1ind++]; 17 | else 18 | arr[ogind] = sub2[s2ind++]; 19 | ogind++; 20 | } 21 | while(s1ind < sub1.length) 22 | arr[ogind++] = sub1[s1ind++]; 23 | while(s2ind < sub2.length) 24 | arr[ogind++] = sub2[s2ind++]; 25 | return arr; 26 | } 27 | private void mergesort(int[] arr, int front, int back){ 28 | if(front < back){ 29 | int half = (front+(back-1))/2; 30 | mergesort(arr, front, half); 31 | mergesort(arr, half+1, back); 32 | arr = sort(arr, front, half, back); 33 | } 34 | } 35 | private void mergesort(int[] arr){ 36 | mergesort(arr, 0, arr.length-1); 37 | } 38 | private void printVals(int[] arr){ 39 | for(int x = 0; x < arr.length; x++){ 40 | System.out.print(arr[x]); 41 | if(x != arr.length-1) System.out.print(", "); 42 | } 43 | System.out.println(); 44 | } 45 | public static void main(String[] args){ 46 | int[] vet={5,7,1,4,3,6,9,8,2}; 47 | /*By standard procedure, an object should be capitalized. 48 | * However by the rules of this repository, this file (and therefore 49 | * this object) must be lowercase. 50 | */ 51 | mergesort m = new mergesort(); 52 | m.mergesort(vet); 53 | m.printVals(vet); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /Algorithms/Mergesort/python/mergesort.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | def mergesort(unsorted_list): 4 | n = len(unsorted_list) 5 | if n > 1: 6 | m = n // 2 7 | left = unsorted_list[:m] 8 | right = unsorted_list[m:] 9 | mergesort(left) 10 | mergesort(right) 11 | merge(unsorted_list, left, right) 12 | 13 | def merge(original, left, right): 14 | i = j = k = 0 15 | nleft = len(left) 16 | nright = len(right) 17 | while i < nleft and j < nright: 18 | if left[i] < right[j]: 19 | original[k] = left[i] 20 | i += 1 21 | else: 22 | original[k] = right[j] 23 | j += 1 24 | k += 1 25 | while i < nleft: 26 | original[k] = left[i] 27 | i += 1 28 | k += 1 29 | while j < nright: 30 | original[k] = right[j] 31 | j += 1 32 | k += 1 33 | 34 | if __name__ == '__main__': 35 | example_list = [-1, 1, 1, 0, -2, 199, 204, 1000, -400, 6] 36 | print(example_list) 37 | mergesort(example_list) 38 | print(example_list) 39 | -------------------------------------------------------------------------------- /Algorithms/Quicksort/Python/naive_quicksort.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | def quicksort(unsorted_list): 4 | """ 5 | T(n) = max{T(r - 1) + T(n - r) + O(n)} 6 | r: rank of pivot 7 | worst case => O(n^2) 8 | avg case => O(c*nlogn) 9 | """ 10 | if unsorted_list == None: 11 | raise Exception('NoneType') 12 | n = len(unsorted_list) 13 | if n < 2: 14 | return unsorted_list 15 | pivot = unsorted_list[0] 16 | left = list(filter(lambda x : x < pivot, unsorted_list[1:])) 17 | right = list(filter(lambda x : x >= pivot, unsorted_list[1:])) 18 | return quicksort(left) + [pivot] + quicksort(right) 19 | 20 | if __name__ == '__main__': 21 | example_list = [-1, 1, 1, -2, -1, -9999, 0, 10000] 22 | print(quicksort(example_list)) 23 | 24 | -------------------------------------------------------------------------------- /Algorithms/Quicksort/c++/quicksort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using std::cout; 4 | 5 | void quick_sort(int a[], int left, int right) { 6 | int i = left, j = right; 7 | int pivot = a[right]; 8 | 9 | while (i <= j) { 10 | while (a[i] < pivot) 11 | i++; //carry on, this part already sorted 12 | while (a[j] > pivot) 13 | j--; //carry on, this part already sorted 14 | if (i <= j) { // a[i]>=pivot and a[j]<=pivot 15 | //swap a[i] with a[j] 16 | int tmp = a[i]; 17 | a[i] = a[j]; 18 | a[j] = tmp; 19 | i++; 20 | j--; 21 | } 22 | } 23 | 24 | if (left < j) 25 | quick_sort(a, left, j); 26 | if (i < right) 27 | quick_sort(a, i, right); 28 | } 29 | 30 | int main(void) { 31 | int a[10] = { 10, 7, 9, 4, 6, 2, 5, 6, 84, 12}; 32 | int a_size = sizeof(a)/sizeof(a[0]); 33 | 34 | quick_sort(a, 0, a_size-1); 35 | 36 | for (int i = 0; i < a_size; i++) { 37 | cout << a[i] << " "; 38 | } 39 | } -------------------------------------------------------------------------------- /Algorithms/Quicksort/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 | -------------------------------------------------------------------------------- /Algorithms/Recursion/coinchange/c++/coin_change_rec.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int coinchange(int amt, int c[],int n,int currentcoin) 4 | { 5 | if(amt==0) 6 | return 1; 7 | 8 | if(amt<0) 9 | return 0; 10 | int ways=0; 11 | for(int i=currentcoin;i>n; 22 | int c[n]; 23 | //enter the coin denimation in array of size n 24 | for(int i=0;i>c[i]; 27 | } 28 | //enter the amount for which you need no. of ways to get that amount 29 | int amt; 30 | cin>>amt; 31 | cout<<"no. of ways to get amount from given denominations is :"< d2: 47 | print("Unit 2 is less") 48 | for ind,val in zip(range(0,no_of_in),mat[u]): 49 | M[ind][1] = M[ind][1] + alpha * (val - M[ind][1]) 50 | else: 51 | print("Unit 1 is less") 52 | for ind,val in zip(range(0,no_of_in),mat[u]): 53 | M[ind][0] = M[ind][0] + alpha * (val - M[ind][0]) 54 | 55 | print("After unit",u+1) 56 | print(M) 57 | d1 = d2 = 0 58 | 59 | print("\n") 60 | print("==============================") 61 | print("After all the updates are done:") 62 | print("Input array\n") 63 | print(mat) 64 | print("\n") 65 | print("Updated array of weights\n") 66 | print(M) 67 | print("\n") 68 | print("==============================") 69 | 70 | 71 | #printing cluster values 72 | print("Results:") 73 | for u in range(0,no_of_in): 74 | for ind,val in zip(range(0,no_of_in),mat[u]): 75 | d1 = d1 + ((val - M[ind][0])*(val - M[ind][0])) 76 | for ind,val in zip(range(0,no_of_in),mat[u]): 77 | d2 = d2 + ((val - M[ind][1])*(val - M[ind][1])) 78 | 79 | if d1 > d2: 80 | res = "Unit " + str(u+1) + " belongs to 1st output cluster" 81 | print(res) 82 | 83 | else: 84 | res = "Unit " + str(u+1) + " belongs to 2nd output cluster" 85 | print(res) 86 | d1 = d2 = 0 87 | -------------------------------------------------------------------------------- /Algorithms/Search/C++/Binary search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int binarySearch(int arr[], int l, int r, int x) //Binary Search function to find element x in array arr[] 4 | { 5 | if (r >= l) { 6 | int mid = l + (r - l) / 2; //selection of mid element 7 | return (arr[mid]==x ? mid:arr[mid]>x ? binarySearch(arr, l, mid - 1, x) : binarySearch(arr, mid + 1, r, x)); 8 | } 9 | return -1; 10 | } 11 | //Main function 12 | int main(void) 13 | { 14 | int arr[50]; 15 | int x,len;//len stores the number of elements to be given as input 16 | cout<<"Enter length of list = "; 17 | cin>>len; 18 | cout<<"Enter array elements\n"; 19 | for(int i = 0; i < len; i++)//Taking array input 20 | { 21 | cin>>arr[i]; 22 | } 23 | cout<<"Enter element you want to find = "; 24 | cin>>x; 25 | 26 | int result = binarySearch(arr, 0, len, x); 27 | (result == -1) ? cout << "Element is not present in array" 28 | : cout << "Element is present at index " << result; 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /Algorithms/Search/C++/Linear_search.cpp: -------------------------------------------------------------------------------- 1 | // Linear Search // 2 | #include 3 | using namespace std; 4 | int main() 5 | { 6 | int *array; 7 | int offset,search_value,size; 8 | 9 | cout<<"\n\t Enter the size of the array : "; 10 | cin>>size; 11 | 12 | array = new int[size]; 13 | 14 | for(offset=0;offset>array[offset]; 18 | } 19 | 20 | cout<<"\n\t Enter the search value : "; 21 | cin>>search_value; 22 | 23 | for(offset=0;offset 3 | #include 4 | 5 | // Utility function to find minimum of two elements 6 | int min(int x, int y) { return (x<=y)? x : y; } 7 | 8 | /* Returns index of x if present, else returns -1 */ 9 | int fibMonaccianSearch(int arr[], int x, int n) 10 | { 11 | /* Initialize fibonacci numbers */ 12 | int fibMMm2 = 0; // (m-2)'th Fibonacci No. 13 | int fibMMm1 = 1; // (m-1)'th Fibonacci No. 14 | int fibM = fibMMm2 + fibMMm1; // m'th Fibonacci 15 | 16 | /* fibM is going to store the smallest Fibonacci 17 | Number greater than or equal to n */ 18 | while (fibM < n) 19 | { 20 | fibMMm2 = fibMMm1; 21 | fibMMm1 = fibM; 22 | fibM = fibMMm2 + fibMMm1; 23 | } 24 | 25 | // Marks the eliminated range from front 26 | int offset = -1; 27 | 28 | /* while there are elements to be inspected. Note that 29 | we compare arr[fibMm2] with x. When fibM becomes 1, 30 | fibMm2 becomes 0 */ 31 | while (fibM > 1) 32 | { 33 | // Check if fibMm2 is a valid location 34 | int i = min(offset+fibMMm2, n-1); 35 | 36 | /* If x is greater than the value at index fibMm2, 37 | cut the subarray array from offset to i */ 38 | if (arr[i] < x) 39 | { 40 | fibM = fibMMm1; 41 | fibMMm1 = fibMMm2; 42 | fibMMm2 = fibM - fibMMm1; 43 | offset = i; 44 | } 45 | 46 | /* If x is greater than the value at index fibMm2, 47 | cut the subarray after i+1 */ 48 | else if (arr[i] > x) 49 | { 50 | fibM = fibMMm2; 51 | fibMMm1 = fibMMm1 - fibMMm2; 52 | fibMMm2 = fibM - fibMMm1; 53 | } 54 | 55 | /* element found. return index */ 56 | else return i; 57 | } 58 | 59 | /* comparing the last element with x */ 60 | if(fibMMm1 && arr[offset+1]==x)return offset+1; 61 | 62 | /*element not found. return -1 */ 63 | return -1; 64 | } 65 | 66 | /* driver function */ 67 | int main(void) 68 | { 69 | int arr[10] ; 70 | std::cout<<"Enter 10 nos in ascending order\n"; 71 | for(int i=0;i<10;i++) std::cin>>arr[i]; 72 | int n = sizeof(arr)/sizeof(arr[0]); 73 | int x; 74 | std::cout<<"Enter no to search\n"; 75 | std::cin>>x; 76 | printf("Found at index: %d", 77 | fibMonaccianSearch(arr, x, n)); 78 | return 0; 79 | } 80 | -------------------------------------------------------------------------------- /Algorithms/Search/C++/interpolation_search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include 4 | 5 | using namespace std; 6 | template 7 | int interpolatio_n(T1 key,T arr[],T2 size){ 8 | int low=0,high=size-1; 9 | while(low<=high && key>=arr[low] && key <=arr[high]){ 10 | if(low==high){ 11 | if(arr[low]==key) return low; 12 | return -1; 13 | } 14 | 15 | int pos=low+(key-arr[low])*(high-low)/(arr[high]-arr[low]); 16 | if(arr[pos]==key) 17 | return pos; 18 | if(arr[pos]>key) 19 | high=pos-1; 20 | if(arr[pos] 30 | int interpolatio_n(p1 key,vector

arr){ 31 | int low=0,high=arr.size()-1; 32 | while(low<=high && key>=arr[low] && key <=arr[high]){ 33 | if(low==high){ 34 | if(arr[low]==key) return low; 35 | return -1; 36 | } 37 | 38 | int pos=low+(key-arr[low])*(high-low)/(arr[high]-arr[low]); 39 | if(arr[pos]==key) 40 | return pos; 41 | if(arr[pos]>key) 42 | high=pos-1; 43 | if(arr[pos] vec={1.2,2.3,5}; 55 | double arr[]={5.2,6.1,8.9,80.6,91,122.32}; 56 | cout< 2 | using namespace std; 3 | 4 | int ternarySearch(int l, int r, int key, vector arr) 5 | { 6 | if (l < r) 7 | { 8 | 9 | int mid1 = l + (r - l) / 3; 10 | int mid2 = r - (r - l) / 3; 11 | 12 | if (ar[mid1] == key) 13 | return mid1; 14 | 15 | if (ar[mid2] == key) 16 | return mid2; 17 | 18 | if (key < ar[mid1]) 19 | return ternarySearch(l, mid1 - 1, key, ar); 20 | 21 | else if (key > ar[mid2]) 22 | return ternarySearch(mid2 + 1, r, key, ar); 23 | 24 | else 25 | return ternarySearch(mid1 + 1, mid2 - 1, key, ar); 26 | } 27 | 28 | return -1; 29 | } 30 | 31 | // Driver code 32 | 33 | int main() 34 | { 35 | vector arr; 36 | int size; 37 | 38 | cout << "Enter size of array -> "; 39 | cin >> size; 40 | 41 | for(int i = 0; i < size; i++) 42 | { 43 | cin >> arr[i]; 44 | } 45 | 46 | sort(arr.begin(),arr.end()); 47 | 48 | int key; 49 | cout << "Enter key to be searched -> "; 50 | cin >> key; 51 | 52 | int ind = ternarySearch(0, size-1, key, arr); 53 | 54 | if(ind != -1) 55 | cout << "Key found at index -> " << ind << "\n"; 56 | else 57 | cout << "Sorry key not found !\n"; 58 | return 0; 59 | 60 | } 61 | -------------------------------------------------------------------------------- /Algorithms/Search/Java/BinarySearch.java: -------------------------------------------------------------------------------- 1 | class BinarySearch { 2 | 3 | // worst case O(log n) time complexity 4 | public int binarySearch(int[] arr, int start, int end, int target){ 5 | if(start > end) 6 | return -1; 7 | 8 | int mid = (start + end) / 2; 9 | 10 | if(arr[mid] == target) 11 | return mid; 12 | 13 | else if(arr[mid] > target) 14 | return binarySearch(arr, start, mid - 1, target); 15 | 16 | else 17 | return binarySearch(arr, mid + 1, end, target); 18 | 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /Algorithms/Search/Java/LinearSearch.java: -------------------------------------------------------------------------------- 1 | class LinearSearch { 2 | 3 | // worst case O(n) time 4 | public int linearSearch(int[] arr, int k){ 5 | for(int i=0;i= l) { 6 | int mid1 = l + (r - l) / 3; 7 | int mid2 = r - (r - l) / 3; 8 | if (ar[mid1] == key) { 9 | return mid1; 10 | } 11 | if (ar[mid2] == key) { 12 | return mid2; 13 | } 14 | if (key < ar[mid1]) { 15 | return ternarySearch(l, mid1 - 1, key, ar); 16 | } 17 | else if (key > ar[mid2]) { 18 | return ternarySearch(mid2 + 1, r, key, ar); 19 | } 20 | else { 21 | return ternarySearch(mid1 + 1, mid2 - 1, key, ar); 22 | } 23 | } 24 | return -1; 25 | } 26 | public static void main(String args[]) 27 | { 28 | int l, r, p, key; 29 | int ar[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 30 | 31 | l = 0; 32 | 33 | r = 9; 34 | 35 | key = 5; 36 | 37 | p = ternarySearch(l, r, key, ar); 38 | 39 | // Print the result 40 | System.out.println("Index of " + key + " is " + p); // 4 as par 0 base index 41 | 42 | // Checking for 50 43 | key = 50; 44 | 45 | p = ternarySearch(l, r, key, ar); 46 | 47 | // Print the result 48 | System.out.println("Index of " + key + " is " + p); //-1 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Algorithms/Search/JavaScript/BinarySearch.js: -------------------------------------------------------------------------------- 1 | let recursiveFunction = function (arr, x, start, end) { 2 | 3 | // Base Condtion 4 | if (start > end) return false; 5 | 6 | // Find the middle index 7 | let mid=Math.floor((start + end)/2); 8 | 9 | // Compare mid with given key x 10 | if (arr[mid]===x) return true; 11 | 12 | // If element at mid is greater than x, 13 | // search in the left half of mid 14 | if(arr[mid] > x) 15 | return recursiveFunction(arr, x, start, mid-1); 16 | else 17 | 18 | // If element at mid is smaller than x, 19 | // search in the right half of mid 20 | return recursiveFunction(arr, x, mid+1, end); 21 | } 22 | -------------------------------------------------------------------------------- /Algorithms/Search/JavaScript/ReadMe.md: -------------------------------------------------------------------------------- 1 | Algorithms in JavaScript 2 | -------------------------------------------------------------------------------- /Algorithms/Search/Python/BinarySearch.py: -------------------------------------------------------------------------------- 1 | def binarysearch(list, left, right, target): 2 | 3 | while left <= right: 4 | middle = (left + (right-1))//2 5 | 6 | # Start finding x at the center of the list 7 | if list[middle] == x: 8 | return middle 9 | 10 | # if it's not on the center, then check if x is larger than the center 11 | elif list[middle] < x : 12 | #if it's greater then the left partition is ignored 13 | left = middle + 1 14 | 15 | # Or if it's smaller, the right partition is ignored 16 | else: 17 | right = middle - 1 18 | 19 | # return -1 if the element did not exists 20 | return -1 21 | 22 | list = [1,2,5,10,15,30,60,120] 23 | x = 30 24 | result = binarysearch(list, 0, len(list)-1, x) 25 | if result == -1 : 26 | print('{} Not Found in The List'.format(x)) 27 | else: 28 | print('{} Found at index {}'.format(x, result)) -------------------------------------------------------------------------------- /Algorithms/Search/Python/LinearSearch.py: -------------------------------------------------------------------------------- 1 | def Search(list,target): 2 | for i in range(len(list)): 3 | if list[i] == x: 4 | return i 5 | 6 | return -1 7 | 8 | list = [1,2,3,10,20,30] 9 | x = 3 10 | result = Search(list, x) 11 | if result == -1 : 12 | print('{} Not Found in List'.format(x)) 13 | else: 14 | print('{} Found at index {}'.format(x,result)) -------------------------------------------------------------------------------- /Algorithms/Search/c++/binary_search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int binarySearch(int arr[], int l, int r, int x) 4 | { 5 | if (r >= l) { 6 | int mid = l + (r - l) / 2; 7 | 8 | 9 | if (arr[mid] == x) 10 | return mid; 11 | 12 | 13 | if (arr[mid] > x) 14 | return binarySearch(arr, l, mid - 1, x); 15 | 16 | return binarySearch(arr, mid + 1, r, x); 17 | } 18 | 19 | return -1; 20 | } 21 | 22 | int main(void) 23 | { 24 | int arr[] = { 2, 3, 4, 10, 40 }; 25 | int n = sizeof(arr) / sizeof(arr[0]); 26 | int x = 10; 27 | int result = binarySearch(arr, 0, n - 1, x); 28 | (result == -1) ? printf("Element is not present in array") 29 | : printf("Element is present at index %d", 30 | result); 31 | return 0; 32 | } -------------------------------------------------------------------------------- /Algorithms/Search/c/binary_search.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int binarySearch(int arr[], int l, int r, int x) 4 | { 5 | if (r >= l) { 6 | int mid = l + (r - l) / 2; 7 | 8 | 9 | if (arr[mid] == x) 10 | return mid; 11 | 12 | 13 | if (arr[mid] > x) 14 | return binarySearch(arr, l, mid - 1, x); 15 | 16 | return binarySearch(arr, mid + 1, r, x); 17 | } 18 | 19 | return -1; 20 | } 21 | 22 | int main(void) 23 | { 24 | int arr[] = { 2, 3, 4, 10, 40 }; 25 | int n = sizeof(arr) / sizeof(arr[0]); 26 | int x = 10; 27 | int result = binarySearch(arr, 0, n - 1, x); 28 | (result == -1) ? printf("Element is not present in array") 29 | : printf("Element is present at index %d", 30 | result); 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /Algorithms/Search/c/linear_search.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int linearSearch(int* array, int n, int element) { 4 | for(int i = 0; i < n; i++) { 5 | if(*(array+i) == element) { 6 | return i; 7 | } 8 | } 9 | 10 | return -1; 11 | } 12 | 13 | int main() { 14 | int array[] = {5, 4, 7, 9, 1, 2, 6, 8, 0}; 15 | int n = 9; 16 | int element1 = 3; 17 | int element2 = 4; 18 | 19 | int index1 = linearSearch(array, n, element1); 20 | if(index1 >= 0) { 21 | printf("Element %d exists at index %d.\n", element1, index1); 22 | } else { 23 | printf("Element %d doesn't exist in the given array.\n", element1); 24 | } 25 | 26 | int index2 = linearSearch(array, n, element2); 27 | if(index2 >= 0) { 28 | printf("Element %d exists at index %d.\n", element2, index2); 29 | } else { 30 | printf("Element %d doesn't exist in the given array.\n", element2); 31 | } 32 | 33 | return 0; 34 | } -------------------------------------------------------------------------------- /Algorithms/Seive-Of-Eratosthenes/c++/seive.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void SieveOfEratosthenes(int n) 5 | { 6 | 7 | bool prime[n+1]; 8 | memset(prime, true, sizeof(prime)); 9 | 10 | for (int p=2; p*p<=n; p++) 11 | { 12 | if (prime[p] == true) 13 | { 14 | for (int i=p*p; i<=n; i += p) 15 | prime[i] = false; 16 | } 17 | } 18 | 19 | // Print all prime numbers 20 | for (int p=2; p<=n; p++) 21 | if (prime[p]) 22 | cout << p << " "; 23 | } 24 | 25 | int main() 26 | { 27 | int n = 30; 28 | cout << "Prime Numbers below "<< n << endl; 29 | SieveOfEratosthenes(n); 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /Algorithms/SelectionSort/c/selection.cpp: -------------------------------------------------------------------------------- 1 | // C program for implementation of selection sort 2 | #include 3 | 4 | void swap(int *xp, int *yp) 5 | { 6 | int temp = *xp; 7 | *xp = *yp; 8 | *yp = temp; 9 | } 10 | 11 | void selectionSort(int arr[], int n) 12 | { 13 | int i, j, min_idx; 14 | 15 | // One by one move boundary of unsorted subarray 16 | for (i = 0; i < n-1; i++) 17 | { 18 | // Find the minimum element in unsorted array 19 | min_idx = i; 20 | for (j = i+1; j < n; j++) 21 | if (arr[j] < arr[min_idx]) 22 | min_idx = j; 23 | 24 | // Swap the found minimum element with the first element 25 | swap(&arr[min_idx], &arr[i]); 26 | } 27 | } 28 | 29 | /* Function to print an array */ 30 | void printArray(int arr[], int size) 31 | { 32 | int i; 33 | for (i=0; i < size; i++) 34 | printf("%d ", arr[i]); 35 | printf("\n"); 36 | } 37 | 38 | // Driver program to test above functions 39 | int main() 40 | { 41 | int arr[] = {64, 25, 12, 22, 11}; 42 | int n = sizeof(arr)/sizeof(arr[0]); 43 | selectionSort(arr, n); 44 | printf("Sorted array: \n"); 45 | printArray(arr, n); 46 | return 0; 47 | } 48 | 49 | -------------------------------------------------------------------------------- /Algorithms/SelectionSort/java/selectionsort.java: -------------------------------------------------------------------------------- 1 | 2 | public class selectionsort{ 3 | public static void main(String[] args){ 4 | int[] arr = {8,6,7,5,3,0,9}; 5 | printArr(arr); 6 | selectionsort(arr); 7 | printArr(arr); 8 | } 9 | 10 | private static void printArr(int[] array){ 11 | for(int x = 0; x < array.length; x++){ 12 | System.out.print(array[x]); 13 | if(x != array.length-1) 14 | System.out.print(", "); 15 | } 16 | System.out.println(); 17 | } 18 | 19 | private static void selectionsort(int[] array){ 20 | for(int x = 0; x < array.length; x++){ 21 | int indexSmallest = x; 22 | for(int y = x+1; y < array.length; y++) 23 | if(array[y] < array[indexSmallest]) 24 | indexSmallest = y; 25 | int temp = array[x]; 26 | array[x] = array[indexSmallest]; 27 | array[indexSmallest]=temp; 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Algorithms/SelectionSort/python/selectionsort.py: -------------------------------------------------------------------------------- 1 | # Python program for implementation of Selection Sort 2 | 3 | import sys 4 | n = input("Enter elements:") 5 | A=n.split() 6 | # Traverse through all array elements 7 | for i in range(len(A)): 8 | 9 | # Find the minimum element in remaining unsorted array 10 | min_idx = i 11 | for j in range(i+1, len(A)): 12 | if A[min_idx] > A[j]: 13 | min_idx = j 14 | 15 | # Swap the found minimum element with the first element 16 | if min_idx != i: 17 | A[i], A[min_idx] = A[min_idx], A[i] 18 | 19 | # Driver code to test above 20 | print ("Sorted array:") 21 | for i in range(len(A)): 22 | print(A[i]) 23 | 24 | -------------------------------------------------------------------------------- /Algorithms/SelectionSort/rust/SelectionSort.rs: -------------------------------------------------------------------------------- 1 | fn selection_sort(array: &mut [i32]) { 2 | for i in 0..array.len() { 3 | let min_idx = array[i..].iter() 4 | .enumerate() 5 | .min_by_key(|&(_, v)| v) 6 | .map(|(i, _)| i) 7 | .unwrap_or(0); 8 | 9 | array.swap(i, min_idx + i); 10 | } 11 | } 12 | 13 | 14 | fn main() { 15 | 16 | let mut array = [ 5, 9, 7, 3, 1, 2, 6, 10, 8, 4]; 17 | 18 | selection_sort(&mut array); 19 | println!("Sorted Array {:?}", array); 20 | } 21 | 22 | -------------------------------------------------------------------------------- /Algorithms/Sort/C++/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 2 | #include 3 | #include 4 | #include 5 | 6 | #define endl "\n" 7 | #define ll long long int 8 | #define vi vector 9 | #define vll vector 10 | #define vvi vector < vi > 11 | #define pii pair 12 | #define pll pair 13 | #define mod 1000000007 14 | #define inf 1000000000000000001; 15 | #define all(c) c.begin(),c.end() 16 | #define mp(x,y) make_pair(x,y) 17 | #define mem(a,val) memset(a,val,sizeof(a)) 18 | #define eb emplace_back 19 | #define f first 20 | #define s second 21 | #define loop(i,j,n) for(ll i=j;ia[lar]) 34 | { 35 | lar=l; 36 | } 37 | 38 | if(ra[lar]) 39 | { 40 | lar=r; 41 | } 42 | 43 | if(lar!=i) 44 | {swap(a[i],a[lar]); 45 | 46 | heapify(a,lar,n); 47 | } 48 | 49 | } 50 | 51 | void build(int a[],int n) 52 | { 53 | for(int i=n/2-1;i>=0;i--) 54 | { 55 | heapify(a,i,n); 56 | } 57 | for(int j=n-1;j>=0;j--) 58 | { 59 | 60 | swap(a[0],a[j]); 61 | 62 | heapify(a,0,n); 63 | } 64 | 65 | loop(i,0,n) cout<>n; 75 | 76 | int *arr = new int(n); 77 | 78 | loop(i,0,n) cin>>arr[i]; 79 | 80 | build(arr,n); 81 | 82 | return 0; 83 | 84 | } -------------------------------------------------------------------------------- /Algorithms/Sort/c/bubble_sort.c: -------------------------------------------------------------------------------- 1 | #include 2 | void bubble_sort(long[],long); 3 | int main() 4 | { 5 | long array[100],n,c,d,swap; 6 | printf("Enter number of elements\n"); 7 | scanf("%ld", &n); 8 | printf("Enter %ld integers\n", n); 9 | for (c=0;clist[d+1]) 25 | { 26 | t = list[d]; 27 | list[d]=list[d+1]; 28 | list[d+1]=t; 29 | }}}} 30 | -------------------------------------------------------------------------------- /Algorithms/Sort/cpp/bubbleSort.cpp: -------------------------------------------------------------------------------- 1 | // Optimized implementation of Bubble sort 2 | #include 3 | 4 | void swap(int *xp, int *yp) 5 | { 6 | int temp = *xp; 7 | *xp = *yp; 8 | *yp = temp; 9 | } 10 | 11 | // An optimized version of Bubble Sort 12 | void bubbleSort(int arr[], int n) 13 | { 14 | int i, j; 15 | bool swapped; 16 | for (i = 0; i < n-1; i++) 17 | { 18 | swapped = false; 19 | for (j = 0; j < n-i-1; j++) 20 | { 21 | if (arr[j] > arr[j+1]) 22 | { 23 | swap(&arr[j], &arr[j+1]); 24 | swapped = true; 25 | } 26 | } 27 | 28 | // IF no two elements were swapped by inner loop, then break 29 | if (swapped == false) 30 | break; 31 | } 32 | } 33 | 34 | /* Function to print an array */ 35 | void printArray(int arr[], int size) 36 | { 37 | int i; 38 | for (i=0; i < size; i++) 39 | printf("%d ", arr[i]); 40 | printf("n"); 41 | } 42 | 43 | // Driver program to test above functions 44 | int main() 45 | { 46 | int arr[] = {64, 34, 25, 12, 22, 11, 90}; 47 | int n = sizeof(arr)/sizeof(arr[0]); 48 | bubbleSort(arr, n); 49 | printf("Sorted array: \n"); 50 | printArray(arr, n); 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /Algorithms/Sort/cpp/bucketsort.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | implementation of bucket sort 3 | */ 4 | 5 | 6 | #include 7 | #include 8 | using namespace std; 9 | void sort(float arr[], int n) // sort function 10 | { 11 | vector b[n]; 12 | 13 | for (int i=0; i>n; 33 | float arr[n]; 34 | cout<<"enter the elements\n"; 35 | for (int i=0; i>arr[i]; 37 | sort(arr, n); 38 | for (int i=0; i 7 | using namespace std; 8 | int main() 9 | { 10 | int a,b; 11 | cout<<"enter the length and maximum value\n"; 12 | cin>>a>>b; 13 | int k1[a], k2[a]; 14 | for(int i=0;i>k1[i]; 17 | 18 | } 19 | int l1[b+1]; // creating an extra array for counting frequency of elements 20 | for(int i=0;i=0; i--) 31 | { 32 | k2[l1[k1[i]]]=k1[i]; // puting elements in sorted order 33 | l1[k1[i]]-=1; 34 | } 35 | for(int i=1; i<=a;i++) // printing array 36 | cout< 2 | #include 3 | using namespace std; 4 | int main() 5 | { 6 | long long int t,n; 7 | cin>>t; 8 | 9 | for(int i=1;i<=t;i++) 10 | { 11 | cin>>n; 12 | 13 | long long int a[n]; 14 | 15 | for(int j=0;j>a[j]; 18 | } 19 | reverse(a,a+n); 20 | 21 | for(int j=0;j 5 | using namespace std; 6 | int max( int arr[],int b) // defining function to find greatest number 7 | { 8 | int j=arr[0]; 9 | for( int i=1; ij) 11 | j=arr[i]; 12 | return j; 13 | } 14 | void sort( int k[],int b, int z) // sort function to sort the array according to z 15 | { 16 | int y[b];int i; 17 | int count[10] = {0}; 18 | for (i = 0; i < b; i++) 19 | count[ (k[i]/z)%10 ]++; 20 | for (i = 1; i < 10; i++) 21 | count[i] += count[i - 1]; 22 | for (i=b-1; i>= 0;i--) 23 | { 24 | y[count[ (k[i]/z)%10 ] - 1] = k[i]; 25 | count[ (k[i]/z)%10 ]--; 26 | } 27 | for (i = 0; i < b; i++) 28 | k[i] = y[i]; 29 | } 30 | void radixsort(int k[], int n) //RADIX SORT FUNCTION 31 | { 32 | int m = max(k, n); 33 | for (int exp = 1; m/exp > 0; exp *= 10) 34 | sort(k, n, exp); // call for sort function 35 | } 36 | void print(int k[], int n) // funtion to print the array 37 | { 38 | for (int i = 0; i < n; i++) 39 | cout << k[i] << " "; 40 | } 41 | 42 | int main() 43 | { 44 | int a; 45 | cout<<"enter length of array\n"; 46 | cin>>a; 47 | cout<<"enter the elements \n"; 48 | int k[a]; 49 | for(int i=0;i>k[i]; 52 | } 53 | radixsort(k,a); 54 | print(k,a); 55 | 56 | return 0; 57 | } -------------------------------------------------------------------------------- /Algorithms/Sort/python/heapsort.py: -------------------------------------------------------------------------------- 1 | def heapify(nums, heap_size, root_index): 2 | # Assume the index of the largest element is the root index 3 | largest = root_index 4 | left_child = (2 * root_index) + 1 5 | right_child = (2 * root_index) + 2 6 | 7 | # If the left child of the root is a valid index, and the element is greater 8 | # than the current largest element, then update the largest element 9 | if left_child < heap_size and nums[left_child] > nums[largest]: 10 | largest = left_child 11 | 12 | # Do the same for the right child of the root 13 | if right_child < heap_size and nums[right_child] > nums[largest]: 14 | largest = right_child 15 | 16 | # If the largest element is no longer the root element, swap them 17 | if largest != root_index: 18 | nums[root_index], nums[largest] = nums[largest], nums[root_index] 19 | # Heapify the new root element to ensure it's the largest 20 | heapify(nums, heap_size, largest) 21 | 22 | 23 | def heap_sort(nums): 24 | n = len(nums) 25 | 26 | # Create a Max Heap from the list 27 | # The 2nd argument of range means we stop at the element before -1 i.e. 28 | # the first element of the list. 29 | # The 3rd argument of range means we iterate backwards, reducing the count 30 | # of i by 1 31 | for i in range(n, -1, -1): 32 | heapify(nums, n, i) 33 | 34 | # Move the root of the max heap to the end of 35 | for i in range(n - 1, 0, -1): 36 | nums[i], nums[0] = nums[0], nums[i] 37 | heapify(nums, i, 0) 38 | 39 | 40 | # Verify it works 41 | random_list_of_nums = [35, 12, 43, 8, 51] 42 | heap_sort(random_list_of_nums) 43 | print(random_list_of_nums) 44 | -------------------------------------------------------------------------------- /Algorithms/Sort/python/quicksort.py: -------------------------------------------------------------------------------- 1 | # There are different ways to do a Quick Sort partition, this implements the 2 | # Hoare partition scheme. Tony Hoare also created the Quick Sort algorithm. 3 | def partition(nums, low, high): 4 | # We select the middle element to be the pivot. Some implementations select 5 | # the first element or the last element. Sometimes the median value becomes 6 | # the pivot, or a random one. There are many more strategies that can be 7 | # chosen or created. 8 | pivot = nums[(low + high) // 2] 9 | i = low - 1 10 | j = high + 1 11 | while True: 12 | i += 1 13 | while nums[i] < pivot: 14 | i += 1 15 | 16 | j -= 1 17 | while nums[j] > pivot: 18 | j -= 1 19 | 20 | if i >= j: 21 | return j 22 | 23 | # If an element at i (on the left of the pivot) is larger than the 24 | # element at j (on right right of the pivot), then swap them 25 | nums[i], nums[j] = nums[j], nums[i] 26 | 27 | 28 | def quick_sort(nums): 29 | # Create a helper function that will be called recursively 30 | def _quick_sort(items, low, high): 31 | if low < high: 32 | # This is the index after the pivot, where our lists are split 33 | split_index = partition(items, low, high) 34 | _quick_sort(items, low, split_index) 35 | _quick_sort(items, split_index + 1, high) 36 | 37 | _quick_sort(nums, 0, len(nums) - 1) 38 | 39 | 40 | # Verify it works 41 | random_list_of_nums = [22, 5, 1, 18, 99] 42 | quick_sort(random_list_of_nums) 43 | print(random_list_of_nums) 44 | -------------------------------------------------------------------------------- /Algorithms/Sudoku_Solver/cpp/sudoku_solver.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | bool canplace(int mat[100][100],int i,int j,int num,int n){ 5 | //check in col and row 6 | for(int x=0;x>n; 58 | int mat[100][100]; 59 | for(int i=0;i>mat[i][j]; 62 | } 63 | } 64 | bool ans=solve_sudoku(mat,0,0,n); 65 | if(!ans){ 66 | cout<<"could not solve"< 6 | #include 7 | using namespace std; 8 | 9 | void init(stack &s, int n); 10 | void print_stack(stack s); 11 | void print_towers(); 12 | void solve(stack &, stack &, stack &, int); 13 | 14 | // Declare the towers. 15 | stack towers[3]; 16 | 17 | int main() 18 | { 19 | 20 | int n; 21 | 22 | cout<<"Enter the no of stacks: "; 23 | cin>>n; 24 | 25 | init(towers[2], n); 26 | 27 | cout<<"Solving... "< &s, int n) 34 | { 35 | // Initializes the stack with numbers 36 | // from 1 to n (both inclusive). 37 | for (int i = n; i >= 1; i--) 38 | s.push(i); 39 | } 40 | 41 | void print_stack(stack s) 42 | { 43 | // Function to print a single stack. 44 | if (s.empty()) 45 | { 46 | cout<<"Empty stack."< temp; // Create a temporary stack. 54 | while (!s.empty()) 55 | { 56 | temp.push(s.top()); 57 | s.pop(); 58 | } 59 | 60 | // Print the elements of the temp stack. 61 | while (!temp.empty()) 62 | { 63 | cout< &initial, stack &final, stack &auxiliary, int n) 81 | { 82 | // Function to solve the problem. 83 | if (n == 1) 84 | { 85 | final.push(initial.top()); 86 | initial.pop(); 87 | 88 | print_towers(); 89 | return; 90 | } 91 | 92 | print_towers(); 93 | 94 | solve(initial, auxiliary, final, n - 1); 95 | solve(initial, final, auxiliary, 1); 96 | solve(auxiliary, final, initial, n - 1); 97 | } 98 | -------------------------------------------------------------------------------- /Algorithms/TowerOfHanoiOptimised/Java/TowerOfHanoi.java: -------------------------------------------------------------------------------- 1 | /*Tower of Hanoi without recursion or stack */ 2 | 3 | import java.util.*; 4 | import java.lang.*; 5 | import java.io.*; 6 | 7 | class Priyanshu { 8 | 9 | public static String generateString(int x) { 10 | String s = ""; 11 | for(int i = 1; i <= x; i++) { 12 | if(i == 1) s += "1"; 13 | else { 14 | String t = s; 15 | s += "" + i; 16 | s += t; 17 | } 18 | } 19 | return s; 20 | } 21 | 22 | public static void doIt(int n) { 23 | String s = generateString(n); 24 | 25 | String[] poso = new String[3]; 26 | String[] pose = new String[3]; 27 | int[] index = new int[n+1]; 28 | 29 | for(int i = 1, count = 1; i <= n; i += 2, count++) { 30 | index[i] = 0; 31 | } 32 | 33 | if(n%2 != 0) { 34 | poso[0] = "A"; poso[1] = "C"; poso[2] = "B"; 35 | pose[0] = "A"; pose[1] = "B"; pose[2] = "C"; 36 | } else { 37 | poso[0] = "A"; poso[1] = "B"; poso[2] = "C"; 38 | pose[0] = "A"; pose[1] = "C"; pose[2] = "B"; 39 | } 40 | 41 | for(int i = 0; i < s.length(); i++) { 42 | int c = Integer.parseInt(""+s.charAt(i)); 43 | if(c%2 != 0) { 44 | System.out.println("Move plate " + c + " from " + poso[index[c]%3] + " to " + poso[(index[c]+1)%3]); 45 | index[c]++; 46 | } else { 47 | System.out.println("Move plate " + c + " from " + pose[index[c]%3] + " to " + pose[(index[c]+1)%3]); 48 | index[c]++; 49 | } 50 | 51 | } 52 | 53 | } 54 | 55 | public static void main (String[] args) { 56 | doIt(4); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Algorithms/Word Boggle/Problem_Description.md: -------------------------------------------------------------------------------- 1 | Problem: Given a dictionary, a method to do lookup in dictionary and a M x N board where every cell has one character. Find all possible words that can be formed by a sequence of adjacent characters. 2 | Note that we can move to any of 8 adjacent characters, 3 | but a word should not have multiple instances of same cell. 4 | -------------------------------------------------------------------------------- /Algorithms/Word Boggle/WORD_BOGGLE.java: -------------------------------------------------------------------------------- 1 | //java solution for word boggle problem 2 | 3 | import java.lang.*; 4 | import java.io.*; 5 | 6 | class GFG { 7 | 8 | TrieNode root; 9 | Set answer; 10 | GFG(){ 11 | root=new TrieNode(); 12 | answer=new TreeSet<>(); 13 | } 14 | 15 | static class TrieNode{ 16 | Map children; 17 | boolean isEnd; 18 | TrieNode(){ 19 | children=new HashMap<>(); 20 | isEnd=false; 21 | } 22 | } 23 | 24 | void insert(String word){ 25 | if(word==null) return; 26 | TrieNode node=root; 27 | for(char ch:word.toCharArray()){ 28 | if(node.children.get(ch)==null) 29 | node.children.put(ch,new TrieNode()); 30 | node=node.children.get(ch); 31 | } 32 | node.isEnd=true; 33 | } 34 | 35 | void findWords(char boggle[][], int M, int N){ 36 | boolean vis[][]=new boolean[M][N]; 37 | TrieNode child=root; 38 | String str=""; 39 | for(int i=0;i=0 && i=0 && j0){ 104 | GFG ob=new GFG(); 105 | int n=sc.nextInt(); 106 | String dict[]=new String[n]; 107 | for(int i=0;i { 46 | if (!(graph.vertices[start])){ 47 | console.log("Starting vertex must be in given Graph."); 48 | return null; 49 | } 50 | 51 | let queue = [[start,[start]]]; 52 | let visited = new Set([start]); 53 | 54 | while (queue.length > 0) { 55 | let current = queue.shift(); 56 | let currentVal = current[0]; 57 | let currentPath = current[1]; 58 | 59 | visited.add(graph.vertices[currentVal]); 60 | 61 | for (const vertex of graph.vertices[currentVal].connections) { 62 | if (!visited.has(vertex)) { 63 | 64 | let path = currentPath.slice() 65 | path.push(vertex.value); 66 | 67 | if (vertex.value === target) { 68 | return path; 69 | } else { 70 | queue.push([vertex.value,path]); 71 | } 72 | } 73 | 74 | } 75 | 76 | } 77 | return null; 78 | } 79 | 80 | const dfs = (start, target, graph) => { 81 | if (!(graph.vertices[start])){ 82 | console.log("Starting vertex must be in given Graph."); 83 | return null; 84 | } 85 | 86 | let stack = [[start,[start]]]; 87 | let visited = new Set([start]); 88 | 89 | while (stack.length > 0) { 90 | let current = stack.pop(); 91 | let currentVal = current[0]; 92 | let currentPath = current[1]; 93 | 94 | visited.add(graph.vertices[currentVal]); 95 | 96 | for (const vertex of graph.vertices[currentVal].connections) { 97 | if (!visited.has(vertex)) { 98 | 99 | let path = currentPath.slice() 100 | path.push(vertex.value); 101 | 102 | if (vertex.value === target) { 103 | return path; 104 | } else { 105 | stack.push([vertex.value,path]); 106 | } 107 | } 108 | 109 | } 110 | 111 | } 112 | return null; 113 | } 114 | 115 | 116 | function testBfsDfs() { 117 | 118 | let graph = new Graph(); 119 | graph.addVertex(1); 120 | graph.addVertex(2); 121 | graph.addVertex(3); 122 | graph.addVertex(4); 123 | graph.addVertex(5); 124 | graph.connectVertices(1,2); 125 | graph.connectVertices(1,3); 126 | graph.connectVertices(2,4); 127 | graph.connectVertices(3,5); 128 | console.log(dfs(1,5,graph)); 129 | console.log(bfs(1,5,graph)); 130 | console.log(dfs(1,4,graph)); 131 | console.log(bfs(1,4,graph)); 132 | 133 | } 134 | 135 | testBfsDfs(); -------------------------------------------------------------------------------- /Algorithms/bfs_dfs/python/bfs_dfs.py: -------------------------------------------------------------------------------- 1 | #This is an unweighted graph. To add weights, one would have to changed Vertex.edges to a dictionary, where the keys are the vertices and the values 2 | #are the edge weights. 3 | 4 | class Vertex: 5 | def __init__(self, value): 6 | self.value = value 7 | self.edges = set() 8 | 9 | def addEdge(self, vertexToAdd): 10 | self.edges.add(vertexToAdd) 11 | 12 | def getEdges(self): 13 | return [self.edges.value for edge in self.edges] 14 | 15 | def getValue(self): 16 | return self.value 17 | 18 | class Graph: 19 | def __init__(self): 20 | self.vertices = {} 21 | 22 | def addVertex(self, vertexToAdd): 23 | if vertexToAdd in self.vertices: 24 | raise ValueError("Vertex is already in the graph.") 25 | 26 | self.vertices[vertexToAdd] = Vertex(vertexToAdd) 27 | 28 | def connectVertices(self, vertexA, vertexB): 29 | if (vertexA not in self.vertices) or (vertexB not in self.vertices): 30 | raise ValueError("Both vertices given must be in the graph.") 31 | 32 | self.vertices[vertexA].addEdge(self.vertices[vertexB]) 33 | self.vertices[vertexB].addEdge(self.vertices[vertexA]) 34 | 35 | def getVertices(self): 36 | return self.vertices.keys() 37 | 38 | 39 | #Breadth first search for Graph. Time complexity O(Vertices + Edges). Space complexity = O(Vertices) 40 | def bfs(startValue, targetValue, graphToSearch): 41 | if (startValue not in graphToSearch.vertices): 42 | raise ValueError("The starting vertex is not in specified graph.") 43 | 44 | queue = [[startValue, [startValue]]] 45 | visited = set([startValue]) 46 | 47 | while (len(queue) > 0): 48 | currentValue,currentPath = queue.pop(0) 49 | currentVertex = graphToSearch.vertices[currentValue] 50 | 51 | for vertex in currentVertex.edges: 52 | if vertex.value not in visited: 53 | path = currentPath + [vertex.value] 54 | if vertex.value == targetValue: 55 | return path 56 | else: 57 | queue.append([vertex.value, path]) 58 | visited.add(vertex.value) 59 | 60 | return None 61 | 62 | #Depth first search for Graph. Time complexity O(Vertices + Edges). Space complexity = O(Vertices) 63 | def dfs(startValue, targetValue, graphToSearch): 64 | if (startValue not in graphToSearch.vertices): 65 | raise ValueError("The starting vertex is not in specified graph.") 66 | 67 | stack = [[startValue, [startValue]]] 68 | visited = set([startValue]) 69 | 70 | while (len(stack) > 0): 71 | currentValue,currentPath = stack.pop() 72 | currentVertex = graphToSearch.vertices[currentValue] 73 | 74 | for vertex in currentVertex.edges: 75 | if vertex.value not in visited: 76 | path = currentPath + [vertex.value] 77 | if vertex.value == targetValue: 78 | return path 79 | else: 80 | stack.append([vertex.value, path]) 81 | visited.add(vertex.value) 82 | 83 | return None 84 | 85 | #Testing both search functions 86 | def test_bfs_dfs(): 87 | graph = Graph() 88 | for i in range(1,6): 89 | graph.addVertex(i) 90 | graph.connectVertices(1,2) 91 | graph.connectVertices(1,3) 92 | graph.connectVertices(2,4) 93 | graph.connectVertices(3,5) 94 | 95 | test_case1 = bfs(1,5,graph) 96 | test_case2 = dfs(1,5,graph) 97 | test_case3 = bfs(1,6,graph) 98 | test_case4 = dfs(1,6,graph) 99 | if test_case1 != [1,3,5]: 100 | return False 101 | if test_case2 != [1,3,5]: 102 | return False 103 | if test_case3: 104 | return False 105 | if test_case4: 106 | return False 107 | return True 108 | 109 | print(test_bfs_dfs()) 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | -------------------------------------------------------------------------------- /Algorithms/binary_expo.cpp: -------------------------------------------------------------------------------- 1 | //Code to a^b using Binary Exponentiation with O(log n) 2 | #include 3 | using namespace std; 4 | int binpow(int a,int b) 5 | { 6 | if(b==0) 7 | { 8 | return 1; 9 | } 10 | int res = binpow(a,b/2); 11 | if(b%2==0) 12 | { 13 | return res*res; 14 | } 15 | else 16 | { 17 | return res*res*a; //if exponent is odd 18 | } 19 | } 20 | using namespace std; 21 | int main() 22 | { 23 | int base,expo 24 | cout<<"Note: Base, Exponent and Modulo cannot be greater than 2e9\n"<>base; 27 | 28 | cout<<"\nEnter Exponent: "; 29 | cin>>expo; 30 | 31 | cout<<"Result (base^expo): "< 2 | #include 3 | using namespace std; 4 | 5 | void printVals(int arr[], int size){ 6 | for(int x = 0; x < size; x++){ 7 | cout << arr[x]; 8 | if(x != size-1) 9 | cout << ", "; 10 | } 11 | cout << endl; 12 | } 13 | 14 | bool sorted(int arr[], int size){ 15 | for(int x = 0; x < size-1; x++){ 16 | if(arr[x] > arr[x+1]) 17 | return false; 18 | } 19 | return true; 20 | } 21 | 22 | void shuffle(int arr[], int size){ 23 | random_device random; 24 | for(int x = 0; x < size; x++){ 25 | char r = random()%size; 26 | int temp = arr[x]; 27 | arr[x] = arr[r]; 28 | arr[r] = temp; 29 | } 30 | } 31 | 32 | void bogo(int arr[], int size){ 33 | printVals(arr, size); 34 | int count = 1; 35 | while(!sorted(arr, size)){ 36 | shuffle(arr, size); 37 | cout << count++ << " - "; 38 | printVals(arr, size); 39 | } 40 | } 41 | 42 | int main(){ 43 | int arr[] = {8,6,7,5,3,0,9}; 44 | bogo(arr, 7); 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /Algorithms/bogosort/README.md: -------------------------------------------------------------------------------- 1 | Hi folks, 2 | 3 | This algorithm is garbage. It's literally called "stupid sort". The way it works, is that you take an array and you shuffle it. Is it in order? If not, start over. 4 | 5 | It's like throwing a deck of cards in the air. If it's not in completely perfect order, numbers and suits, you throw the deck again. 6 | 7 | However I did learn this in my Data Structures and Algorithms class. So, today I bless you with the fantastic "Quantum Bogosort". 8 | 9 | -------------------------------------------------------------------------------- /Algorithms/bogosort/java/bogosort.java: -------------------------------------------------------------------------------- 1 | public class bogosort{ 2 | private static void printVals(int arr[], int size){ 3 | for(int x = 0; x < size; x++){ 4 | System.out.print(arr[x]); 5 | if(x != size-1) 6 | System.out.print(", "); 7 | } 8 | System.out.println(); 9 | } 10 | 11 | private static boolean sorted(int arr[], int size){ 12 | for(int x = 0; x < size-1; x++){ 13 | if(arr[x] > arr[x+1]) 14 | return false; 15 | } 16 | return true; 17 | } 18 | 19 | private static int[] shuffle(int arr[], int size){ 20 | for(int x = 0; x < size; x++){ 21 | int r = (int)(Math.random()*size); 22 | int temp = arr[x]; 23 | arr[x] = arr[r]; 24 | arr[r] = temp; 25 | } 26 | return arr; 27 | } 28 | 29 | private static void bogo(int arr[], int size){ 30 | printVals(arr, size); 31 | int count = 1; 32 | while(!sorted(arr, size)){ 33 | arr = shuffle(arr, size); 34 | System.out.print(count++ + " - "); 35 | printVals(arr, size); 36 | } 37 | } 38 | 39 | public static void main(String[] args){ 40 | int arr[] = {8,6,7,5,3,0,9}; 41 | bogo(arr, 7); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Algorithms/fast_expo.c: -------------------------------------------------------------------------------- 1 | //Code to find (x^y)%m using Fast Exponentiation 2 | #include 3 | int main() 4 | { 5 | int base,expo,mod=1000000007,ans=1; 6 | char choice; 7 | printf("Note: Base, Exponent and Modulo cannot be greater than 2e9\n"); 8 | printf("Enter Base: "); 9 | scanf("%d",&base); 10 | 11 | printf("\nEnter Exponent: "); 12 | scanf("%d",&expo); 13 | 14 | printf("\nDo you want to change Modulo(default is 1e9 + 7) [y/n]: "); 15 | scanf("%c",&choice); 16 | 17 | if(choice=='y' || 'Y') 18 | scanf("%d",&mod); 19 | 20 | while(expo!=0) 21 | { 22 | if(expo%2 == 0) 23 | { 24 | base=(base*base)%mod; 25 | expo=expo>>1; 26 | //x^y = (x*x)^(y/2) 27 | } 28 | 29 | 30 | else //if exponent is odd expo/2 in c won't be mathematically correct 31 | { 32 | ans=(ans*base)%mod; 33 | expo--; 34 | } 35 | } 36 | 37 | printf("\nAnswer: %d",ans); 38 | 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /Algorithms/graph/c++/Kruskal MST in C++.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | typedef pair iPair; 5 | 6 | struct Graph 7 | { 8 | int V, E; 9 | vector< pair > edges; 10 | 11 | Graph(int V, int E) 12 | { 13 | this->V = V; 14 | this->E = E; 15 | } 16 | 17 | void addEdge(int u, int v, int w) 18 | { 19 | edges.push_back({w, {u, v}}); 20 | } 21 | 22 | int kruskalMST(); 23 | }; 24 | 25 | struct DisjointSets 26 | { 27 | int *parent, *rnk; 28 | int n; 29 | 30 | DisjointSets(int n) 31 | { 32 | this->n = n; 33 | parent = new int[n+1]; 34 | rnk = new int[n+1]; 35 | 36 | 37 | for (int i = 0; i <= n; i++) 38 | { 39 | rnk[i] = 0; 40 | 41 | parent[i] = i; 42 | } 43 | } 44 | 45 | int find(int u) 46 | { 47 | if (u != parent[u]) 48 | parent[u] = find(parent[u]); 49 | return parent[u]; 50 | } 51 | 52 | 53 | void merge(int x, int y) 54 | { 55 | x = find(x), y = find(y); 56 | 57 | if (rnk[x] > rnk[y]) 58 | parent[y] = x; 59 | else 60 | parent[x] = y; 61 | 62 | if (rnk[x] == rnk[y]) 63 | rnk[y]++; 64 | } 65 | }; 66 | 67 | 68 | int Graph::kruskalMST() 69 | { 70 | int mst_wt = 0; 71 | 72 | sort(edges.begin(), edges.end()); 73 | 74 | DisjointSets ds(V); 75 | 76 | vector< pair >::iterator it; 77 | for (it=edges.begin(); it!=edges.end(); it++) 78 | { 79 | int u = it->second.first; 80 | int v = it->second.second; 81 | 82 | int set_u = ds.find(u); 83 | int set_v = ds.find(v); 84 | 85 | if (set_u != set_v) 86 | { 87 | cout << u << " - " << v << endl; 88 | 89 | mst_wt += it->first; 90 | 91 | ds.merge(set_u, set_v); 92 | } 93 | } 94 | 95 | return mst_wt; 96 | } 97 | 98 | int main() 99 | { 100 | int V = 9, E = 14; 101 | Graph g(V, E); 102 | g.addEdge(0, 1, 4); 103 | g.addEdge(0, 7, 8); 104 | g.addEdge(1, 2, 8); 105 | g.addEdge(1, 7, 11); 106 | g.addEdge(2, 3, 7); 107 | g.addEdge(2, 8, 2); 108 | g.addEdge(2, 5, 4); 109 | g.addEdge(3, 4, 9); 110 | g.addEdge(3, 5, 14); 111 | g.addEdge(4, 5, 10); 112 | g.addEdge(5, 6, 2); 113 | g.addEdge(6, 7, 1); 114 | g.addEdge(6, 8, 6); 115 | g.addEdge(7, 8, 7); 116 | 117 | cout << "Edges of MST are \n"; 118 | int mst_wt = g.kruskalMST(); 119 | 120 | cout << "\nWeight of MST is " << mst_wt; 121 | 122 | return 0; 123 | } -------------------------------------------------------------------------------- /Algorithms/knapsack/c++/knapsack.cpp: -------------------------------------------------------------------------------- 1 | /* 0/1 knapsack using dynamic programming */ 2 | #include 3 | using namespace std; 4 | 5 | int knapsack(int W, int wt[], int value[], int N) { 6 | int i,j; 7 | int k[N+1][W+1]; 8 | 9 | for(i=0; i<=N; i++) { 10 | for(j=0; j<=W; j++) { 11 | if(i == 0 || j == 0) { 12 | k[i][j] = 0; 13 | } 14 | else if(wt[i-1] <= j) { 15 | k[i][j] = max(value[i-1] + k[i-1][j-wt[i-1]], k[i-1][j]); 16 | } 17 | else { 18 | k[i][j] = k[i-1][j]; 19 | } 20 | } 21 | } 22 | return k[N][W]; 23 | } 24 | 25 | int main() { 26 | int N = 3; 27 | int value[N] = {40, 20, 100, 60}; 28 | int weight[N] = {1, 2, 3, 4}; 29 | int maxCapacity = 5; 30 | 31 | cout << knapsack(maxCapacity, weight, value, N); 32 | 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /Algorithms/next_greater_element.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void printNGE(int arr[], int n) { 5 | stack < int > s; 6 | 7 | s.push(arr[0]); 8 | 9 | for (int i = 1; i < n; i++) { 10 | 11 | if (s.empty()) { 12 | s.push(arr[i]); 13 | continue; 14 | } 15 | 16 | while (s.empty() == false && s.top() < arr[i]) 17 | { 18 | cout << s.top() << " --> " << arr[i] << endl; 19 | s.pop(); 20 | } 21 | 22 | s.push(arr[i]); 23 | } 24 | 25 | while (s.empty() == false) { 26 | cout << s.top() << " --> " << -1 << endl; 27 | s.pop(); 28 | } 29 | } 30 | 31 | int main() 32 | { 33 | cout << "Enter the length of array"; 34 | int n; 35 | cin >> n; 36 | int arr[n]; 37 | cout << "Enter the elements"; 38 | for (int i = 0; i < n; i++) 39 | { 40 | cin >> arr[i]; 41 | } 42 | 43 | printNGE(arr, n); 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /Algorithms/ratInMazeAllPaths.py: -------------------------------------------------------------------------------- 1 | def isSafe(x, y, maze, sol): 2 | if(x>=0 and x=0 and y 2 | #include 3 | 4 | struct node 5 | { 6 | int key; 7 | struct node *left, *right; 8 | }; 9 | 10 | // A utility function to create a new BST node 11 | struct node *newNode(int item) 12 | { 13 | struct node *temp = (struct node *)malloc(sizeof(struct node)); 14 | temp->key = item; 15 | temp->left = temp->right = NULL; 16 | return temp; 17 | } 18 | 19 | // A utility function to do inorder traversal of BST 20 | void inorder(struct node *root) 21 | { 22 | if (root != NULL) 23 | { 24 | inorder(root->left); 25 | printf("%d \n", root->key); 26 | inorder(root->right); 27 | } 28 | } 29 | 30 | /* A utility function to insert a new node with given key in BST */ 31 | struct node* insert(struct node* node, int key) 32 | { 33 | /* If the tree is empty, return a new node */ 34 | if (node == NULL) return newNode(key); 35 | 36 | /* Otherwise, recur down the tree */ 37 | if (key < node->key) 38 | node->left = insert(node->left, key); 39 | else if (key > node->key) 40 | node->right = insert(node->right, key); 41 | 42 | /* return the (unchanged) node pointer */ 43 | return node; 44 | } 45 | 46 | // Driver Program to test above functions 47 | int main() 48 | { 49 | /* Let us create following BST 50 | 50 51 | / \ 52 | 30 70 53 | / \ / \ 54 | 20 40 60 80 */ 55 | struct node *root = NULL; 56 | root = insert(root, 50); 57 | insert(root, 30); 58 | insert(root, 20); 59 | insert(root, 40); 60 | insert(root, 70); 61 | insert(root, 60); 62 | insert(root, 80); 63 | 64 | // print inoder traversal of the BST 65 | inorder(root); 66 | 67 | return 0; 68 | } 69 | -------------------------------------------------------------------------------- /Data Structures/Binary Tree/C++/NodesBetweenTwoLevels.cpp: -------------------------------------------------------------------------------- 1 | //Nodes between two given levels 2 | 3 | #include 4 | using namespace std; 5 | 6 | struct node 7 | { 8 | int key; 9 | struct node *left, *right; 10 | }; 11 | 12 | // A utility function to create a new BST node 13 | struct node *newNode(int item) 14 | { 15 | struct node *temp = (struct node *)malloc(sizeof(struct node)); 16 | temp->key = item; 17 | temp->left = temp->right = NULL; 18 | return temp; 19 | } 20 | 21 | // A utility function to do inorder traversal of BST 22 | void inorder(struct node *root) 23 | { 24 | if (root != NULL) 25 | { 26 | inorder(root->left); 27 | printf("%d \n", root->key); 28 | inorder(root->right); 29 | } 30 | } 31 | 32 | /* A utility function to insert a new node with given key in BST */ 33 | struct node* insert(struct node* node, int key) 34 | { 35 | /* If the tree is empty, return a new node */ 36 | if (node == NULL) return newNode(key); 37 | 38 | /* Otherwise, recur down the tree */ 39 | if (key < node->key) 40 | node->left = insert(node->left, key); 41 | else if (key > node->key) 42 | node->right = insert(node->right, key); 43 | 44 | /* return the (unchanged) node pointer */ 45 | return node; 46 | } 47 | void print(node*root, int low, int high) 48 | { 49 | if(!root) 50 | return; 51 | 52 | node *marker = new node; 53 | queueq; 54 | //Initial level is 1 55 | int level = 1; 56 | q.push(root); 57 | //Marker delimits levels 58 | q.push(marker); 59 | 60 | while(!q.empty()) 61 | { 62 | node *node = q.front(); 63 | q.pop(); 64 | //End of current level reached 65 | if(node == marker) 66 | { 67 | cout<<"\n"; 68 | level++; 69 | //All nodes which needed to be visited are visited 70 | if(q.empty() || level > high) 71 | break; 72 | q.push(marker); 73 | 74 | continue; 75 | } 76 | 77 | if(level >= low) 78 | cout<key<<" "; 79 | 80 | if(node->left) 81 | q.push(node->left); 82 | if(node->right) 83 | q.push(node->right); 84 | } 85 | } 86 | 87 | // Driver Program to test above functions 88 | int main() 89 | { 90 | /* Let us create following BST 91 | 50 92 | / \ 93 | 30 70 94 | / \ / \ 95 | 20 40 60 80 */ 96 | struct node *root = NULL; 97 | root = insert(root, 50); 98 | insert(root, 30); 99 | insert(root, 20); 100 | insert(root, 40); 101 | insert(root, 70); 102 | insert(root, 60); 103 | insert(root, 80); 104 | 105 | // print inoder traversal of the BST 106 | inorder(root); 107 | print(root, 1, 3); 108 | 109 | return 0; 110 | } 111 | -------------------------------------------------------------------------------- /Data Structures/Binary Tree/c/bt.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | struct btnode 6 | { 7 | 8 | int data; 9 | struct btnode*left; 10 | struct btnode*right; 11 | 12 | }; 13 | 14 | struct btnode*root=NULL,*parent,*temp; 15 | 16 | 17 | 18 | 19 | #define count 10 20 | 21 | 22 | void insertion(); 23 | void display(btnode*,int); 24 | void rootdisp(btnode*); 25 | 26 | 27 | int main() 28 | { 29 | 30 | int ch; 31 | 32 | 33 | while(1) 34 | { 35 | 36 | printf(" CHOOSE FROM THE MENU\n 1.insertion \n 2.display \n 3.exit\n"); 37 | 38 | scanf("%d",&ch); 39 | 40 | 41 | switch(ch) 42 | { 43 | 44 | case 1: insertion(); 45 | break; 46 | 47 | case 2: rootdisp(root); 48 | break; 49 | 50 | 51 | case 3: exit(0); 52 | 53 | 54 | } 55 | 56 | } 57 | 58 | 59 | 60 | 61 | 62 | 63 | return 0; 64 | } 65 | 66 | 67 | 68 | void insertion() 69 | { 70 | 71 | int ch ; 72 | ch=1; 73 | 74 | int countx=0; 75 | 76 | parent=root; 77 | 78 | while(ch==1) 79 | { 80 | 81 | temp = (btnode*)malloc(sizeof(btnode)); 82 | 83 | printf("enter the value of data "); 84 | scanf("%d",&temp->data); 85 | 86 | countx++; 87 | 88 | temp->right=NULL; 89 | temp->left=NULL; 90 | 91 | if(root==NULL) 92 | { 93 | root=temp; 94 | 95 | } 96 | 97 | else 98 | 99 | { 100 | int county=0; 101 | btnode*curr; 102 | 103 | curr=root; 104 | 105 | while(curr) 106 | { 107 | 108 | 109 | parent=curr; 110 | 111 | 112 | if((countx%2)==0) 113 | 114 | { 115 | curr=curr->left; 116 | 117 | 118 | } 119 | 120 | else 121 | { 122 | curr=curr->right; 123 | } 124 | 125 | 126 | 127 | 128 | 129 | } 130 | 131 | if((countx%2)==0) 132 | { 133 | parent->left=temp; 134 | 135 | } 136 | else 137 | { 138 | 139 | parent->right=temp; 140 | 141 | } 142 | 143 | } 144 | 145 | printf(" want to enter more(0/1) "); 146 | scanf("%d",&ch); 147 | 148 | } 149 | 150 | 151 | } 152 | 153 | 154 | 155 | void display(btnode *root,int space) 156 | { 157 | 158 | if (root == NULL) 159 | return; 160 | 161 | 162 | space += count; 163 | 164 | display(root->right, space); 165 | 166 | 167 | printf("\n"); 168 | 169 | for (int i =count; i < space ; i++) 170 | printf(" "); 171 | 172 | printf("%d \n", root->data); 173 | 174 | 175 | display(root->left, space); 176 | } 177 | 178 | 179 | void rootdisp(btnode *root) 180 | { 181 | 182 | display(root, 0); 183 | } 184 | -------------------------------------------------------------------------------- /Data Structures/Binary Tree/c/traversal.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | struct btnode 6 | { 7 | 8 | int data; 9 | struct btnode*left; 10 | struct btnode*right; 11 | 12 | }; 13 | 14 | struct btnode*root=NULL,*parent,*temp; 15 | 16 | 17 | #define count 10 18 | 19 | void insertion(); 20 | void inorder(struct btnode*); 21 | void preorder(struct btnode*); 22 | void postorder(struct btnode*); 23 | 24 | 25 | 26 | int main() 27 | { 28 | 29 | int ch; 30 | 31 | 32 | while(1) 33 | { 34 | 35 | printf(" CHOOSE FROM THE MENU\n 1.insertion \n 2.inorder \n 3.preorder \n 4.postorder \n 5.exit\n"); 36 | 37 | scanf("%d",&ch); 38 | 39 | 40 | switch(ch) 41 | { 42 | 43 | case 1: insertion(); 44 | break; 45 | 46 | case 2: inorder(root); 47 | cout<data); 92 | 93 | countx++; 94 | 95 | temp->right=NULL; 96 | temp->left=NULL; 97 | 98 | if(root==NULL) 99 | { 100 | root=temp; 101 | 102 | } 103 | 104 | else 105 | 106 | { 107 | int county=0; 108 | struct btnode*curr; 109 | 110 | curr=root; 111 | 112 | while(curr) 113 | { 114 | 115 | 116 | parent=curr; 117 | 118 | 119 | if((countx%2)==0) 120 | 121 | { 122 | curr=curr->left; 123 | 124 | 125 | } 126 | 127 | else 128 | { 129 | curr=curr->right; 130 | } 131 | 132 | 133 | } 134 | 135 | if((countx%2)==0) 136 | { 137 | parent->left=temp; 138 | 139 | } 140 | else 141 | { 142 | 143 | parent->right=temp; 144 | 145 | } 146 | 147 | } 148 | 149 | printf(" want to enter more(0/1) "); 150 | scanf("%d",&ch); 151 | 152 | } 153 | 154 | 155 | } 156 | 157 | 158 | 159 | void inorder(struct btnode *root) 160 | { 161 | 162 | if (root == NULL) 163 | return; 164 | inorder(root->left); 165 | printf("%d",root->data); 166 | inorder(root->right); 167 | 168 | } 169 | 170 | void preorder(struct btnode *root) 171 | { 172 | 173 | if (root == NULL) 174 | return; 175 | printf("%d",root->data); 176 | preorder(root->left); 177 | preorder(root->right); 178 | 179 | } 180 | void postorder(struct btnode *root) 181 | { 182 | 183 | if (root == NULL) 184 | return; 185 | postorder(root->left); 186 | postorder(root->right); 187 | printf("%d",root->data); 188 | 189 | } 190 | 191 | 192 | -------------------------------------------------------------------------------- /Data Structures/Binary Tree/python/binary_tree.py: -------------------------------------------------------------------------------- 1 | class Node(): 2 | 3 | def __init__(self,key): 4 | self.key = key 5 | self.left = None 6 | self.right = None 7 | self.parent = None 8 | 9 | 10 | class Tree(): 11 | 12 | def __init__(self): 13 | self.root = None 14 | 15 | def add_node(self,key,node=None): 16 | 17 | if node is None: 18 | node = self.root 19 | 20 | if self.root is None: 21 | self.root = Node(key) 22 | 23 | else: 24 | 25 | if key <= node.key : 26 | if node.left is None: 27 | node.left = Node(key) 28 | node.left.parent = node 29 | print "left" 30 | return 31 | else: 32 | # return self.add_node(key,node = self.root.left) 33 | return self.add_node(key,node = node.left) 34 | else: 35 | if node.right is None: 36 | node.right = Node(key) 37 | node.right.parent = node 38 | print "right" 39 | return 40 | else: 41 | # return self.add_node(key,node = self.root.right) 42 | return self.add_node(key,node = node.right) 43 | 44 | 45 | def search(self,key,node = None): 46 | 47 | if node is None: 48 | node = self.root 49 | 50 | if self.root.key == key: 51 | print "key is at the root" 52 | return self.root 53 | 54 | else: 55 | if node.key == key : 56 | print "key exists" 57 | return node 58 | 59 | elif key < node.key and node.left is not None: 60 | print "left" 61 | return self.search(key,node = node.left) 62 | 63 | elif key > node.key and node.right is not None: 64 | print "right" 65 | return self.search(key,node = node.right) 66 | 67 | else: 68 | print "key does not exist" 69 | return None 70 | 71 | def delete_node(self,key,node=None): 72 | #search for the node to be deleted in tree 73 | if node is None: 74 | node = self.search(key)#return the node to be deleted 75 | 76 | #root has no parent node 77 | if self.root.key == node.key: #if it is root 78 | parent_node = self.root 79 | else: 80 | parent_node = node.parent 81 | 82 | 83 | '''case 1: The node has no chidren''' 84 | if node.left is None and node.right is None: 85 | if key <= parent_node.key: 86 | parent_node.left = None 87 | else: 88 | parent_node.right = None 89 | return 90 | 91 | '''case 2: The node has children''' 92 | ''' if it has a single left node''' 93 | if node.left is not None and node.right is None : 94 | if node.left.key < parent_node.key : 95 | parent_node.left = node.left 96 | else: 97 | parent_node.right = node.left 98 | 99 | return 100 | 101 | '''if it has a single right node''' 102 | if node.right is not None and node.left is None: 103 | if node.key <= parent_node.key: 104 | parent_node.left = node.right 105 | else: 106 | parent_node.right = node.right 107 | return 108 | 109 | '''if it has two children''' 110 | '''find the node with the minimum value from the right subtree. 111 | copy its value to thhe node which needs to be removed. 112 | right subtree now has a duplicate and so remove it.''' 113 | if node.left is not None and node.right is not None: 114 | min_value = self.find_minimum(node) 115 | node.key = min_value.key 116 | min_value.parent.left = None 117 | return 118 | 119 | 120 | def find_minimum(self,node = None): 121 | 122 | if node is None: 123 | node = self.root 124 | 125 | '''find mimimum value from the right subtree''' 126 | 127 | '''case when there is only a root node''' 128 | if node.right is not None: 129 | node = node.right 130 | else: 131 | return node 132 | 133 | if node.left is not None: 134 | return self.find_minimum(node = node.left) 135 | else: 136 | return node 137 | 138 | def tree_data(self,node=None): 139 | if node is None: 140 | node = self.root 141 | 142 | stack = [] 143 | while stack or node: 144 | if node is not None: 145 | stack.append(node) 146 | node = node.left 147 | else: 148 | node = stack.pop() 149 | yield node.key 150 | node = node.right 151 | 152 | 153 | 154 | 155 | 156 | t=Tree() 157 | t.add_node(10) 158 | t.add_node(13) 159 | t.add_node(14) 160 | t.add_node(8) 161 | t.add_node(9) 162 | t.add_node(7) 163 | t.add_node(11) 164 | 165 | ''' 166 | 10---8---7 167 | | | 168 | | ---9 169 | ---13---11 170 | | 171 | ---14 172 | ''' 173 | -------------------------------------------------------------------------------- /Data Structures/Circular_Queue/C/circularqueue.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define SIZE 5 4 | int items[SIZE]; 5 | int front = -1, rear =-1; 6 | int isFull() 7 | { 8 | if( (front == rear + 1) || (front == 0 && rear == SIZE-1)) return 1; 9 | return 0; 10 | } 11 | int isEmpty() 12 | { 13 | if(front == -1) return 1; 14 | return 0; 15 | } 16 | void enQueue(int element) 17 | { 18 | if(isFull()) printf("\n Queue is full!! \n"); 19 | else 20 | { 21 | if(front == -1) front = 0; 22 | rear = (rear + 1) % SIZE; 23 | items[rear] = element; 24 | printf("\n Inserted -> %d", element); 25 | } 26 | } 27 | int deQueue() 28 | { 29 | int element; 30 | if(isEmpty()) { 31 | printf("\n Queue is empty !! \n"); 32 | return(-1); 33 | } else { 34 | element = items[front]; 35 | if (front == rear){ 36 | front = -1; 37 | rear = -1; 38 | } /* Q has only one element, so we reset the queue after dequeing it. ? */ 39 | else { 40 | front = (front + 1) % SIZE; 41 | 42 | } 43 | printf("\n Deleted element -> %d \n", element); 44 | return(element); 45 | } 46 | } 47 | void display() 48 | { 49 | int i; 50 | if(isEmpty()) printf(" \n Empty Queue\n"); 51 | else 52 | { 53 | printf("\n Front -> %d ",front); 54 | printf("\n Items -> "); 55 | for( i = front; i!=rear; i=(i+1)%SIZE) { 56 | printf("%d ",items[i]); 57 | } 58 | printf("%d ",items[i]); 59 | printf("\n Rear -> %d \n",rear); 60 | } 61 | } 62 | 63 | int main() 64 | { 65 | // Fails because front = -1 66 | deQueue(); 67 | 68 | enQueue(1); 69 | enQueue(2); 70 | enQueue(3); 71 | enQueue(4); 72 | enQueue(5); 73 | 74 | // Fails to enqueue because front == 0 && rear == SIZE - 1 75 | enQueue(6); 76 | 77 | display(); 78 | deQueue(); 79 | 80 | display(); 81 | 82 | enQueue(7); 83 | display(); 84 | 85 | // Fails to enqueue because front == rear + 1 86 | enQueue(8); 87 | 88 | return 0; 89 | } 90 | -------------------------------------------------------------------------------- /Data Structures/Fenwick Tree/cpp/fenwick_tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Fenwick Tree implementation in C++ 3 | - calculates sum of elements of array with range [start,end] in O(log n) 4 | - updates an element of the array in O(log n) 5 | - can be constructed in O(n log n) 6 | */ 7 | 8 | #include 9 | using namespace std; 10 | 11 | struct FenwickTree { 12 | int size; 13 | vector fenwickArr; // Fenwick Tree array is 1-based indexed 14 | 15 | FenwickTree(int size) { 16 | this->size = size; 17 | fenwickArr.assign(size+1, 0); 18 | } 19 | 20 | FenwickTree(vector arr) { 21 | FenwickTree(arr.size()+1); 22 | for (int i = 0; i < arr.size()+1; i++) { 23 | add(i, arr[i]); 24 | } 25 | } 26 | 27 | // calculate sum of elements of array A with range [0, end] 28 | int sum(int end) { 29 | end += 1; // Fenwick Tree array is 1-based indexed 30 | int result = 0; 31 | for (; end > 0; end-=end&(-end)) { 32 | result += fenwickArr[end]; 33 | } 34 | return result; 35 | } 36 | 37 | // calculate sum of elements of array A with range [start, end] 38 | int sum(int start, int end) { 39 | return sum(end) - sum(start-1); 40 | } 41 | 42 | // add val to arr[idx] 43 | void add(int idx, int val) { 44 | idx += 1; // Fenwick Tree array is 1-based indexed 45 | for (; idx <= size; idx += idx&(-idx)) { 46 | fenwickArr[idx] += val; 47 | } 48 | } 49 | }; 50 | 51 | int main() { 52 | // create Fenwick Tree with array A of size 10 53 | // A = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 54 | FenwickTree tree = FenwickTree(10); 55 | 56 | // add 2 to A[1] 57 | // A = [0, 2, 0, 0, 0, 0, 0, 0, 0, 0] 58 | tree.add(1, 2); 59 | 60 | // print sum of elements of array A[0, 5] 61 | printf("%d\n", tree.sum(5)); // 2 62 | 63 | // add 5 to A[9] 64 | // A = [0, 2, 0, 0, 0, 0, 0, 0, 0, 5] 65 | tree.add(9, 5); 66 | 67 | // print sum of elements of array A[0, 9] 68 | printf("%d\n", tree.sum(9)); // 7 69 | // print sum of elements of array A[7, 9] 70 | printf("%d\n", tree.sum(7, 9)); // 5 71 | 72 | // add 1 to A[7] 73 | // A = [0, 2, 0, 0, 0, 0, 0, 1, 0, 5] 74 | tree.add(7, 1); 75 | // add 2 to A[8] 76 | // A = [0, 2, 0, 0, 0, 0, 0, 1, 2, 5] 77 | tree.add(8, 2); 78 | // add 5 to A[9] 79 | // A = [0, 2, 0, 0, 0, 0, 0, 1, 2, 8] 80 | tree.add(9, 3); 81 | 82 | // print sum of elements of array A[0, 9] 83 | printf("%d\n", tree.sum(9)); // 13 84 | // print sum of elements of array A[0, 9] 85 | printf("%d\n", tree.sum(0, 9)); // 13 86 | // print sum of elements of array A[7, 9] 87 | printf("%d\n", tree.sum(7, 9)); // 11 88 | // print sum of elements of array A[8, 9] 89 | printf("%d\n", tree.sum(8, 9)); // 10 90 | 91 | return 0; 92 | } -------------------------------------------------------------------------------- /Data Structures/Graphs/cpp/articulationPoint.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 15 3 | 15 4 | 0 1 5 | 1 2 6 | 2 9 7 | 0 7 8 | 7 8 9 | 8 9 10 | 3 9 11 | 9 4 12 | 9 10 13 | 10 11 14 | 5 13 15 | 6 13 16 | 14 13 17 | 11 12 18 | 12 13 19 | */ 20 | /* 21 | 6 22 | 7 23 | 5 0 24 | 0 1 25 | 1 2 26 | 1 3 27 | 2 3 28 | 2 4 29 | 3 4 30 | */ 31 | /* 32 | 7 33 | 8 34 | 5 0 35 | 0 1 36 | 1 2 37 | 1 3 38 | 2 3 39 | 2 4 40 | 3 4 41 | 5 6 42 | */ 43 | #include 44 | using namespace std; 45 | // error shows 2 is ap 46 | class ArticulationPair 47 | { 48 | public: 49 | 50 | int vert; 51 | int disc; 52 | int low; 53 | bool isAP; 54 | bool processed; 55 | int parent=-1; 56 | }; 57 | //static int graph[n][n]; 58 | //static ArticulationPair result[n]; 59 | 60 | void DFT(int time,int currv,int **graph,ArticulationPair *result[],int n) 61 | { 62 | result[currv]->processed=true; 63 | result[currv]->disc=time; 64 | result[currv]->low=time; 65 | 66 | int rootChildCounter=0; 67 | 68 | for(int i=0;iprocessed==false) 76 | { 77 | rootChildCounter++; 78 | result[i]->parent=currv; 79 | DFT(time+1,i,graph,result,n); 80 | result[currv]->low=min(result[currv]->low,result[i]->low); 81 | 82 | if(result[currv]->parent!=-1) 83 | { 84 | if(result[currv]->disc<=result[i]->low) 85 | { 86 | result[currv]->isAP=new bool; 87 | result[currv]->isAP=true; 88 | } 89 | } 90 | else 91 | { 92 | if(rootChildCounter > 1) 93 | { 94 | result[currv]->isAP=new bool; 95 | result[currv]->isAP=true; 96 | } 97 | } 98 | 99 | } 100 | else if(result[currv]->parent!=i) 101 | { 102 | result[currv]->low=min(result[currv]->low,result[i]->disc); 103 | } 104 | 105 | } 106 | 107 | } 108 | 109 | int main() 110 | { 111 | int n,m; 112 | cin>>n; 113 | cin>>m; 114 | 115 | int **graph=new int*[n]; 116 | for(int i=0;i>x; 125 | cin>>y; 126 | graph[x][y]=1; 127 | graph[y][x]=1; 128 | } 129 | 130 | for(int i=0;ivert=i; 134 | } 135 | 136 | for(int i=0;iprocessed==true){ 139 | continue; 140 | } 141 | DFT(0,i,graph,result,n); 142 | } 143 | 144 | vector ap; 145 | for(int i=0;ivert<<" --> "<isAP<isAP==true) 149 | { 150 | ap.push_back(result[i]->vert); 151 | } 152 | } 153 | 154 | for(int i=0;iisAP; 158 | 159 | 160 | 161 | return 0; 162 | } 163 | -------------------------------------------------------------------------------- /Data Structures/Graphs/cpp/bridges.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class bridge 5 | { 6 | public: 7 | 8 | int a; 9 | int b; 10 | }; 11 | class ArticulationPair 12 | { 13 | public: 14 | 15 | int vert; 16 | int disc; 17 | int low; 18 | bool isAP; 19 | bool processed; 20 | int parent=-1; 21 | }; 22 | //static int graph[n][n]; 23 | //static ArticulationPair result[n]; 24 | 25 | void DFT(int time,int currv,int **graph,ArticulationPair *result[],int n,vector &bv) 26 | { 27 | result[currv]->processed=true; 28 | result[currv]->disc=result[currv]->low=time; 29 | 30 | int rootChildCounter=0; 31 | 32 | for(int i=0;iprocessed==false) 40 | { 41 | // rootChildCounter++; 42 | result[i]->parent=currv; 43 | DFT(time+1,i,graph,result,n,bv); 44 | result[currv]->low=min(result[currv]->low,result[i]->low); 45 | 46 | 47 | if(result[currv]->disclow) 48 | { 49 | //result[currv]->isAP=true; 50 | bridge br; 51 | br.a=currv; 52 | br.b=i; 53 | bv.push_back(br); 54 | 55 | } 56 | 57 | 58 | 59 | } 60 | else if(result[currv]->parent!=i) 61 | { 62 | result[currv]->low=min(result[currv]->low,result[i]->disc); 63 | } 64 | 65 | } 66 | 67 | } 68 | 69 | int main() 70 | { 71 | int n,m; 72 | cin>>n; 73 | cin>>m; 74 | 75 | int **graph=new int*[n]; 76 | for(int i=0;i bv; 82 | 83 | for(int i=0;i>x; 87 | cin>>y; 88 | graph[x][y]=1; 89 | graph[y][x]=1; 90 | } 91 | 92 | for(int i=0;ivert=i; 96 | } 97 | 98 | for(int i=0;iprocessed==true){ 101 | continue; 102 | } 103 | DFT(0,i,graph,result,n,bv); 104 | } 105 | 106 | vector ap; 107 | for(int i=0;ivert<<" --> "<isAP<isAP==true) 111 | { 112 | ap.push_back(result[i]->vert); 113 | } 114 | } 115 | 116 | // for(int i=0;iisAP; 120 | 121 | vector::iterator vi; 122 | for(vi=bv.begin();vi!=bv.end();vi++) 123 | { 124 | cout<<(*vi).a<<"--"<<(*vi).b< 2 | using namespace std; 3 | static int flow=0; 4 | static int minCapacity=INT_MAX; 5 | /* 6 | static map> dag; //directed acyclic graph 7 | static int flow=0; 8 | static map processed; 9 | static int minCapacity=INT_MAX; 10 | */ 11 | int hasPath(string v1name,string v2name,int mCap,map > &dag,map &processed) 12 | { 13 | processed[v1name]=true; 14 | 15 | if(v1name==v2name) 16 | { 17 | flow+=mCap; 18 | return mCap; 19 | } 20 | 21 | map nbrs=dag[v1name]; 22 | map::iterator mi; 23 | map::iterator mi2; 24 | for(mi=nbrs.begin();mi!=nbrs.end();mi++){ 25 | // cout<first<second; 26 | } 27 | 28 | for(mi=nbrs.begin();mi!=nbrs.end();mi++) 29 | { 30 | // cout<<"test1"<first=processed.find(mi->first); 33 | /* if(processed.find(mi->first)!=processed.end()){ 34 | continue; 35 | }*/ 36 | if(processed.find(mi->first)==processed.end() && dag[v1name][mi->first]>0) 37 | { 38 | 39 | 40 | int cap=dag[v1name][mi->first]; 41 | int revcap=dag[mi->first][v1name]; 42 | //cout<<"test2"<first,v2name,min(cap,mCap),dag,processed); 44 | 45 | if(localMCap!=-1) 46 | { 47 | // cout<<"test3"<first]=cap-localMCap; 49 | dag[mi->first][v1name]=revcap+localMCap; 50 | return localMCap; 51 | } 52 | 53 | 54 | } 55 | // mi++; 56 | } 57 | 58 | return -1; 59 | } 60 | 61 | int main() 62 | { 63 | map > dag; //directed acyclic graph 64 | // static int flow=0; 65 | // static map processed; 66 | 67 | 68 | //vces 69 | /*dag["S"]=new map<0>; 70 | dag["A"]=new map; 71 | dag["B"]=new map; 72 | dag["C"]=new map; 73 | dag["D"]=new map; 74 | dag["T"]=new map;*/ 75 | 76 | //edges 77 | 78 | dag["S"]["A"]=10; 79 | dag["A"]["S"]=0; 80 | 81 | dag["S"]["C"]=8; 82 | dag["C"]["S"]=0; 83 | 84 | dag["A"]["C"]=2; 85 | dag["C"]["A"]=0; 86 | 87 | dag["C"]["D"]=10; 88 | dag["D"]["C"]=0; 89 | 90 | dag["A"]["B"]=5; 91 | dag["B"]["A"]=0; 92 | 93 | dag["D"]["B"]=8; 94 | dag["B"]["D"]=0; 95 | 96 | dag["B"]["T"]=7; 97 | dag["T"]["B"]=0; 98 | 99 | dag["D"]["T"]=10; 100 | dag["T"]["D"]=0; 101 | 102 | 103 | //ford fulkerson 104 | while(true) 105 | { 106 | //processed=new map(); 107 | map processed; 108 | int localMCap=hasPath("S","T",INT_MAX,dag,processed); 109 | if(localMCap==-1) 110 | { 111 | break; 112 | } 113 | } 114 | 115 | cout< 2 | #include 3 | 4 | using namespace std; 5 | 6 | template 7 | class Node { 8 | public: 9 | Node* next; 10 | string key; 11 | T value; 12 | 13 | Node(string key, T value) { 14 | this->key = key; 15 | this->value = value; 16 | this->next = NULL; 17 | } 18 | }; 19 | 20 | template 21 | class LinkedList { 22 | Node* head; 23 | public: 24 | LinkedList() { 25 | head = NULL; 26 | } 27 | 28 | void appendNode(string key, T value) { 29 | //declare the new node 30 | Node* newNode = new Node(key, value); 31 | 32 | //inserting the first node in the list 33 | if (head == NULL) { 34 | head = new Node(key, value); 35 | return; 36 | } 37 | 38 | //appending new Node after the last node in the list 39 | Node* ptr = head; 40 | while (ptr->next != NULL) { 41 | ptr = ptr->next; 42 | } 43 | ptr->next = new Node(key, value); 44 | } 45 | 46 | void print() { 47 | Node* ptr = head; 48 | while (ptr != NULL) { 49 | cout << " ==>> (" << ptr->key << ", " << ptr->value << ")"; 50 | ptr = ptr->next; 51 | } 52 | } 53 | 54 | T getValueAtKey(string key) { 55 | Node* ptr = head; 56 | while (ptr != NULL) { 57 | //the actual node with the entered key 58 | if (key.compare(ptr->key) == 0) { 59 | return ptr->value; 60 | } 61 | ptr = ptr->next; 62 | } 63 | } 64 | 65 | bool containsKey(string key) { 66 | Node* ptr = head; 67 | while (ptr != NULL) { 68 | //the actual node with the entered key 69 | if (key.compare(ptr->key) == 0) { 70 | return true; 71 | } 72 | ptr = ptr->next; 73 | } 74 | return false; 75 | } 76 | }; 77 | 78 | 79 | template 80 | class HashTable { 81 | int tableSize; 82 | LinkedList* itemsArray; 83 | 84 | //a simple hashing function that returns an index of the key's value in the table 85 | int hashFunction(string key) { 86 | long long hashSum = 0; 87 | for (long long i = 0; i < key.size(); i++) { 88 | //note : 100151 just a simple first prime number that is > 10^5 89 | hashSum += ((i + 1) * key[i]) % 100151; 90 | hashSum = hashSum % 100151; 91 | } 92 | return hashSum % tableSize; 93 | } 94 | bool containsKey(string key) { 95 | int index = hashFunction(key); 96 | return itemsArray[index].containsKey(key); 97 | } 98 | public: 99 | HashTable(int tableSize) { 100 | this->tableSize = tableSize; 101 | itemsArray = new LinkedList[tableSize]; 102 | } 103 | 104 | void insert(string key, T value) { 105 | int index = hashFunction(key); 106 | //insert if the key was not found in the table before 107 | if(!containsKey(key)) 108 | itemsArray[index].appendNode(key, value); 109 | } 110 | 111 | //returns NULL if the value was not in the whole table 112 | T getValue(string key) { 113 | int index = hashFunction(key); 114 | 115 | if(itemsArray[index].containsKey(key)) 116 | return itemsArray[index].getValueAtKey(key); 117 | return NULL; 118 | } 119 | 120 | void printTable() { 121 | for (int i = 0; i < tableSize; i++) { 122 | cout << "At index " << i << " : "; 123 | itemsArray[i].print(); 124 | cout << "\n"; 125 | } 126 | } 127 | }; 128 | 129 | 130 | int main() { 131 | int tableSize = 10; 132 | HashTable myAgeTable(tableSize); 133 | 134 | myAgeTable.insert("John",18); 135 | myAgeTable.insert("Thomas", 21); 136 | myAgeTable.insert("Frank", 39); 137 | myAgeTable.insert("Ivan", 27); 138 | myAgeTable.insert("Julia", 29); 139 | myAgeTable.insert("Scarllet", 40); 140 | myAgeTable.insert("Sara", 19); 141 | 142 | //wouldn't be inseted since the key was there before 143 | myAgeTable.insert("Scarllet", 30); 144 | 145 | myAgeTable.printTable(); 146 | 147 | return 0; 148 | } 149 | -------------------------------------------------------------------------------- /Data Structures/Linked List/C/linked_list.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct node { 5 | int data; 6 | struct node* next; 7 | }; 8 | 9 | int node_size = sizeof(struct node); 10 | 11 | // This function prints contents of linked list starting from 12 | // the given node 13 | void printList(struct node* n){ 14 | while (n != NULL) { 15 | printf(" %d ", n->data); 16 | n = n->next; 17 | } 18 | } 19 | 20 | int main(){ 21 | struct node* head = NULL; 22 | struct node* second = NULL; 23 | struct node* third = NULL; 24 | 25 | // allocate 3 nodes 26 | head = (struct node*) malloc(node_size); 27 | second = (struct node*) malloc(node_size); 28 | third = (struct node*) malloc(node_size); 29 | 30 | head->data = 1; // assign data in first node 31 | head->next = second; // Link first node with second 32 | 33 | second->data = 2; // assign data to second node 34 | second->next = third; // Link second node with third 35 | 36 | third->data = 3; // assign data to third node 37 | third->next = NULL; // Null to End Current List 38 | 39 | printList(head); 40 | 41 | return 0; 42 | } -------------------------------------------------------------------------------- /Data Structures/Linked List/C/linked_list_basics.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | int item; 5 | void insert_beginning(void); 6 | void insert_end(void); 7 | void insert_location(); 8 | void insert_after_value(); 9 | void delete_by_location(); 10 | void delete_by_item(); 11 | void display(void); 12 | struct node 13 | { 14 | int data; 15 | struct node* next; 16 | }; 17 | struct node *start; 18 | struct node*tail=NULL; 19 | void main() 20 | { 21 | int choice; 22 | while(1) 23 | { 24 | printf ("\n LINKED LIST: \n 1. INSERT AT THE BEGINNING\n 2. INSERT AT THE END\n 3. INSERT AT A GIVEN LOCATION\n 4. INSERT AFTER A GIVEN VALUE\n 5. DELETE BY LOCATION\n 6. DELETE BY VALUE\n 7. DISPLAY\n 8. EXIT\n\n"); 25 | printf ("\nENTER YOUR CHOICE:\n"); 26 | scanf("%d",&choice); 27 | switch(choice) 28 | { 29 | case 1:insert_beginning(); 30 | break; 31 | case 2:insert_end(); 32 | break; 33 | case 3:insert_location(); 34 | break; 35 | case 4:insert_after_value(); 36 | break; 37 | case 5:delete_by_location(); 38 | break; 39 | case 6:delete_by_item(); 40 | break; 41 | case 7:display(); 42 | break; 43 | case 8:exit(0); 44 | break; 45 | default: printf("\n YOU HAVE ENTERED A WRONG CHOICE\n"); 46 | } 47 | } 48 | } 49 | void insert_beginning() 50 | { 51 | struct node *p= start, *temp; 52 | temp=(struct node*)malloc(sizeof(struct node)); 53 | printf("\n ENTER ITEM:\n"); 54 | scanf("%d",&item); 55 | temp->data= item; 56 | temp->next= start; 57 | start=temp; 58 | } 59 | void insert_end() 60 | { 61 | struct node *p= start, *temp; 62 | temp=(struct node*)malloc(sizeof(struct node)); 63 | printf("\n ENTER ITEM:\n"); 64 | scanf("%d",&item); 65 | temp->data=item; 66 | while(p->next!=NULL) 67 | { 68 | p=p->next; 69 | } 70 | p->next=temp; 71 | temp->next=NULL; 72 | } 73 | void insert_location() 74 | { 75 | struct node *p=start, *temp; 76 | int loc,i; 77 | printf("\nENTER LOCATION\n "); 78 | scanf("%d",&loc); 79 | temp=(struct node*)malloc(sizeof(struct node)); 80 | printf("\n ENTER ITEM:\n"); 81 | scanf("%d",&item); 82 | temp->data= item; 83 | if (loc==1) 84 | { 85 | temp->next=p; 86 | start=temp; 87 | } 88 | else 89 | { 90 | 91 | for(i=1;inext; 94 | } 95 | struct node *location=p->next; 96 | p->next=temp; 97 | temp->next=location; 98 | } 99 | 100 | } 101 | void insert_after_value() 102 | { 103 | int value; 104 | struct node *p=start, *temp; 105 | printf("\nENTER DATA OF A NODE AFTER WHICH YOU WISH TO SEE ITEM:\n"); 106 | scanf("%d",&value); 107 | while(p!=NULL) 108 | { 109 | if(p->data==value) 110 | { 111 | temp=(struct node*)malloc(sizeof(struct node)); 112 | printf("\n ENTER ITEM:\n"); 113 | scanf("%d",&item); 114 | temp->data= item; 115 | temp->next=p->next; 116 | p->next=temp; 117 | break; 118 | } 119 | p=p->next; 120 | } 121 | } 122 | void delete_by_location() 123 | { 124 | struct node *p=start,*old=start,*temp; 125 | int loc,i; 126 | printf("\nENTER LOCATION:\n"); 127 | scanf("%d",&loc); 128 | for(i=1;inext; 131 | } 132 | 133 | 134 | if (p==start) 135 | { 136 | start=start->next; 137 | free(p); 138 | } 139 | else if (p->next==NULL) 140 | { 141 | for(i=1;inext; 144 | } 145 | old->next=NULL; 146 | free (p); 147 | } 148 | 149 | else 150 | { 151 | for(i=1;inext; 154 | } 155 | old->next=p->next; 156 | free (p); 157 | } 158 | } 159 | void delete_by_item() 160 | { 161 | int value; 162 | struct node *p=start,*old=start,*temp; 163 | printf("\nENTER DATA OF A NODE WHICH YOU WISH TO DELETE:\n"); 164 | scanf("%d",&value); 165 | while(p->data!=value) 166 | { 167 | p=p->next; 168 | } 169 | 170 | if (p==start) 171 | { 172 | start=start->next; 173 | free (p); 174 | } 175 | else if (p->next==NULL) 176 | { 177 | while(old->next->data!=value) 178 | { 179 | old=old->next; 180 | } 181 | old->next=NULL; 182 | free (p); 183 | } 184 | 185 | else 186 | { 187 | while(old->next->data!=value) 188 | { 189 | old=old->next; 190 | } 191 | old->next=p->next; 192 | free (p); 193 | } 194 | } 195 | void display() 196 | { 197 | struct node* p= start; 198 | printf("\n YOUR LINKED LIST LOOKS LIKE :\n\n"); 199 | printf("\n|_START"); 200 | while(p!=NULL) 201 | { 202 | printf(" |_%d_|_|->",p->data); 203 | p=p->next; 204 | } 205 | printf("[NULL]\n"); 206 | } 207 | 208 | -------------------------------------------------------------------------------- /Data Structures/Linked List/Java/DoubleEndedLinkedList.java: -------------------------------------------------------------------------------- 1 | 2 | public class DoubleEndedLinkedList { 3 | 4 | 5 | Neighbor firstLink; 6 | Neighbor lastLink; 7 | 8 | 9 | public void insertInFirstPosition(String houseOwnerName, int houseNumber) { 10 | 11 | Neighbor theNewLink = new Neighbor(houseOwnerName, houseNumber); 12 | 13 | if(isEmpty()) 14 | lastLink = theNewLink; 15 | 16 | else 17 | firstLink.pre = theNewLink; 18 | 19 | theNewLink.next = firstLink; 20 | firstLink = theNewLink; 21 | 22 | 23 | } 24 | 25 | 26 | public void insertInLastPosition(String houseOwnerName, int houseNumber) { 27 | 28 | Neighbor theNewLink = new Neighbor(houseOwnerName, houseNumber); 29 | 30 | 31 | if(isEmpty()) 32 | firstLink = theNewLink; 33 | 34 | else { 35 | lastLink.next = theNewLink; 36 | theNewLink.pre = lastLink; 37 | } 38 | 39 | 40 | lastLink = theNewLink; 41 | 42 | } 43 | 44 | public boolean insertAfterKey(String houseOwnerName, int houseNumber, int key) { 45 | 46 | 47 | Neighbor newLink = new Neighbor(houseOwnerName,houseNumber); 48 | 49 | Neighbor currentNeighbor = firstLink; 50 | 51 | while(currentNeighbor.houseNumber!=key) { 52 | 53 | 54 | currentNeighbor = currentNeighbor.next; 55 | 56 | if(currentNeighbor==null) 57 | return false; 58 | 59 | 60 | } 61 | 62 | if(currentNeighbor == lastLink) { 63 | 64 | newLink.next = null; 65 | lastLink = newLink; 66 | 67 | } 68 | else { 69 | 70 | newLink.next = currentNeighbor.next; 71 | 72 | currentNeighbor.next.pre = newLink; 73 | 74 | 75 | } 76 | 77 | newLink.pre = currentNeighbor; 78 | currentNeighbor.next = newLink; 79 | return true; 80 | 81 | } 82 | 83 | public boolean isEmpty() { 84 | 85 | return (firstLink == null); 86 | 87 | 88 | } 89 | 90 | public void display() { 91 | 92 | Neighbor theLink = firstLink; 93 | 94 | 95 | while(theLink!=null) { 96 | theLink.display(); 97 | 98 | System.out.println("Next Link is "+theLink.next); 99 | 100 | theLink = theLink.next; 101 | System.out.println(); 102 | } 103 | 104 | } 105 | 106 | 107 | public static void main(String[] args) { 108 | 109 | 110 | 111 | DoubleEndedLinkedList linkedlist = new DoubleEndedLinkedList(); 112 | 113 | linkedlist.insertInFirstPosition("Vasu Dixit", 5); 114 | linkedlist.insertInFirstPosition("Kirti", 5); 115 | linkedlist.insertInFirstPosition("Richi Chutiya", 7); 116 | linkedlist.insertInFirstPosition("Nagesh", 2); 117 | 118 | 119 | linkedlist.display(); 120 | 121 | linkedlist.insertAfterKey("Someone", 6, 2); 122 | 123 | linkedlist.display(); 124 | 125 | } 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | } 139 | 140 | 141 | class Neighbor { 142 | 143 | public String homeOwnerName; 144 | public int houseNumber; 145 | 146 | public Neighbor next; 147 | public Neighbor pre; 148 | 149 | 150 | public Neighbor(String homeOwnerName, int houseNumber) { 151 | 152 | this.homeOwnerName = homeOwnerName; 153 | this.houseNumber = houseNumber; 154 | } 155 | 156 | public void display() { 157 | 158 | System.out.println(homeOwnerName+" : "+houseNumber); 159 | 160 | } 161 | 162 | 163 | public String toString() { 164 | 165 | return homeOwnerName; 166 | 167 | } 168 | 169 | 170 | 171 | 172 | } 173 | -------------------------------------------------------------------------------- /Data Structures/Linked List/Java/ReadMe.md: -------------------------------------------------------------------------------- 1 | Java codes for different implementations of linked lists 2 | -------------------------------------------------------------------------------- /Data Structures/Linked List/Javascript/doubly_circular_linked_list.js: -------------------------------------------------------------------------------- 1 | //This is a program for Doubly Circular Linked list in Javascript 2 | // It performs basic operation of adding an element at the last, 3 | // adding an element at a specified index and deleting an element at an index 4 | class doublyCircularLinkedlist 5 | { 6 | constructor() 7 | { 8 | this.size = 0; 9 | this.head = null; 10 | this.element = 11 | class node{ 12 | constructor(d) 13 | { 14 | this.prev = null; 15 | this.next = null; 16 | this.data = d; 17 | } 18 | } 19 | } 20 | 21 | // Inserts an element at the last 22 | 23 | insert(data) 24 | { 25 | this.size++; 26 | let new_node = new this.element(data); 27 | if(this.head === null) 28 | { 29 | 30 | this.head = new_node; 31 | this.head.prev = new_node; 32 | this.head.next = new_node; 33 | } 34 | else 35 | { 36 | 37 | let last_node = this.head; 38 | while(last_node.next !== this.head) 39 | { 40 | last_node = last_node.next; 41 | } 42 | last_node.next = new_node; 43 | new_node.prev = last_node; 44 | new_node.next = this.head; 45 | this.head.prev = new_node; 46 | } 47 | } 48 | 49 | //Inserts element at that index 50 | 51 | insertAt(data,index) 52 | { 53 | if(index>this.size-1 || index<0) throw "invalid index"; 54 | else{ 55 | this.size++; 56 | let curr_node = this.head, i = index; 57 | let new_node = new this.element(data); 58 | if(index===0) 59 | { 60 | new_node.prev = this.head.prev; 61 | this.head.prev.next = new_node; 62 | this.head.prev = new_node 63 | new_node.next = this.head; 64 | this.head = new_node; 65 | } 66 | else 67 | { 68 | while(i--!==0) 69 | { 70 | curr_node = curr_node.next; 71 | } 72 | curr_node.prev.next = new_node; 73 | new_node.prev = curr_node.prev; 74 | new_node.next = curr_node; 75 | curr_node.prev = new_node; 76 | } 77 | }} 78 | 79 | //Deletes an element at the specified index 80 | 81 | deleteAt(index) 82 | { 83 | if(index>this.size-1 || index<0) throw "invalid index"; 84 | else{ 85 | this.size--; 86 | let curr_node = this.head; let i = index; 87 | while(i!==0) 88 | { 89 | curr_node = curr_node.next; 90 | i--; 91 | } 92 | if(index===0) 93 | this.head = curr_node.next; 94 | 95 | curr_node.prev.next = curr_node.next; 96 | curr_node.next.prev = curr_node.prev; 97 | }} 98 | 99 | //Prints elements with arrows to show where they point to, for easy visualization 100 | 101 | print() 102 | { 103 | let curr_node = this.head; 104 | console.log(this.size); 105 | for(let i = 0; i ${curr_node.next.data}`); 108 | curr_node = curr_node.next; 109 | } 110 | } 111 | } 112 | 113 | //Demo operations 114 | 115 | let my_list = new doublyCircularLinkedlist(); 116 | my_list.insert(1); //1 117 | my_list.insert(2); //12 118 | my_list.insert(3); //123 119 | my_list.insertAt(0,0); //0123 120 | my_list.insertAt(4,3); //01243 121 | my_list.insert(6); //012436 122 | my_list.deleteAt(3); //01236 123 | my_list.print(); 124 | 125 | -------------------------------------------------------------------------------- /Data Structures/Linked List/c++/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frextrite/Data-Structures-Algorithms-Hacktoberfest-2K19/a6f1f48a6871b8001965019fa160db57fc9f9bcf/Data Structures/Linked List/c++/a.out -------------------------------------------------------------------------------- /Data Structures/Linked List/cpp/linked_list.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | template 6 | class Node { 7 | public: 8 | Node* next; 9 | T value; 10 | 11 | Node(T value) { 12 | this->value = value; 13 | this->next = NULL; 14 | } 15 | }; 16 | 17 | template 18 | class LinkedList { 19 | Node* head; 20 | public: 21 | LinkedList() { 22 | head = NULL; 23 | } 24 | 25 | void appendNode(T value) { 26 | //declare the new node 27 | Node* newNode = new Node(value); 28 | 29 | //inserting the first node in the list 30 | if (head == NULL) { 31 | head = new Node(value); 32 | return; 33 | } 34 | 35 | //appending new Node after the last node in the list 36 | Node* ptr = head; 37 | while (ptr->next != NULL) { 38 | ptr = ptr->next; 39 | } 40 | ptr->next = new Node(value); 41 | } 42 | 43 | void print() { 44 | cout << "Linked List : \n"; 45 | 46 | Node* ptr = head; 47 | while (ptr != NULL) { 48 | cout << " ==>> " << ptr->value; 49 | ptr = ptr->next; 50 | } 51 | 52 | cout << "\n"; 53 | } 54 | }; 55 | 56 | int main() { 57 | 58 | LinkedList myList; 59 | myList.appendNode(1); 60 | myList.appendNode(3); 61 | myList.appendNode(5); 62 | myList.appendNode(7); 63 | myList.appendNode(9); 64 | myList.appendNode(11); 65 | 66 | myList.print(); 67 | return 0; 68 | } 69 | -------------------------------------------------------------------------------- /Data Structures/Linked List/python/linked_list.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | 3 | def __init__(self,data,nextNode=None): 4 | self.data = data 5 | self.nextNode = nextNode 6 | 7 | def getData(self): 8 | return self.data 9 | 10 | def setData(self,val): 11 | self.data = val 12 | 13 | def getNextNode(self): 14 | return self.nextNode 15 | 16 | def setNextNode(self,val): 17 | self.nextNode = val 18 | 19 | class LinkedList: 20 | 21 | def __init__(self,head = None): 22 | self.head = head 23 | self.size = 0 24 | 25 | def getSize(self): 26 | return self.size 27 | 28 | def addNode(self,data): 29 | newNode = Node(data,self.head) 30 | self.head = newNode 31 | self.size+=1 32 | return True 33 | 34 | def printNode(self): 35 | curr = self.head 36 | while curr: 37 | print(curr.data) 38 | curr = curr.getNextNode() 39 | 40 | myList = LinkedList() 41 | print "Inserting Nodes" 42 | print(myList.addNode(7)) 43 | print(myList.addNode(18)) 44 | print(myList.addNode(27)) 45 | print "Printing Nodes" 46 | myList.printNode() 47 | print "Getting Size of the Linked List" 48 | print(myList.getSize()) -------------------------------------------------------------------------------- /Data Structures/Queue/C/queue.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #define MAX 6 8 | 9 | int intArray[MAX]; 10 | int front = 0; 11 | int rear = -1; 12 | int itemCount = 0; 13 | 14 | int peek() { 15 | return intArray[front]; 16 | } 17 | 18 | bool isEmpty() { 19 | return itemCount == 0; 20 | } 21 | 22 | bool isFull() { 23 | return itemCount == MAX; 24 | } 25 | 26 | int size() { 27 | return itemCount; 28 | } 29 | 30 | void insert(int data) { 31 | 32 | if(!isFull()) { 33 | 34 | if(rear == MAX-1) { 35 | rear = -1; 36 | } 37 | 38 | intArray[++rear] = data; 39 | itemCount++; 40 | } 41 | } 42 | 43 | int removeData() { 44 | int data = intArray[front++]; 45 | 46 | if(front == MAX) { 47 | front = 0; 48 | } 49 | 50 | itemCount--; 51 | return data; 52 | } 53 | 54 | int main() { 55 | 56 | insert(3); 57 | insert(5); 58 | insert(9); 59 | insert(1); 60 | insert(12); 61 | 62 | if(isFull()) { 63 | printf("Queue is full!\n"); 64 | } 65 | 66 | int num = removeData(); 67 | 68 | printf("Element removed: %d\n",num); 69 | 70 | insert(16); 71 | 72 | insert(17); 73 | insert(18); 74 | 75 | printf("Element at front: %d\n",peek()); 76 | 77 | printf("**********************\n"); 78 | printf("index : 5 4 3 2 1 0\n"); 79 | printf("**********************\n"); 80 | printf("Queue: "); 81 | 82 | while(!isEmpty()) { 83 | int n = removeData(); 84 | printf("%d ",n); 85 | } 86 | } -------------------------------------------------------------------------------- /Data Structures/Queue/c++/queue.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | implementation of queue using link list 3 | */ 4 | #include 5 | using namespace std; 6 | class node 7 | { 8 | public: 9 | int data; 10 | node* next; 11 | }; 12 | void enqueue(node** z,int x) // insert function 13 | { 14 | 15 | if(*z==NULL) 16 | { 17 | node* temp = new node(); 18 | temp->data=x; 19 | temp->next=NULL; 20 | *z=temp; 21 | return; 22 | } 23 | node* temp = *z; 24 | while(temp->next!=NULL) 25 | { 26 | temp=temp->next; 27 | } 28 | node* temp2=new node(); 29 | temp2->data=x; 30 | temp2->next=NULL; 31 | temp->next=temp2; 32 | } 33 | void dequeue(node** z) //deletion function 34 | { 35 | if((*z)==NULL) 36 | { 37 | cout<<"queue is empty"<next; 42 | cout<<"dequeued value is "<data<data<<" "; 56 | temp=temp->next; 57 | } 58 | cout< 3 | #include 4 | #define max 50 5 | void push(); 6 | void pop(); 7 | void display(); 8 | int menu(); 9 | int stack[max], top=0; 10 | 11 | void main() 12 | { 13 | int ch; 14 | 15 | do{ 16 | ch=menu(); 17 | switch(ch) 18 | { 19 | case 1: push(); 20 | break; 21 | case 2: pop(); 22 | break; 23 | case 3: display(); 24 | break; 25 | case 4: exit(0); 26 | default: printf("\nEnter a valid choice!!"); 27 | } 28 | }while(1); 29 | } 30 | 31 | int menu() 32 | { 33 | int ch; 34 | printf("\nStack"); 35 | printf("\n1.Push\n2.Pop\n3.Display\n4.Exit"); 36 | printf("\nEnter your Choice:"); 37 | scanf("%d",&ch); 38 | return ch; 39 | } 40 | 41 | void push() 42 | { 43 | if(top==max) 44 | printf("\nOverflow"); 45 | else 46 | { 47 | int element; 48 | printf("\nEnter Element:"); 49 | scanf("%d",&element); 50 | printf("\nElement(%d) has been pushed at %d", element, top); 51 | stack[top++]=element; 52 | } 53 | } 54 | 55 | void pop() 56 | { 57 | if(top==-1) 58 | printf("\nUnderflow"); 59 | else 60 | { 61 | top--; 62 | printf("\nELement has been popped out!"); 63 | } 64 | } 65 | 66 | void display() 67 | { 68 | if(top==0) 69 | printf("\nStack is Empty!!"); 70 | else 71 | { 72 | int i; 73 | for(i=0;i st;` 10 | 11 | Pushing into the stack : `st.push(data);` 12 | 13 | Getting the value at the top of the stack : `dataType x = st.top();` 14 | 15 | Popping from the stack : `st.pop();` 16 | 17 | (Note : replace "dataType" with the type of the data you are using, example: `Stack st;`) 18 | 19 | All the operation are performed in O(1) time complexity. 20 | 21 | ## In order to use the file as a header file 22 | 23 | 1. Rename the file with ".h" extension (header file extension) 24 | 25 | 2. Remove the `main()` function from the file 26 | -------------------------------------------------------------------------------- /Data Structures/Stack/cpp/stack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | template 6 | class Stack 7 | { 8 | //Nodal class 9 | class Node 10 | { 11 | public: 12 | T data; 13 | Node *next; 14 | Node() 15 | { 16 | next = NULL; 17 | } 18 | Node(T val) 19 | { 20 | data = val; 21 | } 22 | }; 23 | 24 | Node *head; 25 | 26 | public: 27 | Stack() 28 | { 29 | head = NULL; 30 | } 31 | 32 | //function to push a value into the stack 33 | void push(T val) 34 | { 35 | Node *n = new Node(val); 36 | 37 | //check for memory assignment error 38 | if (n == NULL) 39 | { 40 | cout << "Memory error\n"<< endl; 41 | exit(0); 42 | } 43 | else if(head == NULL) 44 | { 45 | head = n; 46 | } 47 | else 48 | { 49 | n->next = head; 50 | head = n; 51 | } 52 | 53 | } 54 | 55 | //function to return the value at the top of the stack 56 | T top() 57 | { 58 | return head->data; 59 | } 60 | 61 | //function to pop an element from the top of the stack 62 | void pop() 63 | { 64 | //check for underflow 65 | if(head==NULL) 66 | { 67 | cout<<"Stack underflow\n"<next; 72 | delete(n); 73 | } 74 | }; 75 | 76 | int main() 77 | { 78 | //declaration 79 | Stack st; 80 | 81 | //push into the stack 82 | st.push(10); 83 | st.push(5); 84 | 85 | //pop from the stack 86 | st.pop(); 87 | 88 | //printing the top of the stack 89 | cout< s = new Stack(); 12 | s.push(1); 13 | s.push(2); 14 | System.out.println(s.peek()); 15 | System.out.println(s.pop()); 16 | System.out.println(s.pop()); 17 | } 18 | } 19 | ``` -------------------------------------------------------------------------------- /Data Structures/Stack/java/Stack.java: -------------------------------------------------------------------------------- 1 | // Stack data type implemented in Java 2 | // Written by: @SLaGrave 3 | 4 | public class Stack { 5 | static final int MAX_ITEMS = 15000; // Max number of items in the stack 6 | private int top_of_stack; // Index of the top of the stack 7 | private T arr[]; // Array that represents the stack 8 | 9 | Stack() { 10 | top_of_stack = -1; 11 | arr = (T[]) new Object[MAX_ITEMS]; 12 | } 13 | 14 | boolean isEmpty() { 15 | return top_of_stack < 0; 16 | } 17 | 18 | void push(T input) { 19 | if (top_of_stack < MAX_ITEMS) { 20 | top_of_stack++; 21 | arr[top_of_stack] = input; 22 | } 23 | else { 24 | throw new IndexOutOfBoundsException("The max size of the stack has been reached"); 25 | } 26 | } 27 | 28 | T pop() { 29 | if (top_of_stack >= 0) { 30 | T x = arr[top_of_stack]; 31 | top_of_stack--; 32 | return x; 33 | } 34 | else { 35 | throw new IndexOutOfBoundsException("Tried to access element of empty stack"); 36 | } 37 | } 38 | 39 | T peek() { 40 | if (top_of_stack >= 0) { 41 | T x = arr[top_of_stack]; 42 | return x; 43 | } 44 | else { 45 | throw new IndexOutOfBoundsException("Tried to peek element of empty stack"); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Data Structures/Trie/C++/Trie.cpp: -------------------------------------------------------------------------------- 1 | // Assumption -> All the strings are unique 2 | 3 | /* 4 | Time Complexity-> 5 | Insert = O(length) 6 | Search = O(length) 7 | Remove = O(length) 8 | isEmpty = O(Alphabet) 9 | */ 10 | 11 | /* Structure of Node */ 12 | struct Node 13 | { 14 | bool leaf; 15 | Node *child[26]; // Alphabet => lowercase english alphabets 16 | }; 17 | 18 | /* returns a new node */ 19 | Node *getNode() 20 | { 21 | Node *temp = (Node *)malloc(sizeof(Node)); 22 | 23 | // Initializing Node 24 | temp->leaf=false; 25 | for(int a=0;a<26;a++) 26 | { 27 | temp->child[a]=NULL; 28 | } 29 | return temp; 30 | } 31 | 32 | /* Inserts a string */ 33 | void insert(Node *root,string s) 34 | { 35 | Node *head=root; 36 | for(auto y:s) 37 | { 38 | int b=y-'a'; 39 | if(head->child[b]==NULL) 40 | head->child[b]=getNode(); // We create a node if it does not exist 41 | head=head->child[b]; 42 | } 43 | head->leaf=true; 44 | } 45 | 46 | /* Searches for a string */ 47 | bool search(Node *root,string s) 48 | { 49 | Node *head=root; 50 | for(auto y:s) 51 | { 52 | int b=y-'a'; 53 | if(head->child[b]==NULL) 54 | return false; // If a node does not exist , we return false 55 | head=head->child[b]; 56 | } 57 | return head->leaf; 58 | } 59 | 60 | /* Checks if a node is empty */ 61 | bool isEmpty(Node *root) 62 | { 63 | for(int a=0;a<26;a++) 64 | { 65 | if(root->child[a]) 66 | return false; 67 | } 68 | return true; 69 | } 70 | 71 | /* Deletes a string */ 72 | Node *remove(Node *root,string s,int level=0) 73 | { 74 | int n=s.length(); 75 | if(level==n) 76 | { 77 | if(root->leaf) 78 | { 79 | root->leaf=false; 80 | } 81 | if(isEmpty(root)) 82 | { 83 | delete(root); 84 | root=NULL; 85 | } 86 | return root; 87 | } 88 | 89 | int curr=s[level]-'a'; 90 | root->child[curr]=remove(root->child[curr],s,level+1); 91 | if(isEmpty(root)) 92 | { 93 | delete(root); 94 | root=NULL; 95 | } 96 | return root; 97 | } 98 | -------------------------------------------------------------------------------- /Data Structures/UnionFind/java/README.md: -------------------------------------------------------------------------------- 1 | ## Union Find 2 | 3 | An implementation of the union find (_aka disjoint set_) data structure using the weighted union and path compression heuristics to improve performance. 4 | 5 | #### Complexity: 6 | 7 | - **Space:** _O(N)_ where _N_ is the number of items 8 | - **Time:** _O(N + M log* N)_ where _N_ is the number of items and _M_ is the number of union/find operations 9 | 10 | For extra information, check out the [wikipedia article](https://en.wikipedia.org/wiki/Disjoint-set_data_structure). -------------------------------------------------------------------------------- /Data Structures/UnionFind/java/UnionFind.java: -------------------------------------------------------------------------------- 1 | // a class providing an implementation of the union find operations 2 | // using the weighted union and (full) path compression heuristics 3 | // the items are assumed as integers in the range [0, number of items) 4 | 5 | public class UnionFind { 6 | private int components; // number of disjoint components 7 | private int parent[], // parent of a particular component 8 | size[]; // size of component rooted at i 9 | // however, i should be root of a component 10 | 11 | // initialize a union find object with specified number of items 12 | public UnionFind(int numItems) { 13 | components = numItems; 14 | parent = new int[numItems]; 15 | size = new int[numItems]; 16 | 17 | // initially all components are singleton sets 18 | for (int i = 0; i < numItems; i++) { 19 | parent[i] = i; 20 | size[i] = 1; 21 | } 22 | } 23 | 24 | // get the number of disjoint components 25 | public int components() { 26 | return components; 27 | } 28 | 29 | // are two items in the same component? 30 | public boolean connected(int u, int v) { 31 | return find(u) == find(v); 32 | } 33 | 34 | // get the root of the specified item 35 | // this implements full path-compression 36 | public int find(int u) { 37 | // first get the root for the specified item by traversing to root 38 | int root = u; 39 | while (root != parent[root]) 40 | root = parent[root]; 41 | 42 | // then perform path-compression by traversing to root again 43 | // but setting the parent of the items on the path to the root 44 | while (u != root) { 45 | int prevParent = parent[u]; 46 | parent[u] = root; 47 | u = prevParent; 48 | } 49 | 50 | return root; 51 | } 52 | 53 | // merge two components containing u and v respectively 54 | // into a single component 55 | public void union(int u, int v) { 56 | int rootU = find(u), rootV = find(v); 57 | 58 | if (rootU == rootV) return; 59 | 60 | // add the smaller root to the larger root 61 | // i.e. add the smaller component to the larger one 62 | if (size[rootU] < size[rootV]) { 63 | parent[rootU] = rootV; 64 | size[rootV] += size[rootU]; 65 | } 66 | else { 67 | parent[rootV] = rootU; 68 | size[rootU] += size[rootV]; 69 | } 70 | components--; 71 | } 72 | 73 | // unit testing 74 | public static void main(String[] args) { 75 | UnionFind uf = new UnionFind(10); 76 | uf.union(0, 1); 77 | uf.union(1, 2); 78 | uf.union(0, 1); 79 | uf.union(1, 9); 80 | uf.union(3, 4); 81 | uf.union(3, 5); 82 | uf.union(7, 8); 83 | 84 | // current state, root elements in [...] 85 | // {[0], 1, 2, 9}, {[3], 4, 5}, {[6]}, {[7], 8} 86 | assert uf.components() == 4; 87 | 88 | assert uf.connected(0, 1) && uf.connected(0, 9) && !uf.connected(0, 3) 89 | && uf.connected(3, 5) && !uf.connected(3, 6) && uf.connected(7, 8); 90 | 91 | assert uf.find(0) == 0; 92 | assert uf.find(3) == 3; 93 | assert uf.find(6) == 6; 94 | assert uf.find(7) == 7; 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /Data Structures/heap/cpp/binary_heap.cpp: -------------------------------------------------------------------------------- 1 | // A C++ program to demonstrate common Binary Heap Operations 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | // Prototype of a utility function to swap two integers 7 | void swap(int *x, int *y); 8 | 9 | // A class for Min Heap 10 | class MinHeap 11 | { 12 | int *harr; // pointer to array of elements in heap 13 | int capacity; // maximum possible size of min heap 14 | int heap_size; // Current number of elements in min heap 15 | public: 16 | // Constructor 17 | MinHeap(int capacity); 18 | 19 | // to heapify a subtree with the root at given index 20 | void MinHeapify(int ); 21 | 22 | int parent(int i) { return (i-1)/2; } 23 | 24 | // to get index of left child of node at index i 25 | int left(int i) { return (2*i + 1); } 26 | 27 | // to get index of right child of node at index i 28 | int right(int i) { return (2*i + 2); } 29 | 30 | // to extract the root which is the minimum element 31 | int extractMin(); 32 | 33 | // Decreases key value of key at index i to new_val 34 | void decreaseKey(int i, int new_val); 35 | 36 | // Returns the minimum key (key at root) from min heap 37 | int getMin() { return harr[0]; } 38 | 39 | // Deletes a key stored at index i 40 | void deleteKey(int i); 41 | 42 | // Inserts a new key 'k' 43 | void insertKey(int k); 44 | }; 45 | 46 | // Constructor: Builds a heap from a given array a[] of given size 47 | MinHeap::MinHeap(int cap) 48 | { 49 | heap_size = 0; 50 | capacity = cap; 51 | harr = new int[cap]; 52 | } 53 | 54 | // Inserts a new key 'k' 55 | void MinHeap::insertKey(int k) 56 | { 57 | if (heap_size == capacity) 58 | { 59 | cout << "\nOverflow: Could not insertKey\n"; 60 | return; 61 | } 62 | 63 | // First insert the new key at the end 64 | heap_size++; 65 | int i = heap_size - 1; 66 | harr[i] = k; 67 | 68 | // Fix the min heap property if it is violated 69 | while (i != 0 && harr[parent(i)] > harr[i]) 70 | { 71 | swap(&harr[i], &harr[parent(i)]); 72 | i = parent(i); 73 | } 74 | } 75 | 76 | // Decreases value of key at index 'i' to new_val. It is assumed that 77 | // new_val is smaller than harr[i]. 78 | void MinHeap::decreaseKey(int i, int new_val) 79 | { 80 | harr[i] = new_val; 81 | while (i != 0 && harr[parent(i)] > harr[i]) 82 | { 83 | swap(&harr[i], &harr[parent(i)]); 84 | i = parent(i); 85 | } 86 | } 87 | 88 | // Method to remove minimum element (or root) from min heap 89 | int MinHeap::extractMin() 90 | { 91 | if (heap_size <= 0) 92 | return INT_MAX; 93 | if (heap_size == 1) 94 | { 95 | heap_size--; 96 | return harr[0]; 97 | } 98 | 99 | // Store the minimum value, and remove it from heap 100 | int root = harr[0]; 101 | harr[0] = harr[heap_size-1]; 102 | heap_size--; 103 | MinHeapify(0); 104 | 105 | return root; 106 | } 107 | 108 | 109 | // This function deletes key at index i. It first reduced value to minus 110 | // infinite, then calls extractMin() 111 | void MinHeap::deleteKey(int i) 112 | { 113 | decreaseKey(i, INT_MIN); 114 | extractMin(); 115 | } 116 | 117 | // A recursive method to heapify a subtree with the root at given index 118 | // This method assumes that the subtrees are already heapified 119 | void MinHeap::MinHeapify(int i) 120 | { 121 | int l = left(i); 122 | int r = right(i); 123 | int smallest = i; 124 | if (l < heap_size && harr[l] < harr[i]) 125 | smallest = l; 126 | if (r < heap_size && harr[r] < harr[smallest]) 127 | smallest = r; 128 | if (smallest != i) 129 | { 130 | swap(&harr[i], &harr[smallest]); 131 | MinHeapify(smallest); 132 | } 133 | } 134 | 135 | // A utility function to swap two elements 136 | void swap(int *x, int *y) 137 | { 138 | int temp = *x; 139 | *x = *y; 140 | *y = temp; 141 | } 142 | 143 | // Driver program to test above functions 144 | int main() 145 | { 146 | MinHeap h(11); 147 | h.insertKey(3); 148 | h.insertKey(2); 149 | h.deleteKey(1); 150 | h.insertKey(15); 151 | h.insertKey(5); 152 | h.insertKey(4); 153 | h.insertKey(45); 154 | cout << h.extractMin() << " "; 155 | cout << h.getMin() << " "; 156 | h.decreaseKey(2, 1); 157 | cout << h.getMin(); 158 | return 0; 159 | } 160 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Amol Grover 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Data Structures and Algorithms (Hacktoberfest 2019) 2 | 3 | _Update (October 8, 2019): Thank you everyone for your contributions. Due to Hacktoberfest's policy pull requests created in this repository **will not** count against Hacktoberfest PR count. However we would like to continue this project and everyone is welcome to create this a big collection of Algorithms and Data structures._ :tada: 4 | 5 | ![Hacktoberfest 2019](https://hacktoberfest.digitalocean.com/assets/HF19_social-744d976f227e4aff6866443abcede8c651b309ec9c7c9f7410f5944f8e1299b9.png) 6 | 7 | Do you have a knack for programming? Do Data Structures and Algorithms excite you? Well, you have come to the right place. This repository holds a collection of all the famous Data Structures and Algorithms you'd ever find. 8 | 9 | As a part of Hacktoberfest 2019, you have a chance to contribute to this repository and get familiar with Open Source culture. 10 | 11 | ## How to contribute 12 | 1. Create an issue about the Data Structure/Algorithms or its application you'd like to implement. 13 | 2. Wait for any of the maintainers to give you the green signal 14 | 3. Code your heart out 15 | 4. Create a pull request 16 | 5. You're done! 17 | 18 | ## Steps for contributing 19 | 1. Decide with Algorithm/Data structure you want to work on that has not already been implemented 20 | 2. Create an issue for it and wait for the maintainers to assign it to you 21 | 3. Fork the repository 22 | 4. Clone the forked repository ```git clone https://github.com//Data-Structures-Algorithms-Hacktoberfest-2K19.git``` 23 | 5. Create a new branch for working ```git branch branch_name``` and switch to the branch ```git checkout branch_name``` 24 | 6. Code! 25 | 7. Save your changes ```git add .``` 26 | 8. Commit your code ```git commit -m "Single line description of what you did"``` 27 | 9. Push your code ```git push origin branch_name``` 28 | 10. Create a pull request. Mention which Algorithm/Data structure is implemented along with which issue it closes. Example 29 | ``` 30 | Implemented Floyd Warshall algorithm in Rust 31 | Closes #2 32 | ``` 33 | 11. Wait for it to get merged! 34 | 35 | ## Rules for contributing 36 | 1. Follow the directory structure 37 | ```Data Structures///``` and ```Algorithms///``` 38 | Example: ```Data Structures/Linked List/cpp/linked_list.cpp``` and ```Algorithms/Search/rust/binary_search.rs``` 39 | 2. Format/Indent the code properly 40 | 3. Languages accepted: C, C++, Javascript, Java, Python, Rust, Haskell, Assembly, Kotlin, Julia (wish to code in another language? Update the README!) 41 | 4. Language folder and file names should be lowercase. 42 | 5. Documented code is preferred (don't forget the space and time complexity of your code!) 43 | 6. Only 1 Data Structure/Algorithm per issue/pull request 44 | 7. Every PR should mention which issue it closes 45 | 8. PRs without issues/Spam PRs will be marked as `invalid` as it is against Hacktoberfest code of conduct. 46 | --------------------------------------------------------------------------------