diff --git a/Backtracking/Graph Coloring.cpp b/Backtracking/Graph Coloring.cpp index fdf50b288..cadc6d5ec 100644 --- a/Backtracking/Graph Coloring.cpp +++ b/Backtracking/Graph Coloring.cpp @@ -1,48 +1,47 @@ -#include - +#include + // 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; } diff --git a/Backtracking/N Queens.cpp b/Backtracking/N Queens.cpp index f070c5803..472aaa2fe 100644 --- a/Backtracking/N Queens.cpp +++ b/Backtracking/N Queens.cpp @@ -1,82 +1,77 @@ -#include +#include #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<<""<=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= 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"< +#include 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 -#include -#include +#include +#include +#include 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: "< 0 && z<0.0009) // stoping criteria + if (z > 0 && z < 0.0009) // stoping criteria { goto END; } } - END: - cout<<"\n\nRoot: "< +#include 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<>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=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"< 0 && m<0.009) // stoping criteria + if (m > 0 && m < 0.009) // stoping criteria { goto END; } } - END: - cout<<"\n\nRoot: "< -#include -#include +#include +#include +#include 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: "< 0 && z<0.09) // stoping criteria + z = eq(c); + if (z > 0 && z < 0.09) // stoping criteria { goto END; } } - END: - cout<<"\n\nRoot: "< -#include -#include +#include +#include +#include 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: "< 0 && z<0.09) // stoping criteria + z = eq(c); + if (z > 0 && z < 0.09) // stoping criteria { goto END; } } - END: - cout<<"\n\nRoot: "< -#include -#include +#include +#include +#include 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 "<"; - 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; } getch(); } \ No newline at end of file diff --git a/Data Structure/AVLtree.cpp b/Data Structure/AVLtree.cpp index a3cd52919..db6b9e0d4 100644 --- a/Data Structure/AVLtree.cpp +++ b/Data Structure/AVLtree.cpp @@ -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(itemdata) + 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 q; +void levelOrder(node *root) +{ + queue q; q.push(root); - while(!q.empty()) { + while (!q.empty()) + { root = q.front(); - cout<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; } diff --git a/Data Structure/Binary Search Tree.cpp b/Data Structure/Binary Search Tree.cpp index 5b83263bc..32a65517c 100644 --- a/Data Structure/Binary Search Tree.cpp +++ b/Data Structure/Binary Search Tree.cpp @@ -1,7 +1,6 @@ -#include +#include 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 (xval) + 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 (xval) + if (x < p->val) { - p->right=NULL; + p->right = NULL; } else { - p->left=NULL; - } - } - else if (n->right==NULL) - { - if (xval) - { - p->right=n->left; - } - else - { - p->left=n->left; + p->left = NULL; } } - else if (n->left==NULL) + else if (n->right == NULL) { - if (xval) + 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 (xval) + 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<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<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<val<<" "; + cout << n->val << " "; In(n->right); } } - void Post(node *n) { - if (n!=NULL) + if (n != NULL) { Post(n->left); Post(n->right); - cout<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); } diff --git a/Data Structure/Binaryheap.cpp b/Data Structure/Binaryheap.cpp index 92bcb275a..31129a823 100644 --- a/Data Structure/Binaryheap.cpp +++ b/Data Structure/Binaryheap.cpp @@ -1,159 +1,158 @@ -// A C++ program to demonstrate common Binary Heap Operations -#include -#include -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 +#include +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; +} diff --git a/Data Structure/Doubly Linked List.cpp b/Data Structure/Doubly Linked List.cpp index db550d422..84a239d3f 100644 --- a/Data Structure/Doubly Linked List.cpp +++ b/Data Structure/Doubly Linked List.cpp @@ -1,4 +1,4 @@ -#include +#include 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<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<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; } diff --git a/Data Structure/Linked List.cpp b/Data Structure/Linked List.cpp index b0da4a3b6..a9b839114 100644 --- a/Data Structure/Linked List.cpp +++ b/Data Structure/Linked List.cpp @@ -1,4 +1,4 @@ -#include +#include 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 <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<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; } diff --git a/Data Structure/List Array.cpp b/Data Structure/List Array.cpp index 21f5c6ae5..de984876b 100644 --- a/Data Structure/List Array.cpp +++ b/Data Structure/List Array.cpp @@ -1,32 +1,32 @@ -#include +#include 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(lastarray[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; 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"<>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; } diff --git a/Data Structure/MorrisInorder.cpp b/Data Structure/MorrisInorder.cpp index 5ea630fac..d3a2e9fd7 100644 --- a/Data Structure/MorrisInorder.cpp +++ b/Data Structure/MorrisInorder.cpp @@ -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 q; + else + { + queue 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<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<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; } diff --git a/Data Structure/Queue Using Array.cpp b/Data Structure/Queue Using Array.cpp index 7b5816f84..3b79d06fc 100644 --- a/Data Structure/Queue Using Array.cpp +++ b/Data Structure/Queue Using Array.cpp @@ -1,48 +1,47 @@ -#include +#include 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"<>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; } - diff --git a/Data Structure/Stack Using Array.cpp b/Data Structure/Stack Using Array.cpp index c5ad146cb..af1d57c46 100644 --- a/Data Structure/Stack Using Array.cpp +++ b/Data Structure/Stack Using Array.cpp @@ -1,30 +1,31 @@ -#include +#include 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"<>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; } - diff --git a/Data Structure/Stack Using Linked List.cpp b/Data Structure/Stack Using Linked List.cpp index 753fda8ed..6925cf10c 100644 --- a/Data Structure/Stack Using Linked List.cpp +++ b/Data Structure/Stack Using Linked List.cpp @@ -1,4 +1,4 @@ -#include +#include 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"<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<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; } - diff --git a/Data Structure/Tree.cpp b/Data Structure/Tree.cpp index 963779abe..9be60c309 100644 --- a/Data Structure/Tree.cpp +++ b/Data Structure/Tree.cpp @@ -1,7 +1,6 @@ -#include +#include using namespace std; - struct node { int val; @@ -18,55 +17,51 @@ 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 CreateTree(node *curr, node *n, int x, char pos) { - if(n!=NULL) + if (n != NULL) { char ch; - cout<<"\nLeft or Right of "<val<<" : "; - cin>>ch; - if(ch=='l') + cout << "\nLeft or Right of " << n->val << " : "; + cin >> ch; + if (ch == 'l') CreateTree(n, n->left, x, ch); - else if(ch=='r') + 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') + node *t = new node; + t->val = x; + t->left = NULL; + t->right = NULL; + if (pos == 'l') { - curr->left=t; + curr->left = t; } - else if(pos=='r') + else if (pos == 'r') { - curr->right=t; + curr->right = t; } } } - void BFT(node *n) { - if(n!=NULL) + if (n != NULL) { - cout<val<<" "; + cout << n->val << " "; enqueue(n->left); enqueue(n->right); BFT(dequeue()); @@ -75,9 +70,9 @@ void BFT(node *n) void Pre(node *n) { - if (n!=NULL) + if (n != NULL) { - cout<val<<" "; + cout << n->val << " "; Pre(n->left); Pre(n->right); } @@ -85,76 +80,72 @@ void Pre(node *n) void In(node *n) { - if (n!=NULL) + if (n != NULL) { In(n->left); - cout<val<<" "; + cout << n->val << " "; In(n->right); } } - void Post(node *n) { - if (n!=NULL) + if (n != NULL) { Post(n->left); Post(n->right); - cout<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. Breadth First"; - cout<<"\n3. Preorder Depth First"; - cout<<"\n4. Inorder Depth First"; - cout<<"\n5. Postorder Depth First"; + 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) + 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; + 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); + } while (ch != 0); } diff --git a/Data Structure/TrieTree.cpp b/Data Structure/TrieTree.cpp index 866087d87..2368a76aa 100644 --- a/Data Structure/TrieTree.cpp +++ b/Data Structure/TrieTree.cpp @@ -1,6 +1,6 @@ -#include -#include -#include +#include +#include +#include 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; diff --git a/Data Structure/circular_Queue_using_Linked_List.cpp b/Data Structure/circular_Queue_using_Linked_List.cpp index bf700ae8b..4b1ec476c 100644 --- a/Data Structure/circular_Queue_using_Linked_List.cpp +++ b/Data Structure/circular_Queue_using_Linked_List.cpp @@ -1,36 +1,44 @@ -#include +#include 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<data<<" "; - ptr=ptr->next; - }while(ptr!=rear->next); - cout<data; - cout<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); diff --git a/Data Structure/linkedList_implentation_usingArray.cpp b/Data Structure/linkedList_implentation_usingArray.cpp index ca08653de..6f8205f27 100644 --- a/Data Structure/linkedList_implentation_usingArray.cpp +++ b/Data Structure/linkedList_implentation_usingArray.cpp @@ -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 +#include 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<"; - temp=AvailArray[temp].next; + cout << AvailArray[temp].data << "->"; + temp = AvailArray[temp].next; } - cout<<"-1"<>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"<>x; - insertAtTheBeginning(x); - break; - case 2: - cout<<"Enter the number you want to enter"<>y; - insertAtTheEnd(y); - break; - case 3: - cout<<"The linked list contains the following element in order"<> 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; } } } diff --git a/Dynamic Programming/0-1 Knapsack.cpp b/Dynamic Programming/0-1 Knapsack.cpp index 4bed36fb2..9348372b2 100644 --- a/Dynamic Programming/0-1 Knapsack.cpp +++ b/Dynamic Programming/0-1 Knapsack.cpp @@ -1,6 +1,6 @@ //0-1 Knapsack problem - Dynamic programming //#include -#include +#include using namespace std; //void Print(int res[20][20], int i, int j, int capacity) @@ -15,7 +15,7 @@ using namespace std; // { // cout<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<> capacity; + cout << Knapsack(capacity, n, weight, value); return 0; } diff --git a/Dynamic Programming/Armstrong Number.cpp b/Dynamic Programming/Armstrong Number.cpp index 18d625e1e..098c8c628 100644 --- a/Dynamic Programming/Armstrong Number.cpp +++ b/Dynamic Programming/Armstrong Number.cpp @@ -1,20 +1,20 @@ //program to check whether a number is an armstrong number or not -#include -#include +#include +#include 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< -#include +#include +#include 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"<>V; - cout<<"Enter number of edges: "; - cin>>E; - Graph G(V,E); - for(int i=0; i>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; } diff --git a/Dynamic Programming/Catalan-Numbers.cpp b/Dynamic Programming/Catalan-Numbers.cpp index a086ae6c1..4d73cd51a 100644 --- a/Dynamic Programming/Catalan-Numbers.cpp +++ b/Dynamic Programming/Catalan-Numbers.cpp @@ -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: diff --git a/Dynamic Programming/Coin-Change.cpp b/Dynamic Programming/Coin-Change.cpp index 9b8feda3c..c8acad48e 100644 --- a/Dynamic Programming/Coin-Change.cpp +++ b/Dynamic Programming/Coin-Change.cpp @@ -1,5 +1,5 @@ #include -#include +#include 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; } \ No newline at end of file diff --git a/Dynamic Programming/Cut Rod.cpp b/Dynamic Programming/Cut Rod.cpp index 90e12a532..826332a23 100644 --- a/Dynamic Programming/Cut Rod.cpp +++ b/Dynamic Programming/Cut Rod.cpp @@ -5,25 +5,24 @@ the pieces.*/ #include 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 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; diff --git a/Dynamic Programming/Egg-Dropping-Puzzle.cpp b/Dynamic Programming/Egg-Dropping-Puzzle.cpp index 5b277be26..a441f29cb 100644 --- a/Dynamic Programming/Egg-Dropping-Puzzle.cpp +++ b/Dynamic Programming/Egg-Dropping-Puzzle.cpp @@ -6,40 +6,47 @@ #include 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; } diff --git a/Dynamic Programming/Fibonacci_Bottom_Up.cpp b/Dynamic Programming/Fibonacci_Bottom_Up.cpp index cbd0912e8..929547d7d 100644 --- a/Dynamic Programming/Fibonacci_Bottom_Up.cpp +++ b/Dynamic Programming/Fibonacci_Bottom_Up.cpp @@ -1,19 +1,22 @@ #include 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<> n; + cout << "Fibonacci number is "; + cout << fib(n) << endl; return 0; } \ No newline at end of file diff --git a/Dynamic Programming/Fibonacci_Top_Down.cpp b/Dynamic Programming/Fibonacci_Top_Down.cpp index 657881892..449aefbdc 100644 --- a/Dynamic Programming/Fibonacci_Top_Down.cpp +++ b/Dynamic Programming/Fibonacci_Top_Down.cpp @@ -1,24 +1,26 @@ #include 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 "< -#include -#include +#include +#include +#include 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; iedges[i] = (int*) malloc(V * sizeof(int)); - for(int j=0; jedges = (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"<>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>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); diff --git a/Dynamic Programming/Longest Common Subsequence.cpp b/Dynamic Programming/Longest Common Subsequence.cpp index aba1eeb54..af50720b4 100644 --- a/Dynamic Programming/Longest Common Subsequence.cpp +++ b/Dynamic Programming/Longest Common Subsequence.cpp @@ -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<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<> a >> b; + cout << lcs(a, b); return 0; } diff --git a/Dynamic Programming/Longest Increasing Subsequence.cpp b/Dynamic Programming/Longest Increasing Subsequence.cpp index e2d6111c8..49c54a941 100644 --- a/Dynamic Programming/Longest Increasing Subsequence.cpp +++ b/Dynamic Programming/Longest Increasing Subsequence.cpp @@ -1,7 +1,8 @@ //Program to calculate length of longest increasing subsequence in an array #include 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] 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< +#include using namespace std; -class graph{ +class graph +{ int v; list *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[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;iv;i++){ - cout<<"Adjacency list of vertex "<v; i++) + { + cout << "Adjacency list of vertex " << i + 1 << " is \n"; list::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<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 q; q.push_back(s); list::iterator it; - while(!q.empty()){ + while (!q.empty()) + { int u = q.front(); - cout< 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< #include - #define WHITE 0 #define GREY 1 #define BLACK 2 @@ -12,23 +11,27 @@ using namespace std; int checked[999] = {WHITE}; -void dfs(const list lista[], int start) { +void dfs(const list lista[], int start) +{ stack 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 lista[], int start) { } } -int main() { - int u, w; - int n; - cin >> n; - list 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 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; } diff --git a/Graph/Dijkstra.cpp b/Graph/Dijkstra.cpp index c395cd527..b3ee44c41 100644 --- a/Graph/Dijkstra.cpp +++ b/Graph/Dijkstra.cpp @@ -4,46 +4,52 @@ #include using namespace std; #define INF 10000010 -vector < pair > graph[5*100001]; -int dis[5*100001]; -int dij(vector > * v,int s,int * dis) { - priority_queue < pair , vector < pair >,greater < pair > > pq; +vector> graph[5 * 100001]; +int dis[5 * 100001]; +int dij(vector> *v, int s, int *dis) +{ + priority_queue, vector>, greater>> 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 > :: iterator it = v[u].begin(); it != v[u].end();it++) { - if(dis[u] + it->first < dis[it->second]) { + for (vector>::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< //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 -#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 +#define vpii vector #define vi vector -#define vll vector -#define r(x) scanf("%d",&x) -#define rs(s) scanf("%s",s) +#define vll vector +#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>>v; +ll parent[mx], arr[mx], node, edge; +vector>> 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< #include #include - using namespace std; +using namespace std; -int n , m; // For number of Vertices (V) and number of edges (E) -vector< vector > G; +int n, m; // For number of Vertices (V) and number of edges (E) +vector> G; vector visited; vector 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()); - for(int i = 0 ; i < n ; ++i) { + int x, y; + G.resize(n, vector()); + 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'; diff --git a/Greedy Algorithms/Dijkstra.cpp b/Greedy Algorithms/Dijkstra.cpp index 05191a279..0c7fffc8c 100644 --- a/Greedy Algorithms/Dijkstra.cpp +++ b/Greedy Algorithms/Dijkstra.cpp @@ -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; - 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>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; } diff --git a/Greedy Algorithms/Knapsack.cpp b/Greedy Algorithms/Knapsack.cpp index 41ce4cc9b..2135bd1eb 100644 --- a/Greedy Algorithms/Knapsack.cpp +++ b/Greedy Algorithms/Knapsack.cpp @@ -1,4 +1,4 @@ -#include +#include 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 >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 "<>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"< -#include +#include +#include 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;inext; + while (temp->next) + { + cout << temp->data << " "; + temp = temp->next; } - cout<data; - cout<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<>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 "<> 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< prime_numbers; -vector > factors; +vector> 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< +#include 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>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 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>a[i]; - int temp=0; - for(int i=0;i=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 +#include 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<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; } diff --git a/Operations on Datastructures/Circular Queue Using Array.cpp b/Operations on Datastructures/Circular Queue Using Array.cpp index d91f31af3..36d7e22c3 100644 --- a/Operations on Datastructures/Circular Queue Using Array.cpp +++ b/Operations on Datastructures/Circular Queue Using Array.cpp @@ -1,47 +1,46 @@ -#include +#include 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"<>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; } - diff --git a/Operations on Datastructures/Intersection_of_2_arrays.cpp b/Operations on Datastructures/Intersection_of_2_arrays.cpp index e2c064e1b..05652811f 100644 --- a/Operations on Datastructures/Intersection_of_2_arrays.cpp +++ b/Operations on Datastructures/Intersection_of_2_arrays.cpp @@ -1,28 +1,29 @@ #include 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> a[i]; - for(i=0;i> b[i]; - i=0;j=0; - while((i> 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]) - j++; + if (a[i] < b[j]) + i++; + else if (a[i] > b[j]) + j++; else { - cout << a[i++]<<" "; + cout << a[i++] << " "; j++; } } diff --git a/Operations on Datastructures/Reverse a Linked List using Recusion.cpp b/Operations on Datastructures/Reverse a Linked List using Recusion.cpp index daefa18e8..0908080cc 100644 --- a/Operations on Datastructures/Reverse a Linked List using Recusion.cpp +++ b/Operations on Datastructures/Reverse a Linked List using Recusion.cpp @@ -1,4 +1,4 @@ -#include +#include 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<val<<"\t"; - t=t->next; + cout << t->val << "\t"; + t = t->next; } - } int main() @@ -75,6 +72,5 @@ int main() show(); - return 0; } diff --git a/Operations on Datastructures/Union_of_2_arrays.cpp b/Operations on Datastructures/Union_of_2_arrays.cpp index 4046e1ae8..aaaeb8378 100644 --- a/Operations on Datastructures/Union_of_2_arrays.cpp +++ b/Operations on Datastructures/Union_of_2_arrays.cpp @@ -1,33 +1,34 @@ #include 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>a[i]; - cout << "Enter elements of array 2:"; - for(i=0;i> 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((ib[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 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; } \ No newline at end of file diff --git a/Others/Buzz_number.cpp b/Others/Buzz_number.cpp index 3d39c50f6..f31038aad 100644 --- a/Others/Buzz_number.cpp +++ b/Others/Buzz_number.cpp @@ -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; } diff --git a/Others/Decimal To Binary.cpp b/Others/Decimal To Binary.cpp index b8eaba1f1..4e2119ebc 100644 --- a/Others/Decimal To Binary.cpp +++ b/Others/Decimal To Binary.cpp @@ -1,4 +1,4 @@ -// This function convert decimal to binary number +// This function convert decimal to binary number // #include 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; diff --git a/Others/Decimal To Hexadecimal .cpp b/Others/Decimal To Hexadecimal .cpp index 39333ca00..705f21ba4 100644 --- a/Others/Decimal To Hexadecimal .cpp +++ b/Others/Decimal To Hexadecimal .cpp @@ -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<> 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; } diff --git a/Others/GCD_of_n_numbers.cpp b/Others/GCD_of_n_numbers.cpp index 3e9e9ce17..8158052f8 100644 --- a/Others/GCD_of_n_numbers.cpp +++ b/Others/GCD_of_n_numbers.cpp @@ -3,21 +3,21 @@ using namepsace std; int main() { - cout <<"Enter value of n:"<> n; int a[n]; - int i,j,gcd; + int i, j, gcd; cout << "Enter the n numbers:" << endl; - for(i=0;i> a[i]; - j=1; //to access all elements of the array starting from 1 - gcd=a[0]; - while(j> 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; } diff --git a/Others/Palindromeofnumber.cpp b/Others/Palindromeofnumber.cpp index 8bfdfb073..647803997 100644 --- a/Others/Palindromeofnumber.cpp +++ b/Others/Palindromeofnumber.cpp @@ -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; } diff --git a/Others/Paranthesis Matching.cpp b/Others/Paranthesis Matching.cpp index 25ee7287b..d2bb4d39c 100644 --- a/Others/Paranthesis Matching.cpp +++ b/Others/Paranthesis Matching.cpp @@ -1,5 +1,5 @@ -#include -#include +#include +#include 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; diff --git a/Others/Primality Test.cpp b/Others/Primality Test.cpp index 0b4bb67de..ce8fc1706 100644 --- a/Others/Primality Test.cpp +++ b/Others/Primality Test.cpp @@ -1,33 +1,32 @@ #include 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" <> n; + if (IsPrime(n)) + cout << n << " is Prime" << endl; + else + cout << n << " is not Prime" << endl; + + return 0; +} diff --git a/Others/Sparse matrix.cpp b/Others/Sparse matrix.cpp index 40073c345..1861163f1 100644 --- a/Others/Sparse matrix.cpp +++ b/Others/Sparse matrix.cpp @@ -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> a[i][j]; + cout << "element? "; + cin >> a[i][j]; } } // counts the zero's - for(int i=0;i((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"; } diff --git a/Others/Strassen Matrix Multiplication.cpp b/Others/Strassen Matrix Multiplication.cpp index 1cb398a62..85b627763 100644 --- a/Others/Strassen Matrix Multiplication.cpp +++ b/Others/Strassen Matrix Multiplication.cpp @@ -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 >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 >B[i][j]; + cin >> B[i][j]; } } diff --git a/Others/String Fibonacci.cpp b/Others/String Fibonacci.cpp index 8027b9668..e5475eec9 100644 --- a/Others/String Fibonacci.cpp +++ b/Others/String Fibonacci.cpp @@ -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 #include @@ -69,10 +68,9 @@ void fib_Accurate(long long n) fibMinus2 = fibMinus1; fibMinus1 = tmp; } - cout << fibMinus2; + cout << fibMinus2; } - int main() { int n; diff --git a/Others/Tower of Hanoi.cpp b/Others/Tower of Hanoi.cpp index f9b363784..5783d6a98 100644 --- a/Others/Tower of Hanoi.cpp +++ b/Others/Tower of Hanoi.cpp @@ -1,88 +1,73 @@ -#include +#include 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> 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; } diff --git a/Others/fibonacci.cpp b/Others/fibonacci.cpp index 82b1fd322..87ccda6d3 100644 --- a/Others/fibonacci.cpp +++ b/Others/fibonacci.cpp @@ -6,14 +6,12 @@ //It is a property of fibonacci similar to matrix exponentiation. #include -#include +#include 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; } - diff --git a/Others/sieve_of_Eratosthenes.cpp b/Others/sieve_of_Eratosthenes.cpp index e20aec6ae..e87ad4983 100644 --- a/Others/sieve_of_Eratosthenes.cpp +++ b/Others/sieve_of_Eratosthenes.cpp @@ -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 &P, Point Center, double R) @@ -44,12 +45,12 @@ double circle(vector 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 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 P) void test() { vector 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 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 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() diff --git a/Others/spiral_print.cpp b/Others/spiral_print.cpp index 03ea074e9..1a843c8cd 100644 --- a/Others/spiral_print.cpp +++ b/Others/spiral_print.cpp @@ -1,54 +1,65 @@ -#include +#include 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=startCol;i--,cnt++){ - cout<= 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<= 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; } diff --git a/Range queries/MO.cpp b/Range queries/MO.cpp index 2a2cbfffd..44a0883e3 100644 --- a/Range queries/MO.cpp +++ b/Range queries/MO.cpp @@ -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.rL) + 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 high) + if (low > high) return 0; - if(qlow>high || qhigh 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; } diff --git a/Search/Binary Search.cpp b/Search/Binary Search.cpp index cb67e3a07..2e90855e8 100644 --- a/Search/Binary Search.cpp +++ b/Search/Binary Search.cpp @@ -1,34 +1,36 @@ #include 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>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; + int res = binary_search(a, 0, n - 1, key); + if (res != -1) + cout << key << " found at index " << res << endl; else - cout< +#include 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 : "< 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 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; } diff --git a/Sorting/BitonicSort.cpp b/Sorting/BitonicSort.cpp index e03e4fc14..6ad2489d2 100644 --- a/Sorting/BitonicSort.cpp +++ b/Sorting/BitonicSort.cpp @@ -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 -#include -using namespace std; - + +#include +#include +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 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 -#include +#include +#include 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 numbers; cout << "Enter " << n << " numbers: "; int num; - //Input - for(int i=0; i> num; numbers.push_back(num); } //Bubble Sorting - for(int i=0; inumbers[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 +#include using namespace std; //Iterative Version -void CocktailSelectionSort(vector &vec,int low,int high) +void CocktailSelectionSort(vector &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 &vec,int low,int high) +void CocktailSelectionSort(vector &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 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 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; } diff --git a/Sorting/CountingSortString.cpp b/Sorting/CountingSortString.cpp index 2dbf499e7..6179e5d11 100644 --- a/Sorting/CountingSortString.cpp +++ b/Sorting/CountingSortString.cpp @@ -1,44 +1,41 @@ -// C++ Program for counting sort +// C++ Program for counting sort #include - + 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; - - countSort(arr); - - return 0; -} + cin >> arr; + + countSort(arr); + + return 0; +} diff --git a/Sorting/Counting_Sort.cpp b/Sorting/Counting_Sort.cpp index bea604a98..bda37bbd8 100644 --- a/Sorting/Counting_Sort.cpp +++ b/Sorting/Counting_Sort.cpp @@ -1,55 +1,66 @@ -#include +#include using namespace std; -int Max(int Arr[], int N){ +int Max(int Arr[], int N) +{ int max = Arr[0]; - for(int i=1; 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=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<>n; + cout << "\nEnter the length of your array : "; + cin >> n; int Array[n]; - cout<<"\nEnter any "<>Array[i]; + cin >> Array[i]; } - + //Sorting - for(int i=1; i=0 && temp= 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 +#include 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<>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; } diff --git a/Sorting/NumericStringSort.cpp b/Sorting/NumericStringSort.cpp index 726377ebe..02f6964ba 100644 --- a/Sorting/NumericStringSort.cpp +++ b/Sorting/NumericStringSort.cpp @@ -7,58 +7,56 @@ //This Programme uses a comparator to sort the array in Numerical order instead of Alphanumeric order - -#include -#include -#include +#include +#include +#include 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> n; + int n; + cout << "Enter number of elements to be sorted Numerically\n"; + cin >> n; -vector v(n); -cout << "Enter the string of Numbers\n"; -for(int i=0;i> v[i]; -} - -sort(v.begin(),v.end()); -cout << "Elements sorted normally \n"; -for(int i=0;i 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; } diff --git a/Sorting/OddEven Sort.cpp b/Sorting/OddEven Sort.cpp index 6319cca91..62842c174 100644 --- a/Sorting/OddEven Sort.cpp +++ b/Sorting/OddEven Sort.cpp @@ -7,23 +7,23 @@ using namespace std; void oddEven(vector &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 A, int size) cout << A[i] << "\n"; } - int main() { int size, temp; @@ -46,7 +45,7 @@ int main() vector 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; } diff --git a/Sorting/Quick Sort.cpp b/Sorting/Quick Sort.cpp index b2bb21a77..0b807898f 100644 --- a/Sorting/Quick Sort.cpp +++ b/Sorting/Quick Sort.cpp @@ -1,69 +1,67 @@ /* C implementation QuickSort */ -#include +#include 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 >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; } diff --git a/Sorting/Radix Sort.cpp b/Sorting/Radix Sort.cpp index eb3f12a57..09c91bb22 100644 --- a/Sorting/Radix Sort.cpp +++ b/Sorting/Radix Sort.cpp @@ -3,58 +3,66 @@ #include #include 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 +#include 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] +#include 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 =0; k=k-i) + for (int k = j - i; k >= 0; k = k - i) { - if (array[k] +#include 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]>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; } diff --git a/Sorting/bucketSort.cpp b/Sorting/bucketSort.cpp index 278da92bd..0ffbf8e4c 100644 --- a/Sorting/bucketSort.cpp +++ b/Sorting/bucketSort.cpp @@ -3,40 +3,40 @@ #include #include 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 b[n]; - - // 2) Put array elements in different buckets - for (int i=0; i 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 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; } diff --git a/sleep sort.c b/sleep sort.c deleted file mode 100644 index e0217ca25..000000000 --- a/sleep sort.c +++ /dev/null @@ -1,41 +0,0 @@ -#include -#include -#include - -void routine(void *a) -{ - int n = *(int *) a; // typecasting from void to int - - // Sleeping time is proportional to the number - // More precisely this thread sleep for 'n' milliseconds - Sleep(n); - - // After the sleep, print the number - printf("%d ", n); - -void sleepSort(int arr[], int n) -{ - // An array of threads, one for each of the elements - // in the input array - HANDLE threads[n]; - - // Create the threads for each of the input array elements - for (int i = 0; i < n; i++) - threads[i] = (HANDLE)_beginthread(&routine, 0, &arr[i]); - - // Process these threads - WaitForMultipleObjects(n, threads, TRUE, INFINITE); - return; -} - -// Driver program to test above functions -int main() -{ - // Doesn't work for negative numbers - int arr[] = {34, 23, 122, 9}; - int n = sizeof(arr) / sizeof(arr[0]); - - sleepSort (arr, n); - - return(0); -} \ No newline at end of file diff --git a/ternary_search.cpp b/ternary_search.cpp deleted file mode 100644 index 0a2ffbd2a..000000000 --- a/ternary_search.cpp +++ /dev/null @@ -1,19 +0,0 @@ -int three_part_binary_search(int a[], int x, int low, int high){ - if (low < high){ - int m1 = (low + high) / 3 + 1; - int m2 = 2 * (low + high) / 3 + 1; - - if (x == a[m1]) - return m1; - else if (x == a[m2]) - return m2; - else if (x < a[m1]) - return three_part_binary_search(a, x, low, m1 - 1); - else if (xa[m2]) - return three_part_binary_search(a, x, m2 + 1, high); - } - else - return -1; -} \ No newline at end of file