Skip to content

Commit 38f5b27

Browse files
vidit-agarwalegonSchiele
authored andcommitted
Added c++ implementation (egonSchiele#85)
* Added c++ implementation * Added Bfs implementation in c++
1 parent 0d5d016 commit 38f5b27

File tree

2 files changed

+121
-0
lines changed

2 files changed

+121
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#include "iostream"
2+
using namespace std;
3+
4+
void binarySearch(int data_array[], int element, int len)
5+
{
6+
int low = 0;
7+
int high = len;
8+
while (low <= high)
9+
{
10+
int mid = (low + high)/2;
11+
int guess = data_array[mid];
12+
13+
if (guess == element)
14+
{
15+
cout<<"Element found at "<<mid<<" th index"<<endl ;
16+
return ;
17+
}
18+
else if (guess > element)
19+
{
20+
high = mid - 1;
21+
}
22+
else
23+
{
24+
low = mid + 1;
25+
}
26+
}
27+
cout<<"Element Not Found"<<endl ;
28+
return ; //number not found
29+
}
30+
int main()
31+
{
32+
int data_array[] = {2,10,23,44,100,121};
33+
int length = sizeof(data_array) / sizeof(int);
34+
35+
binarySearch(data_array, 3, length) ; // not found case
36+
binarySearch(data_array, 2, length) ; // found at corner case
37+
binarySearch(data_array, 44, length) ; //found at middle case
38+
return 0;
39+
}
40+
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
#include <iostream>
2+
#include <map>
3+
#include <list>
4+
#include <queue>
5+
using namespace std;
6+
template <typename T>
7+
class Graph {
8+
map <T , list<T>> adjList ;
9+
10+
public :
11+
Graph()
12+
{}
13+
14+
void addEdge(T u , T v , bool bidir = true)
15+
{
16+
adjList[u].push_back(v);
17+
if(bidir)
18+
adjList[v].push_back(u) ;
19+
}
20+
21+
void printAdjList()
22+
{
23+
for( auto key : adjList)
24+
{
25+
cout<<key.first<<"->" ;
26+
for(auto neighbours : key.second)
27+
cout<<neighbours<<"," ;
28+
29+
cout<<endl;
30+
}
31+
}
32+
33+
void bfs(T src)
34+
{
35+
queue<T> q;
36+
37+
map<T , bool> visited ;
38+
39+
q.push(src) ;
40+
visited[src] = true ;
41+
42+
while(!q.empty())
43+
{
44+
T node = q.front() ;
45+
cout<<node<<" ," ;
46+
q.pop();
47+
48+
//push the neighbours
49+
50+
for(auto neighbours : adjList[node])
51+
{
52+
if(!visited[neighbours])
53+
{
54+
q.push(neighbours) ;
55+
visited[neighbours] = true ;
56+
}
57+
}
58+
}
59+
}
60+
} ;
61+
62+
int main() {
63+
Graph<int> g ;
64+
65+
//adding the edges in the Graph
66+
g.addEdge(0,1);
67+
g.addEdge(1,2);
68+
g.addEdge(0,4);
69+
g.addEdge(2,4);
70+
g.addEdge(2,3);
71+
g.addEdge(3,5);
72+
g.addEdge(3,4);
73+
74+
cout <<"The Graph is"<<endl;
75+
g.printAdjList();
76+
cout<<endl;
77+
78+
cout<<"The Breadth First Search from Node 0"<<endl;
79+
80+
g.bfs(0) ;
81+
}

0 commit comments

Comments
 (0)