├── .gitignore ├── GRAPH ├── .gitignore ├── .vscode │ └── settings.json ├── Adjacency_list.cpp ├── BFS.cpp ├── Cycle_Detection_Directed_BFS.cpp ├── Cycle_Detection_Directed_DFS.cpp ├── DFS.cpp ├── MInimum_Cost_Spanning_Tree │ ├── .gitignore │ ├── Disjoint-Set-Union.cpp │ ├── Kruskal_Algorithm.cpp │ └── Prims_Algorithm.cpp ├── Shortest_Path_Algorithm │ ├── .gitignore │ ├── Bellman_Ford.cpp │ ├── Dijkstras.cpp │ └── tempCodeRunnerFile.cpp ├── Topological_Sort_BFS_Kahns_Algorithm.cpp ├── Topological_Sort_DFS.cpp ├── tempCodeRunnerFile.cpp └── trial.cpp ├── LINKED_LIST ├── .gitignore ├── Circular-linked-list.c └── Singly_Linkedlist_operations.c ├── QUEUE ├── QUEUE.txt ├── Queue_CircularLL.c ├── Queue_Circular_arraystruct.c ├── Queue_array.c └── Queue_linked_list.c ├── README.md ├── SearchingTechniques ├── Binary_Search.c ├── Linear_Search.c └── Search.c ├── SortingTechniques ├── BUBBLE-SORT.c ├── INSERTION-SORT.c ├── SELECTION-SORT.c └── SHELL-SORT.c └── TREE ├── .gitignore ├── .vscode └── settings.json ├── BSTree.cpp ├── TREE.txt └── tempCodeRunnerFile.cpp /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | *.exe -------------------------------------------------------------------------------- /GRAPH/.gitignore: -------------------------------------------------------------------------------- 1 | 2 | *.exe -------------------------------------------------------------------------------- /GRAPH/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "array": "cpp", 4 | "deque": "cpp", 5 | "forward_list": "cpp", 6 | "list": "cpp", 7 | "string": "cpp", 8 | "unordered_map": "cpp", 9 | "unordered_set": "cpp", 10 | "vector": "cpp", 11 | "string_view": "cpp", 12 | "initializer_list": "cpp", 13 | "regex": "cpp", 14 | "valarray": "cpp", 15 | "ostream": "cpp", 16 | "iostream": "cpp", 17 | "*.tcc": "cpp" 18 | }, 19 | "C_Cpp.errorSquiggles": "Disabled" 20 | } -------------------------------------------------------------------------------- /GRAPH/Adjacency_list.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | void addEdge(vector adj[], int u, int v) 9 | { 10 | // push back in both the vector as they are UNDIRECTED GRAPH 11 | adj[u].push_back(v); 12 | adj[v].push_back(u); 13 | } 14 | 15 | void printGraph(vector adj[], int V) 16 | { 17 | for (int i = 0; i < V; ++i) 18 | { 19 | cout << " | " << i << " | "; 20 | for (auto x : adj[i]) // traversing on a single list[row] 21 | cout << "-> " << x; 22 | printf("\n"); 23 | } 24 | } 25 | 26 | int main() 27 | { 28 | int V = 5, i; 29 | vector adj[V]; // array of arrays (vector of vectors) --- static fixed size 30 | addEdge(adj, 0, 1); 31 | addEdge(adj, 0, 4); 32 | addEdge(adj, 1, 2); 33 | addEdge(adj, 1, 3); 34 | addEdge(adj, 1, 4); 35 | addEdge(adj, 2, 3); 36 | addEdge(adj, 3, 4); 37 | cout << "\n ************** Adjacency list of vertex ************* \n"; 38 | printGraph(adj, V); 39 | 40 | cout << "\n\n"; 41 | for (auto x : adj[1]) // traversing on a single list[row] 42 | cout << "-> " << x; 43 | 44 | return 0; 45 | } -------------------------------------------------------------------------------- /GRAPH/BFS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Graph 8 | { 9 | public: 10 | int v; 11 | int index; 12 | // vector Vertex = {"a", "b", "c", "d"}; 13 | vector> adjacency_list; // declaration --> Vecotr of Vector means 2D vector dynamic 14 | 15 | // CONSTRUCTOR 16 | Graph(int v) 17 | { 18 | index = 0; 19 | this->v = v; 20 | adjacency_list.resize(v); 21 | } 22 | 23 | /* void vertexInsert() 24 | { 25 | printf("--- Vertex of %d Nodes ---\n", v); 26 | for (auto i : Vertex) 27 | cout << i << " "; 28 | } 29 | 30 | void search(string x, string y) 31 | { 32 | int start, end, i; 33 | for (i = 0; i < Vertex.size(); i++) 34 | { 35 | if (x == Vertex[i]) 36 | start = i; 37 | else if (y == Vertex[i]) 38 | end = i; 39 | } 40 | set_edge(start, end); 41 | } */ 42 | 43 | void set_edge(int start, int end) 44 | { 45 | // cout << "set_edge running "; 46 | adjacency_list[start].push_back(end); 47 | cout << "start = " << start << "\tend = " << end << "\t value : " << adjacency_list[0][0] << "\n "; 48 | } 49 | 50 | void neighbours_show() 51 | { 52 | int k = adjacency_list[0][1]; 53 | cout << "Node in list[0][1] : " << k << endl; 54 | } 55 | 56 | void BFS(int vertex) 57 | { 58 | queue Q; 59 | // cout << adjacency_list.size(); 60 | // vector visited(adjacency_list.size()) = {0}; // vector A (10) = {0} 61 | vector visited(adjacency_list.size(), false); // vector A(10,false) + memory allocate 62 | 63 | if (!visited[vertex]) // not visited the vertex(VERTEX) 64 | { 65 | Q.push(vertex); 66 | visited[vertex] = true; 67 | } 68 | 69 | while (!Q.empty()) 70 | { 71 | // Dequeue a vertex from queue and print it 72 | vertex = Q.front(); 73 | cout << "Vertex popped from queue : " << vertex << "\n"; 74 | Q.pop(); 75 | 76 | // 1st : traversing the list of 2(2--> 0,3) 77 | for (auto i = adjacency_list[vertex].begin(); i != adjacency_list[vertex].end(); ++i) 78 | // for (auto it : adjacency_list[vertex]) 79 | { 80 | cout << "i = " << *i << endl; 81 | if (!visited[*i]) // (!true) 82 | { 83 | visited[*i] = true; 84 | Q.push(*i); 85 | } 86 | } 87 | } 88 | } 89 | }; 90 | 91 | int main() 92 | { 93 | Graph g(4); 94 | cout << "\n************************** Breath First Traversal ************************\n"; 95 | // g.vertexInsert(); 96 | 97 | g.set_edge(0, 1); // DIRECTED edge 98 | g.set_edge(0, 2); 99 | g.set_edge(1, 3); 100 | g.set_edge(2, 0); 101 | g.set_edge(2, 3); 102 | g.set_edge(3, 3); 103 | g.neighbours_show(); 104 | 105 | cout << "\nFollowing is Breadth First Traversal " 106 | << "(starting from vertex 2) \n"; 107 | g.BFS(2); 108 | 109 | return 0; 110 | } 111 | 112 | // Note : We are taking 0 ZERO indexing vector , where the 1st vertex is 0. + Directed Graph. 113 | 114 | /* 115 | Time Complexity 116 | 117 | * While () loop runs V times (total no of verices as each vertices enqueue/dequeue 1 times) 118 | * Inner Loop runs E times (adjacent edges) 119 | 120 | 121 | */ -------------------------------------------------------------------------------- /GRAPH/Cycle_Detection_Directed_BFS.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | /* TOPOLOGICAL SORT : 10 | 11 | - Store the Vertex in the adjacency list 12 | - [LOOP] Frequency calculate in inDegree vector 13 | - [LOOP] Check if (inDegree[i] == 0) ? Queue.push(i) 14 | - [LOOP] FOR BFS -----> 15 | 16 | # Time complexity: O(V + E) | Space complexity: O(V) for Stack 17 | */ 18 | 19 | class Graph 20 | { 21 | public: 22 | int index; 23 | vector> adjacency_list; // declaration --> Vecotr of Vector means 2D vector 24 | 25 | Graph(int size) 26 | { 27 | index = 0; 28 | adjacency_list.resize(size); 29 | } 30 | 31 | void set_edge(int start, int end) 32 | { 33 | adjacency_list[start].push_back(end); 34 | } 35 | 36 | bool topological_Sort_BFS() 37 | { 38 | int size = adjacency_list.size(); // total Vertex 39 | vector inDegree(size, 0); // Number of edges dirrected to it (Node) 40 | queue Q; 41 | int i, vertex, count = 0; 42 | 43 | for (i = 0; i < size; i++) 44 | { 45 | for (auto it : adjacency_list[i]) 46 | inDegree[it]++; 47 | } 48 | 49 | for (i = 0; i < size; i++) 50 | if (inDegree[i] == 0) 51 | Q.push(i); 52 | 53 | while (!Q.empty()) 54 | { 55 | vertex = Q.front(); 56 | Q.pop(); 57 | count++; 58 | cout << "Vertex popped from queue : " << vertex << "\n"; 59 | 60 | for (auto it : adjacency_list[vertex]) 61 | { 62 | inDegree[it]--; 63 | if (inDegree[it] == 0) 64 | Q.push(it); 65 | } 66 | } 67 | 68 | if (count == size) 69 | return false; 70 | else 71 | return true; 72 | } 73 | }; 74 | 75 | int main() 76 | { 77 | Graph g(6); // total number of VERTEX in the graph 78 | cout << "\n************************** Topological Sort using BFS ************************\n\n"; 79 | 80 | // g.set_edge(2, 3); 81 | // g.set_edge(3, 1); 82 | // g.set_edge(4, 0); 83 | // g.set_edge(4, 1); 84 | // g.set_edge(5, 0); 85 | // g.set_edge(5, 2); 86 | 87 | g.set_edge(0, 1); 88 | g.set_edge(1, 2); 89 | g.set_edge(2, 3); 90 | g.set_edge(3, 1); 91 | 92 | bool isCyclic = g.topological_Sort_BFS(); 93 | if (isCyclic) 94 | cout << "\nCYCLE DETECTED \n"; 95 | else 96 | cout << "\nNO CYCLE DETECTED \n"; 97 | 98 | return 0; 99 | } -------------------------------------------------------------------------------- /GRAPH/Cycle_Detection_Directed_DFS.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | /* TOPOLOGICAL SORT : 10 | 11 | - Store the Vertex in the adjacency list 12 | - [LOOP] Frequency calculate in inDegree vector 13 | - [LOOP] Check if (inDegree[i] == 0) ? Queue.push(i) 14 | - [LOOP] FOR BFS -----> 15 | 16 | # Time complexity: O(V + E) | Space complexity: O(V) for Stack 17 | */ 18 | 19 | class Graph 20 | { 21 | public: 22 | int index; 23 | vector> adjacency_list; // declaration --> Vecotr of Vector means 2D vector 24 | 25 | Graph(int size) 26 | { 27 | index = 0; 28 | adjacency_list.resize(size); 29 | } 30 | 31 | void set_edge(int start, int end) 32 | { 33 | adjacency_list[start].push_back(end); 34 | } 35 | 36 | bool DFS_CycleCheck(int vertex, vector &visited, vector &dfsCycleVisited) 37 | { 38 | visited[vertex] = true; 39 | dfsCycleVisited[vertex] = true; 40 | 41 | for (auto it : adjacency_list[vertex]) // 1 --> 2 so dfs(2) 42 | { 43 | if (!visited[it] && DFS_CycleCheck(it, visited, dfsCycleVisited)) 44 | return true; 45 | else if (dfsCycleVisited[it]) 46 | return true; 47 | } 48 | 49 | dfsCycleVisited[vertex] = false; 50 | return false; 51 | } 52 | 53 | bool isCyclic() 54 | { 55 | int i, len = adjacency_list.size(); 56 | vector visited(len, false), dfsCycleVisited(len, false); 57 | for (i = 0; i < len; i++) 58 | { 59 | if (!visited[i]) 60 | if (DFS_CycleCheck(i, visited, dfsCycleVisited)) 61 | return true; 62 | } 63 | return false; 64 | } 65 | }; 66 | 67 | int main() 68 | { 69 | Graph g(4); // total number of VERTEX in the graph 70 | cout << "\n************************** Cycle Detection using BFS ************************\n\n"; 71 | 72 | // EX - 1 73 | // g.set_edge(0, 1); 74 | // g.set_edge(1, 2); 75 | // g.set_edge(2, 3); 76 | // g.set_edge(3, 1); 77 | 78 | // EX - 2 79 | g.set_edge(0, 1); 80 | g.set_edge(0, 2); 81 | g.set_edge(1, 2); 82 | g.set_edge(2, 0); 83 | g.set_edge(2, 3); 84 | g.set_edge(3, 3); 85 | 86 | bool isCyclic = g.isCyclic(); 87 | cout << "isCyclic: " << isCyclic << endl; 88 | if (isCyclic) 89 | cout << "\n CYCLE DETECTED \n\n"; 90 | else 91 | cout << "\n NO CYCLE DETECTED \n\n"; 92 | 93 | return 0; 94 | } -------------------------------------------------------------------------------- /GRAPH/DFS.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | // TIME COMPLEXITY ==> O(V + E) 9 | 10 | class Graph 11 | { 12 | public: 13 | int v; 14 | int index; 15 | vector> adjacency_list; // declaration --> Vecotr of Vector means 2D vector 16 | 17 | Graph(int v) 18 | { 19 | index = 0; 20 | this->v = v; 21 | adjacency_list.resize(6); 22 | } 23 | 24 | void set_edge(int start, int end) 25 | { 26 | adjacency_list[start].push_back(end); 27 | cout << "\n" 28 | << start << " --> " << end << " "; 29 | } 30 | 31 | void neighbours_show() 32 | { 33 | int k = adjacency_list[0][1]; 34 | cout << "\nNode in list[0][1] : " << k << endl; 35 | } 36 | 37 | void dfsUtil(int start, vector &visited) 38 | { 39 | visited[start] = true; 40 | cout << "DFS Node in list : " << start << "\t"; 41 | // for all the vertices adjacent(connected) to this vertex(i) ---------- means i th row traverse 42 | for (auto i = adjacency_list[start].begin(); i != adjacency_list[start].end(); ++i) 43 | { 44 | cout << "\n"; 45 | if (!visited[*i]) 46 | dfsUtil(*i, visited); 47 | } 48 | } 49 | 50 | void DFS() 51 | { 52 | vector visited(adjacency_list.size(), false); // vector A(10,false) + memory allocate 53 | for (int i = 0; i < adjacency_list.size(); i++) 54 | { 55 | if (!visited[i]) // Not Visited 56 | dfsUtil(i, visited); 57 | } 58 | } 59 | }; 60 | 61 | int main() 62 | { 63 | Graph g(5); 64 | cout << "\n************************** Depth First Traversal ************************\n"; 65 | g.set_edge(0, 1); 66 | g.set_edge(0, 2); 67 | g.set_edge(1, 3); 68 | g.set_edge(1, 4); 69 | g.set_edge(2, 2); 70 | g.neighbours_show(); 71 | 72 | cout << "\nFollowing is Depth First Traversal " 73 | << "(starting from vertex 2) \n"; 74 | g.DFS(); 75 | 76 | return 0; 77 | } -------------------------------------------------------------------------------- /GRAPH/MInimum_Cost_Spanning_Tree/.gitignore: -------------------------------------------------------------------------------- 1 | 2 | *.exe -------------------------------------------------------------------------------- /GRAPH/MInimum_Cost_Spanning_Tree/Disjoint-Set-Union.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | class DisjointSet 6 | { 7 | int *rank, *parent, n; 8 | 9 | public: 10 | // Constructor to create and Initialize sets of n items 11 | DisjointSet(int n) 12 | { 13 | rank = new int[n]; 14 | parent = new int[n]; 15 | this->n = n; 16 | makeSet(); 17 | } 18 | 19 | void makeSet() 20 | { 21 | int i; 22 | for (i = 0; i < n; i++) 23 | parent[i] = i; 24 | } 25 | 26 | int Find(int x) 27 | { 28 | if (x == parent[x]) // when X is absolute root 29 | return x; 30 | return Find(parent[x]); 31 | } 32 | 33 | void Union(int x, int y) 34 | { 35 | int absRootX, absRootY; 36 | absRootX = Find(x); 37 | absRootY = Find(y); 38 | 39 | if (absRootX == absRootY) // Belongs to the same set 40 | return; 41 | 42 | if (rank[absRootX] < rank[absRootY]) 43 | parent[absRootX] = absRootY; 44 | 45 | else if (rank[absRootX] > rank[absRootY]) 46 | parent[absRootY] = absRootX; 47 | 48 | else 49 | { 50 | parent[absRootY] = absRootX; 51 | cout << "rank[absRootX] = " << rank[absRootX] << endl; 52 | // rank[absRootX] = rank[absRootX] + 1; 53 | rank[absRootX]++; 54 | } 55 | } 56 | }; 57 | 58 | int main() 59 | { 60 | DisjointSet obj(5); 61 | obj.Union(0, 2); 62 | obj.Union(4, 2); 63 | obj.Union(3, 1); 64 | 65 | if (obj.Find(4) == obj.Find(0)) 66 | cout << "Yes\n"; 67 | else 68 | cout << "No\n"; 69 | 70 | if (obj.Find(1) == obj.Find(0)) 71 | cout << "Yes\n"; 72 | else 73 | cout << "No\n"; 74 | 75 | return 0; 76 | } 77 | -------------------------------------------------------------------------------- /GRAPH/MInimum_Cost_Spanning_Tree/Kruskal_Algorithm.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | struct createGraph 9 | { 10 | int src; 11 | int dest; 12 | int weight; 13 | 14 | // Constructor 15 | createGraph(int start, int end, int wt) 16 | { 17 | src = start; 18 | dest = end; 19 | weight = wt; 20 | } 21 | }; 22 | 23 | bool comp(createGraph a, createGraph b) 24 | { 25 | return a.weight < b.weight; 26 | } 27 | 28 | int Find(int src, vector &parent) 29 | { 30 | if (src == parent[src]) 31 | return src; 32 | return Find(parent[src], parent); 33 | } 34 | 35 | void Union(int x, int y, vector &parent, vector &rank) 36 | { 37 | int rootX = Find(x, parent); 38 | int rootY = Find(y, parent); 39 | 40 | if (rank[rootX] < rank[rootY]) 41 | parent[rootX] = rootY; 42 | 43 | else if (rank[rootX] > rank[rootY]) 44 | parent[rootY] = rootX; 45 | 46 | // When both have same AbsoluteRoot 47 | else 48 | { 49 | parent[rootX] = rootY; 50 | rank[rootY]++; 51 | } 52 | } 53 | 54 | void Kruskal_Algorithm(vector &edgeList, int n) 55 | { 56 | vector parent(n); 57 | vector rank(n, 0); 58 | vector> mst; 59 | int cost = 0, i; 60 | 61 | for (i = 0; i < n; i++) 62 | parent[i] = i; 63 | 64 | for (auto it : edgeList) 65 | { 66 | if (Find(it.src, parent) != Find(it.dest, parent)) 67 | { 68 | cost = cost + it.weight; 69 | mst.push_back({it.src, it.dest}); 70 | Union(it.src, it.dest, parent, rank); 71 | } 72 | } 73 | 74 | cout << cost << endl; 75 | for (auto it : mst) 76 | cout << it.first << " - " << it.second << endl; 77 | } 78 | 79 | int main() 80 | { 81 | int n = 4; // Nodes 82 | vector edgeList; 83 | edgeList.push_back(createGraph(0, 1, 4)); 84 | edgeList.push_back(createGraph(0, 3, 8)); 85 | edgeList.push_back(createGraph(2, 1, 11)); 86 | edgeList.push_back(createGraph(3, 2, 3)); 87 | 88 | sort(edgeList.begin(), edgeList.end(), comp); // sort acc to weight 89 | Kruskal_Algorithm(edgeList, n); 90 | 91 | return 0; 92 | } 93 | -------------------------------------------------------------------------------- /GRAPH/MInimum_Cost_Spanning_Tree/Prims_Algorithm.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | void ShowQueue(priority_queue, vector>, greater>> Q) 10 | { 11 | priority_queue, vector>, greater>> queue = Q; 12 | while (!Q.empty()) 13 | { 14 | cout << '\t' << Q.top().first << ' ' << Q.top().second << endl; 15 | Q.pop(); 16 | } 17 | } 18 | 19 | void Prims(vector> adjList[], int source, int n) 20 | { 21 | // priority_queue , ComparisonType > min_heap; 22 | priority_queue, vector>, greater>> PQ; 23 | vector edgeWeight(n, INT_MAX); 24 | vector parent(n, -1); 25 | vector mst(n, false); 26 | 27 | edgeWeight[0] = 0; 28 | PQ.push({0, 0}); // {cost , node} --> as we are finding Min Cost, thus taking first parameter of MINHEAP as Cost 29 | 30 | while (!PQ.empty()) 31 | { 32 | int node = PQ.top().second; 33 | PQ.pop(); 34 | 35 | mst[node] = true; 36 | 37 | for (auto it = adjList[node].begin(); it != adjList[node].end(); it++) 38 | { 39 | int dest = it->first; 40 | int cost = it->second; 41 | 42 | if (mst[dest] == false && cost < edgeWeight[dest]) 43 | { 44 | edgeWeight[dest] = cost; 45 | parent[dest] = node; 46 | PQ.push({edgeWeight[dest], dest}); 47 | } 48 | } 49 | } 50 | 51 | cout << "\n ************* Prim's Minimum Spanning Tree (MST) | Greedy Algorithm ****************\n"; 52 | for (int i = 1; i < n; i++) 53 | cout << parent[i] << " -> " << i << " \n"; 54 | } 55 | 56 | int main() 57 | { 58 | int n = 5; 59 | vector> adjList[n]; 60 | 61 | // Undirected Graph 0 ---> (1 , 2) === source ---> (destination , cost) 62 | adjList[0].push_back(make_pair(1, 2)); 63 | adjList[0].push_back(make_pair(3, 6)); 64 | adjList[1].push_back(make_pair(3, 8)); 65 | adjList[1].push_back(make_pair(4, 5)); 66 | adjList[1].push_back(make_pair(2, 3)); 67 | adjList[2].push_back(make_pair(4, 7)); 68 | 69 | Prims(adjList, 0, n); 70 | 71 | return 0; 72 | } 73 | 74 | /* 75 | EXPLAINATIONS :: 76 | 77 | 1) Set the adjacency list graph[src].push_back(make_pair(dest , cost)) 78 | 2) Create MIN_HEAP & edgeWeight vector ( to store the cost ) 79 | 3) Initialise : 80 | edgeWeight[0] = 0; 81 | PQ.push({0, 0}); 82 | 83 | 4) While (!Queue.empty()){ 84 | Compare the weight/cost and of the connected/neighbouring nodes and push into Queue 85 | 86 | 5) when the distance[cost] array is Set then traverse it 87 | 88 | */ 89 | 90 | /* it->first simply means(*it).first-- -- > It is a pointer pointing to your variable which has a member first, so to access first, you just dereference the pointer then use.to access the member 91 | In the first loop, you use iterators to iterate over the container M. Iterators emulate pointers, and have to be dereferenced to give the value the iterator is "pointing" at. In fact, for that loop, it->first is really the same as (*it).first. 92 | 93 | for (auto it : arr){ } 94 | In this loop over the values in the container M. The loop itself uses iterators internally and dereferences them for us. This reference about "range-based for loops" might help you. */ -------------------------------------------------------------------------------- /GRAPH/Shortest_Path_Algorithm/.gitignore: -------------------------------------------------------------------------------- 1 | 2 | *.exe -------------------------------------------------------------------------------- /GRAPH/Shortest_Path_Algorithm/Bellman_Ford.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | struct createGraph 10 | { 11 | int src; 12 | int dest; 13 | int weight; 14 | 15 | // Constructor 16 | createGraph(int start, int end, int wt) 17 | { 18 | src = start; 19 | dest = end; 20 | weight = wt; 21 | } 22 | }; 23 | 24 | // BELLMAN FORD ALGORITM FUNCTION 25 | void BellmanFord(vector &edgeList, int source, int totalVertex, int totalEdge) 26 | { 27 | int i, j, u, v, cost, flag = 0; 28 | vector dist(totalVertex, INT_MAX); // setting initial distances of the vertex is infinity 29 | dist[source] = 0; 30 | 31 | for (i = 0; i < totalVertex; i++) // this loop runs for (n - 1) iteration [RULE] 32 | { 33 | for (j = 0; j < totalEdge; j++) 34 | { 35 | // _____ if edgeList is vector of vector _____ 36 | // u = edgeList[j][0]; 37 | // v = edgeList[j][1]; 38 | // cost = edgeList[j][2]; 39 | 40 | u = edgeList[j].src; 41 | v = edgeList[j].dest; 42 | cost = edgeList[j].weight; 43 | 44 | // ------- Relaxation ---------- 45 | int updatedDist = dist[u] + cost; 46 | if (updatedDist < dist[v]) 47 | dist[v] = updatedDist; 48 | } 49 | } 50 | 51 | // for Checking negative cycles ---- Bellman not valid. [1 time traverse through all the edges] 52 | for (j = 0; j < totalEdge; j++) 53 | { 54 | u = edgeList[j].src; 55 | v = edgeList[j].dest; 56 | cost = edgeList[j].weight; 57 | 58 | int updatedDist = dist[u] + cost; 59 | if (updatedDist < dist[v]) 60 | { 61 | cout << "Negative cycle found between vertex " << u << " and " << v << endl; 62 | flag = 1; 63 | break; 64 | } 65 | } 66 | 67 | if (!flag) 68 | { 69 | cout << "______ Bellman Ford Algorithm _________\n"; 70 | for (i = 0; i < totalEdge; i++) 71 | cout << i << "\t" << dist[i] << endl; 72 | } 73 | } 74 | 75 | int main() 76 | { 77 | int tvertex = 4, tedge = 4; 78 | vector edgeList; // vector of structure 79 | 80 | // edgeList.push_back({1, 2, 4}); // ------> if vector of vector is used 81 | 82 | // start vertex(node) from 0 83 | // vec.push_back(constructor()); 84 | edgeList.push_back(createGraph(0, 1, 4)); 85 | edgeList.push_back(createGraph(0, 3, 5)); 86 | edgeList.push_back(createGraph(2, 1, -10)); 87 | edgeList.push_back(createGraph(3, 2, 3)); 88 | 89 | BellmanFord(edgeList, 0, tvertex, tedge); 90 | 91 | return 0; 92 | } 93 | 94 | /* 95 | point mypoint = {0, 1}; 96 | a.push_back(mypoint); 97 | 98 | OR 99 | 100 | vec.push_back(constructor()) 101 | */ 102 | 103 | /* 104 | EXPLAINATIONS :: 105 | 106 | 1) Iterate (N - 1) times 107 | 2) Valid for Negative Edges 108 | 3) InValid for Negative Cycles 109 | 4) Relaxation done (N - 1) times after that on Nth time while relaxation distance EILL NOT modify , BUT 110 | if on Nth time further Relaxation takes place then it has a NEGATIVE CYCLE. 111 | 112 | */ -------------------------------------------------------------------------------- /GRAPH/Shortest_Path_Algorithm/Dijkstras.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | // graph(Destination , Cost); 10 | // queue(Cost ,Destination ) 11 | 12 | // Print queue 13 | void ShowQueue(priority_queue, vector>, greater>> Q) 14 | { 15 | priority_queue, vector>, greater>> queue = Q; 16 | while (!Q.empty()) 17 | { 18 | cout << '\t' << Q.top().first << ' ' << Q.top().second << endl; 19 | Q.pop(); 20 | } 21 | } 22 | 23 | void Dijkstra(vector> graph[], int source, int n) 24 | { 25 | // priority_queue , ComparisonType > min_heap; 26 | priority_queue, vector>, greater>> queue; // min-heap ; In pair => (dist,from) 27 | vector distance(n + 1, INT_MAX); // 1-indexed array for calculating shortest paths (set initially infinite); 28 | 29 | distance[source] = 0; 30 | queue.push(make_pair(0, source)); // (distance , vertex) --> in MinHeap the lowest distance will be on TOP 31 | 32 | while (!queue.empty()) 33 | { 34 | int dist = queue.top().first; 35 | int curVtx = queue.top().second; 36 | cout << " Cost = " << dist << " Current Vertex = " << curVtx << endl; 37 | 38 | queue.pop(); 39 | 40 | for (auto it = graph[curVtx].begin(); it != graph[curVtx].end(); it++) // adjacency list traversal 41 | { 42 | int destVtx = it->first; 43 | int cost = it->second; 44 | cout << " Destination Vertex = " << destVtx << " Cost = " << cost << endl; 45 | 46 | if (distance[destVtx] > distance[curVtx] + cost) // Relaxation takes place 47 | { 48 | distance[destVtx] = distance[curVtx] + cost; // Stores the MINIMUM dist 49 | queue.push(make_pair(distance[destVtx], destVtx)); 50 | } 51 | } 52 | 53 | ShowQueue(queue); 54 | } 55 | 56 | cout << "\n ************* Dijkstra's Algorithm starting Node " << source << " : ****************\n"; 57 | for (int i = 1; i <= n; i++) 58 | cout << distance[i] << "\t"; 59 | } 60 | 61 | int main() 62 | { 63 | int n = 4; 64 | vector> graph[n + 1]; // 2D Array of pairs 65 | 66 | // 1-indexed adjacency list for of graph 67 | // graph[src].push_back(make_pair(dest , cost)); 68 | 69 | graph[1].push_back(make_pair(4, 8)); 70 | graph[1].push_back(make_pair(2, 4)); 71 | graph[3].push_back(make_pair(2, 1)); 72 | graph[4].push_back(make_pair(3, 8)); 73 | 74 | // ---------- FOR USER INPUT Adjacent List ------------ 75 | /* int vertex, edge, a, b, cost; // vertex, edge, from (source) , to (destination) , cost 76 | cin >> vertex >> edge; 77 | for (int i = 0; i < vertex; i++) 78 | { 79 | cin >> a >> b >> cost; 80 | graph[a].push_back(make_pair(b, cost)); 81 | graph[b].push_back(make_pair(a, cost)); 82 | } */ 83 | 84 | Dijkstra(graph, 1, n); 85 | 86 | return 0; 87 | } 88 | 89 | /* 90 | EXPLAINATIONS :: 91 | 92 | 1) Set the adjacency list graph[src].push_back(make_pair(dest , cost)) 93 | 2) Create MIN_HEAP & distance vector ( to store the cost ) 94 | 3) Initialise the Index 1 with cost 0 95 | 4) While (!Queue.empty()){ 96 | 97 | Queue.top() extract // Queue (Cost , Vertex) as all operation is done on queue -> first 98 | traverse the adjacencyList with this vertex 99 | Relaxation - and store the minimum distance 100 | 101 | 5) when the distance[cost] array is Set then traverse it 102 | */ -------------------------------------------------------------------------------- /GRAPH/Shortest_Path_Algorithm/tempCodeRunnerFile.cpp: -------------------------------------------------------------------------------- 1 | make_pair -------------------------------------------------------------------------------- /GRAPH/Topological_Sort_BFS_Kahns_Algorithm.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | /* TOPOLOGICAL SORT : 10 | 11 | - Store the Vertex in the adjacency list 12 | - [LOOP] Frequency calculate in inDegree vector 13 | - [LOOP] Check if (inDegree[i] == 0) ? Queue.push(i) // CONDITION 14 | - [LOOP] FOR BFS -----> 15 | 16 | # Time complexity: O(V + E) | Space complexity: O(V) for Stack 17 | */ 18 | 19 | class Graph 20 | { 21 | public: 22 | int index; 23 | vector> adjacency_list; // declaration --> Vecotr of Vector means 2D vector 24 | 25 | Graph(int size) 26 | { 27 | index = 0; 28 | adjacency_list.resize(size); 29 | } 30 | 31 | void set_edge(int start, int end) 32 | { 33 | adjacency_list[start].push_back(end); 34 | } 35 | 36 | void topological_Sort_BFS() 37 | { 38 | int size = adjacency_list.size(); // total Vertex 39 | vector inDegree(size, 0); // Number of edges directed to it (Node) 40 | vector topoDisplay; 41 | queue Q; 42 | int i, vertex; 43 | 44 | for (i = 0; i < size; i++) 45 | for (auto it : adjacency_list[i]) 46 | inDegree[it]++; 47 | 48 | for (i = 0; i < size; i++) 49 | if (inDegree[i] == 0) 50 | Q.push(i); 51 | 52 | while (!Q.empty()) 53 | { 54 | vertex = Q.front(); 55 | Q.pop(); 56 | cout << "Vertex popped from queue : " << vertex << "\n"; 57 | topoDisplay.push_back(vertex); 58 | 59 | // for (auto it = adjacency_list[vertex].begin(); it != adjacency_list[vertex].end(); ++it) 60 | for (auto it : adjacency_list[vertex]) 61 | { 62 | inDegree[it]--; 63 | if (inDegree[it] == 0) 64 | Q.push(it); 65 | } 66 | } 67 | 68 | // DISPLAY ALL THE ELEMENTS IN THE GRAPH 69 | cout << "\n"; 70 | for (auto it : topoDisplay) 71 | cout << it << "\t"; 72 | 73 | inDegree.clear(); 74 | cout << "\n\n"; 75 | } 76 | }; 77 | 78 | int main() 79 | { 80 | Graph g(6); // total number of VERTEX in the graph 81 | cout << "\n************************** Topological Sort using BFS ************************\n\n"; 82 | 83 | g.set_edge(2, 3); 84 | g.set_edge(3, 1); 85 | g.set_edge(4, 0); 86 | g.set_edge(4, 1); 87 | g.set_edge(5, 0); 88 | g.set_edge(5, 2); 89 | 90 | g.topological_Sort_BFS(); 91 | 92 | return 0; 93 | } -------------------------------------------------------------------------------- /GRAPH/Topological_Sort_DFS.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | /* Topological sort: 10 | # The edges of the graph can be unidirectional/bidirectional ----> DIRECTED GRAPH REQUIRED 11 | # TSort is only POSSIBLE when the graph is Directed Acyclic Graph (DAG). 12 | # Requires a STACK. 13 | # Run DFS on the graph and push each vertex in a stack after all its neighbours are visited. 14 | Pop each vertex from the stack and add it to a list to get the topologically sorted list of vertices. 15 | # 1st vertex in topological sorting is always a vertex with in-degree as 0 (a vertex with no incoming edges). 16 | # Linear orderring of Vertices i.e if there is an edge U --> V then U always comes before V. 17 | 18 | # Time complexity: O(V + E) | Space complexity: O(V) for Stack 19 | */ 20 | 21 | class Graph 22 | { 23 | public: 24 | int index; 25 | vector> adjacency_list; // declaration --> Vecotr of Vector means 2D vector 26 | 27 | Graph(int size) 28 | { 29 | index = 0; 30 | adjacency_list.resize(size); 31 | } 32 | 33 | void set_edge(int start, int end) 34 | { 35 | adjacency_list[start].push_back(end); 36 | } 37 | 38 | void DFS(int start, vector &visited, stack &Stack) 39 | { 40 | visited[start] = true; 41 | 42 | for (auto i = adjacency_list[start].begin(); i != adjacency_list[start].end(); ++i) 43 | if (!visited[*i]) 44 | DFS(*i, visited, Stack); 45 | 46 | Stack.push(start); 47 | } 48 | 49 | void topological_Sort() 50 | { 51 | vector visited(adjacency_list.size(), false); // vector A(10,false) + memory allocate 52 | stack Stack; 53 | vector topoDisplay; 54 | 55 | for (int i = 0; i < adjacency_list.size(); i++) 56 | { 57 | if (!visited[i]) // not visited 58 | DFS(i, visited, Stack); 59 | } 60 | 61 | // At the end when all the vertices are visited, Print the STACK 62 | while (!Stack.empty()) 63 | { 64 | cout << Stack.top() << "\t"; 65 | Stack.pop(); 66 | } 67 | 68 | visited.clear(); 69 | cout << "\n\n"; 70 | } 71 | }; 72 | 73 | int main() 74 | { 75 | Graph g(6); 76 | cout << "\n************************** Topological Sort using DFS ************************\n\n"; 77 | 78 | g.set_edge(2, 3); 79 | g.set_edge(3, 1); 80 | g.set_edge(4, 0); 81 | g.set_edge(4, 1); 82 | g.set_edge(5, 0); 83 | g.set_edge(5, 2); 84 | 85 | g.topological_Sort(); 86 | 87 | return 0; 88 | } -------------------------------------------------------------------------------- /GRAPH/tempCodeRunnerFile.cpp: -------------------------------------------------------------------------------- 1 | * -------------------------------------------------------------------------------- /GRAPH/trial.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/niharika2k00/Data-Structure_DSA/d890e950b3b14841fd2af901ce2068057e098ae4/GRAPH/trial.cpp -------------------------------------------------------------------------------- /LINKED_LIST/.gitignore: -------------------------------------------------------------------------------- 1 | 2 | *.exe -------------------------------------------------------------------------------- /LINKED_LIST/Circular-linked-list.c: -------------------------------------------------------------------------------- 1 | // 2.Write a C program to create a circular linked list and insert a new node at the beginning 2 | 3 | #include 4 | #include 5 | 6 | struct node 7 | { 8 | int num; 9 | struct node *nextptr; 10 | } * stnode; 11 | 12 | void ClListcreation(int n); 13 | void ClLinsertNodeAtBeginning(int num); 14 | void displayClList(int a); 15 | 16 | int main() 17 | { 18 | int n, num1, a; 19 | stnode = NULL; 20 | printf("\n\n Circular Linked List : Insert a node at the beginning of a circular linked list :\n"); 21 | printf("--------------------------------------------------------------------------------------\n"); 22 | printf(" Input the number of nodes : "); 23 | scanf("%d", &n); 24 | ClListcreation(n); 25 | a = 1; 26 | displayClList(a); 27 | printf(" Input data to be inserted at the beginning : "); 28 | scanf("%d", &num1); 29 | ClLinsertNodeAtBeginning(num1); 30 | a = 2; 31 | displayClList(a); 32 | return 0; 33 | } 34 | 35 | void ClListcreation(int n) 36 | { 37 | int i, num; 38 | struct node *preptr, *newnode; 39 | 40 | if (n >= 1) 41 | { 42 | stnode = (struct node *)malloc(sizeof(struct node)); 43 | 44 | printf(" Input data for node 1 : "); 45 | scanf("%d", &num); 46 | stnode->num = num; 47 | stnode->nextptr = NULL; 48 | preptr = stnode; 49 | for (i = 2; i <= n; i++) 50 | { 51 | newnode = (struct node *)malloc(sizeof(struct node)); 52 | printf(" Input data for node %d : ", i); 53 | scanf("%d", &num); 54 | newnode->num = num; 55 | newnode->nextptr = NULL; // next address of new node set as NULL 56 | preptr->nextptr = newnode; // previous node is linking with new node 57 | preptr = newnode; // previous node is advanced 58 | } 59 | preptr->nextptr = stnode; //last node is linking with first node 60 | } 61 | } 62 | 63 | void ClLinsertNodeAtBeginning(int num) 64 | { 65 | struct node *newnode, *curNode; 66 | if (stnode == NULL) 67 | { 68 | printf(" No data found in the List yet."); 69 | } 70 | else 71 | { 72 | newnode = (struct node *)malloc(sizeof(struct node)); 73 | newnode->num = num; 74 | newnode->nextptr = stnode; 75 | curNode = stnode; 76 | while (curNode->nextptr != stnode) 77 | { 78 | curNode = curNode->nextptr; 79 | } 80 | curNode->nextptr = newnode; 81 | stnode = newnode; 82 | } 83 | } 84 | void displayClList(int m) 85 | { 86 | struct node *tmp; 87 | int n = 1; 88 | 89 | if (stnode == NULL) 90 | { 91 | printf(" No data found in the List yet."); 92 | } 93 | else 94 | { 95 | tmp = stnode; 96 | if (m == 1) 97 | { 98 | printf("\n Data entered in the list are :\n"); 99 | } 100 | else 101 | { 102 | printf("\n After insertion the new list are :\n"); 103 | } 104 | do 105 | { 106 | printf(" Data %d = %d\n", n, tmp->num); 107 | tmp = tmp->nextptr; 108 | n++; 109 | } while (tmp != stnode); 110 | } 111 | } -------------------------------------------------------------------------------- /LINKED_LIST/Singly_Linkedlist_operations.c: -------------------------------------------------------------------------------- 1 | 2 | // *********************** LINKED-LIST IMPLEMENTATION ********************** 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | // structure construction 9 | struct node 10 | { 11 | int data; 12 | struct node *next; 13 | }; 14 | struct node *start = NULL, *q = NULL, *p = NULL; // start - global variable 15 | 16 | // prototypes...... 17 | void create(); 18 | void display(struct node *start); 19 | void addbeginning(); 20 | void addend(); 21 | void addbefr_givennode(); 22 | void addaftr_givennode(); 23 | void delbeginning(); 24 | void delend(); 25 | void delany_givennode(); 26 | void delentire_linkedlist(); 27 | void maxNode(); 28 | // void Reverse(); 29 | void Reverse(struct node *start); 30 | void search(struct node *start); 31 | void delodd_ele(); 32 | void findsum(); 33 | void insertele_position(); 34 | void delele_position(); 35 | void reversePrint(struct node *start); 36 | 37 | int main(void) 38 | { 39 | int option; 40 | 41 | do 42 | { 43 | printf("\n \n **************** CHOOSE AN OPTION **********************"); 44 | printf("\n \n 1. Create a linked-list."); 45 | printf("\n 2. Display a linked-list."); 46 | printf("\n 3. Add a node from the beginning."); 47 | printf("\n 4. Add a node from the END."); 48 | printf("\n 5. Add a node BEFORE a given node."); 49 | printf("\n 6. Add a node AFTER a given node."); 50 | printf("\n 7. Delete a node from the beginning."); 51 | printf("\n 8. Delete a node from the END."); 52 | printf("\n 9. Delete any given NODE."); 53 | printf("\n 10. Delete the entire linked-list."); 54 | printf("\n 11. MAXIMUM node value in the whole linked-list. "); 55 | printf("\n 12. REVERSE the linked-list. "); 56 | printf("\n 13. Search an element in the linked-list."); 57 | printf("\n 14. Delete ALL ODD elements."); 58 | printf("\n 15. Sum of all elements."); 59 | printf("\n 16. Insert element at a given POSITION. "); 60 | printf("\n 17. Delete element at a given POSITION. "); 61 | printf("\n 18. Print the REVERSE list. \n"); 62 | printf("\n ********************** EXIT *****************************"); 63 | printf("\n \n Choose a no. -> "); 64 | scanf("%d", &option); 65 | 66 | switch (option) 67 | { 68 | case 1: 69 | create(); 70 | break; 71 | case 2: 72 | display(start); 73 | // display(); 74 | break; 75 | case 3: 76 | addbeginning(); 77 | break; 78 | case 4: 79 | addend(); 80 | break; 81 | case 5: 82 | addbefr_givennode(); 83 | break; 84 | case 6: 85 | addaftr_givennode(); 86 | break; 87 | case 7: 88 | delbeginning(); 89 | break; 90 | case 8: 91 | delend(); 92 | break; 93 | case 9: 94 | delany_givennode(); 95 | break; 96 | case 10: 97 | delentire_linkedlist(); 98 | break; 99 | case 11: 100 | maxNode(); 101 | break; 102 | case 12: 103 | // Reverse(); 104 | Reverse(start); 105 | break; 106 | case 13: 107 | search(start); 108 | break; 109 | case 14: 110 | delodd_ele(); 111 | break; 112 | case 15: 113 | findsum(); 114 | break; 115 | case 16: 116 | insertele_position(); 117 | break; 118 | case 17: 119 | delele_position(); 120 | break; 121 | 122 | case 18: 123 | reversePrint(start); 124 | break; 125 | default: 126 | printf("CHOOSE THE OPTION MENTIONED IN THE MENU....."); 127 | break; 128 | } 129 | 130 | } while ((option >= 1) && (option <= 20)); 131 | return 0; 132 | } 133 | 134 | void create() 135 | { 136 | int i, n, num; 137 | struct node *newnode, *ptr; // variables of struct node pointer types 138 | printf("Enter the no. of nodes : "); 139 | scanf("%d", &n); 140 | 141 | for (i = 0; i < n; i++) 142 | { 143 | printf("Enter a no. --> "); 144 | scanf("%d", &num); 145 | newnode = (struct node *)malloc(sizeof(struct node)); 146 | newnode->data = num; 147 | if (start == NULL) 148 | { 149 | start = newnode; // head / start pointing to the Linked List. 150 | newnode->next = NULL; 151 | } 152 | else 153 | { 154 | ptr = start; 155 | while (ptr->next != NULL) 156 | { 157 | ptr = ptr->next; 158 | } 159 | ptr->next = newnode; 160 | newnode->next = NULL; 161 | } 162 | } 163 | } 164 | 165 | void display(struct node *start) // display using recursion 166 | { 167 | struct node *ptr = start; 168 | if (ptr == NULL) 169 | return; 170 | printf("%d \t", ptr->data); 171 | display(ptr->next); 172 | } 173 | 174 | /* void display() // Iterative Method 175 | { 176 | printf("\n <------------- Display Successfully ------------->\n"); 177 | struct node *ptr; 178 | ptr = start; 179 | while (ptr != NULL) 180 | { 181 | printf("%d \t", ptr->data); 182 | ptr = ptr->next; 183 | } 184 | } */ 185 | 186 | void addbeginning() 187 | { 188 | struct node *newnode; 189 | int num; 190 | printf("####### _______ ADD NODE BEGINNING ________######## \n\n"); 191 | printf("Enter a value of the node that must be entered at the beginning --> "); 192 | scanf("%d", &num); 193 | newnode = (struct node *)malloc(sizeof(struct node)); 194 | newnode->data = num; 195 | newnode->next = start; 196 | start = newnode; 197 | printf("\nNODE SUCCESSFULLY ADDED AT THE BEGINNING\n"); 198 | } 199 | 200 | void addend() 201 | { 202 | struct node *ptr, *newnode; 203 | int num; 204 | printf("####### _______ ADD NODE END ________######## \n\n "); 205 | printf("Enter a value of the node that must be added at the end --> "); 206 | scanf("%d", &num); 207 | newnode = (struct node *)malloc(sizeof(struct node)); 208 | newnode->data = num; 209 | newnode->next = NULL; 210 | ptr = start; 211 | if (start == NULL) 212 | return; 213 | while (ptr->next != NULL) 214 | { 215 | ptr = ptr->next; 216 | } 217 | ptr->next = newnode; 218 | printf("\nNODE SUCCESSFULLY ADDED AT THE END\n"); 219 | } 220 | 221 | void addbefr_givennode() 222 | { 223 | struct node *ptr, *newnode, *preptr; 224 | int num, value; 225 | printf("\nEnter the value of the node before which you want to add new no. : "); 226 | scanf("%d", &value); 227 | printf("Enter a value of the node that must be added --> "); 228 | scanf("%d", &num); 229 | newnode = (struct node *)malloc(sizeof(struct node)); 230 | newnode->data = num; 231 | ptr = start; 232 | while (ptr->data != value) 233 | { 234 | preptr = ptr; 235 | ptr = ptr->next; 236 | } 237 | newnode->next = ptr; 238 | preptr->next = newnode; 239 | printf("\nSUCCESSFULLY INSERTED A NODE\n \n"); 240 | } 241 | 242 | void addaftr_givennode() 243 | { 244 | struct node *ptr, *newnode; 245 | int num, value; 246 | printf("\nEnter the value of the node after which you want to add new no. : "); 247 | scanf("%d", &value); 248 | printf("Enter a value of the node that must be added --> "); 249 | scanf("%d", &num); 250 | newnode = (struct node *)malloc(sizeof(struct node)); 251 | newnode->data = num; 252 | ptr = start; 253 | while (ptr->data != value) 254 | { 255 | ptr = ptr->next; 256 | } 257 | newnode->next = ptr->next; 258 | ptr->next = newnode; 259 | printf("\nSUCCESSFULLY INSERTED A NODE AFTER A GIVEN NODE. \n \n"); 260 | } 261 | 262 | void delbeginning() 263 | { 264 | struct node *ptr; 265 | ptr = start; 266 | start = ptr->next; 267 | printf("\nSUCCESSFULLY DELETED THE 1ST NODE\n \n"); 268 | } 269 | 270 | void delend() 271 | { 272 | struct node *ptr, *preptr; 273 | ptr = start; 274 | while (ptr->next != NULL) 275 | { 276 | preptr = ptr; 277 | ptr = ptr->next; 278 | } 279 | 280 | preptr->next = NULL; 281 | printf("\nSUCCESSFULLY DELETED THE LAST NODE\n \n"); 282 | } 283 | 284 | void delany_givennode() 285 | { 286 | struct node *ptr, *preptr; 287 | int value; 288 | printf("\nEnter the value of the node u want to delete : "); 289 | scanf("%d", &value); 290 | ptr = start; 291 | while (ptr->data != value) 292 | { 293 | preptr = ptr; 294 | ptr = ptr->next; 295 | } 296 | preptr->next = ptr->next; 297 | printf("\nSUCESSFULLY DELETED THE NODE U WANTED......\n"); 298 | } 299 | 300 | void delentire_linkedlist() 301 | { 302 | struct node *temp; 303 | struct node *ptr = start; 304 | while (ptr != NULL) 305 | { 306 | temp = ptr; 307 | ptr = ptr->next; 308 | free(temp); 309 | } 310 | printf("YAAAH !!.... LINKED-LIST DELETED"); 311 | start = ptr; 312 | } 313 | 314 | void maxNode() 315 | { 316 | struct node *current = start; 317 | int max; 318 | 319 | if (start == NULL) 320 | printf("List is empty \n"); 321 | 322 | else 323 | { 324 | max = start->data; 325 | while (current->next != NULL) 326 | { 327 | if (max < current->data) // CPP : max = max(current->data, max); 328 | max = current->data; 329 | current = current->next; 330 | } 331 | printf("\n Maximum value node in the list: %d\n", max); 332 | } 333 | } 334 | 335 | /* void Reverse() // Reversing using an ARRAY. 336 | { 337 | struct node *ptr = start; 338 | int a[20], i; 339 | for (i = 0; ptr->next != NULL; i++) 340 | { 341 | a[i] = ptr->data; 342 | ptr = ptr->next; 343 | } 344 | 345 | ptr = start; 346 | i = i - 1; 347 | while (ptr->next != NULL) 348 | { 349 | ptr->data = a[i--]; 350 | ptr = ptr->next; 351 | } 352 | printf("REVERSED SUCCESSFULLY --------> \n"); 353 | // printing the reversed ll. 354 | ptr = start; 355 | while (ptr->next != NULL) 356 | { 357 | printf("%d \t", ptr->data); 358 | ptr = ptr->next; 359 | } 360 | }*/ 361 | 362 | /* void Reverse() // Reversing using sliding pointer/ changing the arrow direction 363 | { 364 | struct node *ptr = start; 365 | struct node *q = NULL; 366 | struct node *r = NULL; 367 | while (ptr != NULL) 368 | { 369 | r = q; 370 | q = ptr; 371 | ptr = ptr->next; 372 | q->next = r; 373 | } 374 | start = q; 375 | 376 | // printing the reversed ll. 377 | printf("REVERSED SUCCESSFULLY --------> \n"); 378 | ptr = start; 379 | while (ptr != NULL) 380 | { 381 | printf("%d \t", ptr->data); 382 | ptr = ptr->next; 383 | } 384 | } 385 | */ 386 | 387 | void Reverse(struct node *p) // Time Complexity: O(n), Recursive method (BEST) 388 | { 389 | if (p->next == NULL) 390 | { 391 | start = p; 392 | printf("REVERSED SUCCESSFULLY --------> \n"); 393 | return; 394 | } 395 | Reverse(p->next); 396 | struct node *rev; 397 | rev = p->next; 398 | rev->next = p; 399 | p->next = NULL; 400 | } 401 | 402 | void search(struct node *start) 403 | { 404 | int val; 405 | struct node *p = start; 406 | printf("Enter the value that u want to find ? "); 407 | scanf("%d", &val); 408 | while (p != NULL) 409 | { 410 | if (p->data == val) 411 | { 412 | printf("%d is found in the linked list\n", val); 413 | // break; 414 | return; 415 | } 416 | p = p->next; 417 | } 418 | printf("%d is NOT found in the linked list\n", val); 419 | } 420 | 421 | void delodd_ele() 422 | { 423 | struct node *p = start; 424 | if ((p->data) % 2 != 0) // checking whether the data of first node is ODD 425 | { 426 | struct node *t = p->next; 427 | free(p); 428 | p = t; 429 | } 430 | struct node *temp = p; 431 | while (temp != NULL) 432 | { 433 | if (temp->next != NULL && temp->next->data % 2 != 0) 434 | { 435 | struct node *t = temp->next->next; 436 | free(temp->next); 437 | temp->next = t; 438 | } 439 | else 440 | temp = temp->next; 441 | } 442 | printf("DELETED ALL ODD NODES SUCCESSFULLY --------> \n"); 443 | } 444 | 445 | void findsum() 446 | { 447 | int sum = 0; 448 | struct node *ptr; 449 | ptr = start; 450 | while (ptr != NULL) 451 | { 452 | sum = sum + ptr->data; 453 | ptr = ptr->next; 454 | } 455 | printf("\n Sum of all the NODES OF THE Linked-List is :: %d ---------->\n", sum); 456 | } 457 | 458 | void insertele_position() 459 | { 460 | struct node *newnode, *ptr = start, *temp; 461 | int pos = 0, val, position; 462 | newnode = (struct node *)malloc(sizeof(struct node)); 463 | printf("\nEnter the POSITION of the node u want to insert : "); 464 | scanf("%d", &position); 465 | printf("Enter the VALUE to insert : "); 466 | scanf("%d", &val); 467 | newnode->data = val; 468 | 469 | if (!start) 470 | printf("List is empty \n"); 471 | 472 | while (ptr != NULL) 473 | { 474 | if (pos == position) 475 | break; 476 | temp = ptr; 477 | ptr = ptr->next; 478 | pos++; 479 | } 480 | temp->next = newnode; 481 | newnode->next = ptr; 482 | printf("***** Sucessfully Inserted *****"); 483 | } 484 | 485 | void delele_position() 486 | { 487 | struct node *ptr = start, *temp; 488 | int pos = 0, val, position; 489 | printf("\nEnter the POSITION of the node u want to insert : "); 490 | scanf("%d", &position); 491 | 492 | if (position == 0) // If first element of linked list is deleted 493 | { 494 | start = ptr->next; 495 | free(ptr); 496 | } 497 | 498 | while (ptr != NULL) 499 | { 500 | if (pos == position) 501 | break; 502 | temp = ptr; 503 | ptr = ptr->next; 504 | pos++; 505 | } 506 | temp->next = ptr->next; 507 | free(ptr); 508 | printf("***** Sucessfully Deleted *****"); 509 | } 510 | 511 | void reversePrint(struct node *start) 512 | { 513 | if (start == NULL) 514 | { 515 | printf("***** Printing Reverse linked - list :: *****\n"); 516 | return; 517 | } 518 | reversePrint(start->next); // Backtracking 519 | printf("%d\t", start->data); 520 | } 521 | 522 | /*Reverse 523 | SinglyLinkedListNode *prev = head, 524 | *current = head->next, *aftr; 525 | 526 | if (head == NULL) 527 | return head; 528 | head->next = NULL; 529 | while (current) 530 | { 531 | aftr = current->next; 532 | current->next = prev; 533 | prev = current; 534 | current = aftr; 535 | } 536 | 537 | return prev; 538 | 539 | void remove_duplicate() 540 | { 541 | SinglyLinkedListNode *current = head->next, *prev = head, *temp; 542 | if (!head) 543 | return head; 544 | while (current != NULL) 545 | { 546 | if (prev->data == current->data) 547 | { 548 | temp = current; 549 | current = current->next; 550 | prev->next = current; 551 | } 552 | else 553 | { 554 | prev = current; 555 | current = current->next; 556 | } 557 | } 558 | 559 | return head; 560 | } */ -------------------------------------------------------------------------------- /QUEUE/QUEUE.txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | // ---------------------------------------------------------------------------- 4 | QUEUE DS 5 | // ---------------------------------------------------------------------------- 6 | 7 | 8 | 9 | 10 | QUEUE (General) :: 11 | 12 | - FIFO 13 | - pop() deletes the 1st element(FRONT) of the queue 14 | - push() add element in BACK 15 | - front() returns a reference to the 1st element 16 | - back() returns a reference to the LAST element 17 | - swap() 18 | 19 | 20 | DEQUE :: 21 | 22 | Element can be Inserted / Deleted from both the ends 23 | 24 | - back() 25 | - front() 26 | - size() size of the queue 27 | - push_back() 28 | - push_front() 29 | - pop_front() 30 | - pop_back() 31 | 32 | 33 | PRIORITY_QUEUE :: 34 | 35 | // Creates a max heap (default) 36 | priority_queue pq; 37 | 38 | // Creates a min heap 39 | priority_queue , greater > pq; 40 | 41 | 42 | - top() 43 | - push() 44 | - pop() 45 | - size() 46 | - swap() -------------------------------------------------------------------------------- /QUEUE/Queue_CircularLL.c: -------------------------------------------------------------------------------- 1 | 2 | // LINKED-LIST REPRESENTATION OF CIRCULAR QUEUE 3 | 4 | #include 5 | #include 6 | 7 | struct node 8 | { 9 | int data; 10 | struct node *next; 11 | } *rear = NULL, *front = NULL; 12 | 13 | void insert(int item); 14 | int delete (); 15 | void display(); 16 | 17 | int main() 18 | { 19 | int choice, item; 20 | while (1) 21 | { 22 | printf("\n********************** MAIN MENU *************************"); 23 | printf("\n==============================================================="); 24 | printf("\n\n 1.Insert elements in the CIRCULAR QUEUE "); 25 | printf("\n 2.Delete element from the CIRCULAR QUEUE "); 26 | printf("\n 3.Display all elements of the CIRCULAR QUEUE "); 27 | printf("\n 4.EXIT \n"); 28 | printf("\n==============================================================="); 29 | printf("\nEnter your choice : "); 30 | scanf("%d", &choice); 31 | 32 | switch (choice) 33 | { 34 | case 1: 35 | printf("\nEnter the element for insertion : "); 36 | scanf("%d", &item); 37 | insert(item); 38 | break; 39 | case 2: 40 | printf("\nDeleted element is %d\n", delete ()); 41 | break; 42 | case 3: 43 | display(); 44 | break; 45 | case 4: 46 | exit(1); 47 | break; 48 | default: 49 | printf("\nWrong choice\n"); 50 | } 51 | } 52 | } 53 | 54 | void insert(int item) 55 | { 56 | struct node *tmp; 57 | tmp = (struct node *)malloc(sizeof(struct node)); 58 | tmp->data = item; 59 | // tmp->next = NULL; 60 | if (tmp == NULL) 61 | printf("\n**** Memory is not available(allocated) ****\n"); 62 | 63 | else if ((rear == NULL) && (front == NULL)) // for the 1st ele 64 | { 65 | rear = front = tmp; 66 | rear->next = front; 67 | } 68 | else 69 | { 70 | rear->next = tmp; 71 | rear = rear->next; // update rear 72 | rear->next = front; 73 | } 74 | } 75 | 76 | int delete () 77 | { 78 | int item; 79 | struct node *tmp; 80 | tmp = front; 81 | 82 | if ((rear == NULL) && (front == NULL)) 83 | printf("\n**** Queue underflow ****\n"); 84 | 85 | else if (front == rear) 86 | { 87 | front = rear = NULL; 88 | free(tmp); 89 | } 90 | else 91 | { 92 | front = front->next; 93 | rear->next = front; // update rear 94 | // free(tmp); 95 | } 96 | item = tmp->data; 97 | return tmp->data; 98 | } 99 | 100 | void display() 101 | { 102 | struct node *p; 103 | p = front; 104 | if ((rear == NULL) && (front == NULL)) 105 | printf("\nQueue is empty\n"); 106 | 107 | printf("\n<------ Queue is :\n"); 108 | do 109 | { 110 | printf("%d ", p->data); 111 | p = p->next; 112 | } while (p != front); 113 | printf("\n"); 114 | } -------------------------------------------------------------------------------- /QUEUE/Queue_Circular_arraystruct.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | 5 | struct Queue 6 | { 7 | int size; 8 | int front; 9 | int rear; 10 | int *Q; 11 | }; 12 | 13 | void create(struct Queue *q, int size) 14 | { 15 | q->size = size; 16 | q->front = q->rear = 0; 17 | q->Q = (int *)malloc(q->size * sizeof(int)); 18 | } 19 | 20 | void enqueue(struct Queue *q, int x) 21 | { 22 | if ((q->rear + 1) % q->size == q->front) 23 | printf("Queue is Full"); 24 | else 25 | { 26 | q->rear = (q->rear + 1) % q->size; 27 | q->Q[q->rear] = x; 28 | } 29 | } 30 | 31 | int dequeue(struct Queue *q) 32 | { 33 | int x = -1; 34 | 35 | if (q->front == q->rear) 36 | printf("Queue is Empty\n"); 37 | else 38 | { 39 | q->front = (q->front + 1) % q->size; 40 | x = q->Q[q->front]; 41 | } 42 | return x; 43 | } 44 | 45 | void Display(struct Queue q) 46 | { 47 | int i = q.front + 1; 48 | 49 | do 50 | { 51 | printf("%d ", q.Q[i]); 52 | i = (i + 1) % q.size; 53 | } while (i != (q.rear + 1) % q.size); 54 | 55 | printf("\n"); 56 | } 57 | 58 | int main() 59 | { 60 | struct Queue q; 61 | create(&q, 5); 62 | 63 | enqueue(&q, 10); 64 | enqueue(&q, 20); 65 | enqueue(&q, 30); 66 | enqueue(&q, 40); 67 | enqueue(&q, 50); 68 | enqueue(&q, 60); 69 | Display(q); 70 | 71 | printf("%d ", dequeue(&q)); 72 | return 0; 73 | } -------------------------------------------------------------------------------- /QUEUE/Queue_array.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | 5 | #define MAX 50 6 | 7 | void insert(); 8 | void delete (); 9 | void display(); 10 | int queue_array[MAX]; 11 | int rear = -1, front = -1; 12 | 13 | int main() 14 | { 15 | int choice; 16 | while (1) 17 | { 18 | printf("\n \n **************** CHOOSE AN OPTION **********************"); 19 | printf("\n\n 1.Insert elements in the QUEUE "); 20 | printf("\n 2.Delete element from the QUEUE "); 21 | printf("\n 3.Display all elements of the QUEUE "); 22 | printf("\n 4.EXIT \n"); 23 | printf("\n ********************** EXIT *****************************\n"); 24 | printf("Enter your choice : "); 25 | scanf("%d", &choice); 26 | switch (choice) 27 | { 28 | case 1: 29 | push(); 30 | break; 31 | case 2: 32 | pop(); 33 | break; 34 | case 3: 35 | traverse(); 36 | break; 37 | case 4: 38 | exit(1); 39 | default: 40 | printf("Wrong choice \n"); 41 | } 42 | } 43 | } 44 | 45 | void push() // insert , push enqueue same 46 | { 47 | int num; 48 | printf("Inset the element in queue : "); 49 | scanf("%d", &num); 50 | if (rear == MAX - 1) 51 | printf("Queue Overflow \n"); 52 | else 53 | { 54 | if ((front == -1) && (rear == -1)) 55 | front = rear = 0; /*If queue is initially empty */ 56 | else 57 | rear++; 58 | queue_array[rear] = num; 59 | } 60 | } 61 | 62 | void pop() // pop , dequeue same 63 | { 64 | if (front == -1 || front > rear) 65 | { 66 | printf("Queue Underflow \n"); 67 | return; 68 | } 69 | else 70 | { 71 | printf("Element deleted from queue is : %d\n", queue_array[front]); 72 | front++; 73 | } 74 | } 75 | 76 | void traverse() 77 | { 78 | int i; 79 | if ((front == -1) && (rear == -1)) 80 | printf("Queue is empty \n"); 81 | else 82 | { 83 | printf("Queue is : \n"); 84 | for (i = front; i <= rear; i++) 85 | printf("%d ", queue_array[i]); 86 | } 87 | } -------------------------------------------------------------------------------- /QUEUE/Queue_linked_list.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | struct node 5 | { 6 | int data; 7 | struct node *next; 8 | }; 9 | struct node *front; // Global Variables 10 | struct node *rear; 11 | 12 | void insert(); // prototypes 13 | void delete (); 14 | void display(); 15 | void main() 16 | { 17 | int choice; 18 | while (choice != 4) 19 | { 20 | printf("\n*************************Main Menu*****************************"); 21 | printf("\n==============================================================="); 22 | printf("\n\n 1.Insert elements in the QUEUE "); 23 | printf("\n 2.Delete element from the QUEUE "); 24 | printf("\n 3.Display all elements of the QUEUE "); 25 | printf("\n 4.EXIT \n"); 26 | printf("\n==============================================================="); 27 | printf("\nEnter your choice ? "); 28 | scanf("%d", &choice); 29 | switch (choice) 30 | { 31 | case 1: 32 | insert(); 33 | break; 34 | case 2: 35 | delete (); 36 | break; 37 | case 3: 38 | display(); 39 | break; 40 | case 4: 41 | exit(0); 42 | break; 43 | default: 44 | printf("\nEnter valid choice??\n"); 45 | } 46 | } 47 | } 48 | void insert() 49 | { 50 | struct node *ptr; 51 | int item; 52 | ptr = (struct node *)malloc(sizeof(struct node)); 53 | if (ptr == NULL) 54 | printf("\nOVERFLOW\n"); // condition if node ptr is not created. 55 | else 56 | { 57 | printf("\nEnter value ? :-> "); 58 | scanf("%d", &item); 59 | ptr->data = item; 60 | if (front == NULL) 61 | { 62 | front = rear = ptr; 63 | front->next = rear->next = NULL; 64 | } 65 | else 66 | { 67 | rear->next = ptr; 68 | rear = ptr; 69 | rear->next = NULL; 70 | } 71 | } 72 | } 73 | 74 | void delete () 75 | { 76 | struct node *ptr; 77 | int val = -1; 78 | if (front == NULL) // no element present. 79 | printf("< ---- UNDERFLOW --- >"); 80 | else 81 | { 82 | val = front->data; 83 | ptr = front; 84 | front = front->next; 85 | free(ptr); 86 | printf("***** Sucessfully deleted %d ***** ", val); 87 | } 88 | } 89 | 90 | void display() 91 | { 92 | struct node *ptr; 93 | ptr = front; 94 | if (front == NULL) 95 | printf("\n ***** QUEUE IS EMPTY ***** \n"); 96 | else 97 | { 98 | printf("\n***** Display the QUEUE *****\n"); 99 | while (ptr != NULL) 100 | { 101 | printf("%d\t", ptr->data); 102 | ptr = ptr->next; 103 | } 104 | } 105 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Data-Structure_And_Algorithm 2 | -------------------------------------------------------------------------------- /SearchingTechniques/Binary_Search.c: -------------------------------------------------------------------------------- 1 | 2 | // BINARY SEARCH is possible only for the sorted array. 3 | #include 4 | #include 5 | 6 | int main() 7 | { 8 | int c, first, last, mid, n, search, arr[100]; 9 | 10 | printf("Enter number of elements : "); 11 | scanf("%d", &n); 12 | 13 | printf("Enter %d integers\n", n); 14 | 15 | for (c = 0; c < n; c++) 16 | scanf("%d", &arr[c]); 17 | 18 | printf("Enter value to find --> "); 19 | scanf("%d", &search); 20 | 21 | first = 0; 22 | last = n - 1; // as n is the total no. so its INDEX no. will be n-1 23 | mid = (first + last) / 2; 24 | 25 | while (first <= last) 26 | { 27 | if (search > arr[mid] ) 28 | first = mid + 1; 29 | 30 | else if (arr[mid] == search) 31 | { 32 | printf("%d found at location %d.\n", search, mid + 1); 33 | break; 34 | } 35 | else 36 | last = mid - 1; 37 | 38 | mid = (first + last) / 2; 39 | } 40 | if (first > last) 41 | printf("Not found! %d isn't present in the list.\n", search); 42 | } -------------------------------------------------------------------------------- /SearchingTechniques/Linear_Search.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | int n, i, found = 0, a[20], p; 7 | printf("Enter the no. of elements : "); 8 | scanf("%d", &n); 9 | printf("Enter elements : "); 10 | for (i = 0; i < n; i++) 11 | scanf("%d", &a[i]); 12 | 13 | printf("Enter the element to be searched : "); 14 | scanf("%d", &p); 15 | 16 | for (i = 0; i < n; i++) 17 | { 18 | if (p == a[i]) 19 | { 20 | found = 1; 21 | printf("**-- Element %d is found in the position %d having INDEX %d --**", p,i+1,i); 22 | break; 23 | } 24 | } 25 | 26 | if (found == 0) 27 | printf("-- Element %d is NOT found --", p); 28 | } -------------------------------------------------------------------------------- /SearchingTechniques/Search.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | 5 | int search(int arr[], int n, int x) 6 | { 7 | int i; 8 | for (i = 0; i < n; i++) 9 | if (arr[i] == x) 10 | return i; 11 | return -1; 12 | } 13 | 14 | // Driver code 15 | int main(void) 16 | { 17 | int arr[] = {2, 3, 4, 10, 40}; 18 | int x = 10; 19 | int n = sizeof(arr) / sizeof(arr[0]); 20 | 21 | // Function call 22 | int result = search(arr, n, x); 23 | (result == -1) ? printf("Element is not present in array") : printf("Element is present at index %d", result); 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /SortingTechniques/BUBBLE-SORT.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | // structure construction 7 | struct node 8 | { 9 | int data; 10 | struct node *next; 11 | }; 12 | struct node *start = NULL; // start - global variable 13 | 14 | // prototype 15 | void create(); 16 | void bubble_sort(struct node *start); 17 | void display(); 18 | void swap(struct node *a, struct node *b); 19 | 20 | int main(void) 21 | { 22 | int option; 23 | 24 | do 25 | { 26 | 27 | printf("\n \n **************** CHOOSE AN OPTION **********************"); 28 | printf("\n \n 1. Create a linked-list."); 29 | printf("\n 2. Display a linked-list."); 30 | printf("\n 3. BUBBLE-SORT execution.\n \n"); 31 | printf("\n ********************** EXIT ***************************** "); 32 | printf("\n \n Choose a no. -> "); 33 | scanf("%d", &option); 34 | 35 | switch (option) 36 | { 37 | case 1: 38 | create(); 39 | break; 40 | case 2: 41 | display(); 42 | break; 43 | case 3: 44 | bubble_sort(start); 45 | break; 46 | default: 47 | printf("CHOOSE THE OPTION MENTIONED IN THE MENU....."); 48 | break; 49 | } 50 | 51 | } while ((option >= 1) && (option < 4)); 52 | 53 | return 0; 54 | } 55 | 56 | void create() 57 | { 58 | int i, n, num; 59 | struct node *newnode, *ptr; // variables of struct node pointer types 60 | printf("Enter the no. of nodes : "); 61 | scanf("%d", &n); 62 | 63 | for (i = 0; i < n; i++) 64 | { 65 | printf("Enter a no. --> "); 66 | scanf("%d", &num); 67 | newnode = (struct node *)malloc(sizeof(struct node)); 68 | newnode->data = num; 69 | if (start == NULL) 70 | { 71 | start = newnode; 72 | newnode->next = NULL; 73 | } 74 | else 75 | { 76 | ptr = start; 77 | while (ptr->next != NULL) 78 | { 79 | ptr = ptr->next; 80 | } 81 | ptr->next = newnode; 82 | newnode->next = NULL; 83 | } 84 | } 85 | } 86 | 87 | void display() 88 | { 89 | printf("\n <------------- Display Successfully ------------->\n"); 90 | struct node *ptr; 91 | ptr = start; 92 | while (ptr != NULL) 93 | { 94 | printf("%d \t", ptr->data); 95 | ptr = ptr->next; 96 | } 97 | } 98 | 99 | void bubble_sort(struct node *start) 100 | { 101 | int swapped; 102 | struct node *ptr, *q = NULL; 103 | 104 | if (start == NULL) 105 | return; 106 | 107 | do 108 | { 109 | swapped = 0; 110 | ptr = start; 111 | while (ptr->next != q) 112 | { 113 | if (ptr->data > ptr->next->data) 114 | { 115 | swap(ptr, ptr->next); 116 | swapped = 1; 117 | } 118 | ptr = ptr->next; 119 | } 120 | q = ptr; 121 | 122 | } while (swapped); 123 | // return ; 124 | 125 | printf("-------- SUCCESSFULLY SORTED ------"); 126 | } 127 | 128 | void swap(struct node *a, struct node *b) 129 | { 130 | int temp; 131 | temp = a->data; 132 | a->data = b->data; 133 | b->data = temp; 134 | } 135 | -------------------------------------------------------------------------------- /SortingTechniques/INSERTION-SORT.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | int n, i, j, key, a[100]; 7 | printf("Enter the no. of elements in the array : "); 8 | scanf("%d", &n); 9 | 10 | printf("Enter %d the values of the array : \n", n); 11 | for (i = 0; i < n; i++) 12 | scanf("%d", &a[i]); 13 | 14 | for (i = 1; i < n; i++) 15 | { 16 | key = a[i]; 17 | j = i - 1; 18 | while ((j >= 0) && (a[j] > key)) 19 | { 20 | a[j + 1] = a[j]; 21 | j = j - 1; 22 | } 23 | a[j + 1] = key; 24 | } 25 | 26 | printf("******** Äfter INSERTION_SORT ********\n"); 27 | printf("SORTED ARRAY ------>\n"); 28 | for (i = 0; i < n; i++) 29 | printf("%d\t", a[i]); 30 | } -------------------------------------------------------------------------------- /SortingTechniques/SELECTION-SORT.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int main() 7 | { 8 | int n, i, j, min, temp, a[100000], t; 9 | // using clock_t to store time 10 | clock_t start, end; 11 | double time_taken; 12 | 13 | printf("Enter the no. of elements in the array : "); 14 | scanf("%d", &n); 15 | 16 | printf("Enter %d the values of the array : \n", n); 17 | for (i = 0; i < n; i++) 18 | { 19 | // scanf("%d", &a[i]); 20 | a[i] = (rand() % 50) + 10; 21 | printf("%d\n",a[i]); 22 | // scanf("%d", rand()); 23 | } 24 | 25 | start = clock(); 26 | for (i = 0; i < n - 1; i++) 27 | { 28 | min = i; 29 | for (j = i + 1; j < n; j++) 30 | { 31 | if (a[j] < a[min]) 32 | { 33 | min = j; 34 | } 35 | } 36 | 37 | if (min != i) 38 | { 39 | temp = a[i]; 40 | a[i] = a[min]; 41 | a[min] = temp; 42 | } 43 | } 44 | end = clock(); 45 | t = (end - start); 46 | time_taken = (double)t / CLOCKS_PER_SEC; 47 | 48 | printf("******** Äfter SELECTION_SORT ********\n"); 49 | printf("SORTED ARRAY ------>\n"); 50 | /* for (i = 0; i < n; i++) 51 | printf("%d\t", a[i]); */ 52 | printf("\n TIME-TAKEN for %d no. in an array : %lf", n, time_taken); 53 | } -------------------------------------------------------------------------------- /SortingTechniques/SHELL-SORT.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void shellsort(int arr[], int num) 5 | { 6 | int gap, j, k, tmp; 7 | for (gap = num / 2; gap > 0; gap = gap / 2) 8 | { 9 | for (j = gap; j < num; j++) 10 | { 11 | for (k = j - gap; k >= 0; k = k - gap) 12 | { 13 | if (arr[k + gap] >= arr[k]) 14 | break; 15 | else 16 | { 17 | tmp = arr[k]; 18 | arr[k] = arr[k + gap]; 19 | arr[k + gap] = tmp; 20 | } 21 | } 22 | } 23 | } 24 | } 25 | int main() 26 | { 27 | int arr[30], k, num; 28 | 29 | printf("Enter total no. of elements : "); 30 | scanf("%d", &num); 31 | printf("\nEnter %d numbers:\n ", num); 32 | 33 | for (k = 0; k < num; k++) 34 | scanf("%d", &arr[k]); 35 | 36 | shellsort(arr, num); 37 | 38 | printf("******** After SHELL-SORT ********\n"); 39 | printf("SORTED ARRAY ------>\n"); 40 | for (k = 0; k < num; k++) 41 | printf("%d\t", arr[k]); 42 | } 43 | -------------------------------------------------------------------------------- /TREE/.gitignore: -------------------------------------------------------------------------------- 1 | 2 | *.exe -------------------------------------------------------------------------------- /TREE/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "*.tcc": "cpp", 4 | "deque": "cpp", 5 | "list": "cpp", 6 | "string": "cpp", 7 | "unordered_map": "cpp", 8 | "unordered_set": "cpp", 9 | "vector": "cpp", 10 | "iostream": "cpp", 11 | "initializer_list": "cpp", 12 | "valarray": "cpp" 13 | } 14 | } -------------------------------------------------------------------------------- /TREE/BSTree.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | using namespace std; 9 | 10 | struct BST_Node 11 | { 12 | int data; 13 | struct BST_Node *right; // right child 14 | struct BST_Node *left; // left child 15 | }; 16 | struct BST_Node *root = NULL, *newnode = NULL; // Global variables are declared here... 17 | 18 | // prototypes of the declared functions 19 | void insertNode(); 20 | void create(); 21 | void binarySearch(struct BST_Node *root); 22 | void preOrder(struct BST_Node *tree); 23 | void inOrder(struct BST_Node *tree); 24 | void postOrder(struct BST_Node *tree); 25 | void levelOrderTraversal(struct BST_Node *root); 26 | bool checkNodeExsist(struct BST_Node *root, int key); 27 | int tree_height(struct BST_Node *root); 28 | void ancestors(struct BST_Node *root, int val); 29 | BST_Node *commonAncestors(struct BST_Node *root, int a, int b); 30 | BST_Node *deleteNode(struct BST_Node *root, int key); 31 | void isHeap(struct BST_Node *root); 32 | 33 | int main(void) 34 | { 35 | BST_Node *nodeVal; 36 | int option, key, height, ans, a, b; 37 | bool res; 38 | 39 | do 40 | { 41 | printf("\n \n **************** CHOOSE AN OPTION **********************"); 42 | printf("\n \n 1. Create a Binary_Search_Tree."); 43 | printf("\n 2. Display the PRE-ORDER TRAVERSAL of the Binary_Search_Tree."); 44 | printf("\n 3. Display the IN-ORDER TRAVERSAL of the Binary_Search_Tree."); 45 | printf("\n 4. Display the POST-ORDER TRAVERSAL of the Binary_Search_Tree."); 46 | printf("\n 5. Display the LEVEL-ORDER TRAVERSAL using Queue of the Binary_Search_Tree."); 47 | printf("\n 6. Search if a node exsist or not."); 48 | printf("\n 7. Height of the Tree."); 49 | printf("\n 8. Ancestors of a Node in BST ."); 50 | printf("\n 9. Common Ancestors of 2 Nodes in BST."); 51 | printf("\n 10. Delete a NODE in BST."); 52 | printf("\n 11. Check whether this BST is a Heap or Not .\n"); 53 | printf("\n ********************** EXIT *****************************"); 54 | printf("\n \n Choose a no. -> "); 55 | scanf("%d", &option); 56 | 57 | switch (option) 58 | { 59 | case 1: 60 | insertNode(); 61 | break; 62 | case 2: 63 | cout << "______ Post-Order traversal of a Binary Search Tree ______\n"; 64 | preOrder(root); 65 | break; 66 | case 3: 67 | cout << "______ Post-Order traversal of a Binary Search Tree ______\n"; 68 | inOrder(root); 69 | break; 70 | case 4: 71 | cout << "______ Post-Order traversal of a Binary Search Tree ______\n"; 72 | postOrder(root); 73 | break; 74 | case 5: 75 | cout << "______ Level-Order traversal of a Binary Search Tree ______\n"; 76 | levelOrderTraversal(root); 77 | break; 78 | case 6: 79 | cout << "______ Node Exsist Checker of a Binary Search Tree ______\n"; 80 | cout << "Enter a no. for searching : "; 81 | cin >> key; 82 | ans = checkNodeExsist(root, key); 83 | if (ans) 84 | cout << "YES " << key << " ALREADY EXSIST IN THE TREE \n"; 85 | else 86 | cout << "NO " << key << " NOT PRESENT IN THE TREE \n"; 87 | break; 88 | case 7: 89 | height = tree_height(root); 90 | cout << "Height of the Binary Tree ----> " << height << endl; 91 | break; 92 | case 8: 93 | cout << "______ Ancestors of a NODE in a Binary Search Tree ______\n"; 94 | cout << "Enter a no. for whose ancestor you want to find: "; 95 | cin >> key; 96 | ancestors(root, key); 97 | break; 98 | case 9: 99 | cout << "______ Common Ancestors of 2 NODE in a Binary Search Tree ______\n"; 100 | cout << "Enter 2 values for whose Common Ancestors you want to find: "; 101 | cin >> a >> b; 102 | nodeVal = commonAncestors(root, a, b); 103 | cout << nodeVal->data << "\t"; 104 | break; 105 | case 10: 106 | cout << "______ Delete a NODE in BST ______\n"; 107 | cout << "Node You Want to Delete : "; 108 | cin >> key; 109 | deleteNode(root, key); 110 | break; 111 | case 11: 112 | isHeap(root); 113 | break; 114 | default: 115 | printf("CHOOSE THE OPTION MENTIONED IN THE MENU....."); 116 | break; 117 | } 118 | 119 | } while ((option >= 1) && (option <= 20)); 120 | return 0; 121 | } 122 | 123 | // __________________ CREATION OF Binary_Search_Tree. _________________ 124 | void create() 125 | { 126 | int value; 127 | cout << "Enter the DATA of the node to be inserted : "; 128 | cin >> value; 129 | newnode = (struct BST_Node *)malloc(sizeof(struct BST_Node)); 130 | newnode->data = value; 131 | newnode->left = newnode->right = NULL; 132 | } 133 | 134 | void insertNode() 135 | { 136 | create(); 137 | if (root == NULL) 138 | root = newnode; 139 | else 140 | binarySearch(root); 141 | cout << "***** Successfully inserted a node in the Binary_Search_Tree *******"; 142 | } 143 | 144 | // finding the position of the NEWNODE 145 | void binarySearch(struct BST_Node *tree) 146 | { 147 | if ((newnode->data > tree->data) && (tree->right != NULL)) 148 | binarySearch(tree->right); 149 | else if ((newnode->data > tree->data) && (tree->right == NULL)) 150 | tree->right = newnode; 151 | else if ((newnode->data < tree->data) && (tree->left != NULL)) 152 | binarySearch(tree->left); 153 | else if ((newnode->data < tree->data) && (tree->left == NULL)) 154 | tree->left = newnode; 155 | } 156 | // __________________________________________________________________________ 157 | 158 | // PREORDER TRAVERSAL --------- RECURSIVE METHOD 159 | void preOrder(struct BST_Node *tree) 160 | { 161 | if (tree == NULL) 162 | { 163 | printf("No elements in a tree to display "); 164 | return; 165 | } 166 | cout << tree->data << '\t'; 167 | if (tree->left != NULL) 168 | preOrder(tree->left); 169 | if (tree->right != NULL) 170 | preOrder(tree->right); 171 | } 172 | 173 | // INORDER TRAVERSAL --------- RECURSIVE METHOD 174 | void inOrder(struct BST_Node *tree) 175 | { 176 | if (tree == NULL) 177 | { 178 | printf("No elements in a tree to display "); 179 | return; 180 | } 181 | if (tree->left != NULL) 182 | preOrder(tree->left); 183 | cout << tree->data; 184 | if (tree->right != NULL) 185 | preOrder(tree->right); 186 | } 187 | 188 | // POST TRAVERSAL --------- RECURSIVE METHOD 189 | void postOrder(struct BST_Node *tree) 190 | { 191 | if (tree == NULL) 192 | { 193 | printf("No elements in a tree to display "); 194 | return; 195 | } 196 | if (tree->left != NULL) 197 | preOrder(tree->left); 198 | if (tree->right != NULL) 199 | preOrder(tree->right); 200 | cout << tree->data; 201 | } 202 | 203 | // LEVEL ORDER TRAVERSAL OR BREADTH FIRST SEARCH (BFS) using Queue Iterative BFS 204 | void levelOrderTraversal(struct BST_Node *root) // Time Complexity : O(n) 205 | { 206 | /* 207 | ===== ALGORITHM ====== 208 | if(root == NULL) return 209 | else 210 | { 211 | * create a QUEUE data structure 212 | * enqueue the root 213 | * Loop unless Q not Empty 214 | --- print --- 215 | Dequeue(remove) the front node 216 | check its left child ? Q.push() 217 | check its right child ? Q.push() 218 | } 219 | */ 220 | 221 | if (root == NULL) 222 | return; 223 | 224 | queue Q; 225 | Q.push(root); // Enqueue 226 | 227 | while (!Q.empty()) 228 | { 229 | BST_Node *FrontNode = Q.front(); 230 | cout << FrontNode->data << "\t"; 231 | Q.pop(); 232 | 233 | // Enqueue left child 234 | if (FrontNode->left != NULL) 235 | Q.push(FrontNode->left); 236 | 237 | // Enqueue right child 238 | if (FrontNode->right != NULL) 239 | Q.push(FrontNode->right); 240 | } 241 | } 242 | 243 | bool checkNodeExsist(struct BST_Node *root, int key) 244 | { 245 | bool responseL, responseR; 246 | if (root == NULL) 247 | return false; 248 | 249 | if (root->data == key) 250 | return true; 251 | 252 | if (root->left) // If Exsist 253 | { 254 | responseL = checkNodeExsist(root->left, key); 255 | if (responseL) 256 | return true; 257 | } 258 | if (root->right) 259 | { 260 | responseR = checkNodeExsist(root->right, key); 261 | if (responseR) 262 | return true; 263 | } 264 | } 265 | 266 | // Find HEIGHT / DEPTH of a tree, defined by the root node 267 | int tree_height(struct BST_Node *root) // Depth of the tree 268 | { 269 | int leftHt, rightHt; 270 | if (!root) 271 | return 0; 272 | else 273 | { 274 | // Find the height of left, right subtrees 275 | leftHt = tree_height(root->left); 276 | rightHt = tree_height(root->right); 277 | 278 | // Find max(subtree_height) + 1 to get the height of the tree 279 | return max(leftHt, rightHt) + 1; 280 | } 281 | } 282 | 283 | // Find all the ANCESTORS (Parent) of a node 284 | void ancestors(struct BST_Node *root, int val) 285 | { 286 | if (root == NULL) 287 | return; 288 | if (root->data == val) // void return --> jumps out of the function 289 | return; 290 | if (val > root->data) 291 | { 292 | cout << root->data << "\t"; 293 | ancestors(root->right, val); 294 | } 295 | if (val < root->data) 296 | { 297 | cout << root->data << "\t"; 298 | ancestors(root->left, val); 299 | } 300 | } 301 | 302 | BST_Node *commonAncestors(struct BST_Node *root, int a, int b) 303 | { 304 | if (a > root->data && b > root->data) 305 | return commonAncestors(root->right, a, b); 306 | 307 | if (a < root->data && b < root->data) 308 | return commonAncestors(root->left, a, b); 309 | 310 | // cout << root->data << "\t"; 311 | return root; 312 | } 313 | 314 | // ------------------------------------------------------ 315 | // DELETE A NODE OF A BINARY TREE 316 | // ------------------------------------------------------- 317 | 318 | BST_Node *LastRightChild_Finder(BST_Node *root) 319 | { 320 | if (root->right == NULL) // means Last Child 321 | return root; 322 | 323 | LastRightChild_Finder(root->right); 324 | } 325 | 326 | BST_Node *Helper(BST_Node *root) 327 | { 328 | if (root->right == NULL) 329 | return root->left; 330 | 331 | if (root->left == NULL) 332 | return root->right; 333 | 334 | BST_Node *RightChild = root->right; 335 | BST_Node *LastChild = LastRightChild_Finder(root->left); // Root->Left Max Node(at the right) will get connected with the Right SubTree. 336 | LastChild->right = RightChild; 337 | 338 | return root->left; 339 | } 340 | 341 | BST_Node *deleteNode(struct BST_Node *root, int key) 342 | { 343 | if (!root) 344 | return NULL; 345 | 346 | if (root->data == key) 347 | Helper(root); 348 | 349 | BST_Node *storeRoot = root; // storing the root as later it may change 350 | 351 | while (root != NULL) 352 | { 353 | if (key > root->data) // Right Subtree 354 | { 355 | if (root->right && root->right->data == key) 356 | { 357 | root->right = Helper(root->right); 358 | break; 359 | } 360 | else 361 | root = root->right; 362 | } 363 | 364 | else if (key < root->data) // Left Subtree 365 | { 366 | if (root->left && root->left->data == key) 367 | { 368 | root->left = Helper(root->left); 369 | break; 370 | } 371 | else 372 | root = root->left; 373 | } 374 | } 375 | 376 | return storeRoot; 377 | } 378 | 379 | // _______________________ COUNT NUMBER OF NODES _________________________ 380 | int countNodes(struct BST_Node *root) 381 | { 382 | if (root == NULL) 383 | return 0; 384 | else 385 | return (countNodes(root->left) + countNodes(root->right) + 1); // left subtree + right subtree + 1 386 | } 387 | 388 | // checking Complete Binary_Search_Tree or Not 389 | // ITERATIVE METHOD ----- 390 | bool checkCompleteBT_iterative(struct BST_Node *root) // Iterative Method for checking Complete Binary_Search_Tree or Not 391 | { 392 | bool flag = true; 393 | queue Q; 394 | Q.push(root); 395 | 396 | while (!Q.empty()) 397 | { 398 | BST_Node *temp = Q.front(); 399 | Q.pop(); 400 | 401 | if (temp->left) // exsist ? 402 | { 403 | if (flag == false) 404 | return false; 405 | 406 | Q.push(temp->left); 407 | } 408 | else 409 | flag = false; // Not Binary Tree 410 | // ------------------------ 411 | if (temp->right) 412 | { 413 | if (flag == false) 414 | return false; 415 | 416 | Q.push(temp->right); 417 | } 418 | else 419 | flag = false; 420 | } 421 | return true; 422 | } 423 | 424 | // RECURSIVE METHOD ----- 425 | bool checkCompleteBT_recursive(struct BST_Node *root, int index, int totalNodes) 426 | { 427 | if (root == NULL) 428 | return true; 429 | 430 | if (index >= totalNodes) 431 | return false; 432 | 433 | return (checkCompleteBT_recursive(root->left, 2 * index + 1, totalNodes) && checkCompleteBT_recursive(root->right, 2 * index + 1, totalNodes)); 434 | } 435 | 436 | bool heapCheck(struct BST_Node *root) 437 | { 438 | 439 | if (root->left == NULL && root->right == NULL) 440 | return true; 441 | 442 | // only Check Right Subtree as -----------> for Complete BT Right subtree doesnt exsist without Left 443 | if (root->right == NULL) 444 | return (root->data >= root->left->data); // as MaxHeap 445 | 446 | else 447 | { 448 | if (root->data >= root->left->data && root->data >= root->right->data) 449 | return ((heapCheck(root->left)) && (heapCheck(root->right))); 450 | else 451 | return (false); 452 | } 453 | } 454 | 455 | void isHeap(struct BST_Node *root) 456 | { 457 | int totalNodes = countNodes(root), index = 0; 458 | // bool checkComplete = checkCompleteBT_iterative(root); 459 | bool checkComplete = checkCompleteBT_recursive(root, index, totalNodes); 460 | bool checkHeap = heapCheck(root); 461 | 462 | if (checkComplete && checkHeap) 463 | cout << "It is a Complete Binary Tree as well as follows HEAP" << endl; 464 | else 465 | cout << "OOpssss this tree is not a Heap !! " << endl; 466 | } -------------------------------------------------------------------------------- /TREE/TREE.txt: -------------------------------------------------------------------------------- 1 | 2 | ________________________________________ 3 | // TREE \\ 4 | ________________________________________ 5 | 6 | 7 | 1) FULL BINARY TREE --> If every node has 0 or 2 children, in which all nodes except leaf nodes have two children. 8 | 9 | 18 10 | / \ 11 | 15 30 12 | / \ / \ 13 | 40 50 100 40 14 | 15 | 16 | 18 17 | / \ 18 | 40 30 19 | / \ 20 | 100 40 21 | 22 | 23 | 2) COMPLETE BINARY TREE --> If all the levels are completely filled except possibly the last level and the last level has all keys as LEFT as possible 24 | 25 | 18 26 | / \ 27 | 15 30 28 | / \ / \ 29 | 40 50 100 40 30 | / \ / 31 | 8 7 9 32 | 33 | 34 | 3) PERFECT BINARY TREE --> When all the internal nodes have two children and all leaf nodes are at the same level. 35 | 36 | 10 37 | / \ 38 | 15 30 39 | 40 | 41 | :: BST properties :: 42 | 4) Inorder Traversal --> nodes are in sorted order -------------------------------------------------------------------------------- /TREE/tempCodeRunnerFile.cpp: -------------------------------------------------------------------------------- 1 | nt key) --------------------------------------------------------------------------------