Merge branch 'master' into master

This commit is contained in:
Jordan Matthews
2019-08-27 10:33:04 -05:00
committed by GitHub
102 changed files with 3244 additions and 3074 deletions

View File

@@ -1,48 +1,47 @@
#include<stdio.h>
#include <stdio.h>
// Number of vertices in the graph
#define V 4
void printSolution(int color[]);
/* A utility function to check if the current color assignment
is safe for vertex v */
bool isSafe (int v, bool graph[V][V], int color[], int c)
bool isSafe(int v, bool graph[V][V], int color[], int c)
{
for (int i = 0; i < V; i++)
if (graph[v][i] && c == color[i])
return false;
return true;
}
/* A recursive utility function to solve m coloring problem */
void graphColoring(bool graph[V][V], int m, int color[], int v)
{
/* base case: If all vertices are assigned a color then
return true */
if (v == V){
printSolution(color);
if (v == V)
{
printSolution(color);
return;
}
/* Consider this vertex v and try different colors */
for (int c = 1; c <= m; c++)
{
/* Check if assignment of color c to v is fine*/
if (isSafe(v, graph, color, c))
{
color[v] = c;
/* recur to assign colors to rest of the vertices */
graphColoring (graph, m, color, v+1);
color[v] = c;
/* recur to assign colors to rest of the vertices */
graphColoring(graph, m, color, v + 1);
/* If assigning color c doesn't lead to a solution
then remove it */
color[v] = 0;
color[v] = 0;
}
}
}
/* A utility function to print solution */
@@ -50,10 +49,10 @@ void printSolution(int color[])
{
printf(" Following are the assigned colors \n");
for (int i = 0; i < V; i++)
printf(" %d ", color[i]);
printf(" %d ", color[i]);
printf("\n");
}
// driver program to test above function
int main()
{
@@ -64,18 +63,19 @@ int main()
| / |
(0)---(1)
*/
bool graph[V][V] = {{0, 1, 1, 1},
bool graph[V][V] = {
{0, 1, 1, 1},
{1, 0, 1, 0},
{1, 1, 0, 1},
{1, 0, 1, 0},
};
int m = 3; // Number of colors
int color[V];
int color[V];
for (int i = 0; i < V; i++)
for (int i = 0; i < V; i++)
color[i] = 0;
graphColoring(graph, m, color, 0);
return 0;
}

View File

@@ -1,82 +1,77 @@
#include<iostream>
#include <iostream>
#define N 4
using namespace std;
void printSolution(int board[N][N])
{
cout<<"\n";
cout << "\n";
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
cout<<""<<board[i][j];
cout<<"\n";
cout << "" << board[i][j];
cout << "\n";
}
}
bool isSafe(int board[N][N], int row, int col)
{
int i, j;
/* Check this row on left side */
for (i = 0; i < col; i++)
if (board[row][i])
return false;
/* Check upper diagonal on left side */
for (i=row, j=col; i>=0 && j>=0; i--, j--)
for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
if (board[i][j])
return false;
/* Check lower diagonal on left side */
for (i=row, j=col; j>=0 && i<N; i++, j--)
for (i = row, j = col; j >= 0 && i < N; i++, j--)
if (board[i][j])
return false;
return true;
}
void solveNQ(int board[N][N], int col)
{
if (col >= N){
if (col >= N)
{
printSolution(board);
return;
}
/* Consider this column and try placing
this queen in all rows one by one */
for (int i = 0; i < N; i++)
{
/* Check if queen can be placed on
board[i][col] */
if ( isSafe(board, i, col) )
if (isSafe(board, i, col))
{
/* Place this queen in board[i][col] */
// cout<<"\n"<<col<<"can place"<<i;
// cout<<"\n"<<col<<"can place"<<i;
board[i][col] = 1;
/* recur to place rest of the queens */
solveNQ(board, col + 1);
board[i][col] = 0; // BACKTRACK
}
}
}
int main()
{
int board[N][N] = { {0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}
};
solveNQ(board, 0);
int board[N][N] = {{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}};
solveNQ(board, 0);
return 0;
}

View File

@@ -11,64 +11,63 @@
using namespace std;
int solveMaze(int currposrow,int currposcol,int maze[size][size],int soln[size][size])
int solveMaze(int currposrow, int currposcol, int maze[size][size], int soln[size][size])
{
if((currposrow==size-1) && (currposcol==size-1))
if ((currposrow == size - 1) && (currposcol == size - 1))
{
soln[currposrow][currposcol]=1;
for(int i=0;i<size;++i)
soln[currposrow][currposcol] = 1;
for (int i = 0; i < size; ++i)
{
for (int j=0;j<size;++j)
for (int j = 0; j < size; ++j)
{
cout<<soln[i][j];
cout << soln[i][j];
}
cout<<endl;
cout << endl;
}
return 1;
}
else
{
soln[currposrow][currposcol]=1;
soln[currposrow][currposcol] = 1;
// if there exist a solution by moving one step ahead in a collumn
if((currposcol<size-1) && maze[currposrow][currposcol+1]==1 && solveMaze(currposrow,currposcol+1,maze,soln))
if ((currposcol < size - 1) && maze[currposrow][currposcol + 1] == 1 && solveMaze(currposrow, currposcol + 1, maze, soln))
{
return 1;
}
// if there exists a solution by moving one step ahead in a row
if((currposrow<size-1) && maze[currposrow+1][currposcol]==1 && solveMaze(currposrow+1,currposcol,maze,soln))
if ((currposrow < size - 1) && maze[currposrow + 1][currposcol] == 1 && solveMaze(currposrow + 1, currposcol, maze, soln))
{
return 1;
}
// the backtracking part
soln[currposrow][currposcol]=0;
soln[currposrow][currposcol] = 0;
return 0;
}
}
int main(int argc, char const *argv[])
{
int maze[size][size]={
{1,0,1,0},
{1,0,1,1},
{1,0,0,1},
{1,1,1,1}
};
int maze[size][size] = {
{1, 0, 1, 0},
{1, 0, 1, 1},
{1, 0, 0, 1},
{1, 1, 1, 1}};
int soln[size][size];
for(int i=0;i<size;++i)
for (int i = 0; i < size; ++i)
{
for (int j = 0; j < size; ++j)
{
for (int j=0;j<size;++j)
{
soln[i][j]=0;
}
soln[i][j] = 0;
}
}
int currposrow=0;
int currposcol=0;
solveMaze(currposrow,currposcol,maze,soln);
int currposrow = 0;
int currposcol = 0;
solveMaze(currposrow, currposcol, maze, soln);
return 0;
}

View File

@@ -1,24 +1,29 @@
#include<iostream>
#include <iostream>
using namespace std;
///N=9;
int n=9;
int n = 9;
bool isPossible(int mat[][9],int i,int j,int no){
bool isPossible(int mat[][9], int i, int j, int no)
{
///Row or col nahin hona chahiye
for(int x=0;x<n;x++){
if(mat[x][j]==no||mat[i][x]==no){
for (int x = 0; x < n; x++)
{
if (mat[x][j] == no || mat[i][x] == no)
{
return false;
}
}
/// Subgrid mein nahi hona chahiye
int sx = (i/3)*3;
int sy = (j/3)*3;
int sx = (i / 3) * 3;
int sy = (j / 3) * 3;
for(int x=sx;x<sx+3;x++){
for(int y=sy;y<sy+3;y++){
if(mat[x][y]==no){
for (int x = sx; x < sx + 3; x++)
{
for (int y = sy; y < sy + 3; y++)
{
if (mat[x][y] == no)
{
return false;
}
}
@@ -26,49 +31,59 @@ bool isPossible(int mat[][9],int i,int j,int no){
return true;
}
void printMat(int mat[][9]){
void printMat(int mat[][9])
{
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cout<<mat[i][j]<<" ";
if((j+1)%3==0){
cout<<'\t';
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cout << mat[i][j] << " ";
if ((j + 1) % 3 == 0)
{
cout << '\t';
}
}
if((i+1)%3==0){
cout<<endl;
if ((i + 1) % 3 == 0)
{
cout << endl;
}
cout<<endl;
cout << endl;
}
}
bool solveSudoku(int mat[][9],int i,int j){
bool solveSudoku(int mat[][9], int i, int j)
{
///Base Case
if(i==9){
if (i == 9)
{
///Solve kr chuke hain for 9 rows already
printMat(mat);
return true;
}
///Crossed the last Cell in the row
if(j==9){
return solveSudoku(mat,i+1,0);
if (j == 9)
{
return solveSudoku(mat, i + 1, 0);
}
///Blue Cell - Skip
if(mat[i][j]!=0){
return solveSudoku(mat,i,j+1);
if (mat[i][j] != 0)
{
return solveSudoku(mat, i, j + 1);
}
///White Cell
///Try to place every possible no
for(int no=1;no<=9;no++){
if(isPossible(mat,i,j,no)){
for (int no = 1; no <= 9; no++)
{
if (isPossible(mat, i, j, no))
{
///Place the no - assuming solution aa jayega
mat[i][j] = no;
bool aageKiSolveHui = solveSudoku(mat,i,j+1);
if(aageKiSolveHui){
bool aageKiSolveHui = solveSudoku(mat, i, j + 1);
if (aageKiSolveHui)
{
return true;
}
///Nahin solve hui
@@ -80,23 +95,23 @@ bool solveSudoku(int mat[][9],int i,int j){
return false;
}
int main(){
int main()
{
int mat[9][9] =
{{5,3,0,0,7,0,0,0,0},
{6,0,0,1,9,5,0,0,0},
{0,9,8,0,0,0,0,6,0},
{8,0,0,0,6,0,0,0,3},
{4,0,0,8,0,3,0,0,1},
{7,0,0,0,2,0,0,0,6},
{0,6,0,0,0,0,2,8,0},
{0,0,0,4,1,9,0,0,5},
{0,0,0,0,8,0,0,7,9}};
int mat[9][9] =
{{5, 3, 0, 0, 7, 0, 0, 0, 0},
{6, 0, 0, 1, 9, 5, 0, 0, 0},
{0, 9, 8, 0, 0, 0, 0, 6, 0},
{8, 0, 0, 0, 6, 0, 0, 0, 3},
{4, 0, 0, 8, 0, 3, 0, 0, 1},
{7, 0, 0, 0, 2, 0, 0, 0, 6},
{0, 6, 0, 0, 0, 0, 2, 8, 0},
{0, 0, 0, 4, 1, 9, 0, 0, 5},
{0, 0, 0, 0, 8, 0, 0, 7, 9}};
printMat(mat);
cout<<"Solution "<<endl;
solveSudoku(mat,0,0);
printMat(mat);
cout << "Solution " << endl;
solveSudoku(mat, 0, 0);
return 0;
return 0;
}

View File

@@ -1,53 +1,53 @@
#include<iostream.h>
#include<conio.h>
#include<math.h>
#include <iostream.h>
#include <conio.h>
#include <math.h>
float eq(float i)
{
return (pow(i,3)-(4*i)-9); // original equation
return (pow(i, 3) - (4 * i) - 9); // original equation
}
void main()
{
float a,b,x,z;
float a, b, x, z;
clrscr();
for(int i=0;i<100;i++)
for (int i = 0; i < 100; i++)
{
z=eq(i);
if(z>=0)
z = eq(i);
if (z >= 0)
{
b=i;
a=--i;
b = i;
a = --i;
goto START;
}
}
START:
START:
cout<<"\nFirst initial: "<<a;
cout<<"\nSecond initial: "<<b;
for(i=0;i<100;i++)
cout << "\nFirst initial: " << a;
cout << "\nSecond initial: " << b;
for (i = 0; i < 100; i++)
{
x=(a+b)/2;
z=eq(x);
cout<<"\n\nz: "<<z<<"\t["<<a<<" , "<<b<<" | Bisect: "<<x<<"]";
x = (a + b) / 2;
z = eq(x);
cout << "\n\nz: " << z << "\t[" << a << " , " << b << " | Bisect: " << x << "]";
if(z < 0)
if (z < 0)
{
a=x;
a = x;
}
else
{
b=x;
b = x;
}
if(z > 0 && z<0.0009) // stoping criteria
if (z > 0 && z < 0.0009) // stoping criteria
{
goto END;
}
}
END:
cout<<"\n\nRoot: "<<x;
END:
cout << "\n\nRoot: " << x;
getch();
}

View File

@@ -1,59 +1,63 @@
#include<bits/stdc++.h>
#include <bits/stdc++.h>
using namespace std;
int main()
{
int mat_size,i,j,step;
int mat_size, i, j, step;
cout<<"Matrix size: ";
cin>>mat_size;
cout << "Matrix size: ";
cin >> mat_size;
double mat[mat_size+1][mat_size+1], x[mat_size][mat_size+1];
double mat[mat_size + 1][mat_size + 1], x[mat_size][mat_size + 1];
cout<<endl<<"Enter value of the matrix: "<<endl;
for(i=0;i<mat_size;i++)
cout << endl
<< "Enter value of the matrix: " << endl;
for (i = 0; i < mat_size; i++)
{
for(j=0;j<=mat_size;j++)
for (j = 0; j <= mat_size; j++)
{
cin>>mat[i][j]; //Enter (mat_size*mat_size) value of the matrix.
cin >> mat[i][j]; //Enter (mat_size*mat_size) value of the matrix.
}
}
for(step=0;step<mat_size-1;step++){
for(i=step;i<mat_size-1;i++)
for (step = 0; step < mat_size - 1; step++)
{
for (i = step; i < mat_size - 1; i++)
{
double a = (mat[i+1][step]/mat[step][step]);
double a = (mat[i + 1][step] / mat[step][step]);
for(j=step;j<=mat_size;j++)
mat[i+1][j] = mat[i+1][j] - (a * mat[step][j]);
for (j = step; j <= mat_size; j++)
mat[i + 1][j] = mat[i + 1][j] - (a * mat[step][j]);
}
}
cout<<endl<<"Matrix using Gaussian Elimination method: "<<endl;
for(i=0;i<mat_size;i++)
cout << endl
<< "Matrix using Gaussian Elimination method: " << endl;
for (i = 0; i < mat_size; i++)
{
for(j=0;j<=mat_size;j++)
for (j = 0; j <= mat_size; j++)
{
x[i][j] = mat[i][j];
cout<<mat[i][j]<<" ";
cout << mat[i][j] << " ";
}
cout<<endl;
cout << endl;
}
cout<<endl<<"Value of the Gaussian Elimination method: "<<endl;
for(i=mat_size-1;i>=0;i--)
cout << endl
<< "Value of the Gaussian Elimination method: " << endl;
for (i = mat_size - 1; i >= 0; i--)
{
double sum = 0;
for(j=mat_size-1;j>i;j--)
for (j = mat_size - 1; j > i; j--)
{
x[i][j] = x[j][j] * x[i][j];
sum = x[i][j] + sum;
}
if(x[i][i]==0)
if (x[i][i] == 0)
x[i][i] = 0;
else
x[i][i] = (x[i][mat_size] - sum)/(x[i][i]);
x[i][i] = (x[i][mat_size] - sum) / (x[i][i]);
cout<<"x"<<i<<"= "<<x[i][i]<<endl;
cout << "x" << i << "= " << x[i][i] << endl;
}
return 0;
return 0;
}

View File

@@ -1,53 +1,53 @@
#include<iostream.h>
#include<conio.h>
#include<math.h>
#include <iostream.h>
#include <conio.h>
#include <math.h>
float eq(float i)
{
return (pow(i,3)-(4*i)-9); // original equation
return (pow(i, 3) - (4 * i) - 9); // original equation
}
float eq_der(float i)
{
return ((3*pow(i,2))-4); // derivative of equation
return ((3 * pow(i, 2)) - 4); // derivative of equation
}
void main()
{
float a,b,z,c,m,n;
float a, b, z, c, m, n;
clrscr();
for(int i=0;i<100;i++)
for (int i = 0; i < 100; i++)
{
z=eq(i);
if(z>=0)
z = eq(i);
if (z >= 0)
{
b=i;
a=--i;
b = i;
a = --i;
goto START;
}
}
START:
START:
cout<<"\nFirst initial: "<<a;
cout<<"\nSecond initial: "<<b;
c=(a+b)/2;
cout << "\nFirst initial: " << a;
cout << "\nSecond initial: " << b;
c = (a + b) / 2;
for(i=0;i<100;i++)
for (i = 0; i < 100; i++)
{
float h;
m=eq(c);
n=eq_der(c);
m = eq(c);
n = eq_der(c);
z=c-(m/n);
c=z;
z = c - (m / n);
c = z;
if(m > 0 && m<0.009) // stoping criteria
if (m > 0 && m < 0.009) // stoping criteria
{
goto END;
}
}
END:
cout<<"\n\nRoot: "<<z;
END:
cout << "\n\nRoot: " << z;
getch();
}

View File

@@ -1,49 +1,49 @@
#include<iostream.h>
#include<conio.h>
#include<math.h>
#include <iostream.h>
#include <conio.h>
#include <math.h>
float eq(float i)
{
return (pow(i,3)-(4*i)-9); // original equation
return (pow(i, 3) - (4 * i) - 9); // original equation
}
void main()
{
float a,b,z,c,m,n;
float a, b, z, c, m, n;
clrscr();
for(int i=0;i<100;i++)
for (int i = 0; i < 100; i++)
{
z=eq(i);
if(z>=0)
z = eq(i);
if (z >= 0)
{
b=i;
a=--i;
b = i;
a = --i;
goto START;
}
}
START:
START:
cout<<"\nFirst initial: "<<a;
cout<<"\nSecond initial: "<<b;
for(i=0;i<100;i++)
cout << "\nFirst initial: " << a;
cout << "\nSecond initial: " << b;
for (i = 0; i < 100; i++)
{
float h,d;
m=eq(a);
n=eq(b);
float h, d;
m = eq(a);
n = eq(b);
c=((a*n)-(b*m))/(n-m);
a=b;
b=c;
c = ((a * n) - (b * m)) / (n - m);
a = b;
b = c;
z=eq(c);
if(z > 0 && z<0.09) // stoping criteria
z = eq(c);
if (z > 0 && z < 0.09) // stoping criteria
{
goto END;
}
}
END:
cout<<"\n\nRoot: "<<c;
END:
cout << "\n\nRoot: " << c;
getch();
}

View File

@@ -1,49 +1,49 @@
#include<iostream.h>
#include<conio.h>
#include<math.h>
#include <iostream.h>
#include <conio.h>
#include <math.h>
float eq(float i)
{
return (pow(i,3)-(4*i)-9); // origial equation
return (pow(i, 3) - (4 * i) - 9); // origial equation
}
void main()
{
float a,b,z,c,m,n;
float a, b, z, c, m, n;
clrscr();
for(int i=0;i<100;i++)
for (int i = 0; i < 100; i++)
{
z=eq(i);
if(z>=0)
z = eq(i);
if (z >= 0)
{
b=i;
a=--i;
b = i;
a = --i;
goto START;
}
}
START:
START:
cout<<"\nFirst initial: "<<a;
cout<<"\nSecond initial: "<<b;
for(i=0;i<100;i++)
cout << "\nFirst initial: " << a;
cout << "\nSecond initial: " << b;
for (i = 0; i < 100; i++)
{
float h,d;
m=eq(a);
n=eq(b);
float h, d;
m = eq(a);
n = eq(b);
c=((a*n)-(b*m))/(n-m);
a=c;
c = ((a * n) - (b * m)) / (n - m);
a = c;
z=eq(c);
if(z > 0 && z<0.09) // stoping criteria
z = eq(c);
if (z > 0 && z < 0.09) // stoping criteria
{
goto END;
}
}
END:
cout<<"\n\nRoot: "<<c;
END:
cout << "\n\nRoot: " << c;
getch();
}

View File

@@ -1,37 +1,37 @@
#include<conio.h>
#include<iostream.h>
#include<math.h>
#include <conio.h>
#include <iostream.h>
#include <math.h>
float eq(float y)
{
return((3*y)-(cos(y))-2);
return ((3 * y) - (cos(y)) - 2);
}
float eqd(float y)
{
return((0.5)*((cos(y))+2));
return ((0.5) * ((cos(y)) + 2));
}
void main()
{
float y,x1,x2,x3,sum,s,a,f1,f2,gd;
int i,n;
float y, x1, x2, x3, sum, s, a, f1, f2, gd;
int i, n;
clrscr();
for(i=0;i<10;i++)
for (i = 0; i < 10; i++)
{
sum=eq(y);
cout<<"value of equation at "<<i<<" "<<sum<<"\n";
sum = eq(y);
cout << "value of equation at " << i << " " << sum << "\n";
y++;
}
cout<<"enter the x1->";
cin>>x1;
cout<<"enter the no iteration to perform->\n";
cin>>n;
cout << "enter the x1->";
cin >> x1;
cout << "enter the no iteration to perform->\n";
cin >> n;
for(i=0;i<=n;i++)
for (i = 0; i <= n; i++)
{
x2=eqd(x1);
cout<<"\nenter the x2->"<<x2;
x1=x2;
x2 = eqd(x1);
cout << "\nenter the x2->" << x2;
x1 = x2;
}
getch();
}

View File

@@ -3,20 +3,23 @@
using namespace std;
typedef struct node {
typedef struct node
{
int data;
int height;
struct node* left;
struct node* right;
}node;
struct node *left;
struct node *right;
} node;
int max(int a, int b) {
int max(int a, int b)
{
return a > b ? a : b;
}
// Returns a new Node
node* createNode(int data) {
node *createNode(int data)
{
node *nn = new node();
nn->data = data;
nn->height = 0;
@@ -27,21 +30,24 @@ node* createNode(int data) {
// Returns height of tree
int height(node *root) {
if(root==NULL)
int height(node *root)
{
if (root == NULL)
return 0;
return 1 + max(height(root->left), height(root->right));
}
// Returns difference between height of left and right subtree
int getBalance(node *root) {
int getBalance(node *root)
{
return height(root->left) - height(root->right);
}
// Returns Node after Right Rotation
node* rightRotate(node *root) {
node *rightRotate(node *root)
{
node *t = root->left;
node *u = t->right;
t->right = root;
@@ -51,7 +57,8 @@ node* rightRotate(node *root) {
// Returns Node after Left Rotation
node* leftRotate(node *root) {
node *leftRotate(node *root)
{
node *t = root->right;
node *u = t->left;
t->left = root;
@@ -61,57 +68,65 @@ node* leftRotate(node *root) {
// Returns node with minimum value in the tree
node* minValue(node* root) {
if(root->left==NULL)
node *minValue(node *root)
{
if (root->left == NULL)
return root;
return minValue(root->left);
}
// Balanced Insertion
node* insert(node* root, int item) {
node *insert(node *root, int item)
{
node *nn = createNode(item);
if(root == NULL)
if (root == NULL)
return nn;
if(item<root->data)
if (item < root->data)
root->left = insert(root->left, item);
else
root->right = insert(root->right, item);
int b = getBalance(root);
if(b>1) {
if(getBalance(root->left)<0)
root->left = leftRotate(root->left); // Left-Right Case
return rightRotate(root); // Left-Left Case
if (b > 1)
{
if (getBalance(root->left) < 0)
root->left = leftRotate(root->left); // Left-Right Case
return rightRotate(root); // Left-Left Case
}
else if(b<-1) {
if(getBalance(root->right)>0)
root->right = rightRotate(root->right); // Right-Left Case
return leftRotate(root); // Right-Right Case
else if (b < -1)
{
if (getBalance(root->right) > 0)
root->right = rightRotate(root->right); // Right-Left Case
return leftRotate(root); // Right-Right Case
}
return root;
}
// Balanced Deletion
node* deleteNode(node *root, int key) {
if(root == NULL)
node *deleteNode(node *root, int key)
{
if (root == NULL)
return root;
if(key < root->data)
if (key < root->data)
root->left = deleteNode(root->left, key);
else if(key > root->data)
else if (key > root->data)
root->right = deleteNode(root->right, key);
else {
else
{
// Node to be deleted is leaf node or have only one Child
if(!root->right) {
node* temp = root->left;
delete(root);
if (!root->right)
{
node *temp = root->left;
delete (root);
root = NULL;
return temp;
}
else if(!root->left) {
node* temp = root->right;
delete(root);
else if (!root->left)
{
node *temp = root->right;
delete (root);
root = NULL;
return temp;
}
@@ -124,36 +139,38 @@ node* deleteNode(node *root, int key) {
return root;
}
// LevelOrder (Breadth First Search)
void levelOrder(node* root) {
queue<node*> q;
void levelOrder(node *root)
{
queue<node *> q;
q.push(root);
while(!q.empty()) {
while (!q.empty())
{
root = q.front();
cout<<root->data<<" ";
cout << root->data << " ";
q.pop();
if(root->left)
if (root->left)
q.push(root->left);
if(root->right)
if (root->right)
q.push(root->right);
}
}
int main() {
int main()
{
// Testing AVL Tree
node *root = NULL;
int i;
for(i = 1 ; i <= 7 ; i++)
for (i = 1; i <= 7; i++)
root = insert(root, i);
cout<<"LevelOrder: ";
cout << "LevelOrder: ";
levelOrder(root);
root = deleteNode(root, 1); // Deleting key with value 1
cout<<"\nLevelOrder: ";
cout << "\nLevelOrder: ";
levelOrder(root);
root = deleteNode(root, 4); // Deletin key with value 4
cout<<"\nLevelOrder: ";
root = deleteNode(root, 4); // Deletin key with value 4
cout << "\nLevelOrder: ";
levelOrder(root);
return 0;
}

View File

@@ -1,7 +1,6 @@
#include<iostream>
#include <iostream>
using namespace std;
struct node
{
int val;
@@ -18,30 +17,27 @@ struct queue
queue q;
void enqueue(node *n)
{
q.t[q.rear++]=n;
q.t[q.rear++] = n;
}
node * dequeue()
node *dequeue()
{
return (q.t[q.front++]);
}
void Insert(node *n, int x)
{
if (x<n->val)
if (x < n->val)
{
if (n->left==NULL)
if (n->left == NULL)
{
node *temp=new node;
temp->val=x;
temp->left=NULL;
temp->right=NULL;
n->left=temp;
node *temp = new node;
temp->val = x;
temp->left = NULL;
temp->right = NULL;
n->left = temp;
}
else
{
@@ -50,13 +46,13 @@ void Insert(node *n, int x)
}
else
{
if (n->right==NULL)
if (n->right == NULL)
{
node *temp=new node;
temp->val=x;
temp->left=NULL;
temp->right=NULL;
n->left=temp;
node *temp = new node;
temp->val = x;
temp->left = NULL;
temp->right = NULL;
n->left = temp;
}
else
{
@@ -65,63 +61,60 @@ void Insert(node *n, int x)
}
}
int findMaxInLeftST(node *n)
{
while(n->right!=NULL)
while (n->right != NULL)
{
n=n->right;
n = n->right;
}
return n->val;
}
void Remove(node *p, node *n, int x)
{
if (n->val==x)
if (n->val == x)
{
if (n->right==NULL && n->left==NULL)
if (n->right == NULL && n->left == NULL)
{
if (x<p->val)
if (x < p->val)
{
p->right=NULL;
p->right = NULL;
}
else
{
p->left=NULL;
}
}
else if (n->right==NULL)
{
if (x<p->val)
{
p->right=n->left;
}
else
{
p->left=n->left;
p->left = NULL;
}
}
else if (n->left==NULL)
else if (n->right == NULL)
{
if (x<p->val)
if (x < p->val)
{
p->right=n->right;
p->right = n->left;
}
else
{
p->left=n->right;
p->left = n->left;
}
}
else if (n->left == NULL)
{
if (x < p->val)
{
p->right = n->right;
}
else
{
p->left = n->right;
}
}
else
{
int y=findMaxInLeftST(n->left);
n->val=y;
int y = findMaxInLeftST(n->left);
n->val = y;
Remove(n, n->right, y);
}
}
else if (x<n->val)
else if (x < n->val)
{
Remove(n, n->left, x);
}
@@ -131,14 +124,11 @@ void Remove(node *p, node *n, int x)
}
}
void BFT(node *n)
{
if(n!=NULL)
if (n != NULL)
{
cout<<n->val<<" ";
cout << n->val << " ";
enqueue(n->left);
enqueue(n->right);
BFT(dequeue());
@@ -147,9 +137,9 @@ void BFT(node *n)
void Pre(node *n)
{
if (n!=NULL)
if (n != NULL)
{
cout<<n->val<<" ";
cout << n->val << " ";
Pre(n->left);
Pre(n->right);
}
@@ -157,76 +147,72 @@ void Pre(node *n)
void In(node *n)
{
if (n!=NULL)
if (n != NULL)
{
In(n->left);
cout<<n->val<<" ";
cout << n->val << " ";
In(n->right);
}
}
void Post(node *n)
{
if (n!=NULL)
if (n != NULL)
{
Post(n->left);
Post(n->right);
cout<<n->val<<" ";
cout << n->val << " ";
}
}
int main()
{
q.front=0;
q.rear=0;
q.front = 0;
q.rear = 0;
int value;
int ch;
node *root=new node;
cout<<"\nEnter the value of root node :";
cin>>value;
root->val=value;
root->left=NULL;
root->right=NULL;
node *root = new node;
cout << "\nEnter the value of root node :";
cin >> value;
root->val = value;
root->left = NULL;
root->right = NULL;
do
{
cout<<"\n1. Insert";
cout<<"\n2. Delete";
cout<<"\n3. Breadth First";
cout<<"\n4. Preorder Depth First";
cout<<"\n5. Inorder Depth First";
cout<<"\n6. Postorder Depth First";
cout << "\n1. Insert";
cout << "\n2. Delete";
cout << "\n3. Breadth First";
cout << "\n4. Preorder Depth First";
cout << "\n5. Inorder Depth First";
cout << "\n6. Postorder Depth First";
cout<<"\nEnter Your Choice : ";
cin>>ch;
cout << "\nEnter Your Choice : ";
cin >> ch;
int x;
switch(ch)
switch (ch)
{
case 1:
cout<<"\nEnter the value to be Inserted : ";
cin>>x;
Insert(root, x);
break;
case 2:
cout<<"\nEnter the value to be Deleted : ";
cin>>x;
Remove(root, root, x);
break;
case 3:
BFT(root);
break;
case 4:
Pre(root);
break;
case 5:
In(root);
break;
case 6:
Post(root);
break;
case 1:
cout << "\nEnter the value to be Inserted : ";
cin >> x;
Insert(root, x);
break;
case 2:
cout << "\nEnter the value to be Deleted : ";
cin >> x;
Remove(root, root, x);
break;
case 3:
BFT(root);
break;
case 4:
Pre(root);
break;
case 5:
In(root);
break;
case 6:
Post(root);
break;
}
}
while(ch!=0);
} while (ch != 0);
}

View File

@@ -1,159 +1,158 @@
// A C++ program to demonstrate common Binary Heap Operations
#include<iostream>
#include<climits>
using namespace std;
// Prototype of a utility function to swap two integers
void swap(int *x, int *y);
// A class for Min Heap
class MinHeap
{
int *harr; // pointer to array of elements in heap
int capacity; // maximum possible size of min heap
int heap_size; // Current number of elements in min heap
public:
// Constructor
MinHeap(int capacity);
// to heapify a subtree with the root at given index
void MinHeapify(int );
int parent(int i) { return (i-1)/2; }
// to get index of left child of node at index i
int left(int i) { return (2*i + 1); }
// to get index of right child of node at index i
int right(int i) { return (2*i + 2); }
// to extract the root which is the minimum element
int extractMin();
// Decreases key value of key at index i to new_val
void decreaseKey(int i, int new_val);
// Returns the minimum key (key at root) from min heap
int getMin() { return harr[0]; }
// Deletes a key stored at index i
void deleteKey(int i);
// Inserts a new key 'k'
void insertKey(int k);
};
// Constructor: Builds a heap from a given array a[] of given size
MinHeap::MinHeap(int cap)
{
heap_size = 0;
capacity = cap;
harr = new int[cap];
}
// Inserts a new key 'k'
void MinHeap::insertKey(int k)
{
if (heap_size == capacity)
{
cout << "\nOverflow: Could not insertKey\n";
return;
}
// First insert the new key at the end
heap_size++;
int i = heap_size - 1;
harr[i] = k;
// Fix the min heap property if it is violated
while (i != 0 && harr[parent(i)] > harr[i])
{
swap(&harr[i], &harr[parent(i)]);
i = parent(i);
}
}
// Decreases value of key at index 'i' to new_val. It is assumed that
// new_val is smaller than harr[i].
void MinHeap::decreaseKey(int i, int new_val)
{
harr[i] = new_val;
while (i != 0 && harr[parent(i)] > harr[i])
{
swap(&harr[i], &harr[parent(i)]);
i = parent(i);
}
}
// Method to remove minimum element (or root) from min heap
int MinHeap::extractMin()
{
if (heap_size <= 0)
return INT_MAX;
if (heap_size == 1)
{
heap_size--;
return harr[0];
}
// Store the minimum value, and remove it from heap
int root = harr[0];
harr[0] = harr[heap_size-1];
heap_size--;
MinHeapify(0);
return root;
}
// This function deletes key at index i. It first reduced value to minus
// infinite, then calls extractMin()
void MinHeap::deleteKey(int i)
{
decreaseKey(i, INT_MIN);
extractMin();
}
// A recursive method to heapify a subtree with the root at given index
// This method assumes that the subtrees are already heapified
void MinHeap::MinHeapify(int i)
{
int l = left(i);
int r = right(i);
int smallest = i;
if (l < heap_size && harr[l] < harr[i])
smallest = l;
if (r < heap_size && harr[r] < harr[smallest])
smallest = r;
if (smallest != i)
{
swap(&harr[i], &harr[smallest]);
MinHeapify(smallest);
}
}
// A utility function to swap two elements
void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
// Driver program to test above functions
int main()
{
MinHeap h(11);
h.insertKey(3);
h.insertKey(2);
h.deleteKey(1);
h.insertKey(15);
h.insertKey(5);
h.insertKey(4);
h.insertKey(45);
cout << h.extractMin() << " ";
cout << h.getMin() << " ";
h.decreaseKey(2, 1);
cout << h.getMin();
return 0;
}
// A C++ program to demonstrate common Binary Heap Operations
#include <iostream>
#include <climits>
using namespace std;
// Prototype of a utility function to swap two integers
void swap(int *x, int *y);
// A class for Min Heap
class MinHeap
{
int *harr; // pointer to array of elements in heap
int capacity; // maximum possible size of min heap
int heap_size; // Current number of elements in min heap
public:
// Constructor
MinHeap(int capacity);
// to heapify a subtree with the root at given index
void MinHeapify(int);
int parent(int i) { return (i - 1) / 2; }
// to get index of left child of node at index i
int left(int i) { return (2 * i + 1); }
// to get index of right child of node at index i
int right(int i) { return (2 * i + 2); }
// to extract the root which is the minimum element
int extractMin();
// Decreases key value of key at index i to new_val
void decreaseKey(int i, int new_val);
// Returns the minimum key (key at root) from min heap
int getMin() { return harr[0]; }
// Deletes a key stored at index i
void deleteKey(int i);
// Inserts a new key 'k'
void insertKey(int k);
};
// Constructor: Builds a heap from a given array a[] of given size
MinHeap::MinHeap(int cap)
{
heap_size = 0;
capacity = cap;
harr = new int[cap];
}
// Inserts a new key 'k'
void MinHeap::insertKey(int k)
{
if (heap_size == capacity)
{
cout << "\nOverflow: Could not insertKey\n";
return;
}
// First insert the new key at the end
heap_size++;
int i = heap_size - 1;
harr[i] = k;
// Fix the min heap property if it is violated
while (i != 0 && harr[parent(i)] > harr[i])
{
swap(&harr[i], &harr[parent(i)]);
i = parent(i);
}
}
// Decreases value of key at index 'i' to new_val. It is assumed that
// new_val is smaller than harr[i].
void MinHeap::decreaseKey(int i, int new_val)
{
harr[i] = new_val;
while (i != 0 && harr[parent(i)] > harr[i])
{
swap(&harr[i], &harr[parent(i)]);
i = parent(i);
}
}
// Method to remove minimum element (or root) from min heap
int MinHeap::extractMin()
{
if (heap_size <= 0)
return INT_MAX;
if (heap_size == 1)
{
heap_size--;
return harr[0];
}
// Store the minimum value, and remove it from heap
int root = harr[0];
harr[0] = harr[heap_size - 1];
heap_size--;
MinHeapify(0);
return root;
}
// This function deletes key at index i. It first reduced value to minus
// infinite, then calls extractMin()
void MinHeap::deleteKey(int i)
{
decreaseKey(i, INT_MIN);
extractMin();
}
// A recursive method to heapify a subtree with the root at given index
// This method assumes that the subtrees are already heapified
void MinHeap::MinHeapify(int i)
{
int l = left(i);
int r = right(i);
int smallest = i;
if (l < heap_size && harr[l] < harr[i])
smallest = l;
if (r < heap_size && harr[r] < harr[smallest])
smallest = r;
if (smallest != i)
{
swap(&harr[i], &harr[smallest]);
MinHeapify(smallest);
}
}
// A utility function to swap two elements
void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
// Driver program to test above functions
int main()
{
MinHeap h(11);
h.insertKey(3);
h.insertKey(2);
h.deleteKey(1);
h.insertKey(15);
h.insertKey(5);
h.insertKey(4);
h.insertKey(45);
cout << h.extractMin() << " ";
cout << h.getMin() << " ";
h.decreaseKey(2, 1);
cout << h.getMin();
return 0;
}

View File

@@ -1,4 +1,4 @@
#include<iostream>
#include <iostream>
using namespace std;
struct node
@@ -12,83 +12,82 @@ node *start;
void insert(int x)
{
node *t=start;
if (start!=NULL)
node *t = start;
if (start != NULL)
{
while(t->next!=NULL)
while (t->next != NULL)
{
t=t->next;
t = t->next;
}
node *n= new node;
t->next=n;
n->prev=t;
n->val=x;
n->next=NULL;
node *n = new node;
t->next = n;
n->prev = t;
n->val = x;
n->next = NULL;
}
else
{
node *n= new node;
n->val=x;
n->prev=NULL;
n->next=NULL;
start=n;
node *n = new node;
n->val = x;
n->prev = NULL;
n->next = NULL;
start = n;
}
}
void remove(int x)
{
node *t=start;
while(t->val!=x)
node *t = start;
while (t->val != x)
{
t=t->next;
t = t->next;
}
t->prev->next=t->next;
t->next->prev=t->prev;
t->prev->next = t->next;
t->next->prev = t->prev;
delete t;
}
void search(int x)
{
node *t= start;
int found =0;
while(t!=NULL)
node *t = start;
int found = 0;
while (t != NULL)
{
if(t->val==x)
if (t->val == x)
{
cout<<"\nFound";
found=1;
cout << "\nFound";
found = 1;
break;
}
t=t->next;
t = t->next;
}
if(found==0)
if (found == 0)
{
cout<<"\nNot Found";
cout << "\nNot Found";
}
}
void show()
{
node *t=start;
while(t!=NULL)
node *t = start;
while (t != NULL)
{
cout<<t->val<<"\t";
t=t->next;
cout << t->val << "\t";
t = t->next;
}
}
void reverseShow()
{
node *t=start;
while(t->next!=NULL)
node *t = start;
while (t->next != NULL)
{
t=t->next;
t = t->next;
}
while(t!=NULL)
while (t != NULL)
{
cout<<t->val<<"\t";
t=t->prev;
cout << t->val << "\t";
t = t->prev;
}
}
@@ -97,29 +96,39 @@ int main()
int choice, x;
do
{
cout<<"\n1. Insert";
cout<<"\n2. Delete";
cout<<"\n3. Search";
cout<<"\n4. Forward print";
cout<<"\n5. Reverse print";
cout<<"\n\nEnter you choice : ";
cin>>choice;
cout << "\n1. Insert";
cout << "\n2. Delete";
cout << "\n3. Search";
cout << "\n4. Forward print";
cout << "\n5. Reverse print";
cout << "\n\nEnter you choice : ";
cin >> choice;
switch (choice)
{
case 1 : cout<<"\nEnter the element to be inserted : ";
cin>>x;;
insert(x); break;
case 2 : cout<<"\nEnter the element to be removed : ";
cin>>x;
remove(x); break;
case 3 : cout<<"\nEnter the element to be searched : ";
cin>>x;
search(x); break;
case 4 : show(); break;
case 5 : reverseShow(); break;
case 1:
cout << "\nEnter the element to be inserted : ";
cin >> x;
;
insert(x);
break;
case 2:
cout << "\nEnter the element to be removed : ";
cin >> x;
remove(x);
break;
case 3:
cout << "\nEnter the element to be searched : ";
cin >> x;
search(x);
break;
case 4:
show();
break;
case 5:
reverseShow();
break;
}
}
while(choice!=0);
} while (choice != 0);
return 0;
}

View File

@@ -1,4 +1,4 @@
#include<iostream>
#include <iostream>
using namespace std;
struct node
@@ -11,50 +11,56 @@ node *start;
void insert(int x)
{
node *t=start;
if (start!=NULL)
node *t = start;
if (start != NULL)
{
while(t->next!=NULL)
while (t->next != NULL)
{
t=t->next;
t = t->next;
}
node *n= new node;
t->next=n;
n->val=x;
n->next=NULL;
node *n = new node;
t->next = n;
n->val = x;
n->next = NULL;
}
else
{
node *n= new node;
n->val=x;
n->next=NULL;
start=n;
node *n = new node;
n->val = x;
n->next = NULL;
start = n;
}
}
void remove(int x){
void remove(int x)
{
if( start == NULL ){
cout<<"\nLinked List is empty\n";
return ;
if (start == NULL)
{
cout << "\nLinked List is empty\n";
return;
}
else if( start->val == x ){
else if (start->val == x)
{
node *temp = start;
start = start->next;
delete temp;
return ;
return;
}
node *temp = start, *parent = start;
while( temp != NULL && temp->val != x ){
while (temp != NULL && temp->val != x)
{
parent = temp;
temp = temp->next;
}
if( temp == NULL ){
cout <<endl <<x <<" not found in list\n";
return ;
if (temp == NULL)
{
cout << endl
<< x << " not found in list\n";
return;
}
parent->next = temp->next;
@@ -63,47 +69,48 @@ void remove(int x){
void search(int x)
{
node *t= start;
int found =0;
while(t!=NULL)
node *t = start;
int found = 0;
while (t != NULL)
{
if(t->val==x)
if (t->val == x)
{
cout<<"\nFound";
found=1;
cout << "\nFound";
found = 1;
break;
}
t=t->next;
t = t->next;
}
if(found==0)
if (found == 0)
{
cout<<"\nNot Found";
cout << "\nNot Found";
}
}
void show()
{
node *t=start;
while(t!=NULL)
node *t = start;
while (t != NULL)
{
cout<<t->val<<"\t";
t=t->next;
cout << t->val << "\t";
t = t->next;
}
}
void reverse(){
node* first = start;
node* second = first->next;
while(second != NULL){
node* tem = second->next;
second->next = first;
first = second;
second = tem;
}
void reverse()
{
node *first = start;
node *second = first->next;
while (second != NULL)
{
node *tem = second->next;
second->next = first;
first = second;
second = tem;
}
start->next = NULL;
start = first;
start->next = NULL;
start = first;
}
int main()
@@ -111,33 +118,44 @@ int main()
int choice, x;
do
{
cout<<"\n1. Insert";
cout<<"\n2. Delete";
cout<<"\n3. Search";
cout<<"\n4. Print";
cout<<"\n5. Reverse";
cout<<"\n0. Exit";
cout<<"\n\nEnter you choice : ";
cin>>choice;
cout << "\n1. Insert";
cout << "\n2. Delete";
cout << "\n3. Search";
cout << "\n4. Print";
cout << "\n5. Reverse";
cout << "\n0. Exit";
cout << "\n\nEnter you choice : ";
cin >> choice;
switch (choice)
{
case 1 : cout<<"\nEnter the element to be inserted : ";
cin>>x;;
insert(x); break;
case 2 : cout<<"\nEnter the element to be removed : ";
cin>>x;
remove(x); break;
case 3 : cout<<"\nEnter the element to be searched : ";
cin>>x;
search(x); break;
case 4 : show();
cout<<"\n"; break;
case 5 : cout<<"The reversed list: \n";
reverse(); show();
cout<<"\n"; break;
case 1:
cout << "\nEnter the element to be inserted : ";
cin >> x;
;
insert(x);
break;
case 2:
cout << "\nEnter the element to be removed : ";
cin >> x;
remove(x);
break;
case 3:
cout << "\nEnter the element to be searched : ";
cin >> x;
search(x);
break;
case 4:
show();
cout << "\n";
break;
case 5:
cout << "The reversed list: \n";
reverse();
show();
cout << "\n";
break;
}
}
while(choice!=0);
} while (choice != 0);
return 0;
}

View File

@@ -1,32 +1,32 @@
#include<iostream>
#include <iostream>
using namespace std;
struct list
{
int data[50];
int top=0;
bool isSorted=false;
int top = 0;
bool isSorted = false;
int BinarySearch(int *array, int first, int last, int x)
{
if(last<first)
if (last < first)
{
return -1;
}
int mid=(first+last)/2;
if(array[mid]==x)
int mid = (first + last) / 2;
if (array[mid] == x)
return mid;
else if(x<array[mid])
return (BinarySearch(array, first, mid-1, x));
else if(x>array[mid])
return (BinarySearch(array, mid+1, last, x));
else if (x < array[mid])
return (BinarySearch(array, first, mid - 1, x));
else if (x > array[mid])
return (BinarySearch(array, mid + 1, last, x));
}
int LinarSearch(int *array, int x)
{
for (int i = 0; i < top; i++)
{
if (array[i]==x)
if (array[i] == x)
{
return i;
}
@@ -37,102 +37,101 @@ struct list
int Search(int x)
{
int pos=-1;
int pos = -1;
if (isSorted)
{
pos=BinarySearch(data, 0, top-1, x);
pos = BinarySearch(data, 0, top - 1, x);
}
else
{
pos=LinarSearch(data, x);
pos = LinarSearch(data, x);
}
if (pos!=-1)
if (pos != -1)
{
cout<<"\nElement found at position : "<<pos;
cout << "\nElement found at position : " << pos;
}
else
{
cout<<"\nElement not found";
cout << "\nElement not found";
}
return pos;
}
void Sort()
{
int i, j, pos;
for(i=0; i<top; i++)
for (i = 0; i < top; i++)
{
int min=data[i];
for(j=i+1; j<top; j++)
int min = data[i];
for (j = i + 1; j < top; j++)
{
if(data[j]<min)
if (data[j] < min)
{
pos=j;
min=data[pos];
pos = j;
min = data[pos];
}
}
int temp=data[i];
data[i]=data[pos];
data[pos]=temp;
int temp = data[i];
data[i] = data[pos];
data[pos] = temp;
}
isSorted=true;
isSorted = true;
}
void insert(int x)
{
if(!isSorted)
if (!isSorted)
{
if(top==49)
if (top == 49)
{
cout<<"\nOverflow";
cout << "\nOverflow";
}
else
{
data[top]=x;
data[top] = x;
top++;
}
}
else
{
int pos=0;
for (int i = 0; i < top-1; i++)
int pos = 0;
for (int i = 0; i < top - 1; i++)
{
if(data[i]<=x && x<=data[i+1])
if (data[i] <= x && x <= data[i + 1])
{
pos=i+1;
pos = i + 1;
break;
}
}
if (pos==0)
if (pos == 0)
{
pos=top-1;
pos = top - 1;
}
for (int i = top; i > pos; i--)
{
data[i]=data[i-1];
data[i] = data[i - 1];
}
top++;
data[pos]=x;
data[pos] = x;
}
}
void Remove(int x)
{
int pos=Search(x);
cout<<"\n"<<data[pos]<<" deleted";
int pos = Search(x);
cout << "\n"
<< data[pos] << " deleted";
for (int i = pos; i < top; i++)
{
data[i]=data[i+1];
data[i] = data[i + 1];
}
top--;
}
@@ -141,7 +140,7 @@ struct list
{
for (int i = 0; i < top; i++)
{
cout<<data[i]<<"\t";
cout << data[i] << "\t";
}
}
};
@@ -152,34 +151,38 @@ int main()
int choice;
int x;
do
{
cout<<"\n1.Insert";
cout<<"\n2.Delete";
cout<<"\n3.Search";
cout<<"\n4.Sort";
cout<<"\n5.Print";
cout<<"\n\nEnter Your Choice : ";
cin>>choice;
{
cout << "\n1.Insert";
cout << "\n2.Delete";
cout << "\n3.Search";
cout << "\n4.Sort";
cout << "\n5.Print";
cout << "\n\nEnter Your Choice : ";
cin >> choice;
switch (choice)
{
case 1: cout<<"\nEnter the element to be inserted : ";
cin>>x;
L.insert(x);
break;
case 2: cout<<"\nEnter the element to be removed : ";
cin>>x;
L.Remove(x);
break;
case 3: cout<<"\nEnter the element to be searched : ";
cin>>x;
L.Search(x);
break;
case 4: L.Sort();
break;
case 5: L.Show();
break;
case 1:
cout << "\nEnter the element to be inserted : ";
cin >> x;
L.insert(x);
break;
case 2:
cout << "\nEnter the element to be removed : ";
cin >> x;
L.Remove(x);
break;
case 3:
cout << "\nEnter the element to be searched : ";
cin >> x;
L.Search(x);
break;
case 4:
L.Sort();
break;
case 5:
L.Show();
break;
}
}
while(choice!=0);
} while (choice != 0);
return 0;
}

View File

@@ -7,73 +7,86 @@
using namespace std;
struct Btree {
struct Btree
{
int data;
struct Btree* left; //Pointer to left subtree
struct Btree* right; //Pointer to right subtree
struct Btree *left; //Pointer to left subtree
struct Btree *right; //Pointer to right subtree
};
void insert(Btree **root, int d) {
Btree *nn = new Btree(); //Creating new node
void insert(Btree **root, int d)
{
Btree *nn = new Btree(); //Creating new node
nn->data = d;
nn->left = NULL;
nn->right = NULL;
if(*root == NULL) {
if (*root == NULL)
{
*root = nn;
return;
}
else {
queue<Btree*> q;
else
{
queue<Btree *> q;
// Adding root node to queue
q.push(*root);
while(!q.empty()) {
while (!q.empty())
{
Btree *node = q.front();
// Removing parent node from queue
q.pop();
if(node->left)
if (node->left)
// Adding left child of removed node to queue
q.push(node->left);
else {
else
{
// Adding new node if no left child is present
node->left = nn;
return;
}
if(node->right)
if (node->right)
// Adding right child of removed node to queue
q.push(node->right);
else {
else
{
// Adding new node if no right child is present
node->right = nn;
return;
}
}
}
}
}
void morrisInorder(Btree *root) {
void morrisInorder(Btree *root)
{
Btree *curr = root;
Btree *temp;
while(curr) {
if(curr->left==NULL) {
cout<<curr->data<<" ";
while (curr)
{
if (curr->left == NULL)
{
cout << curr->data << " ";
// If left of current node is NULL then curr is shifted to right
curr = curr->right;
}
else {
else
{
// Left of current node is stored in temp
temp = curr->left;
// Moving to extreme right of temp
while(temp->right&&temp->right!=curr)
while (temp->right && temp->right != curr)
temp = temp->right;
// If extreme right is null it is made to point to currrent node (will be used for backtracking)
if(temp->right == NULL) {
if (temp->right == NULL)
{
temp->right = curr;
// current node is made to point its left subtree
curr = curr->left;
}
// If extreme right already points to currrent node it it set to null
else if(temp->right == curr) {
cout<<curr->data<<" ";
else if (temp->right == curr)
{
cout << curr->data << " ";
temp->right = NULL;
// current node is made to point its right subtree
curr = curr->right;
@@ -82,13 +95,14 @@ void morrisInorder(Btree *root) {
}
}
int main() {
int main()
{
// Testing morrisInorder funtion
Btree *root = NULL;
int i;
for(i = 1 ; i <= 7 ; i++)
for (i = 1; i <= 7; i++)
insert(&root, i);
cout<<"Morris Inorder: ";
cout << "Morris Inorder: ";
morrisInorder(root);
return 0;
}

View File

@@ -1,48 +1,47 @@
#include<iostream>
#include <iostream>
using namespace std;
int queue[10];
int front=0;
int rear=0;
int front = 0;
int rear = 0;
void Enque(int x)
{
if(rear==10)
if (rear == 10)
{
cout<<"\nOverflow";
cout << "\nOverflow";
}
else
{
queue[rear++]=x;
queue[rear++] = x;
}
}
void Deque()
{
if (front==rear)
if (front == rear)
{
cout<<"\nUnderflow";
cout << "\nUnderflow";
}
else
{
cout<<"\n"<<queue[front++]<<" deleted";
cout << "\n"
<< queue[front++] << " deleted";
for (int i = front; i < rear; i++)
{
queue[i-front]=queue[i];
queue[i - front] = queue[i];
}
rear=rear-front;
front=0;
rear = rear - front;
front = 0;
}
}
void show()
{
for (int i = front; i < rear; i++)
{
cout<<queue[i]<<"\t";
cout << queue[i] << "\t";
}
}
@@ -51,28 +50,26 @@ int main()
int ch, x;
do
{
cout<<"\n1. Enque";
cout<<"\n2. Deque";
cout<<"\n3. Print";
cout<<"\nEnter Your Choice : ";
cin>>ch;
if (ch==1)
cout << "\n1. Enque";
cout << "\n2. Deque";
cout << "\n3. Print";
cout << "\nEnter Your Choice : ";
cin >> ch;
if (ch == 1)
{
cout<<"\nInsert : ";
cin>>x;
cout << "\nInsert : ";
cin >> x;
Enque(x);
}
else if (ch==2)
else if (ch == 2)
{
Deque();
}
else if (ch==3)
else if (ch == 3)
{
show();
}
}
while(ch!=0);
} while (ch != 0);
return 0;
}

View File

@@ -1,90 +1,89 @@
#include<iostream>
#include <iostream>
using namespace std;
struct node
{
int val;
node *next;
int val;
node *next;
};
node *front, *rear;
void Enque(int x)
{
if (rear==NULL)
{
node *n= new node;
n->val=x;
n->next=NULL;
rear=n;
front=n;
}
if (rear == NULL)
{
node *n = new node;
n->val = x;
n->next = NULL;
rear = n;
front = n;
}
else
{
else
{
node *n = new node;
n->val=x;
n->next=NULL;
rear->next=n;
rear=n;
}
node *n = new node;
n->val = x;
n->next = NULL;
rear->next = n;
rear = n;
}
}
void Deque()
{
if (rear==front)
{
cout<<"\nUnderflow";
}
else
{
node *t = front;
cout<<"\n"<<t->val<<" deleted";
front=front->next;
delete t;
}
if (rear == NULL && front == NULL)
{
cout << "\nUnderflow";
}
else
{
node *t = front;
cout << "\n"
<< t->val << " deleted";
front = front->next;
delete t;
if (front == NULL)
rear = NULL;
}
}
void show()
{
node *t=front;
while(t!=NULL)
{
cout<<t->val<<"\t";
t=t->next;
}
node *t = front;
while (t != NULL)
{
cout << t->val << "\t";
t = t->next;
}
}
int main()
{
int ch, x;
do
{
cout<<"\n1. Enque";
cout<<"\n2. Deque";
cout<<"\n3. Print";
cout<<"\nEnter Your Choice : ";
cin>>ch;
if (ch==1)
{
cout<<"\nInsert : ";
cin>>x;
Enque(x);
}
else if (ch==2)
{
Deque();
}
else if (ch==3)
{
show();
}
}
while(ch!=0);
int ch, x;
do
{
cout << "\n1. Enque";
cout << "\n2. Deque";
cout << "\n3. Print";
cout << "\nEnter Your Choice : ";
cin >> ch;
if (ch == 1)
{
cout << "\nInsert : ";
cin >> x;
Enque(x);
}
else if (ch == 2)
{
Deque();
}
else if (ch == 3)
{
show();
}
} while (ch != 0);
return 0;
return 0;
}

View File

@@ -1,30 +1,31 @@
#include<iostream>
#include <iostream>
using namespace std;
int *stack;
int top=0, size;
int top = 0, size;
void push(int x)
{
if(top==size)
if (top == size)
{
cout<<"\nOverflow";
cout << "\nOverflow";
}
else
{
stack[top++]=x;
stack[top++] = x;
}
}
void pop()
{
if (top==0)
if (top == 0)
{
cout<<"\nUnderflow";
cout << "\nUnderflow";
}
else
{
cout<<"\n"<<stack[--top]<<" deleted";
cout << "\n"
<< stack[--top] << " deleted";
}
}
@@ -32,49 +33,47 @@ void show()
{
for (int i = 0; i < top; i++)
{
cout<<stack[i]<<"\n";
cout << stack[i] << "\n";
}
}
void topmost()
{
cout << "\nTopmost element: "<<stack[top-1];
cout << "\nTopmost element: " << stack[top - 1];
}
int main()
{
cout<<"\nEnter Size of stack : ";
cin>>size;
cout << "\nEnter Size of stack : ";
cin >> size;
stack = new int[size];
int ch, x;
do
{
cout<<"\n1. Push";
cout<<"\n2. Pop";
cout<<"\n3. Print";
cout<<"\n4. Print topmost element:";
cout<<"\nEnter Your Choice : ";
cin>>ch;
if (ch==1)
cout << "\n1. Push";
cout << "\n2. Pop";
cout << "\n3. Print";
cout << "\n4. Print topmost element:";
cout << "\nEnter Your Choice : ";
cin >> ch;
if (ch == 1)
{
cout<<"\nInsert : ";
cin>>x;
cout << "\nInsert : ";
cin >> x;
push(x);
}
else if (ch==2)
else if (ch == 2)
{
pop();
}
else if (ch==3)
else if (ch == 3)
{
show();
}
else if(ch==4)
{
topmost();
}
}
while(ch!=0);
else if (ch == 4)
{
topmost();
}
} while (ch != 0);
return 0;
}

View File

@@ -1,4 +1,4 @@
#include<iostream>
#include <iostream>
using namespace std;
struct node
@@ -7,39 +7,39 @@ struct node
node *next;
};
node *top;
void push(int x)
{
node *n = new node;
n->val=x;
n->next=top;
top=n;
n->val = x;
n->next = top;
top = n;
}
void pop()
{
if (top==NULL)
if (top == NULL)
{
cout<<"\nUnderflow";
cout << "\nUnderflow";
}
else
{
node *t = top;
cout<<"\n"<<t->val<<" deleted";
top=top->next;
cout << "\n"
<< t->val << " deleted";
top = top->next;
delete t;
}
}
void show()
{
node *t=top;
while(t!=NULL)
node *t = top;
while (t != NULL)
{
cout<<t->val<<"\n";
t=t->next;
cout << t->val << "\n";
t = t->next;
}
}
@@ -48,28 +48,26 @@ int main()
int ch, x;
do
{
cout<<"\n1. Push";
cout<<"\n2. Pop";
cout<<"\n3. Print";
cout<<"\nEnter Your Choice : ";
cin>>ch;
if (ch==1)
cout << "\n1. Push";
cout << "\n2. Pop";
cout << "\n3. Print";
cout << "\nEnter Your Choice : ";
cin >> ch;
if (ch == 1)
{
cout<<"\nInsert : ";
cin>>x;
cout << "\nInsert : ";
cin >> x;
push(x);
}
else if (ch==2)
else if (ch == 2)
{
pop();
}
else if (ch==3)
else if (ch == 3)
{
show();
}
}
while(ch!=0);
} while (ch != 0);
return 0;
}

View File

@@ -1,47 +1,43 @@
#include<iostream>
#include <iostream>
#include <list>
using namespace std;
struct node
{
int val;
node *left;
node *right;
int val;
node *left;
node *right;
};
void CreateTree(node *curr, node *n, int x, char pos)
{
if(n!=NULL)
{
char ch;
cout<<"\nLeft or Right of "<<n->val<<" : ";
cin>>ch;
if(ch=='l')
CreateTree(n, n->left, x, ch);
else if(ch=='r')
CreateTree(n, n->right, x, ch);
}
else
{
node *t=new node;
t->val=x;
t->left=NULL;
t->right=NULL;
if (pos=='l')
{
curr->left=t;
}
else if(pos=='r')
{
curr->right=t;
}
}
if (n != NULL)
{
char ch;
cout << "\nLeft or Right of " << n->val << " : ";
cin >> ch;
if (ch == 'l')
CreateTree(n, n->left, x, ch);
else if (ch == 'r')
CreateTree(n, n->right, x, ch);
}
else
{
node *t = new node;
t->val = x;
t->left = NULL;
t->right = NULL;
if (pos == 'l')
{
curr->left = t;
}
else if (pos == 'r')
{
curr->right = t;
}
}
}
void BFT(node *n)
{
list<node*> queue;
@@ -63,84 +59,80 @@ void BFT(node *n)
void Pre(node *n)
{
if (n!=NULL)
{
cout<<n->val<<" ";
Pre(n->left);
Pre(n->right);
}
if (n != NULL)
{
cout << n->val << " ";
Pre(n->left);
Pre(n->right);
}
}
void In(node *n)
{
if (n!=NULL)
{
In(n->left);
cout<<n->val<<" ";
In(n->right);
}
if (n != NULL)
{
In(n->left);
cout << n->val << " ";
In(n->right);
}
}
void Post(node *n)
{
if (n!=NULL)
{
Post(n->left);
Post(n->right);
cout<<n->val<<" ";
}
if (n != NULL)
{
Post(n->left);
Post(n->right);
cout << n->val << " ";
}
}
int main()
{
int value;
int ch;
node *root=new node;
cout<<"\nEnter the value of root node :";
cin>>value;
root->val=value;
root->left=NULL;
root->right=NULL;
do
{
cout<<"\n1. Insert : ";
cout<<"\n2. Breadth First";
cout<<"\n3. Preorder Depth First";
cout<<"\n4. Inorder Depth First";
cout<<"\n5. Postorder Depth First";
int value;
int ch;
node *root = new node;
cout << "\nEnter the value of root node :";
cin >> value;
root->val = value;
root->left = NULL;
root->right = NULL;
do
{
cout << "\n1. Insert : ";
cout << "\n2. Breadth First";
cout << "\n3. Preorder Depth First";
cout << "\n4. Inorder Depth First";
cout << "\n5. Postorder Depth First";
cout<<"\nEnter Your Choice : ";
cin>>ch;
switch(ch)
{
case 1:
int x;
char pos;
cout<<"\nEnter the value to be Inserted : ";
cin>>x;
cout<<"\nLeft or Right of Root : ";
cin>>pos;
if(pos=='l')
CreateTree(root, root->left, x, pos);
else if(pos=='r')
CreateTree(root, root->right, x, pos);
break;
case 2:
BFT(root);
break;
case 3:
Pre(root);
break;
case 4:
In(root);
break;
case 5:
Post(root);
break;
}
}
while(ch!=0);
cout << "\nEnter Your Choice : ";
cin >> ch;
switch (ch)
{
case 1:
int x;
char pos;
cout << "\nEnter the value to be Inserted : ";
cin >> x;
cout << "\nLeft or Right of Root : ";
cin >> pos;
if (pos == 'l')
CreateTree(root, root->left, x, pos);
else if (pos == 'r')
CreateTree(root, root->right, x, pos);
break;
case 2:
BFT(root);
break;
case 3:
Pre(root);
break;
case 4:
In(root);
break;
case 5:
Post(root);
break;
}
} while (ch != 0);
}

View File

@@ -1,6 +1,6 @@
#include<iostream>
#include<string.h>
#include<stdbool.h>
#include <iostream>
#include <string.h>
#include <stdbool.h>
using namespace std;
// structure definition
typedef struct trie
@@ -8,7 +8,7 @@ typedef struct trie
struct trie *arr[26];
bool isEndofWord;
} trie;
// create a new node for trie
// create a new node for trie
trie *createNode()
{
trie *nn = new trie();
@@ -18,8 +18,8 @@ trie *createNode()
return nn;
}
// insert string into the trie
void insert(trie *root, char* str)
// insert string into the trie
void insert(trie *root, char *str)
{
for (int i = 0; i < strlen(str); i++)
{
@@ -38,7 +38,7 @@ void insert(trie *root, char* str)
}
// search a string exists inside the trie
bool search(trie *root, char* str, int index)
bool search(trie *root, char *str, int index)
{
if (index == strlen(str))
{
@@ -54,7 +54,7 @@ bool search(trie *root, char* str, int index)
/* removes the string if it is not a prefix of any other
string, if it is then just sets the endofword to false, else
removes the given string*/
bool deleteString (trie *root, char* str, int index)
bool deleteString(trie *root, char *str, int index)
{
if (index == strlen(str))
{
@@ -68,7 +68,7 @@ bool deleteString (trie *root, char* str, int index)
int j = str[index] - 'a';
if (!root->arr[j])
return false;
bool var = deleteString (root, str, index + 1);
bool var = deleteString(root, str, index + 1);
if (var)
{
root->arr[j] = NULL;

View File

@@ -1,36 +1,44 @@
#include<iostream>
#include <iostream>
using namespace std;
struct node{
struct node
{
int data;
struct node *next;
};
class Queue{
class Queue
{
node *front;
node *rear;
public:
Queue(){
Queue()
{
front = NULL;
rear = NULL;
}
void createNode(int val){
void createNode(int val)
{
node *ptr;
node *nn;
nn = new node;
ptr = front;
nn->data = val;
nn->next = NULL;
front=nn;
rear=nn;
front = nn;
rear = nn;
}
void enqueue(int val){
if(front==NULL || rear==NULL){
void enqueue(int val)
{
if (front == NULL || rear == NULL)
{
createNode(val);
}
else{
else
{
node *ptr;
node *nn;
ptr=front;
ptr = front;
nn = new node;
nn->data = val;
rear->next = nn;
@@ -38,24 +46,28 @@ public:
rear = nn;
}
}
void dequeue(){
void dequeue()
{
node *n;
n = front;
front = front->next;
delete(n);
delete (n);
}
void traverse(){
void traverse()
{
node *ptr;
ptr=front;
do{
cout<<ptr->data<<" ";
ptr=ptr->next;
}while(ptr!=rear->next);
cout<<front->data;
cout<<endl;
ptr = front;
do
{
cout << ptr->data << " ";
ptr = ptr->next;
} while (ptr != rear->next);
cout << front->data;
cout << endl;
}
};
int main(void){
int main(void)
{
Queue q;
q.enqueue(10);
q.enqueue(20);

View File

@@ -3,107 +3,104 @@
2. Limited size. (in the following case it is 100 nodes at max). But we can reuse the nodes that are to be deleted by again linking it bacj to the list.
*/
#include<iostream>
#include <iostream>
using namespace std;
struct Node{
struct Node
{
int data;
int next;
};
Node AvailArray[100]; //array that will act as nodes of a linked list.
int head=-1;
int avail=0;
Node AvailArray[100]; //array that will act as nodes of a linked list.
int head = -1;
int avail = 0;
void initialise_list()
{
for(int i=0;i<=98;i++)
for (int i = 0; i <= 98; i++)
{
AvailArray[i].next=i+1;
AvailArray[i].next = i + 1;
}
AvailArray[99].next=-1; //indicating the end of the linked list.
AvailArray[99].next = -1; //indicating the end of the linked list.
}
int getnode() //This will return the index of the first free node present in the avail list
int getnode() //This will return the index of the first free node present in the avail list
{
int NodeIndexToBeReturned=avail;
avail=AvailArray[avail].next;
int NodeIndexToBeReturned = avail;
avail = AvailArray[avail].next;
return NodeIndexToBeReturned;
}
void freeNode(int nodeToBeDeleted) //This function when called will delete the node with the index presented as an argument, and will put back that node into the array.
void freeNode(int nodeToBeDeleted) //This function when called will delete the node with the index presented as an argument, and will put back that node into the array.
{
AvailArray[nodeToBeDeleted].next=avail;
avail=nodeToBeDeleted;
AvailArray[nodeToBeDeleted].next = avail;
avail = nodeToBeDeleted;
}
void insertAtTheBeginning(int data) //The function will insert the given data into the front of the linked list.
void insertAtTheBeginning(int data) //The function will insert the given data into the front of the linked list.
{
int newNode=getnode();
AvailArray[newNode].data=data;
AvailArray[newNode].next=head;
head=newNode;
int newNode = getnode();
AvailArray[newNode].data = data;
AvailArray[newNode].next = head;
head = newNode;
}
void insertAtTheEnd(int data)
{
int newNode=getnode();
int temp=head;
while(AvailArray[temp].next!=-1)
int newNode = getnode();
int temp = head;
while (AvailArray[temp].next != -1)
{
temp=AvailArray[temp].next;
temp = AvailArray[temp].next;
}
//temp is now pointing to the end node.
AvailArray[newNode].data=data;
AvailArray[newNode].next=-1;
AvailArray[temp].next=newNode;
AvailArray[newNode].data = data;
AvailArray[newNode].next = -1;
AvailArray[temp].next = newNode;
}
void display()
{
int temp=head;
while(temp!=-1)
int temp = head;
while (temp != -1)
{
cout<<AvailArray[temp].data<<"->";
temp=AvailArray[temp].next;
cout << AvailArray[temp].data << "->";
temp = AvailArray[temp].next;
}
cout<<"-1"<<endl;;
cout << "-1" << endl;
;
}
int main()
{ initialise_list();
int x,y,z;
for(;;)
{
initialise_list();
int x, y, z;
for (;;)
{
cout<<"1. Insert At The Beginning"<<endl;
cout<<"2. Insert At The End"<<endl;
cout<<"3. Display"<<endl;
cout<<"4.Exit"<<endl;
cout<<"Enter Your choice"<<endl;
cin>>z;
switch(z)
cout << "1. Insert At The Beginning" << endl;
cout << "2. Insert At The End" << endl;
cout << "3. Display" << endl;
cout << "4.Exit" << endl;
cout << "Enter Your choice" << endl;
cin >> z;
switch (z)
{
case 1:
cout<<"Enter the number you want to enter"<<endl;
cin>>x;
insertAtTheBeginning(x);
break;
case 2:
cout<<"Enter the number you want to enter"<<endl;
cin>>y;
insertAtTheEnd(y);
break;
case 3:
cout<<"The linked list contains the following element in order"<<endl;
display();
break;
case 4:
exit(0);
default:
cout<<"The entered choice is not correct"<<endl;
case 1:
cout << "Enter the number you want to enter" << endl;
cin >> x;
insertAtTheBeginning(x);
break;
case 2:
cout << "Enter the number you want to enter" << endl;
cin >> y;
insertAtTheEnd(y);
break;
case 3:
cout << "The linked list contains the following element in order" << endl;
display();
break;
case 4:
exit(0);
default:
cout << "The entered choice is not correct" << endl;
}
}
}

View File

@@ -1,6 +1,6 @@
//0-1 Knapsack problem - Dynamic programming
//#include <bits/stdc++.h>
#include<iostream>
#include <iostream>
using namespace std;
//void Print(int res[20][20], int i, int j, int capacity)
@@ -15,7 +15,7 @@ using namespace std;
// {
// cout<<i<<" ";
// }
//
//
// Print(res, i-1, j-1, capacity-i);
// }
// else if(res[i-1][j]>res[i][j-1])
@@ -28,43 +28,44 @@ using namespace std;
// }
//}
int Knapsack(int capacity,int n,int weight[],int value[]){
int Knapsack(int capacity, int n, int weight[], int value[])
{
int res[20][20];
for (int i = 0; i < n+1; ++i)
for (int i = 0; i < n + 1; ++i)
{
for (int j = 0; j < capacity+1; ++j)
for (int j = 0; j < capacity + 1; ++j)
{
if(i==0||j==0)
if (i == 0 || j == 0)
res[i][j] = 0;
else if(weight[i-1]<=j)
res[i][j] = max(value[i-1]+res[i-1][j-weight[i-1]], res[i-1][j]);
else if (weight[i - 1] <= j)
res[i][j] = max(value[i - 1] + res[i - 1][j - weight[i - 1]], res[i - 1][j]);
else
res[i][j] = res[i-1][j];
res[i][j] = res[i - 1][j];
}
}
// Print(res, n, capacity, capacity);
// cout<<"\n";
// Print(res, n, capacity, capacity);
// cout<<"\n";
return res[n][capacity];
}
int main()
{
int n;
cout<<"Enter number of items: ";
cin>>n;
cout << "Enter number of items: ";
cin >> n;
int weight[n], value[n];
cout<<"Enter weights: ";
cout << "Enter weights: ";
for (int i = 0; i < n; ++i)
{
cin>>weight[i];
cin >> weight[i];
}
cout<<"Enter values: ";
cout << "Enter values: ";
for (int i = 0; i < n; ++i)
{
cin>>value[i];
cin >> value[i];
}
int capacity;
cout<<"Enter capacity: ";
cin>>capacity;
cout<<Knapsack(capacity,n,weight,value);
cout << "Enter capacity: ";
cin >> capacity;
cout << Knapsack(capacity, n, weight, value);
return 0;
}

View File

@@ -1,20 +1,20 @@
//program to check whether a number is an armstrong number or not
#include<iostream.h>
#include<Math.h>
#include <iostream.h>
#include <Math.h>
int main()
{
int n,k,d,s=0;
cout<<"Enter a number:";
cin>>n;
k=n;
while(k!=0)
int n, k, d, s = 0;
cout << "Enter a number:";
cin >> n;
k = n;
while (k != 0)
{
d=k%10;
s+=(int)pow(d,3);
k/=10;
d = k % 10;
s += (int)pow(d, 3);
k /= 10;
}
if(s==n)
cout<<n<<"is an armstrong number";
if (s == n)
cout << n << "is an armstrong number";
else
cout<<n<<"is not an armstrong number";
cout << n << "is not an armstrong number";
}

View File

@@ -1,116 +1,128 @@
#include<iostream>
#include<limits.h>
#include <iostream>
#include <limits.h>
using namespace std;
//Wrapper class for storing an edge
class Edge{
public: int src,dst,weight;
class Edge
{
public:
int src, dst, weight;
};
//Wrapper class for storing a graph
class Graph{
public:
int vertexNum,edgeNum;
Edge* edges;
class Graph
{
public:
int vertexNum, edgeNum;
Edge *edges;
//Constructs a graph with V vertices and E edges
Graph(int V,int E){
Graph(int V, int E)
{
this->vertexNum = V;
this->edgeNum = E;
this->edges =(Edge*) malloc(E * sizeof(Edge));
this->edges = (Edge *)malloc(E * sizeof(Edge));
}
//Adds the given edge to the graph
void addEdge(int src, int dst, int weight){
//Adds the given edge to the graph
void addEdge(int src, int dst, int weight)
{
static int edgeInd = 0;
if(edgeInd < this->edgeNum){
if (edgeInd < this->edgeNum)
{
Edge newEdge;
newEdge.src = src;
newEdge.dst = dst;
newEdge.weight = weight;
this->edges[edgeInd++] = newEdge;
}
}
};
//Utility function to print distances
void print(int dist[], int V){
cout<<"\nVertex Distance"<<endl;
for(int i = 0; i < V; i++){
if( dist[i] != INT_MAX)
cout<<i<<"\t"<<dist[i]<<endl;
void print(int dist[], int V)
{
cout << "\nVertex Distance" << endl;
for (int i = 0; i < V; i++)
{
if (dist[i] != INT_MAX)
cout << i << "\t" << dist[i] << endl;
else
cout<<i<<"\tINF"<<endl;
cout << i << "\tINF" << endl;
}
}
//The main function that finds the shortest path from given source
//to all other vertices using Bellman-Ford.It also detects negative
//weight cycle
void BellmanFord(Graph graph, int src){
void BellmanFord(Graph graph, int src)
{
int V = graph.vertexNum;
int E = graph.edgeNum;
int dist[V];
//Initialize distances array as INF for all except source
//Intialize source as zero
for(int i=0; i<V; i++)
for (int i = 0; i < V; i++)
dist[i] = INT_MAX;
dist[src] = 0;
//Calculate shortest path distance from source to all edges
//A path can contain maximum (|V|-1) edges
for(int i=0; i<=V-1; i++)
for(int j = 0; j<E; j++){
for (int i = 0; i <= V - 1; i++)
for (int j = 0; j < E; j++)
{
int u = graph.edges[j].src;
int v = graph.edges[j].dst;
int w = graph.edges[j].weight;
if(dist[u]!=INT_MAX && dist[u] + w < dist[v])
if (dist[u] != INT_MAX && dist[u] + w < dist[v])
dist[v] = dist[u] + w;
}
//Iterate inner loop once more to check for negative cycle
for(int j = 0; j<E; j++){
for (int j = 0; j < E; j++)
{
int u = graph.edges[j].src;
int v = graph.edges[j].dst;
int w = graph.edges[j].weight;
if(dist[u]!=INT_MAX && dist[u] + w < dist[v]){
cout<<"Graph contains negative weight cycle. Hence, shortest distance not guaranteed."<<endl;
if (dist[u] != INT_MAX && dist[u] + w < dist[v])
{
cout << "Graph contains negative weight cycle. Hence, shortest distance not guaranteed." << endl;
return;
}
}
print(dist, V);
return;
}
//Driver Function
int main(){
int V,E,gsrc;
int src,dst,weight;
cout<<"Enter number of vertices: ";
cin>>V;
cout<<"Enter number of edges: ";
cin>>E;
Graph G(V,E);
for(int i=0; i<E; i++){
cout<<"\nEdge "<<i+1<<"\nEnter source: ";
cin>>src;
cout<<"Enter destination: ";
cin>>dst;
cout<<"Enter weight: ";
cin>>weight;
int main()
{
int V, E, gsrc;
int src, dst, weight;
cout << "Enter number of vertices: ";
cin >> V;
cout << "Enter number of edges: ";
cin >> E;
Graph G(V, E);
for (int i = 0; i < E; i++)
{
cout << "\nEdge " << i + 1 << "\nEnter source: ";
cin >> src;
cout << "Enter destination: ";
cin >> dst;
cout << "Enter weight: ";
cin >> weight;
G.addEdge(src, dst, weight);
}
cout<<"\nEnter source: ";
cin>>gsrc;
BellmanFord(G,gsrc);
cout << "\nEnter source: ";
cin >> gsrc;
BellmanFord(G, gsrc);
return 0;
}

View File

@@ -13,7 +13,7 @@ int *cat; // global array to hold catalan numbers
unsigned long int catalan_dp(int n)
{
/** Using the tabulation technique in dynamic programming,
/** Using the tabulation technique in dynamic programming,
this function computes the first `n+1` Catalan numbers
Parameter
@@ -26,39 +26,39 @@ unsigned long int catalan_dp(int n)
*/
// By definition, the first two Catalan numbers are 1
cat[0] = cat[1] = 1;
cat[0] = cat[1] = 1;
// Compute the remaining numbers from index 2 to index n, using tabulation
for (int i = 2; i <= n; i++)
{
cat[i] = 0;
for (int j = 0; j < i; j++)
cat[i] += cat[j] * cat[i-j-1]; // applying the definition here
}
for (int i = 2; i <= n; i++)
{
cat[i] = 0;
for (int j = 0; j < i; j++)
cat[i] += cat[j] * cat[i - j - 1]; // applying the definition here
}
// Return the result
return cat[n];
return cat[n];
}
int main(int argc, char *argv[])
{
int n;
cout << "Enter n: ";
cin >> n;
int n;
cout << "Enter n: ";
cin >> n;
cat = new int[n+1];
cat = new int[n + 1];
cout << "Catalan numbers from 0 to " << n << " are:\n";
for (int i = 0; i <= n; i++)
cout << "Catalan numbers from 0 to " << n << " are:\n";
for (int i = 0; i <= n; i++)
{
cout << "catalan (" << i << ") = " << catalan_dp(i) << endl;
// NOTE: Since `cat` is a global array, calling `catalan_dp`
cout << "catalan (" << i << ") = " << catalan_dp(i) << endl;
// NOTE: Since `cat` is a global array, calling `catalan_dp`
// repeatedly will not recompute the the values already computed
// as in case of pre-computed values, the array will simply return them,
// as in case of pre-computed values, the array will simply return them,
// instead of recomputing them.
}
return 0;
return 0;
}
/** Sample Test Case:

View File

@@ -1,5 +1,5 @@
#include <iostream>
#include<climits>
#include <climits>
using namespace std;
// Function to find the Minimum number of coins required to get Sum S
@@ -7,11 +7,10 @@ int findMinCoins(int arr[], int n, int N)
{
// dp[i] = no of coins required to get a total of i
int dp[N + 1];
// 0 coins are needed for 0 sum
dp[0] = 0;
// 0 coins are needed for 0 sum
dp[0] = 0;
for (int i = 1; i <= N; i++)
{
@@ -39,13 +38,13 @@ int findMinCoins(int arr[], int n, int N)
int main()
{
// No of Coins We Have
int arr[] = { 1, 2, 3, 4 };
int arr[] = {1, 2, 3, 4};
int n = sizeof(arr) / sizeof(arr[0]);
// Total Change Required
int N = 15;
cout << "Minimum Number of Coins Required "<< findMinCoins(arr, n, N) << "\n";
cout << "Minimum Number of Coins Required " << findMinCoins(arr, n, N) << "\n";
return 0;
}

View File

@@ -5,25 +5,24 @@ the pieces.*/
#include <bits/stdc++.h>
using namespace std;
int cutrod(int p[],int n)
int cutrod(int p[], int n)
{
int r[n+1];
r[0]=0;
for(int j=0;j<n;j++)
int r[n + 1];
r[0] = 0;
for (int j = 0; j < n; j++)
{
int q=INT_MIN;
for(int i=0;i<=j;i++)
int q = INT_MIN;
for (int i = 0; i <= j; i++)
{
q = max(q,p[i]+r[j-i]);
q = max(q, p[i] + r[j - i]);
}
r[j+1]=q;
r[j + 1] = q;
}
return r[n];
}
int main()
{
int price[]={1,5,8,9,10,17,17,20,24,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50};
cout<<cutrod(price,30);
int price[] = {1, 5, 8, 9, 10, 17, 17, 20, 24, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50};
cout << cutrod(price, 30);
return 0;
}

View File

@@ -15,8 +15,9 @@
#include <string>
using namespace std;
int min(int x, int y, int z){
return min(min(x,y), z);
int min(int x, int y, int z)
{
return min(min(x, y), z);
}
/* A Naive recursive C++ program to find
@@ -24,62 +25,68 @@ int min(int x, int y, int z){
* str1 to str2.
* O(3^m)
*/
int editDist(string str1, string str2, int m, int n) {
if(m == 0) return n;
if(n == 0) return m;
//If last characters are same then continue
//for the rest of them.
if(str1[m-1] == str2[n-1])
return editDist(str1, str2, m-1, n-1);
int editDist(string str1, string str2, int m, int n)
{
if (m == 0)
return n;
if (n == 0)
return m;
//If last not same, then 3 possibilities
//a.Insert b.Remove c. Replace
//Get min of three and continue for rest.
return 1 + min ( editDist(str1, str2, m, n-1),
editDist(str1, str2, m-1, n),
editDist(str1, str2, m-1, n-1)
);
//If last characters are same then continue
//for the rest of them.
if (str1[m - 1] == str2[n - 1])
return editDist(str1, str2, m - 1, n - 1);
//If last not same, then 3 possibilities
//a.Insert b.Remove c. Replace
//Get min of three and continue for rest.
return 1 + min(editDist(str1, str2, m, n - 1),
editDist(str1, str2, m - 1, n),
editDist(str1, str2, m - 1, n - 1));
}
/* A DP based program
* O(m x n)
*/
int editDistDP(string str1, string str2, int m, int n) {
int editDistDP(string str1, string str2, int m, int n)
{
//Create Table for SubProblems
int dp[m+1][n+1];
int dp[m + 1][n + 1];
//Fill d[][] in bottom up manner
for(int i=0; i<=m; i++) {
for(int j=0; j<=n; j++) {
for (int i = 0; i <= m; i++)
{
for (int j = 0; j <= n; j++)
{
//If str1 empty. Then add all of str2
if(i==0)
if (i == 0)
dp[i][j] = j;
//If str2 empty. Then add all of str1
else if(j==0)
//If str2 empty. Then add all of str1
else if (j == 0)
dp[i][j] = i;
//If character same. Recur for remaining
else if(str1[i-1] == str2[j-1])
dp[i][j] = dp[i-1][j-1];
//If character same. Recur for remaining
else if (str1[i - 1] == str2[j - 1])
dp[i][j] = dp[i - 1][j - 1];
else
dp[i][j] = 1 + min(dp[i][j-1],//Insert
dp[i-1][j],//Remove
dp[i-1][j-1]//Replace
);
dp[i][j] = 1 + min(dp[i][j - 1], //Insert
dp[i - 1][j], //Remove
dp[i - 1][j - 1] //Replace
);
}
}
return dp[m][n];
}
int main() {
int main()
{
string str1 = "sunday";
string str2 = "saturday";
cout << editDist(str1, str2, str1.length(), str2.length()) << endl;
cout << editDistDP(str1, str2, str1.length(), str2.length()) << endl;

View File

@@ -6,40 +6,47 @@
#include <climits>
using namespace std;
int eggDrop(int n, int k) {
int eggFloor[n+1][k+1];
int eggDrop(int n, int k)
{
int eggFloor[n + 1][k + 1];
int result;
for(int i=1; i<=n; i++) {
for (int i = 1; i <= n; i++)
{
eggFloor[i][1] = 1; //n eggs..1 Floor
eggFloor[i][0] = 0; //n eggs..0 Floor
}
// Only one egg available
for(int j=1; j<=k ; j++) {
for (int j = 1; j <= k; j++)
{
eggFloor[1][j] = j;
}
for(int i=2; i<=n; i++) {
for(int j=2; j<=k; j++) {
for (int i = 2; i <= n; i++)
{
for (int j = 2; j <= k; j++)
{
eggFloor[i][j] = INT_MAX;
for(int x=1; x<=j; x++) {
for (int x = 1; x <= j; x++)
{
// 1+max(eggBreak[one less egg, lower floors],
// eggDoesntBreak[same # of eggs, upper floors]);
result = 1 + max(eggFloor[i-1][x-1], eggFloor[i][j-x]);
if(result < eggFloor[i][j])
result = 1 + max(eggFloor[i - 1][x - 1], eggFloor[i][j - x]);
if (result < eggFloor[i][j])
eggFloor[i][j] = result;
}
}
}
return eggFloor[n][k];
}
int main() {
int main()
{
int n, k;
cout << "Enter number of eggs and floors: ";
cin>>n>>k;
cin >> n >> k;
cout << "Minimum number of trials in worst case: " << eggDrop(n, k) << endl;
return 0;
}

View File

@@ -1,19 +1,22 @@
#include <bits/stdc++.h>
using namespace std;
int fib(int n){
int res[n+1];
res[0] = 0; res[1] = 1;
for(int i=2;i<=n;i++){
res[i] = res[i-1] + res[i-2];
int fib(int n)
{
int res[n + 1];
res[0] = 0;
res[1] = 1;
for (int i = 2; i <= n; i++)
{
res[i] = res[i - 1] + res[i - 2];
}
return res[n];
}
int main(int argc, char const *argv[])
{
int n;
cout<<"Enter n: ";
cin>>n;
cout<<"Fibonacci number is ";
cout<<fib(n)<<endl;
cout << "Enter n: ";
cin >> n;
cout << "Fibonacci number is ";
cout << fib(n) << endl;
return 0;
}

View File

@@ -1,24 +1,26 @@
#include <bits/stdc++.h>
using namespace std;
int arr[1000000];
int fib(int n){
if(arr[n]==-1){
if(n<=1)
int fib(int n)
{
if (arr[n] == -1)
{
if (n <= 1)
arr[n] = n;
else
arr[n] = fib(n-1) + fib(n-2);
arr[n] = fib(n - 1) + fib(n - 2);
}
return arr[n];
}
int main(int argc, char const *argv[])
{
int n;
cout<<"Enter n: ";
cin>>n;
for (int i = 0; i < n+1; ++i)
cout << "Enter n: ";
cin >> n;
for (int i = 0; i < n + 1; ++i)
{
arr[i] = -1;
}
cout<<"Fibonacci number is "<<fib(n)<<endl;
cout << "Fibonacci number is " << fib(n) << endl;
return 0;
}

View File

@@ -1,103 +1,109 @@
#include<iostream>
#include<limits.h>
#include<string.h>
#include <iostream>
#include <limits.h>
#include <string.h>
using namespace std;
//Wrapper class for storing a graph
class Graph{
public:
class Graph
{
public:
int vertexNum;
int** edges;
int **edges;
//Constructs a graph with V vertices and E edges
Graph(int V){
Graph(int V)
{
this->vertexNum = V;
this->edges =(int**) malloc(V * sizeof(int*));
for(int i=0; i<V; i++){
this->edges[i] = (int*) malloc(V * sizeof(int));
for(int j=0; j<V; j++)
this->edges = (int **)malloc(V * sizeof(int *));
for (int i = 0; i < V; i++)
{
this->edges[i] = (int *)malloc(V * sizeof(int));
for (int j = 0; j < V; j++)
this->edges[i][j] = INT_MAX;
this->edges[i][i] = 0;
}
}
}
//Adds the given edge to the graph
void addEdge(int src, int dst, int weight){
//Adds the given edge to the graph
void addEdge(int src, int dst, int weight)
{
this->edges[src][dst] = weight;
}
};
//Utility function to print distances
void print(int dist[], int V){
cout<<"\nThe Distance matrix for Floyd - Warshall"<<endl;
for(int i = 0; i < V; i++){
for(int j=0; j<V; j++){
void print(int dist[], int V)
{
cout << "\nThe Distance matrix for Floyd - Warshall" << endl;
for (int i = 0; i < V; i++)
{
for (int j = 0; j < V; j++)
{
if(dist[i*V+j] != INT_MAX)
cout<<dist[i*V+j]<<"\t";
else
cout<<"INF"<<"\t";
if (dist[i * V + j] != INT_MAX)
cout << dist[i * V + j] << "\t";
else
cout << "INF"
<< "\t";
}
cout<<endl;
cout << endl;
}
}
//The main function that finds the shortest path from a vertex
//to all other vertices using Floyd-Warshall Algorithm.
void FloydWarshall(Graph graph){
void FloydWarshall(Graph graph)
{
int V = graph.vertexNum;
int dist[V][V];
//Initialise distance array
for(int i=0; i<V; i++)
for(int j=0; j<V; j++)
dist[i][j] = graph.edges[i][j];
for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++)
dist[i][j] = graph.edges[i][j];
//Calculate distances
for(int k=0; k<V; k++)
//Choose an intermediate vertex
for (int k = 0; k < V; k++)
//Choose an intermediate vertex
for(int i=0; i<V; i++)
//Choose a source vertex for given intermediate
for (int i = 0; i < V; i++)
//Choose a source vertex for given intermediate
for(int j=0; j<V; j++)
//Choose a destination vertex for above source vertex
for (int j = 0; j < V; j++)
//Choose a destination vertex for above source vertex
if(dist[i][k] != INT_MAX && dist[k][j] != INT_MAX && dist[i][k] + dist[k][j] < dist[i][j])
//If the distance through intermediate vertex is less than direct edge then update value in distance array
if (dist[i][k] != INT_MAX && dist[k][j] != INT_MAX && dist[i][k] + dist[k][j] < dist[i][j])
//If the distance through intermediate vertex is less than direct edge then update value in distance array
dist[i][j] = dist[i][k] + dist[k][j];
//Convert 2d array to 1d array for print
int dist1d[V*V];
for(int i=0; i<V; i++)
for(int j=0; j<V; j++)
dist1d[i*V+j] = dist[i][j];
print(dist1d,V);
}
int dist1d[V * V];
for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++)
dist1d[i * V + j] = dist[i][j];
print(dist1d, V);
}
//Driver Function
int main(){
int V,E;
int src,dst,weight;
cout<<"Enter number of vertices: ";
cin>>V;
cout<<"Enter number of edges: ";
cin>>E;
int main()
{
int V, E;
int src, dst, weight;
cout << "Enter number of vertices: ";
cin >> V;
cout << "Enter number of edges: ";
cin >> E;
Graph G(V);
for(int i=0; i<E; i++){
cout<<"\nEdge "<<i+1<<"\nEnter source: ";
cin>>src;
cout<<"Enter destination: ";
cin>>dst;
cout<<"Enter weight: ";
cin>>weight;
for (int i = 0; i < E; i++)
{
cout << "\nEdge " << i + 1 << "\nEnter source: ";
cin >> src;
cout << "Enter destination: ";
cin >> dst;
cout << "Enter weight: ";
cin >> weight;
G.addEdge(src, dst, weight);
}
FloydWarshall(G);

View File

@@ -4,69 +4,67 @@ using namespace std;
void Print(int trace[20][20], int m, int n, string a)
{
if (m==0 || n==0)
if (m == 0 || n == 0)
{
return;
}
if (trace[m][n]==1)
if (trace[m][n] == 1)
{
Print(trace, m-1, n-1, a);
cout<<a[m-1];
Print(trace, m - 1, n - 1, a);
cout << a[m - 1];
}
else if(trace[m][n]==2)
else if (trace[m][n] == 2)
{
Print(trace, m-1,n, a);
Print(trace, m - 1, n, a);
}
else if (trace[m][n]==3)
else if (trace[m][n] == 3)
{
Print(trace, m,n-1, a);
Print(trace, m, n - 1, a);
}
}
int lcs(string a, string b)
{
int m = a.length(), n = b.length();
int res[m+1][n+1];
int res[m + 1][n + 1];
int trace[20][20];
// fills up the arrays with zeros.
for (int i = 0; i < m+1; i++)
for (int i = 0; i < m + 1; i++)
{
for (int j = 0; j < n+1; j++)
for (int j = 0; j < n + 1; j++)
{
res[i][j] = 0;
trace[i][j] = 0;
}
}
for (int i = 0; i < m+1; ++i)
for (int i = 0; i < m + 1; ++i)
{
for (int j = 0; j < n+1; ++j)
for (int j = 0; j < n + 1; ++j)
{
if(i==0||j==0)
if (i == 0 || j == 0)
{
res[i][j] = 0;
trace[i][j]=0;
trace[i][j] = 0;
}
else if(a[i-1]==b[j-1])
else if (a[i - 1] == b[j - 1])
{
res[i][j] = 1 + res[i-1][j-1];
trace[i][j]=1; // 1 means trace the matrix in upper left diagonal direction.
res[i][j] = 1 + res[i - 1][j - 1];
trace[i][j] = 1; // 1 means trace the matrix in upper left diagonal direction.
}
else
{
if (res[i-1][j]>res[i][j-1])
if (res[i - 1][j] > res[i][j - 1])
{
res[i][j]=res[i-1][j];
trace[i][j]=2; // 2 means trace the matrix in upwards direction.
res[i][j] = res[i - 1][j];
trace[i][j] = 2; // 2 means trace the matrix in upwards direction.
}
else
{
res[i][j]=res[i][j-1];
trace[i][j]=3; // means trace the matrix in left direction.
res[i][j] = res[i][j - 1];
trace[i][j] = 3; // means trace the matrix in left direction.
}
}
}
@@ -75,13 +73,10 @@ int lcs(string a, string b)
return res[m][n];
}
int main()
{
string a,b;
cin>>a>>b;
cout<<lcs(a,b);
string a, b;
cin >> a >> b;
cout << lcs(a, b);
return 0;
}

View File

@@ -1,7 +1,8 @@
//Program to calculate length of longest increasing subsequence in an array
#include <bits/stdc++.h>
using namespace std;
int LIS(int a[],int n){
int LIS(int a[], int n)
{
int lis[n];
for (int i = 0; i < n; ++i)
{
@@ -11,28 +12,28 @@ int LIS(int a[],int n){
{
for (int j = 0; j < i; ++j)
{
if(a[i]>a[j] && lis[i]<lis[j]+1)
if (a[i] > a[j] && lis[i] < lis[j] + 1)
lis[i] = lis[j] + 1;
}
}
int res = 0;
for (int i = 0; i < n; ++i)
{
res = max(res,lis[i]);
res = max(res, lis[i]);
}
return res;
}
int main(int argc, char const *argv[])
{
int n;
cout<<"Enter size of array: ";
cin>>n;
cout << "Enter size of array: ";
cin >> n;
int a[n];
cout<<"Enter array elements: ";
cout << "Enter array elements: ";
for (int i = 0; i < n; ++i)
{
cin>>a[i];
cin >> a[i];
}
cout<<LIS(a,n)<<endl;
cout << LIS(a, n) << endl;
return 0;
}

View File

@@ -18,7 +18,7 @@ int MatrixChainMultiplication(int dim[], int i, int j)
// needed to compute the matrix M[i+1]...M[j] = M[i..j]
int min = INT_MAX;
// if dp[i][j] is not calculated (calculate it!!)
// if dp[i][j] is not calculated (calculate it!!)
if (dp[i][j] == 0)
{
@@ -34,7 +34,7 @@ int MatrixChainMultiplication(int dim[], int i, int j)
cost += MatrixChainMultiplication(dim, k, j);
// cost to multiply two (i x k) and (k x j) matrix
cost += dim[i] * dim[k] * dim[j];
cost += dim[i] * dim[k] * dim[j];
if (cost < min)
min = cost; // store the minimum cost
@@ -51,7 +51,7 @@ int main()
{
// Matrix i has Dimensions dim[i-1] & dim[i] for i=1..n
// input is 10 x 30 matrix, 30 x 5 matrix, 5 x 60 matrix
int dim[] = { 10, 30, 5, 60 };
int dim[] = {10, 30, 5, 60};
int n = sizeof(dim) / sizeof(dim[0]);
// Function Calling: MatrixChainMultiplications(dimensions_array, starting, ending);

View File

@@ -1,59 +1,72 @@
#include<bits/stdc++.h>
#include <bits/stdc++.h>
using namespace std;
class graph{
class graph
{
int v;
list<int> *adj;
public:
public:
graph(int v);
void addedge(int src,int dest);
void addedge(int src, int dest);
void printgraph();
void bfs(int s);
};
graph::graph(int v){
graph::graph(int v)
{
this->v = v;
this->adj = new list<int>[v];
}
void graph::addedge(int src,int dest){
src--;dest--;
void graph::addedge(int src, int dest)
{
src--;
dest--;
adj[src].push_back(dest);
//adj[dest].push_back(src);
}
void graph::printgraph(){
for(int i=0;i<this->v;i++){
cout<<"Adjacency list of vertex "<<i+1<<" is \n";
void graph::printgraph()
{
for (int i = 0; i < this->v; i++)
{
cout << "Adjacency list of vertex " << i + 1 << " is \n";
list<int>::iterator it;
for(it=adj[i].begin();it!=adj[i].end();++it){
cout<<*it+1<<" ";
for (it = adj[i].begin(); it != adj[i].end(); ++it)
{
cout << *it + 1 << " ";
}
cout<<endl;
cout << endl;
}
}
void graph::bfs(int s){
bool *visited = new bool[this->v+1];
memset(visited,false,sizeof(bool)*(this->v+1));
visited[s]=true;
void graph::bfs(int s)
{
bool *visited = new bool[this->v + 1];
memset(visited, false, sizeof(bool) * (this->v + 1));
visited[s] = true;
list<int> q;
q.push_back(s);
list<int>::iterator it;
while(!q.empty()){
while (!q.empty())
{
int u = q.front();
cout<<u<<" ";
cout << u << " ";
q.pop_front();
for(it=adj[u].begin();it!=adj[u].end();++it){
if(visited[*it]==false){
for (it = adj[u].begin(); it != adj[u].end(); ++it)
{
if (visited[*it] == false)
{
visited[*it] = true;
q.push_back(*it);
}
}
}
}
int main(){
int main()
{
graph g(4);
g.addedge(1,2);
g.addedge(2,3);
g.addedge(3,4);
g.addedge(1,4);
g.addedge(1,3);
g.addedge(1, 2);
g.addedge(2, 3);
g.addedge(3, 4);
g.addedge(1, 4);
g.addedge(1, 3);
//g.printgraph();
g.bfs(2);
return 0;

View File

@@ -1,27 +1,31 @@
#include <bits/stdc++.h>
using namespace std;
int v = 4;
void DFSUtil_(int graph[4][4],bool visited[],int s){
void DFSUtil_(int graph[4][4], bool visited[], int s)
{
visited[s] = true;
cout<<s<<" ";
for(int i=0;i<v;i++){
if(graph[s][i]==1&&visited[i]==false){
DFSUtil_(graph,visited,i);
cout << s << " ";
for (int i = 0; i < v; i++)
{
if (graph[s][i] == 1 && visited[i] == false)
{
DFSUtil_(graph, visited, i);
}
}
}
void DFS_(int graph[4][4],int s){
void DFS_(int graph[4][4], int s)
{
bool visited[v];
memset(visited,0,sizeof(visited));
DFSUtil_(graph,visited,s);
memset(visited, 0, sizeof(visited));
DFSUtil_(graph, visited, s);
}
int main()
{
int graph[4][4] = {{0,1,1,0},{0,0,1,0},{1,0,0,1},{0,0,0,1}};
cout<<"DFS: ";
DFS_(graph,2);
cout<<endl;
return 0;
int graph[4][4] = {{0, 1, 1, 0}, {0, 0, 1, 0}, {1, 0, 0, 1}, {0, 0, 0, 1}};
cout << "DFS: ";
DFS_(graph, 2);
cout << endl;
return 0;
}

View File

@@ -2,7 +2,6 @@
#include <list>
#include <stack>
#define WHITE 0
#define GREY 1
#define BLACK 2
@@ -12,23 +11,27 @@ using namespace std;
int checked[999] = {WHITE};
void dfs(const list<int> lista[], int start) {
void dfs(const list<int> lista[], int start)
{
stack<int> stack;
int checked[999] = {WHITE};
stack.push(start);
checked[start] = GREY;
while(!stack.empty()) {
while (!stack.empty())
{
int act = stack.top();
stack.pop();
if(checked[act] == GREY) {
if (checked[act] == GREY)
{
cout << act << ' ';
for(auto it = lista[act].begin(); it != lista[act].end(); ++it) {
for (auto it = lista[act].begin(); it != lista[act].end(); ++it)
{
stack.push(*it);
if(checked[*it] != BLACK)
if (checked[*it] != BLACK)
checked[*it] = GREY;
}
checked[act] = BLACK; //nodo controllato
@@ -36,18 +39,19 @@ void dfs(const list<int> lista[], int start) {
}
}
int main() {
int u, w;
int n;
cin >> n;
list<int> lista[INF];
for(int i = 0; i < n; ++i) {
cin >> u >> w;
lista[u].push_back(w);
}
int main()
{
int u, w;
int n;
cin >> n;
list<int> lista[INF];
for (int i = 0; i < n; ++i)
{
cin >> u >> w;
lista[u].push_back(w);
}
dfs(lista, 0);
dfs(lista, 0);
return 0;
return 0;
}

View File

@@ -4,46 +4,52 @@
#include <iostream>
using namespace std;
#define INF 10000010
vector < pair <int,int> > graph[5*100001];
int dis[5*100001];
int dij(vector <pair<int,int> > * v,int s,int * dis) {
priority_queue < pair <int,int> , vector < pair <int,int> >,greater < pair <int,int> > > pq;
vector<pair<int, int>> graph[5 * 100001];
int dis[5 * 100001];
int dij(vector<pair<int, int>> *v, int s, int *dis)
{
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
// source distance to zero.
pq.push(make_pair(0,s));
pq.push(make_pair(0, s));
dis[s] = 0;
int u;
while(!pq.empty()) {
while (!pq.empty())
{
u = (pq.top()).second;
pq.pop();
for( vector <pair <int,int> > :: iterator it = v[u].begin(); it != v[u].end();it++) {
if(dis[u] + it->first < dis[it->second]) {
for (vector<pair<int, int>>::iterator it = v[u].begin(); it != v[u].end(); it++)
{
if (dis[u] + it->first < dis[it->second])
{
dis[it->second] = dis[u] + it->first;
pq.push(make_pair(dis[it->second],it->second));
pq.push(make_pair(dis[it->second], it->second));
}
}
}
}
int main() {
int m,n,l,x,y,s;
int main()
{
int m, n, l, x, y, s;
// n--> number of nodes , m --> number of edges
cin>>n>>m;
for(int i = 0;i < m;i++) {
cin >> n >> m;
for (int i = 0; i < m; i++)
{
// input edges.
scanf("%d%d%d",&x,&y,&l);
graph[x].push_back(make_pair(l,y));
graph[y].push_back(make_pair(l,x)); // comment this line for directed graph
scanf("%d%d%d", &x, &y, &l);
graph[x].push_back(make_pair(l, y));
graph[y].push_back(make_pair(l, x)); // comment this line for directed graph
}
// start node.
scanf("%d",&s);
scanf("%d", &s);
// intialise all distances to infinity.
for(int i = 1;i <= n;i++)
for (int i = 1; i <= n; i++)
dis[i] = INF;
dij(graph,s,dis);
for(int i = 1;i <= n;i++)
if(dis[i] == INF)
cout<<"-1 ";
dij(graph, s, dis);
for (int i = 1; i <= n; i++)
if (dis[i] == INF)
cout << "-1 ";
else
cout<<dis[i]<<" ";
cout << dis[i] << " ";
return 0;
}

View File

@@ -1,91 +1,134 @@
#include "bits/stdc++.h"
//#include <boost/multiprecision/cpp_int.hpp>
//using namespace boost::multiprecision;
const int mx = 1e6+5;
const int mx = 1e6 + 5;
const long int inf = 2e9;
typedef long long ll;
#define rep(i,n) for(i=0;i<n;i++)
#define repp(i,a,b) for(i=a;i<=b;i++)
#define pii pair<int,int>
#define vpii vector< pii >
#define rep(i, n) for (i = 0; i < n; i++)
#define repp(i, a, b) for (i = a; i <= b; i++)
#define pii pair<int, int>
#define vpii vector<pii>
#define vi vector<int>
#define vll vector<ll>
#define r(x) scanf("%d",&x)
#define rs(s) scanf("%s",s)
#define vll vector<ll>
#define r(x) scanf("%d", &x)
#define rs(s) scanf("%s", s)
#define gc getchar_unlocked
#define pc putchar_unlocked
#define mp make_pair
#define pb push_back
#define pb push_back
#define lb lower_bound
#define ub upper_bound
#define endl "\n"
#define fast ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define fast \
ios_base::sync_with_stdio(false); \
cin.tie(NULL); \
cout.tie(NULL);
using namespace std;
void in(int &x)
{
register int c = gc(); x = 0; int neg = 0;
for(;((c<48 || c>57) && c != '-');c = gc());if(c=='-') {neg=1;c=gc();} for(;c>47 && c<58;c = gc()) {x = (x<<1) + (x<<3) + c - 48;}
if(neg) x=-x;
register int c = gc();
x = 0;
int neg = 0;
for (; ((c < 48 || c > 57) && c != '-'); c = gc())
;
if (c == '-')
{
neg = 1;
c = gc();
}
for (; c > 47 && c < 58; c = gc())
{
x = (x << 1) + (x << 3) + c - 48;
}
if (neg)
x = -x;
}
void out (int n) { int N = n, rev, count = 0;rev = N; if (N == 0) { pc('0'); return ;} while ((rev % 10) == 0) { count++; rev /= 10;} rev = 0;while (N != 0) { rev = (rev<<3) + (rev<<1) + N % 10; N /= 10;}while (rev != 0) { pc(rev % 10 + '0'); rev /= 10;}
while (count--) pc('0');
void out(int n)
{
int N = n, rev, count = 0;
rev = N;
if (N == 0)
{
pc('0');
return;
}
while ((rev % 10) == 0)
{
count++;
rev /= 10;
}
rev = 0;
while (N != 0)
{
rev = (rev << 3) + (rev << 1) + N % 10;
N /= 10;
}
while (rev != 0)
{
pc(rev % 10 + '0');
rev /= 10;
}
while (count--)
pc('0');
}
ll parent[mx],arr[mx],node,edge;
vector<pair<ll,pair<ll,ll>>>v;
ll parent[mx], arr[mx], node, edge;
vector<pair<ll, pair<ll, ll>>> v;
void initial()
{
int i;
rep(i,node+edge)
rep(i, node + edge)
parent[i] = i;
}
int root(int i)
{
while(parent[i] != i)
while (parent[i] != i)
{
parent[i] = parent[parent[i]];
i = parent[i];
}
return i;
}
void join(int x,int y)
void join(int x, int y)
{
int root_x = root(x); //Disjoint set union by rank
int root_x = root(x); //Disjoint set union by rank
int root_y = root(y);
parent[root_x] = root_y;
}
ll kruskal()
{
ll mincost=0,i,x,y;
rep(i,edge)
ll mincost = 0, i, x, y;
rep(i, edge)
{
x = v[i].second.first;
y = v[i].second.second;
if(root(x) != root(y))
if (root(x) != root(y))
{
mincost += v[i].first;
join(x,y);
join(x, y);
}
}
return mincost;
}
int main(){
int main()
{
fast;
while(1)
while (1)
{
int i,j,from,to,cost,totalcost=0;
cin>>node>>edge; //Enter the nodes and edges
if(node==0 && edge==0) break; //Enter 0 0 to break out
initial(); //Initialise the parent array
rep(i,edge)
int i, j, from, to, cost, totalcost = 0;
cin >> node >> edge; //Enter the nodes and edges
if (node == 0 && edge == 0)
break; //Enter 0 0 to break out
initial(); //Initialise the parent array
rep(i, edge)
{
cin>>from>>to>>cost;
v.pb(mp(cost,mp(from,to)));
cin >> from >> to >> cost;
v.pb(mp(cost, mp(from, to)));
totalcost += cost;
}
sort(v.begin(),v.end());
sort(v.begin(), v.end());
// rep(i,v.size())
// cout<<v[i].first<<" ";
cout<<kruskal()<<endl;
cout << kruskal() << endl;
v.clear();
}
return 0;

View File

@@ -1,44 +1,51 @@
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
using namespace std;
int n , m; // For number of Vertices (V) and number of edges (E)
vector< vector<int> > G;
int n, m; // For number of Vertices (V) and number of edges (E)
vector<vector<int>> G;
vector<bool> visited;
vector<int> ans;
void dfs(int v) {
void dfs(int v)
{
visited[v] = true;
for (int u : G[v]) {
for (int u : G[v])
{
if (!visited[u])
dfs(u);
}
ans.push_back(v);
}
void topological_sort() {
void topological_sort()
{
visited.assign(n, false);
ans.clear();
for (int i = 0; i < n; ++i) {
for (int i = 0; i < n; ++i)
{
if (!visited[i])
dfs(i);
}
reverse(ans.begin(), ans.end());
}
int main(){
int main()
{
cout << "Enter the number of vertices and the number of directed edges\n";
cin >> n >> m;
int x , y;
G.resize(n , vector<int>());
for(int i = 0 ; i < n ; ++i) {
int x, y;
G.resize(n, vector<int>());
for (int i = 0; i < n; ++i)
{
cin >> x >> y;
x-- , y--; // to convert 1-indexed to 0-indexed
x--, y--; // to convert 1-indexed to 0-indexed
G[x].push_back(y);
}
topological_sort();
cout << "Topological Order : \n";
for(int v : ans) {
for (int v : ans)
{
cout << v + 1 << ' '; // converting zero based indexing back to one based.
}
cout << '\n';

View File

@@ -15,7 +15,7 @@ public:
{
// initializes the array edges.
this->edges = new int*[V];
this->edges = new int *[V];
for (int i = 0; i < V; i++)
{
edges[i] = new int[V];
@@ -31,7 +31,6 @@ public:
}
this->vertexNum = V;
}
//Adds the given edge to the graph
@@ -39,36 +38,33 @@ public:
{
this->edges[src][dst] = weight;
}
};
//Utility function to find minimum distance vertex in mdist
int minDistance(int mdist[], bool vset[], int V)
{
int minVal = INT_MAX, minInd = 0;
for(int i=0; i<V; i++)
for (int i = 0; i < V; i++)
{
if(!vset[i] && (mdist[i] < minVal))
if (!vset[i] && (mdist[i] < minVal))
{
minVal = mdist[i];
minInd = i;
}
}
return minInd;
}
//Utility function to print distances
void print(int dist[], int V)
{
cout<<"\nVertex Distance"<<endl;
for(int i = 0; i < V; i++)
cout << "\nVertex Distance" << endl;
for (int i = 0; i < V; i++)
{
if( dist[i] < INT_MAX)
cout<<i<<"\t"<<dist[i]<<endl;
if (dist[i] < INT_MAX)
cout << i << "\t" << dist[i] << endl;
else
cout<<i<<"\tINF"<<endl;
cout << i << "\tINF" << endl;
}
}
@@ -83,54 +79,51 @@ void Dijkstra(Graph graph, int src)
// in the shortest path tree
//Initialise mdist and vset. Set distance of source as zero
for(int i=0; i<V; i++)
for (int i = 0; i < V; i++)
{
mdist[i] = INT_MAX;
vset[i] = false;
}
mdist[src] = 0;
//iterate to find shortest path
for(int count = 0; count<V-1; count++)
for (int count = 0; count < V - 1; count++)
{
int u = minDistance(mdist,vset,V);
int u = minDistance(mdist, vset, V);
vset[u] = true;
for(int v=0; v<V; v++)
for (int v = 0; v < V; v++)
{
if(!vset[v] && graph.edges[u][v] && mdist[u] + graph.edges[u][v] < mdist[v])
if (!vset[v] && graph.edges[u][v] && mdist[u] + graph.edges[u][v] < mdist[v])
{
mdist[v] = mdist[u] + graph.edges[u][v];
}
}
}
print(mdist, V);
}
//Driver Function
int main()
{
int V,E,gsrc;
int src,dst,weight;
cout<<"Enter number of vertices: ";
cin>>V;
cout<<"Enter number of edges: ";
cin>>E;
int V, E, gsrc;
int src, dst, weight;
cout << "Enter number of vertices: ";
cin >> V;
cout << "Enter number of edges: ";
cin >> E;
Graph G(V);
for(int i=0; i<E; i++)
for (int i = 0; i < E; i++)
{
cout<<"\nEdge "<<i+1<<"\nEnter source: ";
cin>>src;
cout<<"Enter destination: ";
cin>>dst;
cout<<"Enter weight: ";
cin>>weight;
cout << "\nEdge " << i + 1 << "\nEnter source: ";
cin >> src;
cout << "Enter destination: ";
cin >> dst;
cout << "Enter weight: ";
cin >> weight;
// makes sure source and destionation are in the proper bounds.
if (src >= 0 && src < V && dst >= 0 && dst < V)
@@ -144,9 +137,9 @@ int main()
continue;
}
}
cout<<"\nEnter source:";
cin>>gsrc;
Dijkstra(G,gsrc);
cout << "\nEnter source:";
cin >> gsrc;
Dijkstra(G, gsrc);
return 0;
}

View File

@@ -1,4 +1,4 @@
#include<iostream>
#include <iostream>
using namespace std;
struct Item
@@ -7,91 +7,86 @@ struct Item
int profit;
};
float profitPerUnit(Item x)
{
return (float)x.profit/(float)x.weight;
return (float)x.profit / (float)x.weight;
}
int partition (Item arr[], int low, int high)
int partition(Item arr[], int low, int high)
{
Item pivot = arr[high]; // pivot
int i = (low - 1); // Index of smaller element
for (int j = low; j <high; j++)
{
// If current element is smaller than or
// equal to pivot
if (profitPerUnit(arr[j]) <= profitPerUnit(pivot))
{
i++; // increment index of smaller element
Item temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
Item temp=arr[i+1];
arr[i+1]=arr[high];
arr[high]=temp;
return (i + 1);
Item pivot = arr[high]; // pivot
int i = (low - 1); // Index of smaller element
for (int j = low; j < high; j++)
{
// If current element is smaller than or
// equal to pivot
if (profitPerUnit(arr[j]) <= profitPerUnit(pivot))
{
i++; // increment index of smaller element
Item temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
Item temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;
return (i + 1);
}
void quickSort(Item arr[], int low, int high)
{
if (low < high)
{
int p= partition(arr, low, high);
if (low < high)
{
quickSort(arr, low, p - 1);
quickSort(arr, p + 1, high);
}
int p = partition(arr, low, high);
quickSort(arr, low, p - 1);
quickSort(arr, p + 1, high);
}
}
int main()
{
cout<<"\nEnter the capacity of the knapsack : ";
cout << "\nEnter the capacity of the knapsack : ";
float capacity;
cin>>capacity;
cout<<"\n Enter the number of Items : ";
cin >> capacity;
cout << "\n Enter the number of Items : ";
int n;
cin>>n;
cin >> n;
Item itemArray[n];
for (int i = 0; i < n; i++)
{
cout<<"\nEnter the weight and profit of item "<<i+1<<" : ";
cin>>itemArray[i].weight;
cin>>itemArray[i].profit;
cout << "\nEnter the weight and profit of item " << i + 1 << " : ";
cin >> itemArray[i].weight;
cin >> itemArray[i].profit;
}
quickSort(itemArray, 0, n-1);
quickSort(itemArray, 0, n - 1);
// show(itemArray, n);
float maxProfit=0;
int i=n;
while(capacity>0 && --i>=0)
float maxProfit = 0;
int i = n;
while (capacity > 0 && --i >= 0)
{
if(capacity>=itemArray[i].weight)
if (capacity >= itemArray[i].weight)
{
maxProfit+=itemArray[i].profit;
capacity-=itemArray[i].weight;
cout<<"\n\t"<<itemArray[i].weight<<"\t"<<itemArray[i].profit;
maxProfit += itemArray[i].profit;
capacity -= itemArray[i].weight;
cout << "\n\t" << itemArray[i].weight << "\t" << itemArray[i].profit;
}
else
{
maxProfit+=profitPerUnit(itemArray[i])*capacity;
cout<<"\n\t"<<capacity<<"\t"<<profitPerUnit(itemArray[i])*capacity;
capacity=0;
maxProfit += profitPerUnit(itemArray[i]) * capacity;
cout << "\n\t" << capacity << "\t" << profitPerUnit(itemArray[i]) * capacity;
capacity = 0;
break;
}
}
cout<<"\nMax Profit : "<<maxProfit;
cout << "\nMax Profit : " << maxProfit;
return 0;
}

View File

@@ -4,35 +4,32 @@ using namespace std;
#define V 6
#define INFINITY 99999
int graph[V][V] ={
int graph[V][V] = {
{0, 4, 1, 4, INFINITY, INFINITY},
{4, 0, 3, 8, 3, INFINITY},
{1, 3, 0, INFINITY, 1, INFINITY},
{4, 8, INFINITY, 0, 5, 7},
{INFINITY, 3, 1, 5, 0, INFINITY},
{INFINITY, INFINITY, INFINITY, 7, INFINITY, 0}
};
{INFINITY, INFINITY, INFINITY, 7, INFINITY, 0}};
void findMinimumEdge()
{
for (int i = 0; i < V; i++)
{
int min=INFINITY;
int minIndex=0;
int min = INFINITY;
int minIndex = 0;
for (int j = 0; j < V; j++)
{
if(graph[i][j]!=0 && graph[i][j]<min)
if (graph[i][j] != 0 && graph[i][j] < min)
{
min=graph[i][j];
minIndex=j;
min = graph[i][j];
minIndex = j;
}
}
cout<<i<<" - "<<minIndex<<"\t"<<graph[i][minIndex]<<"\n";
cout << i << " - " << minIndex << "\t" << graph[i][minIndex] << "\n";
}
}
int main()
{
findMinimumEdge();

View File

@@ -8,9 +8,7 @@ int graph[V][V] = {
{0, 5, 1, 2},
{5, 0, 3, 3},
{1, 3, 0, 4},
{2, 3, 4, 0}
};
{2, 3, 4, 0}};
struct mst
{
@@ -25,39 +23,39 @@ void initilize()
{
for (int i = 0; i < V; i++)
{
MST_Array[i].visited=false;
MST_Array[i].key=INFINITY; // considering INFINITY as inifinity
MST_Array[i].near=i;
MST_Array[i].visited = false;
MST_Array[i].key = INFINITY; // considering INFINITY as inifinity
MST_Array[i].near = i;
}
MST_Array[0].key=0;
MST_Array[0].key = 0;
}
void updateNear()
{
for (int v = 0; v < V; v++)
{
int min=INFINITY;
int minIndex=0;
int min = INFINITY;
int minIndex = 0;
for (int i = 0; i < V; i++)
{
if (MST_Array[i].key<min && MST_Array[i].visited==false && MST_Array[i].key!=INFINITY)
if (MST_Array[i].key < min && MST_Array[i].visited == false && MST_Array[i].key != INFINITY)
{
min=MST_Array[i].key;
minIndex=i;
min = MST_Array[i].key;
minIndex = i;
}
}
MST_Array[minIndex].visited=true;
MST_Array[minIndex].visited = true;
for (int i = 0; i < V; i++)
{
if (graph[minIndex][i]!=0 && graph[minIndex][i]<INFINITY)
if (graph[minIndex][i] != 0 && graph[minIndex][i] < INFINITY)
{
if (graph[minIndex][i]<MST_Array[i].key)
if (graph[minIndex][i] < MST_Array[i].key)
{
MST_Array[i].key=graph[minIndex][i];
MST_Array[i].near=minIndex;
MST_Array[i].key = graph[minIndex][i];
MST_Array[i].near = minIndex;
}
}
}
@@ -68,11 +66,10 @@ void show()
{
for (int i = 0; i < V; i++)
{
cout<<i<<" - "<<MST_Array[i].near<<"\t"<<graph[i][MST_Array[i].near]<<"\n";
cout << i << " - " << MST_Array[i].near << "\t" << graph[i][MST_Array[i].near] << "\n";
}
}
int main()
{
initilize();

View File

@@ -1,117 +1,134 @@
#include<iostream>
#include<math.h>
#include <iostream>
#include <math.h>
using namespace std;
struct Node {
struct Node
{
int data;
struct Node *next;
} *head[100],*curr;
} * head[100], *curr;
void init() {
for(int i=0;i<100;i++)
head[i]=NULL;
void init()
{
for (int i = 0; i < 100; i++)
head[i] = NULL;
}
void add(int x,int h) {
void add(int x, int h)
{
struct Node *temp = new Node;
temp->data = x;
temp->next = NULL;
if(!head[h]) {
if (!head[h])
{
head[h] = temp;
curr = head[h];
}
else {
curr=head[h];
while(curr->next)
else
{
curr = head[h];
while (curr->next)
curr = curr->next;
curr->next = temp;
}
}
void display(int mod) {
void display(int mod)
{
struct Node *temp;
int i;
for(i=0;i<mod;i++) {
if(!head[i]) {
cout<<"Key "<<i<<" is empty"<<endl;
for (i = 0; i < mod; i++)
{
if (!head[i])
{
cout << "Key " << i << " is empty" << endl;
}
else {
cout<<"Key "<<i<<" has values = ";
else
{
cout << "Key " << i << " has values = ";
temp = head[i];
while(temp->next) {
cout<<temp->data<<" ";
temp=temp->next;
while (temp->next)
{
cout << temp->data << " ";
temp = temp->next;
}
cout<<temp->data;
cout<<endl;
cout << temp->data;
cout << endl;
}
}
}
int hash(int x,int mod) {
return x%mod;
int hash(int x, int mod)
{
return x % mod;
}
void find(int x,int h) {
struct Node *temp =head[h];
if(!head[h]) {
cout<<"Element not found";
void find(int x, int h)
{
struct Node *temp = head[h];
if (!head[h])
{
cout << "Element not found";
return;
}
while(temp->data !=x && temp->next)
temp=temp->next;
if(temp->next)
cout<<"Element found";
else{
if(temp->data == x)
cout<<"Element found";
while (temp->data != x && temp->next)
temp = temp->next;
if (temp->next)
cout << "Element found";
else
{
if (temp->data == x)
cout << "Element found";
else
cout<< "Element not found";
cout << "Element not found";
}
}
}
int main(void) {
int main(void)
{
init();
int c,x,mod,h;
cout<<"Enter the size of Hash Table. = ";
cin>>mod;
int c, x, mod, h;
cout << "Enter the size of Hash Table. = ";
cin >> mod;
bool loop = true;
while(loop) {
cout<<endl;
cout<<"PLEASE CHOOSE -"<<endl;
cout<<"1. Add element."<<endl;
cout<<"2. Find element."<<endl;
cout<<"3. Generate Hash."<<endl;
cout<<"4. Display Hash table."<<endl;
cout<<"5. Exit."<<endl;
cin>>c;
switch(c) {
case 1:
cout<<"Enter element to add = ";
cin>>x;
h = hash(x,mod);
h = fabs(h);
add(x,h);
break;
case 2:
cout<<"Enter element to search = ";
cin>>x;
h = hash(x,mod);
find(x,h);
break;
case 3:
cout<<"Enter element to generate hash = ";
cin>>x;
cout<<"Hash of "<<x<<" is = "<<hash(x,mod);
break;
case 4:
display(mod);
break;
default:
loop = false;
break;
while (loop)
{
cout << endl;
cout << "PLEASE CHOOSE -" << endl;
cout << "1. Add element." << endl;
cout << "2. Find element." << endl;
cout << "3. Generate Hash." << endl;
cout << "4. Display Hash table." << endl;
cout << "5. Exit." << endl;
cin >> c;
switch (c)
{
case 1:
cout << "Enter element to add = ";
cin >> x;
h = hash(x, mod);
h = fabs(h);
add(x, h);
break;
case 2:
cout << "Enter element to search = ";
cin >> x;
h = hash(x, mod);
find(x, h);
break;
case 3:
cout << "Enter element to generate hash = ";
cin >> x;
cout << "Hash of " << x << " is = " << hash(x, mod);
break;
case 4:
display(mod);
break;
default:
loop = false;
break;
}
cout<<endl;
cout << endl;
}
/*add(1,&head1);
add(2,&head1);

View File

@@ -14,14 +14,16 @@ using namespace std;
// for multiplication.
// This function may value of res_size
// and returns the new value of res_size
int multiply(int x, int res[], int res_size) {
int multiply(int x, int res[], int res_size)
{
// Initialize carry
int carry = 0;
// One by one multiply n with
// individual digits of res[]
for (int i = 0; i < res_size; i++) {
for (int i = 0; i < res_size; i++)
{
int prod = res[i] * x + carry;
// Store last digit of
@@ -34,7 +36,8 @@ int multiply(int x, int res[], int res_size) {
// Put carry in res and
// increase result size
while (carry) {
while (carry)
{
res[res_size] = carry % 10;
carry = carry / 10;
res_size++;
@@ -48,18 +51,19 @@ void power(int x, int n)
{
//printing value "1" for power = 0
if(n == 0 ){
cout<<"1";
if (n == 0)
{
cout << "1";
return;
}
int res[MAX];
int res_size = 0;
int temp = x;
// Initialize result
while (temp != 0) {
while (temp != 0)
{
res[res_size++] = temp % 10;
temp = temp / 10;
}
@@ -75,7 +79,8 @@ void power(int x, int n)
}
// Driver program
int main() {
int main()
{
int exponent, base;
printf("Enter base ");
scanf("%id \n", &base);

View File

@@ -6,7 +6,7 @@ using namespace std;
// Declaring variables for maintaing prime numbers and to check whether a number is prime or not
bool isprime[1000006];
vector<int> prime_numbers;
vector<pair<int,int> > factors;
vector<pair<int, int>> factors;
// Calculating prime number upto a given range
void SieveOfEratosthenes(int N)
@@ -14,21 +14,20 @@ void SieveOfEratosthenes(int N)
// initializes the array isprime
memset(isprime, true, sizeof isprime);
for(int i=2; i<=N ; i++)
for (int i = 2; i <= N; i++)
{
if(isprime[i])
if (isprime[i])
{
for(int j=2*i; j<=N; j+=i)
isprime[j]=false;
for (int j = 2 * i; j <= N; j += i)
isprime[j] = false;
}
}
for(int i=2; i<=N; i++)
for (int i = 2; i <= N; i++)
{
if(isprime[i])
if (isprime[i])
prime_numbers.push_back(i);
}
}
// Prime factorization of a number
@@ -37,9 +36,9 @@ void prime_factorization(int num)
int number = num;
for(int i=0; prime_numbers[i]<=num; i++)
for (int i = 0; prime_numbers[i] <= num; i++)
{
int count=0;
int count = 0;
// termination condition
if (number == 1)
@@ -47,17 +46,15 @@ void prime_factorization(int num)
break;
}
while(number%prime_numbers[i] == 0)
while (number % prime_numbers[i] == 0)
{
count++;
number = number/prime_numbers[i];
number = number / prime_numbers[i];
}
if(count)
factors.push_back(make_pair(prime_numbers[i],count));
if (count)
factors.push_back(make_pair(prime_numbers[i], count));
}
}
/*
@@ -68,16 +65,16 @@ int main()
int num;
cout << "\t\tComputes the prime factorization\n\n";
cout << "Type in a number: ";
cin>>num;
cin >> num;
SieveOfEratosthenes(num);
prime_factorization(num);
// Prime factors with their powers in the given number in new line
for(auto it: factors)
for (auto it : factors)
{
cout<<it.first<<" "<<it.second<<endl;
cout << it.first << " " << it.second << endl;
}
return 0;

View File

@@ -17,12 +17,16 @@ int isprime[MAX];
* This is the function that finds the primes and eliminates
* the multiples.
*/
void sieve(int N) {
void sieve(int N)
{
isprime[0] = 0;
isprime[1] = 0;
for (int i = 2; i <= N; i++) {
if (isprime[i]) {
for (int j = i * 2; j <= N; j += i) {
for (int i = 2; i <= N; i++)
{
if (isprime[i])
{
for (int j = i * 2; j <= N; j += i)
{
isprime[j] = 0;
}
}
@@ -32,9 +36,12 @@ void sieve(int N) {
/*
* This function prints out the primes to STDOUT
*/
void print(int N) {
for (int i = 1; i <= N; i++) {
if (isprime[i] == 1) {
void print(int N)
{
for (int i = 1; i <= N; i++)
{
if (isprime[i] == 1)
{
cout << i << ' ';
}
}
@@ -45,13 +52,16 @@ void print(int N) {
* NOTE: This function is important for the
* initialization of the array.
*/
void init() {
for (int i = 1; i < MAX; i++) {
void init()
{
for (int i = 1; i < MAX; i++)
{
isprime[i] = 1;
}
}
int main() {
int main()
{
int N = 100;
init();
sieve(N);

View File

@@ -1,30 +1,38 @@
#include<iostream>
#include <iostream>
using namespace std;
int main(){
int n,k;
cout<<"Enter size of array=\t";
cin>>n;
cout<<"Enter Number of indeces u want to rotate the array to left=\t";
cin>>k;
int main()
{
int n, k;
cout << "Enter size of array=\t";
cin >> n;
cout << "Enter Number of indeces u want to rotate the array to left=\t";
cin >> k;
int a[n];
cout<<"Enter elements of array=\t";
for(int i=0;i<n;i++){
cin>>a[i];
cout << "Enter elements of array=\t";
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
int temp=0;
for(int i=0;i<k;i++){
temp=a[0];
for(int j=0;j<n;j++){
if(j==n-1){
a[n-1]=temp;
int temp = 0;
for (int i = 0; i < k; i++)
{
temp = a[0];
for (int j = 0; j < n; j++)
{
if (j == n - 1)
{
a[n - 1] = temp;
}
else{
a[j]=a[j+1];
else
{
a[j] = a[j + 1];
}
}
}cout<<"Your rotated array is=\t";
for(int j=0;j<n;j++){
cout<<a[j]<<" ";
}
cout << "Your rotated array is=\t";
for (int j = 0; j < n; j++)
{
cout << a[j] << " ";
}
getchar();
return 0;

View File

@@ -1,31 +1,35 @@
#include <iostream>
using namespace std;
int main(){
int n,k;
cout<<"Enter size of array=\t";
cin>>n;
cout<<"Enter Number of indices u want to rotate the array to right=\t";
cin>>k;
int a[n];
cout<<"Enter elements of array=\t";
for(int i=0;i<n;i++)
cin>>a[i];
int temp=0;
for(int i=0;i<k;i++){
temp=a[n-1];
for(int j=n-1;j>=0;j--){
if(j==0){
a[j]=temp;
int main()
{
int n, k;
cout << "Enter size of array=\t";
cin >> n;
cout << "Enter Number of indices u want to rotate the array to right=\t";
cin >> k;
int a[n];
cout << "Enter elements of array=\t";
for (int i = 0; i < n; i++)
cin >> a[i];
int temp = 0;
for (int i = 0; i < k; i++)
{
temp = a[n - 1];
for (int j = n - 1; j >= 0; j--)
{
if (j == 0)
{
a[j] = temp;
}
else{
a[j]=a[j-1];}
}
else
{
a[j] = a[j - 1];
}
}
}
cout << "Your rotated array is=\t";
for (int i = 0; i < n; i++)
{
cout << a[i] << " ";
}
cout<<"Your rotated array is=\t";
for(int i=0;i<n;i++){
cout<<a[i]<<" ";
}
}

View File

@@ -1,4 +1,4 @@
#include<iostream>
#include <iostream>
using namespace std;
struct node
@@ -11,71 +11,69 @@ node *start;
void insert(int x)
{
node *t=start;
if (start!=NULL)
node *t = start;
if (start != NULL)
{
while(t->next!=start)
while (t->next != start)
{
t=t->next;
t = t->next;
}
node *n= new node;
t->next=n;
n->val=x;
n->next=start;
node *n = new node;
t->next = n;
n->val = x;
n->next = start;
}
else
{
node *n= new node;
n->val=x;
start=n;
n->next=start;
node *n = new node;
n->val = x;
start = n;
n->next = start;
}
}
void remove(int x)
{
node *t=start;
node *t = start;
node *p;
while(t->val!=x)
while (t->val != x)
{
p=t;
t=t->next;
p = t;
t = t->next;
}
p->next=t->next;
p->next = t->next;
delete t;
}
void search(int x)
{
node *t= start;
int found =0;
while(t->next!=start)
node *t = start;
int found = 0;
while (t->next != start)
{
if(t->val==x)
if (t->val == x)
{
cout<<"\nFound";
found=1;
cout << "\nFound";
found = 1;
break;
}
t=t->next;
t = t->next;
}
if(found==0)
if (found == 0)
{
cout<<"\nNot Found";
cout << "\nNot Found";
}
}
void show()
{
node *t=start;
node *t = start;
do
{
cout<<t->val<<"\t";
t=t->next;
}
while(t!=start);
cout << t->val << "\t";
t = t->next;
} while (t != start);
}
int main()
@@ -83,27 +81,34 @@ int main()
int choice, x;
do
{
cout<<"\n1. Insert";
cout<<"\n2. Delete";
cout<<"\n3. Search";
cout<<"\n4. Print";
cout<<"\n\nEnter you choice : ";
cin>>choice;
cout << "\n1. Insert";
cout << "\n2. Delete";
cout << "\n3. Search";
cout << "\n4. Print";
cout << "\n\nEnter you choice : ";
cin >> choice;
switch (choice)
{
case 1 : cout<<"\nEnter the element to be inserted : ";
cin>>x;
insert(x); break;
case 2 : cout<<"\nEnter the element to be removed : ";
cin>>x;
remove(x); break;
case 3 : cout<<"\nEnter the element to be searched : ";
cin>>x;
search(x); break;
case 4 : show(); break;
case 1:
cout << "\nEnter the element to be inserted : ";
cin >> x;
insert(x);
break;
case 2:
cout << "\nEnter the element to be removed : ";
cin >> x;
remove(x);
break;
case 3:
cout << "\nEnter the element to be searched : ";
cin >> x;
search(x);
break;
case 4:
show();
break;
}
}
while(choice!=0);
} while (choice != 0);
return 0;
}

View File

@@ -1,47 +1,46 @@
#include<iostream>
#include <iostream>
using namespace std;
int queue[10];
int front=0;
int rear=0;
int count=0;
int front = 0;
int rear = 0;
int count = 0;
void Enque(int x)
{
if(count==10)
if (count == 10)
{
cout<<"\nOverflow";
cout << "\nOverflow";
}
else
{
queue[rear]=x;
rear=(rear+1)%10;
queue[rear] = x;
rear = (rear + 1) % 10;
count++;
}
}
void Deque()
{
if (front==rear)
if (front == rear)
{
cout<<"\nUnderflow";
cout << "\nUnderflow";
}
else
{
cout<<"\n"<<queue[front]<<" deleted";
front=(front+1)%10;
cout << "\n"
<< queue[front] << " deleted";
front = (front + 1) % 10;
count--;
}
}
void show()
{
for (int i = 0; i<count; i++)
for (int i = 0; i < count; i++)
{
cout<<queue[(i+front)%10]<<"\t";
cout << queue[(i + front) % 10] << "\t";
}
}
@@ -50,28 +49,26 @@ int main()
int ch, x;
do
{
cout<<"\n1. Enque";
cout<<"\n2. Deque";
cout<<"\n3. Print";
cout<<"\nEnter Your Choice : ";
cin>>ch;
if (ch==1)
cout << "\n1. Enque";
cout << "\n2. Deque";
cout << "\n3. Print";
cout << "\nEnter Your Choice : ";
cin >> ch;
if (ch == 1)
{
cout<<"\nInsert : ";
cin>>x;
cout << "\nInsert : ";
cin >> x;
Enque(x);
}
else if (ch==2)
else if (ch == 2)
{
Deque();
}
else if (ch==3)
else if (ch == 3)
{
show();
}
}
while(ch!=0);
} while (ch != 0);
return 0;
}

View File

@@ -1,28 +1,29 @@
#include <iostream>
int main()
{
int i,j,m,n;
cout <<"Enter size of array 1:";
int i, j, m, n;
cout << "Enter size of array 1:";
cin >> m;
cout <<"Enter size of array 2:";
cout << "Enter size of array 2:";
cin >> n;
int a[m];
int b[n];
cout <<"Enter elements of array 1:";
for(i=0;i<m;i++)
cin >> a[i];
for(i=0;i<n;i++)
cin >> b[i];
i=0;j=0;
while((i<m)&&(j<n))
cout << "Enter elements of array 1:";
for (i = 0; i < m; i++)
cin >> a[i];
for (i = 0; i < n; i++)
cin >> b[i];
i = 0;
j = 0;
while ((i < m) && (j < n))
{
if(a[i]<b[j])
i++;
else if(a[i]>b[j])
j++;
if (a[i] < b[j])
i++;
else if (a[i] > b[j])
j++;
else
{
cout << a[i++]<<" ";
cout << a[i++] << " ";
j++;
}
}

View File

@@ -1,4 +1,4 @@
#include<iostream>
#include <iostream>
using namespace std;
struct node
@@ -11,24 +11,24 @@ node *start;
void insert(int x)
{
node *t=start;
if (start!=NULL)
node *t = start;
if (start != NULL)
{
while(t->next!=NULL)
while (t->next != NULL)
{
t=t->next;
t = t->next;
}
node *n= new node;
t->next=n;
n->val=x;
n->next=NULL;
node *n = new node;
t->next = n;
n->val = x;
n->next = NULL;
}
else
{
node *n= new node;
n->val=x;
n->next=NULL;
start=n;
node *n = new node;
n->val = x;
n->next = NULL;
start = n;
}
}
@@ -36,30 +36,27 @@ void reverse(node *p, node *q)
{
if (q->next == NULL)
{
q->next=p;
p->next=NULL;
start=q;
q->next = p;
p->next = NULL;
start = q;
return;
}
else
{
reverse(q, q->next);
q->next=p;
p->next=NULL;
q->next = p;
p->next = NULL;
}
}
void show()
{
node *t=start;
while(t!=NULL)
node *t = start;
while (t != NULL)
{
cout<<t->val<<"\t";
t=t->next;
cout << t->val << "\t";
t = t->next;
}
}
int main()
@@ -75,6 +72,5 @@ int main()
show();
return 0;
}

View File

@@ -1,33 +1,34 @@
#include <iostream>
int main()
{
int m,n,i=0,j=0;
cout << "Enter size of both arrays:";
cin >> m >> n;
int a[m];
int b[n];
cout << "Enter elements of array 1:";
for(i=0;i<m;i++)
cin >>a[i];
cout << "Enter elements of array 2:";
for(i=0;i<n;i++)
int m, n, i = 0, j = 0;
cout << "Enter size of both arrays:";
cin >> m >> n;
int a[m];
int b[n];
cout << "Enter elements of array 1:";
for (i = 0; i < m; i++)
cin >> a[i];
cout << "Enter elements of array 2:";
for (i = 0; i < n; i++)
cin >> b[i];
i=0;j=0;
while((i<m)&&(j<n))
{
if(a[i]<b[j])
cout << a[i++] <<" ";
else if(a[i]>b[j])
cout << b[j++] <<" ";
i = 0;
j = 0;
while ((i < m) && (j < n))
{
if (a[i] < b[j])
cout << a[i++] << " ";
else if (a[i] > b[j])
cout << b[j++] << " ";
else
{
cout << a[i++];
j++;
}
}
while(i<m)
cout<< a[i++] <<" ";
while(j<n)
cout<< b[j++]<<" ";
return 0;
}
while (i < m)
cout << a[i++] << " ";
while (j < n)
cout << b[j++] << " ";
return 0;
}

View File

@@ -1,41 +1,39 @@
#include <iostream>
using namespace std;
//node defined
class node
{
public:
int data;
node* link;
node *link;
node(int d)
{
data = d;
link = NULL;
}
};
//printing the linked list
void print(node* head)
void print(node *head)
{
node* current = head;
node *current = head;
while (current != NULL)
{
cout << current->data << " ";
current = current-> link;
current = current->link;
}
cout << endl;
}
//creating the linked list with 'n' nodes
node* createlist(int n)
node *createlist(int n)
{
node* head = NULL;
node* t = NULL;
node *head = NULL;
node *t = NULL;
for (int i = 0; i < n; i++)
{
node* temp = NULL;
node *temp = NULL;
int num;
cin >> num;
temp = new node(num);
@@ -45,58 +43,58 @@ node* createlist(int n)
t = temp;
continue;
}
if (t->link == NULL) t->link = temp;
if (t->link == NULL)
t->link = temp;
t = temp;
}
return head;
}
//performing selection sort on the linked list in an iterative manner
void my_selection_sort_linked_list(node* &head)
void my_selection_sort_linked_list(node *&head)
{
node* min = head; //throughout the algorithm 'min' is used to denote the node with min value out of all the nodes left for scanning
//while scanning if we find a node 'X' with value lesser than min,
//then we update the pointers in such a way that 'X' becomes the predecessor of 'min'
node* current = min->link; // 'current' refers to the current node we are scanning
node* previous = min; //'previous' refers to the node that is previous to the current node
node* temp = NULL; // 'temp' in this algo is used to point to the last node of the sorted part of the linked list.
//eg. If at any time instance the state of the linked list is suppose 1->2->5->3->8->NULL
//then, we see that "1->2" is the sorted part of the LL, and therefore temp will be pointing to the last node of the sorted part,i.e,'2'
//We keep on arranging the Linked list in such a way that after each iteration the node with 'min' value is placed at its correct position.
//Eg. Let suppose initially we have 5->4->1->3->2->NULL
//After 1st iteration : 1->4->5->3->2->NULL and so on
while (min->link != NULL) //so that all the nodes are scanned or until there exists a node
{
//pick the first node from the unsorted part and assume that it is the minimum and then start scanning from the next node
node *min = head; //throughout the algorithm 'min' is used to denote the node with min value out of all the nodes left for scanning
//while scanning if we find a node 'X' with value lesser than min,
//then we update the pointers in such a way that 'X' becomes the predecessor of 'min'
node *current = min->link; // 'current' refers to the current node we are scanning
node *previous = min; //'previous' refers to the node that is previous to the current node
node *temp = NULL; // 'temp' in this algo is used to point to the last node of the sorted part of the linked list.
//eg. If at any time instance the state of the linked list is suppose 1->2->5->3->8->NULL
//then, we see that "1->2" is the sorted part of the LL, and therefore temp will be pointing to the last node of the sorted part,i.e,'2'
//We keep on arranging the Linked list in such a way that after each iteration the node with 'min' value is placed at its correct position.
//Eg. Let suppose initially we have 5->4->1->3->2->NULL
//After 1st iteration : 1->4->5->3->2->NULL and so on
while (current != NULL) //suppose you choose the min node to be X, then scan starts from the (X+1)th node until its NULL. current = (X+1)th node and min = X
while (min->link != NULL) //so that all the nodes are scanned or until there exists a node
{
//pick the first node from the unsorted part and assume that it is the minimum and then start scanning from the next node
while (current != NULL) //suppose you choose the min node to be X, then scan starts from the (X+1)th node until its NULL. current = (X+1)th node and min = X
{
if (current->data < min->data) //if the current node is smaller than the presumed node 'min'
if (current->data < min->data) //if the current node is smaller than the presumed node 'min'
{
if (temp == NULL) //temp stays null for the first iteration, therefore it symbolizes that we are scanning for the first time
if (temp == NULL) //temp stays null for the first iteration, therefore it symbolizes that we are scanning for the first time
{
if (previous == min) //if the 'previous' is pointing to the 'min' node
if (previous == min) //if the 'previous' is pointing to the 'min' node
{
//Update the pointers
head = current; //update the head pointer with the current node
//Update the pointers
head = current; //update the head pointer with the current node
min->link = current->link;
current->link = previous;
min = current;
current = previous->link;
}
else //if the 'previous' is not pointing to the 'min' node
else //if the 'previous' is not pointing to the 'min' node
{
//Update the pointers
head = current; //update the head pointer with the current node
//Update the pointers
head = current; //update the head pointer with the current node
previous->link = current->link;
current->link = min;
min = current;
current = previous->link;
}
}
else //if 'temp' is not NULL, i.e., its not the 1st iteration
else //if 'temp' is not NULL, i.e., its not the 1st iteration
{
temp->link = current;
previous->link = current->link;
@@ -105,15 +103,15 @@ void my_selection_sort_linked_list(node* &head)
current = previous->link;
}
}
else //if the current node is greater than min, just move the previous and the current pointer a step further
else //if the current node is greater than min, just move the previous and the current pointer a step further
{
previous = previous->link;
current = current->link;
}
}
//update the pointers. Set 'temp' to the last node in the sorted part. Make 'min' move a step further so that 'min' points to the 1st node of the unsorted part
//start the iteration again
//update the pointers. Set 'temp' to the last node in the sorted part. Make 'min' move a step further so that 'min' points to the 1st node of the unsorted part
//start the iteration again
temp = min;
min = min->link;
previous = min;
@@ -133,7 +131,6 @@ void my_selection_sort_linked_list(node* &head)
// original list is : -1 -2 -3
// sorted list is : -3 -2 -1
// enter the no. of nodes : 8
// 8 7 6 5 4 3 2 1
// original list is : 8 7 6 5 4 3 2 1
@@ -144,19 +141,19 @@ void my_selection_sort_linked_list(node* &head)
// original list is : 5 3 4 1 -2 -4
// sorted list is : -4 -2 1 3 4 5
int main()
{
node* head = NULL;
node *head = NULL;
int n;
cout << "enter the no. of nodes : "; //taking input from user about the number of nodes in linked list
cout << "enter the no. of nodes : "; //taking input from user about the number of nodes in linked list
cin >> n;
if (n == 0) return 0;
head = createlist(n); //creating the list
if (n == 0)
return 0;
head = createlist(n); //creating the list
cout << "original list is : ";
print(head); //printing the original linked list
my_selection_sort_linked_list(head); //applying selection sort
print(head); //printing the original linked list
my_selection_sort_linked_list(head); //applying selection sort
cout << "sorted list is : ";
print(head); //printing the sorted linked list
print(head); //printing the sorted linked list
return 0;
}

View File

@@ -3,15 +3,15 @@
using namespace std;
int main()
{
int n,t;
int n, t;
cin >> t;
while(t--)
while (t--)
{
cin >> n;
if((n%7==0)||(n%10==7))
cout << n << " is a buzz number" << endl;
else
cout << n << " is not a buzz number" << endl;
cin >> n;
if ((n % 7 == 0) || (n % 10 == 7))
cout << n << " is a buzz number" << endl;
else
cout << n << " is not a buzz number" << endl;
}
return 0;
}

View File

@@ -1,4 +1,4 @@
// This function convert decimal to binary number
// This function convert decimal to binary number
//
#include <iostream>
using namespace std;
@@ -10,13 +10,14 @@ int main()
cin >> number;
int remainder, binary = 0, var = 1;
do {
remainder = number % 2;
number = number / 2;
binary = binary + (remainder*var);
do
{
remainder = number % 2;
number = number / 2;
binary = binary + (remainder * var);
var = var * 10;
} while (number>0);
} while (number > 0);
cout << "the binary is :";
cout << binary;
cout << endl;

View File

@@ -2,25 +2,27 @@
using namespace std;
int main(void){
int main(void)
{
int valueToConvert = 0; //Holds user input
int hexArray[8]; //Contains hex values backwards
int i = 0; //counter
int hexArray[8]; //Contains hex values backwards
int i = 0; //counter
char HexValues[] = "0123456789ABCDEF";
cout << "Enter a Decimal Value" << endl; //Displays request to stdout
cin >> valueToConvert; //Stores value into valueToConvert via user input
cin >> valueToConvert; //Stores value into valueToConvert via user input
while (valueToConvert > 15){ //Dec to Hex Algorithm
hexArray[i++] = valueToConvert % 16; //Gets remainder
while (valueToConvert > 15)
{ //Dec to Hex Algorithm
hexArray[i++] = valueToConvert % 16; //Gets remainder
valueToConvert /= 16;
}
hexArray[i] = valueToConvert; //Gets last value
hexArray[i] = valueToConvert; //Gets last value
cout << "Hex Value: ";
while (i >= 0)
cout<<HexValues[hexArray[i--]];
cout << HexValues[hexArray[i--]];
cout << endl;
return 0;
}

View File

@@ -8,50 +8,77 @@
using namespace std;
//This functions fills a string with character c, n times and returns it
string fill( char c, int n )
string fill(char c, int n)
{
string s = "";
while( n-- ) s += c;
while (n--)
s += c;
return s;
}
//to convert to lowercase Roman Numeral
// the function works recursively
string tolowerRoman( int n )
string tolowerRoman(int n)
{
if( n < 4 ) return fill( 'i', n );
if( n < 6 ) return fill( 'i', 5 - n ) + "v";
if( n < 9 ) return string( "v" ) + fill( 'i', n - 5 );
if( n < 11 ) return fill( 'i', 10 - n ) + "x";
if( n < 40 ) return fill( 'x', n / 10 ) + tolowerRoman( n % 10 );
if( n < 60 ) return fill( 'x', 5 - n / 10 ) + 'l' + tolowerRoman( n % 10 );
if( n < 90 ) return string( "l" ) + fill( 'x', n / 10 - 5 ) + tolowerRoman( n % 10 );
if( n < 110 ) return fill( 'x', 10 - n / 10 ) + "c" + tolowerRoman( n % 10 );
if( n < 400 ) return fill( 'c', n / 100 ) + tolowerRoman( n % 100 );
if( n < 600 ) return fill( 'c', 5 - n / 100 ) + 'd' + tolowerRoman( n % 100 );
if( n < 900 ) return string( "d" ) + fill( 'c', n / 100 - 5 ) + tolowerRoman( n % 100 );
if( n < 1100 ) return fill( 'c', 10 - n / 100 ) + "m" + tolowerRoman( n % 100 );
if( n < 4000 ) return fill( 'm', n / 1000 ) + tolowerRoman( n % 1000 );
if (n < 4)
return fill('i', n);
if (n < 6)
return fill('i', 5 - n) + "v";
if (n < 9)
return string("v") + fill('i', n - 5);
if (n < 11)
return fill('i', 10 - n) + "x";
if (n < 40)
return fill('x', n / 10) + tolowerRoman(n % 10);
if (n < 60)
return fill('x', 5 - n / 10) + 'l' + tolowerRoman(n % 10);
if (n < 90)
return string("l") + fill('x', n / 10 - 5) + tolowerRoman(n % 10);
if (n < 110)
return fill('x', 10 - n / 10) + "c" + tolowerRoman(n % 10);
if (n < 400)
return fill('c', n / 100) + tolowerRoman(n % 100);
if (n < 600)
return fill('c', 5 - n / 100) + 'd' + tolowerRoman(n % 100);
if (n < 900)
return string("d") + fill('c', n / 100 - 5) + tolowerRoman(n % 100);
if (n < 1100)
return fill('c', 10 - n / 100) + "m" + tolowerRoman(n % 100);
if (n < 4000)
return fill('m', n / 1000) + tolowerRoman(n % 1000);
return "?";
}
//to convert to uppercase Roman Numeral
// the function works recursively
string toupperRoman( int n )
string toupperRoman(int n)
{
if( n < 4 ) return fill( 'I', n );
if( n < 6 ) return fill( 'I', 5 - n ) + "V";
if( n < 9 ) return string( "V" ) + fill( 'I', n - 5 );
if( n < 11 ) return fill( 'I', 10 - n ) + "X";
if( n < 40 ) return fill( 'X', n / 10 ) + toupperRoman( n % 10 );
if( n < 60 ) return fill( 'X', 5 - n / 10 ) + 'L' + toupperRoman( n % 10 );
if( n < 90 ) return string( "L" ) + fill( 'X', n / 10 - 5 ) + toupperRoman( n % 10 );
if( n < 110 ) return fill( 'X', 10 - n / 10 ) + "C" + toupperRoman( n % 10 );
if( n < 400 ) return fill( 'C', n / 100 ) + toupperRoman( n % 100 );
if( n < 600 ) return fill( 'C', 5 - n / 100 ) + 'D' + toupperRoman( n % 100 );
if( n < 900 ) return string( "D" ) + fill( 'C', n / 100 - 5 ) + toupperRoman( n % 100 );
if( n < 1100 ) return fill( 'C', 10 - n / 100 ) + "M" + toupperRoman( n % 100 );
if( n < 4000 ) return fill( 'M', n / 1000 ) + toupperRoman( n % 1000 );
if (n < 4)
return fill('I', n);
if (n < 6)
return fill('I', 5 - n) + "V";
if (n < 9)
return string("V") + fill('I', n - 5);
if (n < 11)
return fill('I', 10 - n) + "X";
if (n < 40)
return fill('X', n / 10) + toupperRoman(n % 10);
if (n < 60)
return fill('X', 5 - n / 10) + 'L' + toupperRoman(n % 10);
if (n < 90)
return string("L") + fill('X', n / 10 - 5) + toupperRoman(n % 10);
if (n < 110)
return fill('X', 10 - n / 10) + "C" + toupperRoman(n % 10);
if (n < 400)
return fill('C', n / 100) + toupperRoman(n % 100);
if (n < 600)
return fill('C', 5 - n / 100) + 'D' + toupperRoman(n % 100);
if (n < 900)
return string("D") + fill('C', n / 100 - 5) + toupperRoman(n % 100);
if (n < 1100)
return fill('C', 10 - n / 100) + "M" + toupperRoman(n % 100);
if (n < 4000)
return fill('M', n / 1000) + toupperRoman(n % 1000);
return "?";
}
@@ -60,11 +87,11 @@ string toupperRoman( int n )
int main()
{
int n;
cout << "\t\tRoman numbers converter\n\n";
cout << "Type in decimal number between 0 up to 4000 (exclusive): ";
cin >> n;
cout << n << " in Upper Roman Numerals is " << toupperRoman(n) << "\n";
cout << n << " in Lower Roman Numerals is " << tolowerRoman(n) << "\n";
return 0;
int n;
cout << "\t\tRoman numbers converter\n\n";
cout << "Type in decimal number between 0 up to 4000 (exclusive): ";
cin >> n;
cout << n << " in Upper Roman Numerals is " << toupperRoman(n) << "\n";
cout << n << " in Lower Roman Numerals is " << tolowerRoman(n) << "\n";
return 0;
}

View File

@@ -3,21 +3,21 @@
using namepsace std;
int main()
{
cout <<"Enter value of n:"<<endl;
cout << "Enter value of n:" << endl;
cin >> n;
int a[n];
int i,j,gcd;
int i, j, gcd;
cout << "Enter the n numbers:" << endl;
for(i=0;i<n;i++)
for (i = 0; i < n; i++)
cin >> a[i];
j=1; //to access all elements of the array starting from 1
gcd=a[0];
while(j<n)
j = 1; //to access all elements of the array starting from 1
gcd = a[0];
while (j < n)
{
if(a[j]%gcd==0) //value of gcd is as needed so far
j++; //so we check for next element
if (a[j] % gcd == 0) //value of gcd is as needed so far
j++; //so we check for next element
else
gcd=a[j]%gcd; //calculating GCD by division method
gcd = a[j] % gcd; //calculating GCD by division method
}
cout << "GCD of entered n numbers:" << gcd;
}

View File

@@ -5,24 +5,25 @@ using namespace std;
int main()
{
int n,k,s=0,d;
int n, k, s = 0, d;
cout << "Enter a number:";
cin >> n;
s=0;k=n;
while(k>9)
s = 0;
k = n;
while (k > 9)
{
while(k!=0)
while (k != 0)
{
d=k%10;
s+=d;
k/=10;
d = k % 10;
s += d;
k /= 10;
}
k=s;
s=0;
k = s;
s = 0;
}
if(k==1)
cout << n << " is a happy number" << endl;
if (k == 1)
cout << n << " is a happy number" << endl;
else
cout << n << " is not a happy number" << endl;
cout << n << " is not a happy number" << endl;
return 0;
}

View File

@@ -12,12 +12,12 @@ int main()
string s1 = to_string(num);
string s2 = s1;
reverse(s1.begin(),s1.end());
reverse(s1.begin(), s1.end());
if(s1 == s2)
cout<<"true";
if (s1 == s2)
cout << "true";
else
cout<<"false";
cout << "false";
return 0;
}

View File

@@ -1,5 +1,5 @@
#include<iostream>
#include<string>
#include <iostream>
#include <string>
using namespace std;
@@ -10,55 +10,66 @@ using namespace std;
char stack[MAX];
int top = -1;
void push(char ch){
stack[ ++top ] = ch;
void push(char ch)
{
stack[++top] = ch;
}
char pop(){
return stack[ top-- ];
char pop()
{
return stack[top--];
}
// -------------- end stack -----------
char opening(char ch){
switch(ch){
case '}':
return '{';
case ']':
return '[';
case ')':
return '(';
case '>':
return '<';
char opening(char ch)
{
switch (ch)
{
case '}':
return '{';
case ']':
return '[';
case ')':
return '(';
case '>':
return '<';
}
}
int main(){
int main()
{
string exp;
int valid = 1, i = 0;
cout<<"Enter The Expression : ";
cout << "Enter The Expression : ";
cin >> exp;
while (valid == 1 && i < exp.length()){
if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[' || exp[i] == '<'){
push(exp[i]);
}
else if (top >= 0 && stack[top] == opening(exp[i])){
pop();
}
else{
valid = 0;
}
i++;
while (valid == 1 && i < exp.length())
{
if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[' || exp[i] == '<')
{
push(exp[i]);
}
else if (top >= 0 && stack[top] == opening(exp[i]))
{
pop();
}
else
{
valid = 0;
}
i++;
}
// makes sure the stack is empty after processsing (above)
if (valid == 1 && top == -1){
cout<<"\nCorrect Expression";
// makes sure the stack is empty after processsing (above)
if (valid == 1 && top == -1)
{
cout << "\nCorrect Expression";
}
else{
cout<<"\nWrong Expression";
else
{
cout << "\nWrong Expression";
}
return 0;

View File

@@ -1,33 +1,32 @@
#include <iostream>
using namespace std;
//A simple and efficient implementation of a function to test if a number is prime, based on the fact that
//Every Prime number, except 2 and 3 are of the form 6*k+1 or 6*k-1 for integer values of k.
bool IsPrime( int number )
{
if ( ( (!(number & 1)) && number != 2 ) || (number < 2) || (number % 3 == 0 && number != 3) )
return false;
for( int k = 1; 36*k*k-12*k < number;++k)
{
if ( (number % (6*k+1) == 0) || (number % (6*k-1) == 0) )
return false;
}
return true;
}
int main()
{
//Main Function
cout <<"Enter the value of n to check if Prime\n";
int n;
cin >> n;
if(IsPrime(n))
cout << n << " is Prime" <<endl;
else
cout << n << " is not Prime" <<endl;
return 0;
}
//A simple and efficient implementation of a function to test if a number is prime, based on the fact that
//Every Prime number, except 2 and 3 are of the form 6*k+1 or 6*k-1 for integer values of k.
bool IsPrime(int number)
{
if (((!(number & 1)) && number != 2) || (number < 2) || (number % 3 == 0 && number != 3))
return false;
for (int k = 1; 36 * k * k - 12 * k < number; ++k)
{
if ((number % (6 * k + 1) == 0) || (number % (6 * k - 1) == 0))
return false;
}
return true;
}
int main()
{
//Main Function
cout << "Enter the value of n to check if Prime\n";
int n;
cin >> n;
if (IsPrime(n))
cout << n << " is Prime" << endl;
else
cout << n << " is not Prime" << endl;
return 0;
}

View File

@@ -5,8 +5,8 @@ using namespace std;
int main()
{
int m,n;
int counterZeros=0;
int m, n;
int counterZeros = 0;
cout << "Enter dimensions of matrix (seperated with space): ";
cin >> m >> n;
int a[m][n];
@@ -14,28 +14,28 @@ int main()
cout << "\n";
// reads the matrix from stdin
for(int i=0;i<m;i++)
for (int i = 0; i < m; i++)
{
for(int j=0;j<n;j++)
for (int j = 0; j < n; j++)
{
cout << "element? ";
cin >> a[i][j];
cout << "element? ";
cin >> a[i][j];
}
}
// counts the zero's
for(int i=0;i<m;i++)
for (int i = 0; i < m; i++)
{
for(int j=0;j<n;j++)
for (int j = 0; j < n; j++)
{
if(a[i][j]==0)
counterZeros++; //Counting number of zeroes
if (a[i][j] == 0)
counterZeros++; //Counting number of zeroes
}
}
// makes sure the matrix is a sparse matrix
if(counterZeros>((m*n)/2)) //Checking for sparse matrix
cout << "Sparse matrix";
if (counterZeros > ((m * n) / 2)) //Checking for sparse matrix
cout << "Sparse matrix";
else
cout << "Not a sparse matrix";
cout << "Not a sparse matrix";
}

View File

@@ -3,55 +3,51 @@ using namespace std;
Multiply(int A[][], int B[][], int n)
{
if (n==2)
if (n == 2)
{
int p1= (a[0][0] + a[1][1])*(b[0][0]+b[1][1]);
int p2= (a[1][0]+a[1][1])*b[0][0];
int p3= a[0][0]*(b[0][1]-b[1][1]);
int p4= a[1][1]*(b[1][0]-b[0][0]);
int p5= (a[0][0]+a[0][1])*b[1][1];
int p6= (a[1][0]-a[0][0])*(b[0][0]+b[0][1]);
int p7= (a[0][1]-a[1][1])*(b[1][0]+b[1][1]);
int p1 = (a[0][0] + a[1][1]) * (b[0][0] + b[1][1]);
int p2 = (a[1][0] + a[1][1]) * b[0][0];
int p3 = a[0][0] * (b[0][1] - b[1][1]);
int p4 = a[1][1] * (b[1][0] - b[0][0]);
int p5 = (a[0][0] + a[0][1]) * b[1][1];
int p6 = (a[1][0] - a[0][0]) * (b[0][0] + b[0][1]);
int p7 = (a[0][1] - a[1][1]) * (b[1][0] + b[1][1]);
int c[n][n];
c[0][0] = p1 + p4 - p5 + p7;
c[0][1] = p3 + p5;
c[1][0] = p2 + p4;
c[1][1] = p1 - p2 + p3 + p6;
int c[n][n];
c[0][0]=p1+p4-p5+p7;
c[0][1]=p3+p5;
c[1][0]=p2+p4;
c[1][1]=p1-p2+p3+p6;
return c[][];
return c[][];
}
else
{
}
}
int main()
{
int p,q,r,s;
cout<<"Enter the dimensions of Matrices";
cin>>n;
int A[n][n],;
int B[n][n],;
cout<<"Enter the elements of Matrix A";
int p, q, r, s;
cout << "Enter the dimensions of Matrices";
cin >> n;
int A[n][n], ;
int B[n][n], ;
cout << "Enter the elements of Matrix A";
for (int i = 0; i < n; i++)
{
for (int j = 0; j <n ; j++)
for (int j = 0; j < n; j++)
{
cin>>A[i][j];
cin >> A[i][j];
}
}
cout<<"Enter the elements of Matrix B";
cout << "Enter the elements of Matrix B";
for (int i = 0; i < n; i++)
{
for (int j = 0; j <n ; j++)
for (int j = 0; j < n; j++)
{
cin>>B[i][j];
cin >> B[i][j];
}
}

View File

@@ -2,7 +2,6 @@
//The method used is manual addition with carry and placing it in a string which is called string addition
//This makes it have no bounds or limits
#include <iostream>
#include <string>
@@ -69,10 +68,9 @@ void fib_Accurate(long long n)
fibMinus2 = fibMinus1;
fibMinus1 = tmp;
}
cout << fibMinus2;
cout << fibMinus2;
}
int main()
{
int n;

View File

@@ -1,88 +1,73 @@
#include<iostream>
#include <iostream>
using namespace std;
struct tower
{
int values[10];
int top;
}F, U, T;
} F, U, T;
void show()
{
cout<<"\n\n\tF : ";
for(int i=0; i<F.top; i++)
cout << "\n\n\tF : ";
for (int i = 0; i < F.top; i++)
{
cout<<F.values[i]<<"\t";
cout << F.values[i] << "\t";
}
cout<<"\n\tU : ";
for(int i=0; i<U.top; i++)
cout << "\n\tU : ";
for (int i = 0; i < U.top; i++)
{
cout<<U.values[i]<<"\t";
cout << U.values[i] << "\t";
}
cout<<"\n\tT : ";
for(int i=0; i<T.top; i++)
cout << "\n\tT : ";
for (int i = 0; i < T.top; i++)
{
cout<<T.values[i]<<"\t";
cout << T.values[i] << "\t";
}
}
void mov(tower &From, tower &To)
{
--From.top;
To.values[To.top]=From.values[From.top];
To.values[To.top] = From.values[From.top];
++To.top;
}
void TH(int n, tower &From, tower &Using, tower &To)
{
if (n==1)
if (n == 1)
{
mov(From, To);
show();
}
else
{
TH(n-1, From, To, Using);
TH(n - 1, From, To, Using);
mov(From, To);
show();
TH(n-1, Using, From, To);
TH(n - 1, Using, From, To);
}
}
int main()
{
F.top=0;
U.top=0;
T.top=0;
F.top = 0;
U.top = 0;
T.top = 0;
int no;
cout << "\nEnter number of discs : " ;
cout << "\nEnter number of discs : ";
cin >> no;
for (int i = no; i >0; i--)
for (int i = no; i > 0; i--)
{
F.values[F.top++]=i;
F.values[F.top++] = i;
};
show();
TH(no, F, U, T);
return 0;
}

View File

@@ -6,14 +6,12 @@
//It is a property of fibonacci similar to matrix exponentiation.
#include <iostream>
#include<cstdio>
#include <cstdio>
using namespace std;
const long long MAX = 93;
long long f[MAX] = {0};
long long fib(long long n)
{
@@ -22,26 +20,23 @@ long long fib(long long n)
return 0;
if (n == 1 || n == 2)
return (f[n] = 1);
if (f[n])
return f[n];
long long k = (n%2!=0)? (n+1)/2 : n/2;
f[n] = (n%2!=0)? (fib(k)*fib(k) + fib(k-1)*fib(k-1))
: (2*fib(k-1) + fib(k))*fib(k);
long long k = (n % 2 != 0) ? (n + 1) / 2 : n / 2;
f[n] = (n % 2 != 0) ? (fib(k) * fib(k) + fib(k - 1) * fib(k - 1))
: (2 * fib(k - 1) + fib(k)) * fib(k);
return f[n];
}
int main()
{
//Main Function
for(long long i=1;i<93;i++)
{
cout << i << " th fibonacci number is " << fib(i) << "\n";
}
return 0;
//Main Function
for (long long i = 1; i < 93; i++)
{
cout << i << " th fibonacci number is " << fib(i) << "\n";
}
return 0;
}

View File

@@ -13,7 +13,6 @@ using namespace std;
int primes[MAX];
/*
* This is the function that finds the primes and eliminates
* the multiples.
@@ -22,12 +21,13 @@ void sieve(int N)
{
primes[0] = 1;
primes[1] = 1;
for(int i=2;i<=N;i++)
{
if(primes[i] == 1) continue;
for(int j=i+i;j<=N;j+=i)
primes[j] = 1;
}
for (int i = 2; i <= N; i++)
{
if (primes[i] == 1)
continue;
for (int j = i + i; j <= N; j += i)
primes[j] = 1;
}
}
/*
@@ -35,8 +35,8 @@ void sieve(int N)
*/
void print(int N)
{
for(int i=0;i<=N;i++)
if(primes[i] == 0)
for (int i = 0; i <= N; i++)
if (primes[i] == 0)
cout << i << ' ';
cout << '\n';
}
@@ -47,7 +47,7 @@ void print(int N)
*/
void init()
{
for(int i=0;i<MAX;i++)
for (int i = 0; i < MAX; i++)
primes[i] = 0;
}

View File

@@ -4,7 +4,8 @@
using namespace std;
struct Point {
struct Point
{
double x, y;
Point(double a = 0.0, double b = 0.0)
{
@@ -15,7 +16,7 @@ struct Point {
double LenghtLine(Point A, Point B)
{
return sqrt(abs((B.x - A.x)*(B.x - A.x)) + abs((B.y - A.y)*(B.y - A.y)));
return sqrt(abs((B.x - A.x) * (B.x - A.x)) + abs((B.y - A.y) * (B.y - A.y)));
}
double TriangleArea(Point A, Point B, Point C)
@@ -24,7 +25,7 @@ double TriangleArea(Point A, Point B, Point C)
double b = LenghtLine(B, C);
double c = LenghtLine(C, A);
double p = (a + b + c) / 2;
return sqrt(p*(p - a)*(p - b)*(p - c));
return sqrt(p * (p - a) * (p - b) * (p - c));
}
bool PointInCircle(vector<Point> &P, Point Center, double R)
@@ -44,12 +45,12 @@ double circle(vector<Point> P)
Point C;
Point minC;
for (size_t i = 0; i < P.size() - 2; i++)
for (size_t j = i+1; j < P.size(); j++)
for (size_t k = j+1; k < P.size(); k++)
for (size_t j = i + 1; j < P.size(); j++)
for (size_t k = j + 1; k < P.size(); k++)
{
C.x = -0.5 * ((P[i].y*(P[j].x*P[j].x + P[j].y*P[j].y - P[k].x*P[k].x - P[k].y*P[k].y) + P[j].y*(P[k].x*P[k].x + P[k].y*P[k].y - P[i].x*P[i].x - P[i].y*P[i].y) + P[k].y*(P[i].x*P[i].x + P[i].y*P[i].y - P[j].x*P[j].x - P[j].y*P[j].y)) / (P[i].x*(P[j].y - P[k].y) + P[j].x*(P[k].y - P[i].y) + P[k].x*(P[i].y - P[j].y) ));
C.y = 0.5 * ((P[i].x*(P[j].x*P[j].x + P[j].y*P[j].y - P[k].x*P[k].x - P[k].y*P[k].y) + P[j].x*(P[k].x*P[k].x + P[k].y*P[k].y - P[i].x*P[i].x - P[i].y*P[i].y) + P[k].x*(P[i].x*P[i].x + P[i].y*P[i].y - P[j].x*P[j].x - P[j].y*P[j].y)) / (P[i].x*(P[j].y - P[k].y) + P[j].x*(P[k].y - P[i].y) + P[k].x*(P[i].y - P[j].y) ));
R = (LenghtLine(P[i], P[j]) * LenghtLine(P[j], P[k]) * LenghtLine(P[k], P[i])) / (4 * TriangleArea(P[i], P[j], P[k]));
C.x = -0.5 * ((P[i].y * (P[j].x * P[j].x + P[j].y * P[j].y - P[k].x * P[k].x - P[k].y * P[k].y) + P[j].y * (P[k].x * P[k].x + P[k].y * P[k].y - P[i].x * P[i].x - P[i].y * P[i].y) + P[k].y * (P[i].x * P[i].x + P[i].y * P[i].y - P[j].x * P[j].x - P[j].y * P[j].y)) / (P[i].x * (P[j].y - P[k].y) + P[j].x * (P[k].y - P[i].y) + P[k].x * (P[i].y - P[j].y)));
C.y = 0.5 * ((P[i].x * (P[j].x * P[j].x + P[j].y * P[j].y - P[k].x * P[k].x - P[k].y * P[k].y) + P[j].x * (P[k].x * P[k].x + P[k].y * P[k].y - P[i].x * P[i].x - P[i].y * P[i].y) + P[k].x * (P[i].x * P[i].x + P[i].y * P[i].y - P[j].x * P[j].x - P[j].y * P[j].y)) / (P[i].x * (P[j].y - P[k].y) + P[j].x * (P[k].y - P[i].y) + P[k].x * (P[i].y - P[j].y)));
R = (LenghtLine(P[i], P[j]) * LenghtLine(P[j], P[k]) * LenghtLine(P[k], P[i])) / (4 * TriangleArea(P[i], P[j], P[k]));
if (!PointInCircle(P, C, R))
{
continue;
@@ -59,7 +60,6 @@ double circle(vector<Point> P)
minR = R;
minC = C;
}
}
for (size_t i = 0; i < P.size() - 1; i++)
for (size_t j = i + 1; j < P.size(); j++)
@@ -84,30 +84,30 @@ double circle(vector<Point> P)
void test()
{
vector<Point> Pv(5);
Pv.push_back(Point(0,0));
Pv.push_back(Point(1,3));
Pv.push_back(Point(4,1));
Pv.push_back(Point(5,4));
Pv.push_back(Point(3,-2));
Pv.push_back(Point(0, 0));
Pv.push_back(Point(1, 3));
Pv.push_back(Point(4, 1));
Pv.push_back(Point(5, 4));
Pv.push_back(Point(3, -2));
cout << circle(Pv) << endl;
}
void test2()
{
vector<Point> Pv(4);
Pv.push_back(Point(0,0));
Pv.push_back(Point(0,2));
Pv.push_back(Point(2,2));
Pv.push_back(Point(2,0));
Pv.push_back(Point(0, 0));
Pv.push_back(Point(0, 2));
Pv.push_back(Point(2, 2));
Pv.push_back(Point(2, 0));
cout << circle(Pv) << endl;
}
void test3()
{
vector<Point> Pv(3);
Pv.push_back(Point(0.5,1));
Pv.push_back(Point(3.5,3));
Pv.push_back(Point(2.5,0));
Pv.push_back(Point(0.5, 1));
Pv.push_back(Point(3.5, 3));
Pv.push_back(Point(2.5, 0));
cout << circle(Pv) << endl;
}
int main()

View File

@@ -1,54 +1,65 @@
#include<iostream>
#include <iostream>
using namespace std;
void genArray(int a[][10],int r,int c){
void genArray(int a[][10], int r, int c)
{
int value=1;
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
int value = 1;
for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
{
a[i][j] = value;
cout<<a[i][j]<<" ";
cout << a[i][j] << " ";
value++;
}
cout<<endl;
cout << endl;
}
}
void spiralPrint(int a[][10],int r,int c){
void spiralPrint(int a[][10], int r, int c)
{
int startRow=0,endRow=r-1;
int startCol =0, endCol = c-1;
int cnt=0;
int startRow = 0, endRow = r - 1;
int startCol = 0, endCol = c - 1;
int cnt = 0;
while(startRow<=endRow && startCol<=endCol){
while (startRow <= endRow && startCol <= endCol)
{
///Print start row
for(int i=startCol;i<=endCol;i++,cnt++){
cout<<a[startRow][i]<<" ";
for (int i = startCol; i <= endCol; i++, cnt++)
{
cout << a[startRow][i] << " ";
}
startRow++;
///Print the end col
for(int i=startRow;i<=endRow;i++,cnt++){
cout<<a[i][endCol]<<" ";
for (int i = startRow; i <= endRow; i++, cnt++)
{
cout << a[i][endCol] << " ";
}
endCol--;
///Print the end row
if(cnt==r*c){
if (cnt == r * c)
{
break;
}
for(int i=endCol;i>=startCol;i--,cnt++){
cout<<a[endRow][i]<<" ";
for (int i = endCol; i >= startCol; i--, cnt++)
{
cout << a[endRow][i] << " ";
}
endRow--;
///Print the start Col
if(cnt==r*c){
if (cnt == r * c)
{
break;
}
for(int i=endRow;i>=startRow;i--,cnt++){
cout<<a[i][startCol]<<" ";
for (int i = endRow; i >= startRow; i--, cnt++)
{
cout << a[i][startCol] << " ";
}
startCol++;
}
@@ -58,11 +69,10 @@ int main()
{
int a[10][10];
int r,c;
cin>>r>>c;
genArray(a,r,c);
spiralPrint(a,r,c);
int r, c;
cin >> r >> c;
genArray(a, r, c);
spiralPrint(a, r, c);
return 0;
return 0;
}

View File

@@ -1,75 +1,77 @@
#include "bits/stdc++.h"
using namespace std;
const int N = 1e6+5;
int a[N],bucket[N],cnt[N];
const int N = 1e6 + 5;
int a[N], bucket[N], cnt[N];
int bucket_size;
struct query{
int l,r,i;
}q[N];
int ans=0;
struct query
{
int l, r, i;
} q[N];
int ans = 0;
void add(int index)
{
cnt[a[index]]++;
if(cnt[a[index]] == 1)
if (cnt[a[index]] == 1)
ans++;
}
void remove(int index)
{
cnt[a[index]]--;
if(cnt[a[index]] == 0)
if (cnt[a[index]] == 0)
ans--;
}
bool mycmp(query x, query y)
{
if(x.l/bucket_size != y.l/bucket_size)
return x.l/bucket_size < y.l/bucket_size;
return x.r<y.r;
if (x.l / bucket_size != y.l / bucket_size)
return x.l / bucket_size < y.l / bucket_size;
return x.r < y.r;
}
int main() {
int n,t,i,j,k=0;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
int main()
{
int n, t, i, j, k = 0;
scanf("%d", &n);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
bucket_size = ceil(sqrt(n));
scanf("%d",&t);
for(i=0;i<t;i++)
scanf("%d", &t);
for (i = 0; i < t; i++)
{
scanf("%d %d",&q[i].l,&q[i].r);
q[i].l--; q[i].r--;
scanf("%d %d", &q[i].l, &q[i].r);
q[i].l--;
q[i].r--;
q[i].i = i;
}
sort(q,q+t,mycmp);
int left=0,right=0;
for(i=0;i<t;i++)
sort(q, q + t, mycmp);
int left = 0, right = 0;
for (i = 0; i < t; i++)
{
int L=q[i].l, R=q[i].r;
while(left < L)
int L = q[i].l, R = q[i].r;
while (left < L)
{
remove(left);
left++;
}
while(left>L)
while (left > L)
{
add(left-1);
add(left - 1);
left--;
}
while(right<=R)
while (right <= R)
{
add(right);
right++;
}
while(right>R+1)
while (right > R + 1)
{
remove(right-1);
remove(right - 1);
right--;
}
bucket[q[i].i] = ans;
bucket[q[i].i] = ans;
}
for(i=0;i<t;i++)
printf("%d\n",bucket[i]);
for (i = 0; i < t; i++)
printf("%d\n", bucket[i]);
return 0;
}

View File

@@ -2,89 +2,90 @@
#define MAX 4000000
using namespace std;
typedef long long ll;
void ConsTree(ll arr[],ll segtree[],ll low,ll high,ll pos)
void ConsTree(ll arr[], ll segtree[], ll low, ll high, ll pos)
{
if(low == high)
if (low == high)
{
segtree[pos] = arr[low];
return;
}
ll mid = (low+high)/2;
ConsTree(arr,segtree,low,mid,2*pos+1);
ConsTree(arr,segtree,mid+1,high,2*pos+2);
segtree[pos] = segtree[2*pos+1] + segtree[2*pos+2];
ll mid = (low + high) / 2;
ConsTree(arr, segtree, low, mid, 2 * pos + 1);
ConsTree(arr, segtree, mid + 1, high, 2 * pos + 2);
segtree[pos] = segtree[2 * pos + 1] + segtree[2 * pos + 2];
}
ll query(ll segtree[],ll lazy[],ll qlow,ll qhigh,ll low,ll high,ll pos)
ll query(ll segtree[], ll lazy[], ll qlow, ll qhigh, ll low, ll high, ll pos)
{
if(low > high)
if (low > high)
return 0;
if(qlow>high || qhigh<low)
if (qlow > high || qhigh < low)
return 0;
if(lazy[pos] != 0)
if (lazy[pos] != 0)
{
segtree[pos] += lazy[pos]*(high-low+1);
if(low != high)
segtree[pos] += lazy[pos] * (high - low + 1);
if (low != high)
{
lazy[2*pos+1] += lazy[pos];
lazy[2*pos+2] += lazy[pos];
lazy[2 * pos + 1] += lazy[pos];
lazy[2 * pos + 2] += lazy[pos];
}
lazy[pos] = 0;
}
if(qlow<=low && qhigh>=high)
if (qlow <= low && qhigh >= high)
return segtree[pos];
ll mid = (low+high)/2;
return query(segtree,lazy,qlow,qhigh,low,mid,2*pos+1) + query(segtree,lazy,qlow,qhigh,mid+1,high,2*pos+2);
ll mid = (low + high) / 2;
return query(segtree, lazy, qlow, qhigh, low, mid, 2 * pos + 1) + query(segtree, lazy, qlow, qhigh, mid + 1, high, 2 * pos + 2);
}
void update(ll segtree[],ll lazy[],ll start,ll end,ll delta,ll low,ll high,ll pos)
void update(ll segtree[], ll lazy[], ll start, ll end, ll delta, ll low, ll high, ll pos)
{
if(low>high)
if (low > high)
return;
if(lazy[pos] != 0)
if (lazy[pos] != 0)
{
segtree[pos] += lazy[pos]*(high-low+1);
if(low!=high)
segtree[pos] += lazy[pos] * (high - low + 1);
if (low != high)
{
lazy[2*pos+1] += lazy[pos];
lazy[2*pos+2] += lazy[pos];
lazy[2 * pos + 1] += lazy[pos];
lazy[2 * pos + 2] += lazy[pos];
}
lazy[pos] = 0;
}
if(start > high || end < low)
if (start > high || end < low)
return;
if(start <= low && end >= high)
if (start <= low && end >= high)
{
segtree[pos] += delta*(high-low+1);
if(low != high)
segtree[pos] += delta * (high - low + 1);
if (low != high)
{
lazy[2*pos+1] += delta;
lazy[2*pos+2] += delta;
lazy[2 * pos + 1] += delta;
lazy[2 * pos + 2] += delta;
}
return;
}
ll mid = (low+high)/2;
update(segtree,lazy,start,end,delta,low,mid,2*pos+1);
update(segtree,lazy,start,end,delta,mid+1,high,2*pos+2);
segtree[pos] = segtree[2*pos+1] + segtree[2*pos+2];
ll mid = (low + high) / 2;
update(segtree, lazy, start, end, delta, low, mid, 2 * pos + 1);
update(segtree, lazy, start, end, delta, mid + 1, high, 2 * pos + 2);
segtree[pos] = segtree[2 * pos + 1] + segtree[2 * pos + 2];
}
int main() {
ll n,c;
scanf("%lld %lld",&n,&c);
ll arr[n]={0},p,q,v,choice;
ll segtree[MAX],lazy[MAX]={0};
ConsTree(arr,segtree,0,n-1,0);
while(c--)
int main()
{
ll n, c;
scanf("%lld %lld", &n, &c);
ll arr[n] = {0}, p, q, v, choice;
ll segtree[MAX], lazy[MAX] = {0};
ConsTree(arr, segtree, 0, n - 1, 0);
while (c--)
{
scanf("%lld", &choice);
if (choice == 0)
{
scanf("%lld",&choice);
if(choice == 0)
{
scanf("%lld %lld %lld",&p,&q,&v);
update(segtree,lazy,p-1,q-1,v,0,n-1,0);
}
else
{
scanf("%lld %lld",&p,&q);
printf("%lld\n",query(segtree,lazy,p-1,q-1,0,n-1,0));
}
scanf("%lld %lld %lld", &p, &q, &v);
update(segtree, lazy, p - 1, q - 1, v, 0, n - 1, 0);
}
else
{
scanf("%lld %lld", &p, &q);
printf("%lld\n", query(segtree, lazy, p - 1, q - 1, 0, n - 1, 0));
}
}
return 0;
}

View File

@@ -1,34 +1,36 @@
#include <iostream>
using namespace std;
int binary_search(int a[],int l,int r,int key){
while(l<=r){
int m = l+(r-l)/2;
if(key==a[m])
int binary_search(int a[], int l, int r, int key)
{
while (l <= r)
{
int m = l + (r - l) / 2;
if (key == a[m])
return m;
else if(key<a[m])
r = m-1;
else if (key < a[m])
r = m - 1;
else
l = m+1;
l = m + 1;
}
return -1;
}
int main(int argc, char const *argv[])
{
int n,key;
cout<<"Enter size of array: ";
cin>>n;
cout<<"Enter array elements: ";
int n, key;
cout << "Enter size of array: ";
cin >> n;
cout << "Enter array elements: ";
int a[n];
for (int i = 0; i < n; ++i)
{
cin>>a[i];
cin >> a[i];
}
cout<<"Enter search key: ";
cin>>key;
int res = binary_search(a,0,n-1,key);
if(res != -1)
cout<<key<<" found at index "<<res<<endl;
cout << "Enter search key: ";
cin >> key;
int res = binary_search(a, 0, n - 1, key);
if (res != -1)
cout << key << " found at index " << res << endl;
else
cout<<key<<" not found"<<endl;
cout << key << " not found" << endl;
return 0;
}

View File

@@ -1,11 +1,11 @@
#include<iostream>
#include <iostream>
using namespace std;
int LinearSearch(int *array, int size, int key)
{
for (int i = 0; i < size; ++i)
{
if (array[i]==key)
if (array[i] == key)
{
return i;
}
@@ -14,35 +14,34 @@ int LinearSearch(int *array, int size, int key)
return -1;
}
int main()
{
int size;
cout<<"\nEnter the size of the Array : ";
cout << "\nEnter the size of the Array : ";
cin >> size;
int array[size];
int key;
//Input array
cout<<"\nEnter the Array of " << size << " numbers : ";
cout << "\nEnter the Array of " << size << " numbers : ";
for (int i = 0; i < size; i++)
{
cin>>array[i];
cin >> array[i];
}
cout<<"\nEnter the number to be searched : ";
cin>>key;
int index=LinearSearch(array, size, key);
if (index!=-1)
cout << "\nEnter the number to be searched : ";
cin >> key;
int index = LinearSearch(array, size, key);
if (index != -1)
{
cout<<"\nNumber found at index : "<<index;
cout << "\nNumber found at index : " << index;
}
else
{
cout<<"\nNot found";
cout << "\nNot found";
}
return 0;
}

View File

@@ -7,22 +7,23 @@ char paragraph;
int main()
{
string paragraph;
cout << "Please enter your paragraph: \n";
getline (cin,paragraph);
cout << "\nHello, your paragraph is:\n " << paragraph << "!\n";
cout << "\nThe size of your paragraph = " << paragraph.size() << " characters. \n\n";
string paragraph;
cout << "Please enter your paragraph: \n";
getline(cin, paragraph);
cout << "\nHello, your paragraph is:\n " << paragraph << "!\n";
cout << "\nThe size of your paragraph = " << paragraph.size() << " characters. \n\n";
if (paragraph.empty())
{
cout << "\nThe paragraph is empty" << endl;
}
else
if (paragraph.empty())
{
while (true) {
cout << "\nThe paragraph is empty" << endl;
}
else
{
while (true)
{
string word;
cout << "Please enter the word you are searching for: ";
getline (cin,word);
getline(cin, word);
cout << "Hello, your word is " << word << "!\n";
if (paragraph.find(word) == string::npos)
{
@@ -30,10 +31,10 @@ int main()
}
else
{
cout << "The word " << word << " is now found at location " << paragraph.find(word) << endl << endl;
cout << "The word " << word << " is now found at location " << paragraph.find(word) << endl
<< endl;
}
system("pause");
}
}
}
}

View File

@@ -25,7 +25,7 @@ using namespace std;
#define MAX 10000000
int N = 21;
int A[MAX] = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,3,4,10};
int A[MAX] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 10};
/*
* get_input function is to receive input from standard IO
@@ -35,82 +35,94 @@ void get_input()
// TODO: Get input from STDIO or write input to memory as done above.
}
/*
* This is the iterative method of the ternary search which returns the index of the element.
*/
int it_ternary_search(int left, int right, int A[],int target)
int it_ternary_search(int left, int right, int A[], int target)
{
while (1)
{
if (left < right)
{
if(left<right)
{
if(right-left < absolutePrecision)
{
for(int i=left;i<=right;i++)
if(A[i] == target) return i;
return -1;
}
int oneThird = (left+right)/3+1;
int twoThird = (left+right)*2/3+1;
if(A[oneThird] == target) return oneThird;
else if(A[twoThird] == target) return twoThird;
else if(target > A[twoThird]) left = twoThird+1;
else if(target < A[oneThird]) right = oneThird-1;
else left = oneThird+1, right = twoThird-1;
}
else return -1;
if (right - left < absolutePrecision)
{
for (int i = left; i <= right; i++)
if (A[i] == target)
return i;
return -1;
}
int oneThird = (left + right) / 3 + 1;
int twoThird = (left + right) * 2 / 3 + 1;
if (A[oneThird] == target)
return oneThird;
else if (A[twoThird] == target)
return twoThird;
else if (target > A[twoThird])
left = twoThird + 1;
else if (target < A[oneThird])
right = oneThird - 1;
else
left = oneThird + 1, right = twoThird - 1;
}
else
return -1;
}
}
/*
* This is the recursive method of the ternary search which returns the index of the element.
*/
int rec_ternary_search(int left, int right, int A[],int target)
int rec_ternary_search(int left, int right, int A[], int target)
{
if(left<right)
if (left < right)
{
if (right - left < absolutePrecision)
{
if(right-left < absolutePrecision)
{
for(int i=left;i<=right;i++)
if(A[i] == target) return i;
return -1;
}
int oneThird = (left+right)/3+1;
int twoThird = (left+right)*2/3+1;
for (int i = left; i <= right; i++)
if (A[i] == target)
return i;
if(A[oneThird] == target) return oneThird;
if(A[twoThird] == target) return twoThird;
if(target < A[oneThird]) return rec_ternary_search(left, oneThird-1, A, target);
if(target > A[twoThird]) return rec_ternary_search(twoThird+1, right, A, target);
return rec_ternary_search(oneThird+1, twoThird-1, A, target);
return -1;
}
else return -1;
int oneThird = (left + right) / 3 + 1;
int twoThird = (left + right) * 2 / 3 + 1;
if (A[oneThird] == target)
return oneThird;
if (A[twoThird] == target)
return twoThird;
if (target < A[oneThird])
return rec_ternary_search(left, oneThird - 1, A, target);
if (target > A[twoThird])
return rec_ternary_search(twoThird + 1, right, A, target);
return rec_ternary_search(oneThird + 1, twoThird - 1, A, target);
}
else
return -1;
}
/*
* ternary_search is a template function
* You could either use it_ternary_search or rec_ternary_search according to preference.
*/
void ternary_search(int N,int A[],int target)
void ternary_search(int N, int A[], int target)
{
cout << it_ternary_search(0,N-1,A,target) << '\t';
cout << rec_ternary_search(0,N-1,A,target) << '\t';
cout << it_ternary_search(0, N - 1, A, target) << '\t';
cout << rec_ternary_search(0, N - 1, A, target) << '\t';
cout << '\n';
}
int main()
{
get_input();
ternary_search(N,A,_target);
ternary_search(N, A, _target);
return 0;
}

View File

@@ -2,75 +2,75 @@
/* C++ Program for Bitonic Sort. Note that this program
works only when size of input is a power of 2. */
#include<stdio.h>
#include<algorithm.h>
using namespace std;
#include <stdio.h>
#include <algorithm.h>
using namespace std;
/*The parameter dir indicates the sorting direction, ASCENDING
or DESCENDING; if (a[i] > a[j]) agrees with the direction,
then a[i] and a[j] are interchanged.*/
void compAndSwap(int a[], int i, int j, int dir)
{
if (dir==(a[i]>a[j]))
swap(a[i],a[j]);
}
void compAndSwap(int a[], int i, int j, int dir)
{
if (dir == (a[i] > a[j]))
swap(a[i], a[j]);
}
/*It recursively sorts a bitonic sequence in ascending order,
if dir = 1, and in descending order otherwise (means dir=0).
The sequence to be sorted starts at index position low,
the parameter cnt is the number of elements to be sorted.*/
void bitonicMerge(int a[], int low, int cnt, int dir)
{
if (cnt>1)
{
int k = cnt/2;
for (int i=low; i<low+k; i++)
compAndSwap(a, i, i+k, dir);
bitonicMerge(a, low, k, dir);
bitonicMerge(a, low+k, k, dir);
}
}
void bitonicMerge(int a[], int low, int cnt, int dir)
{
if (cnt > 1)
{
int k = cnt / 2;
for (int i = low; i < low + k; i++)
compAndSwap(a, i, i + k, dir);
bitonicMerge(a, low, k, dir);
bitonicMerge(a, low + k, k, dir);
}
}
/* This function first produces a bitonic sequence by recursively
sorting its two halves in opposite sorting orders, and then
calls bitonicMerge to make them in the same order */
void bitonicSort(int a[],int low, int cnt, int dir)
{
if (cnt>1)
{
int k = cnt/2;
// sort in ascending order since dir here is 1
bitonicSort(a, low, k, 1);
// sort in descending order since dir here is 0
bitonicSort(a, low+k, k, 0);
// Will merge wole sequence in ascending order
// since dir=1.
bitonicMerge(a,low, cnt, dir);
}
}
void bitonicSort(int a[], int low, int cnt, int dir)
{
if (cnt > 1)
{
int k = cnt / 2;
// sort in ascending order since dir here is 1
bitonicSort(a, low, k, 1);
// sort in descending order since dir here is 0
bitonicSort(a, low + k, k, 0);
// Will merge wole sequence in ascending order
// since dir=1.
bitonicMerge(a, low, cnt, dir);
}
}
/* Caller of bitonicSort for sorting the entire array of
length N in ASCENDING order */
void sort(int a[], int N, int up)
{
bitonicSort(a,0, N, up);
}
// Driver code
int main()
{
int a[]= {3, 7, 4, 8, 6, 2, 1, 5};
int N = sizeof(a)/sizeof(a[0]);
int up = 1; // means sort in ascending order
sort(a, N, up);
printf("Sorted array: \n");
for (int i=0; i<N; i++)
printf("%d ", a[i]);
return 0;
void sort(int a[], int N, int up)
{
bitonicSort(a, 0, N, up);
}
// Driver code
int main()
{
int a[] = {3, 7, 4, 8, 6, 2, 1, 5};
int N = sizeof(a) / sizeof(a[0]);
int up = 1; // means sort in ascending order
sort(a, N, up);
printf("Sorted array: \n");
for (int i = 0; i < N; i++)
printf("%d ", a[i]);
return 0;
}

View File

@@ -1,55 +1,56 @@
//Bubble Sort
#include<iostream>
#include<vector>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n;
short swap_check=0;
cout << "Enter the amount of numbers to sort: ";
short swap_check = 0;
cout << "Enter the amount of numbers to sort: ";
cin >> n;
vector<int> numbers;
cout << "Enter " << n << " numbers: ";
int num;
//Input
for(int i=0; i<n; i++)
//Input
for (int i = 0; i < n; i++)
{
cin >> num;
numbers.push_back(num);
}
//Bubble Sorting
for(int i=0; i<n; i++)
for (int i = 0; i < n; i++)
{
swap_check=0;
for(int j=0; j<n-1-i; j++)
swap_check = 0;
for (int j = 0; j < n - 1 - i; j++)
{
if(numbers[j]>numbers[j+1])
if (numbers[j] > numbers[j + 1])
{
swap_check=1;
swap(numbers[j], numbers[j+1]);
swap_check = 1;
swap(numbers[j], numbers[j + 1]);
}
}
if(swap_check == 0)
{
if (swap_check == 0)
{
break;
}
}
//Output
cout<<"\nSorted Array : ";
for(int i=0; i<numbers.size(); i++)
cout << "\nSorted Array : ";
for (int i = 0; i < numbers.size(); i++)
{
if(i != numbers.size() -1)
if (i != numbers.size() - 1)
{
cout << numbers[i] << ", ";
}else
}
else
{
cout << numbers[i] << endl;
}
}
return 0;
return 0;
}

View File

@@ -1,116 +1,109 @@
//Returns Sorted elements after performing Cocktail Selection Sort
//It is a Sorting algorithm which chooses the minimum and maximum element in an array simultaneously,
//It is a Sorting algorithm which chooses the minimum and maximum element in an array simultaneously,
//and swaps it with the lowest and highest available position iteratively or recursively
#include<iostream>
#include <iostream>
using namespace std;
//Iterative Version
void CocktailSelectionSort(vector <int> &vec,int low,int high)
void CocktailSelectionSort(vector<int> &vec, int low, int high)
{
while(low<=high)
while (low <= high)
{
int minimum=vec[low];
int minimumindex=low;
int maximum=vec[high];
int maximumindex=high;
int minimum = vec[low];
int minimumindex = low;
int maximum = vec[high];
int maximumindex = high;
for(int i=low;i<=high;i++)
{
if(vec[i]>=maximum)
for (int i = low; i <= high; i++)
{
maximum=vec[i];
maximumindex=i;
if (vec[i] >= maximum)
{
maximum = vec[i];
maximumindex = i;
}
if (vec[i] <= minimum)
{
minimum = vec[i];
minimumindex = i;
}
}
if(vec[i]<=minimum)
if (low != maximumindex || high != minimumindex)
{
minimum=vec[i];
minimumindex=i;
swap(vec[low], vec[minimumindex]);
swap(vec[high], vec[maximumindex]);
}
else
{
swap(vec[low], vec[high]);
}
}
if(low!=maximumindex||high!=minimumindex)
{
swap(vec[low],vec[minimumindex]);
swap(vec[high],vec[maximumindex]);
}
else
{
swap(vec[low],vec[high]);
}
low++;
high--;
}
}
low++;
high--;
}
}
//Recursive Version
void CocktailSelectionSort(vector <int> &vec,int low,int high)
void CocktailSelectionSort(vector<int> &vec, int low, int high)
{
if(low>=high)
return;
int minimum=vec[low];
int minimumindex=low;
int maximum=vec[high];
int maximumindex=high;
for(int i=low;i<=high;i++)
if (low >= high)
return;
int minimum = vec[low];
int minimumindex = low;
int maximum = vec[high];
int maximumindex = high;
for (int i = low; i <= high; i++)
{
if(vec[i]>=maximum)
if (vec[i] >= maximum)
{
maximum=vec[i];
maximumindex=i;
maximum = vec[i];
maximumindex = i;
}
if(vec[i]<=minimum)
if (vec[i] <= minimum)
{
minimum=vec[i];
minimumindex=i;
minimum = vec[i];
minimumindex = i;
}
}
if(low!=maximumindex||high!=minimumindex)
if (low != maximumindex || high != minimumindex)
{
swap(vec[low],vec[minimumindex]);
swap(vec[high],vec[maximumindex]);
swap(vec[low], vec[minimumindex]);
swap(vec[high], vec[maximumindex]);
}
else
{
swap(vec[low],vec[high]);
swap(vec[low], vec[high]);
}
CocktailSelectionSort(vec,low+1,high-1);
CocktailSelectionSort(vec, low + 1, high - 1);
}
//main function, select any one of iterative or recursive version
int main()
{
int n;
cout << "Enter number of elements\n";
cin >> n;
std::vector<int> v(n);
cout << "Enter all the elements\n";
for (int i = 0; i < n; ++i)
{
cin >> v[i];
}
int n;
cout << "Enter number of elements\n";
cin >> n;
std::vector<int> v(n);
cout << "Enter all the elements\n";
for (int i = 0; i < n; ++i)
{
cin >> v[i];
}
CocktailSelectionSort(v,0,n-1);
cout << "Sorted elements are\n";
for (int i = 0; i < n; ++i)
{
cout << v[i] << " ";
}
CocktailSelectionSort(v, 0, n - 1);
cout << "Sorted elements are\n";
for (int i = 0; i < n; ++i)
{
cout << v[i] << " ";
}
return 0;
}

View File

@@ -1,44 +1,41 @@
// C++ Program for counting sort
// C++ Program for counting sort
#include <iostream>
using namespace std;
void countSort(string arr)
{
void countSort(string arr)
{
string output;
int count[256], i;
for(int i=0;i<256;i++)
count[i]=0;
for(i = 0; arr[i]; ++i)
++count[arr[i]];
for (i = 1; i <= 256; ++i)
count[i] += count[i-1];
for (i = 0; arr[i]; ++i)
{
output[count[arr[i]]-1] = arr[i];
--count[arr[i]];
}
int count[256], i;
for (int i = 0; i < 256; i++)
count[i] = 0;
for (i = 0; arr[i]; ++i)
arr[i] = output[i];
cout<<"Sorted character array is "<<arr;
}
int main()
{
for (i = 0; arr[i]; ++i)
++count[arr[i]];
for (i = 1; i <= 256; ++i)
count[i] += count[i - 1];
for (i = 0; arr[i]; ++i)
{
output[count[arr[i]] - 1] = arr[i];
--count[arr[i]];
}
for (i = 0; arr[i]; ++i)
arr[i] = output[i];
cout << "Sorted character array is " << arr;
}
int main()
{
string arr;
cin>>arr;
countSort(arr);
return 0;
}
cin >> arr;
countSort(arr);
return 0;
}

View File

@@ -1,55 +1,66 @@
#include<iostream>
#include <iostream>
using namespace std;
int Max(int Arr[], int N){
int Max(int Arr[], int N)
{
int max = Arr[0];
for(int i=1; i<N; i++)
if(Arr[i] > max)
for (int i = 1; i < N; i++)
if (Arr[i] > max)
max = Arr[i];
return max;
}
int Min(int Arr[], int N){
int Min(int Arr[], int N)
{
int min = Arr[0];
for(int i=1; i<N; i++)
if(Arr[i] < min)
for (int i = 1; i < N; i++)
if (Arr[i] < min)
min = Arr[i];
return min;
}
void Print(int Arr[], int N){
for(int i=0; i<N; i++) cout<<Arr[i] <<", ";
void Print(int Arr[], int N)
{
for (int i = 0; i < N; i++)
cout << Arr[i] << ", ";
}
int *Counting_Sort(int Arr[], int N){
int *Counting_Sort(int Arr[], int N)
{
int max = Max(Arr, N);
int min = Min(Arr, N);
int *Sorted_Arr = new int[N];
int *Count = new int[max-min+1];
for(int i=0; i<N; i++) Count[Arr[i]-min]++;
for(int i=1; i<(max-min+1); i++) Count[i]+=Count[i-1];
for(int i=N-1; i>=0; i--){
Sorted_Arr[Count[Arr[i]-min]-1] = Arr[i];
Count[Arr[i]-min]--;
int *Count = new int[max - min + 1];
for (int i = 0; i < N; i++)
Count[Arr[i] - min]++;
for (int i = 1; i < (max - min + 1); i++)
Count[i] += Count[i - 1];
for (int i = N - 1; i >= 0; i--)
{
Sorted_Arr[Count[Arr[i] - min] - 1] = Arr[i];
Count[Arr[i] - min]--;
}
return Sorted_Arr;
}
int main(){
int main()
{
int Arr[] = {47, 65, 20, 66, 25, 53, 64, 69, 72, 22, 74, 25, 53, 15, 42, 36, 4, 69, 86, 19}, N = 20;
int *Sorted_Arr;
cout<<"\n\tOrignal Array = ";Print(Arr, N);
cout << "\n\tOrignal Array = ";
Print(Arr, N);
Sorted_Arr = Counting_Sort(Arr, N);
cout<<"\n\t Sorted Array = ";Print(Sorted_Arr, N);
cout<<endl;
cout << "\n\t Sorted Array = ";
Print(Sorted_Arr, N);
cout << endl;
return 0;
}

View File

@@ -1,41 +1,40 @@
//Insertion Sort
#include<iostream>
#include <iostream>
using namespace std;
int main()
{
int n;
cout<<"\nEnter the length of your array : ";
cin>>n;
cout << "\nEnter the length of your array : ";
cin >> n;
int Array[n];
cout<<"\nEnter any "<<n<<" Numbers for Unsorted Array : ";
cout << "\nEnter any " << n << " Numbers for Unsorted Array : ";
//Input
for(int i=0; i<n; i++)
for (int i = 0; i < n; i++)
{
cin>>Array[i];
cin >> Array[i];
}
//Sorting
for(int i=1; i<n; i++)
for (int i = 1; i < n; i++)
{
int temp=Array[i];
int j=i-1;
while(j>=0 && temp<Array[j])
int temp = Array[i];
int j = i - 1;
while (j >= 0 && temp < Array[j])
{
Array[j+1]=Array[j];
Array[j + 1] = Array[j];
j--;
}
Array[j+1]=temp;
Array[j + 1] = temp;
}
//Output
cout<<"\nSorted Array : ";
for(int i=0; i<n; i++)
{
cout<<Array[i]<<"\t";
}
return 0;
}
//Output
cout << "\nSorted Array : ";
for (int i = 0; i < n; i++)
{
cout << Array[i] << "\t";
}
return 0;
}

View File

@@ -1,20 +1,19 @@
#include<iostream>
#include <iostream>
using namespace std;
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int n2 = r - m;
int L[n1], R[n2];
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];
R[j] = arr[m + 1 + j];
i = 0;
j = 0;
k = l;
@@ -32,14 +31,13 @@ void merge(int arr[], int l, int m, int r)
}
k++;
}
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
while (j < n2)
{
@@ -48,52 +46,48 @@ void merge(int arr[], int l, int m, int r)
k++;
}
}
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{
int m = l+(r-l)/2;
int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m+1, r);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
void show(int A[], int size)
{
int i;
for (i=0; i < size; i++)
cout<<A[i]<<"\n";
for (i = 0; i < size; i++)
cout << A[i] << "\n";
}
int main()
{
int size;
cout<<"\nEnter the number of elements : ";
int size;
cout << "\nEnter the number of elements : ";
cin>>size;
cin >> size;
int arr[size];
cout<<"\nEnter the unsorted elements : ";
cout << "\nEnter the unsorted elements : ";
for (int i = 0; i < size; ++i)
{
cout<<"\n";
cin>>arr[i];
cout << "\n";
cin >> arr[i];
}
mergeSort(arr, 0, size);
cout<<"Sorted array\n";
cout << "Sorted array\n";
show(arr, size);
return 0;
}

View File

@@ -7,58 +7,56 @@
//This Programme uses a comparator to sort the array in Numerical order instead of Alphanumeric order
#include<iostream>
#include<string>
#include<algorithm>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool NumericSort(string a,string b)
bool NumericSort(string a, string b)
{
while(a[0]=='0')
while (a[0] == '0')
{
a.erase(a.begin());
}
while(b[0]=='0')
while (b[0] == '0')
{
b.erase(b.begin());
}
int n=a.length();
int m=b.length();
if(n==m)
return a<b;
return n<m;
}
int n = a.length();
int m = b.length();
if (n == m)
return a < b;
return n < m;
}
int main()
{
int n;
cout << "Enter number of elements to be sorted Numerically\n";
cin >> n;
int n;
cout << "Enter number of elements to be sorted Numerically\n";
cin >> n;
vector<string> v(n);
cout << "Enter the string of Numbers\n";
for(int i=0;i<n;i++)
{
cin >> v[i];
}
sort(v.begin(),v.end());
cout << "Elements sorted normally \n";
for(int i=0;i<n;i++)
{
cout << v[i] << " ";
}
cout << "\n";
sort(v.begin(),v.end(),NumericSort);
cout << "Elements sorted Numerically \n";
for(int i=0;i<n;i++)
{
cout << v[i] << " ";
}
return 0;
vector<string> v(n);
cout << "Enter the string of Numbers\n";
for (int i = 0; i < n; i++)
{
cin >> v[i];
}
sort(v.begin(), v.end());
cout << "Elements sorted normally \n";
for (int i = 0; i < n; i++)
{
cout << v[i] << " ";
}
cout << "\n";
sort(v.begin(), v.end(), NumericSort);
cout << "Elements sorted Numerically \n";
for (int i = 0; i < n; i++)
{
cout << v[i] << " ";
}
return 0;
}

View File

@@ -7,23 +7,23 @@ using namespace std;
void oddEven(vector<int> &arr, int size)
{
bool sorted = false;
while( ! sorted )
while (!sorted)
{
sorted = true;
for(int i = 1; i < size-1; i += 2)//Odd
for (int i = 1; i < size - 1; i += 2) //Odd
{
if(arr[i] > arr[i+1])
if (arr[i] > arr[i + 1])
{
swap(arr[i], arr[i+1]);
swap(arr[i], arr[i + 1]);
sorted = false;
}
}
for(int i = 0; i < size-1; i += 2)//Even
for (int i = 0; i < size - 1; i += 2) //Even
{
if(arr[i] > arr[i+1])
if (arr[i] > arr[i + 1])
{
swap(arr[i], arr[i+1]);
swap(arr[i], arr[i + 1]);
sorted = false;
}
}
@@ -37,7 +37,6 @@ void show(vector<int> A, int size)
cout << A[i] << "\n";
}
int main()
{
int size, temp;
@@ -46,7 +45,7 @@ int main()
vector<int> arr;
cout<<"\nEnter the unsorted elements : \n";
cout << "\nEnter the unsorted elements : \n";
for (int i = 0; i < size; ++i)
{
@@ -56,7 +55,7 @@ int main()
oddEven(arr, size);
cout<<"Sorted array\n";
cout << "Sorted array\n";
show(arr, size);
return 0;
}

View File

@@ -1,69 +1,67 @@
/* C implementation QuickSort */
#include<iostream>
#include <iostream>
using namespace std;
int partition (int arr[], int low, int high)
int partition(int arr[], int low, int high)
{
int pivot = arr[high]; // pivot
int i = (low - 1); // Index of smaller element
for (int j = low; j <high; j++)
int pivot = arr[high]; // pivot
int i = (low - 1); // Index of smaller element
for (int j = low; j < high; j++)
{
// If current element is smaller than or
// equal to pivot
if (arr[j] <= pivot)
{
i++; // increment index of smaller element
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
i++; // increment index of smaller element
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp=arr[i+1];
arr[i+1]=arr[high];
arr[high]=temp;
int temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;
return (i + 1);
}
void quickSort(int arr[], int low, int high)
{
if (low < high)
{
int p= partition(arr, low, high);
int p = partition(arr, low, high);
quickSort(arr, low, p - 1);
quickSort(arr, p + 1, high);
}
}
void show(int arr[], int size)
{
for (int i=0; i < size; i++)
cout<<arr[i]<<"\n";
for (int i = 0; i < size; i++)
cout << arr[i] << "\n";
}
// Driver program to test above functions
int main()
{
int size;
cout<<"\nEnter the number of elements : ";
cout << "\nEnter the number of elements : ";
cin>>size;
cin >> size;
int arr[size];
cout<<"\nEnter the unsorted elements : ";
cout << "\nEnter the unsorted elements : ";
for (int i = 0; i < size; ++i)
{
cout<<"\n";
cin>>arr[i];
cout << "\n";
cin >> arr[i];
}
quickSort(arr, 0, size);
cout<<"Sorted array\n";
cout << "Sorted array\n";
show(arr, size);
return 0;
}

View File

@@ -3,58 +3,66 @@
#include <cmath>
#include <cstring>
using namespace std;
void radixsort(int a[],int n){
void radixsort(int a[], int n)
{
int count[10];
int output[n];
memset(output,0,sizeof(output));
memset(count,0,sizeof(count));
memset(output, 0, sizeof(output));
memset(count, 0, sizeof(count));
int max = 0;
for (int i = 0; i < n; ++i)
{
if (a[i]>max)
if (a[i] > max)
{
max = a[i];
}
}
int maxdigits = 0;
while(max){
while (max)
{
maxdigits++;
max/=10;
max /= 10;
}
for(int j=0;j<maxdigits;j++){
for(int i=0;i<n;i++){
int t = pow(10,j);
count[(a[i]%(10*t))/t]++;
for (int j = 0; j < maxdigits; j++)
{
for (int i = 0; i < n; i++)
{
int t = pow(10, j);
count[(a[i] % (10 * t)) / t]++;
}
int k = 0;
for(int p=0;p<10;p++){
for(int i=0;i<n;i++){
int t = pow(10,j);
if((a[i]%(10*t))/t==p){
for (int p = 0; p < 10; p++)
{
for (int i = 0; i < n; i++)
{
int t = pow(10, j);
if ((a[i] % (10 * t)) / t == p)
{
output[k] = a[i];
k++;
}
}
}
memset(count,0,sizeof(count));
memset(count, 0, sizeof(count));
for (int i = 0; i < n; ++i)
{
a[i] = output[i];
}
}
}
void print(int a[],int n){
void print(int a[], int n)
{
for (int i = 0; i < n; ++i)
{
cout<<a[i]<<" ";
cout << a[i] << " ";
}
cout<<endl;
cout << endl;
}
int main(int argc, char const *argv[])
{
int a[] = {170, 45, 75, 90, 802, 24, 2, 66};
int n = sizeof(a)/sizeof(a[0]);
radixsort(a,n);
print(a,n);
int n = sizeof(a) / sizeof(a[0]);
radixsort(a, n);
print(a, n);
return 0;
}

View File

@@ -1,39 +1,39 @@
//Selection Sort
#include<iostream>
#include <iostream>
using namespace std;
int main()
{
int Array[6];
cout<<"\nEnter any 6 Numbers for Unsorted Array : ";
cout << "\nEnter any 6 Numbers for Unsorted Array : ";
//Input
for(int i=0; i<6; i++)
for (int i = 0; i < 6; i++)
{
cin>>Array[i];
cin >> Array[i];
}
//Selection Sorting
for(int i=0; i<6; i++)
for (int i = 0; i < 6; i++)
{
int min=i;
for(int j=i+1; j<6; j++)
int min = i;
for (int j = i + 1; j < 6; j++)
{
if(Array[j]<Array[min])
if (Array[j] < Array[min])
{
min=j; //Finding the smallest number in Array
min = j; //Finding the smallest number in Array
}
}
int temp =Array[i];
Array[i]=Array[min];
Array[min]=temp;
int temp = Array[i];
Array[i] = Array[min];
Array[min] = temp;
}
//Output
cout<<"\nSorted Array : ";
for(int i=0; i<6; i++)
cout << "\nSorted Array : ";
for (int i = 0; i < 6; i++)
{
cout<<Array[i]<<"\t";
cout << Array[i] << "\t";
}
}

View File

@@ -1,45 +1,45 @@
#include<iostream>
#include <iostream>
using namespace std;
int main()
{
int size=10;
int size = 10;
int array[size];
// Input
cout<<"\nHow many numbers do want to enter in unsorted array : ";
cin>>size;
cout<<"\nEnter the numbers for unsorted array : ";
cout << "\nHow many numbers do want to enter in unsorted array : ";
cin >> size;
cout << "\nEnter the numbers for unsorted array : ";
for (int i = 0; i < size; i++)
{
cin>>array[i];
cin >> array[i];
}
// Sorting
for (int i = size/2; i>0 ; i=i/2)
for (int i = size / 2; i > 0; i = i / 2)
{
for (int j = i; j <size ; j++)
for (int j = i; j < size; j++)
{
for (int k = j-i; k>=0; k=k-i)
for (int k = j - i; k >= 0; k = k - i)
{
if (array[k]<array[k+i])
if (array[k] < array[k + i])
{
break;
}
else
{
int temp=array[k+i];
array[k+i]=array[k];
array[k]=temp;
int temp = array[k + i];
array[k + i] = array[k];
array[k] = temp;
}
}
}
}
// Output
cout<<"\nSorted array : ";
cout << "\nSorted array : ";
for (int i = 0; i < size; ++i)
{
cout<<array[i]<<"\t";
cout << array[i] << "\t";
}
return 0;
}

View File

@@ -1,27 +1,27 @@
//Returns the sorted vector after performing SlowSort
//It is a sorting algorithm that is of humorous nature and not useful.
//It's based on the principle of multiply and surrender, a tongue-in-cheek joke of divide and conquer.
//It is a sorting algorithm that is of humorous nature and not useful.
//It's based on the principle of multiply and surrender, a tongue-in-cheek joke of divide and conquer.
//It was published in 1986 by Andrei Broder and Jorge Stolfi in their paper Pessimal Algorithms and Simplexity Analysis.
//This algorithm multiplies a single problem into multiple subproblems
//It is interesting because it is provably the least efficient sorting algorithm that can be built asymptotically,
//It is interesting because it is provably the least efficient sorting algorithm that can be built asymptotically,
//and with the restriction that such an algorithm, while being slow, must still all the time be working towards a result.
#include<iostream>
#include <iostream>
using namespace std;
void SlowSort(int a[], int i, int j)
{
if(i>=j)
if (i >= j)
return;
int m=i+(j-i)/2; //midpoint, implemented this way to avoid overflow
int m = i + (j - i) / 2; //midpoint, implemented this way to avoid overflow
int temp;
SlowSort(a, i, m);
SlowSort(a, m + 1, j);
if(a[j]<a[m])
if (a[j] < a[m])
{
temp=a[j]; //swapping a[j] & a[m]
a[j]=a[m];
a[m]=temp;
temp = a[j]; //swapping a[j] & a[m]
a[j] = a[m];
a[m] = temp;
}
SlowSort(a, i, j - 1);
}
@@ -30,28 +30,28 @@ void SlowSort(int a[], int i, int j)
int main()
{
int size;
cout<<"\nEnter the number of elements : ";
int size;
cout << "\nEnter the number of elements : ";
cin>>size;
cin >> size;
int arr[size];
cout<<"\nEnter the unsorted elements : ";
int arr[size];
for (int i = 0; i < size; ++i)
{
cout<<"\n";
cin>>arr[i];
}
cout << "\nEnter the unsorted elements : ";
SlowSort(arr, 0, size);
cout<<"Sorted array\n";
for (int i = 0; i < size; ++i)
{
cout << arr[i] << " ";
}
return 0;
for (int i = 0; i < size; ++i)
{
cout << "\n";
cin >> arr[i];
}
SlowSort(arr, 0, size);
cout << "Sorted array\n";
for (int i = 0; i < size; ++i)
{
cout << arr[i] << " ";
}
return 0;
}

View File

@@ -3,40 +3,40 @@
#include <algorithm>
#include <vector>
using namespace std;
// Function to sort arr[] of size n using bucket sort
void bucketSort(float arr[], int n)
{
// 1) Create n empty buckets
vector<float> b[n];
// 2) Put array elements in different buckets
for (int i=0; i<n; i++)
{
int bi = n*arr[i]; // Index in bucket
b[bi].push_back(arr[i]);
}
// 3) Sort individual buckets
for (int i=0; i<n; i++)
sort(b[i].begin(), b[i].end());
// 4) Concatenate all buckets into arr[]
int index = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < b[i].size(); j++)
arr[index++] = b[i][j];
// 1) Create n empty buckets
vector<float> b[n];
// 2) Put array elements in different buckets
for (int i = 0; i < n; i++)
{
int bi = n * arr[i]; // Index in bucket
b[bi].push_back(arr[i]);
}
// 3) Sort individual buckets
for (int i = 0; i < n; i++)
sort(b[i].begin(), b[i].end());
// 4) Concatenate all buckets into arr[]
int index = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < b[i].size(); j++)
arr[index++] = b[i][j];
}
/* Driver program to test above funtion */
int main()
{
float arr[] = {0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434};
int n = sizeof(arr)/sizeof(arr[0]);
bucketSort(arr, n);
cout << "Sorted array is \n";
for (int i=0; i<n; i++)
cout << arr[i] << " ";
return 0;
float arr[] = {0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434};
int n = sizeof(arr) / sizeof(arr[0]);
bucketSort(arr, n);
cout << "Sorted array is \n";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}

View File

@@ -1,5 +1,5 @@
//Kind of better version of Bubble sort.
//While Bubble sort is comparering adjacent value, Combsort is using gap larger than 1
//While Bubble sort is comparering adjacent value, Combsort is using gap larger than 1
//Best case: O(n)
//Worst case: O(n ^ 2)
@@ -10,29 +10,34 @@ using namespace std;
int a[100005];
int n;
int FindNextGap(int x) {
int FindNextGap(int x)
{
x = (x * 10) / 13;
return max(1, x);
}
void CombSort(int a[], int l, int r) {
void CombSort(int a[], int l, int r)
{
//Init gap
int gap = n;
//Initialize swapped as true to make sure that loop runs
bool swapped = true;
//Keep running until gap = 1 or none elements were swapped
while (gap != 1 || swapped) {
while (gap != 1 || swapped)
{
//Find next gap
gap = FindNextGap(gap);
swapped = false;
// Compare all elements with current gap
for(int i = l; i <= r - gap; ++i) {
if (a[i] > a[i + gap]) {
for (int i = l; i <= r - gap; ++i)
{
if (a[i] > a[i + gap])
{
swap(a[i], a[i + gap]);
swapped = true;
}
@@ -40,12 +45,15 @@ void CombSort(int a[], int l, int r) {
}
}
int main() {
int main()
{
cin >> n;
for(int i = 1; i <= n; ++i) cin >> a[i];
for (int i = 1; i <= n; ++i)
cin >> a[i];
CombSort(a, 1, n);
for(int i = 1; i <= n; ++i) cout << a[i] << ' ';
for (int i = 1; i <= n; ++i)
cout << a[i] << ' ';
return 0;
}

Some files were not shown because too many files have changed in this diff Show More