diff --git a/Arrays-algos/jugglingalgo.cpp b/Arrays-algos/jugglingalgo.cpp index 749f315..91d2ce0 100644 --- a/Arrays-algos/jugglingalgo.cpp +++ b/Arrays-algos/jugglingalgo.cpp @@ -1,3 +1,4 @@ + #include using namespace std; diff --git a/Arrays-algos/maximum-subarray-sum.cpp b/Arrays-algos/maximum-subarray-sum.cpp new file mode 100644 index 0000000..4f2c9d9 --- /dev/null +++ b/Arrays-algos/maximum-subarray-sum.cpp @@ -0,0 +1,30 @@ +// C++ program to print largest contiguous array sum +#include +#include +using namespace std; + +int maxSubArraySum(int a[], int size) +{ + int max_so_far = INT_MIN, max_ending_here = 0; + + for (int i = 0; i < size; i++) + { + max_ending_here = max_ending_here + a[i]; + if (max_so_far < max_ending_here) + max_so_far = max_ending_here; + + if (max_ending_here < 0) + max_ending_here = 0; + } + return max_so_far; +} + +/*Driver program to test maxSubArraySum*/ +int main() +{ + int a[] = {-2, -3, 4, -1, -2, 1, 5, -3}; + int n = sizeof(a)/sizeof(a[0]); + int max_sum = maxSubArraySum(a, n); + cout << "Maximum contiguous sum is " << max_sum; + return 0; +} diff --git a/Arrays-algos/reversearrayalgo2.cpp b/Arrays-algos/reversearrayalgo2.cpp new file mode 100644 index 0000000..7d8950a --- /dev/null +++ b/Arrays-algos/reversearrayalgo2.cpp @@ -0,0 +1,14 @@ +void reversearray2(int arr[],int size) +{ + + int rev[size]; + int j=0; + for(int i=size-1;i>=0;i++) + { + rev[j]=arr[i]; + j++; + } + + return rev; + +} \ No newline at end of file diff --git a/Binary Tree/Tree Traversals.cpp b/Binary Tree/Tree Traversals.cpp new file mode 100644 index 0000000..37d0327 --- /dev/null +++ b/Binary Tree/Tree Traversals.cpp @@ -0,0 +1,86 @@ +// C program for different tree traversals +#include +using namespace std; + +/* A binary tree node has data, pointer to left child +and a pointer to right child */ +struct Node +{ + int data; + struct Node *left, *right; + Node(int data) + { + this->data = data; + left = right = NULL; + } +}; + +/* Given a binary tree, print its nodes according to the +"bottom-up" postorder traversal. */ +void printPostorder(struct Node *node) +{ + if (node == NULL) + return; + + // first recur on left subtree + printPostorder(node->left); + + // then recur on right subtree + printPostorder(node->right); + + // now deal with the node + cout << node->data << " "; +} + +/* Given a binary tree, print its nodes in inorder*/ +void printInorder(struct Node *node) +{ + if (node == NULL) + return; + + /* first recur on left child */ + printInorder(node->left); + + /* then print the data of node */ + cout << node->data << " "; + + /* now recur on right child */ + printInorder(node->right); +} + +/* Given a binary tree, print its nodes in preorder*/ +void printPreorder(struct Node *node) +{ + if (node == NULL) + return; + + /* first print data of node */ + cout << node->data << " "; + + /* then recur on left sutree */ + printPreorder(node->left); + + /* now recur on right subtree */ + printPreorder(node->right); +} + +/* Driver program to test above functions*/ +int main() +{ + struct Node *root = new Node(1); + root->left = new Node(2); + root->right = new Node(3); + root->left->left = new Node(4); + root->left->right = new Node(5); + + cout << "\nPreorder traversal of binary tree is \n"; + printPreorder(root); + + cout << "\nInorder traversal of binary tree is \n"; + printInorder(root); + + cout << "\nPostorder traversal of binary tree is \n"; + printPostorder(root); + + return 0; +} diff --git a/backtracking-algos/Hamiltoniancycle.cpp b/backtracking-algos/Hamiltoniancycle.cpp new file mode 100644 index 0000000..b87a016 --- /dev/null +++ b/backtracking-algos/Hamiltoniancycle.cpp @@ -0,0 +1,154 @@ +/* C++ program for solution of Hamiltonian +Cycle problem using backtracking */ +#include +using namespace std; + +// Number of vertices in the graph +#define V 5 + +void printSolution(int path[]); + +/* A utility function to check if +the vertex v can be added at index 'pos' +in the Hamiltonian Cycle constructed +so far (stored in 'path[]') */ +bool isSafe(int v, bool graph[V][V], + int path[], int pos) +{ + /* Check if this vertex is an adjacent + vertex of the previously added vertex. */ + if (graph [path[pos - 1]][ v ] == 0) + return false; + + /* Check if the vertex has already been included. + This step can be optimized by creating + an array of size V */ + for (int i = 0; i < pos; i++) + if (path[i] == v) + return false; + + return true; +} + +/* A recursive utility function +to solve hamiltonian cycle problem */ +bool hamCycleUtil(bool graph[V][V], + int path[], int pos) +{ + /* base case: If all vertices are + included in Hamiltonian Cycle */ + if (pos == V) + { + // And if there is an edge from the + // last included vertex to the first vertex + if (graph[path[pos - 1]][path[0]] == 1) + return true; + else + return false; + } + + // Try different vertices as a next candidate + // in Hamiltonian Cycle. We don't try for 0 as + // we included 0 as starting point in hamCycle() + for (int v = 1; v < V; v++) + { + /* Check if this vertex can be added + // to Hamiltonian Cycle */ + if (isSafe(v, graph, path, pos)) + { + path[pos] = v; + + /* recur to construct rest of the path */ + if (hamCycleUtil (graph, path, pos + 1) == true) + return true; + + /* If adding vertex v doesn't lead to a solution, + then remove it */ + path[pos] = -1; + } + } + + /* If no vertex can be added to + Hamiltonian Cycle constructed so far, + then return false */ + return false; +} + +/* This function solves the Hamiltonian Cycle problem +using Backtracking. It mainly uses hamCycleUtil() to +solve the problem. It returns false if there is no +Hamiltonian Cycle possible, otherwise return true +and prints the path. Please note that there may be +more than one solutions, this function prints one +of the feasible solutions. */ +bool hamCycle(bool graph[V][V]) +{ + int *path = new int[V]; + for (int i = 0; i < V; i++) + path[i] = -1; + + /* Let us put vertex 0 as the first vertex in the path. + If there is a Hamiltonian Cycle, then the path can be + started from any point of the cycle as the graph is undirected */ + path[0] = 0; + if (hamCycleUtil(graph, path, 1) == false ) + { + cout << "\nSolution does not exist"; + return false; + } + + printSolution(path); + return true; +} + +/* A utility function to print solution */ +void printSolution(int path[]) +{ + cout << "Solution Exists:" + " Following is one Hamiltonian Cycle \n"; + for (int i = 0; i < V; i++) + cout << path[i] << " "; + + // Let us print the first vertex again + // to show the complete cycle + cout << path[0] << " "; + cout << endl; +} + +// Driver Code +int main() +{ + /* Let us create the following graph + (0)--(1)--(2) + | / \ | + | / \ | + | / \ | + (3)-------(4) */ + bool graph1[V][V] = {{0, 1, 0, 1, 0}, + {1, 0, 1, 1, 1}, + {0, 1, 0, 0, 1}, + {1, 1, 0, 0, 1}, + {0, 1, 1, 1, 0}}; + + // Print the solution + hamCycle(graph1); + + /* Let us create the following graph + (0)--(1)--(2) + | / \ | + | / \ | + | / \ | + (3) (4) */ + bool graph2[V][V] = {{0, 1, 0, 1, 0}, + {1, 0, 1, 1, 1}, + {0, 1, 0, 0, 1}, + {1, 1, 0, 0, 0}, + {0, 1, 1, 0, 0}}; + + // Print the solution + hamCycle(graph2); + + return 0; +} + +// This is code is contributed by rathbhupendra diff --git a/backtracking-algos/N-queens.cpp b/backtracking-algos/N-queens.cpp new file mode 100644 index 0000000..84ac8e2 --- /dev/null +++ b/backtracking-algos/N-queens.cpp @@ -0,0 +1,108 @@ +/* C/C++ program to solve N Queen Problem using +backtracking */ +#define N 4 +#include +#include + +/* A utility function to print solution */ +void printSolution(int board[N][N]) +{ + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) + printf(" %d ", board[i][j]); + printf("\n"); + } +} + +/* A utility function to check if a queen can +be placed on board[row][col]. Note that this +function is called when "col" queens are +already placed in columns from 0 to col -1. +So we need to check only left side for +attacking queens */ +bool isSafe(int board[N][N], int row, int col) +{ + int i, j; + + /* Check this row on left side */ + for (i = 0; i < col; i++) + if (board[row][i]) + return false; + + /* Check upper diagonal on left side */ + for (i = row, j = col; i >= 0 && j >= 0; i--, j--) + if (board[i][j]) + return false; + + /* Check lower diagonal on left side */ + for (i = row, j = col; j >= 0 && i < N; i++, j--) + if (board[i][j]) + return false; + + return true; +} + +/* A recursive utility function to solve N +Queen problem */ +bool solveNQUtil(int board[N][N], int col) +{ + /* base case: If all queens are placed + then return true */ + if (col >= N) + return true; + + /* Consider this column and try placing + this queen in all rows one by one */ + for (int i = 0; i < N; i++) { + /* Check if the queen can be placed on + board[i][col] */ + if (isSafe(board, i, col)) { + /* Place this queen in board[i][col] */ + board[i][col] = 1; + + /* recur to place rest of the queens */ + if (solveNQUtil(board, col + 1)) + return true; + + /* If placing queen in board[i][col] + doesn't lead to a solution, then + remove queen from board[i][col] */ + board[i][col] = 0; // BACKTRACK + } + } + + /* If the queen cannot be placed in any row in + this colum col then return false */ + return false; +} + +/* This function solves the N Queen problem using +Backtracking. It mainly uses solveNQUtil() to +solve the problem. It returns false if queens +cannot be placed, otherwise, return true and +prints placement of queens in the form of 1s. +Please note that there may be more than one +solutions, this function prints one of the +feasible solutions.*/ +bool solveNQ() +{ + int board[N][N] = { { 0, 0, 0, 0 }, + { 0, 0, 0, 0 }, + { 0, 0, 0, 0 }, + { 0, 0, 0, 0 } }; + + if (solveNQUtil(board, 0) == false) { + printf("Solution does not exist"); + return false; + } + + printSolution(board); + return true; +} + +// driver program to test above function +int main() +{ + solveNQ(); + return 0; +} diff --git a/backtracking-algos/m-coloring.cpp b/backtracking-algos/m-coloring.cpp new file mode 100644 index 0000000..caf2aad --- /dev/null +++ b/backtracking-algos/m-coloring.cpp @@ -0,0 +1,103 @@ +#include +#include + +// Number of vertices in the graph +#define V 4 + +void printSolution(int color[]); + +// check if the colored +// graph is safe or not +bool isSafe( + bool graph[V][V], int color[]) +{ + // check for every edge + for (int i = 0; i < V; i++) + for (int j = i + 1; j < V; j++) + if ( + graph[i][j] && color[j] == color[i]) + return false; + return true; +} + +/* This function solves the m Coloring +problem using recursion. It returns +false if the m colours cannot be assigned, +otherwise, return true and prints +assignments of colours to all vertices. +Please note that there may be more than +one solutions, this function prints one +of the feasible solutions.*/ +bool graphColoring( + bool graph[V][V], int m, + int i, int color[V]) +{ + // if current index reached end + if (i == V) { + // if coloring is safe + if (isSafe(graph, color)) { + // Print the solution + printSolution(color); + return true; + } + return false; + } + + // Assign each color from 1 to m + for (int j = 1; j <= m; j++) { + color[i] = j; + + // Recur of the rest vertices + if (graphColoring( + graph, m, i + 1, color)) + return true; + + color[i] = 0; + } + + return false; +} + +/* A utility function to print solution */ +void printSolution(int color[]) +{ + printf( + "Solution Exists:" + " Following are the assigned colors \n"); + for (int i = 0; i < V; i++) + printf(" %d ", color[i]); + printf("\n"); +} + +// Driver program to test above function +int main() +{ + /* Create following graph and + test whether it is 3 colorable + (3)---(2) + | / | + | / | + | / | + (0)---(1) + */ + bool graph[V][V] = { + { 0, 1, 1, 1 }, + { 1, 0, 1, 0 }, + { 1, 1, 0, 1 }, + { 1, 0, 1, 0 }, + }; + int m = 3; // Number of colors + + // Initialize all color values as 0. + // This initialization is needed + // correct functioning of isSafe() + int color[V]; + for (int i = 0; i < V; i++) + color[i] = 0; + + if (!graphColoring( + graph, m, 0, color)) + printf("Solution does not exist"); + + return 0; +} diff --git a/backtracking-algos/sudoku.cpp b/backtracking-algos/sudoku.cpp new file mode 100644 index 0000000..0537d8c --- /dev/null +++ b/backtracking-algos/sudoku.cpp @@ -0,0 +1,138 @@ +#include + +using namespace std; + +// N is the size of the 2D matrix N*N +#define N 9 + +/* A utility function to print grid */ +void print(int arr[N][N]) +{ + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) + cout << arr[i][j] << " "; + cout << endl; + } +} + +// Checks whether it will be +// legal to assign num to the +// given row, col +bool isSafe(int grid[N][N], int row, + int col, int num) +{ + + // if we find the same num + // in the similar row , we + // return false + for (int x = 0; x <= 8; x++) + if (grid[row][x] == num) + return false; + + // if we find the same num in + // the similar column , we + // return false + for (int x = 0; x <= 8; x++) + if (grid[x][col] == num) + return false; + + // if we find the same num in + // the particular 3*3 matrix, + // we return false + int startRow = row - row % 3, + startCol = col - col % 3; + + for (int i = 0; i < 3; i++) + for (int j = 0; j < 3; j++) + if (grid[i + startRow][j + + startCol] == num) + return false; + + return true; +} + +/* Takes a partially filled-in grid and attempts +to assign values to all unassigned locations in +such a way to meet the requirements for +Sudoku solution (non-duplication across rows, +columns, and boxes) */ +bool solveSuduko(int grid[N][N], int row, int col) +{ + // Check if we have reached the 8th + // row and 9th column (0 + // indexed matrix) , we are + // returning true to avoid + // further backtracking + if (row == N - 1 && col == N) + return true; + + // Check if column value becomes 9 , + // we move to next row and + // column start from 0 + if (col == N) { + row++; + col = 0; + } + + // Check if the current position of + // the grid already contains + // value >0, we iterate for next column + if (grid[row][col] > 0) + return solveSuduko(grid, row, col + 1); + + for (int num = 1; num <= N; num++) + { + + // if it is safe to place + // the num (1-9) in the + // given row ,col ->we + // move to next column + if (isSafe(grid, row, col, num)) + { + + /* Assigning the num in + the current (row,col) + position of the grid + and assuming our assined + num in the position + is correct */ + grid[row][col] = num; + + // Checking for next possibility with next + // column + if (solveSuduko(grid, row, col + 1)) + return true; + } + + // Removing the assigned num , + // since our assumption + // was wrong , and we go for + // next assumption with + // diff num value + grid[row][col] = 0; + } + return false; +} + +// Driver Code +int main() +{ + // 0 means unassigned cells + int grid[N][N] = { { 3, 0, 6, 5, 0, 8, 4, 0, 0 }, + { 5, 2, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 8, 7, 0, 0, 0, 0, 3, 1 }, + { 0, 0, 3, 0, 1, 0, 0, 8, 0 }, + { 9, 0, 0, 8, 6, 3, 0, 0, 5 }, + { 0, 5, 0, 0, 9, 0, 6, 0, 0 }, + { 1, 3, 0, 0, 0, 0, 2, 5, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 7, 4 }, + { 0, 0, 5, 2, 0, 6, 3, 0, 0 } }; + + if (solveSuduko(grid, 0, 0)) + print(grid); + else + cout << "no solution exists " << endl; + + return 0; + // This is code is contributed by Pradeep Mondal P +} diff --git a/greedy-algos/0-1 Knapsack Problem/0-1 knapsack.cpp b/greedy-algos/0-1 Knapsack Problem/0-1 knapsack.cpp new file mode 100644 index 0000000..56696fc --- /dev/null +++ b/greedy-algos/0-1 Knapsack Problem/0-1 knapsack.cpp @@ -0,0 +1,46 @@ +/* A Naive recursive implementation of + 0-1 Knapsack problem */ +#include +using namespace std; + +// A utility function that returns +// maximum of two integers +int max(int a, int b) { return (a > b) ? a : b; } + +// Returns the maximum value that +// can be put in a knapsack of capacity W +int knapSack(int W, int wt[], int val[], int n) +{ + + // Base Case + if (n == 0 || W == 0) + return 0; + + // If weight of the nth item is more + // than Knapsack capacity W, then + // this item cannot be included + // in the optimal solution + if (wt[n] > W) + return knapSack(W, wt, val, n - 1); + + // Return the maximum of two cases: + // (1) nth item included + // (2) not included + else + return max( + val[n] + knapSack(W - wt[n], + wt, val, n - 1), + knapSack(W, wt, val, n - 1)); +} + +// Driver code +int main() +{ + int val[] = { 60, 100, 120 }; + int wt[] = { 10, 20, 30 }; + int W = 50; + int n = sizeof(val) / sizeof(val[0]); + cout << knapSack(W, wt, val, n); + return 0; +} +//contributed by Rhythm Verma \ No newline at end of file diff --git a/search-with-noob/a.exe b/search-with-noob/a.exe new file mode 100644 index 0000000..6d6e27f Binary files /dev/null and b/search-with-noob/a.exe differ diff --git a/search-with-noob/a.out b/search-with-noob/a.out new file mode 100644 index 0000000..05f1f11 Binary files /dev/null and b/search-with-noob/a.out differ diff --git a/search-with-noob/binary_search.cpp b/search-with-noob/binary_search.cpp index ab79acb..e2f86ce 100644 --- a/search-with-noob/binary_search.cpp +++ b/search-with-noob/binary_search.cpp @@ -23,13 +23,25 @@ int binary_search(int array[], int search, int lower, int upper) //Since the Binary Search needs a sorted array but we have an unsorted array so it needs to be sorted first. //You can use any sorting method as per your convenience. -int sort(int arr[],int search) +int sort(int arr[],int search, int size) { + for (int step = 0; step < size - 1; ++step) + { + for (int i = 0; i < size - step - 1; ++i) + { + if (arr[i] > arr[i + 1]) + { + int temp = arr[i]; + arr[i] = arr[i + 1]; + arr[i + 1] = temp; + } + } +} // You have to sort the array and call the binary function and return the result you get from that function to the main. - int result = binary_search(sorted_array_name, search_element, initial_lower_value, initial_upper value ); + int result = binary_search(arr, search, 0, size-1 ); return result; } @@ -41,7 +53,7 @@ int main() cout<<"Enter search element"<>search; int size = sizeof(array) / sizeof(array[0]); - int result = sort(array, search); + int result = sort(array, search,size); if (result == -1) cout<<"Element not found"< +using namespace std; + +int jumpSearch(int arr[], int x, int n) +{ + // Finding block size to be jumped + int step = sqrt(n); + + // Finding the block where element is + // present (if it is present) + int prev = 0; + while (arr[min(step, n)-1] < x) + { + prev = step; + step += sqrt(n); + if (prev >= n) + return -1; + } + + // Doing a linear search for x in block + // beginning with prev. + while (arr[prev] < x) + { + prev++; + + // If we reached next block or end of + // array, element is not present. + if (prev == min(step, n)) + return -1; + } + // If element is found + if (arr[prev] == x) + return prev; + + return -1; +} + +// Driver program to test function +int main() +{ + int arr[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, + 34, 55, 89, 144, 233, 377, 610 }; + int x = 55; + int n = sizeof(arr) / sizeof(arr[0]); + + // Find the index of 'x' using Jump Search + int index = jumpSearch(arr, x, n); + + // Print the index where 'x' is located + cout << "\nNumber " << x << " is at index " << index; + return 0; +} + +// Contributed by nuclode diff --git a/search-with-noob/linear_search.cpp b/search-with-noob/linear_search.cpp index 8806cd8..9c395e4 100644 --- a/search-with-noob/linear_search.cpp +++ b/search-with-noob/linear_search.cpp @@ -18,13 +18,17 @@ int main() int search_element; //Take the input of the element to be searched by the user. + scanf("%d",&search_element); int result = linear_search(arr,size,search_element); //If the result is -1 then print that the element is not present in the array. + if(result==-1) + printf("element not found\n"); //If the result is any value but -1 then print the element is found on that index. - + else + printf("element found at index %d",result); return 0; } \ No newline at end of file