diff --git a/graphs/count_diconnected_components.cpp b/graphs/count_diconnected_components.cpp new file mode 100644 index 00000000..0ee61601 --- /dev/null +++ b/graphs/count_diconnected_components.cpp @@ -0,0 +1,69 @@ +#include +#include +using namespace std; + +int count=1; +// Graph class represents a directed graph +// using adjacency list representation +class Graph +{ + int V; + list *adj; + void DFSUtil(int v, bool visited[]); +public: + Graph(int V); + void addEdge(int v, int w); + void DFS(int v); +}; + +Graph::Graph(int V) +{ + this->V = V; + adj = new list[V]; +} + +void Graph::addEdge(int v, int w) +{ + adj[v].push_back(w); // Add w to v’s list. +} + +void Graph::DFSUtil(int v, bool visited[]) +{ + visited[v] = true; + list::iterator i; + for (i = adj[v].begin(); i != adj[v].end(); ++i) + if (!visited[*i]) + DFSUtil(*i, visited); +} +void Graph::DFS(int v) +{ + bool *visited = new bool[V]; + for (int i = 0; i < V; i++) + visited[i] = false; + DFSUtil(v, visited); + for (int i = 0; i < V; i++) + if(visited[i] == false) + { + count++; + DFSUtil(i, visited); + } +} + +int main() +{ + Graph g(9); + g.addEdge(0, 1); + g.addEdge(0, 2); + g.addEdge(1, 2); + g.addEdge(2, 0); + g.addEdge(2, 3); + g.addEdge(3, 3); + g.addEdge(4, 5); + g.addEdge(6, 7); + g.addEdge(6, 8); + + g.DFS(2); + cout << "Number of disconnected components in the given graph is : " < +using namespace std; + +typedef long long int ll; + +ll power(ll x, ll y, ll p) +{ + if(x==0) + return 0; + if(y==0) + return 1; + if (y%2==0) + { + ll g=power(x,y/2,p); + return (g*g)%p; + } + else + { + ll g=power(x,y/2,p); + return (x*(g*g)%p)%p; + } +} + +int main() +{ + ll x = 2,y = 5, p = 13; + printf("Power is %lld", power(x, y, p)); + return 0; +} \ No newline at end of file diff --git a/sorting/selection_sort.cpp b/sorting/selection_sort.cpp new file mode 100644 index 00000000..0ba110d0 --- /dev/null +++ b/sorting/selection_sort.cpp @@ -0,0 +1,49 @@ +// C++ implementation of selection sort +// +// Author: Rituparno Biswas + +#include + +// Swap elements +void swap(int *x, int *y) +{ + int temp = *x; + *x = *y; + *y = temp; +} + +// Implement selection sort +void selectionSort(int arr[], int n) +{ + int i, j, min_id; + for (i = 0; i < n-1; i++) + { + min_id=i; + for (j = i+1; j < n; j++) + if (arr[min_id] > arr[j]) + min_id=j; + swap(&arr[i], &arr[min_id]); + } +} + +// Function to print elements +void printArray(int arr[], int size) +{ + int i; + for (i=0; i < size; i++) + printf("%d ", arr[i]); + printf("\n"); +} + +// test +int main() +{ + int arr[] = {46, 24, 33, 10, 2, 81, 50}; + int n = sizeof(arr)/sizeof(arr[0]); + printf("Unsorted array: \n"); + printArray(arr, n); + selectionSort(arr, n); + printf("Sorted array: \n"); + printArray(arr, n); + return 0; +}