├── graphs ├── BFS.cpp ├── DFS.cpp ├── Experiment 5.docx ├── kruskals.c ├── Prims.cpp ├── Djiksras.cpp ├── Bellmanford.cpp └── Kruskals.cpp ├── Linear Sorting ├── Lab-8.docx ├── countingsorting.cpp ├── Countsort.c └── RadixSort.cpp ├── greedy ├── Experiment 4.docx ├── expt_4_2.c ├── preemptivepriorityscheduling.c ├── intervalpartitioning.c ├── activityselection.c ├── fractionalknapsack.c ├── PriorityPremptiveScheduling.cpp └── Huffmann.cpp ├── Branch and Bound └── Lab10.docx ├── Backtracking ├── BackTracking.docx ├── Nqueen.cpp ├── subsetproblem.cpp └── graphcoloring.cpp ├── Dynamic Programming ├── Lab6.docx ├── Lab7.docx ├── lcs.cpp ├── matrixchainmultiplication.cpp ├── knapsackdp.cpp └── floyd.cpp ├── Brute Force Techniques ├── Lab1.docx ├── inputtimedependsonuser.c ├── linearsearch.c ├── 3.c └── bubbleandselection.cpp ├── Divide And Conquer ├── Experiment2.docx ├── Experiment 3.docx ├── powernum │ ├── iterative.c │ └── recursive.c ├── insertion.cpp ├── linearsearch.c ├── strmatrix.c ├── binarysearch.c ├── quick.c ├── naivemultiplication.c └── merge.cpp ├── sorting ├── insertion.cpp ├── selection.cpp ├── bubble.cpp ├── quick.c └── merge.cpp ├── matrix ├── strmatrix.c ├── strassens.c ├── matrixaddition.c └── naivemultiplication.c ├── LICENSE └── README.md /graphs/BFS.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NishkarshRaj/Design-and-Analysis-of-Algorithms/HEAD/graphs/BFS.cpp -------------------------------------------------------------------------------- /graphs/DFS.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NishkarshRaj/Design-and-Analysis-of-Algorithms/HEAD/graphs/DFS.cpp -------------------------------------------------------------------------------- /Linear Sorting/Lab-8.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NishkarshRaj/Design-and-Analysis-of-Algorithms/HEAD/Linear Sorting/Lab-8.docx -------------------------------------------------------------------------------- /graphs/Experiment 5.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NishkarshRaj/Design-and-Analysis-of-Algorithms/HEAD/graphs/Experiment 5.docx -------------------------------------------------------------------------------- /greedy/Experiment 4.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NishkarshRaj/Design-and-Analysis-of-Algorithms/HEAD/greedy/Experiment 4.docx -------------------------------------------------------------------------------- /Branch and Bound/Lab10.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NishkarshRaj/Design-and-Analysis-of-Algorithms/HEAD/Branch and Bound/Lab10.docx -------------------------------------------------------------------------------- /Backtracking/BackTracking.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NishkarshRaj/Design-and-Analysis-of-Algorithms/HEAD/Backtracking/BackTracking.docx -------------------------------------------------------------------------------- /Dynamic Programming/Lab6.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NishkarshRaj/Design-and-Analysis-of-Algorithms/HEAD/Dynamic Programming/Lab6.docx -------------------------------------------------------------------------------- /Dynamic Programming/Lab7.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NishkarshRaj/Design-and-Analysis-of-Algorithms/HEAD/Dynamic Programming/Lab7.docx -------------------------------------------------------------------------------- /Brute Force Techniques/Lab1.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NishkarshRaj/Design-and-Analysis-of-Algorithms/HEAD/Brute Force Techniques/Lab1.docx -------------------------------------------------------------------------------- /Divide And Conquer/Experiment2.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NishkarshRaj/Design-and-Analysis-of-Algorithms/HEAD/Divide And Conquer/Experiment2.docx -------------------------------------------------------------------------------- /Divide And Conquer/Experiment 3.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NishkarshRaj/Design-and-Analysis-of-Algorithms/HEAD/Divide And Conquer/Experiment 3.docx -------------------------------------------------------------------------------- /Divide And Conquer/powernum/iterative.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | int a,n,i,p=1; 5 | printf("Enter the number whose power you want: "); 6 | scanf("%d",&a); 7 | printf("Enter the number who must be exponent: "); 8 | scanf("%d",&n); 9 | for(i=0;i 2 | #include 3 | int main() 4 | { 5 | clock_t start,end; 6 | //Note that clock functions capturers current clock puls... Hence we divide by clocks per sec to get answer in seconds 7 | double t; 8 | int a; 9 | start=clock(); 10 | scanf("%d",&a); 11 | end=clock(); 12 | t=(double)(end-start)/CLOCKS_PER_SEC; 13 | printf("User took these nanoseconds: %f\n",t*1000000000); 14 | return 0; 15 | } 16 | -------------------------------------------------------------------------------- /Divide And Conquer/powernum/recursive.c: -------------------------------------------------------------------------------- 1 | #include 2 | int power(int a,int n) 3 | { 4 | int i,p=1; 5 | if(n==1) 6 | return p; 7 | else 8 | { 9 | p=p*a; 10 | power(a,n-1); 11 | } 12 | } 13 | int main() 14 | { 15 | int a,n,p; 16 | printf("Enter the number whose exponent you want: "); 17 | scanf("%d",&a); 18 | printf("Enter the exponent value: "); 19 | scanf("%d",&n); 20 | p=power(a,n); 21 | printf("The value of %d over %d is: %d\n",a,n,p); 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /greedy/expt_4_2.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | int n; 5 | printf("Enter the number of problems you want: "); 6 | scanf("%d",&n); 7 | int pnum[n],start[n],burst[n],endtime[n]; 8 | for(i=0;i 2 | int main() 3 | { 4 | int n,i; 5 | printf("Enter the number of elements in the array you want: "); 6 | scanf("%d",&n); 7 | int A[n],output[n]; 8 | printf("Enter the elements of the array\n"); 9 | for(i=0;i 2 | using namespace std; 3 | int main() 4 | { 5 | int n,i,j,key; 6 | cout<<"Enter size of array you want: "; 7 | cin>>n; 8 | int A[n]; 9 | for(i=0;i>A[i]; 13 | } 14 | cout<<"Lets do Insertion sort"<=0 && A[j]>key) 20 | { 21 | A[j+1] = A[j]; 22 | j=j-1; 23 | } 24 | A[j+1]=key; 25 | } 26 | cout<<"Sorted Array is:"< 2 | using namespace std; 3 | int main() 4 | { 5 | int n,i,j,temp; 6 | cout<<"Enter number of elements of array: "; 7 | cin>>n; 8 | int A[n]; 9 | for(i=0;i>A[i]; 13 | } 14 | cout<<"Lets do selection sorting"< 2 | #include 3 | int max(int a, int b); 4 | int lcs( char *X, char *Y, int m, int n ) 5 | { 6 | if (m == 0 || n == 0) 7 | return 0; 8 | if (X[m-1] == Y[n-1]) 9 | return 1 + lcs(X, Y, m-1, n-1); 10 | else 11 | return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n)); 12 | } 13 | int max(int a, int b) 14 | { 15 | return (a > b)? a : b; 16 | } 17 | int main() 18 | { 19 | char X[100],Y[100]; 20 | scanf("%s",&X); 21 | scanf("%s",&Y); 22 | int m = strlen(X); 23 | int n = strlen(Y); 24 | printf("Length of LCS is %d", lcs( X, Y, m, n ) ); 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /sorting/bubble.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int n,i,j,temp; 6 | cout<<"Enter number of elements you want in array: "; 7 | cin>>n; 8 | int A[n]; 9 | for(i=0;i>A[i]; 13 | } 14 | cout<<"Lets sort the array by Bubble Sorting"<A[j+1]) 20 | { 21 | temp = A[j+1]; 22 | A[j+1] = A[j]; 23 | A[j] = temp; 24 | } 25 | } 26 | } 27 | cout<<"Lets see the sorted array"< 2 | #include 3 | using namespace std; 4 | int main() 5 | { 6 | clock_t s,e; 7 | float t; 8 | int n,i,j,key; 9 | cout<<"Enter size of array you want: "; 10 | cin>>n; 11 | int A[n]; 12 | for(i=0;i>A[i]; 16 | } 17 | cout<<"Lets do Insertion sort"<=0 && A[j]>key) 24 | { 25 | A[j+1] = A[j]; 26 | j=j-1; 27 | } 28 | A[j+1]=key; 29 | } 30 | e=clock(); 31 | t=(float)e-s/CLOCKS_PER_SEC; 32 | cout<<"Sorted Array is:"< 2 | #include 3 | int MatrixChainOrder(int p[], int i, int j) 4 | { 5 | if(i == j) 6 | return 0; 7 | int k; 8 | int min = INT_MAX; 9 | int count; 10 | for (k = i; k 2 | int main() 3 | { 4 | int A[2][2],B[2][2],C[2][2],i,j,p1,p2,p3,p4,p5,p6,p7; 5 | printf("Enter the elements of matrix A\n"); 6 | for(i=0;i<2;i++) 7 | { 8 | for(j=0;j<2;j++) 9 | { 10 | scanf("%d",&A[i][j]); 11 | } 12 | } 13 | printf("Enter the elements of matrix B\n"); 14 | for(i=0;i<2;i++) 15 | { 16 | for(j=0;j<2;j++) 17 | { 18 | scanf("%d",&B[i][j]); 19 | } 20 | } 21 | p1=A[0][0]*(B[0][1]-B[1][1]); 22 | p2=(A[0][0]+A[0][1])*B[1][1]; 23 | p3=(A[1][0]+A[1][1])*B[0][0]; 24 | p4=A[1][1]*(B[1][0]-B[0][0]); 25 | p5=(A[0][0]+A[1][1])*(B[0][0]+B[1][1]); 26 | p6=(A[0][1]-A[1][1])*(B[1][0]+B[1][1]); 27 | p7=(A[0][0]-A[1][0])*(B[0][0]+B[0][1]); 28 | C[0][0]=p5+p4-p2+p6; 29 | C[0][1]=p1+p2; 30 | C[1][0]=p3+p4; 31 | C[1][1]=p1+p5-p3-p7; 32 | printf("Printing the array C\n"); 33 | for(i=0;i<2;i++) 34 | { 35 | for(j=0;j<2;j++) 36 | { 37 | printf("%d\t",C[i][j]); 38 | } 39 | printf("\n"); 40 | } 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /matrix/strassens.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | int a[2][2],b[2][2],c[2][2],i,j; 5 | int m1,m2,m3,m4,m5,m6,m7; 6 | printf("Enter the 4 elements of first matrix row wise:\n"); 7 | for(i=0;i<=2;i++) 8 | for(j=0;j<=2;j++) 9 | scanf("%d",&a[i][j]); 10 | printf("Enter the 4 elements of second matrix:\n"); 11 | for(i=0;i<=2;i++) 12 | for(j=0;j<=2;j++) 13 | scanf("%d",&b[i][j]); 14 | m1= (a[0][0] + a[1][1])*(b[0][0]+b[1][1]); 15 | m2= (a[1][0]+a[1][1])*b[0][0]; 16 | m3= a[0][0]*(b[0][1]-b[1][1]); 17 | m4= a[1][1]*(b[1][0]-b[0][0]); 18 | m5= (a[0][0]+a[0][1])*b[1][1]; 19 | m6= (a[1][0]-a[0][0])*(b[0][0]+b[0][1]); 20 | m7= (a[0][1]-a[1][1])*(b[1][0]+b[1][1]); 21 | c[0][0]=m1+m4-m5+m7; 22 | c[0][1]=m3+m5; 23 | c[1][0]=m2+m4; 24 | c[1][1]=m1-m2+m3+m6; 25 | printf("\nAfter multiplication using \n"); 26 | for(i=0;i<2;i++){ 27 | printf("\n"); 28 | for(j=0;j<2;j++) 29 | printf("%d\t",c[i][j]); 30 | } 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /Divide And Conquer/linearsearch.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int linearsearch(int A[],int el,int n) 4 | { 5 | int i,flag=0; 6 | for(i=0;i 2 | #include 3 | int linearsearch(int A[],int el,int n) 4 | { 5 | int i,flag=0; 6 | for(i=0;i 2 | #include 3 | int search(char A[],char B[],int n,int m) 4 | { 5 | int i,j,pos=-1; 6 | for(i=0;i=m) 27 | { 28 | char TEXT[n],PATTERN[m]; 29 | printf("Enter the text string\n"); 30 | scanf("%s",TEXT); 31 | printf("Enter the pattern string\n"); 32 | scanf("%s",PATTERN); 33 | start=clock(); 34 | pos = search(TEXT,PATTERN,n,m); 35 | end=clock(); 36 | t=(double)start-end/CLOCKS_PER_SEC; 37 | printf("The element is found at %d index\n",pos); 38 | printf("The time taken is %f\n",t); 39 | } 40 | else 41 | { 42 | printf("The size of pattern cannot be more than text!!"); 43 | } 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /Divide And Conquer/strmatrix.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int main() 4 | { 5 | int A[2][2],B[2][2],C[2][2],i,j,p1,p2,p3,p4,p5,p6,p7; 6 | clock_t s,e; 7 | float t; 8 | printf("Enter the elements of matrix A\n"); 9 | for(i=0;i<2;i++) 10 | { 11 | for(j=0;j<2;j++) 12 | { 13 | scanf("%d",&A[i][j]); 14 | } 15 | } 16 | printf("Enter the elements of matrix B\n"); 17 | for(i=0;i<2;i++) 18 | { 19 | for(j=0;j<2;j++) 20 | { 21 | scanf("%d",&B[i][j]); 22 | } 23 | } 24 | s=clock(); 25 | p1=A[0][0]*(B[0][1]-B[1][1]); 26 | p2=(A[0][0]+A[0][1])*B[1][1]; 27 | p3=(A[1][0]+A[1][1])*B[0][0]; 28 | p4=A[1][1]*(B[1][0]-B[0][0]); 29 | p5=(A[0][0]+A[1][1])*(B[0][0]+B[1][1]); 30 | p6=(A[0][1]-A[1][1])*(B[1][0]+B[1][1]); 31 | p7=(A[0][0]-A[1][0])*(B[0][0]+B[0][1]); 32 | C[0][0]=p5+p4-p2+p6; 33 | C[0][1]=p1+p2; 34 | C[1][0]=p3+p4; 35 | C[1][1]=p1+p5-p3-p7; 36 | e=clock(); 37 | printf("Printing the array C\n"); 38 | for(i=0;i<2;i++) 39 | { 40 | for(j=0;j<2;j++) 41 | { 42 | printf("%d\t",C[i][j]); 43 | } 44 | printf("\n"); 45 | } 46 | t=(float)e-s/CLOCKS_PER_SEC; 47 | printf("Time taken for processing is: %f\n",t); 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /greedy/preemptivepriorityscheduling.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main () 3 | { 4 | int n,i,j,temp; 5 | printf("Enter the number of processes: "); 6 | scanf("%d",&n); 7 | int pnum[n],start[n],burst[n],turn[n]; 8 | for(i=0;i 2 | #include 3 | void bubble_sort(int A[],int n) 4 | { 5 | int i,j,temp; 6 | for(i=0;iA[j+1]) 11 | { 12 | temp = A[j+1]; 13 | A[j+1] = A[j]; 14 | A[j] = temp; 15 | } 16 | } 17 | } 18 | } 19 | void selection_sort(int A[],int n) 20 | { 21 | int i,j,temp; 22 | for(i=0;i 2 | int main() 3 | { 4 | int i,n,wt,r,c,temp,k; 5 | printf("Enter the number of elements of the array: "); 6 | scanf("%d",&n); 7 | printf("Enter the total weight of the bag: "); 8 | scanf("%d",&wt); 9 | int item[n],value[n],weight[n],matrix[n+1][wt+1]; 10 | for(i=0;ic) 30 | { 31 | matrix[r][c]=matrix[r-1][c]; 32 | } 33 | else if(weight[r-1]<=c) 34 | { 35 | k=c-weight[r-1]; 36 | temp=value[r-1]+matrix[r-1][k]; 37 | if((matrix[r-1][c])>=(temp)) 38 | { 39 | matrix[r][c]=matrix[r-1][c]; 40 | } 41 | else 42 | { 43 | matrix[r][c]=temp; 44 | } 45 | } 46 | } 47 | } 48 | printf("\n\n"); 49 | for(r=0;r 2 | int main() 3 | { 4 | int n,i,j,temp; 5 | printf("Enter the number of activities: "); 6 | scanf("%d",&n); 7 | int pnum[n],start[n],end[n],result,hall; 8 | for(i=0;istart[j]) 23 | { 24 | temp=start[i]; 25 | start[i]=start[j]; 26 | start[j]=temp; 27 | temp=end[i]; 28 | end[i]=end[j]; 29 | end[j]=temp; 30 | temp=pnum[i]; 31 | pnum[i]=pnum[j]; 32 | pnum[j]=temp; 33 | } 34 | } 35 | } 36 | printf("Sorted process on basis of start time are\n"); 37 | printf("Process number start time End time\n"); 38 | for(i=0;i 2 | int main() 3 | { 4 | printf("Matrix addition of matrix!!\n"); 5 | printf("Matrix Addition is only possible for same ordered matrix\n"); 6 | int r,c,i,j; 7 | printf("Enter the number of rows: "); 8 | scanf("%d",&r); 9 | printf("Enter the number of columns: "); 10 | scanf("%d",&c); 11 | int A[r][c],B[r][c],C[r][c]; 12 | for(i=0;i 2 | #include 3 | int binarysearch(int A[],int n,int el); 4 | int binarysearch(int A[],int n,int el) 5 | { 6 | int l,u,mid,flag=0; 7 | l=0; 8 | u=n-1; 9 | while(lA[mid]) 13 | l=mid+1; 14 | else if (el 2 | int main() 3 | { 4 | int count[10],i,n,j,A[10]; 5 | for(i=0;i<10;i++) 6 | { 7 | count[i]=0; 8 | } 9 | printf("Enter number of elements you want (less than 10): "); 10 | scanf("%d",&n); 11 | int B[n]; 12 | for(i=0;i 2 | #include 3 | int main() 4 | { 5 | int n,i,j,temp1,temp2,temp3,lastindex; 6 | clock_t s,end; 7 | float t; 8 | printf("Enter the number of activities to be performed: "); 9 | scanf("%d",&n); 10 | int anum[n],start[n],final[n]; 11 | for(i=0;i=final[lastindex]) 48 | { 49 | printf("%d Activity is performed\n",anum[i]); 50 | lastindex=i; 51 | } 52 | } 53 | end=clock(); 54 | t=(float)end-s/CLOCKS_PER_SEC; 55 | printf("Time taken for processing is: %f\n",t); 56 | return 0; 57 | } 58 | -------------------------------------------------------------------------------- /sorting/quick.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | /////////////////////////// 4 | void swap(int *x,int *y) 5 | { 6 | int temp; 7 | temp = *x; 8 | *x = *y; 9 | *y =temp; 10 | } 11 | //////////////////////////// 12 | int partition(int A[],int low,int high) 13 | { 14 | int i,j,pivot; 15 | pivot = A[high]; 16 | i=low-1; 17 | for(j=low;j<=high-1;j++) 18 | { 19 | if(A[j]<=pivot) 20 | { 21 | i++; 22 | swap(&A[i],&A[j]); 23 | } 24 | } 25 | swap(&A[i+1],&A[high]); 26 | return (i+1); 27 | } 28 | ////////////////////////////// 29 | void quicksort(int A[],int low,int high) 30 | { 31 | int pi; 32 | if (low 2 | #include 3 | /////////////////////////// 4 | void swap(int *x,int *y) 5 | { 6 | int temp; 7 | temp = *x; 8 | *x = *y; 9 | *y =temp; 10 | } 11 | //////////////////////////// 12 | int partition(int A[],int low,int high) 13 | { 14 | int i,j,pivot; 15 | pivot = A[high]; 16 | i=low-1; 17 | for(j=low;j<=high-1;j++) 18 | { 19 | if(A[j]<=pivot) 20 | { 21 | i++; 22 | swap(&A[i],&A[j]); 23 | } 24 | } 25 | swap(&A[i+1],&A[high]); 26 | return (i+1); 27 | } 28 | ////////////////////////////// 29 | void quicksort(int A[],int low,int high) 30 | { 31 | int pi; 32 | if (low 2 | #define V 4 3 | #define INF 99999 4 | void printSolution(int dist[][V]); 5 | void floydWarshall (int graph[][V]) 6 | { 7 | int dist[V][V], i, j, k; 8 | for (i = 0; i < V; i++) 9 | for (j = 0; j < V; j++) 10 | dist[i][j] = graph[i][j]; 11 | for (k = 0; k < V; k++) 12 | { 13 | for (i = 0; i < V; i++) 14 | { 15 | for (j = 0; j < V; j++) 16 | { 17 | if (dist[i][k] + dist[k][j] < dist[i][j]) 18 | dist[i][j] = dist[i][k] + dist[k][j]; 19 | } 20 | } 21 | } 22 | printSolution(dist); 23 | } 24 | void printSolution(int dist[][V]) 25 | { 26 | printf ("The following matrix shows the shortest distances" 27 | " between every pair of vertices \n"); 28 | for (int i = 0; i < V; i++) 29 | { 30 | for (int j = 0; j < V; j++) 31 | { 32 | if (dist[i][j] == INF) 33 | printf("%7s", "INF"); 34 | else 35 | printf ("%7d", dist[i][j]); 36 | } 37 | printf("\n"); 38 | } 39 | } 40 | int main() 41 | { 42 | int graph[V][V] = { {0, 5, INF, 10}, 43 | {INF, 0, 3, INF}, 44 | {INF, INF, 0, 1}, 45 | {INF, INF, INF, 0} 46 | }; 47 | floydWarshall(graph); 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # How to Collaborate: 2 | 3 | 1. Fork the repository to your own GitHub account. 4 | 5 | 2. Clone the repository to your local machine 6 | ``` 7 | $ git clone "https://www.github.com/{Username}/Design-and-Analysis-of-Algorithms.git" 8 | ``` 9 | where username is your GitHub account username. 10 | 11 | 3. Create a branch where you can do your local work. 12 | Never work on **master** branch as we do not allow master commits except by admins. 13 | ``` 14 | $ git branch {branchname} 15 | $ git checkout branchname 16 | ``` 17 | 18 | 4. Do your work and stage your changes. 19 | ``` 20 | $ git add 21 | ``` 22 | 23 | 5. Commit you changes with a commit message containing your name, file(s) worked upon, changes added. 24 | ``` 25 | $ git commit -m "Name| files| Changes" 26 | ``` 27 | 28 | 6. Push changes to your forked repository 29 | ``` 30 | $ git push -u origin branchname 31 | ``` 32 | 33 | # Synchronize forked repository with Upstream repository 34 | 35 | 1. Create upstream as our repository 36 | ``` 37 | $ git remote add upstream "https://www.github.com/NishkarshRaj/Design-and-Analysis-of-Algorithms.git" 38 | ``` 39 | 40 | 2. Fetch upstream changes in local machine 41 | ``` 42 | $ git fetch upstream 43 | ``` 44 | 45 | 3. Switch to master branch 46 | ``` 47 | $ git checkout master 48 | ``` 49 | 50 | 4. Merge changes in local machine 51 | ``` 52 | $ git merge upstream/master 53 | ``` 54 | 55 | 5. Push changes to your forked GitHub repository 56 | ``` 57 | $ git push -f origin master 58 | ``` 59 | 60 | -------------------------------------------------------------------------------- /greedy/fractionalknapsack.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | int n,i,bag,itemp,j; 5 | printf("Enter the number of items: "); 6 | scanf("%d",&n); 7 | int profit[n],weight[n],item[n]; 8 | float ppw[n],ftemp,p=0; 9 | for(i=0;i0) 52 | { 53 | for(i=0;iweight[i]) 60 | { 61 | bag=bag-weight[i]; 62 | p=p+profit[i]; 63 | } 64 | else 65 | { 66 | p=p+ppw[i]*bag; 67 | bag=0; 68 | } 69 | } 70 | } 71 | printf("Total Profit by Knapsack problem is: %f\n",p); 72 | return 0; 73 | } 74 | -------------------------------------------------------------------------------- /Backtracking/Nqueen.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int board[20],count; //global variables 4 | int main() 5 | { 6 | int n,i,j; 7 | void queen(int row,int n); 8 | 9 | printf(" - N Queens Problem Using Backtracking -"); 10 | printf("\n\nEnter number of Queens: "); 11 | scanf("%d",&n); 12 | queen(1,n); 13 | return 0; 14 | } 15 | 16 | //function for printing the solution 17 | void print(int n) 18 | { 19 | int i,j; 20 | printf("\n\nSolution %d:\n\n",++count); 21 | 22 | for(i=1;i<=n;++i) 23 | printf("\t%d",i); 24 | 25 | for(i=1;i<=n;++i) 26 | { 27 | printf("\n\n%d",i); 28 | for(j=1;j<=n;++j) //for nxn board 29 | { 30 | if(board[i]==j) 31 | printf("\tQ"); //queen at i,j position 32 | else 33 | printf("\t-"); //empty slot 34 | } 35 | } 36 | } 37 | 38 | /*funtion to check conflicts 39 | If no conflict for desired postion returns 1 otherwise returns 0*/ 40 | int place(int row,int column) 41 | { 42 | int i; 43 | for(i=1;i<=row-1;++i) 44 | { 45 | //checking column and digonal conflicts 46 | if(board[i]==column) 47 | return 0; 48 | else 49 | if(abs(board[i]-column)==abs(i-row)) 50 | return 0; 51 | } 52 | 53 | return 1; //no conflicts 54 | } 55 | 56 | //function to check for proper positioning of queen 57 | void queen(int row,int n) 58 | { 59 | int column; 60 | for(column=1;column<=n;++column) 61 | { 62 | if(place(row,column)) 63 | { 64 | board[row]=column; //no conflicts so place queen 65 | if(row==n) //dead end 66 | print(n); //printing the board configuration 67 | else //try queen with next position 68 | queen(row+1,n); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /Backtracking/subsetproblem.cpp: -------------------------------------------------------------------------------- 1 | // A Dynamic Programming solution for subset sum problem 2 | #include 3 | 4 | // Returns true if there is a subset of set[] with sun equal to given sum 5 | bool isSubsetSum(int set[], int n, int sum) 6 | { 7 | // The value of subset[i][j] will be true if there is a 8 | // subset of set[0..j-1] with sum equal to i 9 | bool subset[n+1][sum+1]; 10 | 11 | // If sum is 0, then answer is true 12 | for (int i = 0; i <= n; i++) 13 | subset[i][0] = true; 14 | 15 | // If sum is not 0 and set is empty, then answer is false 16 | for (int i = 1; i <= sum; i++) 17 | subset[0][i] = false; 18 | 19 | // Fill the subset table in botton up manner 20 | for (int i = 1; i <= n; i++) 21 | { 22 | for (int j = 1; j <= sum; j++) 23 | { 24 | if(j= set[i-1]) 27 | subset[i][j] = subset[i-1][j] || subset[i - 1][j-set[i-1]]; 28 | } 29 | } 30 | 31 | // uncomment this code to print table 32 | for (int i = 0; i <= n; i++) 33 | { 34 | for (int j = 0; j <= sum; j++) 35 | printf ("%4d\t", subset[i][j]); 36 | printf("\n"); 37 | } 38 | 39 | return subset[n][sum]; 40 | } 41 | int main() 42 | { 43 | int set[] = {3, 34, 4, 12, 5, 2}; 44 | int sum = 9; 45 | int n = sizeof(set)/sizeof(set[0]); 46 | if (isSubsetSum(set, n, sum) == true) 47 | printf("Found a subset with given sum"); 48 | else 49 | printf("No subset with given sum"); 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /matrix/naivemultiplication.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | int r1,c1,r2,c2,i,j,k; 5 | printf("Enter the number of rows and columns of first matrix\n"); 6 | scanf("%d%d",&r1,&c1); 7 | int A[r1][c1]; 8 | for(i=0;i 2 | int main() 3 | { 4 | int n,i,j,temp,t=0; 5 | printf("Enter the number of processes you want: "); 6 | scanf("%d",&n); 7 | int p[n],s[n],pt[n],c[n]; 8 | for(i=0;is[j+1]) 31 | { 32 | temp=s[j]; 33 | s[j]=s[j+1]; 34 | s[j+1]=temp; 35 | // 36 | temp=p[j]; 37 | p[j]=p[j+1]; 38 | p[j+1]=temp; 39 | // 40 | temp=pt[j+1]; 41 | pt[j]=pt[j+1]; 42 | pt[j+1]=temp; 43 | // 44 | } 45 | } 46 | } 47 | /////////////// 48 | printf("PNum Start Burst\n"); 49 | for(i=0;i 2 | int main() 3 | { 4 | int n,r,c,k=0,temp,count=0; 5 | printf("Enter the number of vertex you want: "); 6 | scanf("%d",&n); 7 | int adj[n][n]; 8 | int E[20],E1[20],E2[20]; 9 | for(r=0;rc) 14 | { 15 | printf("Enter the weight between %d and %d element: ",r+1,c+1); 16 | scanf("%d",&adj[r][c]); 17 | E[k]=adj[r][c]; 18 | E1[k]=r+1; 19 | E2[k]=c+1; 20 | k++; 21 | } 22 | else 23 | { 24 | adj[r][c]=0; 25 | } 26 | } 27 | } 28 | ////////////////////////////////////////// 29 | for(r=0;r 2 | using namespace std; 3 | //l is lowest index and r is the max index (left and right) 4 | void merge(int A[],int l,int m ,int r) 5 | { 6 | //this function is to merge the partitioned arrays 7 | //creating temp arrays 8 | int n1 = m-l+1; 9 | int n2 = r-m; 10 | int A1[n1],A2[n2],i,j,k; 11 | //First subarray begins from l to m 12 | //second subarray begins from m+1 to r 13 | //Filling the array 14 | for(i=0;i>n; 73 | int A[n]; 74 | for(i=0;i>A[i]; 78 | } 79 | cout<<"Lets do merge sorting"< 2 | #include 3 | int main() 4 | { 5 | int r1,c1,r2,c2,i,j,k; 6 | clock_t s,e; 7 | float t; 8 | printf("Enter the number of rows and columns of first matrix\n"); 9 | scanf("%d%d",&r1,&c1); 10 | int A[r1][c1]; 11 | for(i=0;i 2 | #include 3 | using namespace std; 4 | //l is lowest index and r is the max index (left and right) 5 | void merge(int A[],int l,int m ,int r) 6 | { 7 | //this function is to merge the partitioned arrays 8 | //creating temp arrays 9 | int n1 = m-l+1; 10 | int n2 = r-m; 11 | int A1[n1],A2[n2],i,j,k; 12 | //First subarray begins from l to m 13 | //second subarray begins from m+1 to r 14 | //Filling the array 15 | for(i=0;i>n; 76 | int A[n]; 77 | for(i=0;i>A[i]; 81 | } 82 | cout<<"Lets do merge sorting"< 2 | using namespace std; 3 | // A Function to get the number with the maximum number in the array 4 | int getMax(int arr[], int n) 5 | { 6 | int mx = arr[0]; 7 | for (int i = 1; i < n; i++) 8 | if (arr[i] > mx) 9 | mx = arr[i]; 10 | return mx; 11 | } 12 | //Count sort function that is used to sort any combination of array elements that can be mapped in 10 element array (0-9) 13 | void countSort(int arr[], int n, int exp) 14 | { 15 | int output[n]; // output array 16 | int i,count[10]; 17 | for(i=0;i<10;i++) 18 | { 19 | count[i]=0; 20 | } 21 | // Store count of occurrences in count[] 22 | for (i = 0; i < n; i++) 23 | count[ (arr[i]/exp)%10 ]++; 24 | // Change count[i] so that count[i] now contains actual 25 | // position of this digit in output[] 26 | for (i = 1; i < 10; i++) 27 | count[i] += count[i - 1]; 28 | // Build the output array 29 | for (i = n - 1; i >= 0; i--) 30 | { 31 | output[count[ (arr[i]/exp)%10 ] - 1] = arr[i]; 32 | count[ (arr[i]/exp)%10 ]--; 33 | } 34 | // Copy the output array to arr[], so that arr[] now 35 | // contains sorted numbers according to current digit 36 | for (i = 0; i < n; i++) 37 | { 38 | arr[i] = output[i]; 39 | } 40 | } 41 | //Radix sort function 42 | ///////////////////////////////// 43 | void radixsort(int arr[], int n) 44 | { 45 | //Getting the maximum number of digits in the array such that the exponent loop can be defined around it 46 | int m = getMax(arr, n); 47 | 48 | // Do counting sort for every digit. Note that instead 49 | // of passing digit number, exp is passed. exp is 10^i 50 | // where i is current digit number 51 | for (int exp = 1; m/exp > 0; exp *= 10) 52 | { 53 | countSort(arr, n, exp); 54 | } 55 | } 56 | //Print Array to print the array 57 | //////////////////////////////////////////// 58 | void print(int arr[], int n) 59 | { 60 | cout< 2 | #include 3 | using namespace std; 4 | 5 | // A class that represents an undirected graph 6 | class Graph 7 | { 8 | int V; // No. of vertices 9 | list *adj; // A dynamic array of adjacency lists 10 | public: 11 | // Constructor and destructor 12 | Graph(int V) { this->V = V; adj = new list[V]; } 13 | ~Graph() { delete [] adj; } 14 | 15 | // function to add an edge to graph 16 | void addEdge(int v, int w); 17 | 18 | // Prints greedy coloring of the vertices 19 | void greedyColoring(); 20 | }; 21 | 22 | void Graph::addEdge(int v, int w) 23 | { 24 | adj[v].push_back(w); 25 | adj[w].push_back(v); // Note: the graph is undirected 26 | } 27 | 28 | // Assigns colors (starting from 0) to all vertices and prints 29 | // the assignment of colors 30 | void Graph::greedyColoring() 31 | { 32 | int result[V]; 33 | 34 | // Assign the first color to first vertex 35 | result[0] = 0; 36 | 37 | // Initialize remaining V-1 vertices as unassigned 38 | for (int u = 1; u < V; u++) 39 | result[u] = -1; // no color is assigned to u 40 | 41 | // A temporary array to store the available colors. True 42 | // value of available[cr] would mean that the color cr is 43 | // assigned to one of its adjacent vertices 44 | bool available[V]; 45 | for (int cr = 0; cr < V; cr++) 46 | available[cr] = false; 47 | 48 | // Assign colors to remaining V-1 vertices 49 | for (int u = 1; u < V; u++) 50 | { 51 | // Process all adjacent vertices and flag their colors 52 | // as unavailable 53 | list::iterator i; 54 | for (i = adj[u].begin(); i != adj[u].end(); ++i) 55 | if (result[*i] != -1) 56 | available[result[*i]] = true; 57 | 58 | // Find the first available color 59 | int cr; 60 | for (cr = 0; cr < V; cr++) 61 | if (available[cr] == false) 62 | break; 63 | 64 | result[u] = cr; // Assign the found color 65 | 66 | // Reset the values back to false for the next iteration 67 | for (i = adj[u].begin(); i != adj[u].end(); ++i) 68 | if (result[*i] != -1) 69 | available[result[*i]] = false; 70 | } 71 | 72 | // print the result 73 | for (int u = 0; u < V; u++) 74 | cout << "Vertex " << u << " ---> Color " 75 | << result[u] << endl; 76 | } 77 | 78 | // Driver program to test above function 79 | int main() 80 | { 81 | Graph g1(5); 82 | g1.addEdge(0, 1); 83 | g1.addEdge(0, 2); 84 | g1.addEdge(1, 2); 85 | g1.addEdge(1, 3); 86 | g1.addEdge(2, 3); 87 | g1.addEdge(3, 4); 88 | cout << "Coloring of graph 1 \n"; 89 | g1.greedyColoring(); 90 | Graph g2(5); 91 | g2.addEdge(0, 1); 92 | g2.addEdge(0, 2); 93 | g2.addEdge(1, 2); 94 | g2.addEdge(1, 4); 95 | g2.addEdge(2, 4); 96 | g2.addEdge(4, 3); 97 | cout << "\nColoring of graph 2 \n"; 98 | g2.greedyColoring(); 99 | return 0; 100 | } 101 | -------------------------------------------------------------------------------- /graphs/Prims.cpp: -------------------------------------------------------------------------------- 1 | 2 | // A C / C++ program for Prim's Minimum 3 | // Spanning Tree (MST) algorithm. The program is 4 | // for adjacency matrix representation of the graph 5 | #include 6 | #include 7 | #include 8 | // Number of vertices in the graph 9 | #define V 5 10 | 11 | // A utility function to find the vertex with 12 | // minimum key value, from the set of vertices 13 | // not yet included in MST 14 | int minKey(int key[], bool mstSet[]) 15 | { 16 | // Initialize min value 17 | int min = INT_MAX, min_index; 18 | 19 | for (int v = 0; v < V; v++) 20 | if (mstSet[v] == false && key[v] < min) 21 | min = key[v], min_index = v; 22 | 23 | return min_index; 24 | } 25 | 26 | // A utility function to print the 27 | // constructed MST stored in parent[] 28 | int printMST(int parent[], int n, int graph[V][V]) 29 | { 30 | printf("Edge \tWeight\n"); 31 | for (int i = 1; i < V; i++) 32 | printf("%d - %d \t%d \n", parent[i], i, graph[i][parent[i]]); 33 | } 34 | 35 | // Function to construct and print MST for 36 | // a graph represented using adjacency 37 | // matrix representation 38 | void primMST(int graph[V][V]) 39 | { 40 | // Array to store constructed MST 41 | int parent[V]; 42 | // Key values used to pick minimum weight edge in cut 43 | int key[V]; 44 | // To represent set of vertices not yet included in MST 45 | bool mstSet[V]; 46 | 47 | // Initialize all keys as INFINITE 48 | for (int i = 0; i < V; i++) 49 | key[i] = INT_MAX, mstSet[i] = false; 50 | 51 | // Always include first 1st vertex in MST. 52 | // Make key 0 so that this vertex is picked as first vertex. 53 | key[0] = 0; 54 | parent[0] = -1; // First node is always root of MST 55 | 56 | // The MST will have V vertices 57 | for (int count = 0; count < V-1; count++) 58 | { 59 | // Pick the minimum key vertex from the 60 | // set of vertices not yet included in MST 61 | int u = minKey(key, mstSet); 62 | 63 | // Add the picked vertex to the MST Set 64 | mstSet[u] = true; 65 | 66 | // Update key value and parent index of 67 | // the adjacent vertices of the picked vertex. 68 | // Consider only those vertices which are not 69 | // yet included in MST 70 | for (int v = 0; v < V; v++) 71 | 72 | // graph[u][v] is non zero only for adjacent vertices of m 73 | // mstSet[v] is false for vertices not yet included in MST 74 | // Update the key only if graph[u][v] is smaller than key[v] 75 | if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v]) 76 | parent[v] = u, key[v] = graph[u][v]; 77 | } 78 | 79 | // print the constructed MST 80 | printMST(parent, V, graph); 81 | } 82 | 83 | 84 | // driver program to test above function 85 | int main() 86 | { 87 | /* Let us create the following graph 88 | 2 3 89 | (0)--(1)--(2) 90 | | / \ | 91 | 6| 8/ \5 |7 92 | | / \ | 93 | (3)-------(4) 94 | 9 */ 95 | int graph[V][V] = {{0, 2, 0, 6, 0}, 96 | {2, 0, 3, 8, 5}, 97 | {0, 3, 0, 0, 7}, 98 | {6, 8, 0, 0, 9}, 99 | {0, 5, 7, 9, 0}}; 100 | 101 | // Print the solution 102 | primMST(graph); 103 | 104 | return 0; 105 | } 106 | -------------------------------------------------------------------------------- /graphs/Djiksras.cpp: -------------------------------------------------------------------------------- 1 | 2 | // A C++ program for Dijkstra's single source shortest path algorithm. 3 | // The program is for adjacency matrix representation of the graph 4 | 5 | #include 6 | #include 7 | 8 | // Number of vertices in the graph 9 | #define V 9 10 | 11 | // A utility function to find the vertex with minimum distance value, from 12 | // the set of vertices not yet included in shortest path tree 13 | int minDistance(int dist[], bool sptSet[]) 14 | { 15 | // Initialize min value 16 | int min = INT_MAX, min_index; 17 | 18 | for (int v = 0; v < V; v++) 19 | if (sptSet[v] == false && dist[v] <= min) 20 | min = dist[v], min_index = v; 21 | 22 | return min_index; 23 | } 24 | 25 | // A utility function to print the constructed distance array 26 | int printSolution(int dist[], int n) 27 | { 28 | printf("Vertex Distance from Source\n"); 29 | for (int i = 0; i < V; i++) 30 | printf("%d tt %d\n", i, dist[i]); 31 | } 32 | 33 | // Function that implements Dijkstra's single source shortest path algorithm 34 | // for a graph represented using adjacency matrix representation 35 | void dijkstra(int graph[V][V], int src) 36 | { 37 | int dist[V]; // The output array. dist[i] will hold the shortest 38 | // distance from src to i 39 | 40 | bool sptSet[V]; // sptSet[i] will true if vertex i is included in shortest 41 | // path tree or shortest distance from src to i is finalized 42 | 43 | // Initialize all distances as INFINITE and stpSet[] as false 44 | for (int i = 0; i < V; i++) 45 | dist[i] = INT_MAX, sptSet[i] = false; 46 | 47 | // Distance of source vertex from itself is always 0 48 | dist[src] = 0; 49 | 50 | // Find shortest path for all vertices 51 | for (int count = 0; count < V-1; count++) 52 | { 53 | // Pick the minimum distance vertex from the set of vertices not 54 | // yet processed. u is always equal to src in the first iteration. 55 | int u = minDistance(dist, sptSet); 56 | 57 | // Mark the picked vertex as processed 58 | sptSet[u] = true; 59 | 60 | // Update dist value of the adjacent vertices of the picked vertex. 61 | for (int v = 0; v < V; v++) 62 | 63 | // Update dist[v] only if is not in sptSet, there is an edge from 64 | // u to v, and total weight of path from src to v through u is 65 | // smaller than current value of dist[v] 66 | if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX 67 | && dist[u]+graph[u][v] < dist[v]) 68 | dist[v] = dist[u] + graph[u][v]; 69 | } 70 | 71 | // print the constructed distance array 72 | printSolution(dist, V); 73 | } 74 | 75 | // driver program to test above function 76 | int main() 77 | { 78 | /* Let us create the example graph discussed above */ 79 | int graph[V][V] = {{0, 4, 0, 0, 0, 0, 0, 8, 0}, 80 | {4, 0, 8, 0, 0, 0, 0, 11, 0}, 81 | {0, 8, 0, 7, 0, 4, 0, 0, 2}, 82 | {0, 0, 7, 0, 9, 14, 0, 0, 0}, 83 | {0, 0, 0, 9, 0, 10, 0, 0, 0}, 84 | {0, 0, 4, 14, 10, 0, 2, 0, 0}, 85 | {0, 0, 0, 0, 0, 2, 0, 1, 6}, 86 | {8, 11, 0, 0, 0, 0, 1, 0, 7}, 87 | {0, 0, 2, 0, 0, 0, 6, 7, 0} 88 | }; 89 | 90 | dijkstra(graph, 0); 91 | 92 | return 0; 93 | } 94 | -------------------------------------------------------------------------------- /graphs/Bellmanford.cpp: -------------------------------------------------------------------------------- 1 | // A C++ program for Bellman-Ford's single source 2 | // shortest path algorithm. 3 | #include 4 | 5 | // a structure to represent a weighted edge in graph 6 | struct Edge 7 | { 8 | int src, dest, weight; 9 | }; 10 | 11 | // a structure to represent a connected, directed and 12 | // weighted graph 13 | struct Graph 14 | { 15 | // V-> Number of vertices, E-> Number of edges 16 | int V, E; 17 | 18 | // graph is represented as an array of edges. 19 | struct Edge* edge; 20 | }; 21 | 22 | // Creates a graph with V vertices and E edges 23 | struct Graph* createGraph(int V, int E) 24 | { 25 | struct Graph* graph = new Graph; 26 | graph->V = V; 27 | graph->E = E; 28 | graph->edge = new Edge[E]; 29 | return graph; 30 | } 31 | 32 | // A utility function used to print the solution 33 | void printArr(int dist[], int n) 34 | { 35 | printf("Vertex Distance from Source\n"); 36 | for (int i = 0; i < n; ++i) 37 | printf("%d \t\t %d\n", i, dist[i]); 38 | } 39 | 40 | // The main function that finds shortest distances from src to 41 | // all other vertices using Bellman-Ford algorithm. The function 42 | // also detects negative weight cycle 43 | void BellmanFord(struct Graph* graph, int src) 44 | { 45 | int V = graph->V; 46 | int E = graph->E; 47 | int dist[V]; 48 | 49 | // Step 1: Initialize distances from src to all other vertices 50 | // as INFINITE 51 | for (int i = 0; i < V; i++) 52 | dist[i] = INT_MAX; 53 | dist[src] = 0; 54 | 55 | // Step 2: Relax all edges |V| - 1 times. A simple shortest 56 | // path from src to any other vertex can have at-most |V| - 1 57 | // edges 58 | for (int i = 1; i <= V-1; i++) 59 | { 60 | for (int j = 0; j < E; j++) 61 | { 62 | int u = graph->edge[j].src; 63 | int v = graph->edge[j].dest; 64 | int weight = graph->edge[j].weight; 65 | if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) 66 | dist[v] = dist[u] + weight; 67 | } 68 | } 69 | 70 | // Step 3: check for negative-weight cycles. The above step 71 | // guarantees shortest distances if graph doesn't contain 72 | // negative weight cycle. If we get a shorter path, then there 73 | // is a cycle. 74 | for (int i = 0; i < E; i++) 75 | { 76 | int u = graph->edge[i].src; 77 | int v = graph->edge[i].dest; 78 | int weight = graph->edge[i].weight; 79 | if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) 80 | printf("Graph contains negative weight cycle"); 81 | } 82 | 83 | printArr(dist, V); 84 | 85 | return; 86 | } 87 | 88 | // Driver program to test above functions 89 | int main() 90 | { 91 | /* Let us create the graph given in above example */ 92 | int V = 5; // Number of vertices in graph 93 | int E = 8; // Number of edges in graph 94 | struct Graph* graph = createGraph(V, E); 95 | 96 | // add edge 0-1 (or A-B in above figure) 97 | graph->edge[0].src = 0; 98 | graph->edge[0].dest = 1; 99 | graph->edge[0].weight = -1; 100 | 101 | // add edge 0-2 (or A-C in above figure) 102 | graph->edge[1].src = 0; 103 | graph->edge[1].dest = 2; 104 | graph->edge[1].weight = 4; 105 | 106 | // add edge 1-2 (or B-C in above figure) 107 | graph->edge[2].src = 1; 108 | graph->edge[2].dest = 2; 109 | graph->edge[2].weight = 3; 110 | 111 | // add edge 1-3 (or B-D in above figure) 112 | graph->edge[3].src = 1; 113 | graph->edge[3].dest = 3; 114 | graph->edge[3].weight = 2; 115 | 116 | // add edge 1-4 (or A-E in above figure) 117 | graph->edge[4].src = 1; 118 | graph->edge[4].dest = 4; 119 | graph->edge[4].weight = 2; 120 | 121 | // add edge 3-2 (or D-C in above figure) 122 | graph->edge[5].src = 3; 123 | graph->edge[5].dest = 2; 124 | graph->edge[5].weight = 5; 125 | 126 | // add edge 3-1 (or D-B in above figure) 127 | graph->edge[6].src = 3; 128 | graph->edge[6].dest = 1; 129 | graph->edge[6].weight = 1; 130 | 131 | // add edge 4-3 (or E-D in above figure) 132 | graph->edge[7].src = 4; 133 | graph->edge[7].dest = 3; 134 | graph->edge[7].weight = -3; 135 | 136 | BellmanFord(graph, 0); 137 | 138 | return 0; 139 | } 140 | -------------------------------------------------------------------------------- /graphs/Kruskals.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 14 | // and weighted graph 15 | struct Graph 16 | { 17 | // V-> Number of vertices, E-> Number of edges 18 | int V, E; 19 | 20 | // graph is represented as an array of edges. 21 | // Since the graph is undirected, the edge 22 | // from src to dest is also edge from dest 23 | // to src. Both are counted as 1 edge here. 24 | struct Edge* edge; 25 | }; 26 | 27 | // Creates a graph with V vertices and E edges 28 | struct Graph* createGraph(int V, int E) 29 | { 30 | struct Graph* graph = new Graph; 31 | graph->V = V; 32 | graph->E = E; 33 | 34 | graph->edge = new Edge[E]; 35 | 36 | return graph; 37 | } 38 | 39 | // A structure to represent a subset for union-find 40 | struct subset 41 | { 42 | int parent; 43 | int rank; 44 | }; 45 | 46 | // A utility function to find set of an element i 47 | // (uses path compression technique) 48 | int find(struct subset subsets[], int i) 49 | { 50 | // find root and make root as parent of i 51 | // (path compression) 52 | if (subsets[i].parent != i) 53 | subsets[i].parent = find(subsets, subsets[i].parent); 54 | 55 | return subsets[i].parent; 56 | } 57 | 58 | // A function that does union of two sets of x and y 59 | // (uses union by rank) 60 | void Union(struct subset subsets[], int x, int y) 61 | { 62 | int xroot = find(subsets, x); 63 | int yroot = find(subsets, y); 64 | 65 | // Attach smaller rank tree under root of high 66 | // rank tree (Union by Rank) 67 | if (subsets[xroot].rank < subsets[yroot].rank) 68 | subsets[xroot].parent = yroot; 69 | else if (subsets[xroot].rank > subsets[yroot].rank) 70 | subsets[yroot].parent = xroot; 71 | 72 | // If ranks are same, then make one as root and 73 | // increment its rank by one 74 | else 75 | { 76 | subsets[yroot].parent = xroot; 77 | subsets[xroot].rank++; 78 | } 79 | } 80 | 81 | // Compare two edges according to their weights. 82 | // Used in qsort() for sorting an array of edges 83 | int myComp(const void* a, const void* b) 84 | { 85 | struct Edge* a1 = (struct Edge*)a; 86 | struct Edge* b1 = (struct Edge*)b; 87 | return a1->weight > b1->weight; 88 | } 89 | 90 | // The main function to construct MST using Kruskal's algorithm 91 | void KruskalMST(struct Graph* graph) 92 | { 93 | int V = graph->V; 94 | struct Edge result[V]; // Tnis will store the resultant MST 95 | int e = 0; // An index variable, used for result[] 96 | int i = 0; // An index variable, used for sorted edges 97 | 98 | // Step 1: Sort all the edges in non-decreasing 99 | // order of their weight. If we are not allowed to 100 | // change the given graph, we can create a copy of 101 | // array of edges 102 | qsort(graph->edge, graph->E, sizeof(graph->edge[0]), myComp); 103 | 104 | // Allocate memory for creating V ssubsets 105 | struct subset *subsets = 106 | (struct subset*) malloc( V * sizeof(struct subset) ); 107 | 108 | // Create V subsets with single elements 109 | for (int v = 0; v < V; ++v) 110 | { 111 | subsets[v].parent = v; 112 | subsets[v].rank = 0; 113 | } 114 | 115 | // Number of edges to be taken is equal to V-1 116 | while (e < V - 1) 117 | { 118 | // Step 2: Pick the smallest edge. And increment 119 | // the index for next iteration 120 | struct Edge next_edge = graph->edge[i++]; 121 | 122 | int x = find(subsets, next_edge.src); 123 | int y = find(subsets, next_edge.dest); 124 | 125 | // If including this edge does't cause cycle, 126 | // include it in result and increment the index 127 | // of result for next edge 128 | if (x != y) 129 | { 130 | result[e++] = next_edge; 131 | Union(subsets, x, y); 132 | } 133 | // Else discard the next_edge 134 | } 135 | 136 | // print the contents of result[] to display the 137 | // built MST 138 | printf("Following are the edges in the constructed MST\n"); 139 | for (i = 0; i < e; ++i) 140 | printf("%d -- %d == %d\n", result[i].src, result[i].dest, 141 | result[i].weight); 142 | return; 143 | } 144 | 145 | // Driver program to test above functions 146 | int main() 147 | { 148 | /* Let us create following weighted graph 149 | 10 150 | 0--------1 151 | | \ | 152 | 6| 5\ |15 153 | | \ | 154 | 2--------3 155 | 4 */ 156 | int V = 4; // Number of vertices in graph 157 | int E = 5; // Number of edges in graph 158 | struct Graph* graph = createGraph(V, E); 159 | 160 | 161 | // add edge 0-1 162 | graph->edge[0].src = 0; 163 | graph->edge[0].dest = 1; 164 | graph->edge[0].weight = 10; 165 | 166 | // add edge 0-2 167 | graph->edge[1].src = 0; 168 | graph->edge[1].dest = 2; 169 | graph->edge[1].weight = 6; 170 | 171 | // add edge 0-3 172 | graph->edge[2].src = 0; 173 | graph->edge[2].dest = 3; 174 | graph->edge[2].weight = 5; 175 | 176 | // add edge 1-3 177 | graph->edge[3].src = 1; 178 | graph->edge[3].dest = 3; 179 | graph->edge[3].weight = 15; 180 | 181 | // add edge 2-3 182 | graph->edge[4].src = 2; 183 | graph->edge[4].dest = 3; 184 | graph->edge[4].weight = 4; 185 | 186 | KruskalMST(graph); 187 | 188 | return 0; 189 | } 190 | -------------------------------------------------------------------------------- /greedy/Huffmann.cpp: -------------------------------------------------------------------------------- 1 | 2 | // C program for Huffman Coding 3 | #include 4 | #include 5 | 6 | // This constant can be avoided by explicitly 7 | // calculating height of Huffman Tree 8 | #define MAX_TREE_HT 100 9 | 10 | // A Huffman tree node 11 | struct MinHeapNode { 12 | 13 | // One of the input characters 14 | char data; 15 | 16 | // Frequency of the character 17 | unsigned freq; 18 | 19 | // Left and right child of this node 20 | struct MinHeapNode *left, *right; 21 | }; 22 | 23 | // A Min Heap: Collection of 24 | // min heap (or Hufmman tree) nodes 25 | struct MinHeap { 26 | 27 | // Current size of min heap 28 | unsigned size; 29 | 30 | // capacity of min heap 31 | unsigned capacity; 32 | 33 | // Attay of minheap node pointers 34 | struct MinHeapNode** array; 35 | }; 36 | 37 | // A utility function allocate a new 38 | // min heap node with given character 39 | // and frequency of the character 40 | struct MinHeapNode* newNode(char data, unsigned freq) 41 | { 42 | struct MinHeapNode* temp 43 | = (struct MinHeapNode*)malloc 44 | (sizeof(struct MinHeapNode)); 45 | 46 | temp->left = temp->right = NULL; 47 | temp->data = data; 48 | temp->freq = freq; 49 | 50 | return temp; 51 | } 52 | 53 | // A utility function to create 54 | // a min heap of given capacity 55 | struct MinHeap* createMinHeap(unsigned capacity) 56 | 57 | { 58 | 59 | struct MinHeap* minHeap 60 | = (struct MinHeap*)malloc(sizeof(struct MinHeap)); 61 | 62 | // current size is 0 63 | minHeap->size = 0; 64 | 65 | minHeap->capacity = capacity; 66 | 67 | minHeap->array 68 | = (struct MinHeapNode**)malloc(minHeap-> 69 | capacity * sizeof(struct MinHeapNode*)); 70 | return minHeap; 71 | } 72 | 73 | // A utility function to 74 | // swap two min heap nodes 75 | void swapMinHeapNode(struct MinHeapNode** a, 76 | struct MinHeapNode** b) 77 | 78 | { 79 | 80 | struct MinHeapNode* t = *a; 81 | *a = *b; 82 | *b = t; 83 | } 84 | 85 | // The standard minHeapify function. 86 | void minHeapify(struct MinHeap* minHeap, int idx) 87 | 88 | { 89 | 90 | int smallest = idx; 91 | int left = 2 * idx + 1; 92 | int right = 2 * idx + 2; 93 | 94 | if (left < minHeap->size && minHeap->array[left]-> 95 | freq < minHeap->array[smallest]->freq) 96 | smallest = left; 97 | 98 | if (right < minHeap->size && minHeap->array[right]-> 99 | freq < minHeap->array[smallest]->freq) 100 | smallest = right; 101 | 102 | if (smallest != idx) { 103 | swapMinHeapNode(&minHeap->array[smallest], 104 | &minHeap->array[idx]); 105 | minHeapify(minHeap, smallest); 106 | } 107 | } 108 | 109 | // A utility function to check 110 | // if size of heap is 1 or not 111 | int isSizeOne(struct MinHeap* minHeap) 112 | { 113 | 114 | return (minHeap->size == 1); 115 | } 116 | 117 | // A standard function to extract 118 | // minimum value node from heap 119 | struct MinHeapNode* extractMin(struct MinHeap* minHeap) 120 | 121 | { 122 | 123 | struct MinHeapNode* temp = minHeap->array[0]; 124 | minHeap->array[0] 125 | = minHeap->array[minHeap->size - 1]; 126 | 127 | --minHeap->size; 128 | minHeapify(minHeap, 0); 129 | 130 | return temp; 131 | } 132 | 133 | // A utility function to insert 134 | // a new node to Min Heap 135 | void insertMinHeap(struct MinHeap* minHeap, 136 | struct MinHeapNode* minHeapNode) 137 | 138 | { 139 | 140 | ++minHeap->size; 141 | int i = minHeap->size - 1; 142 | 143 | while (i && minHeapNode->freq < minHeap->array[(i - 1) / 2]->freq) { 144 | 145 | minHeap->array[i] = minHeap->array[(i - 1) / 2]; 146 | i = (i - 1) / 2; 147 | } 148 | 149 | minHeap->array[i] = minHeapNode; 150 | } 151 | 152 | // A standard funvtion to build min heap 153 | void buildMinHeap(struct MinHeap* minHeap) 154 | 155 | { 156 | 157 | int n = minHeap->size - 1; 158 | int i; 159 | 160 | for (i = (n - 1) / 2; i >= 0; --i) 161 | minHeapify(minHeap, i); 162 | } 163 | 164 | // A utility function to print an array of size n 165 | void printArr(int arr[], int n) 166 | { 167 | int i; 168 | for (i = 0; i < n; ++i) 169 | printf("%d", arr[i]); 170 | 171 | printf("\n"); 172 | } 173 | 174 | // Utility function to check if this node is leaf 175 | int isLeaf(struct MinHeapNode* root) 176 | 177 | { 178 | 179 | return !(root->left) && !(root->right); 180 | } 181 | 182 | // Creates a min heap of capacity 183 | // equal to size and inserts all character of 184 | // data[] in min heap. Initially size of 185 | // min heap is equal to capacity 186 | struct MinHeap* createAndBuildMinHeap(char data[], int freq[], int size) 187 | 188 | { 189 | 190 | struct MinHeap* minHeap = createMinHeap(size); 191 | 192 | for (int i = 0; i < size; ++i) 193 | minHeap->array[i] = newNode(data[i], freq[i]); 194 | 195 | minHeap->size = size; 196 | buildMinHeap(minHeap); 197 | 198 | return minHeap; 199 | } 200 | 201 | // The main function that builds Huffman tree 202 | struct MinHeapNode* buildHuffmanTree(char data[], int freq[], int size) 203 | 204 | { 205 | struct MinHeapNode *left, *right, *top; 206 | 207 | // Step 1: Create a min heap of capacity 208 | // equal to size. Initially, there are 209 | // modes equal to size. 210 | struct MinHeap* minHeap = createAndBuildMinHeap(data, freq, size); 211 | 212 | // Iterate while size of heap doesn't become 1 213 | while (!isSizeOne(minHeap)) { 214 | 215 | // Step 2: Extract the two minimum 216 | // freq items from min heap 217 | left = extractMin(minHeap); 218 | right = extractMin(minHeap); 219 | 220 | // Step 3: Create a new internal 221 | // node with frequency equal to the 222 | // sum of the two nodes frequencies. 223 | // Make the two extracted node as 224 | // left and right children of this new node. 225 | // Add this node to the min heap 226 | // '$' is a special value for internal nodes, not used 227 | top = newNode('$', left->freq + right->freq); 228 | 229 | top->left = left; 230 | top->right = right; 231 | 232 | insertMinHeap(minHeap, top); 233 | } 234 | 235 | // Step 4: The remaining node is the 236 | // root node and the tree is complete. 237 | return extractMin(minHeap); 238 | } 239 | 240 | // Prints huffman codes from the root of Huffman Tree. 241 | // It uses arr[] to store codes 242 | void printCodes(struct MinHeapNode* root, int arr[], int top) 243 | 244 | { 245 | 246 | // Assign 0 to left edge and recur 247 | if (root->left) { 248 | 249 | arr[top] = 0; 250 | printCodes(root->left, arr, top + 1); 251 | } 252 | 253 | // Assign 1 to right edge and recur 254 | if (root->right) { 255 | 256 | arr[top] = 1; 257 | printCodes(root->right, arr, top + 1); 258 | } 259 | 260 | // If this is a leaf node, then 261 | // it contains one of the input 262 | // characters, print the character 263 | // and its code from arr[] 264 | if (isLeaf(root)) { 265 | 266 | printf("%c: ", root->data); 267 | printArr(arr, top); 268 | } 269 | } 270 | 271 | // The main function that builds a 272 | // Huffman Tree and print codes by traversing 273 | // the built Huffman Tree 274 | void HuffmanCodes(char data[], int freq[], int size) 275 | 276 | { 277 | // Construct Huffman Tree 278 | struct MinHeapNode* root 279 | = buildHuffmanTree(data, freq, size); 280 | 281 | // Print Huffman codes using 282 | // the Huffman tree built above 283 | int arr[MAX_TREE_HT], top = 0; 284 | 285 | printCodes(root, arr, top); 286 | } 287 | 288 | // Driver program to test above functions 289 | int main() 290 | { 291 | 292 | char arr[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; 293 | int freq[] = { 5, 9, 12, 13, 16, 45 }; 294 | 295 | int size = sizeof(arr) / sizeof(arr[0]); 296 | 297 | HuffmanCodes(arr, freq, size); 298 | 299 | return 0; 300 | } 301 | --------------------------------------------------------------------------------