├── image.jpg ├── Patterns ├── Upper Triangle LEFT.cpp ├── Square Pattern.cpp ├── pattern1108.cpp ├── Lower Triangle LEFT.cpp ├── Lower Triangle LEFT (numbers).cpp ├── Inverted Tree Pattern.cpp ├── Upper Tree Triangle.cpp ├── Increment by 1 Lower LEFT Trianlge.cpp ├── LEFT (base) Pyramid.cpp ├── Pattern9.cpp ├── ALternate 1 0 Lower LEFT Triangle.cpp ├── Pascals Triangle.cpp └── Bell Triangle.c ├── Sorting ├── insertionsort.cpp ├── selectionsort.c ├── bubblesort.c ├── radixsort.cpp ├── countingsort.cpp ├── quicksort.c ├── shellsort.c ├── bucketsort.cpp ├── count_sort.c ├── Heapsort.cpp ├── selectionsort2.c └── mergesort.cpp ├── duplicate.c ├── Searching problems ├── LINEAR_SEARCH.cpp ├── DepthFirstSearch.c ├── ternarySearch.cpp ├── BINARY_SEARCH.cpp ├── jumpsearch.cpp └── BreadthFirstSearch.cpp ├── main.c ├── Graph Programs ├── dfs.c ├── graph_connected_components.cpp ├── bfs.c ├── graph_adjacency_matrix.cpp ├── graph_dfs.cpp ├── graph_bfs.cpp ├── dijkstra.cpp ├── graph_topological_sort.cpp ├── graph_adjacency_list.cpp └── graph_kruskals_algorithm.cpp ├── Stack ├── largestRectangleHistogram.cpp ├── Stack.cpp ├── StackLL.cpp ├── reverse-a-string └── Stack2.cpp ├── .gitignore ├── hackt.cbp ├── Plan.md ├── LinkedList ├── SLL.cpp ├── xorlist.c └── DLL.cpp ├── unionarray.c ├── README.md ├── lucky 7 game.c ├── Queue ├── queue.c └── queue ├── Backtracking ├── NQueens.c └── KnightTour.c ├── Searching Techniques └── MEDIAN_SEARCH.cpp ├── Heap └── heap.cpp └── Tree Problems ├── BINARY_SEARCH_TREE.cpp └── TREE.cpp /image.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rishabh-bansal/C-Data-Structures-and-Algorithms/HEAD/image.jpg -------------------------------------------------------------------------------- /Patterns/Upper Triangle LEFT.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | 6 | int n; 7 | cin >> n; 8 | 9 | for( int i = n; i > 0; i-- ){ //Iterating over number of rows backwards from n down to 0 10 | for( int j = 0; j < i; j++ ){ // Number of columns with * will be equal to row number to form an upside down triangle 11 | cout << "*"; 12 | } 13 | cout << endl; 14 | } 15 | 16 | return 0; 17 | } 18 | 19 | /* 20 | 5 21 | 22 | ***** 23 | **** 24 | *** 25 | ** 26 | * 27 | 28 | */ 29 | -------------------------------------------------------------------------------- /Patterns/Square Pattern.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | 6 | int n; 7 | cin >> n; //Input n to create a n*n square of stars (*) 8 | 9 | for( int i = 0; i < n; i++ ){ //Loop to iterate over 'n' number of rows 10 | for( int j = 0; j < n; j++ ){ //Loop to iterate over 'n' columns 11 | cout << "*"; 12 | } 13 | cout << endl; // Print next row in new line 14 | } 15 | return 0; 16 | 17 | } 18 | /* 19 | At n=5, output: 20 | 21 | 5 22 | 23 | ***** 24 | ***** 25 | ***** 26 | ***** 27 | ***** 28 | 29 | */ 30 | -------------------------------------------------------------------------------- /Sorting/insertionsort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void insertionSort(int a[],int n){ 5 | for(int i=1;i=1;j--){ 7 | if (a[j] 2 | #define MAX 100 3 | int main(void) 4 | { 5 | int arr[MAX],i,j,k,n; 6 | printf("Enter the number of elements : "); 7 | scanf("%d",&n); 8 | for(i=0; i=0 && k 2 | using namespace std; 3 | int main() 4 | { 5 | for(int i=5;i>=1;i--) //loop for changing line and giving path for printing pattern format 6 | { 7 | for(int j=1;j<=i;j++)//loop for printing format upper part 8 | { 9 | cout<<"*"; 10 | } 11 | cout< 2 | using namespace std; 3 | 4 | int main(){ 5 | //take input for number of rows 6 | int n; 7 | cin >> n; 8 | 9 | for( int i = 0; i < n; i++ ){ //Iterate over n rows 10 | for( int j = 0; j <= i; j++ ){ // Number of columns will be equal to one more than the row number (since rows are 0 indexed ) 11 | cout << "*"; 12 | } 13 | //cursor will move to new line after complete iterations of column loop 14 | cout << endl; 15 | } 16 | 17 | return 0; 18 | 19 | } 20 | 21 | /* 22 | 23 | at n=5 Output : 24 | 25 | * 26 | ** 27 | *** 28 | **** 29 | ***** 30 | 31 | */ 32 | -------------------------------------------------------------------------------- /duplicate.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | int a[101],i,n,k,c=0,j; 5 | 6 | printf("Enter the value of n not more than 100\n"); 7 | scanf("%d",&n); 8 | 9 | printf("Enter n numbers \n"); 10 | 11 | for(i=0;i 2 | using namespace std; 3 | 4 | int main(){ 5 | 6 | /* Accept the number of rows to be printed */ 7 | int n; 8 | cin >> n; 9 | 10 | /* Print a row 11 | * Number of elements in a row = row count. 12 | * eg. row1 has 1 element, row 2 has 2 elements, so on... 13 | */ 14 | for( int i = 1; i <= n; i++ ){ 15 | /* Print the same number repeatedly */ 16 | for( int j = 1; j <= i; j++ ){ 17 | cout << i; 18 | } 19 | /* Once all the numbers of a row a printed, 20 | * print a newline before starting the next row. 21 | */ 22 | cout << endl; 23 | } 24 | 25 | return 0; 26 | } 27 | 28 | /* 29 | 30 | 5 31 | 32 | 1 33 | 22 34 | 333 35 | 4444 36 | 55555 37 | 38 | */ 39 | -------------------------------------------------------------------------------- /Searching problems/LINEAR_SEARCH.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | const int N = 1000; 5 | int arr[N]; 6 | int n,m,k; 7 | int main() 8 | { 9 | //First we will load our array. It will be consisted of n integers. 10 | scanf("%d",&n); 11 | for(int i=0;i 14 | #include 15 | 16 | int main() 17 | { 18 | int a,i,j,k; 19 | scanf("%d",&a);//taking the input of how many lines the pattern should run. 20 | for(i=0;i // including header file (standard input/output) 2 | int main() // main function starts here(begining) 3 | { 4 | 5 | for(int i=1;i<=5;i++) // this loop is used to print rows(upto 5) 6 | { 7 | for(int j=1;j<=9;j++) // this loop is used to print columns 8 | { 9 | if(j>=i&&j<=10-i) //condition to print * 10 | printf("*"); 11 | else 12 | printf(" "); // if the above condition doesn't satisfies it prints space 13 | } 14 | printf("\n"); /* Used ,Once all the numbers of a row a printed, 15 | print a newline before starting the next row. 16 | */ 17 | } 18 | } 19 | /* 20 | OUTPUT: 21 | 22 | ********* 23 | ******* 24 | ***** 25 | *** 26 | * 27 | 28 | */ 29 | 30 | -------------------------------------------------------------------------------- /Patterns/Upper Tree Triangle.cpp: -------------------------------------------------------------------------------- 1 | #include // including header file (standard input/output) 2 | int main() // main function starts here(begining) 3 | { 4 | 5 | for(int i=1;i<=5;i++) // this loop is used to print rows(upto 5) 6 | { 7 | for(int j=1;j<=9;j++) // this loop is used to print columns 8 | { 9 | if(j>=6-i && j<=4+i) //condition to print * 10 | printf("*"); 11 | else 12 | printf(" "); // if the above condition doesn't satisfies it prints space 13 | } 14 | printf("\n"); /* Used ,Once all the numbers of a row a printed, 15 | print a newline before starting the next row. 16 | */ 17 | } 18 | } 19 | /* 20 | OUTPUT: 21 | 22 | * 23 | *** 24 | ***** 25 | ******* 26 | ********* 27 | 28 | */ 29 | 30 | -------------------------------------------------------------------------------- /Graph Programs/dfs.c: -------------------------------------------------------------------------------- 1 | // Depth first search for graph implementation 2 | #include 3 | 4 | void DFS(int); 5 | int G[10][10],visited[10],n; //n is no of vertices and graph is sorted in array G[10][10] 6 | 7 | void main() 8 | { 9 | int i,j; 10 | printf("Enter number of vertices:"); 11 | 12 | scanf("%d",&n); 13 | 14 | //read the adjecency matrix 15 | printf("\nEnter adjecency matrix of the graph:"); 16 | 17 | for(i=0;i 2 | #include 3 | int a[20][20],reach[20],n; 4 | void dfs(int v) 5 | { 6 | int i; 7 | reach[v]=1; 8 | for(i=1;i<=n;i++) 9 | if(a[v][i] && !reach[i]) 10 | { 11 | printf("\n %d->%d",v,i); 12 | dfs(i); 13 | } 14 | } 15 | void main() 16 | { 17 | int i,j,count=0; 18 | clrscr(); 19 | printf("\n Enter number of vertices:"); 20 | scanf("%d",&n); 21 | for(i=1;i<=n;i++) 22 | { 23 | reach[i]=0; 24 | for(j=1;j<=n;j++) 25 | a[i][j]=0; 26 | } 27 | printf("\n Enter the adjacency matrix:\n"); 28 | for(i=1;i<=n;i++) 29 | for(j=1;j<=n;j++) 30 | scanf("%d",&a[i][j]); 31 | dfs(1); 32 | printf("\n"); 33 | for(i=1;i<=n;i++) 34 | { 35 | if(reach[i]) 36 | count++; 37 | } 38 | if(count==n) 39 | printf("\n Graph is connected"); 40 | else 41 | printf("\n Graph is not connected"); 42 | getch(); 43 | -------------------------------------------------------------------------------- /Stack/largestRectangleHistogram.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | int main() { 6 | int n; 7 | int a[]={6,2,5,4,5,1,6}; //input array 8 | n = sizeof(a)/sizeof(a[0]); 9 | int i,q; 10 | stack s; // stack to calculate max area 11 | i=0; 12 | int area,maxarea=INT_MIN; 13 | while(i 2 | using namespace std; 3 | 4 | int main(){ 5 | 6 | /* Accept the number of rows to be printed */ 7 | int n; 8 | cin >> n; 9 | 10 | /* Initialise the number to be printed */ 11 | int count = 1; 12 | 13 | /* Begin printing numbers from 1 to n */ 14 | 15 | /* Print a row 16 | * Number of elements in a row = row count. 17 | * eg. row1 has 1 element, row 2 has 2 elements, 18 | */ 19 | for( int i = 0; i < n; i++ ){ 20 | /* Print the numbers in a particular row. 21 | * Each number is followed by a single space 22 | */ 23 | for( int j = 0; j <= i; j++ ){ 24 | cout << count << " "; 25 | count++; 26 | } 27 | /* Once all the numbers of a row a printed, 28 | * print a newline before starting the next row. 29 | */ 30 | cout << endl; 31 | } 32 | 33 | return 0; 34 | 35 | } 36 | 37 | /* 38 | 39 | 5 40 | 41 | 1 42 | 2 3 43 | 4 5 6 44 | 7 8 9 10 45 | 11 12 13 14 15 46 | 47 | */ 48 | -------------------------------------------------------------------------------- /Sorting/bubblesort.c: -------------------------------------------------------------------------------- 1 | #include 2 | #define MAX 100 3 | int main(void) 4 | { 5 | int arr[MAX],i,j,temp,n,xchanges; 6 | printf("Enter the number of elements : "); 7 | scanf("%d",&n); 8 | for(i=0; i arr[j+1]) 24 | { 25 | //Swapping the elements 26 | temp = arr[j]; 27 | arr[j] = arr[j+1]; 28 | arr[j+1] = temp; 29 | xchanges++; 30 | } 31 | } 32 | if(xchanges==0) /*If list is sorted*/ 33 | break; 34 | } 35 | printf("Sorted list is :\n"); 36 | for(i=0; i 2 | using namespace std; 3 | 4 | void countSort(int arr[], int n, int exp){ 5 | int output[n+1]; // output array 6 | int i,freq[10] = {0}; 7 | for(i=0;i=0;i--){ 12 | output[freq[(arr[i]/exp)%10]-1]=arr[i]; 13 | freq[(arr[i]/exp)%10]--; 14 | } 15 | for (i = 0; i < n; i++) 16 | arr[i] = output[i]; 17 | } 18 | void radixsort(int arr[], int n) 19 | { 20 | int m = arr[0]; 21 | for(int i=1;im) 23 | m=arr[i]; 24 | for (int exp = 1; m/exp > 0; exp *= 10) 25 | countSort(arr, n, exp); 26 | } 27 | void print(int arr[],int n){ 28 | for (int i=0;i 2 | using namespace std; 3 | 4 | int main(){ 5 | 6 | int n; 7 | cin >> n; // Accept n to construct : a right triangle with n rows followed by an upside down right triangle with n rows 8 | 9 | for( int i = 0; i < n; i++ ){ // Iterate over the number of rows for first triangle 10 | for( int j = 0; j <= i; j++ ){ // Number of stars in a column will be equal to the row number we are at currently. 11 | cout << "*"; // Print * 12 | } 13 | cout << endl; // Mover over to the next row 14 | } 15 | 16 | for( int i = n-1; i > 0; i-- ){ // Iterate backwards from n to 0 to construct an upside down triangle with n rows 17 | for( int j = 0; j < i; j++ ){ // Number of stars in a column will be equal to the row number we are at currently. 18 | cout << "*"; // Print * 19 | } 20 | cout << endl; // Move to the next row 21 | } 22 | 23 | return 0; 24 | 25 | } 26 | 27 | /* 28 | 29 | 5 30 | 31 | * 32 | ** 33 | *** 34 | **** 35 | ***** 36 | **** 37 | *** 38 | ** 39 | * 40 | 41 | */ 42 | -------------------------------------------------------------------------------- /Patterns/Pattern9.cpp: -------------------------------------------------------------------------------- 1 | /*program to print the following pattern:- 2 | * 3 | * * 4 | * * * 5 | * * * * 6 | * * * * * 7 | -----------------------------------------------------------------------------*/ 8 | 9 | 10 | #include //header file for input and output 11 | #include //header file for direct run 12 | void main() //main function excute from here 13 | { 14 | int i,j,k,t=0; //declerations of the variables 15 | clrscr(); //for clearing the screen 16 | for (i=1; i<=5; i++) //loop for rows 17 | { 18 | for (k=t; k<5; k++) // loops for printins spaces 19 | { 20 | printf(" "); //printing spaces 21 | } 22 | for (j=0; j< i; j++) //loop for printing star 23 | { 24 | printf(" * ");//printing * 25 | t = t + 1; //updating the variable t 26 | } 27 | printf("\n"); //moving to new line 28 | } 29 | getch(); 30 | }_ 31 | 32 | -------------------------------------------------------------------------------- /Graph Programs/graph_connected_components.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | vector adj[12]; 6 | bool visited[12]; 7 | 8 | void dfs(int s) { 9 | visited[s] = true; 10 | for(int i = 0;i < adj[s].size();++i) { 11 | if(visited[adj[s][i]] == false) 12 | dfs(adj[s][i]); 13 | } 14 | } 15 | 16 | void initialize() { 17 | for(int i = 0;i < 10;++i) 18 | visited[i] = false; 19 | } 20 | 21 | int main() { 22 | int nodes, edges, x, y, connectedComponents = 0; 23 | cin >> nodes; 24 | cin >> edges; 25 | for(int i = 0;i < edges;++i) { 26 | cin >> x >> y; 27 | adj[x].push_back(y); 28 | adj[y].push_back(x); 29 | } 30 | initialize(); 31 | for(int i = 1;i <= nodes;++i) { 32 | if(visited[i] == false) { 33 | dfs(i); 34 | connectedComponents++; 35 | } 36 | } 37 | cout << "Number of connected components: " << connectedComponents << endl; 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /Searching problems/ternarySearch.cpp: -------------------------------------------------------------------------------- 1 | //Ternary Search Uses Divide And Conquer Technique 2 | #include 3 | 4 | using namespace std; 5 | int ternarySearch(int arr[],int l,int r, int x){ 6 | if(r>=l){ 7 | int mid1 = l + (r-l)/3; 8 | int mid2 = r - (r-l)/3; 9 | if(arr[mid1] == x) 10 | return mid1; 11 | /* 12 | In this search, after each iteration it neglects (1/3)rd part of the array and repeats the same operations on the remaining 2/3rd part of array 13 | */ 14 | if(arr[mid2] == x) 15 | return mid2; 16 | if(xarr[mid2]) 19 | return ternarySearch(arr,mid2+1,r,x); 20 | else 21 | return ternarySearch(arr,mid1+1,mid2-1,x); 22 | } 23 | return -1; // if x is not found in array arr 24 | } 25 | int main(){ 26 | int arr[] = {1, 2, 3, 5}; 27 | int size = sizeof(arr)/ sizeof(arr[0]); 28 | int find = 3; 29 | cout<<"Position of "< 2 | using namespace std; 3 | 4 | void CounterSort(int a[], int n, int r, int lower) 5 | { 6 | int i, j = 0, counter[r] = {0}; 7 | // Counting the number occurrence of each element. 8 | for(i=0; i 0) 22 | goto flag; 23 | i++; 24 | } 25 | } 26 | 27 | int main() 28 | { 29 | int n, i, range, ulimit, llimit; 30 | cout<<"\nEnter the number of elements: "; 31 | cin>>n; 32 | 33 | cout<<"\nEnter the lower and upper limit of the data: "; 34 | cin>>llimit>>ulimit; 35 | 36 | // Range of the input data. 37 | range = ulimit-llimit+1; 38 | 39 | int arr[n]; 40 | for(i = 0; i < n; i++) 41 | { 42 | cout<<"Enter element "<>arr[i]; 44 | } 45 | 46 | CounterSort(arr, n, range, llimit); 47 | 48 | // Printing the sorted data. 49 | cout<<"\nSorted Data "; 50 | for (i = 0; i < n; i++) 51 | cout<<"->"< 3 | int a[20][20], q[20], visited[20], n, i, j, f = 0, r = -1; 4 | 5 | void bfs(int v) { 6 | for(i = 1; i <= n; i++) 7 | if(a[v][i] && !visited[i]) 8 | q[++r] = i; 9 | if(f <= r) { 10 | visited[q[f]] = 1; 11 | bfs(q[f++]); 12 | } 13 | } 14 | 15 | void main() { 16 | int v; 17 | printf("\n Enter the number of vertices:"); 18 | scanf("%d", &n); 19 | 20 | for(i=1; i <= n; i++) { 21 | q[i] = 0; 22 | visited[i] = 0; 23 | } 24 | 25 | printf("\n Enter graph data in matrix form:\n"); 26 | for(i=1; i<=n; i++) { 27 | for(j=1;j<=n;j++) { 28 | scanf("%d", &a[i][j]); 29 | } 30 | } 31 | 32 | printf("\n Enter the starting vertex:"); 33 | scanf("%d", &v); 34 | bfs(v); 35 | printf("\n The node which are reachable are:\n"); 36 | 37 | for(i=1; i <= n; i++) { 38 | if(visited[i]) 39 | printf("%d\t", i); 40 | else { 41 | printf("\n Bfs is not possible. Not all nodes are reachable"); 42 | break; 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Sorting/quicksort.c: -------------------------------------------------------------------------------- 1 | /* C implementation QuickSort */ 2 | #include 3 | void swap(int* a, int* b) 4 | { 5 | int t = *a; 6 | *a = *b; 7 | *b = t; 8 | } 9 | int partition (int arr[], int low, int high) 10 | { 11 | int pivot = arr[high]; // pivot 12 | int i = (low - 1); // Index of smaller element 13 | 14 | for (int j = low; j <= high- 1; j++) 15 | { 16 | 17 | if (arr[j] <= pivot) 18 | { 19 | i++; 20 | swap(&arr[i], &arr[j]); 21 | } 22 | } 23 | swap(&arr[i + 1], &arr[high]); 24 | return (i + 1); 25 | } 26 | 27 | void quickSort(int arr[], int low, int high) 28 | { 29 | if (low < high) 30 | { 31 | int pi = partition(arr, low, high); 32 | 33 | quickSort(arr, low, pi - 1); 34 | quickSort(arr, pi + 1, high); 35 | } 36 | } 37 | 38 | void printArray(int arr[], int size) 39 | { 40 | int i; 41 | for (i=0; i < size; i++) 42 | printf("%d ", arr[i]); 43 | printf("\n"); 44 | } 45 | int main() 46 | { 47 | int arr[] = {10, 7, 8, 9, 1, 5}; 48 | int n = sizeof(arr)/sizeof(arr[0]); 49 | quickSort(arr, 0, n-1); 50 | printf("Sorted array: \n"); 51 | printArray(arr, n); 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /hackt.cbp: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 44 | 45 | -------------------------------------------------------------------------------- /Sorting/shellsort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void shellsort(int arr[], int num) 4 | 5 | { 6 | int i, j, k, tmp; 7 | for (i = num / 2; i > 0; i = i / 2) 8 | { 9 | 10 | // Do a gapped insertion sort for this gap size. 11 | // The first gap elements a[0..i-1] are already in 12 | //gapped order keep adding one more element until the 13 | //entire array is gap sorted. 14 | for (j = i; j < num; j++) 15 | { 16 | for(k = j - i; k >= 0; k = k - i) 17 | { 18 | if (arr[k+i] >= arr[k]) 19 | break; 20 | else 21 | { 22 | tmp = arr[k]; 23 | arr[k] = arr[k+i]; 24 | arr[k+i] = tmp; 25 | } 26 | } 27 | } 28 | } 29 | } 30 | 31 | int main() 32 | 33 | { 34 | int arr[30]; 35 | int k, num; 36 | printf("Enter total no. of elements : "); 37 | scanf("%d", &num); 38 | printf("\nEnter %d numbers: ", num); 39 | for (k = 0 ; k < num; k++) 40 | { 41 | scanf("%d", &arr[k]); 42 | } 43 | shellsort(arr, num); 44 | printf("\n Sorted array is: "); 45 | for (k = 0; k < num; k++) 46 | printf("%d ", arr[k]); 47 | return 0; 48 | 49 | } -------------------------------------------------------------------------------- /Patterns/ALternate 1 0 Lower LEFT Triangle.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main(){ 4 | int i,j,n; 5 | cin>>n; //input n for number of rows 6 | for(i=1;i<=n;i++){ //iterate over n number of rows 7 | for(j=1;j<=i;j++){ //no of columns will be just equal to the row number 8 | if(i%2==0){ //choosing even row 9 | if(j%2!=0){ //at odd column positions print 0 10 | cout<<"0"; 11 | } 12 | else{ //at even column positions print 1 13 | cout<<"1"; 14 | } 15 | } 16 | else{ //choosing odd row 17 | if(j%2==0){ //at even column positions print 0 18 | cout<<"0"; 19 | } 20 | else{ //at odd column positions print 1 21 | cout<<"1"; 22 | } 23 | } 24 | } 25 | cout< 4 | #include 5 | #include 6 | 7 | /** 8 | * Function to sort a float array using bucket sort 9 | * @param vec The vector to sort 10 | */ 11 | void bucketSort(std::vector& vec) 12 | { 13 | const std::size_t size = vec.size(); 14 | std::vector> buckets(size); 15 | 16 | // Move array elements to different buckets 17 | for (const auto val : vec) 18 | { 19 | std::size_t bucket_index = static_cast(size * val); 20 | buckets.at(bucket_index).push_back(val); 21 | } 22 | 23 | // Sort the individual buckets 24 | for (auto bucket : buckets) 25 | { 26 | std::sort(bucket.begin(), bucket.end()); 27 | } 28 | 29 | // Set the sorted values in the original vector 30 | std::size_t index = 0; 31 | for (const auto& bucket : buckets) 32 | { 33 | for (const auto value : bucket) 34 | { 35 | vec.at(index++) = value; 36 | } 37 | } 38 | } 39 | 40 | /** 41 | * Test program for the bucketSort function 42 | */ 43 | int main() 44 | { 45 | std::vector data = { 0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434 }; 46 | 47 | bucketSort(data); 48 | 49 | std::cout << "Sorted vector is:\n"; 50 | for (auto value : data) 51 | { 52 | std::cout << value << ' '; 53 | } 54 | 55 | return 0; 56 | } 57 | -------------------------------------------------------------------------------- /Plan.md: -------------------------------------------------------------------------------- 1 | #### Plan 2 | -[ ] [Linked list] 3 | - [ ] [Singly Linked list] 4 | - [ ] [Doubly Linked list] 5 | - [ ] Circular Linked list 6 | - [ ] Memory efficient doubly Linked list 7 | - [ ] Skip Linked list 8 | - [ ] Unrolled Linked list 9 | 10 | - [ ] [Stacks] 11 | 12 | - [ ] [Queues] 13 | 14 | - [ ] [Sorting] 15 | - [ ] Bubble sort 16 | - [ ] Merge sort 17 | - [ ] Insertion sort 18 | - [ ] Selection sort 19 | - [ ] Quick sort 20 | - [ ] Topological sort 21 | - [ ] Heap sort 22 | - [ ] Bucket sort 23 | - [ ] Shell sort 24 | 25 | - [ ] [Heap] 26 | 27 | - [ ] [Tree] 28 | - [ ] [general tree] 29 | - [ ] [BST] 30 | 31 | - [ ] Searching 32 | - [ ] Binary search 33 | - [ ] Jump search 34 | - [ ] Fibonacci search 35 | - [ ] Depth First Search 36 | - [ ] Breadth First Search 37 | - [ ] Kosaraju's Algorithm (find all SCCs) 38 | 39 | - [ ] Backtrack 40 | - [ ] anagram 41 | - [ ] array sum combinations 42 | - [ ] combination sum 43 | - [ ] expression add operators 44 | - [ ] factor combinations 45 | - [ ] generate abbreviations 46 | - [ ] generate parenthesis 47 | - [ ] letter combination 48 | - [ ] palindrome partitioning 49 | - [ ] pattern match 50 | - [ ] permute 51 | - [ ] permute unique 52 | - [ ] subsets 53 | - [ ] subsets unique 54 | 55 | - [ ] Array 56 | - [ ] next_permutation 57 | -------------------------------------------------------------------------------- /Searching problems/BINARY_SEARCH.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | const int N = 1000; 5 | int arr[N]; 6 | int n,m,k; 7 | int main() 8 | { 9 | //First we will load our array. It will be consisted of n integers. 10 | scanf("%d",&n); 11 | for(int i=0;i>1; 27 | //If our number at position midd is higher than the m that means that our 28 | //number is in the left side of the array, so we are putting the high to be midd -1 29 | //We checked that midd isn't our wanted element, so the element with tha highest id that we didn't 30 | //check is midd -1 so we are putting high to that value. 31 | //Because we are dividing our array by two each time we are getting complexity of O(log(N)) 32 | if(arr[midd]>m)high=midd-1; 33 | else low=midd; 34 | } 35 | //Complexity of the given solution is O(log(N)) 36 | if(arr[low]==m) 37 | printf("Found it on the %d-th position.\n",low+1); 38 | else 39 | printf("We didn't find it.\n"); 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /Sorting/count_sort.c: -------------------------------------------------------------------------------- 1 | // C Program for counting sort 2 | #include 3 | #include 4 | #define RANGE 255 5 | 6 | // The main function that sort the given string arr[] in 7 | // alphabatical order 8 | void countSort(char arr[]) 9 | { 10 | // The output character array that will have sorted arr 11 | char output[strlen(arr)]; 12 | 13 | // Create a count array to store count of inidividul 14 | // characters and initialize count array as 0 15 | int count[RANGE + 1], i; 16 | memset(count, 0, sizeof(count)); 17 | 18 | // Store count of each character 19 | for(i = 0; arr[i]; ++i) 20 | ++count[arr[i]]; 21 | 22 | // Change count[i] so that count[i] now contains actual 23 | // position of this character in output array 24 | for (i = 1; i <= RANGE; ++i) 25 | count[i] += count[i-1]; 26 | 27 | // Build the output character array 28 | for (i = 0; arr[i]; ++i) 29 | { 30 | output[count[arr[i]]-1] = arr[i]; 31 | --count[arr[i]]; 32 | } 33 | 34 | // Copy the output array to arr, so that arr now 35 | // contains sorted characters 36 | for (i = 0; arr[i]; ++i) 37 | arr[i] = output[i]; 38 | } 39 | 40 | // Driver program to test above function 41 | int main() 42 | { 43 | char arr[] = "array";//"applepp"; 44 | 45 | countSort(arr); 46 | 47 | printf("Sorted character array is %sn", arr); 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /Searching problems/jumpsearch.cpp: -------------------------------------------------------------------------------- 1 | /* ===== ===== ===== 2 | Theory of Programming 3 | Jump Search Algorithm 4 | 5 | ===== ===== ===== */ 6 | 7 | #include 8 | #include 9 | #include 10 | 11 | using namespace std; 12 | 13 | int jumpSearch(int arr[], int n, int value) 14 | { 15 | int i, right, left, jump = (int) sqrt(n); 16 | 17 | for (i = 0; i + jump < n && arr[i] < value; i += jump) { 18 | // Keep jumping until value is between any two 19 | // elements of the array or when i goes out of bound 20 | } 21 | 22 | if (value <= arr[i]) { 23 | // right is i if search value is less than 24 | // any jumped element in the array. 25 | right = i; 26 | } else { 27 | // If not, right is last element 28 | right = n; 29 | } 30 | 31 | left = max(right - jump, 0); // ensuring left doesn't go negative 32 | 33 | // Linear search backwards 34 | while (right >= left) { 35 | if (arr[right--] == value) { 36 | return right + 1; 37 | } 38 | } 39 | 40 | return -1; 41 | } 42 | 43 | int main() 44 | { 45 | int arr[] = {1, 3, 5, 7, 9, 11, 13, 15}; 46 | int n = sizeof(arr) / sizeof(int); 47 | 48 | cout << jumpSearch(arr, n, 0) << endl; // -1 49 | cout << jumpSearch(arr, n, 3) << endl; // 1 50 | cout << jumpSearch(arr, n, 11) << endl; // 5 51 | cout << jumpSearch(arr, n, 16) << endl; // -1 52 | 53 | return 0; 54 | } 55 | -------------------------------------------------------------------------------- /Patterns/Pascals Triangle.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | * C++ Program to Print Pascal's Triangle 4 | 5 | */ 6 | 7 | 8 | 9 | #include //including header file 10 | 11 | using namespace std; // using this to avoid writing "std" repeatedly 12 | 13 | 14 | 15 | int main() 16 | 17 | { 18 | 19 | int rows; 20 | 21 | cout << "Enter the number of rows : "; 22 | 23 | cin >> rows; 24 | 25 | cout << endl; 26 | 27 | 28 | 29 | for (int i = 0; i < rows; i++) 30 | 31 | { 32 | 33 | int val = 1; 34 | 35 | for (int j = 1; j < (rows - i); j++) // loop to print spaces 36 | 37 | { 38 | 39 | cout << " "; 40 | 41 | } 42 | 43 | for (int k = 0; k <= i; k++) // loop to intialise numbers from pascal's series in "var". 44 | 45 | { 46 | 47 | cout << " " << val; 48 | 49 | val = val * (i - k) / (k + 1); 50 | 51 | } 52 | 53 | cout << endl << endl; 54 | 55 | } 56 | 57 | cout << endl; 58 | 59 | return 0; 60 | 61 | } 62 | /* INPUT - 5 */ 63 | /* OUTPUT 64 | 65 | 1 66 | 67 | 1 1 68 | 69 | 1 2 1 70 | 71 | 1 3 3 1 72 | 73 | 1 4 6 4 1 74 | 75 | 76 | 77 | */ 78 | -------------------------------------------------------------------------------- /LinkedList/SLL.cpp: -------------------------------------------------------------------------------- 1 | // A simple C program for traversal of a linked list 2 | #include 3 | #include 4 | #include 5 | struct Node 6 | { 7 | int data; 8 | struct Node *next; 9 | }; 10 | 11 | // This function prints contents of linked list starting from 12 | // the given node 13 | void printList(struct Node *n) 14 | { 15 | while (n != NULL) 16 | { 17 | printf("%d ", n->data); 18 | n = n->next; 19 | } 20 | std::cout << "\n"; 21 | 22 | } 23 | 24 | size_t length(struct Node* n) 25 | { 26 | size_t length = 0; 27 | struct Node * iterator = NULL; 28 | iterator = n; 29 | 30 | while(iterator) 31 | { 32 | ++length; 33 | iterator = iterator->next; 34 | } 35 | return length; 36 | } 37 | int main() 38 | { 39 | struct Node* head = NULL; 40 | struct Node* second = NULL; 41 | struct Node* third = NULL; 42 | 43 | // allocate 3 nodes in the heap 44 | head = (struct Node*)malloc(sizeof(struct Node)); 45 | second = (struct Node*)malloc(sizeof(struct Node)); 46 | third = (struct Node*)malloc(sizeof(struct Node)); 47 | 48 | head->data = 1; //assign data in first node 49 | head->next = second; // Link first node with second 50 | 51 | second->data = 2; //assign data to second node 52 | second->next = third; 53 | 54 | third->data = 3; //assign data to third node 55 | third->next = NULL; 56 | 57 | printList(head); 58 | std::cout << length(head) << "\n"; 59 | 60 | return 0; 61 | } 62 | -------------------------------------------------------------------------------- /unionarray.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int main() 4 | { 5 | int n1,n2; 6 | int a[20],b[20],c[20]; 7 | int i,j; 8 | int d=0; 9 | int e=0; 10 | int g=0; 11 | int f=0; 12 | printf("enter a size of array 1: "); 13 | scanf("%d",&n1); 14 | for(i=0;i 3 | 4 | 5 | 6 | 7 | # Data-Structures 8 | 9 | ### Implementation tree 10 | ``` 11 | Data Structures 12 | ├── Graph Programs 13 | │ ├── adjacency_list.hpp # graph implementation with adjacency list 14 | │ └── adjacency_matrix.hpp # graph implementation with adjacency matrix 15 | │ └── topological_sort.hpp # topological sort (adjacency list) 16 | ├── Heap Programs 17 | │ └── HEAP.cpp # heap implementation 18 | ├── Linked List Programs 19 | │ ├── DOUBLY_LINKED_LIST.cpp # doubly linked list 20 | │ └── SINGLY_LINKED_LIST.cpp # singly linked list 21 | ├── Queue Programs 22 | │ └── QUEUE.cpp # queue implementation 23 | ├── Sorting Programs 24 | │ ├── BUBBLE_SORT.cpp # bubble sort 25 | │ ├── INSERTION_SORT.cpp # insertion sort 26 | │ ├── MERGE_SORT.cpp # merge sort 27 | │ ├── QUICK_SORT.cpp # quick sort 28 | │ └── SELECTION_SORT.cpp # selection sort 29 | ├── Searching Programs 30 | │ ├── LINEAR_SEARCH.cpp # Linear search 31 | │ ├── BINARY_SEARCH.cpp # Binary search 32 | ├── Stack Programs 33 | │ └── Stack.cpp # stack implementation 34 | └── Tree Programs 35 | ├── TREE.cpp # general tree implementation 36 | ├── SEGMENT_TREE.cpp # segment tree implementation 37 | └── BINARY_SEARCH_TREE.cpp # binary search tree 38 | ``` 39 | -------------------------------------------------------------------------------- /Stack/Stack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #define Stack_Size 10 4 | using namespace std; 5 | 6 | class Stack{ 7 | 8 | private: 9 | int top; 10 | int item; 11 | int s[Stack_Size]; 12 | public: 13 | Stack(){top=-1;} 14 | void push(int item); 15 | int pop(); 16 | void display(); 17 | }; 18 | 19 | void Stack::push(int item) 20 | { 21 | if(top==Stack_Size-1) 22 | { 23 | cout<<"Stack Overflow!"<>choice; 61 | 62 | switch(choice) 63 | { 64 | case 1: 65 | cout<<"Enter an item to push:"<>item; 67 | s.push(item); 68 | break; 69 | case 2: 70 | item=s.pop(); 71 | if(item==-1) 72 | cout<<"Stack Underflow!"< 2 | using namespace std; 3 | 4 | // To heapify a subtree rooted with node i which is 5 | // an index in arr[]. n is size of heap 6 | void heapify(int arr[], int n, int i) 7 | { 8 | int largest = i; // Initialize largest as root 9 | int l = 2*i + 1; // left = 2*i + 1 10 | int r = 2*i + 2; // right = 2*i + 2 11 | 12 | // If left child is larger than root 13 | if (l < n && arr[l] > arr[largest]) 14 | largest = l; 15 | 16 | // If right child is larger than largest so far 17 | if (r < n && arr[r] > arr[largest]) 18 | largest = r; 19 | 20 | // If largest is not root 21 | if (largest != i) 22 | { 23 | swap(arr[i], arr[largest]); 24 | 25 | // Recursively heapify the affected sub-tree 26 | heapify(arr, n, largest); 27 | } 28 | } 29 | 30 | // main function to do heap sort 31 | void heapSort(int arr[], int n) 32 | { 33 | // Build heap (rearrange array) 34 | for (int i = n / 2 - 1; i >= 0; i--) 35 | heapify(arr, n, i); 36 | 37 | // One by one extract an element from heap 38 | for (int i=n-1; i>=0; i--) 39 | { 40 | // Move current root to end 41 | swap(arr[0], arr[i]); 42 | 43 | // call max heapify on the reduced heap 44 | heapify(arr, i, 0); 45 | } 46 | } 47 | 48 | /* A utility function to print array of size n */ 49 | void printArray(int arr[], int n) 50 | { 51 | for (int i=0; i 3 | #include 4 | 5 | struct Node 6 | { 7 | int data; 8 | struct Node *x_ptr; 9 | }; 10 | 11 | //XOR Operation 12 | struct Node * xor(struct Node *m, struct Node *n){ 13 | return (struct Node *)((unsigned)m ^ (unsigned)n); 14 | } 15 | 16 | //Inserting into XOR List to beg 17 | void insert(struct Node **head, int x){ 18 | //Create a new node to be inserted 19 | struct Node *temp = (struct Node *)malloc(sizeof(struct Node)); 20 | temp->data = x; 21 | 22 | //As it is inserted at beginning its x_ptr will (NULL XOR head) 23 | temp->x_ptr = xor(NULL,(*head)); 24 | 25 | //If list is not empty then x_ptr of head will be (new node XOR next node) 26 | if((*head) != NULL){ 27 | //Get address of Next Node 28 | struct Node *nextNode = xor(NULL,(*head)->x_ptr); 29 | 30 | //Store XOR of new node and next node 31 | (*head)->x_ptr = xor(temp,nextNode); 32 | } 33 | 34 | //Make the new node as head 35 | *head = temp; 36 | } 37 | 38 | //Printing XOR List 39 | void printList(struct Node *head) 40 | { 41 | struct Node *previous, *current, *next; 42 | previous = NULL; 43 | current = head; 44 | 45 | while(current) 46 | { 47 | //print data of current node 48 | printf(" %d ",current->data); 49 | 50 | //get address of next node as (previous node XOR (previous XOR next node)) 51 | //where current->x_ptr = (previous XOR next node) 52 | next = xor(previous,current->x_ptr); 53 | 54 | //update previous and current for next iteration 55 | previous = current; 56 | current = next; 57 | } 58 | 59 | printf("\n"); 60 | } 61 | 62 | int main(){ 63 | /*10->20->30->40->50 */ 64 | struct Node *head=NULL; 65 | insert(&head,50); 66 | insert(&head,40); 67 | insert(&head,30); 68 | insert(&head,20); 69 | insert(&head,10); 70 | printList(head); 71 | return 0; 72 | } 73 | -------------------------------------------------------------------------------- /lucky 7 game.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | printf("\t\t\t\t********welcome to LUCKY 7 GAME*********\t\t\t\t\t\n\n"); 7 | int n,choice,amt; 8 | char ch; 9 | srand(time(NULL)); 10 | n=rand()%15; 11 | printf("Please enter the amount you want to put at stake : "); 12 | scanf("%d",&amt); 13 | 14 | 15 | do 16 | { 17 | printf("please select one option from below : \n"); 18 | printf("1. Below 7\n"); 19 | printf("2. On 7\n"); 20 | printf("3. Above 7\n"); 21 | printf("Please enter your choice : "); 22 | scanf("%d",&choice); 23 | 24 | 25 | switch(choice) 26 | { 27 | case 1: 28 | if(n<7) 29 | { 30 | printf("\nCongrats!! you won %d rupees\n",2*amt); 31 | } 32 | else 33 | { 34 | printf("\nSorry you lost %d rupees\n",amt); 35 | } 36 | break; 37 | case 2: 38 | if(n==7) 39 | { 40 | printf("\nCongrats!! you won %d rupees\n",3*amt); 41 | } 42 | else 43 | { 44 | printf("\nSorry you lost %d rupees\n",amt); 45 | } 46 | break; 47 | case 3: 48 | if(n>7) 49 | { 50 | printf("\nCongrats!! you won %d rupees\n",2*amt); 51 | } 52 | else 53 | { 54 | printf("\nSorry you lost %d rupees\n",amt); 55 | } 56 | break; 57 | default: 58 | printf("Please enter a no. between 1 and 3"); 59 | 60 | } 61 | printf ("\nDo you want to play the game again Y/N: "); 62 | scanf (" %c", &ch); 63 | } 64 | while (ch == 'y' || ch == 'Y'); 65 | 66 | return 0; 67 | } 68 | -------------------------------------------------------------------------------- /Sorting/selectionsort2.c: -------------------------------------------------------------------------------- 1 | /*Selection Sort - C program to sort an Array 2 | in Ascending and Descending Order.*/ 3 | 4 | #include 5 | 6 | #define MAX 100 7 | 8 | int main() 9 | { 10 | int arr[MAX],limit; 11 | int i,j,temp,position; 12 | 13 | printf("Enter total number of elements: "); 14 | scanf("%d",&limit); 15 | 16 | /*Read array*/ 17 | printf("Enter array elements: \n"); 18 | for(i=0; iarr[j]) 31 | { 32 | position=j; 33 | } 34 | if(position!=i) 35 | { 36 | temp=arr[i]; 37 | arr[i]=arr[position]; 38 | arr[position]=temp; 39 | } 40 | } 41 | } 42 | 43 | printf("Array elements in Ascending Order:\n"); 44 | for(i=0; i 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | template 7 | struct node 8 | { 9 | T n; 10 | node *next; 11 | }; 12 | 13 | template 14 | class Stack 15 | { 16 | private: 17 | node *top; 18 | public: 19 | Stack(); 20 | void push(T); 21 | T pop(); 22 | void display(); 23 | }; 24 | 25 | template Stack::Stack() 26 | { 27 | top=nullptr; 28 | } 29 | 30 | template void Stack::push(T n) 31 | { 32 | node *ptr=new node; 33 | ptr->n=n; 34 | ptr->next=top; 35 | top=ptr; 36 | } 37 | 38 | template T Stack::pop() 39 | { 40 | if(top==nullptr) 41 | return INT_MIN; 42 | node *ptr=top; 43 | T n=ptr->n; 44 | top=top->next; 45 | delete ptr; 46 | return n; 47 | } 48 | 49 | template void Stack::display() 50 | { 51 | node *ptr=top; 52 | while(ptr!=nullptr) 53 | { 54 | cout << ptr->n << "-> "; 55 | ptr=ptr->next; 56 | } 57 | cout << "NULL" << endl; 58 | } 59 | 60 | int main() 61 | { 62 | Stack S; 63 | int n,choice; 64 | while(true) 65 | { 66 | system("cls"); 67 | cout << "1.Push" << endl 68 | << "2.Pop" << endl 69 | << "3.Display" << endl 70 | << "4.Exit" << endl; 71 | cin >> choice; 72 | switch(choice) 73 | { 74 | case 1: 75 | cout << "Enter the element to be entered. "; 76 | cin >> n; 77 | S.push(n); 78 | break; 79 | case 2: 80 | S.pop(); 81 | break; 82 | case 3: 83 | S.display(); 84 | system("pause"); 85 | break; 86 | default: 87 | exit(0); 88 | } 89 | } 90 | return 0; 91 | } 92 | -------------------------------------------------------------------------------- /Queue/queue.c: -------------------------------------------------------------------------------- 1 | // LinkedList implementation of queue 2 | #include 3 | #include 4 | // A LinkedList node to store queue entry 5 | typedef struct Node{ 6 | int key; 7 | struct Node *next; 8 | } Node; 9 | 10 | typedef struct Queue{ 11 | Node *front; 12 | Node *rear; 13 | } Queue; 14 | 15 | // Function to create an empty queue 16 | struct Queue *createQueue() 17 | { 18 | struct Queue *q = (struct Queue*)malloc(sizeof(struct Queue)); 19 | q->front = q->rear = NULL; 20 | return q; 21 | } 22 | 23 | // Function to create new node with key k 24 | Node *newNode(int k){ 25 | Node *n = (Node*) malloc(sizeof(Node)); 26 | n->key = k; 27 | return n; 28 | } 29 | 30 | // Function to add key k to the q 31 | void enqueue(Queue *q,int k){ 32 | Node *node = newNode(k); 33 | // if q is empty then node is front and read both 34 | if(q->rear == NULL){ 35 | q->front = q->rear = node; 36 | return ; 37 | } 38 | // add node to end of the q 39 | q->rear->next = node; 40 | // update q rear pointer 41 | q->rear = node; 42 | } 43 | 44 | Node *dequeue(Queue *q){ 45 | // If queue is emoty return NULL 46 | if(q->front == NULL) return NULL; 47 | // Store the node at front & update the front pointer to next node 48 | Node *temp = q->front; 49 | q->front = q->front->next; 50 | // if front is NULL the q is empty so update rear pointer to NULL 51 | if(q->front == NULL){ 52 | q->rear = NULL; 53 | } 54 | return temp; 55 | } 56 | 57 | // Main function 58 | int main(){ 59 | 60 | Queue *q = createQueue(); 61 | enqueue(q,10); // rear -> 10 <- front 62 | enqueue(q,20); // rear -> 20 10 <- front 63 | enqueue(q,30); // rear -> 30 20 10 <- front 64 | dequeue(q); // rear -> 30 20 10 <- front 65 | printf("%d\n",q->front->key); // prints 20 66 | dequeue(q); // rear -> 30 <- front 67 | printf("%d\n",q->front->key); // prints 30 68 | 69 | return 0; 70 | } -------------------------------------------------------------------------------- /Stack/reverse-a-string: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define MAX 100 /*maximum no. of characters*/ 5 | 6 | /*stack variables*/ 7 | int top=-1; 8 | int item; 9 | /***************/ 10 | 11 | /*string declaration*/ 12 | char stack_string[MAX]; 13 | 14 | /*function to push character (item)*/ 15 | void pushChar(char item); 16 | 17 | /*function to pop character (item)*/ 18 | char popChar(void); 19 | 20 | /*function to check stack is empty or not*/ 21 | int isEmpty(void); 22 | 23 | /*function to check stack is full or not*/ 24 | int isFull(void); 25 | 26 | int main() 27 | { 28 | char str[MAX]; 29 | 30 | int i; 31 | 32 | printf("Input a string: "); 33 | scanf("%[^\n]s",str); /*read string with spaces*/ 34 | /*gets(str);-can be used to read string with spaces*/ 35 | 36 | for(i=0;i 5 | #include 6 | using namespace std; 7 | #define MAX 20 8 | /* 9 | * Adjacency Matrix Class 10 | */ 11 | class AdjacencyMatrix 12 | { 13 | private: 14 | int n; 15 | int **adj; 16 | bool *visited; 17 | public: 18 | AdjacencyMatrix(int n) 19 | { 20 | this->n = n; 21 | visited = new bool [n]; 22 | adj = new int* [n]; 23 | for (int i = 0; i < n; i++) 24 | { 25 | adj[i] = new int [n]; 26 | for(int j = 0; j < n; j++) 27 | { 28 | adj[i][j] = 0; 29 | } 30 | } 31 | } 32 | /* 33 | * Adding Edge to Graph 34 | */ 35 | void add_edge(int origin, int destin) 36 | { 37 | if( origin > n || destin > n || origin < 0 || destin < 0) 38 | { 39 | cout<<"Invalid edge!\n"; 40 | } 41 | else 42 | { 43 | adj[origin - 1][destin - 1] = 1; 44 | } 45 | } 46 | /* 47 | * Print the graph 48 | */ 49 | void display() 50 | { 51 | int i,j; 52 | for(i = 0;i < n;i++) 53 | { 54 | for(j = 0; j < n; j++) 55 | cout<>nodes; 68 | AdjacencyMatrix am(nodes); 69 | max_edges = nodes * (nodes - 1); 70 | for (int i = 0; i < max_edges; i++) 71 | { 72 | cout<<"Enter edge (-1 -1 to exit): "; 73 | cin>>origin>>destin; 74 | if((origin == -1) && (destin == -1)) 75 | break; 76 | am.add_edge(origin, destin); 77 | } 78 | am.display(); 79 | return 0; 80 | } -------------------------------------------------------------------------------- /Patterns/Bell Triangle.c: -------------------------------------------------------------------------------- 1 | /*A Bell Triangle is a very special kind of triangle implemented using coding. 2 | A Bell Triangle is as this one- 3 | 4 | 1 5 | 1 2 6 | 2 3 5 7 | 5 7 10 15 8 | 15 20 27 37 52 9 | 10 | The Bell Traingle is obtained by beginning the first row with 1 and beginning subsequent rows with last number of the previous row. 11 | Rows are filled out by adding the number in the preceding column to the number above it. Eg. in third row 2+(number above it i.e. 1)=3...The pattern follows on similarly 12 | The C code for Bell Triangle is as follows: 13 | -----------------------------------------------------------------------------------------------------------------------------> 14 | 15 | #include 16 | int main() 17 | { 18 | int i,j,ch,k,n; /*declaring the variables i,j.k as loop variables,n as the height of the Triangle,ch as array variabole*/ 19 | int arr[100]; /*declaring an array of size 100*/ 20 | int arr1[100]; /*declaring another array of size 100*/ 21 | arr[0]=1; /*storing 1 as the first element of array arr*/ 22 | ch=1; 23 | printf("Enter the height of Bell Triangle"); 24 | scanf("%d",&n); /*inputting the height or the no. of rows to be printed of the Bel Traingle*/ 25 | for(i=0;i 2 | #define MAX 10 3 | 4 | int QUEUE[MAX],front=-1,rear=-1; 5 | 6 | /** function : insert_in_Q(), 7 | to push an item into queue. 8 | **/ 9 | void insert_in_Q(int queue[],int ele) 10 | { 11 | if(rear==-1) 12 | { 13 | front=rear=0; 14 | queue[rear]=ele; 15 | } 16 | else if(rear==MAX-1) 17 | { 18 | printf("\nQUEUE is full.\n"); 19 | return; 20 | } 21 | else 22 | { 23 | rear++; 24 | queue[rear]=ele; 25 | } 26 | printf("\nItem inserted.."); 27 | } 28 | 29 | /** function : display_Q(), 30 | to display queue elements 31 | **/ 32 | 33 | void display_Q(int queue[]) 34 | { int i; 35 | if(rear==-1) { printf("\nQUEUE is Empty."); return; } 36 | for(i=front;i<=rear;i++) 37 | { printf("%d,",queue[i]); } 38 | 39 | } 40 | 41 | /** function : remove_from_Q(), 42 | to remove (pop) an item from queue. 43 | **/ 44 | void remove_from_Q(int queue[]) 45 | { 46 | int ele; 47 | if(front==-1) 48 | { 49 | printf("QUEUE is Empty."); 50 | return; 51 | } 52 | else if(front==rear) 53 | { 54 | ele=queue[front]; 55 | front=rear=-1; 56 | } 57 | else 58 | { 59 | ele=queue[front]; 60 | front++; 61 | } 62 | printf("\nItem removed : %d.",ele); 63 | } 64 | 65 | 66 | 67 | 68 | int main() 69 | { 70 | int ele,choice; 71 | while(1) 72 | { 73 | //clrscr(); 74 | printf("\nQUEUE Elements are :"); 75 | display_Q(QUEUE); 76 | printf("\n\nEnter choice (1:Insert,2:Display,3:Remove,0:Exit):"); 77 | scanf("%d",&choice); 78 | switch(choice) 79 | { 80 | case 0: 81 | exit(1); 82 | break; 83 | case 1: 84 | printf("Enter an element to insert:"); 85 | scanf("%d",&ele); 86 | insert_in_Q(QUEUE,ele); 87 | break; 88 | case 2: 89 | display_Q(QUEUE); 90 | break; 91 | case 3: 92 | remove_from_Q(QUEUE); 93 | break; 94 | default: 95 | printf("\nInvalid choice\n"); 96 | break; 97 | } 98 | 99 | } //end of while(1) 100 | return 0; 101 | } 102 | -------------------------------------------------------------------------------- /Backtracking/NQueens.c: -------------------------------------------------------------------------------- 1 | // C program to solve N Queen Problem using backtracking 2 | // Size of the board 3 | #define N 5 4 | #include 5 | 6 | 7 | typedef int bool; 8 | #define true 1 9 | #define false 0 10 | 11 | // function to print solution 12 | void printSolution(int board[N][N]) 13 | { 14 | for (int i = 0; i < N; i++) 15 | { 16 | for (int j = 0; j < N; j++) 17 | printf("%d ", board[i][j]); 18 | printf("\n"); 19 | } 20 | } 21 | 22 | // function to check if a queen can be placed on board[row][col]. 23 | bool isSafe(int board[N][N], int row, int col) 24 | { 25 | int i, j; 26 | 27 | // Check this row on left side 28 | for (i = 0; i < col; i++) 29 | if (board[row][i]) 30 | return false; 31 | 32 | // Check upper diagonal on left side 33 | for (i=row, j=col; i>=0 && j>=0; i--, j--) 34 | if (board[i][j]) 35 | return false; 36 | 37 | // Check lower diagonal on left side 38 | for (i=row, j=col; j>=0 && i= N) 50 | return true; 51 | 52 | for (int i = 0; i < N; i++) 53 | { 54 | // Check if queen can be placed on board[i][col] 55 | if ( isSafe(board, i, col) ) 56 | { 57 | // Place this queen in board[i][col] 58 | board[i][col] = 1; 59 | 60 | // recur 61 | if ( solveNQueens(board, col + 1) ) 62 | return true; 63 | 64 | board[i][col] = 0; // BACKTRACK 65 | } 66 | } 67 | return false; 68 | } 69 | 70 | int main() 71 | { 72 | 73 | int board[N][N] = { 74 | {0, 0, 0, 0, 0}, 75 | {0, 0, 0, 0, 0}, 76 | {0, 0, 0, 0, 0}, 77 | {0, 0, 0, 0, 0}, 78 | {0, 0, 0, 0, 0} 79 | }; 80 | 81 | if ( solveNQueens(board, 0) == false ) 82 | { 83 | printf("Solution doesn't exist\n"); 84 | } 85 | 86 | printSolution(board); 87 | return 0; 88 | } -------------------------------------------------------------------------------- /Graph Programs/graph_dfs.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to print DFS traversal from a given vertex in a given graph 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | // Graph class represents a directed graph using adjacency list representation 8 | class Graph 9 | { 10 | int V; // No. of vertices 11 | list *adj; // Pointer to an array containing adjacency lists 12 | void DFSUtil(int v, bool visited[]); // A function used by DFS 13 | public: 14 | Graph(int V); // Constructor 15 | void addEdge(int v, int w); // function to add an edge to graph 16 | void DFS(int v); // DFS traversal of the vertices reachable from v 17 | }; 18 | 19 | Graph::Graph(int V) 20 | { 21 | this->V = V; 22 | adj = new list[V]; 23 | } 24 | 25 | void Graph::addEdge(int v, int w) 26 | { 27 | adj[v].push_back(w); // Add w to v’s list. 28 | } 29 | 30 | void Graph::DFSUtil(int v, bool visited[]) 31 | { 32 | // Mark the current node as visited and print it 33 | visited[v] = true; 34 | cout << v << " "; 35 | 36 | // Recur for all the vertices adjacent to this vertex 37 | list::iterator i; 38 | for (i = adj[v].begin(); i != adj[v].end(); ++i) 39 | if (!visited[*i]) 40 | DFSUtil(*i, visited); 41 | } 42 | 43 | // DFS traversal of the vertices reachable from v. 44 | // It uses recursive DFSUtil() 45 | void Graph::DFS(int v) 46 | { 47 | // Mark all the vertices as not visited 48 | bool *visited = new bool[V]; 49 | for (int i = 0; i < V; i++) 50 | visited[i] = false; 51 | 52 | // Call the recursive helper function to print DFS traversal 53 | DFSUtil(v, visited); 54 | } 55 | 56 | // Driver program to test methods of graph class 57 | int main() 58 | { 59 | int choice,initial_vertex,dest_vertex,no_of_vertex,dfs_start; 60 | cout << "Enter the number of vertices"; 61 | cin >> no_of_vertex; 62 | Graph g(no_of_vertex); 63 | while(1){ 64 | cout << "1. Enter a new edge\n"; 65 | cout << "2. DFS\n"; 66 | cout << "3.Exit"; 67 | cout << "Enter your choice"; 68 | cin >> choice; 69 | switch(choice){ 70 | case 1: cout << "Enter the initial vertex"; 71 | cin >> initial_vertex; 72 | cout << "Enter the destination vertex"; 73 | cin >> dest_vertex; 74 | addEdge(initial_vertex,dest_vertex); 75 | break; 76 | 77 | case 2: 78 | cout << "Enter the node from which DFS should start"; 79 | cin >> dfs_start; 80 | g.DFS(dfs_start); 81 | break; 82 | } 83 | if(choice==3){ 84 | break; 85 | } 86 | } 87 | 88 | return 0; 89 | } -------------------------------------------------------------------------------- /Sorting/mergesort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* Merges two subarrays of Arr[] 5 | First subarray is Arr[l .. m] 6 | Second subarray is Arr[m+1 .. r] */ 7 | void merge(int Arr[], int l, int m, int r) 8 | { 9 | int n1 = m - l + 1; //Size of the first subarray 10 | int n2 = r - m; //Size of the second subarray 11 | 12 | int L[n1], R[n2]; //Temporary arrays 13 | 14 | //Copy data to the temporary arrays 15 | for(int i = 0; i < n1; i++) 16 | L[i] = Arr[l + i]; 17 | for(int i = 0; i < n2; i++) 18 | R[i] = Arr[m + 1 + i]; 19 | 20 | //Merge the temp arrays back into Arr[l .. r] 21 | int i = 0; //Initial index of first subarray 22 | int j = 0; //Initial index of second subarray 23 | int k = l; //Initial index of merged subarray 24 | while( (i < n1) && (j < n2)) 25 | { 26 | if(L[i] <= R[j]) 27 | { 28 | Arr[k] = L[i]; 29 | i++; 30 | } 31 | else 32 | { 33 | Arr[k] = R[j]; 34 | j++; 35 | } 36 | k++; 37 | } 38 | 39 | //Copy the remaining elements of L[], if any 40 | while(i < n1) 41 | { 42 | Arr[k] = L[i]; 43 | i++; 44 | k++; 45 | } 46 | 47 | //Copy the remaining elements of R[], if any 48 | while(j < n2) 49 | { 50 | Arr[k] = R[j]; 51 | j++; 52 | k++; 53 | } 54 | } 55 | 56 | 57 | /* l is for left index and r is right index of the subarray of Arr to be sorted */ 58 | void mergeSort(int Arr[], int l, int r) 59 | { 60 | if(l < r) 61 | { 62 | //Calculating mid position 63 | //Same as (l+r)/2 but avoids overflow for large l and r 64 | int m = l + (r-l)/2; 65 | 66 | //Divide the array into 2 halves to solve 67 | mergeSort(Arr, l, m); 68 | mergeSort(Arr, m+1, r); 69 | 70 | //Merge the divided arrays 71 | merge(Arr, l, m, r); 72 | } 73 | } 74 | 75 | 76 | /* UTILITY FUNCTIONS */ 77 | 78 | /* Function to print an array 79 | Inline function as it is short and might be called often */ 80 | inline void printArray(int Arr[], int size) 81 | { 82 | for(int i = 0; i < size; i++) 83 | cout< 3 | 4 | // bool defination 5 | typedef int bool; 6 | #define true 1 7 | #define false 0 8 | 9 | #define N 8 10 | 11 | int solveKnightTourUtil(int x, int y, int movei, int sol[N][N], 12 | int xMove[], int yMove[]); 13 | 14 | /* function to check if i,j are valid indexes 15 | for N*N chessboard */ 16 | bool isSafe(int x, int y, int sol[N][N]) 17 | { 18 | return ( x >= 0 && x < N && y >= 0 && 19 | y < N && sol[x][y] == -1); 20 | } 21 | 22 | /*function to print solution matrix sol[N][N] */ 23 | void printSolution(int sol[N][N]) 24 | { 25 | for (int x = 0; x < N; x++) 26 | { 27 | for (int y = 0; y < N; y++) 28 | printf(" %2d ", sol[x][y]); 29 | printf("\n"); 30 | } 31 | } 32 | 33 | /* This function solves the Knight Tour problem using 34 | Backtracking */ 35 | bool solveKT() 36 | { 37 | int sol[N][N]; 38 | 39 | /* Initialization of solution matrix */ 40 | for (int x = 0; x < N; x++) 41 | for (int y = 0; y < N; y++) 42 | sol[x][y] = -1; 43 | 44 | /* xMove[] and yMove[] define next move of Knight. 45 | xMove[] is for next value of x coordinate 46 | yMove[] is for next value of y coordinate */ 47 | int xMove[8] = { 2, 1, -1, -2, -2, -1, 1, 2 }; 48 | int yMove[8] = { 1, 2, 2, 1, -1, -2, -2, -1 }; 49 | 50 | // Since the Knight is initially at the first block 51 | sol[0][0] = 0; 52 | 53 | /* Start from 0,0 and explore all tours using 54 | solveKnightTourUtil() */ 55 | if (solveKnightTourUtil(0, 0, 1, sol, xMove, yMove) == false) 56 | { 57 | printf("Solution does not exist"); 58 | return false; 59 | } 60 | else 61 | printSolution(sol); 62 | 63 | return true; 64 | } 65 | 66 | /* A recursive utility function to solve Knight Tour 67 | problem */ 68 | int solveKnightTourUtil(int x, int y, int movei, int sol[N][N], 69 | int xMove[N], int yMove[N]) 70 | { 71 | int k, next_x, next_y; 72 | if (movei == N*N) 73 | return true; 74 | 75 | /* Try all next moves from the current coordinate x, y */ 76 | for (k = 0; k < 8; k++) 77 | { 78 | next_x = x + xMove[k]; 79 | next_y = y + yMove[k]; 80 | if (isSafe(next_x, next_y, sol)) 81 | { 82 | sol[next_x][next_y] = movei; 83 | if (solveKnightTourUtil(next_x, next_y, movei+1, sol, 84 | xMove, yMove) == true) 85 | return true; 86 | else 87 | sol[next_x][next_y] = -1;// backtracking 88 | } 89 | } 90 | 91 | return false; 92 | } 93 | 94 | // Main function 95 | int main() 96 | { 97 | solveKT(); 98 | return 0; 99 | } -------------------------------------------------------------------------------- /Searching problems/BreadthFirstSearch.cpp: -------------------------------------------------------------------------------- 1 | /* ===== ===== ===== 2 | Theory of Programming 3 | Breadth First Search Algorithm 4 | 5 | ===== ===== ===== */ 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | using namespace std; 13 | 14 | void breadthFirstSearch(vector< list< int > > adjacencyList, int parent[], int level[]) 15 | { 16 | list::iterator itr; 17 | int i, par, lev; 18 | bool flag = true; 19 | // 'lev' represents the level to be assigned 20 | // 'par' represents the parent to be assigned 21 | // 'flag' indicates if graph is unexplored or not 22 | 23 | lev = 0; 24 | level[1] = lev; 25 | // We start from node - 1 26 | // So, Node - 1 is at level 0 27 | // All immediate neighbours are at 28 | // level 1 and so on. 29 | 30 | while (flag) { 31 | flag = false; 32 | for (i = 1; i < adjacencyList.size(); ++i) { 33 | if (level[i] == lev) { 34 | flag = true; 35 | itr = adjacencyList[i].begin(); 36 | par = i; 37 | 38 | while (itr != adjacencyList[i].end()) { 39 | if (level[*itr] != -1) { 40 | ++itr; 41 | continue; 42 | } 43 | 44 | level[*itr] = lev + 1; 45 | parent[*itr] = par; 46 | ++itr; 47 | } 48 | } 49 | } 50 | 51 | ++lev; 52 | } 53 | } 54 | 55 | int main() 56 | { 57 | int vertices, edges, v1, v2, weight; 58 | 59 | printf("Enter the Number of Vertices -\n"); 60 | scanf("%d", &vertices); 61 | 62 | printf("Enter the Number of Edges -\n"); 63 | scanf("%d", &edges); 64 | 65 | // Adjacency List is a vector of lists. 66 | vector< list > adjacencyList(vertices + 1); 67 | 68 | printf("Enter the Edges V1 -> V2\n"); 69 | 70 | for (int i = 1; i <= edges; ++i) { 71 | scanf("%d%d", &v1, &v2); 72 | 73 | // Adding Edges 74 | adjacencyList[v1].push_back(v2); 75 | adjacencyList[v2].push_back(v1); 76 | } 77 | 78 | printf("\nThe Adjacency List-\n"); 79 | // Printing Adjacency List 80 | for (int i = 1; i < adjacencyList.size(); ++i) { 81 | printf("adjacencyList[%d] ", i); 82 | 83 | list::iterator itr = adjacencyList[i].begin(); 84 | 85 | while (itr != adjacencyList[i].end()) { 86 | printf(" -> %d", *itr); 87 | ++itr; 88 | } 89 | printf("\n"); 90 | 91 | 92 | int parent[vertices + 1]; 93 | // Each element of Parent Array holds the Node value of its parent 94 | int level[vertices + 1]; 95 | // Each element of Level Array holds the Level value of that node 96 | 97 | for (int i = 0; i <= vertices; ++i) { 98 | //Initialising our arrays 99 | parent[i] = 0; 100 | level[i] = -1; 101 | } 102 | 103 | breadthFirstSearch(adjacencyList, parent, level); 104 | 105 | // Level Array 106 | printf("\nLevel and Parent Arrays -\n"); 107 | for (int i = 1; i <= vertices; ++i) { 108 | printf("Level of Node %d is %d, Parent is %d\n", i, level[i], parent[i]); 109 | } 110 | 111 | return 0; 112 | } 113 | 114 | -------------------------------------------------------------------------------- /Graph Programs/graph_bfs.cpp: -------------------------------------------------------------------------------- 1 | // Program to print BFS traversal from a given source vertex. BFS(int s) 2 | // traverses vertices reachable from s. 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | // This class represents a directed graph using adjacency list representation 9 | class Graph 10 | { 11 | int V; // No. of vertices 12 | list *adj; // Pointer to an array containing adjacency lists 13 | public: 14 | Graph(int V); // Constructor 15 | void addEdge(int v, int w); // function to add an edge to graph 16 | void BFS(int s); // prints BFS traversal from a given source s 17 | }; 18 | 19 | Graph::Graph(int V) 20 | { 21 | this->V = V; 22 | adj = new list[V]; 23 | } 24 | 25 | void Graph::addEdge(int v, int w) 26 | { 27 | adj[v].push_back(w); // Add w to v’s list. 28 | } 29 | 30 | void Graph::BFS(int s) 31 | { 32 | // Mark all the vertices as not visited 33 | bool *visited = new bool[V]; 34 | for(int i = 0; i < V; i++) 35 | visited[i] = false; 36 | 37 | // Create a queue for BFS 38 | list queue; 39 | 40 | // Mark the current node as visited and enqueue it 41 | visited[s] = true; 42 | queue.push_back(s); 43 | 44 | // 'i' will be used to get all adjacent vertices of a vertex 45 | list::iterator i; 46 | 47 | while(!queue.empty()) 48 | { 49 | // Dequeue a vertex from queue and print it 50 | s = queue.front(); 51 | cout << s << " "; 52 | queue.pop_front(); 53 | 54 | // Get all adjacent vertices of the dequeued vertex s 55 | // If a adjacent has not been visited, then mark it visited 56 | // and enqueue it 57 | for(i = adj[s].begin(); i != adj[s].end(); ++i) 58 | { 59 | if(!visited[*i]) 60 | { 61 | visited[*i] = true; 62 | queue.push_back(*i); 63 | } 64 | } 65 | } 66 | } 67 | 68 | // Driver program to test methods of graph class 69 | int main() 70 | { 71 | int choice,initial_vertex,dest_vertex,no_of_vertex,bfs_start; 72 | cout << "Enter the number of vertices"; 73 | cin >> no_of_vertex; 74 | Graph g(no_of_vertex); 75 | while(1){ 76 | cout << "1. Enter a new edge\n"; 77 | cout << "2. BFS\n"; 78 | cout << "3.Exit"; 79 | cout << "Enter your choice"; 80 | cin >> choice; 81 | switch(choice){ 82 | case 1: cout << "Enter the initial vertex"; 83 | cin >> initial_vertex; 84 | cout << "Enter the destination vertex"; 85 | cin >> dest_vertex; 86 | addEdge(initial_vertex,dest_vertex); 87 | break; 88 | 89 | case 2: 90 | cout << "Enter the node from which BFS should start"; 91 | cin >> bfs_start; 92 | g.BFS(bfs_start); 93 | break; 94 | } 95 | if(choice==3){ 96 | break; 97 | } 98 | } 99 | 100 | return 0; 101 | } -------------------------------------------------------------------------------- /Graph Programs/dijkstra.cpp: -------------------------------------------------------------------------------- 1 | // A C / C++ program for Dijkstra's single source shortest path algorithm. 2 | // The program is for adjacency matrix representation of the graph 3 | //Time Complexity - (V+E) 4 | #include 5 | // Number of vertices in the graph 6 | #define V 9 7 | 8 | // A utility function to find the vertex with minimum distance value, from 9 | // the set of vertices not yet included in shortest path tree 10 | int minDistance(int dist[], bool sptSet[]) 11 | { 12 | // Initialize min value 13 | int min = INT_MAX, min_index; 14 | 15 | for (int v = 0; v < V; v++) 16 | if (sptSet[v] == false && dist[v] <= min) 17 | min = dist[v], min_index = v; 18 | 19 | return min_index; 20 | } 21 | 22 | // A utility function to print the constructed distance array 23 | int printSolution(int dist[], int n) 24 | { 25 | printf("Vertex Distance from Sourcen"); 26 | for (int i = 0; i < V; i++) 27 | printf("%d tt %dn", i, dist[i]); 28 | } 29 | 30 | // Funtion that implements Dijkstra's single source shortest path algorithm 31 | // for a graph represented using adjacency matrix representation 32 | void dijkstra(int graph[V][V], int src) 33 | { 34 | int dist[V]; // The output array. dist[i] will hold the shortest 35 | // distance from src to i 36 | 37 | bool sptSet[V]; // sptSet[i] will true if vertex i is included in shortest 38 | // path tree or shortest distance from src to i is finalized 39 | 40 | // Initialize all distances as INFINITE and stpSet[] as false 41 | for (int i = 0; i < V; i++) 42 | dist[i] = INT_MAX, sptSet[i] = false; 43 | 44 | // Distance of source vertex from itself is always 0 45 | dist[src] = 0; 46 | 47 | // Find shortest path for all vertices 48 | for (int count = 0; count < V-1; count++) 49 | { 50 | // Pick the minimum distance vertex from the set of vertices not 51 | // yet processed. u is always equal to src in first iteration. 52 | int u = minDistance(dist, sptSet); 53 | 54 | // Mark the picked vertex as processed 55 | sptSet[u] = true; 56 | 57 | // Update dist value of the adjacent vertices of the picked vertex. 58 | for (int v = 0; v < V; v++) 59 | 60 | // Update dist[v] only if is not in sptSet, there is an edge from 61 | // u to v, and total weight of path from src to v through u is 62 | // smaller than current value of dist[v] 63 | if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX 64 | && dist[u]+graph[u][v] < dist[v]) 65 | dist[v] = dist[u] + graph[u][v]; 66 | } 67 | 68 | // print the constructed distance array 69 | printSolution(dist, V); 70 | } 71 | 72 | // driver program to test above function 73 | int main() 74 | { 75 | /* Let us create the example graph discussed above */ 76 | int graph[V][V] = {{0, 4, 0, 0, 0, 0, 0, 8, 0}, 77 | {4, 0, 8, 0, 0, 0, 0, 11, 0}, 78 | {0, 8, 0, 7, 0, 4, 0, 0, 2}, 79 | {0, 0, 7, 0, 9, 14, 0, 0, 0}, 80 | {0, 0, 0, 9, 0, 10, 0, 0, 0}, 81 | {0, 0, 4, 14, 10, 0, 2, 0, 0}, 82 | {0, 0, 0, 0, 0, 2, 0, 1, 6}, 83 | {8, 11, 0, 0, 0, 0, 1, 0, 7}, 84 | {0, 0, 2, 0, 0, 0, 6, 7, 0} 85 | }; 86 | 87 | dijkstra(graph, 0); 88 | 89 | return 0; 90 | } -------------------------------------------------------------------------------- /Graph Programs/graph_topological_sort.cpp: -------------------------------------------------------------------------------- 1 | // A C++ program to print topological sorting of a DAG 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | // Class to represent a graph 8 | class Graph 9 | { 10 | int V; // No. of vertices' 11 | 12 | // Pointer to an array containing adjacency listsList 13 | list *adj; 14 | 15 | // A function used by topologicalSort 16 | void topologicalSortUtil(int v, bool visited[], stack &Stack); 17 | public: 18 | Graph(int V); // Constructor 19 | 20 | // function to add an edge to graph 21 | void addEdge(int v, int w); 22 | 23 | // prints a Topological Sort of the complete graph 24 | void topologicalSort(); 25 | }; 26 | 27 | Graph::Graph(int V) 28 | { 29 | this->V = V; 30 | adj = new list[V]; 31 | } 32 | 33 | void Graph::addEdge(int v, int w) 34 | { 35 | adj[v].push_back(w); // Add w to v’s list. 36 | } 37 | 38 | // A recursive function used by topologicalSort 39 | void Graph::topologicalSortUtil(int v, bool visited[], 40 | stack &Stack) 41 | { 42 | // Mark the current node as visited. 43 | visited[v] = true; 44 | 45 | // Recur for all the vertices adjacent to this vertex 46 | list::iterator i; 47 | for (i = adj[v].begin(); i != adj[v].end(); ++i) 48 | if (!visited[*i]) 49 | topologicalSortUtil(*i, visited, Stack); 50 | 51 | // Push current vertex to stack which stores result 52 | Stack.push(v); 53 | } 54 | 55 | // The function to do Topological Sort. It uses recursive 56 | // topologicalSortUtil() 57 | void Graph::topologicalSort() 58 | { 59 | stack Stack; 60 | 61 | // Mark all the vertices as not visited 62 | bool *visited = new bool[V]; 63 | for (int i = 0; i < V; i++) 64 | visited[i] = false; 65 | 66 | // Call the recursive helper function to store Topological 67 | // Sort starting from all vertices one by one 68 | for (int i = 0; i < V; i++) 69 | if (visited[i] == false) 70 | topologicalSortUtil(i, visited, Stack); 71 | 72 | // Print contents of stack 73 | while (Stack.empty() == false) 74 | { 75 | cout << Stack.top() << " "; 76 | Stack.pop(); 77 | } 78 | } 79 | 80 | // Driver program to test above functions 81 | // Driver program to test above functions 82 | int main() 83 | { 84 | // Create a graph given in the above diagram 85 | int choice,initial_vertex,dest_vertex,no_of_vertex; 86 | cout << "Enter the number of vertices"; 87 | cin >> no_of_vertex; 88 | Graph g(no_of_vertex); 89 | while(1){ 90 | cout << "1. Enter a new edge\n"; 91 | cout << "2. Print graph\n"; 92 | cout << "3.Exit"; 93 | cout << "Enter your choice"; 94 | cin >> choice; 95 | switch(choice){ 96 | case 1: cout << "Enter the initial vertex\n"; 97 | cin >> initial_vertex; 98 | cout << "Enter the destination vertex\n"; 99 | cin >> dest_vertex; 100 | g.addEdge(initial_vertex,dest_vertex); 101 | break; 102 | 103 | case 2: 104 | cout << "Following is a Topological Sort of the given graph\n"; 105 | g.topologicalSort(); 106 | break; 107 | } 108 | if(choice==3){ 109 | break; 110 | } 111 | } 112 | 113 | return 0; 114 | } -------------------------------------------------------------------------------- /Searching Techniques/MEDIAN_SEARCH.cpp: -------------------------------------------------------------------------------- 1 | //Libraries Included 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | 7 | /* 8 | 9 | int findMedian() -> Returns the median of the input array. 10 | int partition() -> The partition work is done by this function. 11 | int kthSmallest() -> The recursive function that performs the major calculations 12 | of finding the kthSmallest element only on the condition that the 13 | value of k is less than the size of the array produced after after 14 | every recursive cycle. 15 | int main() -> Driver Function. 16 | */ 17 | 18 | 19 | /* 20 | predefined stuff -> 21 | 22 | sort() 23 | swap() 24 | INT_MAX 25 | */ 26 | int findMedian(int arr[], int size_of_array) 27 | { 28 | sort(arr, arr+size_of_array); // Sort the array 29 | return arr[size_of_array/2]; // Return middle element 30 | } 31 | 32 | int partition(int arr[], int low, int high, int variable_to_be_found) 33 | { 34 | // Search for variable_to_find in arr[low..high] and move it to end 35 | int i; 36 | for (i=low; i 0 && k <= high - low + 1) 60 | { 61 | int n = high-low+1; // Number of elements in arr[low..high] 62 | 63 | // Divide arr[] in groups of size 5, calculate median 64 | // of every group and store it in median[] array. 65 | int i, median[(n+4)/5]; // There will be floor((n+4)/5) groups; 66 | for (i=0; i k-1) // If position is more, recur for left 88 | return kthSmallest(arr, low, pos-1, k); 89 | 90 | // Else recur for right subarray 91 | return kthSmallest(arr, pos+1, high, k-pos+l-1); 92 | } 93 | 94 | // If k is more than number of elements in array 95 | return INT_MAX; 96 | } 97 | 98 | // It searches for x in arr[l..r], and partitions the array 99 | // around x. 100 | 101 | int main() 102 | { 103 | int arr[] = {12, 3, 5, 7, 4, 19, 26}; 104 | int n = sizeof(arr)/sizeof(arr[0]), k = 3; 105 | cout << "K'th smallest element is " 106 | << kthSmallest(arr, 0, n-1, k); 107 | return 0; 108 | } -------------------------------------------------------------------------------- /Stack/Stack2.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This program implements stack as an array using template. 3 | The program is menu-driven. 4 | Shared under Creative Commons 0 (CC0) License. 5 | */ 6 | 7 | #include /*Importing the necessary header files*/ 8 | using namespace std; 9 | #define MAX 50 /*Defining the size of the stack*/ 10 | template 11 | class Stack { 12 | private: 13 | X S[MAX]; /*The stack array*/ 14 | int top; /*The top element to be pushed to stack */ 15 | public: 16 | Stack() { top = -1;} /*Initialized the top to -1 (empty) */ 17 | /* 18 | The push method pushes the element to the top of the stack. 19 | If the stack is full, it returns an error message, otherwise the element is pushed to stack. 20 | */ 21 | void push(X el) { 22 | if(!isFull()) 23 | { 24 | top++; 25 | S[top]=el; 26 | cout << el << " pushed to stack.\n"; 27 | } 28 | else 29 | cout << "Stack is full!\n"; 30 | } 31 | /* 32 | The pop method pops and element from the stack. 33 | If the stack is empty, it returns an error message, otherwise the element is popped from stack. 34 | */ 35 | void pop() { 36 | if(!isEmpty()) 37 | { 38 | cout << topel() << " popped from stack.\n"; 39 | top--; 40 | } 41 | else 42 | cout << "Stack is empty!\n"; 43 | } 44 | /* 45 | The clear method clears all the elements from the stack. 46 | If the stack is empty, it returns an error message, otherwise the stack is cleared. 47 | */ 48 | void clear() { 49 | if(!isEmpty()) 50 | { 51 | top=-1; 52 | cout << "Stack cleared successfully!\n"; 53 | } 54 | else 55 | cout << "Stack is empty!\n"; 56 | } 57 | /* 58 | The topel method returns the topmost element from the stack. 59 | If the stack is empty, it returns an error message, otherwise the top element from stack is returned. 60 | */ 61 | X topel() { 62 | if(!isEmpty()) 63 | return S[top]; 64 | else 65 | cout << "Stack is empty!\n"; 66 | } 67 | /* 68 | The isEmpty method checks whether the stack is empty. 69 | If the top = -1, it returns true, otherwise false. 70 | */ 71 | bool isEmpty() { 72 | if(top==-1) 73 | return true; 74 | else 75 | return false; 76 | } 77 | /* 78 | The isFull method checks whether the stack is full. 79 | If the top >= MAX - 1, it returns true, otherwise false. 80 | */ 81 | bool isFull() { 82 | if(top>=MAX-1) 83 | return true; 84 | else 85 | return false; 86 | } 87 | }; 88 | int main() 89 | { 90 | Stack s1; /* Stack obj implemented as an int */ 91 | Stack s2; /* Stack obj implemented as a char */ 92 | int el; 93 | char el1; 94 | char ch; 95 | do { 96 | cout << "MENU: (q to quit)\n"; 97 | cout << "a) Push to int stack\n"; 98 | cout << "b) Push to char stack\n"; 99 | cout << "c) Pop from int stack\n"; 100 | cout << "d) Pop from char stack\n"; 101 | cout << "e) Clear int stack\n"; 102 | cout << "f) Clear char stack\n"; 103 | cin >> ch; 104 | switch(ch) { 105 | case 'a': 106 | cout << "Enter value for int stack\n"; 107 | cin >> el; 108 | s1.push(el); 109 | break; 110 | case 'b': 111 | cout << "Enter value for char stack\n"; 112 | cin >> el1; 113 | s2.push(el1); 114 | break; 115 | case 'c': 116 | s1.pop(); 117 | break; 118 | case 'd': 119 | s2.pop(); 120 | break; 121 | case 'e': 122 | s1.clear(); 123 | break; 124 | case 'f': 125 | s2.clear(); 126 | break; 127 | default: 128 | cout << "Wrong option\n"; 129 | } 130 | } while(ch!='q'); /* Run the menu till q is pressed. */ 131 | return 0; 132 | } 133 | -------------------------------------------------------------------------------- /Graph Programs/graph_adjacency_list.cpp: -------------------------------------------------------------------------------- 1 | // A C++ Program to demonstrate adjacency list representation of graphs 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | // A structure to represent an adjacency list node 10 | struct AdjListNode 11 | { 12 | int dest; 13 | struct AdjListNode* next; 14 | }; 15 | 16 | // A structure to represent an adjacency list 17 | struct AdjList 18 | { 19 | struct AdjListNode *head; // pointer to head node of list 20 | }; 21 | 22 | // A structure to represent a graph. A graph is an array of adjacency lists. 23 | // Size of array will be V (number of vertices in graph) 24 | struct Graph 25 | { 26 | int V; 27 | struct AdjList* array; 28 | }; 29 | 30 | // A utility function to create a new adjacency list node 31 | struct AdjListNode* newAdjListNode(int dest) 32 | { 33 | struct AdjListNode* newNode = 34 | (struct AdjListNode*) malloc(sizeof(struct AdjListNode)); 35 | newNode->dest = dest; 36 | newNode->next = NULL; 37 | return newNode; 38 | } 39 | 40 | // A utility function that creates a graph of V vertices 41 | struct Graph* createGraph(int V) 42 | { 43 | struct Graph* graph = (struct Graph*) malloc(sizeof(struct Graph)); 44 | graph->V = V; 45 | 46 | // Create an array of adjacency lists. Size of array will be V 47 | graph->array = (struct AdjList*) malloc(V * sizeof(struct AdjList)); 48 | 49 | // Initialize each adjacency list as empty by making head as NULL 50 | int i; 51 | for (i = 0; i < V; ++i) 52 | graph->array[i].head = NULL; 53 | 54 | return graph; 55 | } 56 | 57 | // Adds an edge to an undirected graph 58 | void addEdge(struct Graph* graph, int src, int dest) 59 | { 60 | // Add an edge from src to dest. A new node is added to the adjacency 61 | // list of src. The node is added at the begining 62 | struct AdjListNode* newNode = newAdjListNode(dest); 63 | newNode->next = graph->array[src].head; 64 | graph->array[src].head = newNode; 65 | 66 | // Since graph is undirected, add an edge from dest to src also 67 | newNode = newAdjListNode(src); 68 | newNode->next = graph->array[dest].head; 69 | graph->array[dest].head = newNode; 70 | } 71 | 72 | // A utility function to print the adjacenncy list representation of graph 73 | void printGraph(struct Graph* graph) 74 | { 75 | int v; 76 | for (v = 0; v < graph->V; ++v) 77 | { 78 | struct AdjListNode* pCrawl = graph->array[v].head; 79 | printf("\n Adjacency list of vertex %d\n head ", v); 80 | while (pCrawl) 81 | { 82 | printf("-> %d", pCrawl->dest); 83 | pCrawl = pCrawl->next; 84 | } 85 | printf("\n"); 86 | } 87 | } 88 | 89 | // Driver program to test above functions 90 | int main() 91 | { 92 | int choice,initial_vertex,dest_vertex,no_of_vertex; 93 | cout << "Enter the number of vertices"; 94 | cin >> no_of_vertex; 95 | struct Graph* graph = createGraph(no_of_vertex); 96 | while(1){ 97 | cout << "1. Enter a new edge\n"; 98 | cout << "2. Print graph\n"; 99 | cout << "3.Exit"; 100 | cout << "Enter your choice"; 101 | cin >> choice; 102 | switch(choice){ 103 | case 1: cout << "Enter the initial vertex"; 104 | cin >> initial_vertex; 105 | cout << "Enter the destination vertex"; 106 | cin >> dest_vertex; 107 | addEdge(graph,initial_vertex,dest_vertex); 108 | break; 109 | 110 | case 2: 111 | // print the adjacency list representation of the above graph 112 | printGraph(graph); 113 | break; 114 | } 115 | if(choice==3){ 116 | break; 117 | } 118 | } 119 | } -------------------------------------------------------------------------------- /Heap/heap.cpp: -------------------------------------------------------------------------------- 1 | // A C++ program to demonstrate Binary Heap Operations 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | // function to swap two integers 7 | void swap(int *x, int *y) 8 | { 9 | int temp = *x; 10 | *x = *y; 11 | *y = temp; 12 | } 13 | // A class for Min Heap 14 | class MinHeap 15 | { 16 | int *harr; // pointer to array of elements in heap 17 | int capacity; // maximum possible size of min heap 18 | int heap_size; // Current number of elements in min heap 19 | public: 20 | // Constructor 21 | MinHeap(int capacity); 22 | 23 | // to heapify a subtree with root at given index 24 | void MinHeapify(int ); 25 | 26 | int parent(int i) { return (i-1)/2; } 27 | 28 | // to get index of left child of node at index i 29 | int left(int i) { return (2*i + 1); } 30 | 31 | // to get index of right child of node at index i 32 | int right(int i) { return (2*i + 2); } 33 | 34 | // to extract the root which is the minimum element 35 | int extractMin(); 36 | 37 | // Decreases key value of key at index i to new_val 38 | void decreaseKey(int i, int new_val); 39 | 40 | // Returns the minimum key (key at root) from min heap 41 | int getMin() { return harr[0]; } 42 | 43 | // Deletes a key stored at index i 44 | void deleteKey(int i); 45 | 46 | // Inserts a new key 'k' 47 | void insertKey(int k); 48 | }; 49 | 50 | // Constructor: Builds a heap from a given array a[] of given size 51 | MinHeap::MinHeap(int cap) 52 | { 53 | heap_size = 0; 54 | capacity = cap; 55 | harr = new int[cap]; 56 | } 57 | 58 | // Inserts a key 'k' 59 | void MinHeap::insertKey(int k) 60 | { 61 | if (heap_size == capacity) 62 | { 63 | cout << "\nOverflow: Could not insertKey\n"; 64 | return; 65 | } 66 | 67 | // First insert the key at the end 68 | heap_size++; 69 | int i = heap_size - 1; 70 | harr[i] = k; 71 | 72 | // Fix the min heap property if it is violated 73 | while (i != 0 && harr[parent(i)] > harr[i]) 74 | { 75 | swap(&harr[i], &harr[parent(i)]); 76 | i = parent(i); 77 | } 78 | } 79 | 80 | // Decreases value of key at index 'i' to new_val. It is assumed that 81 | // new_val is smaller than harr[i]. 82 | void MinHeap::decreaseKey(int i, int new_val) 83 | { 84 | harr[i] = new_val; 85 | while (i != 0 && harr[parent(i)] > harr[i]) 86 | { 87 | swap(&harr[i], &harr[parent(i)]); 88 | i = parent(i); 89 | } 90 | } 91 | 92 | // Method to remove minimum element (or root) from min heap 93 | int MinHeap::extractMin() 94 | { 95 | if (heap_size <= 0) 96 | return INT_MAX; 97 | if (heap_size == 1) 98 | { 99 | heap_size--; 100 | return harr[0]; 101 | } 102 | 103 | // Store the minimum value, and remove it from heap 104 | int root = harr[0]; 105 | harr[0] = harr[heap_size-1]; 106 | heap_size--; 107 | MinHeapify(0); 108 | 109 | return root; 110 | } 111 | 112 | 113 | // This function deletes key at index i. It first reduced value to minus 114 | // infinite, then calls extractMin() 115 | void MinHeap::deleteKey(int i) 116 | { 117 | decreaseKey(i, INT_MIN); 118 | extractMin(); 119 | } 120 | 121 | // A recursive method to heapify a subtree with root at given index 122 | // This method assumes that the subtrees are already heapified 123 | void MinHeap::MinHeapify(int i) 124 | { 125 | int l = left(i); 126 | int r = right(i); 127 | int smallest = i; 128 | if (l < heap_size && harr[l] < harr[i]) 129 | smallest = l; 130 | if (r < heap_size && harr[r] < harr[smallest]) 131 | smallest = r; 132 | if (smallest != i) 133 | { 134 | swap(&harr[i], &harr[smallest]); 135 | MinHeapify(smallest); 136 | } 137 | } 138 | 139 | // Main Function 140 | int main() 141 | { 142 | MinHeap h(11); 143 | h.insertKey(3); 144 | h.insertKey(2); 145 | h.deleteKey(1); 146 | h.insertKey(15); 147 | h.insertKey(5); 148 | h.insertKey(4); 149 | h.insertKey(45); 150 | cout << h.extractMin() << " "; 151 | cout << h.getMin() << " "; 152 | h.decreaseKey(2, 1); 153 | cout << h.getMin(); 154 | return 0; 155 | } -------------------------------------------------------------------------------- /LinkedList/DLL.cpp: -------------------------------------------------------------------------------- 1 | // Doubly LinkedList Implementation 2 | // A complete working C program to demonstrate all insertion methods 3 | #include 4 | #include 5 | 6 | // A linked list node 7 | struct Node 8 | { 9 | int data; 10 | struct Node *next; 11 | struct Node *prev; 12 | }; 13 | 14 | /* Given a reference (pointer to pointer) to the head of a list 15 | and an int, inserts a new node on the front of the list. */ 16 | void push(struct Node** head_ref, int new_data) 17 | { 18 | /* 1. allocate node */ 19 | struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); 20 | 21 | /* 2. put in the data */ 22 | new_node->data = new_data; 23 | 24 | /* 3. Make next of new node as head and previous as NULL */ 25 | new_node->next = (*head_ref); 26 | new_node->prev = NULL; 27 | 28 | /* 4. change prev of head node to new node */ 29 | if((*head_ref) != NULL) 30 | (*head_ref)->prev = new_node ; 31 | 32 | /* 5. move the head to point to the new node */ 33 | (*head_ref) = new_node; 34 | } 35 | 36 | /* Given a node as prev_node, insert a new node after the given node */ 37 | void insertAfter(struct Node* prev_node, int new_data) 38 | { 39 | /*1. check if the given prev_node is NULL */ 40 | if (prev_node == NULL) 41 | { 42 | printf("the given previous node cannot be NULL"); 43 | return; 44 | } 45 | 46 | /* 2. allocate new node */ 47 | struct Node* new_node =(struct Node*) malloc(sizeof(struct Node)); 48 | 49 | /* 3. put in the data */ 50 | new_node->data = new_data; 51 | 52 | /* 4. Make next of new node as next of prev_node */ 53 | new_node->next = prev_node->next; 54 | 55 | /* 5. Make the next of prev_node as new_node */ 56 | prev_node->next = new_node; 57 | 58 | /* 6. Make prev_node as previous of new_node */ 59 | new_node->prev = prev_node; 60 | 61 | /* 7. Change previous of new_node's next node */ 62 | if (new_node->next != NULL) 63 | new_node->next->prev = new_node; 64 | } 65 | 66 | /* Given a reference (pointer to pointer) to the head 67 | of a DLL and an int, appends a new node at the end */ 68 | void append(struct Node** head_ref, int new_data) 69 | { 70 | /* 1. allocate node */ 71 | struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); 72 | 73 | struct Node *last = *head_ref; /* used in step 5*/ 74 | 75 | /* 2. put in the data */ 76 | new_node->data = new_data; 77 | 78 | /* 3. This new node is going to be the last node, so 79 | make next of it as NULL*/ 80 | new_node->next = NULL; 81 | 82 | /* 4. If the Linked List is empty, then make the new 83 | node as head */ 84 | if (*head_ref == NULL) 85 | { 86 | new_node->prev = NULL; 87 | *head_ref = new_node; 88 | return; 89 | } 90 | 91 | /* 5. Else traverse till the last node */ 92 | while (last->next != NULL) 93 | last = last->next; 94 | 95 | /* 6. Change the next of last node */ 96 | last->next = new_node; 97 | 98 | /* 7. Make last node as previous of new node */ 99 | new_node->prev = last; 100 | 101 | return; 102 | } 103 | 104 | // This function prints contents of linked list starting from the given node 105 | void printList(struct Node *node) 106 | { 107 | struct Node *last; 108 | printf("\nTraversal in forward direction \n"); 109 | while (node != NULL) 110 | { 111 | printf(" %d ", node->data); 112 | last = node; 113 | node = node->next; 114 | } 115 | 116 | printf("\nTraversal in reverse direction \n"); 117 | while (last != NULL) 118 | { 119 | printf(" %d ", last->data); 120 | last = last->prev; 121 | } 122 | } 123 | 124 | /* Drier program to test above functions*/ 125 | int main() 126 | { 127 | /* Start with the empty list */ 128 | struct Node* head = NULL; 129 | 130 | // Insert 6. So linked list becomes 6->NULL 131 | append(&head, 6); 132 | 133 | // Insert 7 at the beginning. So linked list becomes 7->6->NULL 134 | push(&head, 7); 135 | 136 | // Insert 1 at the beginning. So linked list becomes 1->7->6->NULL 137 | push(&head, 1); 138 | 139 | // Insert 4 at the end. So linked list becomes 1->7->6->4->NULL 140 | append(&head, 4); 141 | 142 | // Insert 8, after 7. So linked list becomes 1->7->8->6->4->NULL 143 | insertAfter(head->next, 8); 144 | 145 | printf("Created DLL is: "); 146 | printList(head); 147 | 148 | getchar(); 149 | return 0; 150 | } 151 | -------------------------------------------------------------------------------- /Graph Programs/graph_kruskals_algorithm.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for Kruskal's algorithm to find Minimum Spanning Tree 2 | // of a given connected, undirected and weighted graph 3 | #include 4 | #include 5 | #include 6 | 7 | // a structure to represent a weighted edge in graph 8 | struct Edge 9 | { 10 | int src, dest, weight; 11 | }; 12 | 13 | // a structure to represent a connected, undirected and weighted graph 14 | struct Graph 15 | { 16 | // V-> Number of vertices, E-> Number of edges 17 | int V, E; 18 | 19 | // graph is represented as an array of edges. Since the graph is 20 | // undirected, the edge from src to dest is also edge from dest 21 | // to src. Both are counted as 1 edge here. 22 | struct Edge* edge; 23 | }; 24 | 25 | // Creates a graph with V vertices and E edges 26 | struct Graph* createGraph(int V, int E) 27 | { 28 | struct Graph* graph = (struct Graph*) malloc( sizeof(struct Graph) ); 29 | graph->V = V; 30 | graph->E = E; 31 | 32 | graph->edge = (struct Edge*) malloc( graph->E * sizeof( struct Edge ) ); 33 | 34 | return graph; 35 | } 36 | 37 | // A structure to represent a subset for union-find 38 | struct subset 39 | { 40 | int parent; 41 | int rank; 42 | }; 43 | 44 | // A utility function to find set of an element i 45 | // (uses path compression technique) 46 | int find(struct subset subsets[], int i) 47 | { 48 | // find root and make root as parent of i (path compression) 49 | if (subsets[i].parent != i) 50 | subsets[i].parent = find(subsets, subsets[i].parent); 51 | 52 | return subsets[i].parent; 53 | } 54 | 55 | // A function that does union of two sets of x and y 56 | // (uses union by rank) 57 | void Union(struct subset subsets[], int x, int y) 58 | { 59 | int xroot = find(subsets, x); 60 | int yroot = find(subsets, y); 61 | 62 | // Attach smaller rank tree under root of high rank tree 63 | // (Union by Rank) 64 | if (subsets[xroot].rank < subsets[yroot].rank) 65 | subsets[xroot].parent = yroot; 66 | else if (subsets[xroot].rank > subsets[yroot].rank) 67 | subsets[yroot].parent = xroot; 68 | 69 | // If ranks are same, then make one as root and increment 70 | // its rank by one 71 | else 72 | { 73 | subsets[yroot].parent = xroot; 74 | subsets[xroot].rank++; 75 | } 76 | } 77 | 78 | // Compare two edges according to their weights. 79 | // Used in qsort() for sorting an array of edges 80 | int myComp(const void* a, const void* b) 81 | { 82 | struct Edge* a1 = (struct Edge*)a; 83 | struct Edge* b1 = (struct Edge*)b; 84 | return a1->weight > b1->weight; 85 | } 86 | 87 | // The main function to construct MST using Kruskal's algorithm 88 | void KruskalMST(struct Graph* graph) 89 | { 90 | int V = graph->V; 91 | struct Edge result[V]; // Tnis will store the resultant MST 92 | int e = 0; // An index variable, used for result[] 93 | int i = 0; // An index variable, used for sorted edges 94 | 95 | // Step 1: Sort all the edges in non-decreasing order of their weight 96 | // If we are not allowed to change the given graph, we can create a copy of 97 | // array of edges 98 | qsort(graph->edge, graph->E, sizeof(graph->edge[0]), myComp); 99 | 100 | // Allocate memory for creating V ssubsets 101 | struct subset *subsets = 102 | (struct subset*) malloc( V * sizeof(struct subset) ); 103 | 104 | // Create V subsets with single elements 105 | for (int v = 0; v < V; ++v) 106 | { 107 | subsets[v].parent = v; 108 | subsets[v].rank = 0; 109 | } 110 | 111 | // Number of edges to be taken is equal to V-1 112 | while (e < V - 1) 113 | { 114 | // Step 2: Pick the smallest edge. And increment the index 115 | // for next iteration 116 | struct Edge next_edge = graph->edge[i++]; 117 | 118 | int x = find(subsets, next_edge.src); 119 | int y = find(subsets, next_edge.dest); 120 | 121 | // If including this edge does't cause cycle, include it 122 | // in result and increment the index of result for next edge 123 | if (x != y) 124 | { 125 | result[e++] = next_edge; 126 | Union(subsets, x, y); 127 | } 128 | // Else discard the next_edge 129 | } 130 | 131 | // print the contents of result[] to display the built MST 132 | printf("Following are the edges in the constructed MST\n"); 133 | for (i = 0; i < e; ++i) 134 | printf("%d -- %d == %d\n", result[i].src, result[i].dest, 135 | result[i].weight); 136 | return; 137 | } 138 | 139 | // Driver program to test methods of graph class 140 | int main() 141 | { 142 | int choice,initial_vertex,dest_vertex,no_of_vertex,no_of_edges,edge_weight; 143 | cout << "Enter the number of vertices"; 144 | cin >> no_of_vertex; 145 | cout << "Enter the number of edges"; 146 | cin >> no_of_edges; 147 | struct Graph* graph = createGraph(no_of_vertex,no_of_edges); 148 | cout << "Enter the edges\n"; 149 | for(int i=0;i<=no_of_edges-1;i++){ 150 | cout << "Enter the initial vertex\n"; 151 | cin >> initial_vertex; 152 | cout << "Enter the destination vertex\n"; 153 | cin >> dest_vertex; 154 | cout << "Enter the weight of the edge\n"; 155 | cin >> edge_weight; 156 | graph->edge[initial_vertex].src = initial_vertex; 157 | graph->edge[initial_vertex].dest = dest_vertex; 158 | graph->edge[initial_vertex].weight = edge_weight; 159 | } 160 | cout << "The minimum spanning tree is\n"; 161 | KruskalMST(graph); 162 | return 0; 163 | } -------------------------------------------------------------------------------- /Tree Problems/BINARY_SEARCH_TREE.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class BinarySearchTree { 6 | private: 7 | 8 | struct tree_node { 9 | tree_node* left; 10 | tree_node* right; 11 | int data; 12 | }; 13 | tree_node* root; 14 | public: 15 | 16 | BinarySearchTree() { 17 | root = NULL; 18 | } 19 | 20 | bool isEmpty() const { 21 | return root == NULL; 22 | } 23 | void print_inorder(); 24 | void inorder(tree_node*); 25 | void print_preorder(); 26 | void preorder(tree_node*); 27 | void print_postorder(); 28 | void postorder(tree_node*); 29 | void insert(int); 30 | void remove(int); 31 | }; 32 | 33 | // Smaller elements go left 34 | // larger elements go right 35 | 36 | void BinarySearchTree::insert(int d) { 37 | tree_node* t = new tree_node; 38 | tree_node* parent; 39 | t->data = d; 40 | t->left = NULL; 41 | t->right = NULL; 42 | parent = NULL; 43 | // is this a new tree? 44 | if (isEmpty()) root = t; 45 | else { 46 | //Note: ALL insertions are as leaf nodes 47 | tree_node* curr; 48 | curr = root; 49 | // Find the Node's parent 50 | while (curr) { 51 | parent = curr; 52 | if (t->data > curr->data) curr = curr->right; 53 | else curr = curr->left; 54 | } 55 | 56 | if (t->data < parent->data) 57 | parent->left = t; 58 | else 59 | parent->right = t; 60 | } 61 | } 62 | 63 | void BinarySearchTree::remove(int d) { 64 | //Locate the element 65 | bool found = false; 66 | if (isEmpty()) { 67 | cout << " This Tree is empty! " << endl; 68 | return; 69 | } 70 | tree_node* curr; 71 | tree_node* parent; 72 | curr = root; 73 | while (curr != NULL) { 74 | if (curr->data == d) { 75 | found = true; 76 | break; 77 | } else { 78 | parent = curr; 79 | if (d > curr->data) curr = curr->right; 80 | else curr = curr->left; 81 | } 82 | } 83 | if (!found) { 84 | cout << " Data not found! " << endl; 85 | return; 86 | } 87 | 88 | // 3 cases : 89 | // 1. We're removing a leaf node 90 | // 2. We're removing a node with a single child 91 | // 3. we're removing a node with 2 children 92 | 93 | // Node with single child 94 | if ((curr->left == NULL && curr->right != NULL) || (curr->left != NULL 95 | && curr->right == NULL)) { 96 | if (curr->left == NULL && curr->right != NULL) { 97 | if (parent->left == curr) { 98 | parent->left = curr->right; 99 | delete curr; 100 | } else { 101 | parent->right = curr->right; 102 | delete curr; 103 | } 104 | } else // left child present, no right child 105 | { 106 | if (parent->left == curr) { 107 | parent->left = curr->left; 108 | delete curr; 109 | } else { 110 | parent->right = curr->left; 111 | delete curr; 112 | } 113 | } 114 | return; 115 | } 116 | 117 | //We're looking at a leaf node 118 | if (curr->left == NULL && curr->right == NULL) { 119 | if (parent->left == curr) 120 | parent->left = NULL; 121 | else parent->right = NULL; 122 | delete curr; 123 | return; 124 | } 125 | 126 | //Node with 2 children 127 | // replace node with smallest value in right subtree 128 | if (curr->left != NULL && curr->right != NULL) { 129 | tree_node* chkr; 130 | chkr = curr->right; 131 | if ((chkr->left == NULL) && (chkr->right == NULL)) { 132 | curr = chkr; 133 | delete chkr; 134 | curr->right = NULL; 135 | } else // right child has children 136 | { 137 | //if the node's right child has a left child 138 | // Move all the way down left to locate smallest element 139 | 140 | if ((curr->right)->left != NULL) { 141 | tree_node* lcurr; 142 | tree_node* lcurrp; 143 | lcurrp = curr->right; 144 | lcurr = (curr->right)->left; 145 | while (lcurr->left != NULL) { 146 | lcurrp = lcurr; 147 | lcurr = lcurr->left; 148 | } 149 | curr->data = lcurr->data; 150 | delete lcurr; 151 | lcurrp->left = NULL; 152 | } else { 153 | tree_node* tmp; 154 | tmp = curr->right; 155 | curr->data = tmp->data; 156 | curr->right = tmp->right; 157 | delete tmp; 158 | } 159 | 160 | } 161 | return; 162 | } 163 | } 164 | 165 | void BinarySearchTree::print_inorder() { 166 | inorder(root); 167 | } 168 | 169 | void BinarySearchTree::inorder(tree_node* p) { 170 | if (p != NULL) { 171 | if (p->left) inorder(p->left); 172 | cout << " " << p->data << " "; 173 | if (p->right) inorder(p->right); 174 | } else return; 175 | } 176 | 177 | void BinarySearchTree::print_preorder() { 178 | preorder(root); 179 | } 180 | 181 | void BinarySearchTree::preorder(tree_node* p) { 182 | if (p != NULL) { 183 | cout << " " << p->data << " "; 184 | if (p->left) preorder(p->left); 185 | if (p->right) preorder(p->right); 186 | } else return; 187 | } 188 | 189 | void BinarySearchTree::print_postorder() { 190 | postorder(root); 191 | } 192 | 193 | void BinarySearchTree::postorder(tree_node* p) { 194 | if (p != NULL) { 195 | if (p->left) postorder(p->left); 196 | if (p->right) postorder(p->right); 197 | cout << " " << p->data << " "; 198 | } else return; 199 | } 200 | 201 | int main() { 202 | BinarySearchTree b; 203 | int ch, tmp, tmp1; 204 | while (1) { 205 | cout << endl << endl; 206 | cout << " Binary Search Tree Operations " << endl; 207 | cout << " ----------------------------- " << endl; 208 | cout << " 1. Insertion/Creation " << endl; 209 | cout << " 2. In-Order Traversal " << endl; 210 | cout << " 3. Pre-Order Traversal " << endl; 211 | cout << " 4. Post-Order Traversal " << endl; 212 | cout << " 5. Removal " << endl; 213 | cout << " 6. Exit " << endl; 214 | cout << " Enter your choice : "; 215 | cin>>ch; 216 | switch (ch) { 217 | case 1: cout << " Enter Number to be inserted : "; 218 | cin>>tmp; 219 | b.insert(tmp); 220 | break; 221 | case 2: cout << endl; 222 | cout << " In-Order Traversal " << endl; 223 | cout << " -------------------" << endl; 224 | b.print_inorder(); 225 | break; 226 | case 3: cout << endl; 227 | cout << " Pre-Order Traversal " << endl; 228 | cout << " -------------------" << endl; 229 | b.print_preorder(); 230 | break; 231 | case 4: cout << endl; 232 | cout << " Post-Order Traversal " << endl; 233 | cout << " --------------------" << endl; 234 | b.print_postorder(); 235 | break; 236 | case 5: cout << " Enter data to be deleted : "; 237 | cin>>tmp1; 238 | b.remove(tmp1); 239 | break; 240 | case 6: system("pause"); 241 | return 0; 242 | break; 243 | } 244 | } 245 | } 246 | -------------------------------------------------------------------------------- /Tree Problems/TREE.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * C++ Program To Implement BST 3 | */ 4 | # include 5 | # include 6 | using namespace std; 7 | /* 8 | * Node Declaration 9 | */ 10 | struct node 11 | { 12 | int info; 13 | struct node *left; 14 | struct node *right; 15 | }*root; 16 | 17 | /* 18 | * Class Declaration 19 | */ 20 | class BST 21 | { 22 | public: 23 | void find(int, node **, node **); 24 | void insert(int); 25 | void del(int); 26 | void case_a(node *,node *); 27 | void case_b(node *,node *); 28 | void case_c(node *,node *); 29 | void preorder(node *); 30 | void inorder(node *); 31 | void postorder(node *); 32 | void display(node *, int); 33 | BST() 34 | { 35 | root = NULL; 36 | } 37 | }; 38 | /* 39 | * Main Contains Menu 40 | */ 41 | int main() 42 | { 43 | int choice, num; 44 | BST bst; 45 | node *temp; 46 | while (1) 47 | { 48 | cout<<"-----------------"<>choice; 60 | switch(choice) 61 | { 62 | case 1: 63 | temp = new node; 64 | cout<<"Enter the number to be inserted : "; 65 | cin>>temp->info; 66 | bst.insert(root, temp); 67 | case 2: 68 | if (root == NULL) 69 | { 70 | cout<<"Tree is empty, nothing to delete"<>num; 75 | bst.del(num); 76 | break; 77 | case 3: 78 | cout<<"Inorder Traversal of BST:"<info) 118 | { 119 | *loc = root; 120 | *par = NULL; 121 | return; 122 | } 123 | if (item < root->info) 124 | ptr = root->left; 125 | else 126 | ptr = root->right; 127 | ptrsave = root; 128 | while (ptr != NULL) 129 | { 130 | if (item == ptr->info) 131 | { 132 | *loc = ptr; 133 | *par = ptrsave; 134 | return; 135 | } 136 | ptrsave = ptr; 137 | if (item < ptr->info) 138 | ptr = ptr->left; 139 | else 140 | ptr = ptr->right; 141 | } 142 | *loc = NULL; 143 | *par = ptrsave; 144 | } 145 | 146 | /* 147 | * Inserting Element into the Tree 148 | */ 149 | void BST::insert(node *tree, node *newnode) 150 | { 151 | if (root == NULL) 152 | { 153 | root = new node; 154 | root->info = newnode->info; 155 | root->left = NULL; 156 | root->right = NULL; 157 | cout<<"Root Node is Added"<info == newnode->info) 161 | { 162 | cout<<"Element already in the tree"<info > newnode->info) 166 | { 167 | if (tree->left != NULL) 168 | { 169 | insert(tree->left, newnode); 170 | } 171 | else 172 | { 173 | tree->left = newnode; 174 | (tree->left)->left = NULL; 175 | (tree->left)->right = NULL; 176 | cout<<"Node Added To Left"<right != NULL) 183 | { 184 | insert(tree->right, newnode); 185 | } 186 | else 187 | { 188 | tree->right = newnode; 189 | (tree->right)->left = NULL; 190 | (tree->right)->right = NULL; 191 | cout<<"Node Added To Right"<left == NULL && location->right == NULL) 215 | case_a(parent, location); 216 | if (location->left != NULL && location->right == NULL) 217 | case_b(parent, location); 218 | if (location->left == NULL && location->right != NULL) 219 | case_b(parent, location); 220 | if (location->left != NULL && location->right != NULL) 221 | case_c(parent, location); 222 | free(location); 223 | } 224 | 225 | /* 226 | * Case A 227 | */ 228 | void BST::case_a(node *par, node *loc ) 229 | { 230 | if (par == NULL) 231 | { 232 | root = NULL; 233 | } 234 | else 235 | { 236 | if (loc == par->left) 237 | par->left = NULL; 238 | else 239 | par->right = NULL; 240 | } 241 | } 242 | 243 | /* 244 | * Case B 245 | */ 246 | void BST::case_b(node *par, node *loc) 247 | { 248 | node *child; 249 | if (loc->left != NULL) 250 | child = loc->left; 251 | else 252 | child = loc->right; 253 | if (par == NULL) 254 | { 255 | root = child; 256 | } 257 | else 258 | { 259 | if (loc == par->left) 260 | par->left = child; 261 | else 262 | par->right = child; 263 | } 264 | } 265 | 266 | /* 267 | * Case C 268 | */ 269 | void BST::case_c(node *par, node *loc) 270 | { 271 | node *ptr, *ptrsave, *suc, *parsuc; 272 | ptrsave = loc; 273 | ptr = loc->right; 274 | while (ptr->left != NULL) 275 | { 276 | ptrsave = ptr; 277 | ptr = ptr->left; 278 | } 279 | suc = ptr; 280 | parsuc = ptrsave; 281 | if (suc->left == NULL && suc->right == NULL) 282 | case_a(parsuc, suc); 283 | else 284 | case_b(parsuc, suc); 285 | if (par == NULL) 286 | { 287 | root = suc; 288 | } 289 | else 290 | { 291 | if (loc == par->left) 292 | par->left = suc; 293 | else 294 | par->right = suc; 295 | } 296 | suc->left = loc->left; 297 | suc->right = loc->right; 298 | } 299 | 300 | /* 301 | * Pre Order Traversal 302 | */ 303 | void BST::preorder(node *ptr) 304 | { 305 | if (root == NULL) 306 | { 307 | cout<<"Tree is empty"<info<<" "; 313 | preorder(ptr->left); 314 | preorder(ptr->right); 315 | } 316 | } 317 | /* 318 | * In Order Traversal 319 | */ 320 | void BST::inorder(node *ptr) 321 | { 322 | if (root == NULL) 323 | { 324 | cout<<"Tree is empty"<left); 330 | cout<info<<" "; 331 | inorder(ptr->right); 332 | } 333 | } 334 | 335 | /* 336 | * Postorder Traversal 337 | */ 338 | void BST::postorder(node *ptr) 339 | { 340 | if (root == NULL) 341 | { 342 | cout<<"Tree is empty"<left); 348 | postorder(ptr->right); 349 | cout<info<<" "; 350 | } 351 | } 352 | 353 | /* 354 | * Display Tree Structure 355 | */ 356 | void BST::display(node *ptr, int level) 357 | { 358 | int i; 359 | if (ptr != NULL) 360 | { 361 | display(ptr->right, level+1); 362 | cout<: "; 365 | else 366 | { 367 | for (i = 0;i < level;i++) 368 | cout<<" "; 369 | } 370 | cout<info; 371 | display(ptr->left, level+1); 372 | } 373 | } --------------------------------------------------------------------------------