Skip to content

Commit

Permalink
Merge pull request technojam#217 from gunjan543/pull-request-prims
Browse files Browse the repository at this point in the history
Prims Algorithm for Minimum Spanning Tree
  • Loading branch information
BetaZeon authored Oct 10, 2020
2 parents d6723bf + 15b32b5 commit 0e52815
Show file tree
Hide file tree
Showing 2 changed files with 113 additions and 0 deletions.
71 changes: 71 additions & 0 deletions Prims.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
#include<iostream>
#include<vector>
#include<queue>
using namespace std;

class Graph{
//adjacency list
vector<pair<int,int> >*l;
int V;

public:
Graph(int n){
V=n;
l=new vector<pair<int,int>>[V];
}
void addEdge(int x,int y,int w){
l[x].push_back({y,w});
l[y].push_back({x,w});
}

int prim_mst(){
// Syntax to create a min heap for priority queue
// priority_queue <int, vector<int>, greater<int>> g = gq
priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> Q;
//make another array for mst set
//visited array that denotes whether a node has been included in MST or not
bool *vis=new bool[V]{0};
int ans=0;
//begin start from src node and push src node
Q.push({0,0});

while(!Q.empty()){
//pick out the edge with min weight
//because its min heap
auto best=Q.top();
Q.pop()

int to=best.second;
int weight=best.first;

if(vis[to]){
//discard edge , and continue
continue;
}
//otherwise take the current edge
ans+=weight;
vis[to]=1;

//add the new edges in the queue
for(auto x:l[to]){
if(vis[x.first]==0){
Q.push({x.second,x.first});
}
}
}
return ans;

}
};
int main(){
int n,m;
cin>>n>>m;
Graph g(n);
for(int i=0;i<m;i++){
int x,y,w;
cin>>x>>y>>w;
g.addEdge(x-1,y-1,w);
}
cout<<g.prim_mst()<<endl;
return 0;
}
42 changes: 42 additions & 0 deletions quickSort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
//inspace algorithm
//divide and conquer
//N log N on avg case and N^2 worst case
#include<iostream>
using namespace std;

int partition(int *a, int s, int e) {
int i = s - 1;
int j = s;
int pivot = a[e];
for (; j <= e - 1;) {
if (a[j] <= pivot) {
i = i + 1;
swap(a[i], a[j]);
}
j = j + 1;
}
swap(a[i + 1], a[e]);
return i + 1;

}
void quick_sort(int *arr, int s, int e) {
if (s >= e) {
return;
}
//recursive case
int p = partition(arr, s, e);
//left part
quick_sort(arr, s, p - 1);
//right part
quick_sort(arr, p + 1, e);
}

int main() {
int arr[] = {2, 3, 8, 6, 1, 5, 4};
quick_sort(arr, 0, 6);

for (int i = 0; i <= 6; i++) {
cout << arr[i] << endl;
}
return 0;
}

0 comments on commit 0e52815

Please sign in to comment.