├── .all-contributorsrc
├── .vscode
├── c_cpp_properties.json
├── launch.json
├── settings.json
└── tasks.json
├── Algorithms
├── Approximation
│ └── main.c
├── BackTracking
│ ├── 0
│ │ └── 1 Knapsack
│ │ │ └── main.c
│ ├── Graph Coloring
│ │ ├── main.c
│ │ ├── main.exe
│ │ └── tempCodeRunnerFile.c
│ ├── Hamiltonian Cycle
│ │ ├── main.c
│ │ └── main.exe
│ ├── NQueens Problem
│ │ ├── main.c
│ │ ├── main.cpp
│ │ └── main.exe
│ └── Sum Of Subset
│ │ ├── main.c
│ │ └── main.exe
├── Divide and Conquer
│ ├── Closest Pair
│ │ └── main.c
│ ├── Insertion Sort
│ │ ├── main.c
│ │ └── main.exe
│ ├── Merge Sort
│ │ ├── main.c
│ │ └── main.exe
│ ├── MinMax Algo
│ │ ├── MinMax.png
│ │ ├── main.c
│ │ └── main.exe
│ ├── Quick Sort
│ │ ├── main.c
│ │ └── main.exe
│ ├── Randomized Quick Sort
│ │ └── main.c
│ └── Strassen's Matrix Multiplication
│ │ ├── main.c
│ │ └── main.exe
├── Dynamic Programming
│ ├── Bellman Ford
│ │ ├── main.c
│ │ └── main.exe
│ ├── Coin Change
│ │ ├── Memoization
│ │ │ ├── main.c
│ │ │ ├── main.exe
│ │ │ └── tempCodeRunnerFile.c
│ │ ├── Recursion
│ │ │ └── main.c
│ │ └── Tabulation
│ │ │ ├── main.c
│ │ │ ├── main.exe
│ │ │ └── tempCodeRunnerFile.c
│ ├── Fibonacci Problem
│ │ └── main.c
│ ├── Floyd Warshall
│ │ ├── main.c
│ │ └── main.exe
│ ├── Johnson's Algo
│ │ └── main.c
│ ├── Knapsack
│ │ └── 0
│ │ │ └── 1 Knapsack
│ │ │ ├── Memoization
│ │ │ └── main.c
│ │ │ └── Recursion
│ │ │ └── main.c
│ ├── LCS
│ │ ├── Memoization
│ │ │ ├── main.c
│ │ │ └── main.exe
│ │ ├── Recursive
│ │ │ └── main.c
│ │ ├── main.c
│ │ └── main.exe
│ ├── MCM
│ │ ├── Memoization
│ │ │ ├── main.c
│ │ │ └── main.exe
│ │ └── Recursive
│ │ │ └── main.c
│ ├── Multistage Graph
│ │ ├── Tabularization
│ │ │ └── main.c
│ │ └── images
│ │ │ ├── image1.png
│ │ │ └── image2.png
│ ├── Optimal Binary Search Tree
│ │ └── main.c
│ └── TSP
│ │ ├── main.c
│ │ └── main.exe
├── Greedy
│ ├── Dijkstra's Algorithm
│ │ ├── main.c
│ │ └── main.exe
│ ├── Fractional Knapsack
│ │ └── main.c
│ ├── Job Sequencing
│ │ └── main.c
│ └── Minimum Spanning Tree
│ │ ├── Kruskal's Algorithm
│ │ ├── main.c
│ │ └── main.exe
│ │ └── Prim's Algorithm
│ │ ├── main.c
│ │ └── main.exe
├── Practice
│ ├── BackTracking
│ │ ├── Graph Coloring
│ │ │ ├── main.c
│ │ │ └── main.exe
│ │ ├── Hamiltonian Cycles
│ │ │ ├── main.c
│ │ │ └── main.exe
│ │ ├── NQueen Problem
│ │ │ ├── main.c
│ │ │ └── main.exe
│ │ └── Sum Of Subset
│ │ │ ├── main.c
│ │ │ └── main.exe
│ ├── Divide and Conquer
│ │ ├── Insertion Sort
│ │ │ ├── main.c
│ │ │ └── main.exe
│ │ ├── Merge Sort
│ │ │ ├── main.c
│ │ │ └── main.exe
│ │ ├── MinMax Algorithm
│ │ │ ├── main.c
│ │ │ └── main.exe
│ │ ├── Quick Sort
│ │ │ ├── main.c
│ │ │ └── main.exe
│ │ ├── Selection Sort
│ │ │ ├── main.c
│ │ │ └── main.exe
│ │ └── Strassen's Matrix Multiplication
│ │ │ ├── main.c
│ │ │ ├── main.exe
│ │ │ └── tempCodeRunnerFile.c
│ ├── Dynamic Programming
│ │ ├── 0
│ │ │ └── 1 Knapsack
│ │ │ │ ├── main.c
│ │ │ │ └── main.exe
│ │ ├── Bellman Ford
│ │ │ ├── main.c
│ │ │ └── main.exe
│ │ ├── Floyd Warshall
│ │ │ ├── main.c
│ │ │ └── main.exe
│ │ ├── LCS
│ │ │ ├── main.c
│ │ │ └── main.exe
│ │ └── MCM
│ │ │ ├── main.c
│ │ │ └── main.exe
│ ├── Experiment List
│ │ └── List.txt
│ ├── Greedy Method
│ │ ├── Dijkstra's Algorithm
│ │ │ ├── main.c
│ │ │ └── main.exe
│ │ ├── Fractional Knapsack
│ │ │ ├── main.c
│ │ │ └── main.exe
│ │ ├── Kruskal's Algorithm
│ │ │ ├── main.c
│ │ │ └── main.exe
│ │ └── Prim's Algorithm
│ │ │ ├── main.c
│ │ │ └── main.exe
│ └── String Matching
│ │ ├── KMP
│ │ ├── main.c
│ │ └── main.exe
│ │ └── Rabin Karp
│ │ ├── main.c
│ │ └── main.exe
├── Readme.md
├── Sliding Window
│ ├── FirstNegInt
│ │ ├── input.txt
│ │ ├── main.cpp
│ │ ├── main.exe
│ │ └── output.txt
│ └── Max subarr sum of size k
│ │ ├── input.txt
│ │ ├── main.cpp
│ │ ├── main.exe
│ │ └── output.txt
└── String Matching
│ ├── KMP
│ ├── input.txt
│ ├── main.c
│ ├── main.exe
│ └── output.txt
│ └── Rabin Karp
│ ├── main.c
│ ├── main.exe
│ └── tempCodeRunnerFile.c
├── Graph
├── Graph (undirected) Representation.png
├── Minimum Spanning Tree
│ ├── Kruskal's Algorithm
│ │ ├── main.c
│ │ └── main.exe
│ └── Prim's Algorithm
│ │ ├── main.c
│ │ └── main.exe
├── Queue.h
├── README.md
└── main.c
├── Hash
├── Chaining
│ ├── Readme.md
│ ├── chains.exe
│ ├── chains.h
│ ├── main.c
│ └── main.exe
├── Linear Probing
│ ├── Readme.md
│ ├── linear probing.png
│ ├── main.c
│ └── main.exe
├── Quadratic Probing
│ ├── main.c
│ └── quadratic probing.png
└── README.md
├── Heap
├── Heapify
│ └── heapify.png
├── README.md
├── main.c
├── main.exe
└── operations
│ ├── Creation of Max Heap.png
│ ├── Deletion in Max Heap.png
│ └── Insertion in Max Heap.png
├── Linked List
├── Circular Linked List
│ ├── README.md
│ ├── insertion and deletion based on position.png
│ ├── insertion based value.png
│ ├── main.c
│ ├── main.exe
│ ├── operations.exe
│ └── operations.h
├── Doubly Linked List
│ ├── Insert & deletion based on the valule.png
│ ├── README.md
│ ├── insertion deletion based the position.png
│ ├── main.c
│ ├── main.exe
│ ├── operations.exe
│ └── operations.h
├── README.md
├── Singly Linked List
│ ├── C
│ │ ├── main.c
│ │ ├── main.exe
│ │ ├── middleElement
│ │ │ ├── main.c
│ │ │ └── main.exe
│ │ └── operations.h
│ ├── README.md
│ └── index.js
└── problems
│ ├── Swapping
│ ├── README.md
│ ├── main.c
│ ├── main.exe
│ └── swapping image.PNG
│ ├── polynomial
│ ├── Readme.md
│ ├── main.c
│ ├── operations.h
│ └── polynomial.png
│ └── sparse matrix
│ ├── Readme.md
│ ├── main.c
│ ├── operations.h
│ └── sparse matrix represenation.png
├── Queue
├── Array
│ ├── Circular
│ │ ├── main.c
│ │ └── main.exe
│ └── linear
│ │ ├── main.c
│ │ └── main.exe
├── DEQueue
│ └── Array
│ │ └── main.c
├── LinkedLilst
│ ├── main.c
│ └── main.exe
├── Priority Queue
│ ├── Array
│ │ ├── main.c
│ │ ├── main.exe
│ │ └── priority queue.png
│ └── LinkedList
│ │ ├── main.c
│ │ └── main.exe
├── README.md
└── Stack
│ ├── a.exe
│ ├── main.c
│ └── main.exe
├── README.md
├── Search
├── BinarySearch
│ ├── main.c
│ └── readme.md
├── FibonacciSearch
│ └── main.c
├── LinearSearch
│ ├── Readme.md
│ └── main.c
└── Readme.md
├── Tree
├── AVL
│ ├── Node height.png
│ ├── README.md
│ ├── Rotation
│ │ ├── LLRotation.png
│ │ ├── LRRotation.png
│ │ ├── RLRotation.png
│ │ └── RRRotation.png
│ ├── main.c
│ └── main.exe
├── B-Tree
│ └── main.c
├── BST
│ ├── BST Quiz.png
│ ├── Delete.png
│ ├── DeleteIterative.png
│ ├── Depth of a node.png
│ ├── README.md
│ ├── find min and max element.png
│ ├── main.c
│ ├── main.exe
│ ├── practice of delete iterative.png
│ └── stack.h
├── Binary Tree
│ ├── Binary Tree representation.png
│ ├── README.md
│ ├── height & level.png
│ ├── main.c
│ ├── operations.h
│ └── stack.h
└── README.md
├── notes
└── Data Structure.docx
├── recursion
├── example.js
├── global.js
├── head.js
├── indirect.js
├── linear.js
├── nested.js
├── package.json
├── programs
│ ├── Factorial.js
│ ├── Fibonacci.js
│ ├── Sum of digits.js
│ ├── TOH.js
│ ├── combination.js
│ ├── power of a number.js
│ ├── quiz5.js
│ ├── sum of natural numbers.js
│ ├── taylor series e^x.js
│ └── taylor series.js
├── tail.js
└── tree.js
├── sorting algo
├── Bin
│ └── main.c
├── Bubble
│ └── bubble.js
├── Count
│ └── main.c
├── Insertion
│ ├── InsertionSort.c
│ └── Readme.md
├── Merge
│ ├── MergeSort.c
│ ├── MergeSort.exe
│ └── Readme.md
├── Quick
│ ├── QuickSort.c
│ ├── QuickSort.exe
│ └── Readme.md
├── Radix
│ └── main.c
├── Readme.md
└── Selection
│ ├── Readme.md
│ └── SelectionSort.c
└── stack
├── Evaluation of postfix
├── main.c
└── main.exe
├── Evaluation of prefix
├── main.c
├── main.exe
└── operations.h
├── README.md
├── infix to postfix
├── infixToPostfixAsso.c
├── infixToPostfixAsso.exe
├── main.c
├── main.exe
├── mainInfixToPostfix.c
├── mainInfixToPostfix.exe
└── tempCodeRunnerFile.exe
├── infix to prefix
├── main.c
├── main.exe
├── operations.exe
└── operations.h
├── linkedlist.c
├── linkedlist.exe
├── main.c
├── main.exe
└── parenthesis problems
├── pm.c
└── pm.exe
/.all-contributorsrc:
--------------------------------------------------------------------------------
1 | {
2 | "files": ["README.md"],
3 | "imageSize": 100,
4 | "commit": false,
5 | "contributors": [],
6 | "contributorsPerLine": 7,
7 | "projectName": "your-repo-name",
8 | "projectOwner": "your-github-username",
9 | "repoType": "github",
10 | "repoHost": "https://github.com",
11 | "skipCi": true
12 | }
13 |
--------------------------------------------------------------------------------
/.vscode/c_cpp_properties.json:
--------------------------------------------------------------------------------
1 | {
2 | "configurations": [
3 | {
4 | "name": "Win32",
5 | "includePath": [
6 | "${workspaceFolder}/**",
7 | "${workspaceFolder}/Hash/Chaining"
8 | ],
9 | "defines": [
10 | "_DEBUG",
11 | "UNICODE",
12 | "_UNICODE"
13 | ],
14 | "compilerPath": "C:\\MinGW\\bin\\gcc.exe",
15 | "cStandard": "c11",
16 | "cppStandard": "gnu++14",
17 | "intelliSenseMode": "windows-gcc-x86"
18 | }
19 | ],
20 | "version": 4
21 | }
--------------------------------------------------------------------------------
/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | // Use IntelliSense to learn about possible attributes.
3 | // Hover to view descriptions of existing attributes.
4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5 | "version": "0.2.0",
6 | "configurations": []
7 | }
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "files.associations": {
3 | "stdbool.h": "c",
4 | "stdio.h": "c",
5 | "chains.h": "c",
6 | "operations.h": "c",
7 | "stdlib.h": "c",
8 | "tree.h": "c",
9 | "stack.h": "c",
10 | "random": "c",
11 | "limits.h": "c",
12 | "string.h": "c"
13 | },
14 | "C_Cpp.errorSquiggles": "disabled"
15 | }
--------------------------------------------------------------------------------
/.vscode/tasks.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "2.0.0",
3 | "tasks": [
4 | {
5 | "label": "Compile and Run",
6 | "type": "shell",
7 | "command": "cmd.exe",
8 | "args": [
9 | "/C",
10 | "echo Compiling ${fileBasename}... && g++ \"${file}\" -o \"${fileDirname}/${fileBasenameNoExtension}.exe\" && echo Running program... && \"${fileDirname}/${fileBasenameNoExtension}.exe\" < \"${fileDirname}/input.txt\" > \"${fileDirname}/output.txt\" && echo Output saved to output.txt && type \"${fileDirname}/output.txt\""
11 | ],
12 | "options": {
13 | "cwd": "${fileDirname}"
14 | },
15 | "presentation": {
16 | "reveal": "always",
17 | "panel": "shared",
18 | "clear": true,
19 | "showReuseMessage": false
20 | },
21 | "group": "build",
22 | "problemMatcher": [
23 | "$gcc"
24 | ]
25 | },
26 | {
27 | "type": "cppbuild",
28 | "label": "C/C++: gcc.exe build active file",
29 | "command": "C:\\MinGW\\bin\\gcc.exe",
30 | "args": [
31 | "-fdiagnostics-color=always",
32 | "-g",
33 | "${file}",
34 | "-o",
35 | "${fileDirname}\\${fileBasenameNoExtension}.exe"
36 | ],
37 | "options": {
38 | "cwd": "${fileDirname}"
39 | },
40 | "problemMatcher": [
41 | "$gcc"
42 | ],
43 | "group": {
44 | "kind": "build",
45 | "isDefault": true
46 | },
47 | "detail": "Task generated by Debugger."
48 | }
49 | ]
50 | }
--------------------------------------------------------------------------------
/Algorithms/Approximation/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | #define N 4
6 |
7 | int dist[N][N] = {
8 | {0, 10, 15, 20},
9 | {10, 0, 35, 25},
10 | {15, 35, 0, 30},
11 | {20, 25, 30, 0}
12 | };
13 |
14 | int primMST() {
15 | int key[N];
16 | bool mstSet[N];
17 |
18 | for (int i = 0; i < N; i++) {
19 | key[i] = INT_MAX;
20 | mstSet[i] = false;
21 | }
22 |
23 | key[0] = 0;
24 |
25 | for (int count = 0; count < N - 1; count++) {
26 | int u = -1;
27 |
28 | for (int i = 0; i < N; i++) {
29 | if (!mstSet[i] && (u == -1 || key[i] < key[u])) {
30 | u = i;
31 | }
32 | }
33 |
34 | mstSet[u] = true;
35 |
36 | for (int v = 0; v < N; v++) {
37 | if (dist[u][v] && !mstSet[v] && dist[u][v] < key[v]) {
38 | key[v] = dist[u][v];
39 | }
40 | }
41 | }
42 |
43 | int mstWeight = 0;
44 | for (int i = 1; i < N; i++) {
45 | mstWeight += key[i];
46 | }
47 | return mstWeight;
48 | }
49 |
50 | int main() {
51 | int approxCost = 2 * primMST();
52 | printf("Approximate cost: %d\n", approxCost);
53 | return 0;
54 | }
55 |
--------------------------------------------------------------------------------
/Algorithms/BackTracking/Graph Coloring/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | #define V 5
6 |
7 | int solutionCount = 0;
8 |
9 | bool isSafe(int graph[V][V], int color[], int v, int c) {
10 | for (int i = 1; i < V; i++) {
11 | if (graph[v][i] && color[i] == c)
12 | return false;
13 | }
14 | return true;
15 | }
16 |
17 | void graphColoringUtil(int graph[V][V], int m, int color[], int v) {
18 | if (v == V) {
19 | solutionCount++;
20 | printf("Solution %d:\n", solutionCount);
21 | for (int i = 1; i < V; i++) {
22 | printf("Vertex %d → Color %d\n", i, color[i]);
23 | }
24 | printf("\n");
25 | return;
26 | }
27 |
28 | for (int c = 1; c <= m; c++) {
29 | if (isSafe(graph, color, v, c)) {
30 | color[v] = c;
31 | graphColoringUtil(graph, m, color, v + 1);
32 | color[v] = 0; // Backtrack
33 | }
34 | }
35 | }
36 |
37 | void graphColoring(int graph[V][V], int m) {
38 | int color[V] = {0};
39 | graphColoringUtil(graph, m, color, 1);
40 |
41 | if (solutionCount == 0)
42 | printf("No valid coloring possible with %d colors.\n", m);
43 | else
44 | printf("Total Solutions: %d\n", solutionCount);
45 | }
46 |
47 | int main() {
48 | int graph[V][V] = {
49 | {0, 0, 0, 0, 0},
50 | {0, 0, 1, 0, 0},
51 | {0, 1, 0, 1, 0},
52 | {0, 0, 1, 0, 1},
53 | {0, 0, 0, 1, 0}
54 | };
55 |
56 | int m = 3; // Number of colors
57 | graphColoring(graph, m);
58 | return 0;
59 | }
60 |
--------------------------------------------------------------------------------
/Algorithms/BackTracking/Graph Coloring/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/BackTracking/Graph Coloring/main.exe
--------------------------------------------------------------------------------
/Algorithms/BackTracking/Graph Coloring/tempCodeRunnerFile.c:
--------------------------------------------------------------------------------
1 | int graph[V][V] = {
2 | {0, 0, 0, 0, 0},
3 | {0, 0, 1, 1, 0},
4 | {0, 1, 0, 0, 1},
5 | {0, 1, 0, 0, 1},
6 | {0, 0, 1, 1, 0}
7 | };
--------------------------------------------------------------------------------
/Algorithms/BackTracking/Hamiltonian Cycle/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/BackTracking/Hamiltonian Cycle/main.exe
--------------------------------------------------------------------------------
/Algorithms/BackTracking/NQueens Problem/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | int board[20], count;
4 |
5 | int main()
6 | {
7 | int n, i, j;
8 | void queen(int row, int n);
9 |
10 | printf(" - N Queens Problem Using Backtracking -");
11 | printf("\n\nEnter number of Queens:");
12 | scanf("%d", &n);
13 |
14 | if(n == 2 || n == 3){
15 | printf("\nNo Solutions exists.");
16 | return 0;
17 | }
18 |
19 | queen(1, n);
20 | return 0;
21 | }
22 |
23 | // function for printing the solution
24 | void print(int n)
25 | {
26 | int i, j;
27 | printf("\n\nSolution %d:\n\n", ++count);
28 |
29 | for (i = 1; i <= n; ++i)
30 | printf("\t%d", i);
31 |
32 | for (i = 1; i <= n; ++i)
33 | {
34 | printf("\n\n%d", i);
35 | for (j = 1; j <= n; ++j) // for nxn board
36 | {
37 | if (board[i] == j)
38 | printf("\tQ"); // queen at i,j position
39 | else
40 | printf("\t-"); // empty slot
41 | }
42 | }
43 | }
44 |
45 | /*funtion to check conflicts
46 | If no conflict for desired postion returns 1 otherwise returns 0*/
47 | int place(int row, int column)
48 | {
49 | int i;
50 | for (i = 1; i <= row - 1; ++i)
51 | {
52 | // checking column and digonal conflicts
53 | if (board[i] == column)
54 | return 0;
55 | else if (abs(board[i] - column) == abs(i - row))
56 | return 0;
57 | }
58 |
59 | return 1; // no conflicts
60 | }
61 |
62 | // function to check for proper positioning of queen
63 | void queen(int row, int n)
64 | {
65 | int column;
66 | for (column = 1; column <= n; ++column)
67 | {
68 | if (place(row, column))
69 | {
70 | board[row] = column; // no conflicts so place queen
71 | if (row == n) // dead end
72 | print(n); // printing the board configuration
73 | else // try queen with next position
74 | queen(row + 1, n);
75 | }
76 | }
77 | }
--------------------------------------------------------------------------------
/Algorithms/BackTracking/NQueens Problem/main.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | using namespace std;
3 |
4 | bool isSafe(int row, int col, vector &board, int n) {
5 | int dupRow = row;
6 | int dupCol = col;
7 |
8 | // Check upper diagonal
9 | while (row >= 0 && col >= 0) {
10 | if (board[row][col] == 'Q') return false;
11 | row--;
12 | col--;
13 | }
14 |
15 | // Check left
16 | col = dupCol;
17 | row = dupRow;
18 | while (col >= 0) {
19 | if (board[row][col] == 'Q') return false;
20 | col--;
21 | }
22 |
23 | // Check lower diagonal
24 | row = dupRow;
25 | col = dupCol;
26 | while (row < n && col >= 0) {
27 | if (board[row][col] == 'Q') return false;
28 | row++;
29 | col--;
30 | }
31 |
32 | return true;
33 | }
34 |
35 | void solve(int col, vector &board, vector> &ans, int n) {
36 | if (col == n) {
37 | ans.push_back(board);
38 | return;
39 | }
40 |
41 | for (int row = 0; row < n; row++) {
42 | if (isSafe(row, col, board, n)) {
43 | board[row][col] = 'Q';
44 | solve(col + 1, board, ans, n);
45 | board[row][col] = '.';
46 | }
47 | }
48 | }
49 |
50 | vector> solveNQueens(int n) {
51 | vector> ans;
52 | vector board(n, string(n, '.'));
53 |
54 | solve(0, board, ans, n);
55 | return ans;
56 | }
57 |
58 | int main() {
59 | int n = 4;
60 | vector> ans = solveNQueens(n);
61 |
62 | for (auto &solution : ans) {
63 | for (auto &row : solution) {
64 | cout << row << endl;
65 | }
66 | cout << endl;
67 | }
68 |
69 | return 0;
70 | }
71 |
--------------------------------------------------------------------------------
/Algorithms/BackTracking/NQueens Problem/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/BackTracking/NQueens Problem/main.exe
--------------------------------------------------------------------------------
/Algorithms/BackTracking/Sum Of Subset/main.c:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | void printSubset(int subSet[], int subsetSize){
4 | int i;
5 | printf("Subset: { ");
6 | for (int i = 0; i < subsetSize; i++) {
7 | printf("%d ", subSet[i]);
8 | }
9 | printf("}\n");
10 | }
11 |
12 | void sumOfSubsetUtil(int w[], int targetSum, int n, int subset[], int subsetSize,int sum, int index){
13 |
14 | // Base condition
15 | if(sum == targetSum){
16 | printSubset(subset, subsetSize);
17 | return;
18 | }
19 | int i;
20 | for(i = index; i < n; i++){
21 | if(w[i] + sum <= targetSum){
22 | subset[subsetSize] = w[i];
23 | sumOfSubsetUtil(w, targetSum, n, subset, subsetSize+1, sum + w[i] , i + 1);
24 | }
25 | }
26 |
27 | }
28 |
29 | void sumOfSubset(int w[], int targetSum, int n){
30 | int subset[n];
31 | sumOfSubsetUtil(w, targetSum, n, subset,0, 0, 0);
32 | }
33 |
34 | int main(){
35 | int n, i;
36 | printf("Enter the number of elements: ");
37 | scanf("%d", &n);
38 |
39 | int weights[n];
40 | printf("Enter the elements: ");
41 | for(i = 0; i < n; i++){
42 | scanf("%d", &weights[i]);
43 | }
44 |
45 | int targetSum;
46 | printf("Enter the target sum: ");
47 | scanf("%d", &targetSum);
48 |
49 | sumOfSubset(weights, targetSum, n);
50 | }
--------------------------------------------------------------------------------
/Algorithms/BackTracking/Sum Of Subset/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/BackTracking/Sum Of Subset/main.exe
--------------------------------------------------------------------------------
/Algorithms/Divide and Conquer/Insertion Sort/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | #define SIZE 30000
6 |
7 | void printArray(int *A, int n){
8 | int i;
9 | for(i = 0; i < n; i++){
10 | printf("%d ", A[i]);
11 | }
12 | printf("\n");
13 | }
14 |
15 | void InsertionSort(int A[], int n){
16 | int i, j, x;
17 |
18 | for(i = 1; i < n; i++){
19 | j = i-1;
20 | x = A[i];
21 |
22 | while(j > -1 && A[j] > x){
23 | // Swap
24 | A[j+1] = A[j];
25 | j--;
26 | }
27 |
28 | A[j+1] = x;
29 | }
30 | }
31 |
32 | void reverse(int *A, int n){
33 | int temp[SIZE];
34 |
35 | for(int i = 0; i < n; i++){
36 | temp[i] = A[n - i -1];
37 | }
38 |
39 | for(int i = 0; i < n; i++){
40 | A[i] = temp[i];
41 | }
42 | }
43 |
44 | int main(){
45 | int A[SIZE];
46 | int n = sizeof(A)/ sizeof(A[0]);
47 | clock_t t1, t2, t3, t4, t5, t6;
48 | double total_t;
49 |
50 |
51 | for(int i = 0; i < SIZE; i++){
52 | A[i] = rand() % 100;
53 | }
54 |
55 | t1 = clock();
56 | InsertionSort(A, n);
57 | // printArray(A, n);
58 | t2 = clock();
59 |
60 | total_t = (double) (t2 - t1) / CLOCKS_PER_SEC;
61 | printf("\nTime Take to sort Random array: %.2f", total_t);
62 |
63 | t3 = clock();
64 | InsertionSort(A, n);
65 | // printArray(A, n);
66 | t4 = clock();
67 |
68 | total_t = (double) (t4 - t3) / CLOCKS_PER_SEC;
69 | printf("\nTime Take to sort Sorted array: %.2f", total_t);
70 |
71 | reverse(A, n);
72 | t5 = clock();
73 | InsertionSort(A, n);
74 | // printArray(A, n);
75 | t6 = clock();
76 |
77 | total_t = (double) (t6 - t5) / CLOCKS_PER_SEC;
78 | printf("\nTime Take to sort Reverse array: %.2f", total_t);
79 |
80 | return 0;
81 | }
--------------------------------------------------------------------------------
/Algorithms/Divide and Conquer/Insertion Sort/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Divide and Conquer/Insertion Sort/main.exe
--------------------------------------------------------------------------------
/Algorithms/Divide and Conquer/Merge Sort/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Divide and Conquer/Merge Sort/main.exe
--------------------------------------------------------------------------------
/Algorithms/Divide and Conquer/MinMax Algo/MinMax.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Divide and Conquer/MinMax Algo/MinMax.png
--------------------------------------------------------------------------------
/Algorithms/Divide and Conquer/MinMax Algo/main.c:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | int min, max; // for left tree
4 |
5 | void MinMax(int A[], int low , int high){
6 | int min1, max1; // for right tree
7 |
8 | // Case 1: For 1 element
9 | if(low == high){
10 | min = max =A[low];
11 | }
12 | // Case 2: For 2 elements
13 | else if(low == high-1){
14 | if(A[low] < A[high]){
15 | min = A[low];
16 | max = A[high];
17 | }else{
18 | min = A[high];
19 | max = A[low];
20 | }
21 | }else{
22 | // Divide
23 | int mid = (low + high)/2;
24 |
25 | MinMax(A, low, mid); // for left tree
26 | min1 = min;
27 | max1 = max;
28 |
29 | MinMax(A, mid+1, high);// for right tree
30 |
31 | // Compare left sub tree with right sub tree
32 | if(max1 > max){
33 | max = max1;
34 | }
35 | if(min1 < min){
36 | min = min1;
37 | }
38 |
39 | }
40 | }
41 |
42 |
43 | int main(){
44 | int n = 9;
45 | int A[n];
46 |
47 | for(int i = 0 ;i < n ; i++){
48 | printf("Enter the Array elements: ");
49 | scanf("%d", &A[i]);
50 | }
51 |
52 | MinMax(A, 0, n-1);
53 |
54 | printf("\nMax value: %d \nMin value: %d",max,min);
55 | return 0;
56 | }
--------------------------------------------------------------------------------
/Algorithms/Divide and Conquer/MinMax Algo/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Divide and Conquer/MinMax Algo/main.exe
--------------------------------------------------------------------------------
/Algorithms/Divide and Conquer/Quick Sort/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Divide and Conquer/Quick Sort/main.exe
--------------------------------------------------------------------------------
/Algorithms/Divide and Conquer/Randomized Quick Sort/main.c:
--------------------------------------------------------------------------------
1 | /*
2 | * C Program to Implement Quick Sort Using Randomization
3 | */
4 | #include
5 | #include
6 | #define MAX 100
7 | void random_shuffle(int arr[])
8 | {
9 | srand(time(NULL));
10 | int i, j, temp;
11 | for (i = MAX - 1; i > 0; i--)
12 | {
13 | j = rand()%(i + 1);
14 | temp = arr[i];
15 | arr[i] = arr[j];
16 | arr[j] = temp;
17 | }
18 | }
19 |
20 | void swap(int *a, int *b)
21 | {
22 | int temp;
23 | temp = *a;
24 | *a = *b;
25 | *b = temp;
26 | }
27 | int partion(int arr[], int p, int r)
28 | {
29 | int pivotIndex = p + rand()%(r - p + 1); //generates a random number as a pivot
30 | int pivot;
31 | int i = p - 1;
32 | int j;
33 | pivot = arr[pivotIndex];
34 | swap(&arr[pivotIndex], &arr[r]);
35 | for (j = p; j < r; j++)
36 | {
37 | if (arr[j] < pivot)
38 | {
39 | i++;
40 | swap(&arr[i], &arr[j]);
41 | }
42 |
43 | }
44 | swap(&arr[i+1], &arr[r]);
45 | return i + 1;
46 | }
47 |
48 | void quick_sort(int arr[], int p, int q)
49 | {
50 | int j;
51 | if (p < q)
52 | {
53 | j = partion(arr, p, q);
54 | quick_sort(arr, p, j-1);
55 | quick_sort(arr, j+1, q);
56 | }
57 | }
58 | int main()
59 | {
60 | int i;
61 | int arr[MAX];
62 | for (i = 0; i < MAX; i++)
63 | arr[i] = i;
64 | random_shuffle(arr); //To randomize the array
65 | quick_sort(arr, 0, MAX-1); //function to sort the elements of array
66 | for (i = 0; i < MAX; i++)
67 | printf("%d \n", arr[i]);
68 | return 0;
69 | }
--------------------------------------------------------------------------------
/Algorithms/Divide and Conquer/Strassen's Matrix Multiplication/main.c:
--------------------------------------------------------------------------------
1 | /*
2 | C code of two 2 by 2 matrix multiplication using Strassen's algorithm
3 | */
4 | #include
5 | int main()
6 | {
7 | int a[2][2], b[2][2], c[2][2], i, j;
8 | int m1, m2, m3, m4, m5, m6, m7;
9 |
10 | printf("Enter the 4 elements of first matrix: ");
11 | for (i = 0; i < 2; i++)
12 | for (j = 0; j < 2; j++)
13 | scanf("%d", &a[i][j]);
14 |
15 | printf("Enter the 4 elements of second matrix: ");
16 | for (i = 0; i < 2; i++)
17 | for (j = 0; j < 2; j++)
18 | scanf("%d", &b[i][j]);
19 |
20 | printf("\nThe first matrix is\n");
21 | for (i = 0; i < 2; i++)
22 | {
23 | printf("\n");
24 | for (j = 0; j < 2; j++)
25 | printf("%d\t", a[i][j]);
26 | }
27 |
28 | printf("\nThe second matrix is\n");
29 | for (i = 0; i < 2; i++)
30 | {
31 | printf("\n");
32 | for (j = 0; j < 2; j++)
33 | printf("%d\t", b[i][j]);
34 | }
35 |
36 | m1 = (a[0][0] + a[1][1]) * (b[0][0] + b[1][1]);
37 | m2 = (a[1][0] + a[1][1]) * b[0][0];
38 | m3 = a[0][0] * (b[0][1] - b[1][1]);
39 | m4 = a[1][1] * (b[1][0] - b[0][0]);
40 | m5 = (a[0][0] + a[0][1]) * b[1][1];
41 | m6 = (a[1][0] - a[0][0]) * (b[0][0] + b[0][1]);
42 | m7 = (a[0][1] - a[1][1]) * (b[1][0] + b[1][1]);
43 |
44 | c[0][0] = m1 + m4 - m5 + m7;
45 | c[0][1] = m3 + m5;
46 | c[1][0] = m2 + m4;
47 | c[1][1] = m1 - m2 + m3 + m6;
48 |
49 | printf("\nAfter multiplication using Strassen's algorithm \n");
50 | for (i = 0; i < 2; i++)
51 | {
52 | printf("\n");
53 | for (j = 0; j < 2; j++)
54 | printf("%d\t", c[i][j]);
55 | }
56 |
57 | return 0;
58 | }
--------------------------------------------------------------------------------
/Algorithms/Divide and Conquer/Strassen's Matrix Multiplication/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Divide and Conquer/Strassen's Matrix Multiplication/main.exe
--------------------------------------------------------------------------------
/Algorithms/Dynamic Programming/Bellman Ford/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | #define I INT_MAX // Infinity
6 | #define N 5 // Number of vertices + 1 (0 index not used)
7 |
8 | // Cost matrix (1-based indexing)
9 | int cost[N][N] = {
10 | {I, I, I, I, I}, // 0 (not used)
11 | {I, 0, 4, I, 5}, // 1
12 | {I, I, 0, I, 5}, // 2
13 | {I, I, -10, 0, I}, // 3
14 | {I, I, I, 3, 0} // 4
15 | };
16 |
17 | int d[N], parent[N];
18 |
19 | bool BellmanFord(int src, int n) {
20 | for (int i = 1; i <= n; i++) {
21 | d[i] = I;
22 | parent[i] = -1;
23 | }
24 | d[src] = 0;
25 |
26 | // Relax all edges (n-1) times
27 | for (int i = 1; i <= n - 1; i++) {
28 | for (int u = 1; u <= n; u++) {
29 | for (int v = 1; v <= n; v++) {
30 | if (cost[u][v] != I && d[u] != I && d[u] + cost[u][v] < d[v]) {
31 | d[v] = d[u] + cost[u][v];
32 | parent[v] = u;
33 | }
34 | }
35 | }
36 | }
37 |
38 | // Check for negative-weight cycles
39 | for (int u = 1; u <= n; u++) {
40 | for (int v = 1; v <= n; v++) {
41 | if (cost[u][v] != I && d[u] != I && d[u] + cost[u][v] < d[v]) {
42 | return false; // Negative cycle detected
43 | }
44 | }
45 | }
46 |
47 | return true;
48 | }
49 |
50 | void printShortestPaths(int n) {
51 | printf("Vertex\tDistance\tParent\n");
52 | for (int i = 1; i <= n; i++) {
53 | printf("%d\t%d\t\t%d\n", i, d[i], parent[i]);
54 | }
55 | }
56 |
57 | int main() {
58 |
59 |
60 | if (BellmanFord(1, N-1)) {
61 | printf("\nShortest Paths from Vertex 1 using Bellman-Ford Algorithm:\n");
62 | printShortestPaths(N-1);
63 | } else {
64 | printf("Negative-weight cycle detected!");
65 | }
66 |
67 | return 0;
68 | }
69 |
--------------------------------------------------------------------------------
/Algorithms/Dynamic Programming/Bellman Ford/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Dynamic Programming/Bellman Ford/main.exe
--------------------------------------------------------------------------------
/Algorithms/Dynamic Programming/Coin Change/Memoization/main.c:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | int minCoins(int amount , int A[] , int n,int dp[]){
4 | if(amount == 0){
5 | return 0;
6 | }
7 |
8 | if(dp[amount] != -1){
9 | return dp[amount];
10 | }
11 |
12 | int ans = 1000000;
13 | for(int i = 0; i < n; i ++){
14 | if(amount-A[i] >= 0){
15 | int subAns = minCoins(amount-A[i] , A , n, dp);
16 |
17 | if(subAns + 1 < ans){
18 | ans = subAns + 1;
19 | }
20 | }
21 | }
22 | return dp[amount] = ans;
23 | }
24 |
25 | int main() {
26 | int A[] = { 7 , 5 , 1};
27 | int n = sizeof(A) / sizeof(A[0]);
28 | int amount = 18;
29 | int dp[amount +1];
30 |
31 | // Initialize dp as -1
32 | for(int i = 0 ; i <=amount ;i++ ){
33 | dp[i] = -1;
34 | }
35 | dp[0] = 0; // For Amount 0 , 0 coins will be needed
36 | printf("%d\n" , minCoins(amount, A, n, dp));
37 |
38 | for(int i = 0 ; i <= amount; i++){
39 | printf("%d ",dp[i]);
40 | }
41 | return 0;
42 | }
--------------------------------------------------------------------------------
/Algorithms/Dynamic Programming/Coin Change/Memoization/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Dynamic Programming/Coin Change/Memoization/main.exe
--------------------------------------------------------------------------------
/Algorithms/Dynamic Programming/Coin Change/Memoization/tempCodeRunnerFile.c:
--------------------------------------------------------------------------------
1 | minCoins
--------------------------------------------------------------------------------
/Algorithms/Dynamic Programming/Coin Change/Recursion/main.c:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | int minCoins(int amount , int A[] , int n){
4 | if(amount == 0){
5 | return 0;
6 | }
7 | int ans = 1000000;
8 | for(int i = 0; i < n; i ++){
9 | if(amount-A[i] >= 0){
10 | int subAns = minCoins(amount-A[i] , A , n);
11 | if(subAns + 1 < ans){
12 | ans = subAns + 1;
13 | }
14 | }
15 | }
16 | return ans;
17 | }
18 |
19 | int main() {
20 | int A[] = { 7 , 5 , 1};
21 | int amount = 18;
22 |
23 | printf("%d" , minCoins(amount, A, 3));
24 |
25 | return 0;
26 | }
--------------------------------------------------------------------------------
/Algorithms/Dynamic Programming/Coin Change/Tabulation/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #define I 1000000
3 |
4 | int minCoins( int coins[], int n, int w){
5 | int dp[w+1];
6 |
7 | // Initialize DP as Infinity
8 | for(int i = 0 ;i <= w ; i++){
9 | dp[i] = I;
10 | }
11 |
12 | dp[0] = 0; // Base case: 0 Coins required for amount 0
13 |
14 | // Fill table using given coins
15 | for(int i = 0; i < n ; i++){ // For each coins
16 | for(int j = coins[i] ; j <= w; j++){ // For each amount from coin to w
17 | if(dp[j - coins[i]] != I){ // If amount is possible
18 | // Select the min coins
19 | int sum = 1 + dp[j- coins[i]];
20 | dp[j] = (dp[j] < sum) ? dp[j] : sum;
21 | }
22 | }
23 | }
24 |
25 | return (dp[w] == I)? -1 : dp[w]; // If dp is I, return -1 (not possible)
26 | }
27 |
28 | int main(){
29 | // int coins[] = {1, 5, 6, 9};
30 | // int coins[] = {7, 5, 1};
31 | int coins[] = {1};
32 | int n = sizeof(coins) / sizeof(coins[0]);
33 | int w = 0;
34 |
35 | int ans = minCoins(coins, n, w);
36 | if(ans == -1){
37 | printf("No possible way to form amount.\n");
38 | }else{
39 | printf("Minimum coins required: %d\n", ans);
40 | }
41 |
42 | return 0;
43 | }
--------------------------------------------------------------------------------
/Algorithms/Dynamic Programming/Coin Change/Tabulation/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Dynamic Programming/Coin Change/Tabulation/main.exe
--------------------------------------------------------------------------------
/Algorithms/Dynamic Programming/Coin Change/Tabulation/tempCodeRunnerFile.c:
--------------------------------------------------------------------------------
1 | for(int i = 0 ;i < n ;i++){
2 | for(int j = 0 ; j <= w; j++){
3 | printf("%d ", dp[i][j]);
4 | }
5 | printf("\n");
6 | }
7 |
--------------------------------------------------------------------------------
/Algorithms/Dynamic Programming/Fibonacci Problem/main.c:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | int fibonacci(int n){
4 | if(n <= 1){ // base case
5 | return n;
6 | }
7 |
8 | int F[n+1];
9 |
10 | F[0] = 0; F[1] = 1;
11 |
12 | for(int i = 2; i <= n; i++){
13 | F[i] = F[i-2] + F[i-1];
14 | }
15 |
16 | return F[n];
17 | }
18 |
19 | int main(){
20 | int n;
21 | printf("Enter the no to find Fibonacci: ");
22 | scanf("%d", &n);
23 |
24 | int fibNo = fibonacci(n);
25 |
26 | printf("\n%d" , fibNo);
27 |
28 | return 0;
29 | }
--------------------------------------------------------------------------------
/Algorithms/Dynamic Programming/Floyd Warshall/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | #define I INT_MAX
5 |
6 | int main(){
7 | int n = 5;
8 | int A[5][5] = {
9 | {0, 3, 8, I, -4},
10 | {I, 0, I, 1, 7},
11 | {I, 4, 0, I, I},
12 | {2, I, -5, 0, I},
13 | {I, I, I, 6, 0},
14 | };
15 |
16 | int P[5][5];
17 | int i, j, k;
18 |
19 | // Initialize parent matrix
20 | for(i = 0; i < n; i++){
21 | for(j = 0; j < n; j++){
22 | if(i == j || A[i][j] == I)
23 | P[i][j] = -1;
24 | else
25 | P[i][j] = i; // Path from i to j goes through i initially
26 | }
27 | }
28 |
29 | // Floyd-Warshall Algorithm
30 | for(k = 0; k < n; k++){
31 | for(i = 0; i < n; i++){
32 | for(j = 0; j < n; j++){
33 | if(A[i][k] != I && A[k][j] != I && A[i][k] + A[k][j] < A[i][j]){
34 | A[i][j] = A[i][k] + A[k][j];
35 | P[i][j] = k;
36 | }
37 | }
38 | }
39 | }
40 |
41 | // Print Distance Matrix
42 | printf("Final distance matrix:\n");
43 | for(i = 0; i < n; i++){
44 | for(j = 0; j < n; j++){
45 | if(A[i][j] == I)
46 | printf(" INF ");
47 | else
48 | printf(" %4d", A[i][j]);
49 | }
50 | printf("\n");
51 | }
52 |
53 | // Print Parent Matrix
54 | printf("\nFinal parent table:\n");
55 | for(i = 0; i < n; i++){
56 | for(j = 0; j < n; j++){
57 | if(P[i][j] == -1)
58 | printf(" - ");
59 | else
60 | printf(" %3d ", P[i][j] + 1); // optional: +1 for 1-based display
61 | }
62 | printf("\n");
63 | }
64 |
65 | return 0;
66 | }
67 |
--------------------------------------------------------------------------------
/Algorithms/Dynamic Programming/Floyd Warshall/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Dynamic Programming/Floyd Warshall/main.exe
--------------------------------------------------------------------------------
/Algorithms/Dynamic Programming/Johnson's Algo/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | int min(int a, int b);
5 | int cost[10][10], a[10][10], i, j, k, c;
6 |
7 | int main(int argc, char **argv) {
8 | int n, m;
9 | printf("Enter no of vertices: \n");
10 | scanf("%d", &n);
11 | printf("\nEnter no od edges: \n");
12 | scanf("%d", &m);
13 | printf("\nEnter the\nEDGE Cost\n");
14 | for (k = 1; k <= m; k++) {
15 | scanf("%d", &i);
16 | scanf("%d", &j);
17 | scanf("%d", &c);
18 | a[i][j] = cost[i][j] = c;
19 | }
20 | for (i = 1; i <= n; i++)
21 | for (j = 1; j <= n; j++) {
22 | if (a[i][j] == 0 && i != j)
23 | a[i][j] = 31999;
24 | }
25 | for (k = 1; k <= n; k++)
26 | for (i = 1; i <= n; i++)
27 | for (j = 1; j <= n; j++)
28 | a[i][j] = min(a[i][j], a[i][k] + a[k][j]);
29 | printf("Resultant adjacency matrix\n");
30 | for (i = 1; i <= n; i++) {
31 | for (j = 1; j <= n; j++) {
32 | if (a[i][j] != 31999)
33 | printf("%d ", a[i][j]);
34 | }
35 | printf("\n");
36 | }
37 | return 0;
38 | }
39 | int min(int a, int b) {
40 | if (a < b)
41 | return a;
42 | else
43 | return b;
44 | }
--------------------------------------------------------------------------------
/Algorithms/Dynamic Programming/Knapsack/0/1 Knapsack/Memoization/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #define MAX_ITEMS 102
3 | #define MAX_WEIGHT 1002
4 | // constraints
5 | /**
6 | * n <= 100
7 | * W <= 1000
8 | */
9 |
10 |
11 | // static Dp
12 | int dp[MAX_ITEMS][MAX_WEIGHT];
13 |
14 |
15 | // Initialize DP as -1
16 | void init_dp() {
17 | for (int i = 0; i < MAX_ITEMS; i++) {
18 | for (int j = 0; j < MAX_WEIGHT; j++) {
19 | dp[i][j] = -1;
20 | }
21 | }
22 | }
23 |
24 |
25 | int max(int a , int b){
26 | return (a > b )? a : b;
27 | }
28 |
29 |
30 |
31 | int knapsack(int wt[], int val[], int W, int n){
32 | // base conditioni
33 | if(n == 0 || W == 0){
34 | return 0;
35 | }
36 |
37 | // Dp present or not ?
38 | if(dp[n][W] != -1){
39 | return dp[n][W];
40 | }
41 |
42 | // choice diagram
43 | if(wt[n-1] <= W){
44 | // include
45 | int a = val[n-1] + knapsack(wt, val, W-wt[n-1], n-1);
46 | // exclude
47 | int b = knapsack(wt, val, W, n-1);
48 |
49 | dp[n][W] = max(a, b);
50 |
51 | return dp[n][W];
52 | }
53 |
54 | if(wt[n-1] > W){
55 | dp[n][W] = knapsack(wt, val, W, n-1);
56 |
57 | return dp[n][W];
58 | }
59 | }
60 |
61 |
62 | int main(){
63 |
64 | int wt[] = {1, 3, 4, 5};
65 | int val[] = {1, 4, 5, 7};
66 | int W = 7;
67 |
68 | int n = sizeof(wt) / sizeof(wt[0]);
69 |
70 |
71 | init_dp();
72 | printf("Max Profit: %d", knapsack(wt, val, W, n));
73 | return 0;
74 | }
--------------------------------------------------------------------------------
/Algorithms/Dynamic Programming/Knapsack/0/1 Knapsack/Recursion/main.c:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | int max(int a, int b){
4 | return (a > b) ? a : b;
5 | }
6 |
7 |
8 | // Knapsack
9 | int Knapsack(int wt[], int val[], int W, int n){
10 | // base condition
11 | if(n == 0 || W == 0){
12 | return 0;
13 | }
14 |
15 | // choice diagram
16 | if(wt[n-1] <= W){
17 | int a = val[n-1] + Knapsack(wt, val, W-wt[n-1], n-1);
18 | int b = Knapsack(wt, val, W, n-1);
19 | return max(a, b);
20 | }
21 |
22 | else if(wt[n-1] > W){
23 | return Knapsack(wt, val, W, n-1);
24 | }
25 | }
26 |
27 | int main()
28 | {
29 | int wt[] = {1, 3, 4, 5};
30 | int val[] = {1, 4, 5, 7};
31 | int W = 7;
32 |
33 | int n = sizeof(wt) / sizeof(wt[0]);
34 |
35 | printf("Max Profit: %d", Knapsack(wt, val, W, n));
36 |
37 | return 0;
38 | }
--------------------------------------------------------------------------------
/Algorithms/Dynamic Programming/LCS/Memoization/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | #define MAX_LENGTH 1001
5 |
6 | /**
7 | * n <= 1001
8 | * m <= 1001
9 | */
10 |
11 | int dp[MAX_LENGTH][MAX_LENGTH];
12 |
13 |
14 | int max(int a,int b){
15 | return (a > b) ? a : b;
16 | }
17 |
18 | int LCS(char x[], char y[], int n , int m){
19 | // Base condition
20 | if(n == 0 || m == 0){
21 | return 0;
22 | }
23 |
24 | // present or not
25 | if(dp[n][m] != -1){
26 | return dp[n][m];
27 | }
28 |
29 | // Choice diagram
30 | if(x[n-1] == y[m-1]){
31 | dp[n][m] = 1 + LCS(x, y, n-1, m-1);
32 |
33 | return dp[n][m];
34 | }else {
35 | // choices
36 | int a = LCS(x, y, n, m-1);
37 | int b = LCS(x, y, n-1, m);
38 | return dp[n][m] = max(a, b);
39 | }
40 | }
41 |
42 | void PrintLCS(char x[], char y[], int n, int m){
43 | char lcs[MAX_LENGTH];
44 | int index = dp[n][m];
45 |
46 | lcs[index] = '\0';
47 |
48 | int i = n, j = m;
49 |
50 | while(i > 0 && j > 0){
51 |
52 | // char match
53 | if(x[i-1] == y[j-1]){
54 | lcs[index - 1] = x[i-1];
55 | i--;
56 | j--;
57 | index--;
58 | }
59 | // Comapre diagonal elements of dp
60 | else if(dp[i-1][j] > dp[i][j-1]){
61 | i--;
62 | }else{
63 | j--;
64 | }
65 | }
66 |
67 | printf("\nLCS String: %s", lcs);
68 | }
69 |
70 | int main()
71 | {
72 | char x[] = "abcdgh";
73 | char y[] = "abedfha";
74 |
75 | int n = strlen(x);
76 | int m = strlen(y);
77 |
78 | // Initialize dp as -1
79 | memset(dp, -1, sizeof(dp));
80 |
81 | printf("LCS Length: %d", LCS(x, y, n, m));
82 |
83 | PrintLCS(x, y, n, m);
84 |
85 | return 0;
86 | }
--------------------------------------------------------------------------------
/Algorithms/Dynamic Programming/LCS/Memoization/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Dynamic Programming/LCS/Memoization/main.exe
--------------------------------------------------------------------------------
/Algorithms/Dynamic Programming/LCS/Recursive/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | int max(int a,int b){
5 | return (a > b) ? a : b;
6 | }
7 |
8 | int LCS(char x[], char y[], int n , int m){
9 | // Base condition
10 | if(n == 0 || m == 0){
11 | return 0;
12 | }
13 |
14 | // Choice diagram
15 | if(x[n-1] == y[m-1]){
16 | return 1 + LCS(x, y, n-1, m-1);
17 | }else {
18 | // choices
19 | int a = LCS(x, y, n, m-1);
20 | int b = LCS(x, y, n-1, m);
21 | return max(a, b);
22 | }
23 | }
24 |
25 | int main()
26 | {
27 | char x[] = "abcdgh";
28 | char y[] = "abedfha";
29 |
30 | int n = strlen(x);
31 | int m = strlen(y);
32 |
33 | printf("LCS Length: %d", LCS(x, y, n, m));
34 |
35 | return 0;
36 | }
--------------------------------------------------------------------------------
/Algorithms/Dynamic Programming/LCS/main.c:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | void PrintLCS(char A[] , char B[], int m, int n){
4 | int LCS[m+1][n+1];
5 | int i,j;
6 |
7 | // Initialize 0th row and column as Zero
8 | for (i = 0; i <= m; i++) {
9 | for (j = 0; j <= n; j++) {
10 | if (i == 0 || j == 0) {
11 | LCS[i][j] = 0;
12 | }
13 | }
14 | }
15 |
16 | for(i = 1 ; i <= m; i++){
17 | for(j = 1; j <= n; j++){
18 | if(A[i-1] == B[j-1]){
19 | // Plus one with Previous Diagonal Element
20 | LCS[i][j] = 1 + LCS[i-1][j-1];
21 | }else {
22 | // Take the max of previous row and column
23 | LCS[i][j] = (LCS[i-1][j] > LCS[i][j-1]) ? LCS[i-1][j] : LCS[i][j-1];
24 | }
25 | }
26 | }
27 |
28 | // Print the LCS array
29 | for (i = 0; i <=m; i++) {
30 | for (j = 0; j <=n; j++) {
31 | printf("%d ", LCS[i][j]);
32 | }
33 | printf("\n");
34 | }
35 |
36 | // Print LCS length
37 | printf("\nLength of LCS: %d\n", LCS[m][n]);
38 |
39 | // Backtrack to find the LCS string
40 | int lcsLength = LCS[m][n];
41 | char lcsStr[lcsLength + 1]; // +1 for null terminator
42 | lcsStr[lcsLength] = '\0';
43 |
44 | i = m, j = n;
45 | while(i > 0 && j > 0){
46 | if(A[i-1] == B[j-1]){ // If characters match, it's part of LCS
47 | lcsStr[--lcsLength] = A[i-1];
48 | i--;
49 | j--;
50 | }else if(LCS[i-1][j] > LCS[i][j-1]){
51 | i--; // Move up
52 | }else{
53 | j--; // Move left
54 | }
55 | }
56 |
57 | printf("LCS: %s" , lcsStr);
58 | }
59 | int main()
60 | {
61 | char A[] = "bd";
62 | char B[] = "abcd";
63 |
64 | int m = sizeof(A)/ sizeof(A[0]) - 1; // Subtract 1 to remove null terminator
65 | int n = sizeof(B)/ sizeof(B[0]) - 1; // Subtract 1 to remove null terminator
66 | printf("%d %d\n\n" , m, n);
67 |
68 | PrintLCS(A, B, m, n);
69 | return 0;
70 | }
--------------------------------------------------------------------------------
/Algorithms/Dynamic Programming/LCS/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Dynamic Programming/LCS/main.exe
--------------------------------------------------------------------------------
/Algorithms/Dynamic Programming/MCM/Memoization/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | /**
6 | * n <= 1000
7 | */
8 | int dp[1001][1001];
9 | int bracket[1001][1001]; // to store split point
10 |
11 | int solve(int arr[], int i, int j){
12 | // Base condition
13 | if(i >= j){
14 | return 0;
15 | }
16 |
17 | // Presnet or not
18 | if(dp[i][j] != -1){
19 | return dp[i][j];
20 | }
21 |
22 | int min = INT_MAX;
23 | // k loop
24 | for(int k = i; k <= j-1; k++){
25 | // temp ans
26 | int tempAns = solve(arr, i, k) + solve(arr, k+1, j) + arr[i-1] * arr[k] * arr[j];
27 |
28 | // Idenitfy min cost from temp ans
29 | if(tempAns < min){
30 | min = tempAns;
31 | bracket[i][j]= k;
32 | }
33 | }
34 |
35 | return dp[i][j] = min;
36 | }
37 |
38 | void printParenthesis(int i, int j, char *name){
39 | // base condition
40 | if(i == j){
41 | printf("%c", (*name)++);
42 | return;
43 | }
44 | printf("(");
45 | printParenthesis(i, bracket[i][j], name);
46 | printParenthesis(bracket[i][j] + 1, j, name);
47 | printf(")");
48 | }
49 |
50 | int main()
51 | {
52 | int arr[] = {40, 20, 30, 10, 30};
53 |
54 | int n = sizeof(arr) / sizeof(arr[0]);
55 |
56 | // Initialize dp as -1
57 | memset(dp, -1, sizeof(dp));
58 | printf("Min Cost: %d", solve(arr, 1, n-1));
59 |
60 | char name = 'A';
61 | printf("Optimal Parenthesization: \n");
62 | printParenthesis(1, n - 1, &name);
63 | printf("\n");
64 |
65 |
66 | return 0;
67 | }
--------------------------------------------------------------------------------
/Algorithms/Dynamic Programming/MCM/Memoization/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Dynamic Programming/MCM/Memoization/main.exe
--------------------------------------------------------------------------------
/Algorithms/Dynamic Programming/MCM/Recursive/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | int solve(int arr[], int i, int j){
5 | // Base condition
6 | if(i >= j){
7 | return 0;
8 | }
9 |
10 | int min = INT_MAX;
11 | // k loop
12 | for(int k = i; k <= j-1; k++){
13 | // temp ans
14 | int tempAns = solve(arr, i, k) + solve(arr, k+1, j) + arr[i-1] * arr[k] * arr[j];
15 |
16 | // Idenitfy min cost from temp ans
17 | if(tempAns < min){
18 | min = tempAns;
19 | }
20 | }
21 |
22 | return min;
23 | }
24 |
25 | int main()
26 | {
27 | int arr[] = {40, 20, 30, 10, 30};
28 |
29 | int n = sizeof(arr) / sizeof(arr[0]);
30 |
31 | printf("Min Cost: %d", solve(arr, 1, n-1));
32 |
33 | return 0;
34 | }
--------------------------------------------------------------------------------
/Algorithms/Dynamic Programming/Multistage Graph/Tabularization/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | // Required DS
5 | int stages = 4, min;
6 | int n = 8;
7 | int cost[9], P[9], d[9];
8 | int c[9][9] = {
9 | {0, 0, 0, 0, 0, 0, 0, 0, 0},
10 | {0, 0, 2, 1, 3, 0, 0, 0, 0},
11 | {0, 0, 0, 0, 0, 2, 3, 0, 0},
12 | {0, 0, 0, 0, 0, 6, 7, 0, 0},
13 | {0, 0, 0, 0, 0, 6, 8, 9, 0},
14 | {0, 0, 0, 0, 0, 0, 0, 0, 6},
15 | {0, 0, 0, 0, 0, 0, 0, 0, 4},
16 | {0, 0, 0, 0, 0, 0, 0, 0, 5},
17 | {0, 0, 0, 0, 0, 0, 0, 0, 0}
18 | };
19 |
20 | int main(){
21 |
22 | cost[n] = 0; // cost of end vertex
23 |
24 | // calculate cost and distance array
25 | for(int i = n-1; i>=1; i--){
26 | min = INT_MAX;
27 | for(int k = i+1; k <= n; k++){
28 | // identify min
29 | if(c[i][k] != 0 && c[i][k] + cost[k] < min){
30 | min = c[i][k] + cost[k];
31 | d[i] = k;
32 | }
33 | }
34 |
35 | cost[i] = min;
36 | }
37 |
38 | // Identify path
39 | P[1] = 1; P[stages] = n;
40 |
41 | for(int i = 2; i < stages; i++){
42 | P[i] = d[P[i-1]];
43 | }
44 |
45 | // Display path
46 | printf("Distance is : ");
47 |
48 | for(int i = 1; i <= stages; i++){
49 | printf("%d -> ", P[i]);
50 | }
51 |
52 | return 0;
53 | }
--------------------------------------------------------------------------------
/Algorithms/Dynamic Programming/Multistage Graph/images/image1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Dynamic Programming/Multistage Graph/images/image1.png
--------------------------------------------------------------------------------
/Algorithms/Dynamic Programming/Multistage Graph/images/image2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Dynamic Programming/Multistage Graph/images/image2.png
--------------------------------------------------------------------------------
/Algorithms/Dynamic Programming/TSP/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | #define INF INT_MAX
6 | #define N 4 // Number of cities
7 |
8 | int dist[N][N] = {
9 | {0, 10, 15, 20},
10 | {10, 0, 35, 25},
11 | {15, 35, 0, 30},
12 | {20, 25, 30, 0}
13 | };
14 |
15 | int dp[1 << N][N]; // dp[mask][i]
16 |
17 | int tsp(int mask, int pos) {
18 | if (mask == (1 << N) - 1) {
19 | return dist[pos][0]; // Return to the starting city
20 | }
21 |
22 | if (dp[mask][pos] != -1) {
23 | return dp[mask][pos];
24 | }
25 |
26 | int ans = INF;
27 | for (int city = 0; city < N; city++) {
28 | if (!(mask & (1 << city))) {
29 | // city not yet visited
30 | int newAns = dist[pos][city] + tsp(mask | (1 << city), city);
31 | ans = (newAns < ans) ? newAns : ans;
32 | }
33 | }
34 | return dp[mask][pos] = ans;
35 | }
36 |
37 | int main() {
38 | memset(dp, -1, sizeof(dp));
39 | printf("The minimum cost is %d\n", tsp(1, 0));
40 | return 0;
41 | }
--------------------------------------------------------------------------------
/Algorithms/Dynamic Programming/TSP/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Dynamic Programming/TSP/main.exe
--------------------------------------------------------------------------------
/Algorithms/Greedy/Dijkstra's Algorithm/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #define I INT_MAX
4 |
5 | // Initialization
6 | int cost[7][7] = {
7 | {I, I, I, I, I, I, I}, // 0
8 | {I, I, 2, 4, I, I, I}, // 1
9 | {I, I, I, 1, 7, I, I}, // 2
10 | {I, I, I, I, I, 3, I}, // 3
11 | {I, I, I, I, I, I, 1}, // 4
12 | {I, I, I, I, 2, I, 5}, // 5
13 | {I, I, I, I, I, I, I} // 6
14 | };
15 |
16 | // Distance array for Dijkstra's Algorithm
17 | int d[9] = {I};
18 | int parent[9] = {-1};
19 | int visited[9] = {0};
20 |
21 | // Dijkstra's Algorithm for Shortest Path
22 | void Dijkstra(int src, int n)
23 | {
24 | int min, u, i, j;
25 | // Initialize distances to infinity
26 | for (i = 1; i <= n; i++)
27 | {
28 | d[i] = I;
29 | visited[i] = 0;
30 | }
31 | // Distance to source is 0
32 | d[src] = 0;
33 | for (i = 1; i <= n; i++)
34 | {
35 | // Find the vertex with minimum distance which is not yet visited
36 | min = I;
37 | u = -1;
38 | for (j = 1; j <= n; j++)
39 | {
40 | if (!visited[j] && d[j] < min)
41 | {
42 | min = d[j];
43 | u = j;
44 | }
45 | }
46 | if (u == -1)
47 | break; // All vertices are visited or unreachable
48 | visited[u] = 1;
49 | // Relaxation step
50 | for (j = 1; j <= n; j++)
51 | {
52 | if (!visited[j] && cost[u][j] != I && d[u] + cost[u][j] < d[j])
53 | {
54 | d[j] = d[u] + cost[u][j];
55 | parent[j] = u;
56 | }
57 | }
58 | }
59 | }
60 | int main()
61 | {
62 | int i, j, u, v, k, min = I, n = 6, sum = 0;
63 |
64 | // Dijkstra's Algorithm to find shortest path from vertex 1
65 | Dijkstra(1, n);
66 | // Output Dijkstra's result
67 | printf("\nShortest Paths from Vertex 1 using Dijkstra's Algorithm:\n");
68 | printf("Vertices Distance Parent\n");
69 | for (i = 1; i <= n; i++)
70 | {
71 | if (i != 1)
72 | {
73 | printf("%d\t %d\t %d\n", i, d[i], parent[i]);
74 | }
75 | }
76 | return 0;
77 | }
--------------------------------------------------------------------------------
/Algorithms/Greedy/Dijkstra's Algorithm/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Greedy/Dijkstra's Algorithm/main.exe
--------------------------------------------------------------------------------
/Algorithms/Greedy/Fractional Knapsack/main.c:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | struct Item{
4 | int profits;
5 | int weights;
6 | double ratio;
7 | };
8 |
9 | double getMaxProfit(int W, struct Item items[], int n){
10 | double totalValue = 0;
11 | struct Item temp;
12 | // Get ratio by profit/ weight
13 | for(int i = 0 ;i < n ;i++){
14 | items[i].ratio = (double)items[i].profits / items[i].weights;
15 | }
16 |
17 | // Select item based on the highest ratio
18 | // Sort ratio in descending order
19 | for(int i = 0; i < n; i++){
20 | for(int j = i+1; j < n; j++){
21 | if(items[i].ratio < items[j].ratio){
22 | temp = items[i];
23 | items[i] = items[j];
24 | items[j] = temp;
25 | }
26 | }
27 | }
28 |
29 | // Iterate each items and pick highest ratio
30 | for(int i = 0 ;i < n;i++){
31 | if(W == 0 ){ // if container is full
32 | break;
33 | }
34 |
35 | if(items[i].weights <= W){
36 | totalValue += items[i].profits;
37 | W-= items[i].weights;
38 | }else{
39 | totalValue += items[i].profits * ((double)W / items[i].weights);
40 | W = 0;
41 | }
42 | }
43 |
44 | return totalValue;
45 | }
46 |
47 |
48 | int main(){
49 | struct Item items[] = {
50 | {10, 2, 0},
51 | {5, 3, 0},
52 | {15, 5, 0},
53 | {7, 7, 0},
54 | {6, 1, 0},
55 | {18, 4, 0},
56 | {3, 1, 0}
57 | };
58 |
59 | int n = sizeof(items)/ sizeof(items[0]); // 7
60 | int m = 15; // Knapsack capacity
61 |
62 | double maxProfit = getMaxProfit(m, items, n);
63 |
64 | printf("\n Total profit: %.2f", maxProfit);
65 |
66 | return 0;
67 | }
--------------------------------------------------------------------------------
/Algorithms/Greedy/Minimum Spanning Tree/Kruskal's Algorithm/main.c:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | #define I 32767
4 |
5 | int edges[3][9] = {
6 | {1, 1, 2, 2, 3, 4, 4, 5, 5},
7 | {2, 6, 3, 7, 4, 5, 7, 6, 7},
8 | {25, 5, 12, 10, 8, 16, 14, 20, 18}
9 | };
10 |
11 | int set[8] = {-1};
12 |
13 | // (7) vertices -> 7-1 (6) edges
14 | int t[2][6];
15 |
16 | int included[9] = {0};
17 |
18 | void unionOperation(int u, int v){
19 | if(set[u] < set[v]){
20 | set[u] += set[v];
21 | set[v] = u;
22 | }else{
23 | set[v] += set[u];
24 | set[u] = v;
25 | }
26 | }
27 |
28 | int find(int u){
29 | int x = u;
30 |
31 | while(set[x] > 0){
32 | x = set[x];
33 | }
34 |
35 | return x;
36 | }
37 |
38 | int main(){
39 | int i=0, j, u, v, k, min, n=7, e=9, sum=0;
40 |
41 | while(i < n-1){
42 | // Identify min cost edge
43 | min = I;
44 | for(j=0; j
2 | #include
3 |
4 | #define V 5
5 |
6 | int graph[V][V] = {
7 | {0, 0, 0, 0, 0},
8 | {0, 0, 1, 0, 0},
9 | {0, 1, 0, 1, 0},
10 | {0, 0, 1, 0, 1},
11 | {0, 0, 0, 1, 0}
12 | };
13 |
14 | int solutionCount = 0;
15 |
16 | int isSafe(int n, int color[], int m, int v, int c){
17 | int i;
18 |
19 | // Check that adjancent vertex has same color?
20 | for(i = 1; i <= n; i++){
21 | if(graph[v][i] && color[i] == c){
22 | return 0; // Conflict
23 | }
24 | }
25 |
26 | return 1; // No conflict
27 | }
28 |
29 | // Coloring the vertices from 1st vertex
30 | void graphColoringUtil(int n, int color[], int m, int v){
31 | // If all vertices are colored
32 | if(v == V){
33 | // Print solution
34 | ++solutionCount;
35 | printf("\nSolution %d: ", solutionCount);
36 |
37 | printf("\nColor Assignment: \n");
38 | for(int i = 1; i <= n; i++){
39 | printf("%d vertex -> %d color\n", i, color[i]);
40 | }
41 | printf("\n");
42 | return;
43 | }
44 |
45 | // if not then perform following things
46 | // start coloring each vertices until all colors are traversed
47 | for(int c = 1; c <= m; c++){
48 | // check adjacent vertex should not have same color
49 | if(isSafe(n, color, m, v, c)){
50 | // Safe the assign the color
51 | color[v] = c;
52 |
53 | // Go for other vertices
54 | graphColoringUtil(n, color, m, v+1);
55 |
56 | // Backtrack
57 | color[v] = 0;
58 | }
59 | }
60 | }
61 |
62 |
63 | void graphColoring(int n, int m){
64 | int color[V];
65 |
66 | // Initlize color as 0
67 | memset(color, 0, sizeof(color));
68 |
69 | // Start coloring vertices from 1st vertex
70 | graphColoringUtil(n, color, m, 1);
71 |
72 | // If there are solutions
73 | if(solutionCount != 0){
74 | printf("\nTotal Solutions with %d colors: %d", m, solutionCount);
75 | }
76 | // If there are not any solutions
77 | else{
78 | printf("\nSolution deson't exist with %d colors.");
79 | }
80 | }
81 |
82 |
83 | int main(){
84 | int n = 4;
85 | int m = 3; // no of colors
86 |
87 | graphColoring(n, m);
88 |
89 | }
--------------------------------------------------------------------------------
/Algorithms/Practice/BackTracking/Graph Coloring/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Practice/BackTracking/Graph Coloring/main.exe
--------------------------------------------------------------------------------
/Algorithms/Practice/BackTracking/Hamiltonian Cycles/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Practice/BackTracking/Hamiltonian Cycles/main.exe
--------------------------------------------------------------------------------
/Algorithms/Practice/BackTracking/NQueen Problem/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | int board[20]; // It will store column no at which queen is placed
5 | int count = 0;
6 |
7 | int print(int n){
8 |
9 | printf("\n\nSolution %d:\n\n", ++count);
10 | int i, j;
11 | for(i = 1; i<= n;i++){
12 | printf("\t%d", i);
13 | }
14 |
15 | for(i = 1; i<= n; i++){
16 | printf("\n\n%d", i);
17 |
18 | for(j = 1; j <= n; j++){
19 | if(board[i] == j){
20 | printf("\tQ");
21 | }else{
22 | printf("\t-");
23 | }
24 | }
25 | }
26 | }
27 |
28 | int place(int row, int col){
29 | // Check queen can be placed with given row and column
30 | int i;
31 |
32 | // Check prev rows from to top to bottom not current row
33 | for(i = 1; i <= row-1; i++){
34 | // Check Same column
35 | if(board[i] == col){
36 | return 0; // Conflict
37 | }
38 |
39 | // Check diagonal
40 | if(abs(board[i] - col) == abs(i - row)){
41 | return 0; // Conflic
42 | }
43 | }
44 |
45 | return 1; // No conflict
46 | }
47 |
48 | void nQueen(int row, int n){
49 |
50 | int col;
51 | for(col = 1; col <= n; col++){
52 | // Is it safe to place queen?
53 | if(place(row, col)){
54 | // safe then place queen
55 | // We are storing Queen row by row
56 | board[row] = col;
57 |
58 | // if row reaches the end
59 | if(row == n){
60 | // print configuration board
61 | print(n);
62 | }else{
63 | // Try with new rows
64 | nQueen(row + 1, n);
65 | }
66 | }
67 | }
68 | }
69 |
70 | int main(){
71 | int n;
72 |
73 | printf("Enter no of queens: ");
74 | scanf("%d", &n);
75 |
76 | if(n == 2 || n == 3){
77 | printf("No solutions exists.");
78 | return 0;
79 | }
80 |
81 | nQueen(1, n);
82 |
83 | }
--------------------------------------------------------------------------------
/Algorithms/Practice/BackTracking/NQueen Problem/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Practice/BackTracking/NQueen Problem/main.exe
--------------------------------------------------------------------------------
/Algorithms/Practice/BackTracking/Sum Of Subset/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #define MAX 100
3 |
4 | void print(int subset[], int subsetSize){
5 | printf("Subset: {");
6 |
7 | for(int i = 0; i < subsetSize; i++){
8 | printf(" %d ", subset[i]);
9 | }
10 |
11 | printf("}\n\n");
12 | }
13 |
14 | void sumOfSubsetUtil(int wt[],int n, int m, int subset[], int subsetSize, int sum, int index){
15 |
16 | // Base condition
17 | if(sum == m){
18 | print(subset, subsetSize);
19 | return;
20 | }
21 |
22 | // Iterate i to n and identify elements which are equal to sum
23 | for(int i = index; i <= n; i++){
24 | // If current element + sum <= target then include
25 | if(wt[i] + sum <= m){
26 | // Add subset array
27 | subset[subsetSize] = wt[i];
28 |
29 | // Identify remaining elemtents
30 | sumOfSubsetUtil(wt, n, m, subset, subsetSize + 1, wt[i] + sum, i + 1);
31 | }
32 | }
33 | }
34 |
35 | void sumOfSubset(int wt[], int n, int m){
36 | int subset[MAX];
37 | sumOfSubsetUtil(wt, n, m, subset, 0, 0, 0);
38 | }
39 |
40 | int main(){
41 | int n, wt[MAX], m;
42 |
43 | printf("Enter size of the wt: ");
44 | scanf("%d", &n);
45 |
46 | printf("Enter WT elements: ");
47 | for(int i =0; i
2 | #include
3 | #include
4 |
5 | #define SIZE 30000
6 |
7 | void printArray(int *A, int n){
8 | int i;
9 | for(i = 0; i < n; i++){
10 | printf("%d ", A[i]);
11 | }
12 | printf("\n");
13 | }
14 |
15 | void InsertionSort(int A[], int n){
16 | int i, j, x;
17 |
18 | for(i = 1; i < n; i++){
19 | j = i-1;
20 | x = A[i];
21 |
22 | while(j > -1 && A[j] > x){
23 | // Swap
24 | A[j+1] = A[j];
25 | j--;
26 | }
27 |
28 | A[j+1] = x;
29 | }
30 | }
31 |
32 | void reverse(int *A, int n){
33 | int temp[SIZE];
34 |
35 | for(int i = 0; i < n; i++){
36 | temp[i] = A[n - i -1];
37 | }
38 |
39 | for(int i = 0; i < n; i++){
40 | A[i] = temp[i];
41 | }
42 | }
43 |
44 | int main(){
45 | int A[SIZE];
46 | int n = sizeof(A)/ sizeof(A[0]);
47 | clock_t t1, t2, t3, t4, t5, t6;
48 | double total_t;
49 |
50 |
51 | for(int i = 0; i < SIZE; i++){
52 | A[i] = rand() % 100;
53 | }
54 |
55 | t1 = clock();
56 | InsertionSort(A, n);
57 | // printArray(A, n);
58 | t2 = clock();
59 |
60 | total_t = (double) (t2 - t1) / CLOCKS_PER_SEC;
61 | printf("\nTime Take to sort Random array: %.2f", total_t);
62 |
63 | t3 = clock();
64 | InsertionSort(A, n);
65 | // printArray(A, n);
66 | t4 = clock();
67 |
68 | total_t = (double) (t4 - t3) / CLOCKS_PER_SEC;
69 | printf("\nTime Take to sort Sorted array: %.2f", total_t);
70 |
71 | reverse(A, n);
72 | t5 = clock();
73 | InsertionSort(A, n);
74 | // printArray(A, n);
75 | t6 = clock();
76 |
77 | total_t = (double) (t6 - t5) / CLOCKS_PER_SEC;
78 | printf("\nTime Take to sort Reverse array: %.2f", total_t);
79 |
80 | return 0;
81 | }
--------------------------------------------------------------------------------
/Algorithms/Practice/Divide and Conquer/Insertion Sort/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Practice/Divide and Conquer/Insertion Sort/main.exe
--------------------------------------------------------------------------------
/Algorithms/Practice/Divide and Conquer/Merge Sort/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Practice/Divide and Conquer/Merge Sort/main.exe
--------------------------------------------------------------------------------
/Algorithms/Practice/Divide and Conquer/MinMax Algorithm/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | int min ,max; // Left subtree
5 |
6 | void minMax(int A[], int l, int h){
7 | int min1, max1; // Right subtree
8 | // Base conditions
9 | if(l == h){
10 | min = max = A[l];
11 | }
12 |
13 | // If two elements
14 | else if(l == h-1){
15 | // Identify min and max between those two elements
16 | if(A[l] < A[h]){
17 | min = A[l];
18 | max = A[h];
19 | }else{
20 | min = A[h];
21 | max = A[l];
22 | }
23 | }
24 | else {
25 | // choice diagram
26 |
27 | // Divide
28 | int mid = (l + h) / 2;
29 | minMax(A, l, mid); // For left subtree
30 |
31 | min1 = min;
32 | max1 = max;
33 |
34 | minMax(A, mid+1, h);
35 |
36 | if(min1 < min){
37 | min = min1;
38 | }
39 |
40 | if(max1 > max){
41 | max = max1;
42 | }
43 | }
44 |
45 | }
46 |
47 | int main(){
48 |
49 | int A[] = {70, 10, 50, 20, 80, 15, 5, 40, 60};
50 | int n = sizeof(A)/ sizeof(A[0]);
51 | clock_t start , end;
52 | double timeTaken;
53 |
54 | start = clock();
55 | minMax(A, 0, n-1);
56 | end = clock();
57 |
58 |
59 | printf("Min: %d \nMax: %d", min, max);
60 |
61 | timeTaken = (double)(end - start) / CLOCKS_PER_SEC;
62 | printf("\nTime Taken by CPU: %f", timeTaken);
63 |
64 | return 0;
65 | }
--------------------------------------------------------------------------------
/Algorithms/Practice/Divide and Conquer/MinMax Algorithm/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Practice/Divide and Conquer/MinMax Algorithm/main.exe
--------------------------------------------------------------------------------
/Algorithms/Practice/Divide and Conquer/Quick Sort/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Practice/Divide and Conquer/Quick Sort/main.exe
--------------------------------------------------------------------------------
/Algorithms/Practice/Divide and Conquer/Selection Sort/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | #define SIZE 30000
6 |
7 | void printArray(int *A, int n){
8 | int i;
9 | for(i = 0; i < n; i++){
10 | printf("%d ", A[i]);
11 | }
12 | printf("\n");
13 | }
14 |
15 | void SelectionSort(int A[], int n){
16 | int i, j, k;
17 |
18 | for(i = 0; i < n-1; i++){
19 | for(j = k = i; j < n; j++){
20 | // Identify min element
21 | if(A[j] < A[k]){
22 | k = j; // K will point to that position
23 | }
24 | }
25 |
26 | // After this swap min element with selected position
27 | int temp = A[k];
28 | A[k] = A[i];
29 | A[i] = temp;
30 | }
31 | }
32 |
33 | void reverse(int *A, int n){
34 | int temp[SIZE];
35 |
36 | for(int i = 0; i < n; i++){
37 | temp[i] = A[n - i -1];
38 | }
39 |
40 | for(int i = 0; i < n; i++){
41 | A[i] = temp[i];
42 | }
43 | }
44 |
45 | int main(){
46 | int A[SIZE];
47 | int n = sizeof(A)/ sizeof(A[0]);
48 | clock_t t1, t2, t3, t4, t5, t6;
49 | double total_t;
50 |
51 |
52 | for(int i = 0; i < SIZE; i++){
53 | A[i] = rand() % 100;
54 | }
55 |
56 | t1 = clock();
57 | SelectionSort(A, n);
58 | // printArray(A, n);
59 | t2 = clock();
60 |
61 | total_t = (double) (t2 - t1) / CLOCKS_PER_SEC;
62 | printf("\nTime Take to sort Random array: %.2f", total_t);
63 |
64 | t3 = clock();
65 | SelectionSort(A, n);
66 | // printArray(A, n);
67 | t4 = clock();
68 |
69 | total_t = (double) (t4 - t3) / CLOCKS_PER_SEC;
70 | printf("\nTime Take to sort Sorted array: %.2f", total_t);
71 |
72 | reverse(A, n);
73 | t5 = clock();
74 | SelectionSort(A, n);
75 | // printArray(A, n);
76 | t6 = clock();
77 |
78 | total_t = (double) (t6 - t5) / CLOCKS_PER_SEC;
79 | printf("\nTime Take to sort Reverse array: %.2f", total_t);
80 |
81 | return 0;
82 | }
--------------------------------------------------------------------------------
/Algorithms/Practice/Divide and Conquer/Selection Sort/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Practice/Divide and Conquer/Selection Sort/main.exe
--------------------------------------------------------------------------------
/Algorithms/Practice/Divide and Conquer/Strassen's Matrix Multiplication/main.c:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | #define d 3
4 |
5 |
6 | int main()
7 | {
8 | int n = 2;
9 | int A[d][d], B[d][d], C[d][d];
10 | int P, Q, R, S, T, U, V;
11 | int i, j;
12 |
13 | printf("Enter A matrix: ");
14 | for(i = 1; i <= n; i++){
15 | for(j = 1; j <= n; j++)
16 | scanf("%d", &A[i][j]);
17 | }
18 |
19 | printf("Enter B matrix: ");
20 | for(i = 1; i <= n; i++){
21 | for(j = 1; j <= n; j++)
22 | scanf("%d", &B[i][j]);
23 | }
24 |
25 | printf("\nA Matrix: \n");
26 | for(i = 1; i <= n; i++)
27 | for(j = 1; j <= n; j++)
28 | printf(" %d ", A[i][j]);
29 | printf("\n");
30 |
31 | printf("\nB Matrix: \n");
32 | for(i = 1; i <= n; i++)
33 | for(j = 1; j <= n; j++)
34 | printf(" %d ", A[i][j]);
35 | printf("\n");
36 |
37 | // SMM Working
38 | P = (A[1][1] + A[2][2]) * (B[1][1] + B[2][2]);
39 | Q = (A[2][1] + A[2][2]) * B[1][1];
40 | R = A[1][1] * (B[1][2] - B[2][2]);
41 | S = A[2][2] * (B[2][1] - B[1][1]);
42 | T = (A[1][1] + A[1][2]) * B[2][2];
43 | U = (A[2][1] - A[1][1]) * (B[1][1] + B[1][2]);
44 | V = (A[1][2] - A[2][2]) * (B[2][1] + B[2][2]);
45 |
46 | // Calculate Result matrix
47 | C[1][1] = P + S - T + V;
48 | C[1][2] = R + T;
49 | C[2][1] = Q + S;
50 | C[2][2] = P - Q + R + U;
51 |
52 | // Result matrix
53 | printf("\nC Matrix: \n");
54 | for(i = 1; i <= n; i++)
55 | for(j = 1; j <= n; j++)
56 | printf(" %d ", C[i][j]);
57 | printf("\n");
58 |
59 | return 0;
60 | }
61 |
--------------------------------------------------------------------------------
/Algorithms/Practice/Divide and Conquer/Strassen's Matrix Multiplication/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Practice/Divide and Conquer/Strassen's Matrix Multiplication/main.exe
--------------------------------------------------------------------------------
/Algorithms/Practice/Divide and Conquer/Strassen's Matrix Multiplication/tempCodeRunnerFile.c:
--------------------------------------------------------------------------------
1 | // SMM
2 | P = (A[1][1] + A[2][2]) * (B[1][1] + B[2][2]);
3 | Q = (A[2][1] + A[2][2]) * B[1][1];
4 | R = A[1][1] * (B[1][2] - B[2][2]);
5 | S = A[2][2] * (B[2][1] - B[1][1]);
6 | T = (A[1][1] + A[1][2]) * B[2][2];
7 | U = (A[1][1] - A[2][1]) * (B[1][1] + B[1][2]);
8 | V = (A[1][2] - A[2][2]) * (B[2][1] + B[2][2]);
9 |
10 |
11 | // Calculate result matrix
12 |
13 | C[1][1] = P + S - T + V;
14 | C[1][2] = R + T;
15 | C[2][1] = Q + S;
16 | C[2][2] = P + R - Q + U;
17 |
--------------------------------------------------------------------------------
/Algorithms/Practice/Dynamic Programming/0/1 Knapsack/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | #define MAX_ITEM 102
5 | #define MAX_WT 1002
6 |
7 | int dp[MAX_ITEM][MAX_WT];
8 |
9 | int max(int a, int b){
10 | return (a > b) ? a : b;
11 | }
12 |
13 | int Knapsack(int val[], int wt[], int n, int W){
14 | // Base condition
15 | if(W == 0 || n == 0){
16 | return 0;
17 | }
18 |
19 | // Present or not ?
20 | if(dp[n][W] != -1){
21 | return dp[n][W];
22 | }
23 |
24 | // Choice diagram
25 | // If weight less than equal knapsack capacity
26 | if(wt[n-1] <= W){
27 | // Include
28 | int a = val[n-1] + Knapsack(val, wt, n-1 , W - wt[n-1]);
29 |
30 | // Exclude
31 | int b = Knapsack(val, wt, n-1 , W);
32 |
33 | return dp[n][W] = max(a,b);
34 |
35 | }else {
36 | // Exclude
37 | return dp[n][W] = Knapsack(val, wt, n-1, W);
38 | }
39 | }
40 |
41 | int main(){
42 | int val[] = {1, 4, 5, 7};
43 | int wt[] = {1, 3, 4, 5};
44 | int W = 7;
45 |
46 | int n = sizeof(wt) / sizeof(wt[0]);
47 |
48 | memset(dp, -1, sizeof(dp));
49 |
50 | printf("Max profit: %d", Knapsack(val, wt, n, W));
51 |
52 | }
--------------------------------------------------------------------------------
/Algorithms/Practice/Dynamic Programming/0/1 Knapsack/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Practice/Dynamic Programming/0/1 Knapsack/main.exe
--------------------------------------------------------------------------------
/Algorithms/Practice/Dynamic Programming/Bellman Ford/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | #define I INT_MAX
5 |
6 | int cost[8][8] = {
7 | {I, I, I, I, I, I, I, I},
8 | {I, I, 6, 5, 5, I, I, I},
9 | {I, I, I, I, I, -1, I, I},
10 | {I, I, -2, I, I, 1, I, I},
11 | {I, I, I, -2, I, I, -1, I},
12 | {I, I, I, I, I, I, I, 3},
13 | {I, I, I, I, I, I, I, 3},
14 | {I, I, I, I, I, I, I, I},
15 | };
16 |
17 | // int cost[5][5] = {
18 | // {I, I, I, I, I}, // 0 (not used)
19 | // {I, 0, 4, I, 5}, // 1
20 | // {I, I, 0, I, 5}, // 2
21 | // {I, I, -10, 0, I}, // 3
22 | // {I, I, I, 3, 0} // 4
23 | // };
24 |
25 |
26 |
27 | int d[8];
28 | int p[8];
29 |
30 | int BellmanFord(int src, int n){
31 | int i, u, v;
32 |
33 | // Initialize distand and parent matrix
34 | for(i = 1; i <= n; i++){
35 | d[i] = I;
36 | p[i] = -1;
37 | }
38 |
39 | d[src]= 0;
40 |
41 | // Relaxation till n-1 times
42 | for(i = 1; i <= n-1; i++){
43 | for(u = 1; u <= n; u++){
44 | for(v = 1; v <= n; v++){
45 | if(cost[u][v] != I && d[u] + cost[u][v] < d[v]){
46 | // Update distance & parent array
47 | d[v] = d[u] + cost[u][v];
48 | p[v] = u;
49 | }
50 | }
51 | }
52 | }
53 |
54 | // Again Relaxation to check negative edge cycle
55 | for(u = 1; u <= n; u++){
56 | for(v = 1; v <= n; v++){
57 | if(cost[u][v] != I && d[u]+ cost[u][v] < d[v]){
58 | // There is a cycle
59 | return 1;
60 | }
61 | }
62 | }
63 | // There is no any cycle
64 | return 0;
65 |
66 | }
67 |
68 | int main(){
69 |
70 | int n = 7;
71 |
72 | if(BellmanFord(1 , n)){
73 | printf("\nThere is a negative edge cycle.");
74 | }else{
75 | printf("\nShortest Path Table\n");
76 | for(int i =1; i <= n; i++){
77 | printf("%d\t%d\t%d\t\n", i, d[i], p[i]);
78 | }
79 | }
80 |
81 | return 0;
82 | }
--------------------------------------------------------------------------------
/Algorithms/Practice/Dynamic Programming/Bellman Ford/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Practice/Dynamic Programming/Bellman Ford/main.exe
--------------------------------------------------------------------------------
/Algorithms/Practice/Dynamic Programming/Floyd Warshall/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | #define I INT_MAX
5 |
6 | int main(){
7 | int n = 5;
8 | int A[5][5] = {
9 | {0, 3, 8, I, -4},
10 | {I, 0, I, 1, 7},
11 | {I, 4, 0, I, I},
12 | {2, I, -5, 0, I},
13 | {I, I, I, 6, 0},
14 | };
15 |
16 | int P[5][5];
17 |
18 | // Initialize parent matrix
19 | for(int i = 0; i < n; i++){
20 | for(int j = 0; j < n; j++){
21 | if(i == j || A[i][j] == I){
22 | P[i][j] = I;
23 | }else{
24 | P[i][j] = i;
25 | }
26 | }
27 | }
28 |
29 | // Floyd warshall working
30 | for(int k = 0; k < n; k++){
31 | for(int i = 0; i < n; i++){
32 | for(int j = 0; j < n; j++){
33 | if(A[i][k] != I && A[k][j] != I && A[i][k] + A[k][j] < A[i][j]){
34 | // Update matrix
35 | A[i][j] = A[i][k] + A[k][j];
36 | P[i][j] = k;
37 | }
38 | }
39 | }
40 | }
41 |
42 | // Print matrix
43 | printf("\nResult matrix: \n");
44 | for(int i = 0; i < n; i++){
45 | for(int j = 0; j < n; j++){
46 | printf(" %4d ", A[i][j]);
47 | }
48 |
49 | printf("\n");
50 | }
51 |
52 | printf("\nParent matrix: \n");
53 | for(int i = 0; i < n; i++){
54 | for(int j = 0; j < n; j++){
55 | if(P[i][j] == I){
56 | printf(" _ ");
57 | }else{
58 | printf(" %3d ", P[i][j] + 1);
59 | }
60 | }
61 | printf("\n");
62 | }
63 | }
--------------------------------------------------------------------------------
/Algorithms/Practice/Dynamic Programming/Floyd Warshall/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Practice/Dynamic Programming/Floyd Warshall/main.exe
--------------------------------------------------------------------------------
/Algorithms/Practice/Dynamic Programming/LCS/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | int dp[1001][1001];
5 |
6 | int max(int a, int b){
7 | return (a > b) ? a : b;
8 | }
9 |
10 | int LCS(char x[], char y[], int n, int m){
11 | // Base condition
12 | if(n == 0 || m == 0){
13 | return 0;
14 | }
15 |
16 | // Present or not
17 | if(dp[n][m] != -1){
18 | return dp[n][m];
19 | }
20 |
21 | // Choice diagram
22 | // If char matches
23 | if(x[n-1] == y[m-1]){
24 | return dp[n][m]= 1 + LCS(x, y, n-1, m-1);
25 | }
26 | // not matches
27 | else{
28 | int a = LCS(x, y, n, m-1);
29 | int b = LCS(x, y, n-1, m);
30 | return dp[n][m] = max(a, b);
31 | }
32 | }
33 |
34 | void printLCS(char x[], char y[], int n, int m){
35 | char lcs[1001];
36 |
37 | int index = dp[n][m];
38 |
39 | lcs[index] = '\0';
40 | int i = n , j = m;
41 |
42 | while( i > 0 && j > 0){
43 | if(x[i - 1] == y[j - 1]){
44 | lcs[index -1] = x[i - 1];
45 | i--;
46 | j--;
47 | index--;
48 | }else if(dp[i-1][j] > dp[i][j-1] ){
49 | i--;
50 | }else {
51 | j--;
52 | }
53 | }
54 | printf("\nLCS string: %s", lcs);
55 | }
56 |
57 | int main(){
58 | char x[] = "abcdgh";
59 | char y[] = "abedfgr";
60 |
61 | int n = strlen(x);
62 | int m = strlen(y);
63 |
64 | memset(dp, -1, sizeof(dp));
65 | printf("LCS Len: %d", LCS(x, y, n, m));
66 |
67 | printLCS(x, y, n, m);
68 |
69 | return 0;
70 | }
--------------------------------------------------------------------------------
/Algorithms/Practice/Dynamic Programming/LCS/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Practice/Dynamic Programming/LCS/main.exe
--------------------------------------------------------------------------------
/Algorithms/Practice/Dynamic Programming/MCM/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | /**
6 | * n <= 1000
7 | */
8 | int dp[1001][1001];
9 | int bracket[1001][1001]; // to store split point
10 |
11 | int solve(int arr[], int i, int j){
12 | // Base condition
13 | if(i >= j){
14 | return 0;
15 | }
16 |
17 | // Presnet or not
18 | if(dp[i][j] != -1){
19 | return dp[i][j];
20 | }
21 |
22 | int min = INT_MAX;
23 | // k loop
24 | for(int k = i; k <= j-1; k++){
25 | // temp ans
26 | int tempAns = solve(arr, i, k) + solve(arr, k+1, j) + arr[i-1] * arr[k] * arr[j];
27 |
28 | // Idenitfy min cost from temp ans
29 | if(tempAns < min){
30 | min = tempAns;
31 | bracket[i][j]= k;
32 | }
33 | }
34 |
35 | return dp[i][j] = min;
36 | }
37 |
38 | void printParenthesis(int i, int j, char *name){
39 | // base condition
40 | if(i == j){
41 | printf("%c", (*name)++);
42 | return;
43 | }
44 | printf("(");
45 | printParenthesis(i, bracket[i][j], name);
46 | printParenthesis(bracket[i][j] + 1, j, name);
47 | printf(")");
48 | }
49 |
50 | int main()
51 | {
52 | int arr[] = {40, 20, 30, 10, 30};
53 |
54 | int n = sizeof(arr) / sizeof(arr[0]);
55 |
56 | // Initialize dp as -1
57 | memset(dp, -1, sizeof(dp));
58 | printf("Min Cost: %d", solve(arr, 1, n-1));
59 |
60 | char name = 'A';
61 | printf("Optimal Parenthesization: \n");
62 | printParenthesis(1, n - 1, &name);
63 | printf("\n");
64 |
65 |
66 | return 0;
67 | }
--------------------------------------------------------------------------------
/Algorithms/Practice/Dynamic Programming/MCM/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Practice/Dynamic Programming/MCM/main.exe
--------------------------------------------------------------------------------
/Algorithms/Practice/Experiment List/List.txt:
--------------------------------------------------------------------------------
1 | # Algorithms by Category
2 |
3 | ## Divide and Conquer
4 | 1. Min-Max algorithm (completed)
5 | 2. Strassen's algorithm (completed)
6 | 3. Merge sort (completed)
7 | 4. Quick Sort (completed)
8 | 5. insertion sort (Incremental Approach) (completed)
9 |
10 | ## Greedy Method
11 | 1. Fractional Knapsack (completed)
12 | 2. Job Sequencing with Deadline (Not in experiment list)
13 | 3. Kruskal's/Prim's algorithm (completed)
14 | 4. Dijkstra's Algorithm (Single Source Shortest Path) (completed)
15 | 5. Selection sort (completed)
16 |
17 | ## Dynamic Programming
18 | 1. Bellman Ford Algorithm (completed)
19 | 2. Longest Common Subsequence (LCS) (completed)
20 | 3. Traveling Salesman Problem (TSP) (Not in experiment list)
21 | 4. Multistage Graph (Not in experiment list)
22 | 5. Coin Change Problem (Not in experiment list)
23 | 6. 0/1 Knapsack (completed)
24 | 7. Matrix chain multiplication (completed)
25 | 8. All Pairs Shortest Path (Floyd Warshall) (completed)
26 |
27 | ## Backtracking
28 | 1. N-Queen Problem (completed)
29 | 2. Sum of Subset (completed)
30 | 3. Graph Coloring (completed)
31 | 4. Hamiltonian Cycles (completed)
32 |
33 | ## String Matching
34 | 1. Knuth-Morris-Pratt (KMP) Algorithm (completed)
35 | 2. Rabin Karp Algorithm (completed)
--------------------------------------------------------------------------------
/Algorithms/Practice/Greedy Method/Dijkstra's Algorithm/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | #define I INT_MAX
6 |
7 | // Adjancency matrix
8 | int cost[7][7] = {
9 | {I, I, I, I, I, I, I}, // 0
10 | {I, I, 2, 4, I, I, I}, // 1
11 | {I, I, I, 1, 7, I, I}, // 2
12 | {I, I, I, I, I, 3, I}, // 3
13 | {I, I, I, I, I, I, 1}, // 4
14 | {I, I, I, I, 2, I, 5}, // 5
15 | {I, I, I, I, I, I, I} // 6
16 | };
17 |
18 | int d[7];
19 | int p[7];
20 | int visited[7];
21 |
22 | void Dijkstra(int src, int n){
23 | int min, u, v, i, j;
24 |
25 | // Initialize distance and visited matrix
26 | for(i = 1; i <= n; i++) {
27 | d[i] = I;
28 | visited[i] = 0;
29 | }
30 |
31 | // Initially set src as 0
32 | d[src] = 0;
33 |
34 | for(i = 1; i <= n; i++){
35 | // Idenitfy min distance vertex and not visisted
36 | min = I;
37 | u = -1;
38 |
39 | for(j = 1; j <= n ;j++){
40 | if(!visited[j] && d[j] < min){
41 | u = j;
42 | min = d[j];
43 | }
44 | }
45 |
46 | if(u == -1)
47 | break; // All vertices are visisted and uncreashable
48 | // Update visited
49 | visited[u] = 1;
50 | // Relaxation
51 | for(v = 1; v <= n; v++){
52 | // Relax those vertices which are having connection and not visisted
53 | if(!visited[v] && cost[u][v] != I && d[u] + cost[u][v] < d[v]){
54 | // update parent and distance array
55 | d[v] = d[u] + cost[u][v];
56 | p[v] = u;
57 | }
58 | }
59 |
60 | }
61 |
62 | }
63 |
64 | int main(){
65 | int n = 6, i;
66 |
67 | Dijkstra(1 , n);
68 |
69 | printf("\nShortest Paths from Vertex 1 using Dijkstra's Algorithm:\n");
70 | printf("Vertices Distance Parent\n");
71 |
72 | for(i = 1; i <= n;i++){
73 | if(i == 1){
74 | printf("%d\t%d\t_\n", i, d[i]);
75 | continue;
76 | }
77 | printf("%d\t%d\t%d\n", i, d[i], p[i]);
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/Algorithms/Practice/Greedy Method/Dijkstra's Algorithm/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Practice/Greedy Method/Dijkstra's Algorithm/main.exe
--------------------------------------------------------------------------------
/Algorithms/Practice/Greedy Method/Fractional Knapsack/main.c:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | // Time complexity : O(n^2)
4 | // Optimize using quick sort : O(nlogn)
5 |
6 | typedef struct {
7 | int profit;
8 | int weight;
9 | double ratio;
10 | } Item;
11 |
12 | double getMaxProfit(Item items[], int n, int W){
13 | double totalValue = 0;
14 | // Step 1: calculate ratio for each object
15 | for(int i = 0; i < n; i++){
16 | items[i].ratio = (double) items[i].profit / items[i].weight;
17 | }
18 |
19 | // Step 2: Sort items as descending order of ratio
20 | for(int i = 0; i < n-1; i++){
21 | for(int j = i; j < n; j++){
22 | if(items[j].ratio > items[i].ratio){
23 | Item temp = items[j];
24 | items[j] = items[i];
25 | items[i] = temp;
26 | }
27 | }
28 | }
29 |
30 | // Step 3: select item as per the highest ratio
31 | for(int i = 0; i < n; i++){
32 | // Base condition
33 | if(W == 0){
34 | break;
35 | }
36 |
37 | // Calculate profit
38 | if(items[i].weight <= W){
39 | totalValue += items[i].profit;
40 | W -= items[i].weight;
41 | }else{
42 | totalValue += items[i].ratio * W;
43 | // We can also use this
44 | // totalValue += items[i].profit * ((double) W / items[i].weight);
45 | W = 0;
46 | }
47 | }
48 |
49 | return totalValue;
50 | }
51 |
52 | int main(){
53 | Item items[]= {
54 | {10, 2, 0},
55 | {5, 3, 0},
56 | {15, 5, 0},
57 | {7, 7, 0},
58 | {6, 1, 0},
59 | {18, 4, 0},
60 | {3, 1, 0},
61 | };
62 | int n = sizeof(items) / sizeof(items[0]);
63 | double max;
64 | int W = 15;
65 |
66 | max = getMaxProfit(items, n, W);
67 |
68 | printf("Max Profit : %.2f", max);
69 |
70 | }
--------------------------------------------------------------------------------
/Algorithms/Practice/Greedy Method/Fractional Knapsack/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Practice/Greedy Method/Fractional Knapsack/main.exe
--------------------------------------------------------------------------------
/Algorithms/Practice/Greedy Method/Kruskal's Algorithm/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | #define I INT_MAX
5 |
6 | // Edges
7 | int edges[3][9] = {
8 | {1, 1, 2, 2, 3, 4, 4, 5, 5},
9 | {2, 6, 3, 7, 4, 5, 7, 6, 7},
10 | {25, 5, 12, 10, 8, 16, 14, 20, 18}
11 | };
12 |
13 | // Set for detecting cyclecs
14 | int s[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
15 |
16 | // Included for edge included or not
17 | int included[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
18 |
19 | // Spanning tree
20 | int t[2][6];
21 |
22 | void unionSet(int u, int v){
23 | if(s[u] < s[v]){
24 | s[u] = s[u] + s[v];
25 | s[v] = u;
26 | }else{
27 | s[v] = s[v] + s[u];
28 | s[u] = v;
29 | }
30 | }
31 |
32 | int find(int u){
33 | int x = u;
34 |
35 | while(s[x] > 0){
36 | x = s[x];
37 | }
38 | return x;
39 | }
40 |
41 | int main(){
42 | int i , j, u, v, min, k;
43 | int n = 7;
44 | int sum = 0;
45 |
46 | i = 0;
47 |
48 | // Iterate till n-1
49 | while(i < n-1){
50 | // Identify min edge and not included
51 | min = I;
52 | for(j = 0; j < 9; j++){
53 | if(included[j] == 0 && edges[2][j] < min){
54 | min = edges[2][j];
55 | u = edges[0][j]; v = edges[1][j];
56 | k = j;
57 | }
58 | }
59 |
60 | // Check cycle
61 | if(find(u) != find(v)){
62 | sum += min;
63 | t[0][i] = u; t[1][i] = v;
64 | unionSet(find(u), find(v));
65 | i++;
66 | }
67 |
68 | // Update included array
69 | included[k] = 1;
70 | }
71 |
72 | // Print spanning tree
73 | for(i = 0; i < n-1; i++){
74 | printf("(%d, %d) ", t[0][i], t[1][i]);
75 | }
76 |
77 | // Cost
78 | printf("\nCost: %d", sum);
79 |
80 | return 0;
81 | }
--------------------------------------------------------------------------------
/Algorithms/Practice/Greedy Method/Kruskal's Algorithm/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Practice/Greedy Method/Kruskal's Algorithm/main.exe
--------------------------------------------------------------------------------
/Algorithms/Practice/Greedy Method/Prim's Algorithm/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Practice/Greedy Method/Prim's Algorithm/main.exe
--------------------------------------------------------------------------------
/Algorithms/Practice/String Matching/KMP/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | #define MAX 100
5 |
6 | void computeLPS(char P[], int lps[], int m){
7 | // Set lps[0] as 0;
8 | lps[0] = 0;
9 | int k = 0;
10 | int q;
11 |
12 | for(q = 1; q < m; q++){
13 | // If pattern not matches and k is less than 0
14 | while(k > 0 && P[q] != P[k]){
15 | // Backtrack
16 | k = lps[k-1];
17 | }
18 |
19 | // If pattern matches then inc the k poitner
20 | if(P[q] == P[k]){
21 | k++;
22 | }
23 |
24 | // Set the k value in lps table
25 | lps[q] = k;
26 | }
27 | }
28 |
29 | int main(){
30 | char str[] = "ababcabcabababdababd";
31 | char P[] = "ababd";
32 |
33 | int n = strlen(str);
34 | int m = strlen(P);
35 |
36 | // Compute LPS
37 | int lps[MAX];
38 | computeLPS(P, lps, m);
39 |
40 | printf("LPS Array: ");
41 | for(int i = 0; i < m; i++){
42 | printf("%d ", lps[i]);
43 | }
44 |
45 | // Now perform string matching algo
46 | int q = 0; // For pointing pattern
47 | int i; // For pointing string
48 |
49 |
50 | for(i = 0; i < n; i++){
51 | while(q > 0 && str[i] != P[q]){
52 | q = lps[q - 1];
53 | }
54 |
55 | if(str[i] == P[q]){
56 | q++;
57 | }
58 |
59 | // if q reaches the pattern size
60 | if(q == m){
61 | printf("\nPattern found at index: %d - %d", i - q + 1, i);
62 | // Continues to search for other occurences
63 | q = lps[q-1];
64 | }
65 | }
66 |
67 | return 0;
68 | }
--------------------------------------------------------------------------------
/Algorithms/Practice/String Matching/KMP/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Practice/String Matching/KMP/main.exe
--------------------------------------------------------------------------------
/Algorithms/Practice/String Matching/Rabin Karp/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | #define d 252 // no of input alphabet
6 |
7 | void search(char text[], char pat[], int n, int m, int q){
8 | // For rolling hash function
9 | int h = 0;
10 | int i, j;
11 | // Calculate rolling has function till m-1
12 | for(i = 0; i < m-1; i++){
13 | h = (h * d) % q;
14 | }
15 |
16 | int t = 0; // Hash val for text
17 | int p = 0; // Hash val for pattern
18 |
19 | // Compute hash code for first window
20 | for(i = 0; i < m; i++){
21 | t = (d * t) % q;
22 | p = (d * p) % q;
23 | }
24 |
25 | // Rabin karp loop
26 | for(i = 0; i <= n-m; i++){
27 | // If hash code same
28 | if(t == p){
29 | for(j = 0; j < m; j++){
30 | // Then check chars are matching?
31 | if(text[i+j] != pat[j]){
32 | break;
33 | }
34 | }
35 |
36 | // If all chars are matching
37 | if(j == m){
38 | printf("Index is found at %d.\n", i);
39 | }
40 | }else{
41 | // Acheive window size
42 | if(i < n-m){
43 | // Roll hash function
44 | t = (d * (t - text[i] * h) + text[i+m]) % q;
45 |
46 | // if t becomes negative?
47 | if(t < 0){
48 | t += q;
49 | }
50 | }
51 | }
52 | }
53 | }
54 |
55 | int main(){
56 | char text[] = "aaaab";
57 | char pat[] = "aab";
58 |
59 | int n = strlen(text);
60 | int m = strlen(pat);
61 | // prime no
62 | int q = 101;
63 |
64 | search(text, pat, n, m, q);
65 | }
--------------------------------------------------------------------------------
/Algorithms/Practice/String Matching/Rabin Karp/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Practice/String Matching/Rabin Karp/main.exe
--------------------------------------------------------------------------------
/Algorithms/Sliding Window/FirstNegInt/input.txt:
--------------------------------------------------------------------------------
1 | 5 3
2 | 4 0 3 -12 1
--------------------------------------------------------------------------------
/Algorithms/Sliding Window/FirstNegInt/main.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | using namespace std;
3 |
4 | void firstNegInt(vector &arr, int n, int k){
5 | list q;
6 | vector res;
7 |
8 | int i = 0, j = 0;
9 |
10 | while(j < n){
11 | // calculation
12 | if(arr[j] < 0){
13 | q.push_back(arr[j]);
14 | }
15 |
16 | // acheive window size
17 | if(j - i + 1 < k){
18 | j++;
19 | }
20 | else if(j - i + 1 == k){ // maintain window size
21 | // ans <- calc
22 | // edge case : no negative values
23 | if(q.empty()){
24 | res.push_back(0);
25 | }else {
26 | res.push_back(q.front());
27 |
28 | if(arr[i] == q.front()){
29 | q.pop_front();
30 | }
31 | }
32 |
33 | // Slide window
34 | i++;
35 | j++;
36 | }
37 | }
38 |
39 | for(auto no: res){
40 | cout << no;
41 | }
42 | }
43 |
44 | int main(){
45 | int n, k;
46 | cin >> n >> k;
47 |
48 | vector arr;
49 | for(int i = 0 ; i < n ; i++){
50 | int x;
51 | cin >> x;
52 | arr.push_back(x);
53 | }
54 |
55 | firstNegInt(arr, n, k);
56 | return 0;
57 | }
--------------------------------------------------------------------------------
/Algorithms/Sliding Window/FirstNegInt/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Sliding Window/FirstNegInt/main.exe
--------------------------------------------------------------------------------
/Algorithms/Sliding Window/FirstNegInt/output.txt:
--------------------------------------------------------------------------------
1 | 0-12-12
--------------------------------------------------------------------------------
/Algorithms/Sliding Window/Max subarr sum of size k/input.txt:
--------------------------------------------------------------------------------
1 | 7 3
2 | 2 1 5 1 3 2 1
3 |
--------------------------------------------------------------------------------
/Algorithms/Sliding Window/Max subarr sum of size k/main.cpp:
--------------------------------------------------------------------------------
1 | /* Problem Statement:
2 | Maximum Sum Subarray of Size K
3 | Given an integer array arr of size n and an integer k, find the maximum sum of any contiguous subarray of size k.
4 | */
5 |
6 | #include
7 | using namespace std;
8 |
9 | void maxSumSubarray(int arr[], int n, int k){
10 | int i = 0, j = 0;
11 | int sum = 0;
12 | int mx = INT_MIN;
13 | while(j < n){
14 | sum += arr[j];
15 | // Achieve window size
16 | if((j - i + 1) < k){
17 | j++;
18 | }else if((j - i + 1) == k){ // Maintain window size
19 | mx = max(mx, sum);
20 | sum -= arr[i];
21 | i++;
22 | j++;
23 | }
24 | }
25 |
26 | cout << mx << endl;
27 | }
28 |
29 | int main(){
30 | int n, k;
31 | cin >> n >> k;
32 |
33 | int arr[n];
34 |
35 | for(int i = 0; i < n; i++){
36 | cin >> arr[i];
37 | }
38 |
39 | maxSumSubarray(arr, n, k);
40 |
41 | return 0;
42 | }
--------------------------------------------------------------------------------
/Algorithms/Sliding Window/Max subarr sum of size k/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/Sliding Window/Max subarr sum of size k/main.exe
--------------------------------------------------------------------------------
/Algorithms/Sliding Window/Max subarr sum of size k/output.txt:
--------------------------------------------------------------------------------
1 | 9
2 |
--------------------------------------------------------------------------------
/Algorithms/String Matching/KMP/input.txt:
--------------------------------------------------------------------------------
1 | 5 3
2 | 4 0 3 -12 1
--------------------------------------------------------------------------------
/Algorithms/String Matching/KMP/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | void computeLPS(char *P, int m, int *lps){
5 | // 0th index letter always set to 0
6 | lps[0] = 0;
7 | int k = 0;
8 |
9 | for(int q = 1; q < m; q++){
10 | // Compare P with P until k > 0;
11 | while(k > 0 && P[q] != P[k]){
12 | k = lps[k-1];
13 | }
14 |
15 | // If match
16 | if(P[q] == P[k]){
17 | // Increment k value
18 | k++;
19 | }
20 |
21 | // Store in lps
22 | lps[q] = k;
23 | }
24 | }
25 |
26 | int main(){
27 | char str[] = "ababcabcabababd";
28 | int n = strlen(str);
29 |
30 | char P[] = "ababd";
31 | int m = strlen(P);
32 |
33 | int lps[m];
34 | computeLPS(P, m, lps);
35 |
36 | printf("LPS array:\n");
37 | for (int i = 0; i < m; i++) {
38 | printf("%d ", lps[i]);
39 | }
40 |
41 | int q = 0;
42 | // Now apply KMP algo
43 | for (int i = 0; i < n; i++) {
44 | while (q > 0 && str[i] != P[q]) {
45 | q = lps[q - 1];
46 | }
47 |
48 | if (str[i] == P[q]) {
49 | q++;
50 | }
51 |
52 | if (q == m) {
53 | printf("Pattern found at index %d\n", i - m + 1);
54 | q = lps[q - 1]; // To continue searching for next occurrence
55 | }
56 | }
57 |
58 | return 0;
59 | }
--------------------------------------------------------------------------------
/Algorithms/String Matching/KMP/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/String Matching/KMP/main.exe
--------------------------------------------------------------------------------
/Algorithms/String Matching/KMP/output.txt:
--------------------------------------------------------------------------------
1 | 0-12-12
--------------------------------------------------------------------------------
/Algorithms/String Matching/Rabin Karp/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | // Reference: https://prepinsta.com/c-program/rabin-karp-algorithm/
5 |
6 | // d is the number of characters in input alphabet
7 | #define d 256
8 |
9 | /* pat -> pattern
10 | txt -> text
11 | q -> A prime number
12 | */
13 | void search(char *pat, char *txt, int q)
14 | {
15 | int M = strlen(pat);
16 | int N = strlen(txt);
17 | int i, j;
18 | int p = 0; // hash value for pattern
19 | int t = 0; // hash value for txt
20 | int h = 1;
21 |
22 | // The value of h would be "pow(d, M-1)%q"
23 | for (i = 0; i < M-1; i++)
24 | h = (h*d)%q;
25 |
26 | // Calculate the hash value of pattern and first window of text
27 | for (i = 0; i < M; i++)
28 | {
29 | p = (d*p + pat[i])%q;
30 | t = (d*t + txt[i])%q;
31 | }
32 |
33 | // Slide the pattern over text one by one
34 | for (i = 0; i <= N - M; i++)
35 | {
36 |
37 | // Check the hash values of current window of text and pattern
38 | // If the hash values match then only check for characters on by one
39 | if ( p == t )
40 | {
41 | /* Check for characters one by one */
42 | for (j = 0; j < M; j++)
43 | {
44 | if (txt[i+j] != pat[j])
45 | break;
46 | }
47 | if (j == M) // if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1]
48 | {
49 | printf("Pattern found at index %d \n", i);
50 | }
51 | }
52 |
53 | // Calculate hash value for next window of text: Remove leading digit,
54 | // add trailing digit
55 | if ( i < N-M )
56 | {
57 | t = (d*(t - txt[i]*h) + txt[i+M])%q;
58 |
59 | // We might get negative value of t, converting it to positive
60 | if(t < 0)
61 | t = (t + q);
62 | }
63 | }
64 | }
65 |
66 | /* Driver program to test above function */
67 | int main()
68 | {
69 | char *txt = "Sanfoundry C Programming Examples";
70 | char *pat = "San";
71 | int q = 101; // A prime number
72 | search(pat, txt, q);
73 | return 0;
74 | }
--------------------------------------------------------------------------------
/Algorithms/String Matching/Rabin Karp/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Algorithms/String Matching/Rabin Karp/main.exe
--------------------------------------------------------------------------------
/Algorithms/String Matching/Rabin Karp/tempCodeRunnerFile.c:
--------------------------------------------------------------------------------
1 | // We might get negative value of t, converting it to positive
2 | if(t < 0)
3 | t = (t + q);
--------------------------------------------------------------------------------
/Graph/Graph (undirected) Representation.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Graph/Graph (undirected) Representation.png
--------------------------------------------------------------------------------
/Graph/Minimum Spanning Tree/Kruskal's Algorithm/main.c:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | #define I 32767
4 |
5 | int edges[3][9] = {
6 | {1, 1, 2, 2, 3, 4, 4, 5, 5},
7 | {2, 6, 3, 7, 4, 5, 7, 6, 7},
8 | {25, 5, 12, 10, 8, 16, 14, 20, 18}
9 | };
10 |
11 | int set[8] = {-1};
12 |
13 | // (7) vertices -> 7-1 (6) edges
14 | int t[2][6];
15 |
16 | int included[9] = {0};
17 |
18 | void unionOperation(int u, int v){
19 | if(set[u] < set[v]){
20 | set[u] += set[v];
21 | set[v] = u;
22 | }else{
23 | set[v] += set[u];
24 | set[u] = v;
25 | }
26 | }
27 |
28 | int find(int u){
29 | int x = u;
30 |
31 | while(set[x] > 0){
32 | x = set[x];
33 | }
34 |
35 | return x;
36 | }
37 |
38 | int main(){
39 | int i=0, j, u, v, k, min, n=7, e=9, sum=0;
40 |
41 | while(i < n-1){
42 | // Identify min cost edge
43 | min = I;
44 | for(j=0; j
2 |
3 | #define I 32767
4 |
5 | // Algorithm:
6 | /**
7 | * 1. First select vertices having minimum edge cost from cost matrix
8 | * 2. Select the adjacent Vertices having minimum edge cost
9 | */
10 |
11 | // Initialization
12 | int cost[8][8] = {
13 | {I, I, I, I, I, I, I, I},
14 | {I, I, 25, I, I, I, 5, I},
15 | {I, 25, I, 12, I, I, I, 10},
16 | {I, I, 12, I, 8, I, I, I},
17 | {I, I, I, 8, I, 16, I, 14},
18 | {I, I, I, I, 16, I, 20, 18},
19 | {I, 5, I, I, I, 20, I, I},
20 | {I, I, 10, I, 14, 18, I, I}
21 | };
22 |
23 | // Initialize as Infinity
24 | int near[8] = {I, I, I, I, I, I, I, I};
25 |
26 | // n-> nodes , n-1 -> edges(6)
27 | int t[2][6];
28 |
29 | int main(){
30 | int i, j, u, v, k,min = I, n=7, sum=0;
31 |
32 | // Initial work
33 | // Find minimum edge from Cost matrix(upper triangular)
34 | for(i = 1; i<=n;i++){
35 | for(j = i; j<=n ;j++){
36 | if(cost[i][j] < min){
37 | min = cost[i][j];
38 | u = i; v = j;
39 | }
40 | }
41 | }
42 |
43 | near[u] = near[v] = 0;
44 | t[0][0] = u; t[1][0] = v;
45 | sum += min;
46 |
47 | // Identify near vertex having minium edge and connected by the selected edge
48 | for (i = 1; i <= n; i++) {
49 | if (near[i] != 0) {
50 | near[i] = (cost[i][u] < cost[i][v]) ? u : v;
51 | }
52 | }
53 |
54 | // Repeatetion work
55 | for(i=1; i
2 | struct Queue{
3 | int size;
4 | int front;
5 | int rear;
6 | int *Q;
7 | };
8 |
9 | struct Queue createQueue(int size) {
10 | struct Queue q;
11 | q.size = size;
12 | q.Q = (int *)malloc(q.size * sizeof(int));
13 | q.front = q.rear = -1;
14 |
15 | return q;
16 | }
17 | void enqueue(struct Queue *q , int data){
18 | if(q->rear == q->size-1){
19 | printf("Queue is full.");
20 | }else{
21 | q->rear++;
22 | q->Q[q->rear] = data;
23 | }
24 | }
25 |
26 | int dequeue(struct Queue *q){
27 | int x = -1;
28 |
29 | if(q->front == q->rear){
30 | printf("Queue is empty.");
31 | }else{
32 | q->front++;
33 | x = q->Q[q->front];
34 | }
35 | return x;
36 | }
37 |
38 | int isEmpty(struct Queue *q){
39 | return (q->front == q->rear)? 1 : 0;
40 | }
41 |
42 | void display(struct Queue *q) {
43 | if (q->front == q->rear) {
44 | printf("Queue is empty\n");
45 | return;
46 | }
47 |
48 | // Use a temporary index to iterate through the queue
49 | int i = q->front + 1;
50 |
51 | printf("Queue elements: ");
52 | while (i <= q->rear) {
53 | printf("%d ", q->Q[i]);
54 | i++;
55 | }
56 | printf("\n");
57 | }
--------------------------------------------------------------------------------
/Graph/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include "Queue.h"
3 |
4 | int n;
5 | int adj[10][10] , visited[10];
6 |
7 | // (Breadth First Search)
8 | // TC : O(n^2)
9 | void BFS(int i){
10 | struct Queue q = createQueue(10);
11 | int u;
12 | // Initial step :
13 | printf("%d " , i);
14 | visited[i] = 1;
15 | enqueue(&q , i);
16 |
17 | // Explore all it's adjacents
18 | while(!isEmpty(&q)){
19 | u = dequeue(&q);
20 | for(int v = 1 ; v<=n ; v++){
21 | // check there is connection and visited or not
22 | if(adj[u][v]==1 && visited[v] == 0){
23 | printf("%d ",v);
24 | visited[v] =1;
25 | enqueue(&q , v);
26 | }
27 | }
28 | }
29 | }
30 |
31 | void DFS(int v){
32 | if(visited[v] == 0){
33 | printf("%d ",v);
34 | visited[v] =1;
35 | // explore all it's adjacents
36 | for(int i = 1; i<=n ; i++){
37 | // if connection and not visited then enter
38 | if(adj[v][i]== 1 && visited[i] == 0){
39 | DFS(i);
40 | }
41 | }
42 | }
43 | }
44 |
45 | int main(){
46 | int v;
47 | printf("\nEnter the no of vertices : ");
48 | scanf("%d" , &n);
49 |
50 | printf("\nEnter graph : \n");
51 | for(int i=1 ; i<=n ; i++){
52 | for(int j =1 ; j<=n;j++){
53 | printf("Enter connection between %d and %d : " , i , j);
54 | scanf("%d" , &adj[i][j]);
55 | // Eptional
56 | if (i != j) {
57 | adj[j][i] = adj[i][j]; // Ensure undirected symmetry
58 | }
59 | }
60 | }
61 |
62 | // Initialize visited array as zero(0)
63 | for(int i = 1 ; i<=n ; i++){
64 | visited[i] = 0;
65 | }
66 |
67 | // printf("Enter the starting vertex : ");
68 | // scanf("%d" , &v);
69 | // BFS(v);
70 |
71 | printf("Enter the starting vertex : ");
72 | scanf("%d" , &v);
73 | DFS(v);
74 |
75 |
76 |
77 | return 0;
78 | }
--------------------------------------------------------------------------------
/Hash/Chaining/Readme.md:
--------------------------------------------------------------------------------
1 | # Chaining in Hashing
2 |
3 | Chaining is a method used to resolve hash collisions in hash tables. In this method, each bucket (or slot) of the hash table stores a linked list of all elements that hash to the same index. When a collision occurs, the element is simply added to the linked list at that index.
4 |
5 |
6 |
7 |
8 |
9 | ### Time and Space Complexity
10 |
11 | | **Operation** | **Average Case** | **Worst Case** |
12 | |--------------------|------------------|----------------|
13 | | **Search** | O(1) | O(n) |
14 | | **Insert** | O(1) | O(n) |
15 | | **Delete** | O(1) | O(n) |
16 |
17 | ### Explanation
18 |
19 | - **Search**: On average, the search operation takes constant time since elements are stored in a linked list in each bucket. However, in the worst case, all elements could hash to the same bucket, resulting in a linear search.
20 |
21 | - **Insert**: Insertion also takes constant time on average. If a collision occurs, the element is added to the linked list at the corresponding bucket.
22 |
23 | - **Delete**: Deletion follows the same approach as the search operation: O(1) on average but could degrade to O(n) in the worst case.
24 |
25 | ### Space Complexity
26 |
27 | The space complexity of chaining in hashing is O(n), where n is the number of elements in the hash table. This is because, in the worst case, all elements can be stored in a single linked list.
28 |
--------------------------------------------------------------------------------
/Hash/Chaining/chains.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Hash/Chaining/chains.exe
--------------------------------------------------------------------------------
/Hash/Chaining/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Hash/Chaining/main.exe
--------------------------------------------------------------------------------
/Hash/Linear Probing/Readme.md:
--------------------------------------------------------------------------------
1 | # Linear Probing in Hashing
2 |
3 | Linear Probing is a collision resolution technique used in open addressing to resolve hash collisions. When a collision occurs, linear probing checks the next available slot in a sequential manner (i.e., it moves linearly through the hash table until an empty slot is found).
4 |
5 |
6 |
7 |
8 |
9 | ### Time and Space Complexity
10 |
11 | | **Operation** | **Average Case** | **Worst Case** |
12 | |--------------------|------------------|----------------|
13 | | **Search** | O(1) | O(n) |
14 | | **Insert** | O(1) | O(n) |
15 | | **Delete** | O(1) | O(n) |
16 |
17 | ### Explanation
18 |
19 | - **Search**: In linear probing, the search operation can be very efficient if the load factor is low. However, if many slots are occupied, it might take longer, resulting in O(n) time complexity in the worst case.
20 |
21 | - **Insert**: Insertions are generally efficient with linear probing, but in cases where the hash table is nearing its capacity, insertions might degrade to O(n) as the algorithm will need to probe multiple slots to find an available one.
22 |
23 | - **Delete**: Deletion works similarly to insertion. In cases of full tables or long chains of collisions, the time complexity may degrade to O(n).
24 |
25 | ### Space Complexity
26 |
27 | The space complexity of linear probing is O(n), where n is the number of elements in the hash table. This is because the space is determined by the size of the hash table itself, and additional space is not required beyond the table.
28 |
--------------------------------------------------------------------------------
/Hash/Linear Probing/linear probing.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Hash/Linear Probing/linear probing.png
--------------------------------------------------------------------------------
/Hash/Linear Probing/main.c:
--------------------------------------------------------------------------------
1 |
2 | #include
3 | #define SIZE 10
4 |
5 | int hash(int key){
6 | return key % 10;
7 | }
8 |
9 | int prob(int HT[] , int key){
10 | int index = hash(key);
11 |
12 | int i = 0 ;
13 | while(HT[(index + i) % SIZE] != 0){
14 | i++;
15 | }
16 |
17 | return (index + i) % SIZE;
18 | }
19 |
20 | void Insert(int HT[] ,int key){
21 | int index = hash(key);
22 |
23 | // already occupied
24 | if(HT[index] != 0){
25 | index = prob(HT , key);
26 | }
27 |
28 | HT[index]=key;
29 | }
30 |
31 | int Search(int HT[] , int key){
32 | int index = hash(key);
33 |
34 | int i = 0;
35 | // Linear probing to find the key
36 | while(HT[(index + i) % SIZE] != 0){
37 | if(HT[(index + i) % SIZE] == key){
38 | return (index + i) % SIZE; // Return the index if found
39 | }
40 | i++;
41 | }
42 |
43 | return -1; // Return -1 if the key is not found
44 | }
45 |
46 | void display(int HT[]){
47 | int i;
48 | for( i = 0 ; i < SIZE ; i++){
49 | // only occupied elements will be displayed
50 | if(HT[i] != 0 ){
51 | printf(" %d " , HT[i]);
52 | }
53 | }
54 | }
55 |
56 |
57 | int main()
58 | {
59 | int HT[10] = {0};
60 |
61 | Insert(HT , 20);
62 | Insert(HT , 23);
63 | Insert(HT , 40);
64 | Insert(HT , 25);
65 | Insert(HT , 30);
66 |
67 | display(HT);
68 |
69 | // Searching for keys
70 | printf("\nSearch 20: %d\n", Search(HT, 20)); // Should return the index where 20 is stored
71 | printf("Search 25: %d\n", Search(HT, 25)); // Should return the index where 25 is stored
72 | printf("Search 50: %d\n", Search(HT, 50)); // Should return -1 (not found)
73 |
74 |
75 | return 0;
76 | }
77 |
--------------------------------------------------------------------------------
/Hash/Linear Probing/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Hash/Linear Probing/main.exe
--------------------------------------------------------------------------------
/Hash/Quadratic Probing/main.c:
--------------------------------------------------------------------------------
1 |
2 | #include
3 | #define SIZE 10
4 |
5 | int hash(int key){
6 | return key %10;
7 | }
8 |
9 | int prob(int HT[] , int key){
10 | int index = hash(key);
11 | int i = 0;
12 | while(HT[(index + i^2) % SIZE] != 0){
13 | i++;
14 | }
15 |
16 | return (index + i^2)%SIZE;
17 | }
18 |
19 | int Insert(int HT[] , int key){
20 | int index = hash(key);
21 |
22 | // already occupied
23 | if(HT[index]!= 0){
24 | index = prob(HT , key);
25 | }
26 |
27 | HT[index] = key;
28 | }
29 |
30 | int Search(int HT[] , int key){
31 | int index = hash(key);
32 | int i = 0;
33 | // blanck space nhi huna chahiye
34 | while(HT[(index + i^2) % SIZE] != 0){
35 | while(HT[(index + i^2) % SIZE] != key){
36 | return (index + i^2) % SIZE;
37 | }
38 | i++;
39 | }
40 |
41 | return -1;
42 | }
43 |
44 | void display(int HT[]){
45 | int i;
46 | for(i = 0 ; i < SIZE ; i++){
47 | if(HT[i]!= 0){
48 | printf("HT[%d] -> %d \n",i , HT[i]);
49 | }
50 | }
51 | }
52 |
53 | int main()
54 | {
55 | int HT[10] = {0};
56 |
57 | Insert(HT , 23);
58 | Insert(HT , 43);
59 | Insert(HT , 13);
60 | Insert(HT , 27);
61 |
62 | display(HT);
63 | // Searching for keys
64 | printf("\nSearch 20: %d\n", Search(HT, 20)); // Should return the index where 20 is stored
65 | printf("Search 23: %d\n", Search(HT, 23)); // Should return the index where 25 is stored
66 | printf("Search 50: %d\n", Search(HT, 50)); // Should return -1 (not found)
67 |
68 | return 0;
69 | }
70 |
--------------------------------------------------------------------------------
/Hash/Quadratic Probing/quadratic probing.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Hash/Quadratic Probing/quadratic probing.png
--------------------------------------------------------------------------------
/Heap/Heapify/heapify.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Heap/Heapify/heapify.png
--------------------------------------------------------------------------------
/Heap/README.md:
--------------------------------------------------------------------------------
1 | # Heap Data Structure
2 |
3 |
4 |
5 |
6 |
7 | ## Definition
8 |
9 | A **heap** is a **complete binary tree** that is usually stored in an array. The elements in a heap are organized as either a **min heap** or a **max heap**.
10 |
11 | - **Min Heap**: The root element is the smallest, and each parent node is smaller than its children.
12 | - **Max Heap**: The root element is the largest, and each parent node is larger than its children.
13 |
14 | Heaps are best suited for implementing **priority queues**.
15 |
16 | ---
17 |
18 | ## Conditions for Creating a Heap
19 |
20 | 1. **Binary Tree should be a Complete Binary Tree**
21 | A **complete binary tree** is a binary tree in which all the levels are completely filled except possibly for the last level, and the last level has all keys as left as possible.
22 |
23 |
24 |
25 |
26 |
27 | There should not be any blank spaces between the elements in an array. This structure is called a **complete binary tree**.
28 |
29 | 2. **Node Relationships**
30 | - In a **min heap**, every node element should be **greater than or equal to** its descendants.
31 | - In a **max heap**, every node element should be **less than or equal to** its descendants.
32 |
33 | ---
34 |
35 | ## Heap Operations and Time Complexity
36 |
37 | 1. **Creation**: Build a heap by rearranging elements in an array to satisfy the heap properties.
38 | **Time Complexity**: O(n log n)
39 |
40 | 2. **Insertion**: Add a new element into the heap and ensure that the heap property is maintained.
41 | **Time Complexity**: O(log n)
42 |
43 | 3. **Deletion**: Remove the root (either the minimum or maximum, depending on heap type) and reheapify the structure.
44 | **Time Complexity**: O(log n)
45 |
46 | 4. **Heapify**: Adjusting an entire array into a heap structure.
47 | **Time Complexity**: O(n)
48 |
49 | ---
50 |
51 | Feel free to explore and contribute!
52 |
--------------------------------------------------------------------------------
/Heap/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Heap/main.exe
--------------------------------------------------------------------------------
/Heap/operations/Creation of Max Heap.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Heap/operations/Creation of Max Heap.png
--------------------------------------------------------------------------------
/Heap/operations/Deletion in Max Heap.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Heap/operations/Deletion in Max Heap.png
--------------------------------------------------------------------------------
/Heap/operations/Insertion in Max Heap.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Heap/operations/Insertion in Max Heap.png
--------------------------------------------------------------------------------
/Linked List/Circular Linked List/README.md:
--------------------------------------------------------------------------------
1 | # Circular Linked List
2 |
3 | A circular linked list is a variation of a linked list where the last node points back to the first node, forming a circular structure. This allows for continuous traversal of the list.
4 |
5 |
6 |

7 |
8 |
9 | ## Features
10 |
11 | - Dynamic size
12 | - Continuous traversal of elements
13 | - Efficient insertion and deletion at any point
14 |
15 | ## Basic Operations
16 |
17 | 1. Insertion
18 | - At the beginning
19 | - At the end
20 | - At a specific position
21 |
22 | 2. Deletion
23 | - From the beginning
24 | - From the end
25 | - From a specific position
26 |
27 | 3. Traversal
28 | - Print all elements
29 |
30 | 4. Search
31 | - Find an element by value
32 |
33 | ## Structure of a Circular Linked List Node
34 | Each node in a circular linked list consists of:
35 | 1. **Data**: The value stored in the node.
36 | 2. **Next Pointer**: A reference to the next node in the list.
37 |
38 | ### Node Representation
39 | ```c
40 | struct Node {
41 | int data;
42 | struct Node* next;
43 | };
44 |
--------------------------------------------------------------------------------
/Linked List/Circular Linked List/insertion and deletion based on position.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Linked List/Circular Linked List/insertion and deletion based on position.png
--------------------------------------------------------------------------------
/Linked List/Circular Linked List/insertion based value.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Linked List/Circular Linked List/insertion based value.png
--------------------------------------------------------------------------------
/Linked List/Circular Linked List/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include "operations.h"
3 |
4 | int main() {
5 | int choice;
6 |
7 | while (1) {
8 | printf("\n--- Circular Linked List Menu ---\n");
9 | printf("1. Create Circular Linked List\n");
10 | printf("2. Traverse Circular Linked List\n");
11 | printf("3. Insert Before\n");
12 | printf("4. Insert After\n");
13 | printf("5. Delete Element\n");
14 | printf("6. Exit\n");
15 | printf("Enter your choice: ");
16 | scanf("%d", &choice);
17 |
18 | switch (choice) {
19 | case 1:
20 | create();
21 | break;
22 | case 2:
23 | traverse();
24 | break;
25 | case 3:
26 | insertBefore();
27 | break;
28 | case 4:
29 | insertAfter();
30 | break;
31 | case 5:
32 | deleteElement();
33 | break;
34 | case 6:
35 | printf("Exiting...\n");
36 | return 0;
37 | default:
38 | printf("Invalid choice! Please try again.\n");
39 | }
40 | }
41 |
42 | return 0;
43 | }
44 |
--------------------------------------------------------------------------------
/Linked List/Circular Linked List/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Linked List/Circular Linked List/main.exe
--------------------------------------------------------------------------------
/Linked List/Circular Linked List/operations.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Linked List/Circular Linked List/operations.exe
--------------------------------------------------------------------------------
/Linked List/Doubly Linked List/Insert & deletion based on the valule.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Linked List/Doubly Linked List/Insert & deletion based on the valule.png
--------------------------------------------------------------------------------
/Linked List/Doubly Linked List/README.md:
--------------------------------------------------------------------------------
1 | # Doubly Linked List
2 |
3 | A doubly linked list is a more advanced data structure than a singly linked list, where each node contains a reference to both the next and the previous node in the sequence.
4 |
5 |
6 |

7 |
8 |
9 | ## Features
10 |
11 | - Dynamic size
12 | - Efficient insertion and deletion at both ends
13 | - Bidirectional traversal (forward and backward)
14 |
15 | ## Basic Operations
16 |
17 | 1. Insertion
18 | - At the beginning
19 | - At the end
20 | - At a specific position
21 |
22 | 2. Deletion
23 | - From the beginning
24 | - From the end
25 | - From a specific position
26 |
27 | 3. Traversal
28 | - Print all elements (forward and backward)
29 |
30 | 4. Search
31 | - Find an element by value
32 |
33 | ## Structure of a Doubly Linked List Node
34 | Each node in a doubly linked list consists of:
35 | 1. **Data**: The value stored in the node.
36 | 2. **Next Pointer**: A reference to the next node in the list.
37 | 3. **Previous Pointer**: A reference to the previous node in the list.
38 |
39 | ### Node Representation
40 | ```c
41 | struct Node {
42 | int data;
43 | struct Node* next;
44 | struct Node* prev;
45 | };
46 |
--------------------------------------------------------------------------------
/Linked List/Doubly Linked List/insertion deletion based the position.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Linked List/Doubly Linked List/insertion deletion based the position.png
--------------------------------------------------------------------------------
/Linked List/Doubly Linked List/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include "operations.h"
3 |
4 | int main() {
5 | int choice;
6 |
7 | while (1) {
8 | printf("\n--- Doubly Linked List Menu ---\n");
9 | printf("1. Create Circular Linked List\n");
10 | printf("2. Traverse Circular Linked List\n");
11 | printf("3. Insert Before\n");
12 | printf("4. Insert After\n");
13 | printf("5. Delete Element\n");
14 | printf("6. Exit\n");
15 | printf("Enter your choice: ");
16 | scanf("%d", &choice);
17 |
18 | switch (choice) {
19 | case 1:
20 | create();
21 | break;
22 | case 2:
23 | traverse();
24 | break;
25 | case 3:
26 | insertBefore();
27 | break;
28 | case 4:
29 | insertAfter();
30 | break;
31 | case 5:
32 | delete();
33 | break;
34 | case 6:
35 | printf("Exiting...\n");
36 | return 0;
37 | default:
38 | printf("Invalid choice! Please try again.\n");
39 | }
40 | }
41 |
42 | return 0;
43 | }
44 |
--------------------------------------------------------------------------------
/Linked List/Doubly Linked List/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Linked List/Doubly Linked List/main.exe
--------------------------------------------------------------------------------
/Linked List/Doubly Linked List/operations.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Linked List/Doubly Linked List/operations.exe
--------------------------------------------------------------------------------
/Linked List/README.md:
--------------------------------------------------------------------------------
1 | # Linked Lists
2 |
3 | 
4 |
5 | ## Overview
6 |
7 | A linked list is a linear data structure where each element is a separate object called a "node." Each node contains a reference (or link) to the next node in the sequence. Linked lists are dynamic and can grow and shrink in size by allocating and deallocating memory as needed.
8 |
9 | ## Table of Contents
10 | - [Introduction](#introduction)
11 | - [Types of Linked Lists](#types-of-linked-lists)
12 | - [Operations](#operations)
13 | - [Examples](#examples)
14 |
15 | ## Introduction
16 |
17 | A linked list is a linear data structure which is a collection of multiple nodes. Each node contains two parts: a data part and a next part, which is a pointer that contains the address of the next node. Linked lists are dynamic and can grow and shrink in size by allocating and deallocating memory as needed.
18 |
19 |
20 | ## Types of Linked Lists
21 |
22 | - **Singly Linked List**: Each node contains a single link to the next node.
23 | - **Doubly Linked List**: Each node contains links to both the next and previous nodes.
24 | - **Circular Linked List**: The last node in the list points back to the first node, forming a circular structure.
25 |
26 | ## Operations
27 |
28 | Common operations performed on linked lists include:
29 |
30 | - **Insertion**: Adding a new node at the beginning, end, or middle of the list.
31 | - **Deletion**: Removing a node from the list.
32 | - **Traversal**: Visiting each node in the list.
33 | - **Search**: Finding a node with a specific value.
34 |
35 | ## Examples
36 |
37 | - **Reverse a Linked List**: Reverse the order of nodes in a linked list.
38 | - **Detect a Cycle**: Check if the linked list contains a cycle (loop).
39 |
--------------------------------------------------------------------------------
/Linked List/Singly Linked List/C/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include "operations.h"
4 |
5 | int main()
6 | {
7 | // create linked list
8 | create();
9 |
10 | // traverse
11 | // traverse();
12 |
13 | // middleNode
14 | // printf("\n ELemenet ; %d" , middleNode());
15 |
16 | // start = reverse(start);
17 |
18 | traverse();
19 | deleteNode(3);
20 | traverse();
21 | return 0;
22 | }
--------------------------------------------------------------------------------
/Linked List/Singly Linked List/C/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Linked List/Singly Linked List/C/main.exe
--------------------------------------------------------------------------------
/Linked List/Singly Linked List/C/middleElement/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Linked List/Singly Linked List/C/middleElement/main.exe
--------------------------------------------------------------------------------
/Linked List/Singly Linked List/README.md:
--------------------------------------------------------------------------------
1 | # Singly Linked List
2 |
3 | A singly linked list is a fundamental data structure in computer science, consisting of a sequence of elements where each element points to the next one in the sequence.
4 |
5 |
6 |

7 |
8 |
9 | ## Features
10 |
11 | - Dynamic size
12 | - Efficient insertion and deletion at the beginning
13 | - Sequential access to elements
14 |
15 | ## Basic Operations
16 |
17 | 1. Insertion
18 | - At the beginning
19 | - At the end
20 | - At a specific position
21 |
22 | 2. Deletion
23 | - From the beginning
24 | - From the end
25 | - From a specific position
26 |
27 | 3. Traversal
28 | - Print all elements
29 |
30 | 4. Search
31 | - Find an element by value
32 | ## Structure of a Singly Linked List Node
33 | Each node in a singly linked list consists of:
34 | 1. **Data**: The value stored in the node.
35 | 2. **Next Pointer**: A reference to the next node in the list.
36 |
37 | ### Node Representation
38 | ```c
39 | struct Node {
40 | int data;
41 | struct Node* next;
42 | };
43 |
44 |
--------------------------------------------------------------------------------
/Linked List/problems/Swapping/README.md:
--------------------------------------------------------------------------------
1 | # Swapping Two Variables Using XOR in C
2 |
3 | This project demonstrates how to swap two variables using the XOR bitwise operation in **C**, without using a third variable. The XOR technique allows us to swap values efficiently without the need for extra memory.
4 |
5 |
6 |

7 |
8 |
9 |
10 | ## How XOR Works
11 |
12 | The XOR (Exclusive OR) operation is a bitwise operator that compares two bits:
13 | - If the bits are different, the result is `1`.
14 | - If the bits are the same, the result is `0`.
15 |
16 | Using this property, we can swap two variables without the need for a third variable. The process for swapping two variables `A` and `B` is as follows:
17 |
18 | 1. Perform the operation: `A = A ^ B`.
19 | 2. Then, perform: `B = A ^ B` (this gives the original value of `A` to `B`).
20 | 3. Finally, perform: `A = A ^ B` (this assigns the original value of `B` to `A`).
21 |
22 | ## Example Code in C
23 |
24 | ```c
25 | #include
26 |
27 | int main() {
28 | int A = 5, B = 10;
29 |
30 | // Display initial values
31 | printf("Before swapping: A = %d, B = %d\n", A, B);
32 |
33 | // XOR swap logic
34 | A = A ^ B; // A now holds A ^ B
35 | B = A ^ B; // B now holds the original value of A
36 | A = A ^ B; // A now holds the original value of B
37 |
38 | // Display swapped values
39 | printf("After swapping: A = %d, B = %d\n", A, B);
40 |
41 | return 0;
42 | }
43 |
44 | Output :
45 |
46 | Before swapping: A = 5, B = 10
47 | After swapping: A = 10, B = 5
48 |
49 |
--------------------------------------------------------------------------------
/Linked List/problems/Swapping/main.c:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | int main()
4 | {
5 | int a = 10;
6 | int b = 20;
7 |
8 | printf("Before swapping : a= %d , b = %d " , a , b);
9 |
10 |
11 | a = a ^ b; // ^ : this sign is XOR
12 | b = b ^ a;
13 | a = a ^ b;
14 | printf("After swapping : a = %d , b = %d" , a , b);
15 |
16 | return 0;
17 | }
--------------------------------------------------------------------------------
/Linked List/problems/Swapping/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Linked List/problems/Swapping/main.exe
--------------------------------------------------------------------------------
/Linked List/problems/Swapping/swapping image.PNG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Linked List/problems/Swapping/swapping image.PNG
--------------------------------------------------------------------------------
/Linked List/problems/polynomial/Readme.md:
--------------------------------------------------------------------------------
1 | # Polynomial Operations in C
2 |
3 | This program implements polynomial operations using a linked list representation in C. It allows users to create polynomials, display them, and perform addition of two polynomials.
4 |
5 | ## Visual Representation
6 |
7 | The following image illustrates the concept of polynomial addition:
8 |
9 | 
10 |
11 | *Image source: GeeksforGeeks*
12 |
13 | ## Features
14 |
15 | - Create polynomials by entering terms (coefficient and power)
16 | - Display polynomials in a readable format
17 | - Add two polynomials
18 |
19 | ## Data Structure
20 |
21 | The program uses a linked list to represent polynomials. Each node in the list contains:
22 | - Coefficient (integer)
23 | - Power (integer)
24 | - Pointer to the next term
25 |
26 | ## Functions
27 |
28 | 1. `createNode`: Creates a new node for a polynomial term
29 | 2. `createPolynomial`: Allows user to input a polynomial
30 | 3. `displayPolynomial`: Displays a polynomial in standard algebraic notation
31 | 4. `addPolynomials`: Adds two polynomials and returns the result
32 |
33 | ## Limitations
34 |
35 | - The program assumes input polynomials are in descending order of power
36 | - It does not handle floating-point coefficients
37 |
38 | ## Future Improvements
39 |
40 | - Implement polynomial multiplication
41 | - Add support for floating-point coefficients
42 | - Implement polynomial division
43 | - Add error handling for invalid inputs
44 | - Implement memory deallocation to prevent memory leaks
45 |
46 | ## Contributing
47 |
48 | Feel free to fork this project and submit pull requests with improvements or additional features.
49 |
50 | ## License
51 |
52 | This project is open source and available under the [MIT License](LICENSE).
--------------------------------------------------------------------------------
/Linked List/problems/polynomial/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include "operations.h"
3 | int main()
4 | {
5 | start1 = create(start1);
6 | start2 = create(start2);
7 |
8 | add();
9 | displayPolynomial(result);
10 |
11 | result = NULL;
12 | subtract();
13 | displayPolynomial(result);
14 |
15 | return 0;
16 | }
--------------------------------------------------------------------------------
/Linked List/problems/polynomial/polynomial.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Linked List/problems/polynomial/polynomial.png
--------------------------------------------------------------------------------
/Linked List/problems/sparse matrix/Readme.md:
--------------------------------------------------------------------------------
1 | # Sparse Matrix Program
2 |
3 | This program demonstrates the creation and display of a **sparse matrix** using linked lists in C. A sparse matrix is a matrix that contains a large number of zero elements. Instead of storing all elements (including zeros), this program efficiently stores and represents only the non-zero elements using a list of lists.
4 |
5 | ## Features
6 | - **Sparse Matrix Creation**: The program allows you to create a sparse matrix by specifying the number of non-zero elements for each row, along with their column positions and values.
7 | - **Display Sparse Matrix**: The sparse matrix is displayed in its original matrix form, filling in zero values for elements that are not explicitly stored.
8 |
9 | ## Example
10 | Here's how a sparse matrix is represented in memory using a list of lists:
11 |
12 | 
13 |
14 | ## How it Works
15 | 1. **Structure Definition**: The program uses a `Node` structure to store the column index, data (value), and the pointer to the next non-zero element in the row.
16 | 2. **Matrix Creation**: Users input the number of rows and columns, and specify the non-zero elements for each row.
17 | 3. **Matrix Display**: The sparse matrix is displayed with appropriate spacing, showing zeroes in the positions where no value is stored.
18 |
19 | ## Code Structure
20 | - `createNode(int col, int data)`: Creates a new node to store non-zero elements.
21 | - `createSparseMatrix(struct Node** A, int m, int n)`: Creates the sparse matrix by taking user input for non-zero values.
22 | - `displaySparseMatrix(struct Node** A, int m, int n)`: Displays the sparse matrix in its full form, filling zeroes where necessary.
23 |
24 | ## Usage
25 | 1. Compile the program:
26 | ```bash
27 | gcc sparse_matrix.c -o sparse_matrix
28 | ```
29 | 2. Run the program:
30 | ```bash
31 | ./sparse_matrix
32 | ```
33 | 3. Input the number of rows, columns, and the non-zero elements to create and display the sparse matrix.
34 |
35 | ## Conclusion
36 | This program offers an efficient way to handle sparse matrices, reducing memory usage by storing only the non-zero elements using linked lists.
--------------------------------------------------------------------------------
/Linked List/problems/sparse matrix/main.c:
--------------------------------------------------------------------------------
1 | // sparse matrix
2 | #include
3 | #include "operations.h"
4 |
5 |
6 | int main()
7 | {
8 | int m , n;
9 | printf("Enter the dimension for sparse matrix : ");
10 | scanf("%d %d" , &m , &n);
11 |
12 | struct Node *A[m];
13 |
14 | // Create sparse matrix
15 | createSparseMatrix(A , m , n);
16 |
17 | // display sparse matrix
18 | displaySparseMatrix(A , m , n);
19 | return 0;
20 | }
21 |
--------------------------------------------------------------------------------
/Linked List/problems/sparse matrix/operations.h:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | struct Node {
5 | int col;
6 | int data;
7 | struct Node *next;
8 | };
9 |
10 | struct Node *createNode(int col , int data){
11 | struct Node *temp = (struct Node *)malloc(sizeof(struct Node));
12 | temp->col = col;
13 | temp->data = data;
14 | temp->next = NULL;
15 |
16 | return temp;
17 | }
18 |
19 | // create
20 | void createSparseMatrix(struct Node** A , int m , int n){
21 | struct Node *last ,*newNode;
22 | int nz, col , value;
23 |
24 | for(int i = 0 ; inext = newNode;
39 | last =newNode;
40 | }
41 | }
42 | }
43 | }
44 |
45 | // display
46 | void displaySparseMatrix(struct Node **A , int m , int n){
47 | struct Node *temp;
48 | printf("Sparse matrix representation:\n");
49 | for(int i = 0 ; i < m ; i++){
50 | temp = A[i];
51 | for(int j = 0 ; j< n; j++){
52 | if(temp != NULL && j == temp->col){
53 | printf(" %d " , temp->data);
54 | temp = temp->next;
55 | }else{
56 | printf(" 0 ");
57 | }
58 | }
59 | printf("\n");
60 | }
61 | }
--------------------------------------------------------------------------------
/Linked List/problems/sparse matrix/sparse matrix represenation.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Linked List/problems/sparse matrix/sparse matrix represenation.png
--------------------------------------------------------------------------------
/Queue/Array/Circular/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | struct Queue{
5 | int size;
6 | int front;
7 | int rear;
8 | int *Q;
9 | };
10 |
11 | // time complexity : O(1)
12 | void enqueue(struct Queue *q , int x){
13 | if((q->rear +1) %q->size == q->front ){
14 | printf("Queue is full.");
15 | }else{
16 | // to iterate cicularary
17 | q->rear = (q->rear +1 ) % q->size;
18 | q->Q[q->rear] = x;
19 | }
20 | }
21 |
22 | // time complexity : O(1)
23 | int dequeue(struct Queue *q){
24 | int x = -1;
25 | if(q->rear == q->front){
26 | printf("Queue is empty.");
27 | }else{
28 | // to iterate cicularary
29 | q->front = (q->front + 1)% q->size;
30 | x = q->Q[q->front];
31 | }
32 |
33 | return x;
34 | }
35 |
36 | void display(struct Queue *q){
37 | if(q->rear == q->front){
38 | printf("Queue is empty.");
39 | return;
40 | }
41 | // to iterate cicularly
42 | int i = q->front +1;
43 | while( i != (q->rear + 1) % q->size){
44 | printf("\nElement : %d" , q->Q[i]);
45 | i = (i+1) % q->size;
46 | }
47 | }
48 |
49 |
50 |
51 | int main(){
52 | struct Queue q;
53 | printf("Enter the size of the queue : ");
54 | scanf("%d" , &q.size);
55 |
56 | // initialize q's front and rear
57 | q.front = q.rear = 0;
58 |
59 | q.Q = (int *)malloc(q.size * sizeof(int));
60 | int value, choice , x;
61 | while(1){
62 | printf("\nEnter your choice : ");
63 | printf("\n1.Enqueue \n2.Dequeue \n3.Display \n4.Exit\n");
64 | scanf("%d" , &choice);
65 | switch (choice)
66 | {
67 | case 1:
68 | printf("Enter the element to insert : ");
69 | scanf("%d" ,&value);
70 | enqueue(&q , value);
71 | break;
72 | case 2:
73 | x = dequeue(&q);
74 | if(x !=-1){
75 | printf("\n %d element is deleted from the queue.\n" , x);
76 | }
77 | break;
78 | case 3:
79 | display(&q);
80 | break;
81 | case 4:
82 | exit(0);
83 |
84 | default:
85 | printf("\n Invalid choice.\n");
86 | break;
87 | }
88 | }
89 |
90 | return 0;
91 | }
--------------------------------------------------------------------------------
/Queue/Array/Circular/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Queue/Array/Circular/main.exe
--------------------------------------------------------------------------------
/Queue/Array/linear/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | struct Queue{
5 | int size;
6 | int front;
7 | int rear;
8 | int *Q;
9 | };
10 |
11 | void enqueue(struct Queue *q , int data){
12 | if(q->rear == q->size-1){
13 | printf("Queue is full.");
14 | }else{
15 | q->rear++;
16 | q->Q[q->rear] = data;
17 | }
18 | }
19 |
20 | int dequeue(struct Queue *q){
21 | int x = -1;
22 |
23 | if(q->front == q->rear){
24 | printf("Queue is empty.");
25 | }else{
26 | q->front++;
27 | x = q->Q[q->front];
28 | }
29 | return x;
30 | }
31 |
32 | void display(struct Queue *q) {
33 | if (q->front == q->rear) {
34 | printf("Queue is empty\n");
35 | return;
36 | }
37 |
38 | // Use a temporary index to iterate through the queue
39 | int i = q->front + 1;
40 |
41 | printf("Queue elements: ");
42 | while (i <= q->rear) {
43 | printf("%d ", q->Q[i]);
44 | i++;
45 | }
46 | printf("\n");
47 | }
48 |
49 | int main(){
50 | // Initialization of Queue
51 | struct Queue q;
52 | // printf("Enter the size of the queue : ");
53 | // scanf("%d" , &q.size);
54 | q.size = 7;
55 | q.Q = (int *)malloc(q.size * sizeof(int));
56 | q.front = q.rear = -1;
57 |
58 | enqueue(&q , 10);
59 | enqueue(&q , 20);
60 | enqueue(&q , 30);
61 | enqueue(&q , 40);
62 |
63 | display(&q);
64 |
65 | dequeue(&q);
66 | dequeue(&q);
67 | dequeue(&q);
68 | dequeue(&q);
69 |
70 | display(&q);
71 |
72 | return 0;
73 | }
--------------------------------------------------------------------------------
/Queue/Array/linear/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Queue/Array/linear/main.exe
--------------------------------------------------------------------------------
/Queue/LinkedLilst/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | struct Node{
5 | int data;
6 | struct Node *next;
7 | }*front = NULL , *rear = NULL;
8 |
9 | struct Node *newNode(int x){
10 | struct Node *temp = (struct Node*)malloc(sizeof(struct Node));
11 | if(temp==NULL){
12 | printf("Queue is full");
13 | }
14 | temp->data = x;
15 | temp->next = NULL;
16 | return temp;
17 | }
18 |
19 | // time complexity : O(1);
20 | void enqueue(int x){
21 | struct Node *nNode = newNode(x);
22 |
23 | // first Node
24 | if(front == NULL){
25 | front = rear = nNode;
26 | }else{
27 | rear->next = nNode;
28 | rear = nNode;
29 | }
30 | }
31 |
32 | // time complexity : O(1);
33 | int dequeue(){
34 | int x=-1;
35 | struct Node *temp;
36 | if(front == NULL){
37 | printf("Queue is empty.");
38 | }else{
39 | temp = front;
40 | front = front->next;
41 | x = temp->data;
42 | free(temp);
43 | }
44 | return x;
45 | }
46 |
47 | void display(){
48 | struct Node *temp = front;
49 | if(front == NULL){
50 | printf("Queue is empty");
51 | }
52 | while(temp!=NULL){
53 | printf("\n Element : %d" , temp->data);
54 | temp=temp->next;
55 | }
56 | }
57 |
58 | int main(){
59 | int value, choice , x;
60 | while(1){
61 | printf("\nEnter your choice : ");
62 | printf("\n1.Enqueue \n2.Dequeue \n3.Display \n4.Exit\n");
63 | scanf("%d" , &choice);
64 | switch (choice)
65 | {
66 | case 1:
67 | printf("Enter the element to insert : ");
68 | scanf("%d" ,&value);
69 | enqueue(value);
70 | break;
71 | case 2:
72 | x = dequeue();
73 | if(x !=-1){
74 | printf("\n %d element is deleted from the queue.\n" , x);
75 | }
76 | break;
77 | case 3:
78 | display();
79 | break;
80 | case 4:
81 | exit(0);
82 |
83 | default:
84 | printf("\n Invalid choice.\n");
85 | break;
86 | }
87 | }
88 | return 0;
89 | }
--------------------------------------------------------------------------------
/Queue/LinkedLilst/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Queue/LinkedLilst/main.exe
--------------------------------------------------------------------------------
/Queue/Priority Queue/Array/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Queue/Priority Queue/Array/main.exe
--------------------------------------------------------------------------------
/Queue/Priority Queue/Array/priority queue.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Queue/Priority Queue/Array/priority queue.png
--------------------------------------------------------------------------------
/Queue/Priority Queue/LinkedList/main.c:
--------------------------------------------------------------------------------
1 | // 10 / 2 , 20/ 1 , 30/1 , 40 /2 , 100/3
2 | // 20 / 1 , 30 /1 , 10/2 , 40/2 , 100/3
3 |
4 | #include
5 | #include
6 |
7 | struct Node{
8 | int data;
9 | int priority;
10 | struct Node *next;
11 | }*front = NULL;
12 |
13 | struct Node *newNode(int data , int priority){
14 | struct Node *temp = (struct Node*)malloc(sizeof(struct Node));
15 | if(temp == NULL){
16 | printf("Queue is full");
17 | }
18 | temp->data = data;
19 | temp->priority = priority;
20 | temp->next = NULL;
21 |
22 | return temp;
23 | }
24 |
25 | int isEmpty(){
26 | return (front == NULL) ? 1 : 0;
27 | }
28 |
29 | void enqueue(int value , int priority){
30 | struct Node *temp,*prev , *nNode = newNode(value , priority);
31 | temp = front;
32 | // If the queue is empty or the new node has higher priority than the front
33 | if(front == NULL || nNode->priority < front->priority){
34 | nNode->next = front;
35 | front = nNode;
36 | }else{
37 | while(temp != NULL && nNode->priority >= temp->priority){
38 | prev = temp;
39 | temp = temp->next;
40 | }
41 | // Insert the new node after prev
42 | prev->next = nNode;
43 | nNode->next = temp;
44 | }
45 | }
46 |
47 | int dequeue(){
48 | struct Node *temp = front;
49 | int x = -1;
50 | if(isEmpty()){
51 | printf("Queue is empty.");
52 | }else{
53 | x = temp->data;
54 | front = front->next;
55 | free(temp);
56 | }
57 |
58 | return x;
59 | }
60 |
61 | void display(){
62 | struct Node *temp = front;
63 | while(temp!=NULL){
64 | printf("%d " , temp->data);
65 | temp = temp->next;
66 | }
67 | printf("\n");
68 | }
69 |
70 | int main(){
71 |
72 | enqueue(10 , 2);
73 | enqueue(20 , 1);
74 | enqueue(30 , 1);
75 | enqueue(40 , 2);
76 | enqueue(100 , 3);
77 | display();
78 |
79 | dequeue();
80 | dequeue();
81 | dequeue();
82 |
83 | display();
84 |
85 |
86 | return 0;
87 | }
88 |
89 |
--------------------------------------------------------------------------------
/Queue/Priority Queue/LinkedList/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Queue/Priority Queue/LinkedList/main.exe
--------------------------------------------------------------------------------
/Queue/Stack/a.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Queue/Stack/a.exe
--------------------------------------------------------------------------------
/Queue/Stack/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Queue/Stack/main.exe
--------------------------------------------------------------------------------
/Search/BinarySearch/main.c:
--------------------------------------------------------------------------------
1 | //Binary Search
2 | #include
3 |
4 | int binarySearch(int *a,int size,int element)
5 | {
6 | int low,high,mid;
7 | low=0;
8 | high=size-1;
9 | while(low<=high)
10 | {
11 | mid=(low+high)/2;
12 | if(a[mid]==element)
13 | {
14 | return mid;
15 | }
16 | if(a[mid]
6 |
7 |
8 |
9 | ### Time and Space Complexity
10 |
11 | | **Algorithm** | **Time Complexity** | **Space Complexity** |
12 | |-------------------|---------------------|----------------------|
13 | | **Binary Search** | O(log n) | O(1) |
14 |
--------------------------------------------------------------------------------
/Search/FibonacciSearch/main.c:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | int FibonacciSearch(int A[] , int n , int key){
4 | // Generate Fibonacci Sequence until F(k) >= n
5 | int fibk_2 = 0; // f(k-2);
6 | int fibk_1 = 1; // f(k-1);
7 | int fibk = fibk_1 + fibk_2;
8 |
9 | while(fibk < n){
10 | fibk_2 = fibk_1;
11 | fibk_1 = fibk;
12 | fibk = fibk_1 + fibk_2;
13 | }
14 |
15 | // initialzie variable
16 | int offset = -1; // offset for the index
17 | int i;
18 |
19 | while(fibk > 1){
20 | // Calculate the index to be checked
21 | i = (offset + fibk_2 < n-1) ? offset + fibk_2 : n-1; // finding the min index
22 |
23 | // Compare with the target element
24 | if(A[i] == key){
25 | return i;
26 | }else if(key > A[i]){
27 | // Move left in the Fibonacci sequence k = k-1
28 | fibk = fibk_1;
29 | fibk_1 = fibk_2;
30 | fibk_2 = fibk - fibk_1;
31 | offset = i;
32 | }else {
33 | // Move two steps left in the Fibonacci sequence k = k-2
34 | fibk = fibk_2;
35 | fibk_1 = fibk_1 - fibk_2;
36 | fibk_2 = fibk - fibk_1;
37 | }
38 | }
39 |
40 | // checking the last element manually
41 | if(fibk_1 && offset+1 < n && A[offset +1 ] == key){
42 | return offset + 1;
43 | }
44 |
45 | return -1; // unseccussfull search
46 | }
47 |
48 |
49 | int main(){
50 | int A[] = {5 , 6 , 7 , 8 , 9};
51 | int n = sizeof(A) / sizeof(A[0]);
52 |
53 | int result = FibonacciSearch(A , n , 9);
54 |
55 | if(result == -1){
56 | printf("%d" , result);
57 | }else{
58 | printf("%d" , result);
59 | }
60 | return 0;
61 | }
--------------------------------------------------------------------------------
/Search/LinearSearch/Readme.md:
--------------------------------------------------------------------------------
1 | # Linear Search
2 |
3 | Linear Search is a simple search algorithm that checks each element of a list sequentially until it finds the target or reaches the end of the list.
4 |
5 |
6 |
7 |
8 |
9 | ### Time and Space Complexity
10 |
11 | | **Algorithm** | **Time Complexity** | **Space Complexity** |
12 | |--------------------|---------------------|----------------------|
13 | | **Linear Search** | O(n) | O(1) |
14 |
--------------------------------------------------------------------------------
/Search/LinearSearch/main.c:
--------------------------------------------------------------------------------
1 | //Linear Search
2 | #include
3 |
4 | int linearSearch(int *a,int size,int element)
5 | {
6 | for(int i=0;i
6 |
7 |
8 |
9 | ## Linear Search
10 | Linear Search is a simple algorithm that checks every element in the list sequentially until it finds the target or reaches the end.
11 |
12 | ### Time and Space Complexity
13 |
14 | | **Algorithm** | **Time Complexity** | **Space Complexity** |
15 | |--------------------|---------------------|----------------------|
16 | | **Linear Search** | O(n) | O(1) |
17 |
18 | ## Binary Search
19 | Binary Search is a more efficient algorithm than Linear Search. It works on sorted arrays and repeatedly divides the search interval in half.
20 |
21 | ### Time and Space Complexity
22 |
23 | | **Algorithm** | **Time Complexity** | **Space Complexity** |
24 | |--------------------|---------------------|----------------------|
25 | | **Binary Search** | O(log n) | O(1) |
26 |
--------------------------------------------------------------------------------
/Tree/AVL/Node height.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Tree/AVL/Node height.png
--------------------------------------------------------------------------------
/Tree/AVL/README.md:
--------------------------------------------------------------------------------
1 | # AVL Trees
2 |
3 | ## Introduction
4 | An AVL tree is a self-balancing binary search tree where the difference in heights between the left and right subtrees (the balance factor) is at most 1 for every node. This property ensures that the tree remains approximately balanced, providing efficient performance for operations such as insertion, deletion, and lookup.
5 |
6 | ## Properties of AVL Trees
7 | 1. **Balance Factor**: For any node in the AVL tree, the balance factor is defined as:
8 | \[
9 | \text{Balance Factor} = \text{Height of Left Subtree} - \text{Height of Right Subtree}
10 | \]
11 | The balance factor can be -1, 0, or 1.
12 |
13 | 2. **Height-Balancing**: The AVL tree maintains its balance by performing rotations during insertions and deletions.
14 |
15 | ## AVL Tree Rotations
16 | When the balance factor becomes greater than 1 or less than -1 after an insertion or deletion, rotations are performed to restore the balance.
17 |
18 | ### Types of Rotations
19 | 1. **Single Right Rotation**
20 | 2. **Single Left Rotation**
21 | 3. **Left-Right Rotation**
22 | 4. **Right-Left Rotation**
23 |
24 | ## AVL Tree Insertion
25 | When inserting a node into an AVL tree, the following steps are followed:
26 | 1. Insert the node as you would in a regular binary search tree.
27 | 2. Update the heights of the ancestors of the newly inserted node.
28 | 3. Check the balance factors of the ancestors.
29 | 4. Perform the appropriate rotation(s) if necessary.
30 |
31 | ### AVL Tree Insertion Example
32 |
33 |
34 | 
35 |
36 |
37 |
38 | In the image above, we can see the process of inserting nodes into an AVL tree and how rotations are applied to maintain balance.
39 |
40 | ## Conclusion
41 | AVL trees are crucial for maintaining sorted data and ensuring efficient data retrieval. They offer better performance than unbalanced trees, especially in scenarios with frequent insertions and deletions.
42 |
--------------------------------------------------------------------------------
/Tree/AVL/Rotation/LLRotation.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Tree/AVL/Rotation/LLRotation.png
--------------------------------------------------------------------------------
/Tree/AVL/Rotation/LRRotation.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Tree/AVL/Rotation/LRRotation.png
--------------------------------------------------------------------------------
/Tree/AVL/Rotation/RLRotation.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Tree/AVL/Rotation/RLRotation.png
--------------------------------------------------------------------------------
/Tree/AVL/Rotation/RRRotation.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Tree/AVL/Rotation/RRRotation.png
--------------------------------------------------------------------------------
/Tree/AVL/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Tree/AVL/main.exe
--------------------------------------------------------------------------------
/Tree/BST/BST Quiz.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Tree/BST/BST Quiz.png
--------------------------------------------------------------------------------
/Tree/BST/Delete.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Tree/BST/Delete.png
--------------------------------------------------------------------------------
/Tree/BST/DeleteIterative.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Tree/BST/DeleteIterative.png
--------------------------------------------------------------------------------
/Tree/BST/Depth of a node.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Tree/BST/Depth of a node.png
--------------------------------------------------------------------------------
/Tree/BST/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | # Binary Search Tree (BST)
4 |
5 |

6 |
7 |
8 |
9 | ## Overview
10 | A Binary Search Tree (BST) is a data structure that enables efficient searching, insertion, and deletion of values. In a BST, each node has at most two children: the left child contains values less than the parent node, and the right child contains values greater than the parent node.
11 |
12 | ## Operations
13 |
14 | ### 1. Insertion
15 | - **Iterative Insert**: Insert a new node into the BST using an iterative approach.
16 | - **Recursive Insert**: Insert a new node using a recursive method.
17 |
18 | ### 2. Traversal
19 | - **PreOrder Traversal**: Visit nodes in the order of Root → Left → Right.
20 | - **InOrder Traversal**: Visit nodes in the order of Left → Root → Right.
21 | - **PostOrder Traversal**: Visit nodes in the order of Left → Right → Root.
22 |
23 | ### 3. Searching
24 | - **Iterative Search**: Search for a specific key using an iterative method.
25 | - **Recursive Search**: Search for a specific key using recursion.
26 |
27 | ### 4. Deletion
28 | - **Delete**: Remove a node from the BST while maintaining its properties.
29 | - **Delete Iterative**: Delete a node from the BST using an iterative approach.
30 |
31 | ### 5. Additional Functions
32 | - **Height**: Calculate the height of the BST.
33 | - **Inorder Predecessor**: Find the largest node in the left subtree of a given node.
34 | - **Inorder Successor**: Find the smallest node in the right subtree of a given node.
35 | - **Generate Tree from PreOrder**: Create a BST from a given preorder traversal.
36 | - **Mirror**: Create a mirror image of the BST.
37 |
38 | ## Usage
39 | Follow the menu prompts in the code to perform operations on the BST. You can insert values, traverse the tree, search for elements, delete nodes, and more.
40 |
--------------------------------------------------------------------------------
/Tree/BST/find min and max element.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Tree/BST/find min and max element.png
--------------------------------------------------------------------------------
/Tree/BST/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Tree/BST/main.exe
--------------------------------------------------------------------------------
/Tree/BST/practice of delete iterative.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Tree/BST/practice of delete iterative.png
--------------------------------------------------------------------------------
/Tree/BST/stack.h:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | // Structure for stack
5 | struct Stack {
6 | int size;
7 | int top;
8 | struct Node **s; // Array of pointers to tree nodes
9 | };
10 |
11 | // Stack operations
12 | void createStack(struct Stack *st , int size) {
13 | st->size = size;
14 | st->top = -1;
15 | st->s = (struct Node **)malloc(st->size * sizeof(struct Node *));
16 | }
17 |
18 | // Check if stack is empty
19 | int isStackEmpty(struct Stack *st) {
20 | return (st->top == -1);
21 | }
22 |
23 | // Return top element of the stack
24 | struct Node* stackTop(struct Stack *st) {
25 | return isStackEmpty(st) ? NULL : st->s[st->top];
26 | }
27 |
28 | // Check if stack is full
29 | int isStackFull(struct Stack *st) {
30 | return (st->top == st->size - 1);
31 | }
32 |
33 | // Push a node onto the stack
34 | void push(struct Stack *st, struct Node *value) {
35 | if (!isStackFull(st)) {
36 | st->top++;
37 | st->s[st->top] = value;
38 | } else {
39 | printf("\nStack is full.\n");
40 | }
41 | }
42 |
43 | // Pop a node from the stack
44 | struct Node* pop(struct Stack *st) {
45 | struct Node *value = NULL;
46 | if (!isStackEmpty(st)) {
47 | value = st->s[st->top];
48 | st->top--;
49 | } else {
50 | printf("\nStack is empty!\n");
51 | }
52 | return value;
53 | }
54 |
--------------------------------------------------------------------------------
/Tree/Binary Tree/Binary Tree representation.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Tree/Binary Tree/Binary Tree representation.png
--------------------------------------------------------------------------------
/Tree/Binary Tree/README.md:
--------------------------------------------------------------------------------
1 | # Binary Tree
2 |
3 | A **Binary Tree** is a tree data structure in which each node has at most two children referred to as the left child and the right child. It is one of the simplest forms of hierarchical data structures used in computer science.
4 |
5 |
6 |
7 |
8 |
9 | ## Overview
10 |
11 | In a Binary Tree, each node contains:
12 | - A data element
13 | - A pointer to the left child node
14 | - A pointer to the right child node
15 |
16 | The tree starts at a root node, and each node can have a left and/or right child, recursively creating the structure of the tree.
17 |
18 | ## Operations
19 |
20 | The following operations are supported for the **Binary Tree**:
21 |
22 | 1. **Node Creation**
23 | Creating a new node that contains data and points to `NULL` for its left and right children.
24 |
25 | 2. **Insertion**
26 | Inserting a node at the correct position based on certain rules (e.g., level order insertion).
27 |
28 | 3. **Traversal**
29 | Traversing the binary tree in different ways:
30 | - Inorder (Left, Root, Right)
31 | - Preorder (Root, Left, Right)
32 | - Postorder (Left, Right, Root)
33 | - Level Order (Breadth-First)
34 |
35 | 4. **Searching**
36 | Finding a node in the tree by comparing the data in each node with the target data.
37 |
38 | 5. **Counting Nodes**
39 | Counting the total number of nodes present in the binary tree.
40 |
41 | 6. **Height/Depth of the Tree**
42 | Determining the height or depth of the binary tree, which is the longest path from the root to a leaf node.
43 |
44 | 7. **Deletion**
45 | Removing a node from the tree while maintaining the structure.
46 |
47 | 8. **Level Order Traversal using Queue**
48 | Performing level order traversal (Breadth-First Search) using a queue to visit nodes level by level.
49 |
50 | ## Additional Information
51 |
52 | Binary Trees are fundamental in computer science and are used in various applications such as searching, sorting, and hierarchical data representation.
53 |
--------------------------------------------------------------------------------
/Tree/Binary Tree/height & level.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/Tree/Binary Tree/height & level.png
--------------------------------------------------------------------------------
/Tree/Binary Tree/operations.h:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | // Node structure for Binary Tree
5 | struct Node {
6 | struct Node *lChild;
7 | int data;
8 | struct Node *rChild;
9 | };
10 |
11 | // Creation of a Node
12 | struct Node* createNode(int data){
13 | struct Node *temp = (struct Node*)malloc(sizeof(struct Node));
14 | temp->data = data;
15 | temp->lChild = NULL;
16 | temp->rChild = NULL;
17 |
18 | return temp;
19 | }
20 |
21 | struct Queue{
22 | int size;
23 | int front;
24 | int rear;
25 | struct Node **Q; // bcoz it stores address of the tree node
26 | };
27 |
28 | void createQ(struct Queue *q , int size){
29 | q->size = size;
30 | q->front = q->rear = 0;
31 | q->Q = (struct Node **)malloc(q->size * sizeof(struct Node *));
32 | }
33 |
34 | void enqueue(struct Queue *q , struct Node* data){
35 | if(q->rear == q->size-1){
36 | printf("Queue is full.");
37 | }else{
38 | q->rear++;
39 | q->Q[q->rear] = data;
40 | }
41 | }
42 |
43 | struct Node * dequeue(struct Queue *q){
44 | struct Node * x = NULL;
45 |
46 | if(q->front == q->rear){
47 | printf("Queue is empty.");
48 | }else{
49 | q->front++;
50 | x = q->Q[q->front];
51 | }
52 | return x;
53 | }
54 |
55 | int isEmpty(struct Queue *q){
56 | return (q->front == q->rear) ? 1 : 0;
57 | }
58 |
59 | int count(struct Node *p){
60 | if(p){
61 | return count(p->lChild) + count(p->rChild) + 1;
62 | }
63 | return 0;
64 | }
--------------------------------------------------------------------------------
/Tree/Binary Tree/stack.h:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | // Structure for stack
5 | struct Stack {
6 | int size;
7 | int top;
8 | struct Node **s; // Array of pointers to tree nodes
9 | };
10 |
11 | // Stack operations
12 | void createStack(struct Stack *st , int size) {
13 | st->size = size;
14 | st->top = -1;
15 | st->s = (struct Node **)malloc(st->size * sizeof(struct Node *));
16 | }
17 |
18 | // Check if stack is empty
19 | int isStackEmpty(struct Stack *st) {
20 | return (st->top == -1);
21 | }
22 |
23 | // Check if stack is full
24 | int isStackFull(struct Stack *st) {
25 | return (st->top == st->size - 1);
26 | }
27 |
28 | // Push a node onto the stack
29 | void push(struct Stack *st, struct Node *value) {
30 | if (!isStackFull(st)) {
31 | st->top++;
32 | st->s[st->top] = value;
33 | } else {
34 | printf("\nStack is full.\n");
35 | }
36 | }
37 |
38 | // Pop a node from the stack
39 | struct Node* pop(struct Stack *st) {
40 | struct Node *value = NULL;
41 | if (!isStackEmpty(st)) {
42 | value = st->s[st->top];
43 | st->top--;
44 | } else {
45 | printf("\nStack is empty!\n");
46 | }
47 | return value;
48 | }
49 |
--------------------------------------------------------------------------------
/Tree/README.md:
--------------------------------------------------------------------------------
1 | ## Tree Data Structures
2 |
3 | A **Tree** is a widely used data structure that simulates a hierarchical tree structure, with a root value and subtrees of children represented as a set of linked nodes.
4 |
5 |
6 |
7 |
8 |
9 | ### Types of Trees Implemented
10 |
11 | - **Binary Tree**
12 | A tree data structure in which each node has at most two children referred to as the left child and the right child.
13 |
14 | - **Binary Search Tree (BST)**
15 | A binary tree in which all the left descendants of a node are smaller than the node, and all the right descendants are larger.
16 |
17 | - **AVL Tree**
18 | A self-balancing binary search tree where the difference between heights of left and right subtrees cannot be more than one for all nodes.
19 |
20 | ### Operations
21 |
22 | 1. **Creation**
23 | - Inserting nodes into the tree (starting from the root).
24 | - Defining rules for left and right children based on the type of tree (binary, BST, AVL).
25 |
26 | 2. **Traversal**
27 | - **Inorder**: Left, Root, Right
28 | - **Preorder**: Root, Left, Right
29 | - **Postorder**: Left, Right, Root
30 | - **Level Order Traversal**
31 |
32 | 3. **Search**
33 | - Searching for a node in the tree using Binary Search (in the case of BST).
34 |
35 | 4. **Insertion**
36 | - Adding new nodes to the tree, maintaining the properties of the specific tree (BST, AVL, etc.).
37 |
38 | 5. **Deletion**
39 | - Removing nodes from the tree, ensuring that the tree's properties remain intact after deletion.
40 |
41 | 6. **Rotation** (for AVL Tree)
42 | - **Single Rotation** (Left or Right)
43 | - **Double Rotation** (Left-Right or Right-Left)
44 |
45 | 7. **Balancing** (for AVL Tree)
46 | - Re-balancing the tree after insertions or deletions to maintain height balance.
47 |
48 | ### Usage
49 |
50 | You can find implementations of these tree structures in the respective directories:
51 |
52 | - [Binary Tree](./Tree/Binary%20Tree)
53 | - [Binary Search Tree (BST)](./Tree/BST)
54 | - [AVL Tree](./Tree/AVL)
55 |
56 | Explore the source code to understand how each operation is implemented.
57 |
--------------------------------------------------------------------------------
/notes/Data Structure.docx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/notes/Data Structure.docx
--------------------------------------------------------------------------------
/recursion/example.js:
--------------------------------------------------------------------------------
1 | // Types of Recursion :
2 |
3 | // 1. Tail Recursion
4 | // 2. Head Recursion
5 | // 3. Tree Recursion
6 | // 4. Indirect Recursion
7 | // 5. Nested Recursion
8 |
9 | // function tail(n){ // recursive function
10 | // if(n > 0 ){
11 | // console.log(n); //
12 |
13 | // tail(n-1); // recursive call
14 | // }
15 | // }
16 |
17 |
18 | // tail : when a recursive function call itself and that recursive call is the last statement , then it is called as "Tail Recursion".
19 |
20 | // Time complexity : O(n);
21 | // Space complexity : O(n);
22 |
23 | // tail(3);
24 | // output : 3 2 1
25 |
26 | // function head(n){
27 | // if(n > 0 ){
28 | // head(n-1);
29 | // console.log(n);
30 |
31 | // }
32 | // }
33 | // head(3);
34 |
35 | // output : 1 2 3
36 |
37 | // Head recursion : it is a function that doesn't have to perform any operation & process at the time of calling. It has to do all the operations and process at the time of returning so these functions are called "Head recursions";
38 |
39 | // Time complexity : O(n);
40 | // Space complexity : O(n);
41 |
42 | // Recursion vs loop
43 | // Recursion : Ascending and descending
44 | // Loop : Ascending
45 |
46 |
47 | // function factorial(n){
48 | // let fact = 1;
49 | // for(let i = 1 ; i<=n ; i++){
50 | // fact *= i;
51 | // }
52 |
53 | // return fact;
54 | // }
55 |
56 | // console.log(factorial(3));
57 |
58 |
59 | function factorial(n){
60 | if(n > 0){
61 | return factorial(n-1) * n;
62 | }
63 |
64 | return 1;
65 | }
66 | console.log(factorial(3));
67 |
--------------------------------------------------------------------------------
/recursion/global.js:
--------------------------------------------------------------------------------
1 | // Local variable.
2 | // function recursive(n){
3 | // if(n > 0){
4 | // return recursive(n-1) * n;
5 | // }
6 |
7 | // return 1;
8 | // }
9 |
10 | // console.log(recursive(3));
11 |
12 | // Global variable
13 | let x = 0;
14 |
15 | // function recursive(n){
16 | // if(n > 0){
17 | // ++x;
18 | // return recursive(n-1) * x;
19 | // }
20 |
21 | // return 1;
22 | // }
23 | // console.log(recursive(3));
24 |
25 | // Time Complexity : O(n);
26 | // Space complexity : O(1);
--------------------------------------------------------------------------------
/recursion/head.js:
--------------------------------------------------------------------------------
1 | function recursive(n){
2 | if(n > 0){
3 | recursive(n-1);
4 | console.log(n);
5 | }
6 | }
7 |
8 | let x = 3;
9 | recursive(x);
10 |
11 | // output : 3 2 1
--------------------------------------------------------------------------------
/recursion/indirect.js:
--------------------------------------------------------------------------------
1 | function A(n){
2 | if(n > 0){
3 | console.log(n);
4 |
5 | B(n-1);
6 | }
7 | }
8 |
9 | function B(n){
10 | if(n > 0){
11 | console.log(n);
12 | A(parseInt(n/2));
13 | }
14 | }
15 |
16 | A(20);
17 | //20 19 9 8 4 3 1
--------------------------------------------------------------------------------
/recursion/linear.js:
--------------------------------------------------------------------------------
1 | function recursive(n){
2 | if(n>0){
3 | console.log(n);
4 |
5 | recursive(n-1); // linear recursion
6 |
7 | console.log(n);
8 | }
9 | }
10 |
11 | // Linear Recursion : It is a function which is called after some process and before some process is called linear recursion. Which is called only one time.
12 |
13 | recursive(3);
--------------------------------------------------------------------------------
/recursion/nested.js:
--------------------------------------------------------------------------------
1 | function nested(n){ // T(n);
2 | if(n > 100){ // 1
3 | return n-10; // 1
4 | }else {
5 | return nested(nested(n+11)); // recursive call // T(T(n+11))
6 | }
7 | }
8 |
9 | console.log(nested(95));
10 |
11 | // Definition : If a recursive function is passed as a parameter in a recursive call then it is called as "Nested Recursion".
12 |
13 | // Time Complexity : O(n) Bcoz it is linear.
14 |
15 | // Space Complexity : O(n)
16 |
17 | // output : 91
18 |
--------------------------------------------------------------------------------
/recursion/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "recursion",
3 | "version": "1.0.0",
4 | "main": "tail.js",
5 | "scripts": {
6 | "test": "echo \"Error: no test specified\" && exit 1"
7 | },
8 | "author": "",
9 | "license": "ISC",
10 | "keywords": [],
11 | "description": ""
12 | }
13 |
--------------------------------------------------------------------------------
/recursion/programs/Factorial.js:
--------------------------------------------------------------------------------
1 | function factorial(n){
2 | if( n > 0){
3 | return factorial(n-1) * n;
4 | }
5 | return 1;
6 | }
7 |
8 | console.log(factorial(3)); // 6
9 |
10 |
--------------------------------------------------------------------------------
/recursion/programs/Fibonacci.js:
--------------------------------------------------------------------------------
1 |
2 | // let n = parseInt(process.argv[2]); // convert string to int
3 |
4 | // let first = 0;
5 | // let second = 1;
6 |
7 | // let s = first + " " + second;
8 |
9 | // if (n === 0) {
10 | // console.log([]);
11 | // return;
12 | // }
13 |
14 | // if (n == 1){
15 | // console.log(s.substring(0,1));
16 | // return;
17 | // }
18 |
19 | // // first second nextNum
20 | // // 3 => 0 1 1
21 |
22 | // let nextNum = first + second; // 1
23 |
24 | // for (let i = 3; i <= n; i++) {
25 | // s = s + " " + nextNum;
26 | // first = second;
27 | // second = nextNum;
28 | // nextNum = first + second;
29 | // }
30 |
31 | // if (n >= 2) {
32 | // console.log(s);
33 | // }
34 |
35 |
36 | // 0 => []
37 | // 1 => [0]
38 | // 2 => [0 , 1] sequence =
39 | // 3 => [0 1 1]
40 | // 4 => [0 1 1 2]
41 |
42 | // let s = "0 1";
43 | // let first = 0;
44 | // let second = 1;
45 | // let nextNum;
46 |
47 | // let n = parseInt(process.argv[2]);
48 |
49 | // if(n <=0){
50 | // console.log("Enter a positive number.");
51 | // }else if(n === 1 ){
52 | // console.log(s.substring(0 ,1));
53 | // } else {
54 | // console.log(fibonacci(n-2));
55 | // }
56 |
57 | // function fibonacci(n){
58 | // if(n > 0){
59 | // nextNum = first +second;
60 | // s = s + " "+nextNum;
61 | // first = second;
62 | // second = nextNum;
63 | // fibonacci(n-1);
64 | // }
65 | // return s;
66 | // }
67 |
68 | let F = []; // it is used to store values which is return by the fib function
69 | // THis is the concept of memoziation which increases the performance of function.
70 | // It is used to avoid excessive recursion;
71 | // Excessive recursion is a function which is called multiple times for the same parameter.
72 |
73 |
74 | // function fib(n){
75 | // if(n<=1){
76 | // F[n] = n;
77 | // return n;
78 | // }
79 | // return fib(n-2) + fib(n-1);
80 | // }
81 |
82 | function fib(n){
83 | if(n<=1){
84 | F[n] = n;
85 | return n;
86 | }else{
87 | if(!F[n-2]){
88 | F[n-2] = fib(n-2);
89 | }
90 | if(!F[n-1]){
91 | F[n-1] = fib(n-1);
92 | }
93 | return F[n-2] + F[n-1];
94 | }
95 | }
96 |
97 | console.log(fib(parseInt(process.argv[2])));
98 |
--------------------------------------------------------------------------------
/recursion/programs/Sum of digits.js:
--------------------------------------------------------------------------------
1 | function foo(n, sum) {
2 | let k = 0, j = 0;
3 | if (n === 0) return;
4 |
5 | k = n % 10;
6 | j = parseInt(n / 10);
7 | sum = sum + k;
8 | foo(j, sum);
9 | console.log(k);
10 | }
11 |
12 | let a = 2048, sum = 0;
13 | foo(a, sum);
14 |
15 | console.log(sum);
--------------------------------------------------------------------------------
/recursion/programs/TOH.js:
--------------------------------------------------------------------------------
1 | function TOH(n, A, B, C) {
2 | if (n > 0) {
3 | TOH(n-1, A, C, B);
4 | console.log("From " + A + " to " + C);
5 | TOH(n-1 , B , A , C);
6 | }
7 | }
8 |
9 |
10 | TOH(parseInt(process.argv[2]) , 1 , 2 , 3);
--------------------------------------------------------------------------------
/recursion/programs/combination.js:
--------------------------------------------------------------------------------
1 | function fact(n){
2 | if(n===0) return 1;
3 | return fact(n-1) *n;
4 | }
5 |
6 | function nCr(n , r){
7 | let num = fact(n);
8 | let den = fact(r) * fact(n-r);
9 |
10 | return num/den;
11 | }
12 |
13 | // function c(n, r) {
14 | // if (r === 0 || n === r) {
15 | // return 1;
16 | // } else {
17 | // return c(n - 1, r - 1) + c(n - 1, r);
18 | // }
19 | // }
20 |
21 | console.log(nCr(5 , 3));
--------------------------------------------------------------------------------
/recursion/programs/power of a number.js:
--------------------------------------------------------------------------------
1 | // let base = 2;
2 | // let exponent = 3;
3 |
4 | // let power = 1;
5 | // for(let i = 1 ; i <=exponent ; i++){
6 | // power *= base;
7 | // }
8 |
9 | // console.log(power);
10 |
11 | // 2 ^ 3 = 2 -> base & 3 -> exponent
12 | // 2 * 2 * 2
13 | // power = 1;
14 | // power * = base;
15 | // 1 * 2 = 2
16 | // 2 * 2 = 4
17 | // 4 * 2 = 8
18 |
19 | // 0 -> 1
20 |
21 |
22 | function power(exponent , base){
23 | if(exponent > 0 ){
24 | return power(exponent - 1 , base) * base;
25 | }
26 | return 1;
27 | }
28 |
29 | console.log(power(3 , 2));
30 |
31 | // 3 , 2
32 | // power(3 , base) -> 4 * 2 = 8
33 | // power(2 , base) -> 2 * 2 = 4
34 | // power(1 , base) -> 1 * 2 = 2
35 | // power(0 , base) -> 1
--------------------------------------------------------------------------------
/recursion/programs/quiz5.js:
--------------------------------------------------------------------------------
1 | let d = 1;
2 | function count(n){
3 | console.log(n);
4 | console.log(d);
5 | d++;
6 | if(n > 1) count(n-1);
7 | console.log(d);
8 | }
9 |
10 | count(3);
11 |
12 |
--------------------------------------------------------------------------------
/recursion/programs/sum of natural numbers.js:
--------------------------------------------------------------------------------
1 | // let sum = 0 ;
2 | // for(let i = 1 ; i <= 2 ; i++ ){
3 | // sum+= i;
4 | // }
5 |
6 | // console.log(sum);
7 |
8 | // 2 = 1+2
9 | // 3 = 1+ 2 + 3
10 |
11 | function sumOfN(n){
12 | if(n > 0){
13 | return sumOfN(n-1) + n;
14 | }
15 |
16 | return 0;
17 | }
18 |
19 | console.log(sumOfN(3));
20 |
21 | // Time complexity : O(n);
22 | // space complexity : o(n);
--------------------------------------------------------------------------------
/recursion/programs/taylor series e^x.js:
--------------------------------------------------------------------------------
1 | // Taylor series e^x
2 |
3 | // e^x = 1 + x^1 / !1 + x^2 / !2 + x^3 / !3 + x^4 / !4 -- n terms
4 |
5 | let p = 1; // power
6 | let f = 1; // factorial
7 | let result;
8 |
9 | function e(x , n){
10 | if(n === 0 ){
11 | return 1;
12 | }else{
13 | result = e(x , n-1);
14 | p = p * x;
15 | f = f * n;
16 | return result + p/f;
17 | }
18 | }
19 |
20 | console.log(e(1, 4).toFixed(2));
--------------------------------------------------------------------------------
/recursion/programs/taylor series.js:
--------------------------------------------------------------------------------
1 | let s =1;
2 |
3 | function e(x , n){
4 | while(n > 0){
5 | s = 1 + x/n *s;
6 | e(x , n-1);
7 | return s;
8 | }
9 | return s;
10 | }
11 |
12 | console.log(e(1, 4).toFixed(2));
13 |
--------------------------------------------------------------------------------
/recursion/tail.js:
--------------------------------------------------------------------------------
1 | function recursive(n){
2 | if(n > 0){
3 | console.log(n);
4 | recursive(n-1);
5 | }
6 | }
7 |
8 | let x = 3;
9 | recursive(x);
10 |
11 | // output : 3 2 1
--------------------------------------------------------------------------------
/recursion/tree.js:
--------------------------------------------------------------------------------
1 | function tree(n){
2 | if(n > 0 ){
3 | console.log(n);
4 | tree(n-1); // Recursive call
5 |
6 | tree(n-1); // Recursive call
7 | }
8 | }
9 |
10 | tree(5);
11 |
12 | // Tree recursion : When a recursive function is called more than one time this recursive function is called "Tree Recursion".
13 |
14 | // output : 3 , 2 , 1 , 1 , 2 , 1 , 1
15 |
16 |
--------------------------------------------------------------------------------
/sorting algo/Bubble/bubble.js:
--------------------------------------------------------------------------------
1 | function bubbleSort(a) {
2 | let temp;
3 | for (let i = 0; i < a.length - 1; i++) {
4 | for (let j = i + 1; j < a.length - 1; j++) {
5 | if (a[j] > a[i]) {
6 | temp = a[j];
7 | a[j] = a[i];
8 | a[i] = temp;
9 | }
10 | }
11 | }
12 | return a;
13 | }
14 |
15 | let a = [20 , 30 ,1 , 2 , 4];
16 | console.log(bubbleSort(a));
--------------------------------------------------------------------------------
/sorting algo/Count/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | int findMax(int A[] , int n){
5 | int max =0, i;
6 | for(i = 0 ; i< n;i++){
7 | if(A[i] > max){
8 | max = A[i];
9 | }
10 | }
11 | return max;
12 | }
13 |
14 | void CountSort(int A[] , int n){
15 | int max ,i , j;
16 | int *C;
17 |
18 | // find max
19 | max = findMax(A , n);
20 | // create count as the max element
21 | C = (int *)malloc(sizeof(int) *max+1);
22 |
23 | // initialize count array as empty (0)
24 | for(i = 0 ; i < max+1 ; i++)
25 | C[i] = 0;
26 |
27 | // store frequency/count of elements in A
28 | for(i = 0 ; i < n ; i++){
29 | C[A[i]]++;
30 | }
31 |
32 | // retrieve all the elements from count by decrementing count
33 | i = 0 ,j = 0;
34 | while(i < max +1){
35 | if(C[i] > 0){
36 | A[j++] = i;
37 | C[i]--;
38 | }else {
39 | i++;
40 | }
41 | }
42 | }
43 |
44 | int main()
45 | {
46 | int A[] = {11 , 3 , 10 , 15 , 5, 4 , 5 , 7 , 1 , 2} , n = 10 ,i;
47 |
48 | CountSort(A , n);
49 |
50 | for(i = 0 ; i
2 |
3 |
4 | void Insertion(int A[] , int n){
5 | int x,i,j;
6 | for(i = 1 ; i-1 && A[j] > x){
10 | // first shifting
11 | A[j+1] = A[j];
12 | j--;
13 | }
14 | A[j+1] =x;
15 | }
16 | }
17 |
18 |
19 | int main()
20 | {
21 | int A[] = {11 , 3 , 10 , 15 , 5, 4 , 5 , 7 , 1 , 2} , n = 10 ,i;
22 |
23 | Insertion(A , n);
24 |
25 | for(i = 0 ; i
2 |
3 | void Merge(int A[] , int l , int mid , int h){
4 | int i , k , j;
5 | int B[100]; // auxiliary array
6 | i = l , j = mid+1 , k = l;
7 |
8 | while(i <= mid && j <= h){
9 | if(A[i] < A[j])
10 | B[k++] = A[i++];
11 | else
12 | B[k++] = A[j++];
13 | }
14 |
15 | // get all remaining elements from the array
16 | for(; i <=mid ; i++){
17 | B[k++] = A[i];
18 | }
19 | for(; j<=h ; j++){
20 | B[k++] = A[i];
21 | }
22 |
23 | // copy all elements from B to A
24 | for(i = 0; i <= h ; i++){
25 | A[i] = B[i];
26 | }
27 | }
28 |
29 | void MergeSort(int A[] , int l , int h){
30 | int mid;
31 | // atleast two elements should be there
32 | if(l < h){
33 | mid = (l+h)/2; // calc mid
34 | // left list MergeSort
35 | MergeSort(A , l ,mid);
36 | //right list MergeSort
37 | MergeSort(A , mid+1 , h);
38 | //perform merging
39 | Merge(A , l , mid , h);
40 | }
41 | }
42 |
43 | int main()
44 | {
45 | int A[] = {11 , 3 , 10 , 15 , 5, 4 , 5 , 7 , 1 , 2} , n = 10 ,i;
46 |
47 | MergeSort(A , 0 , n-1);
48 |
49 | for(i = 0 ; i
6 |
7 |
8 |
9 | ## How Merge Sort Works
10 | 1. **Divide**: Split the array into two halves.
11 | 2. **Conquer**: Recursively sort each half.
12 | 3. **Merge**: Combine the sorted halves into a single sorted array.
13 |
14 | ## Example
15 | Consider an array `[38, 27, 43, 3, 9, 82, 10]`. Using merge sort:
16 | 1. Split into `[38, 27, 43, 3]` and `[9, 82, 10]`.
17 | 2. Continue splitting until single-element arrays are obtained.
18 | 3. Merge back step by step until the array is fully sorted: `[3, 9, 10, 27, 38, 43, 82]`.
19 |
20 | ## Time and Space Complexity
21 |
22 | | **Complexity** | **Best Case** | **Average Case** | **Worst Case** |
23 | |----------------|---------------|------------------|----------------|
24 | | **Time** | O(n log n) | O(n log n) | O(n log n) |
25 | | **Space** | O(n) | O(n) | O(n) |
26 |
--------------------------------------------------------------------------------
/sorting algo/Quick/QuickSort.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | void swap(int *x, int *y)
5 | {
6 | int t = *x;
7 | *x = *y;
8 | *y = t;
9 | }
10 |
11 | int partition(int a[], int l, int h)
12 | {
13 | int povit = a[l]; //first element as pivot
14 | int i = l, j = h;
15 |
16 | do
17 | {
18 | do
19 | {
20 | i++;
21 | } while (a[i] <= povit);
22 | do
23 | {
24 | j--;
25 | } while (a[j] > povit);
26 |
27 | if (i < j) // i should be less than j
28 | {
29 | swap(&a[i], &a[j]);
30 | }
31 |
32 | } while (i < j);
33 |
34 | swap(&a[l], &a[j]); // swap pivot with jth element
35 |
36 | return j; // partitioning position
37 | }
38 |
39 | void QuickSort(int a[], int l, int h)
40 | {
41 | int j;
42 | if (l < h)
43 | {
44 | j = partition(a, l, h); // here j was missing
45 | QuickSort(a, l, j);
46 | QuickSort(a, j + 1, h);
47 | }
48 | }
49 |
50 | int main()
51 | {
52 | int a[100], n, i;
53 | printf("\n ENter size of array");
54 | scanf("%d", &n);
55 |
56 | for (i = 0; i < n; i++)
57 | {
58 | printf(" ENter a[%d]", i);
59 | scanf("%d", &a[i]);
60 | }
61 |
62 | printf("\n Elements before sorting\n");
63 |
64 | for (i = 0; i < n; i++)
65 | {
66 | printf(" %d", a[i]);
67 | }
68 |
69 | QuickSort(a, 0, n);
70 |
71 | printf("\n Elements after sorting\n");
72 |
73 | for (i = 0; i < n; i++)
74 | {
75 | printf(" %d", a[i]);
76 | }
77 | }
--------------------------------------------------------------------------------
/sorting algo/Quick/QuickSort.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/sorting algo/Quick/QuickSort.exe
--------------------------------------------------------------------------------
/sorting algo/Quick/Readme.md:
--------------------------------------------------------------------------------
1 | # Quick Sort
2 |
3 | Quick Sort is a divide-and-conquer algorithm. It picks an element as a pivot and partitions the given array around the pivot. The array is then recursively sorted on either side of the pivot.
4 |
5 |
6 |
7 |
8 |
9 | ## How Quick Sort Works
10 | 1. **Choose a pivot**: Select an element from the array (commonly the last element) as the pivot.
11 | 2. **Partition**: Rearrange the array so that elements smaller than the pivot are on the left, and elements larger are on the right.
12 | 3. **Recursively sort**: Recursively apply the same process to the left and right subarrays.
13 |
14 | ## Example
15 | Consider the array `[10, 80, 30, 90, 40, 50, 70]` and choosing 70 as the pivot:
16 | 1. Partition the array around 70: `[10, 30, 40, 50, 70, 90, 80]`.
17 | 2. Recursively sort the left and right subarrays: `[10, 30, 40, 50]` and `[80, 90]`.
18 | 3. Final sorted array: `[10, 30, 40, 50, 70, 80, 90]`.
19 |
20 | ## Time and Space Complexity
21 |
22 | | **Complexity** | **Best Case** | **Average Case** | **Worst Case** |
23 | |----------------|---------------|------------------|----------------|
24 | | **Time** | O(n log n) | O(n log n) | O(n²) |
25 | | **Space** | O(log n) | O(log n) | O(n) |
26 |
--------------------------------------------------------------------------------
/sorting algo/Selection/Readme.md:
--------------------------------------------------------------------------------
1 | # Selection Sort
2 |
3 | Selection Sort is a simple comparison-based sorting algorithm. It repeatedly selects the minimum (or maximum) element from the unsorted portion of the array and swaps it with the first unsorted element.
4 |
5 |
6 |
7 |
8 |
9 | ## How Selection Sort Works
10 | 1. **Find the minimum element**: Traverse the entire unsorted part of the array and find the minimum element.
11 | 2. **Swap**: Swap the found minimum element with the first element of the unsorted part.
12 | 3. **Repeat**: Move the boundary of the sorted and unsorted parts of the array by one and repeat the process until the entire array is sorted.
13 |
14 | ## Example
15 | Consider the array `[64, 25, 12, 22, 11]`:
16 | 1. Find the minimum (11), and swap it with the first element: `[11, 25, 12, 22, 64]`.
17 | 2. Find the minimum of the remaining array (12), and swap it with the second element: `[11, 12, 25, 22, 64]`.
18 | 3. Continue this process until the entire array is sorted: `[11, 12, 22, 25, 64]`.
19 |
20 | ## Time and Space Complexity
21 |
22 | | **Complexity** | **Best Case** | **Average Case** | **Worst Case** |
23 | |----------------|---------------|------------------|----------------|
24 | | **Time** | O(n²) | O(n²) | O(n²) |
25 | | **Space** | O(1) | O(1) | O(1) |
26 |
--------------------------------------------------------------------------------
/sorting algo/Selection/SelectionSort.c:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | void swap(int *i , int *k){
4 | int temp = *i;
5 | *i = *k;
6 | *k = temp;
7 | }
8 |
9 | void Selection(int A[] , int n){
10 | int i , j , k;
11 |
12 | for(i = 0; i < n-1;i++){
13 | for(j = k =i; j< n; j++){
14 | if(A[j] < A[k]) // find min element
15 | k = j;
16 | }
17 | // after finding smallest element swap ith and kth element
18 | swap(&A[i] , &A[k]);
19 | }
20 | }
21 |
22 |
23 | int main()
24 | {
25 | int A[] = {11 , 3 , 10 , 15 , 5, 4 , 5 , 7 , 1 , 2} , n = 10 ,i;
26 |
27 | Selection(A , n);
28 |
29 | for(i = 0 ; i
2 | #include "operations.h"
3 |
4 | int main(){
5 | char prefix[] = "+*54/67";
6 |
7 | int result= eval(prefix);
8 |
9 | if(result){
10 | printf("Evaluation of prefix %s : %d" , prefix , result);
11 | }
12 | return 0;
13 | }
--------------------------------------------------------------------------------
/stack/Evaluation of prefix/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/stack/Evaluation of prefix/main.exe
--------------------------------------------------------------------------------
/stack/Evaluation of prefix/operations.h:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | struct Stack {
6 | int top;
7 | int size;
8 | int *s;
9 | };
10 |
11 | int isEmpty(struct Stack *st){
12 | return (st->top ==-1) ? 1: 0;
13 | }
14 |
15 | int isFull(struct Stack *st){
16 | return (st->top == st->size-1) ? 1 : 0;
17 | }
18 |
19 | void push(struct Stack *st , int x){
20 | if(isFull(st)){
21 | printf("Stack is full");
22 | }else{
23 | st->top++;
24 | st->s[st->top] = x;
25 | }
26 | }
27 |
28 | int pop(struct Stack *st){
29 | int x = -1;
30 | if(!isEmpty(st)){
31 | x = st->s[st->top--];
32 | }else{
33 | printf("Stack is empty");
34 | }
35 | return x;
36 | }
37 |
38 | int isOperand(char x){
39 | if(x == '+' || x == '-' || x == '/' || x == '*'){
40 | return 0;
41 | }
42 | return 1;
43 | }
44 |
45 | int eval(char *prefix){
46 | struct Stack st;
47 | st.size = strlen(prefix);
48 | st.top = -1;
49 | st.s = (int *)malloc(st.size * sizeof(int));
50 |
51 | int i, x1 , x2 , r;
52 | for(i = strlen(prefix) -1 ; i >=0 ; i--){
53 | if(isOperand(prefix[i])){
54 | push(&st , prefix[i] - '0');
55 | }else{
56 | x1 = pop(&st); x2 = pop(&st);
57 | switch (prefix[i])
58 | {
59 | case '+':
60 | r = x1 +x2;
61 | push(&st , r);
62 | break;
63 | case '-':
64 | r = x1 -x2;
65 | push(&st , r);
66 | break;
67 | case '/':
68 | if (x2 != 0) {
69 | r = x1 / x2; // Integer division
70 | } else {
71 | printf("Error: Division by zero\n");
72 | return -1; // Handle division by zero error
73 | }
74 | push(&st , r);
75 |
76 | break;
77 | case '*':
78 | r = x1 *x2;
79 | push(&st , r);
80 | break;
81 |
82 | default:
83 | printf("Invalid case.");
84 | break;
85 | }
86 | }
87 | }
88 |
89 | return pop(&st);
90 | }
--------------------------------------------------------------------------------
/stack/infix to postfix/infixToPostfixAsso.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/stack/infix to postfix/infixToPostfixAsso.exe
--------------------------------------------------------------------------------
/stack/infix to postfix/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | struct Stack{
6 | int size;
7 | int top;
8 | char *s;
9 | }st;
10 |
11 | int isEmpty(){
12 | return (st.top == -1) ? 1 : 0;
13 | }
14 |
15 | int isFull(){
16 | return (st.top == st.size-1) ? 1 : 0;
17 | }
18 |
19 | void push(char x){
20 | if(!isFull()){
21 | st.top++;
22 | st.s[st.top] = x;
23 | }else {
24 | printf("Stack is full");
25 | }
26 | }
27 |
28 | int pop(){
29 | char x;
30 | if(!isEmpty()){
31 | x = st.s[st.top];
32 | st.top--;
33 | }else {
34 | return -1;
35 | }
36 | }
37 |
38 | int stackTop(){
39 | if(st.top == -1){
40 | return -1;
41 | }
42 | return st.s[st.top];
43 | }
44 |
45 | int isOperand(char x){
46 | if(x == '+' || x=='-' || x=='*' || x=='/'){
47 | return 0;
48 | }
49 | return 1;
50 | }
51 |
52 | int pre(char x){
53 | if( x == '+' || x == '-'){
54 | return 1;
55 | }else if(x == '*' || x == '/'){
56 | return 2;
57 | }
58 | return 0;
59 | }
60 |
61 | char *convert(char *infix){
62 |
63 | // initialization of stack
64 | st.size = strlen(infix);
65 | st.top = -1;
66 | st.s = (char *)malloc(st.size * sizeof(char));
67 |
68 | char *postfix = (char *)malloc(strlen(infix)+1);
69 | int i = 0 , j= 0;
70 |
71 | while(infix[i]!='\0'){
72 | if(isOperand(infix[i])){
73 | postfix[j++] = infix[i++];
74 | }else{
75 | if(pre(infix[i]) > pre(stackTop())){
76 | push(infix[i++]);
77 | }else {
78 | postfix[j++] = pop();
79 | }
80 | }
81 | }
82 |
83 | while(!isEmpty()){
84 | postfix[j++] = pop();
85 | }
86 |
87 | postfix[j] = '\0';
88 |
89 | return postfix;
90 | }
91 |
92 |
93 | int main(){
94 | char exp[] = "a+b*c-d/e";
95 |
96 | printf("%s" , convert(exp));
97 | return 0;
98 | }
99 |
--------------------------------------------------------------------------------
/stack/infix to postfix/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/stack/infix to postfix/main.exe
--------------------------------------------------------------------------------
/stack/infix to postfix/mainInfixToPostfix.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | struct Stack{
6 | int size;
7 | int top;
8 | char *s;
9 | };
10 |
11 | int isEmpty(struct Stack *st){
12 | return (st->top == -1) ? 1 : 0;
13 | }
14 |
15 | int isFull(struct Stack *st){
16 | return (st->top == st->size-1) ? 1: 0;
17 | }
18 |
19 | int peek(struct Stack *st){
20 | if(st->top == -1){
21 | return -1;
22 | }else{
23 | return st->s[st->top];
24 | }
25 | }
26 |
27 | void push(struct Stack *st , char x){
28 | if(!isFull(st)){
29 | st->top++;
30 | st->s[st->top] = x;
31 | }else{
32 | printf("Stack is full!");
33 | }
34 | }
35 |
36 | int pop(struct Stack *st){
37 | if(!isEmpty(st)){
38 | return st->s[st->top--];
39 | }else{
40 | return -1;
41 | }
42 | }
43 |
44 | int isOperand(char x){
45 | if(x == '+' || x =='-' || x=='*' || x=='/'){
46 | return 0; // false
47 | }
48 | return 1;
49 | }
50 |
51 | int pre(char x){
52 | if(x == '+' || x =='-' ){
53 | return 1;
54 | }else if( x=='*' || x=='/'){
55 | return 2;
56 | }else {
57 | return 0;
58 | }
59 | }
60 |
61 | char *convert(char *infix){
62 | // stack initialization
63 | struct Stack st;
64 | st.size = strlen(infix);
65 | st.top = -1;
66 | st.s = (char *)malloc(st.size * sizeof(char));
67 |
68 | char *postfix = (char *)malloc(strlen(infix));
69 |
70 | int i = 0 , j = 0;
71 |
72 | while(infix[i]!='\0'){
73 | if(isOperand(infix[i])){
74 | postfix[j++] = infix[i++];
75 | }else if(pre(infix[i]) > pre(peek(&st))){
76 | push(&st , infix[i++]);
77 | }else{
78 | postfix[j++] = pop(&st);
79 | }
80 | }
81 |
82 | while(!isEmpty(&st)){
83 | postfix[j++] = pop(&st);
84 | }
85 |
86 | postfix[j] = '\0';
87 |
88 | return postfix;
89 |
90 | }
91 |
92 | int main(){
93 | char infix[] = "a+b*c-d/e";
94 |
95 | printf("%s" ,convert(infix));
96 |
97 |
98 | return 0;
99 | }
--------------------------------------------------------------------------------
/stack/infix to postfix/mainInfixToPostfix.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/stack/infix to postfix/mainInfixToPostfix.exe
--------------------------------------------------------------------------------
/stack/infix to postfix/tempCodeRunnerFile.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/stack/infix to postfix/tempCodeRunnerFile.exe
--------------------------------------------------------------------------------
/stack/infix to prefix/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include "operations.h"
4 |
5 | int main(){
6 | char exp[] = "a+b*c/d";
7 | printf("Prefix expression : %s" , convert(exp));
8 | char str[20] = "mam";
9 |
10 | // printf("Enter your string : ");
11 | // scanf("%s" , str);
12 | // if(palindrome(str)){
13 | // printf("\npalindrome!");
14 | // }else{
15 | // printf("\nNot palindrome");
16 | // }
17 |
18 |
19 | // using two pointer approach
20 | if(palindrome2(str)){
21 | printf("\npalindrome!");
22 | }else{
23 | printf("\nNot palindrome");
24 | }
25 | return 0;
26 | }
--------------------------------------------------------------------------------
/stack/infix to prefix/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/stack/infix to prefix/main.exe
--------------------------------------------------------------------------------
/stack/infix to prefix/operations.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/stack/infix to prefix/operations.exe
--------------------------------------------------------------------------------
/stack/linkedlist.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | struct Node{
5 | int data;
6 | struct Node *next;
7 | }*top=NULL;
8 |
9 | struct Node *newNode(int data){
10 | struct Node *temp = (struct Node*)malloc(sizeof(struct Node));
11 | temp->next = NULL;
12 | temp->data = data;
13 |
14 | return temp;
15 | }
16 |
17 | void push(int x){
18 | struct Node *nNode;
19 |
20 | nNode = newNode(x);
21 |
22 | nNode->next = top;
23 | top = nNode;
24 | }
25 |
26 | void display(){
27 | struct Node *temp = top;
28 | if(top == NULL){
29 | printf("List is empty!");
30 | }else{
31 | while(temp!=NULL){
32 | printf("\nElement : %d",temp->data);
33 | temp = temp->next;
34 | }
35 | }
36 | }
37 |
38 |
39 | int pop(){
40 | int x =-1;
41 | struct Node *temp = top;
42 | if(top == NULL){
43 | return x;
44 | }else {
45 | x = top->data;
46 | top = top->next;
47 | free(temp);
48 |
49 | return x;
50 | }
51 | }
52 |
53 | // used to return top element
54 | int peek(){
55 | if(top == NULL){
56 | return -1;
57 | }else {
58 | return top->data;
59 | }
60 | }
61 |
62 | int main()
63 | {
64 |
65 | push(10);
66 | push(20);
67 | display();
68 |
69 | int x = pop();
70 | if (x != -1) { // Corrected the condition check
71 | printf("\nValue is deleted from stack: %d\n", x);
72 | } else {
73 | printf("\nStack is empty\n");
74 | }
75 |
76 | display(); // Display the stack after popping
77 |
78 | int topElement = peek();
79 | if(topElement!=-1){
80 | printf("\nTop element : %d" , topElement);
81 | }else{
82 | printf("\nStack is empty !");
83 | }
84 |
85 | return 0;
86 | }
--------------------------------------------------------------------------------
/stack/linkedlist.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/stack/linkedlist.exe
--------------------------------------------------------------------------------
/stack/main.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/stack/main.exe
--------------------------------------------------------------------------------
/stack/parenthesis problems/pm.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | struct Stack {
6 | int size;
7 | int top;
8 | char *s;
9 | }st;
10 |
11 | int isEmpty(){
12 | return (st.top == -1) ? 1 : 0;
13 | }
14 |
15 | int isFull(){
16 | return (st.top == st.size-1) ? 1 : 0;
17 | }
18 |
19 | void push(char value){
20 | if(!isFull()){
21 | st.top++;
22 | st.s[st.top] = value;
23 | }else {
24 | printf("Stack is full");
25 | }
26 | }
27 |
28 | int pop(){
29 |
30 | if(isEmpty()){
31 | return '\0';
32 | }else{
33 | return st.s[(st.top)--];
34 | }
35 | }
36 |
37 | int isMatching(char a , char b){
38 | if(a == '(' && b == ')'){
39 | return 1;
40 | }else if(a == '{' && b == '}'){
41 | return 1;
42 | }else if(a == '[' && b == ']'){
43 | return 1;
44 | }
45 | return 0;
46 | }
47 |
48 | int isBalanced(char *exp){
49 | st.size = strlen(exp);
50 | st.top = -1;
51 | st.s = (char *)malloc(st.size * sizeof(char));
52 | char temp;
53 | for(int i = 0 ; exp[i]!='\0' ; i++){
54 | if(exp[i] == '{' || exp[i] == '(' || exp[i] == '['){
55 | push(exp[i]);
56 | }else if(exp[i] == '}' || exp[i] == ')' || exp[i] == ')'){
57 | if(isEmpty()){
58 | return 0;
59 | }
60 | temp = pop();
61 | if(!isMatching( temp , exp[i] )){
62 | return 0;
63 | }
64 | }
65 | }
66 | // T F
67 | return isEmpty() ? 1 : 0;
68 | }
69 |
70 | int main(){
71 | char exp[] = "([a+b)*(a-b))";
72 |
73 | if(isBalanced(exp)){
74 | printf("Paranthesis Matched.");
75 | }else{
76 | printf("Not matched");
77 | }
78 | return 0;
79 | }
80 |
--------------------------------------------------------------------------------
/stack/parenthesis problems/pm.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSAAlgo987/Data-Structures-Algorithms/698f9df69a1c6ae640e05781ad62577a5d19f35b/stack/parenthesis problems/pm.exe
--------------------------------------------------------------------------------