From 2f0ff9517e261920737a174f8db29ce10dcfa659 Mon Sep 17 00:00:00 2001 From: crcrpar Date: Mon, 11 Feb 2019 18:01:04 +0900 Subject: [PATCH] format --- .clang-format | 88 +++++ Array Left Rotation.cpp | 58 +-- Array Right Rotation.cpp | 51 ++- Backtracking/Graph Coloring.cpp | 123 +++---- Backtracking/N Queens.cpp | 124 +++---- Backtracking/Rat_maze.cpp | 107 +++--- Backtracking/sudoku_solve.cpp | 167 ++++----- Binary Search Tree.cpp | 347 +++++++----------- Binary Search.cpp | 58 ++- Buzz_number.cpp | 21 +- Circular Linked List.cpp | 176 +++++---- Circular Queue Using Array.cpp | 112 +++--- .../Gaussian_elimination.cpp | 84 ++--- Data Structure/AVLtree.cpp | 211 ++++++----- Data Structure/Binary Search Tree.cpp | 347 +++++++----------- Data Structure/Doubly Linked List.cpp | 205 +++++------ Data Structure/Linked List.cpp | 202 +++++----- Data Structure/List Array.cpp | 328 ++++++++--------- Data Structure/MorrisInorder.cpp | 153 ++++---- Data Structure/Queue Using Array.cpp | 115 +++--- Data Structure/Queue Using Linked List.cpp | 128 +++---- Data Structure/Stack Using Array.cpp | 114 +++--- Data Structure/Stack Using Linked List.cpp | 108 +++--- Data Structure/Tree.cpp | 244 ++++++------ Data Structure/TrieTree.cpp | 150 ++++---- .../linkedList_implentation_usingArray.cpp | 169 +++++---- Decimal To Binary.cpp | 33 +- Decimal To Hexadecimal .cpp | 38 +- Decimal to Roman Numeral.cpp | 126 ++++--- Doubly Linked List.cpp | 205 +++++------ Dynamic Programming/0-1 Knapsack.cpp | 80 ++-- Dynamic Programming/Armstrong Number.cpp | 32 +- Dynamic Programming/Bellman-Ford.cpp | 209 +++++------ Dynamic Programming/Catalan-Numbers.cpp | 92 +++-- Dynamic Programming/Cut Rod.cpp | 40 +- Dynamic Programming/Edit Distance.cpp | 92 ++--- Dynamic Programming/Egg-Dropping-Puzzle.cpp | 64 ++-- Dynamic Programming/Fibonacci_Bottom_Up.cpp | 30 +- Dynamic Programming/Fibonacci_Top_Down.cpp | 36 +- Dynamic Programming/Floyd-Warshall.cpp | 175 +++++---- .../Longest Common Subsequence.cpp | 126 +++---- .../Longest Increasing Subsequence.cpp | 62 ++-- GCD_of_n_numbers.cpp | 24 +- Graph/BFS.cpp | 108 +++--- Graph/DFS.cpp | 37 +- Graph/Dijkstra.cpp | 87 ++--- Graph/Kruskal.cpp | 170 +++++---- Greedy Algorithms/Dijkstra.cpp | 230 +++++------- Greedy Algorithms/Knapsack.cpp | 140 +++---- .../Kruskals Minimum Spanning Tree.cpp | 51 ++- .../Prims Minimum Spanning Tree.cpp | 108 +++--- Happy_number.cpp | 34 +- Hashing/Chaining.cpp | 210 ++++++----- Intersection_of_2_arrays.cpp | 38 +- Linear Search.cpp | 75 ++-- Linked List.cpp | 174 +++++---- List Array.cpp | 328 ++++++++--------- .../primefactorization.cpp | 99 +++-- Math/sieve_of_Eratosthenes.cpp | 46 +-- NumericStringSort.cpp | 89 ++--- .../Array Left Rotation.cpp | 58 +-- .../Array Right Rotation.cpp | 51 ++- .../Circular Linked List.cpp | 176 +++++---- .../Circular Queue Using Array.cpp | 112 +++--- .../Intersection_of_2_arrays.cpp | 38 +- .../Reverse a Linked List using Recusion.cpp | 115 +++--- .../Union_of_2_arrays.cpp | 52 ++- Others/Buzz_number.cpp | 21 +- Others/Decimal To Binary.cpp | 28 +- Others/Decimal To Hexadecimal .cpp | 86 +++-- Others/Decimal to Roman Numeral.cpp | 130 ++++--- Others/GCD_of_n_numbers.cpp | 24 +- Others/Happy_number.cpp | 34 +- Others/Paranthesis Matching.cpp | 88 +++-- Others/Sparse matrix.cpp | 33 +- Others/Strassen Matrix Multiplication.cpp | 95 +++-- Others/String Fibonacci.cpp | 116 +++--- Others/Tower of Hanoi.cpp | 121 +++--- Others/fibonacci.cpp | 65 ++-- Others/sieve_of_Eratosthenes.cpp | 37 +- Palindromeofnumber.cpp | 27 +- Paranthesis Matching.cpp | 93 ++--- Primality Test.cpp | 56 ++- Queue Using Array.cpp | 115 +++--- Queue Using Linked List.cpp | 128 +++---- Range queries/MO.cpp | 119 +++--- Range queries/segTree.cpp | 157 ++++---- Reverse a Linked List using Recusion.cpp | 115 +++--- Search/Binary Search.cpp | 58 ++- Search/Linear Search.cpp | 75 ++-- Search/searching.cpp | 57 ++- Search/ternary_search.cpp | 137 +++---- Sorting/BitonicSort.cpp | 129 +++---- Sorting/Bubble Sort.cpp | 85 ++--- Sorting/CocktailSelectionSort.cpp | 160 ++++---- Sorting/CountingSortString.cpp | 75 ++-- Sorting/Counting_Sort.cpp | 93 ++--- Sorting/Heap Sort .cpp | 102 +++-- Sorting/Insertion Sort.cpp | 66 ++-- Sorting/Merge Sort.cpp | 151 ++++---- Sorting/OddEven Sort.cpp | 84 ++--- Sorting/Quick Sort.cpp | 99 +++-- Sorting/Radix Sort.cpp | 103 +++--- Sorting/Selection Sort.cpp | 64 ++-- Sorting/Shell Sort.cpp | 71 ++-- Sorting/Slow Sort.cpp | 89 +++-- Sorting/Tim Sort.cpp | 190 +++++----- Sorting/bucketSort.cpp | 65 ++-- Sparse matrix.cpp | 28 +- Stack Using Array.cpp | 106 +++--- Stack Using Linked List.cpp | 108 +++--- Strassen Matrix Multiplication.cpp | 95 +++-- Tower of Hanoi.cpp | 121 +++--- Tree.cpp | 244 ++++++------ Union_of_2_arrays.cpp | 52 ++- circluar_Queue_using_Linked_List.cpp | 130 +++---- combsort.cpp | 63 ++-- fibonacci.cpp | 66 ++-- searching.cpp | 57 ++- sleep sort.c | 53 ++- smallest-circle.cpp | 203 +++++----- spiral_print.cpp | 103 +++--- ternary_search.cpp | 33 +- 123 files changed, 6110 insertions(+), 7073 deletions(-) create mode 100644 .clang-format diff --git a/.clang-format b/.clang-format new file mode 100644 index 00000000000..73304266bd6 --- /dev/null +++ b/.clang-format @@ -0,0 +1,88 @@ +--- +AccessModifierOffset: -1 +AlignAfterOpenBracket: AlwaysBreak +AlignConsecutiveAssignments: false +AlignConsecutiveDeclarations: false +AlignEscapedNewlinesLeft: true +AlignOperands: false +AlignTrailingComments: false +AllowAllParametersOfDeclarationOnNextLine: false +AllowShortBlocksOnASingleLine: false +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: Empty +AllowShortIfStatementsOnASingleLine: false +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: true +AlwaysBreakTemplateDeclarations: true +BinPackArguments: false +BinPackParameters: false +BraceWrapping: + AfterClass: false + AfterControlStatement: false + AfterEnum: false + AfterFunction: false + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + BeforeCatch: false + BeforeElse: false + IndentBraces: false +BreakBeforeBinaryOperators: None +BreakBeforeBraces: Attach +BreakBeforeTernaryOperators: true +BreakConstructorInitializersBeforeComma: false +BreakAfterJavaFieldAnnotations: false +BreakStringLiterals: false +ColumnLimit: 80 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerAllOnOneLineOrOnePerLine: true +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DerivePointerAlignment: false +DisableFormat: false +ForEachMacros: [ FOR_EACH_RANGE, FOR_EACH, ] +IncludeCategories: + - Regex: '^<.*\.h(pp)?>' + Priority: 1 + - Regex: '^<.*' + Priority: 2 + - Regex: '.*' + Priority: 3 +IndentCaseLabels: true +IndentWidth: 2 +IndentWrappedFunctionNames: false +KeepEmptyLinesAtTheStartOfBlocks: false +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +ObjCBlockIndentWidth: 2 +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: false +PenaltyBreakBeforeFirstCallParameter: 1 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakString: 1000 +PenaltyExcessCharacter: 1000000 +PenaltyReturnTypeOnItsOwnLine: 2000000 +PointerAlignment: Left +ReflowComments: true +SortIncludes: true +SpaceAfterCStyleCast: false +SpaceBeforeAssignmentOperators: true +SpaceBeforeParens: ControlStatements +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: false +SpacesInContainerLiterals: true +SpacesInCStyleCastParentheses: false +SpacesInParentheses: false +SpacesInSquareBrackets: false +Standard: Cpp11 +TabWidth: 8 +UseTab: Never +... diff --git a/Array Left Rotation.cpp b/Array Left Rotation.cpp index 177dada01bf..aa3f895e415 100644 --- a/Array Left Rotation.cpp +++ b/Array Left Rotation.cpp @@ -1,31 +1,31 @@ -#include +#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 a[n]; - cout<<"Enter elements of array=\t"; - for(int i=0;i>a[i]; - } - int temp=0; - for(int i=0;i> n; + cout << "Enter Number of indeces u want to rotate the array to left=\t"; + cin >> k; + int a[n]; + cout << "Enter elements of array=\t"; + for (int i = 0; i < n; i++) { + cin >> a[i]; + } + int temp = 0; + for (int i = 0; i < k; i++) { + temp = a[0]; + for (int j = 0; j < n; j++) { + if (j == n - 1) { + a[n - 1] = temp; + } else { + a[j] = a[j + 1]; + } + } + } + cout << "Your rotated array is=\t"; + for (int j = 0; j < n; j++) { + cout << a[j] << " "; + } + getchar(); + return 0; } diff --git a/Array Right Rotation.cpp b/Array Right Rotation.cpp index 9f3e7603786..d46554ee229 100644 --- a/Array Right Rotation.cpp +++ b/Array Right Rotation.cpp @@ -1,31 +1,28 @@ #include 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; - } - else{ - a[j]=a[j-1];} - - } - +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]; + } } - cout<<"Your rotated array is=\t"; - for(int i=0;i - +#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) -{ - for (int i = 0; i < V; i++) - if (graph[v][i] && c == color[i]) - return false; - return true; +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); - 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); - - - /* If assigning color c doesn't lead to a solution - then remove it */ - color[v] = 0; - } +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); + 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); + + /* If assigning color c doesn't lead to a solution + then remove it */ + color[v] = 0; } - + } } /* A utility function to print solution */ -void printSolution(int color[]) -{ - printf(" Following are the assigned colors \n"); - for (int i = 0; i < V; i++) - printf(" %d ", color[i]); - printf("\n"); +void printSolution(int color[]) { + printf(" Following are the assigned colors \n"); + for (int i = 0; i < V; i++) + printf(" %d ", color[i]); + printf("\n"); } - + // driver program to test above function -int main() -{ - /* Create following graph and test whether it is 3 colorable - (3)---(2) - | / | - | / | - | / | - (0)---(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 main() { + /* Create following graph and test whether it is 3 colorable + (3)---(2) + | / | + | / | + | / | + (0)---(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++) + color[i] = 0; - for (int i = 0; i < V; i++) - color[i] = 0; - - graphColoring(graph, m, color, 0); - return 0; + graphColoring(graph, m, color, 0); + return 0; } diff --git a/Backtracking/N Queens.cpp b/Backtracking/N Queens.cpp index f070c5803ee..ab1695ded26 100644 --- a/Backtracking/N Queens.cpp +++ b/Backtracking/N Queens.cpp @@ -1,82 +1,64 @@ -#include +#include #define N 4 using namespace std; -void printSolution(int board[N][N]) -{ - cout<<"\n"; - for (int i = 0; i < N; i++) - { - for (int j = 0; j < N; j++) - cout<<""<=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 && j >= 0; i--, j--) + if (board[i][j]) + return false; + + /* Check lower diagonal on left side */ + for (i = row, j = col; j >= 0 && i < N; i++, j--) + if (board[i][j]) + return false; + + return true; } - -void solveNQ(int board[N][N], int col) -{ - - 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) ) - { - /* Place this queen in board[i][col] */ -// cout<<"\n"<= 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)) { + /* Place this queen in board[i][col] */ + // cout<<"\n"< #define size 4 using namespace std; -int solveMaze(int currposrow,int currposcol,int maze[size][size],int soln[size][size]) -{ - if((currposrow==size-1) && (currposcol==size-1)) - { - soln[currposrow][currposcol]=1; - for(int i=0;i +#include using namespace std; -///N=9; -int n=9; - - -bool isPossible(int mat[][9],int i,int j,int no){ - ///Row or col nahin hona chahiye - for(int x=0;x +#include using namespace std; - -struct node -{ - int val; - node *left; - node *right; +struct node { + int val; + node* left; + node* right; }; -struct queue -{ - node *t[100]; - int front; - int rear; +struct queue { + node* t[100]; + int front; + int rear; }; queue q; - -void enqueue(node *n) -{ - q.t[q.rear++]=n; +void enqueue(node* n) { + q.t[q.rear++] = n; } -node * dequeue() -{ - return (q.t[q.front++]); +node* dequeue() { + return (q.t[q.front++]); } - - -void Insert(node *n, int x) -{ - if (xval) - { - if (n->left==NULL) - { - node *temp=new node; - temp->val=x; - temp->left=NULL; - temp->right=NULL; - n->left=temp; - } - else - { - Insert(n->left, x); - } - } - else - { - if (n->right==NULL) - { - node *temp=new node; - temp->val=x; - temp->left=NULL; - temp->right=NULL; - n->left=temp; - } - else - { - Insert(n->right, x); - } - } +void Insert(node* n, int x) { + if (x < n->val) { + if (n->left == NULL) { + node* temp = new node; + temp->val = x; + temp->left = NULL; + temp->right = NULL; + n->left = temp; + } else { + Insert(n->left, x); + } + } else { + if (n->right == NULL) { + node* temp = new node; + temp->val = x; + temp->left = NULL; + temp->right = NULL; + n->left = temp; + } else { + Insert(n->right, x); + } + } } - - - -int findMaxInLeftST(node *n) -{ - while(n->right!=NULL) - { - n=n->right; - } - return n->val; +int findMaxInLeftST(node* n) { + while (n->right != NULL) { + n = n->right; + } + return n->val; } -void Remove(node *p, node *n, int x) -{ - if (n->val==x) - { - if (n->right==NULL && n->left==NULL) - { - if (xval) - { - p->right=NULL; - } - else - { - p->left=NULL; - } - } - else if (n->right==NULL) - { - if (xval) - { - p->right=n->left; - } - else - { - p->left=n->left; - } - } - else if (n->left==NULL) - { - if (xval) - { - p->right=n->right; - } - else - { - p->left=n->right; - } - } - else - { - int y=findMaxInLeftST(n->left); - n->val=y; - Remove(n, n->right, y); - } - } - else if (xval) - { - Remove(n, n->left, x); - } - else - { - Remove(n, n->right, x); - } +void Remove(node* p, node* n, int x) { + if (n->val == x) { + if (n->right == NULL && n->left == NULL) { + if (x < p->val) { + p->right = NULL; + } else { + p->left = NULL; + } + } else if (n->right == NULL) { + if (x < p->val) { + p->right = n->left; + } else { + p->left = n->left; + } + } 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; + Remove(n, n->right, y); + } + } else if (x < n->val) { + Remove(n, n->left, x); + } else { + Remove(n, n->right, x); + } } - - - -void BFT(node *n) -{ - if(n!=NULL) - { - cout<val<<" "; - enqueue(n->left); - enqueue(n->right); - BFT(dequeue()); - } +void BFT(node* n) { + if (n != NULL) { + cout << n->val << " "; + enqueue(n->left); + enqueue(n->right); + BFT(dequeue()); + } } -void Pre(node *n) -{ - if (n!=NULL) - { - cout<val<<" "; - Pre(n->left); - Pre(n->right); - } +void Pre(node* n) { + if (n != NULL) { + cout << n->val << " "; + Pre(n->left); + Pre(n->right); + } } -void In(node *n) -{ - if (n!=NULL) - { - In(n->left); - cout<val<<" "; - In(n->right); - } +void In(node* n) { + if (n != NULL) { + In(n->left); + cout << n->val << " "; + In(n->right); + } } - -void Post(node *n) -{ - if (n!=NULL) - { - Post(n->left); - Post(n->right); - cout<val<<" "; - } +void Post(node* n) { + if (n != NULL) { + Post(n->left); + Post(n->right); + cout << n->val << " "; + } } - - -int main() -{ - 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; - 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<<"\nEnter Your Choice : "; - cin>>ch; - int x; - 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; - } - } - while(ch!=0); +int main() { + 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; + 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 << "\nEnter Your Choice : "; + cin >> ch; + int x; + 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; + } + } while (ch != 0); } diff --git a/Binary Search.cpp b/Binary Search.cpp index cb67e3a077f..7c4f79a1bba 100644 --- a/Binary Search.cpp +++ b/Binary Search.cpp @@ -1,34 +1,32 @@ #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]) - return m; - else if(key>n; - cout<<"Enter array elements: "; - int a[n]; - for (int i = 0; i < n; ++i) - { - cin>>a[i]; - } - cout<<"Enter search key: "; - cin>>key; - int res = binary_search(a,0,n-1,key); - if(res != -1) - cout<> n; + cout << "Enter array elements: "; + int a[n]; + for (int i = 0; i < n; ++i) { + cin >> a[i]; + } + cout << "Enter search key: "; + cin >> key; + int res = binary_search(a, 0, n - 1, key); + if (res != -1) + cout << key << " found at index " << res << endl; + else + cout << key << " not found" << endl; + return 0; } \ No newline at end of file diff --git a/Buzz_number.cpp b/Buzz_number.cpp index 3d39c50f63c..93d63fc5eb0 100644 --- a/Buzz_number.cpp +++ b/Buzz_number.cpp @@ -1,17 +1,16 @@ -//A buzz number is a number that is either divisble by 7 or has last digit as 7. +// A buzz number is a number that is either divisble by 7 or has last digit +// as 7. #include using namespace std; -int main() -{ - int n,t; +int main() { + int n, t; cin >> 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; + 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; } return 0; } diff --git a/Circular Linked List.cpp b/Circular Linked List.cpp index bd68043dc05..6708b39d9ee 100644 --- a/Circular Linked List.cpp +++ b/Circular Linked List.cpp @@ -1,109 +1,97 @@ -#include +#include using namespace std; -struct node -{ - int val; - node *next; +struct node { + int val; + node* next; }; -node *start; +node* start; -void insert(int x) -{ - node *t=start; - - if (start!=NULL) - { - while(t->next!=start) - { - t=t->next; - } - 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; - } -} +void insert(int x) { + node* t = start; -void remove(int x) -{ - node *t=start; - node *p; - while(t->val!=x) - { - p=t; - t=t->next; - } - p->next=t->next; - delete t; + if (start != NULL) { + while (t->next != start) { + t = t->next; + } + 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; + } } -void search(int x) -{ - node *t= start; - int found =0; - while(t->next!=start) - { - if(t->val==x) - { - cout<<"\nFound"; - found=1; - break; - } - t=t->next; - } - if(found==0) - { - cout<<"\nNot Found"; - } +void remove(int x) { + node* t = start; + node* p; + while (t->val != x) { + p = t; + t = t->next; + } + p->next = t->next; + delete t; } -void show() -{ - node *t=start; - do - { - cout<val<<"\t"; - t=t->next; - } - while(t!=start); +void search(int x) { + node* t = start; + int found = 0; + while (t->next != start) { + if (t->val == x) { + cout << "\nFound"; + found = 1; + break; + } + t = t->next; + } + if (found == 0) { + cout << "\nNot Found"; + } +} +void show() { + node* t = start; + do { + cout << t->val << "\t"; + t = t->next; + } while (t != start); } -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; - 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; - } - } - while(choice!=0); +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; + 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; + } + } while (choice != 0); - return 0; + return 0; } diff --git a/Circular Queue Using Array.cpp b/Circular Queue Using Array.cpp index d91f31af3dc..a1b205046a4 100644 --- a/Circular Queue Using Array.cpp +++ b/Circular Queue Using Array.cpp @@ -1,77 +1,57 @@ -#include +#include using namespace std; int queue[10]; -int front=0; -int rear=0; -int count=0; - -void Enque(int x) -{ - if(count==10) - { - cout<<"\nOverflow"; - } - else - { - queue[rear]=x; - rear=(rear+1)%10; - count++; - } +int front = 0; +int rear = 0; +int count = 0; + +void Enque(int x) { + if (count == 10) { + cout << "\nOverflow"; + } else { + queue[rear] = x; + rear = (rear + 1) % 10; + count++; + } } -void Deque() -{ - if (front==rear) - { - cout<<"\nUnderflow"; - } - - else - { - cout<<"\n"<>ch; - if (ch==1) - { - cout<<"\nInsert : "; - cin>>x; - Enque(x); - } - else if (ch==2) - { - Deque(); - } - else if (ch==3) - { - show(); - } - } - while(ch!=0); - - return 0; +int main() { + int ch, x; + do { + cout << "\n1. Enque"; + cout << "\n2. Deque"; + cout << "\n3. Print"; + cout << "\nEnter Your Choice : "; + cin >> ch; + if (ch == 1) { + cout << "\nInsert : "; + cin >> x; + Enque(x); + } else if (ch == 2) { + Deque(); + } else if (ch == 3) { + show(); + } + } while (ch != 0); + + return 0; } - diff --git a/Computer Oriented Statistical Methods/Gaussian_elimination.cpp b/Computer Oriented Statistical Methods/Gaussian_elimination.cpp index d98e5f626da..ed8996e8f7b 100644 --- a/Computer Oriented Statistical Methods/Gaussian_elimination.cpp +++ b/Computer Oriented Statistical Methods/Gaussian_elimination.cpp @@ -1,59 +1,51 @@ -#include +#include using namespace std; -int main() -{ - int mat_size,i,j,step; +int main() { + 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. - } + cout << endl << "Enter value of the matrix: " << endl; + for (i = 0; i < mat_size; i++) { + for (j = 0; j <= mat_size; j++) { + cin >> mat[i][j]; // Enter (mat_size*mat_size) value of the matrix. } + } - for(step=0;step=0;i--) - { - double sum = 0; - 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) - x[i][i] = 0; - else - x[i][i] = (x[i][mat_size] - sum)/(x[i][i]); - - cout<<"x"<= 0; i--) { + double sum = 0; + for (j = mat_size - 1; j > i; j--) { + x[i][j] = x[j][j] * x[i][j]; + sum = x[i][j] + sum; } -return 0; + if (x[i][i] == 0) + x[i][i] = 0; + else + x[i][i] = (x[i][mat_size] - sum) / (x[i][i]); + + cout << "x" << i << "= " << x[i][i] << endl; + } + return 0; } diff --git a/Data Structure/AVLtree.cpp b/Data Structure/AVLtree.cpp index a3cd5291963..c5e6a915111 100644 --- a/Data Structure/AVLtree.cpp +++ b/Data Structure/AVLtree.cpp @@ -4,156 +4,153 @@ using namespace std; typedef struct node { - int data; - int height; - struct node* left; - struct node* right; -}node; + int data; + int height; + struct node* left; + struct node* right; +} node; int max(int a, int b) { - return a > b ? a : b; + return a > b ? a : b; } // Returns a new Node node* createNode(int data) { - node *nn = new node(); - nn->data = data; - nn->height = 0; - nn->left = NULL; - nn->right = NULL; - return nn; + node* nn = new node(); + nn->data = data; + nn->height = 0; + nn->left = NULL; + nn->right = NULL; + return nn; } // Returns height of tree -int height(node *root) { - if(root==NULL) - return 0; - return 1 + max(height(root->left), height(root->right)); +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) { - return height(root->left) - height(root->right); +int getBalance(node* root) { + return height(root->left) - height(root->right); } // Returns Node after Right Rotation -node* rightRotate(node *root) { - node *t = root->left; - node *u = t->right; - t->right = root; - root->left = u; - return t; +node* rightRotate(node* root) { + node* t = root->left; + node* u = t->right; + t->right = root; + root->left = u; + return t; } // Returns Node after Left Rotation -node* leftRotate(node *root) { - node *t = root->right; - node *u = t->left; - t->left = root; - root->right = u; - return t; +node* leftRotate(node* root) { + node* t = root->right; + node* u = t->left; + t->left = root; + root->right = u; + return t; } // Returns node with minimum value in the tree node* minValue(node* root) { - if(root->left==NULL) - return root; - return minValue(root->left); + if (root->left == NULL) + return root; + return minValue(root->left); } // Balanced Insertion node* insert(node* root, int item) { - node *nn = createNode(item); - if(root == NULL) - return nn; - if(itemdata) - 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 - } - 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; + node* nn = createNode(item); + if (root == NULL) + return nn; + 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 + } 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) - return root; - if(key < root->data) - root->left = deleteNode(root->left, key); - else if(key > root->data) - root->right = deleteNode(root->right, key); - - else { - // Node to be deleted is leaf node or have only one Child - if(!root->right) { - node* temp = root->left; - delete(root); - root = NULL; - return temp; - } - else if(!root->left) { - node* temp = root->right; - delete(root); - root = NULL; - return temp; - } - // Node to be deleted have both left and right subtrees - node *temp = minValue(root->right); - root->data = temp->data; - root->right = deleteNode(root->right, temp->data); - } - // Balancing Tree after deletion - return root; +node* deleteNode(node* root, int key) { + if (root == NULL) + return root; + if (key < root->data) + root->left = deleteNode(root->left, key); + else if (key > root->data) + root->right = deleteNode(root->right, key); + + else { + // Node to be deleted is leaf node or have only one Child + if (!root->right) { + node* temp = root->left; + delete (root); + root = NULL; + return temp; + } else if (!root->left) { + node* temp = root->right; + delete (root); + root = NULL; + return temp; + } + // Node to be deleted have both left and right subtrees + node* temp = minValue(root->right); + root->data = temp->data; + root->right = deleteNode(root->right, temp->data); + } + // Balancing Tree after deletion + return root; } - // LevelOrder (Breadth First Search) void levelOrder(node* root) { - queue q; - q.push(root); - while(!q.empty()) { - root = q.front(); - cout<data<<" "; - q.pop(); - if(root->left) - q.push(root->left); - if(root->right) - q.push(root->right); - } + queue q; + q.push(root); + while (!q.empty()) { + root = q.front(); + cout << root->data << " "; + q.pop(); + if (root->left) + q.push(root->left); + if (root->right) + q.push(root->right); + } } int main() { - // Testing AVL Tree - node *root = NULL; - int i; - for(i = 1 ; i <= 7 ; i++) - root = insert(root, i); - cout<<"LevelOrder: "; - levelOrder(root); - root = deleteNode(root, 1); // Deleting key with value 1 - cout<<"\nLevelOrder: "; - levelOrder(root); - root = deleteNode(root, 4); // Deletin key with value 4 - cout<<"\nLevelOrder: "; - levelOrder(root); - return 0; + // Testing AVL Tree + node* root = NULL; + int i; + for (i = 1; i <= 7; i++) + root = insert(root, i); + cout << "LevelOrder: "; + levelOrder(root); + root = deleteNode(root, 1); // Deleting key with value 1 + cout << "\nLevelOrder: "; + levelOrder(root); + 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 5b83263bc05..1ad53394aad 100644 --- a/Data Structure/Binary Search Tree.cpp +++ b/Data Structure/Binary Search Tree.cpp @@ -1,232 +1,169 @@ -#include +#include using namespace std; - -struct node -{ - int val; - node *left; - node *right; +struct node { + int val; + node* left; + node* right; }; -struct queue -{ - node *t[100]; - int front; - int rear; +struct queue { + node* t[100]; + int front; + int rear; }; queue q; - -void enqueue(node *n) -{ - q.t[q.rear++]=n; +void enqueue(node* n) { + q.t[q.rear++] = n; } -node * dequeue() -{ - return (q.t[q.front++]); +node* dequeue() { + return (q.t[q.front++]); } - - -void Insert(node *n, int x) -{ - if (xval) - { - if (n->left==NULL) - { - node *temp=new node; - temp->val=x; - temp->left=NULL; - temp->right=NULL; - n->left=temp; - } - else - { - Insert(n->left, x); - } - } - else - { - if (n->right==NULL) - { - node *temp=new node; - temp->val=x; - temp->left=NULL; - temp->right=NULL; - n->left=temp; - } - else - { - Insert(n->right, x); - } - } +void Insert(node* n, int x) { + if (x < n->val) { + if (n->left == NULL) { + node* temp = new node; + temp->val = x; + temp->left = NULL; + temp->right = NULL; + n->left = temp; + } else { + Insert(n->left, x); + } + } else { + if (n->right == NULL) { + node* temp = new node; + temp->val = x; + temp->left = NULL; + temp->right = NULL; + n->left = temp; + } else { + Insert(n->right, x); + } + } } - - - -int findMaxInLeftST(node *n) -{ - while(n->right!=NULL) - { - n=n->right; - } - return n->val; +int findMaxInLeftST(node* n) { + while (n->right != NULL) { + n = n->right; + } + return n->val; } -void Remove(node *p, node *n, int x) -{ - if (n->val==x) - { - if (n->right==NULL && n->left==NULL) - { - if (xval) - { - p->right=NULL; - } - else - { - p->left=NULL; - } - } - else if (n->right==NULL) - { - if (xval) - { - p->right=n->left; - } - else - { - p->left=n->left; - } - } - else if (n->left==NULL) - { - if (xval) - { - p->right=n->right; - } - else - { - p->left=n->right; - } - } - else - { - int y=findMaxInLeftST(n->left); - n->val=y; - Remove(n, n->right, y); - } - } - else if (xval) - { - Remove(n, n->left, x); - } - else - { - Remove(n, n->right, x); - } +void Remove(node* p, node* n, int x) { + if (n->val == x) { + if (n->right == NULL && n->left == NULL) { + if (x < p->val) { + p->right = NULL; + } else { + p->left = NULL; + } + } else if (n->right == NULL) { + if (x < p->val) { + p->right = n->left; + } else { + p->left = n->left; + } + } 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; + Remove(n, n->right, y); + } + } else if (x < n->val) { + Remove(n, n->left, x); + } else { + Remove(n, n->right, x); + } } - - - -void BFT(node *n) -{ - if(n!=NULL) - { - cout<val<<" "; - enqueue(n->left); - enqueue(n->right); - BFT(dequeue()); - } +void BFT(node* n) { + if (n != NULL) { + cout << n->val << " "; + enqueue(n->left); + enqueue(n->right); + BFT(dequeue()); + } } -void Pre(node *n) -{ - if (n!=NULL) - { - cout<val<<" "; - Pre(n->left); - Pre(n->right); - } +void Pre(node* n) { + if (n != NULL) { + cout << n->val << " "; + Pre(n->left); + Pre(n->right); + } } -void In(node *n) -{ - if (n!=NULL) - { - In(n->left); - cout<val<<" "; - In(n->right); - } +void In(node* n) { + if (n != NULL) { + In(n->left); + cout << n->val << " "; + In(n->right); + } } - -void Post(node *n) -{ - if (n!=NULL) - { - Post(n->left); - Post(n->right); - cout<val<<" "; - } +void Post(node* n) { + if (n != NULL) { + Post(n->left); + Post(n->right); + cout << n->val << " "; + } } - - -int main() -{ - 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; - 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<<"\nEnter Your Choice : "; - cin>>ch; - int x; - 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; - } - } - while(ch!=0); +int main() { + 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; + 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 << "\nEnter Your Choice : "; + cin >> ch; + int x; + 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; + } + } while (ch != 0); } diff --git a/Data Structure/Doubly Linked List.cpp b/Data Structure/Doubly Linked List.cpp index db550d4225b..a1535d948e5 100644 --- a/Data Structure/Doubly Linked List.cpp +++ b/Data Structure/Doubly Linked List.cpp @@ -1,125 +1,114 @@ -#include +#include using namespace std; -struct node -{ - int val; - node *prev; - node *next; +struct node { + int val; + node* prev; + node* next; }; -node *start; +node* start; -void insert(int x) -{ - node *t=start; - if (start!=NULL) - { - while(t->next!=NULL) - { - t=t->next; - } - 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; - } +void insert(int x) { + node* t = start; + if (start != NULL) { + while (t->next != NULL) { + t = t->next; + } + 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; + } } -void remove(int x) -{ - node *t=start; - while(t->val!=x) - { - t=t->next; - } - t->prev->next=t->next; - t->next->prev=t->prev; - delete t; +void remove(int x) { + node* t = start; + while (t->val != x) { + t = t->next; + } + 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) - { - if(t->val==x) - { - cout<<"\nFound"; - found=1; - break; - } - t=t->next; - } - if(found==0) - { - cout<<"\nNot Found"; - } +void search(int x) { + node* t = start; + int found = 0; + while (t != NULL) { + if (t->val == x) { + cout << "\nFound"; + found = 1; + break; + } + t = t->next; + } + if (found == 0) { + cout << "\nNot Found"; + } } -void show() -{ - node *t=start; - while(t!=NULL) - { - cout<val<<"\t"; - t=t->next; - } - +void show() { + node* t = start; + while (t != NULL) { + cout << t->val << "\t"; + t = t->next; + } } -void reverseShow() -{ - node *t=start; - while(t->next!=NULL) - { - t=t->next; - } - while(t!=NULL) - { - cout<val<<"\t"; - t=t->prev; - } +void reverseShow() { + node* t = start; + while (t->next != NULL) { + t = t->next; + } + while (t != NULL) { + cout << t->val << "\t"; + t = t->prev; + } } -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; - 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; - } - } - while(choice!=0); +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; + 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; + } + } while (choice != 0); - return 0; + return 0; } diff --git a/Data Structure/Linked List.cpp b/Data Structure/Linked List.cpp index 5abebd58458..2ccf2b9047f 100644 --- a/Data Structure/Linked List.cpp +++ b/Data Structure/Linked List.cpp @@ -1,125 +1,115 @@ -#include +#include using namespace std; -struct node -{ - int val; - node *next; +struct node { + int val; + node* next; }; -node *start; +node* start; -void insert(int x) -{ - node *t=start; - if (start!=NULL) - { - while(t->next!=NULL) - { - t=t->next; - } - 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; - } +void insert(int x) { + node* t = start; + if (start != NULL) { + while (t->next != NULL) { + t = t->next; + } + 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; + } } -void remove(int x){ +void remove(int x) { + if (start == NULL) { + cout << "\nLinked List is empty\n"; + return; + } else if (start->val == x) { + node* temp = start; + start = start->next; + delete temp; + return; + } - if( start == NULL ){ - cout<<"\nLinked List is empty\n"; - return ; - } - else if( start->val == x ){ - node *temp = start; - start = start->next; - delete temp; - return ; - } + node *temp = start, *parent = start; - node *temp = start, *parent = start; + while (temp != NULL && temp->val != x) { + parent = temp; + temp = temp->next; + } - while( temp != NULL && temp->val != x ){ - parent = temp; - temp = temp->next; - } + if (temp == NULL) { + cout << endl << x << " not found in list\n"; + return; + } - if( temp == NULL ){ - cout <next = temp->next; - delete temp; + parent->next = temp->next; + delete temp; } -void search(int x) -{ - node *t= start; - int found =0; - while(t!=NULL) - { - if(t->val==x) - { - cout<<"\nFound"; - found=1; - break; - } - t=t->next; - } - if(found==0) - { - cout<<"\nNot Found"; - } +void search(int x) { + node* t = start; + int found = 0; + while (t != NULL) { + if (t->val == x) { + cout << "\nFound"; + found = 1; + break; + } + t = t->next; + } + if (found == 0) { + cout << "\nNot Found"; + } } -void show() -{ - node *t=start; - while(t!=NULL) - { - cout<val<<"\t"; - t=t->next; - } - +void show() { + node* t = start; + while (t != NULL) { + cout << t->val << "\t"; + t = t->next; + } } -int main() -{ - int choice, x; - do - { - cout<<"\n1. Insert"; - cout<<"\n2. Delete"; - cout<<"\n3. Search"; - cout<<"\n4. Print"; - 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; - } - } - while(choice!=0); +int main() { + int choice, x; + do { + cout << "\n1. Insert"; + cout << "\n2. Delete"; + cout << "\n3. Search"; + cout << "\n4. Print"; + 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; + } + } while (choice != 0); - return 0; + return 0; } diff --git a/Data Structure/List Array.cpp b/Data Structure/List Array.cpp index 21f5c6ae53c..a2f4c5cb33e 100644 --- a/Data Structure/List Array.cpp +++ b/Data Structure/List Array.cpp @@ -1,185 +1,153 @@ -#include +#include using namespace std; -struct list -{ - int data[50]; - 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)); - } - - int LinarSearch(int *array, int x) - { - for (int i = 0; i < top; i++) - { - if (array[i]==x) - { - return i; - } - } - - return -1; - } - - int Search(int x) - { - int pos=-1; - - if (isSorted) - { - pos=BinarySearch(data, 0, top-1, x); - } - - else - { - pos=LinarSearch(data, x); - } - - if (pos!=-1) - { - cout<<"\nElement found at position : "< pos; i--) - { - data[i]=data[i-1]; - } - top++; - data[pos]=x; - } - } - - void Remove(int x) - { - int pos=Search(x); - cout<<"\n"< 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) { + return i; + } + } + + return -1; + } + + int Search(int x) { + int pos = -1; + + if (isSorted) { + pos = BinarySearch(data, 0, top - 1, x); + } + + else { + pos = LinarSearch(data, x); + } + + if (pos != -1) { + cout << "\nElement found at position : " << pos; + } else { + cout << "\nElement not found"; + } + return pos; + } + + void Sort() { + int i, j, pos; + for (i = 0; i < top; i++) { + int min = data[i]; + for (j = i + 1; j < top; j++) { + if (data[j] < min) { + pos = j; + min = data[pos]; + } + } + + int temp = data[i]; + data[i] = data[pos]; + data[pos] = temp; + } + isSorted = true; + } + + void insert(int x) { + if (!isSorted) { + if (top == 49) { + cout << "\nOverflow"; + } else { + data[top] = x; + top++; + } + } + + else { + int pos = 0; + + for (int i = 0; i < top - 1; i++) { + if (data[i] <= x && x <= data[i + 1]) { + pos = i + 1; + break; + } + } + if (pos == 0) { + pos = top - 1; + } + + for (int i = top; i > pos; i--) { + data[i] = data[i - 1]; + } + top++; + data[pos] = x; + } + } + + void Remove(int x) { + int pos = Search(x); + cout << "\n" << data[pos] << " deleted"; + for (int i = pos; i < top; i++) { + data[i] = data[i + 1]; + } + top--; + } + + void Show() { + for (int i = 0; i < top; i++) { + cout << data[i] << "\t"; + } + } }; -int main() -{ - list L; - int choice; - int x; - do - { - cout<<"\n1.Insert"; - cout<<"\n2.Delete"; - cout<<"\n3.Search"; - cout<<"\n4.Sort"; - cout<<"\n5.Print"; - cout<<"\n\nEnter Your Choice : "; - cin>>choice; - 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; - } - } - while(choice!=0); - return 0; +int main() { + list L; + int choice; + int x; + do { + cout << "\n1.Insert"; + cout << "\n2.Delete"; + cout << "\n3.Search"; + cout << "\n4.Sort"; + cout << "\n5.Print"; + cout << "\n\nEnter Your Choice : "; + cin >> choice; + 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; + } + } while (choice != 0); + return 0; } diff --git a/Data Structure/MorrisInorder.cpp b/Data Structure/MorrisInorder.cpp index 5ea630fac0a..029999ef376 100644 --- a/Data Structure/MorrisInorder.cpp +++ b/Data Structure/MorrisInorder.cpp @@ -2,93 +2,92 @@ #include /************************** - @author shrutisheoran + @author shrutisheoran **************************/ using namespace std; struct Btree { - int data; - struct Btree* left; //Pointer to left subtree - struct Btree* right; //Pointer to right subtree + int data; + 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 - nn->data = d; - nn->left = NULL; - nn->right = NULL; - if(*root == NULL) { - *root = nn; - return; - } - else { - queue q; - // Adding root node to queue - q.push(*root); - while(!q.empty()) { - Btree *node = q.front(); - // Removing parent node from queue - q.pop(); - if(node->left) - // Adding left child of removed node to queue - q.push(node->left); - else { - // Adding new node if no left child is present - node->left = nn; - return; - } - if(node->right) - // Adding right child of removed node to queue - q.push(node->right); - else { - // Adding new node if no right child is present - node->right = nn; - return; - } - } - } +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) { + *root = nn; + return; + } else { + queue q; + // Adding root node to queue + q.push(*root); + while (!q.empty()) { + Btree* node = q.front(); + // Removing parent node from queue + q.pop(); + if (node->left) + // Adding left child of removed node to queue + q.push(node->left); + else { + // Adding new node if no left child is present + node->left = nn; + return; + } + if (node->right) + // Adding right child of removed node to queue + q.push(node->right); + else { + // Adding new node if no right child is present + node->right = nn; + return; + } + } + } } -void morrisInorder(Btree *root) { - Btree *curr = root; - Btree *temp; - while(curr) { - if(curr->left==NULL) { - cout<data<<" "; - // If left of current node is NULL then curr is shifted to right - curr = curr->right; - } - else { - // Left of current node is stored in temp - temp = curr->left; - // Moving to extreme right of temp - 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) { - 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<<" "; - temp->right = NULL; - // current node is made to point its right subtree - curr = curr->right; - } - } - } +void morrisInorder(Btree* root) { + Btree* curr = root; + Btree* temp; + 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 { + // Left of current node is stored in temp + temp = curr->left; + // Moving to extreme right of temp + 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) { + temp->right = curr; + // current node is made to point its left subtree + curr = curr->left; + } + // If extreme right already points to currrent node it it set to null + else if (temp->right == curr) { + cout << curr->data << " "; + temp->right = NULL; + // current node is made to point its right subtree + curr = curr->right; + } + } + } } int main() { - // Testing morrisInorder funtion - Btree *root = NULL; - int i; - for(i = 1 ; i <= 7 ; i++) - insert(&root, i); - cout<<"Morris Inorder: "; - morrisInorder(root); - return 0; + // Testing morrisInorder funtion + Btree* root = NULL; + int i; + for (i = 1; i <= 7; i++) + insert(&root, i); + cout << "Morris Inorder: "; + morrisInorder(root); + return 0; } diff --git a/Data Structure/Queue Using Array.cpp b/Data Structure/Queue Using Array.cpp index 7b5816f84b5..548d0c031f5 100644 --- a/Data Structure/Queue Using Array.cpp +++ b/Data Structure/Queue Using Array.cpp @@ -1,78 +1,57 @@ -#include +#include using namespace std; int queue[10]; -int front=0; -int rear=0; - -void Enque(int x) -{ - if(rear==10) - { - cout<<"\nOverflow"; - } - else - { - queue[rear++]=x; - } +int front = 0; +int rear = 0; + +void Enque(int x) { + if (rear == 10) { + cout << "\nOverflow"; + } else { + queue[rear++] = x; + } } -void Deque() -{ - if (front==rear) - { - cout<<"\nUnderflow"; - } - - else - { - cout<<"\n"<>ch; - if (ch==1) - { - cout<<"\nInsert : "; - cin>>x; - Enque(x); - } - else if (ch==2) - { - Deque(); - } - else if (ch==3) - { - show(); - } - } - while(ch!=0); - - return 0; +int main() { + int ch, x; + do { + cout << "\n1. Enque"; + cout << "\n2. Deque"; + cout << "\n3. Print"; + cout << "\nEnter Your Choice : "; + cin >> ch; + if (ch == 1) { + cout << "\nInsert : "; + cin >> x; + Enque(x); + } else if (ch == 2) { + Deque(); + } else if (ch == 3) { + show(); + } + } while (ch != 0); + + return 0; } - diff --git a/Data Structure/Queue Using Linked List.cpp b/Data Structure/Queue Using Linked List.cpp index acf32ebd503..8ada3092cdc 100644 --- a/Data Structure/Queue Using Linked List.cpp +++ b/Data Structure/Queue Using Linked List.cpp @@ -1,90 +1,68 @@ -#include +#include using namespace std; -struct node -{ - int val; - node *next; +struct node { + int val; + node* next; }; - node *front, *rear; +void Enque(int x) { + if (rear == NULL) { + node* n = new node; + n->val = x; + n->next = NULL; + rear = n; + front = n; + } -void Enque(int x) -{ - if (rear==NULL) - { - node *n= new node; - n->val=x; - n->next=NULL; - rear=n; - front=n; - } - - else - { - - node *n = new node; - n->val=x; - n->next=NULL; - rear->next=n; - rear=n; - } + else { + node* n = new node; + n->val = x; + n->next = NULL; + rear->next = n; + rear = n; + } } -void Deque() -{ - if (rear==front) - { - cout<<"\nUnderflow"; - } - else - { - node *t = front; - cout<<"\n"<val<<" deleted"; - front=front->next; - delete t; - } +void Deque() { + if (rear == front) { + cout << "\nUnderflow"; + } else { + node* t = front; + cout << "\n" << t->val << " deleted"; + front = front->next; + delete t; + } } -void show() -{ - node *t=front; - while(t!=NULL) - { - cout<val<<"\t"; - t=t->next; - } +void show() { + node* t = front; + while (t != NULL) { + cout << t->val << "\t"; + t = t->next; + } } -int main() -{ - int ch, x; - do - { - cout<<"\n1. Enque"; - cout<<"\n2. Deque"; - cout<<"\n3. Print"; - cout<<"\nEnter Your Choice : "; - cin>>ch; - if (ch==1) - { - cout<<"\nInsert : "; - cin>>x; - Enque(x); - } - else if (ch==2) - { - Deque(); - } - else if (ch==3) - { - show(); - } - } - while(ch!=0); +int main() { + int ch, x; + do { + cout << "\n1. Enque"; + cout << "\n2. Deque"; + cout << "\n3. Print"; + cout << "\nEnter Your Choice : "; + cin >> ch; + if (ch == 1) { + cout << "\nInsert : "; + cin >> x; + Enque(x); + } else if (ch == 2) { + Deque(); + } else if (ch == 3) { + show(); + } + } while (ch != 0); - return 0; + return 0; } - diff --git a/Data Structure/Stack Using Array.cpp b/Data Structure/Stack Using Array.cpp index c5ad146cb40..10f0c2fc098 100644 --- a/Data Structure/Stack Using Array.cpp +++ b/Data Structure/Stack Using Array.cpp @@ -1,80 +1,58 @@ -#include +#include using namespace std; -int *stack; -int top=0, size; +int* stack; +int top = 0, size; -void push(int x) -{ - if(top==size) - { - cout<<"\nOverflow"; - } - else - { - stack[top++]=x; - } +void push(int x) { + if (top == size) { + cout << "\nOverflow"; + } else { + stack[top++] = x; + } } -void pop() -{ - if (top==0) - { - cout<<"\nUnderflow"; - } - else - { - cout<<"\n"<>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<<"\nInsert : "; - cin>>x; - push(x); - } - else if (ch==2) - { - pop(); - } - else if (ch==3) - { - show(); - } - else if(ch==4) - { - topmost(); - } - } - while(ch!=0); +int main() { + 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 << "\nInsert : "; + cin >> x; + push(x); + } else if (ch == 2) { + pop(); + } else if (ch == 3) { + show(); + } else if (ch == 4) { + topmost(); + } + } while (ch != 0); - return 0; + return 0; } - diff --git a/Data Structure/Stack Using Linked List.cpp b/Data Structure/Stack Using Linked List.cpp index 753fda8ed9e..abea4b9e06a 100644 --- a/Data Structure/Stack Using Linked List.cpp +++ b/Data Structure/Stack Using Linked List.cpp @@ -1,75 +1,57 @@ -#include +#include using namespace std; -struct node -{ - int val; - node *next; +struct node { + int val; + node* next; }; +node* top; -node *top; - -void push(int x) -{ - node *n = new node; - n->val=x; - n->next=top; - top=n; +void push(int x) { + node* n = new node; + n->val = x; + n->next = top; + top = n; } -void pop() -{ - if (top==NULL) - { - cout<<"\nUnderflow"; - } - else - { - node *t = top; - cout<<"\n"<val<<" deleted"; - top=top->next; - delete t; - } +void pop() { + if (top == NULL) { + cout << "\nUnderflow"; + } else { + node* t = top; + cout << "\n" << t->val << " deleted"; + top = top->next; + delete t; + } } -void show() -{ - node *t=top; - while(t!=NULL) - { - cout<val<<"\n"; - t=t->next; - } +void show() { + node* t = top; + while (t != NULL) { + cout << t->val << "\n"; + t = t->next; + } } -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<<"\nInsert : "; - cin>>x; - push(x); - } - else if (ch==2) - { - pop(); - } - else if (ch==3) - { - show(); - } - } - while(ch!=0); - - return 0; +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 << "\nInsert : "; + cin >> x; + push(x); + } else if (ch == 2) { + pop(); + } else if (ch == 3) { + show(); + } + } while (ch != 0); + + return 0; } - diff --git a/Data Structure/Tree.cpp b/Data Structure/Tree.cpp index 963779abe6a..406ff26e0a5 100644 --- a/Data Structure/Tree.cpp +++ b/Data Structure/Tree.cpp @@ -1,160 +1,130 @@ -#include +#include using namespace std; - -struct node -{ - int val; - node *left; - node *right; +struct node { + int val; + node* left; + node* right; }; -struct queue -{ - node *t[100]; - int front; - int rear; +struct queue { + node* t[100]; + int front; + int rear; }; queue q; - -void enqueue(node *n) -{ - q.t[q.rear++]=n; +void enqueue(node* n) { + q.t[q.rear++] = n; } -node * dequeue() -{ - return (q.t[q.front++]); +node* dequeue() { + return (q.t[q.front++]); } - - -void CreateTree(node *curr, node *n, int x, char pos) -{ - if(n!=NULL) - { - char ch; - cout<<"\nLeft or Right of "<val<<" : "; - cin>>ch; - if(ch=='l') - CreateTree(n, n->left, x, ch); - else if(ch=='r') - CreateTree(n, n->right, x, ch); - } - - else - { - node *t=new node; - t->val=x; - t->left=NULL; - t->right=NULL; - if (pos=='l') - { - curr->left=t; - } - else if(pos=='r') - { - curr->right=t; - } - } +void CreateTree(node* curr, node* n, int x, char pos) { + if (n != NULL) { + char ch; + cout << "\nLeft or Right of " << n->val << " : "; + cin >> ch; + if (ch == 'l') + CreateTree(n, n->left, x, ch); + else if (ch == 'r') + CreateTree(n, n->right, x, ch); + } + + else { + node* t = new node; + t->val = x; + t->left = NULL; + t->right = NULL; + if (pos == 'l') { + curr->left = t; + } else if (pos == 'r') { + curr->right = t; + } + } } - -void BFT(node *n) -{ - if(n!=NULL) - { - cout<val<<" "; - enqueue(n->left); - enqueue(n->right); - BFT(dequeue()); - } +void BFT(node* n) { + if (n != NULL) { + cout << n->val << " "; + enqueue(n->left); + enqueue(n->right); + BFT(dequeue()); + } } -void Pre(node *n) -{ - if (n!=NULL) - { - cout<val<<" "; - Pre(n->left); - Pre(n->right); - } +void Pre(node* n) { + if (n != NULL) { + cout << n->val << " "; + Pre(n->left); + Pre(n->right); + } } -void In(node *n) -{ - if (n!=NULL) - { - In(n->left); - cout<val<<" "; - In(n->right); - } +void In(node* n) { + if (n != NULL) { + In(n->left); + cout << n->val << " "; + In(n->right); + } } - -void Post(node *n) -{ - if (n!=NULL) - { - Post(n->left); - Post(n->right); - cout<val<<" "; - } +void Post(node* n) { + if (n != NULL) { + Post(n->left); + Post(n->right); + cout << n->val << " "; + } } - - -int main() -{ - 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; - do - { - cout<<"\n1. Insert : "; - cout<<"\n2. Breadth First"; - cout<<"\n3. Preorder Depth First"; - cout<<"\n4. Inorder Depth First"; - cout<<"\n5. Postorder Depth First"; - - cout<<"\nEnter Your Choice : "; - cin>>ch; - switch(ch) - { - case 1: - int x; - char pos; - cout<<"\nEnter the value to be Inserted : "; - cin>>x; - cout<<"\nLeft or Right of Root : "; - cin>>pos; - if(pos=='l') - CreateTree(root, root->left, x, pos); - else if(pos=='r') - CreateTree(root, root->right, x, pos); - break; - case 2: - BFT(root); - break; - case 3: - Pre(root); - break; - case 4: - In(root); - break; - case 5: - Post(root); - break; - } - } - while(ch!=0); +int main() { + 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; + do { + cout << "\n1. Insert : "; + cout << "\n2. Breadth First"; + cout << "\n3. Preorder Depth First"; + cout << "\n4. Inorder Depth First"; + cout << "\n5. Postorder Depth First"; + + cout << "\nEnter Your Choice : "; + cin >> ch; + switch (ch) { + case 1: + int x; + char pos; + cout << "\nEnter the value to be Inserted : "; + cin >> x; + cout << "\nLeft or Right of Root : "; + cin >> pos; + if (pos == 'l') + CreateTree(root, root->left, x, pos); + else if (pos == 'r') + CreateTree(root, root->right, x, pos); + break; + case 2: + BFT(root); + break; + case 3: + Pre(root); + break; + case 4: + In(root); + break; + case 5: + Post(root); + break; + } + } while (ch != 0); } diff --git a/Data Structure/TrieTree.cpp b/Data Structure/TrieTree.cpp index 866087d8734..86629526666 100644 --- a/Data Structure/TrieTree.cpp +++ b/Data Structure/TrieTree.cpp @@ -1,97 +1,83 @@ -#include -#include -#include +#include +#include +#include using namespace std; // structure definition -typedef struct trie -{ - struct trie *arr[26]; - bool isEndofWord; +typedef struct trie { + struct trie* arr[26]; + bool isEndofWord; } trie; -// create a new node for trie -trie *createNode() -{ - trie *nn = new trie(); - for (int i = 0; i < 26; i++) - nn->arr[i] = NULL; - nn->isEndofWord = false; - return nn; +// create a new node for trie +trie* createNode() { + trie* nn = new trie(); + for (int i = 0; i < 26; i++) + nn->arr[i] = NULL; + nn->isEndofWord = false; + return nn; } -// insert string into the trie -void insert(trie *root, char* str) -{ - for (int i = 0; i < strlen(str); i++) - { - int j = str[i] - 'a'; - if (root->arr[j]) - { - root = root->arr[j]; - } - else - { - root->arr[j] = createNode(); - root = root->arr[j]; - } +// insert string into the trie +void insert(trie* root, char* str) { + for (int i = 0; i < strlen(str); i++) { + int j = str[i] - 'a'; + if (root->arr[j]) { + root = root->arr[j]; + } else { + root->arr[j] = createNode(); + root = root->arr[j]; } - root->isEndofWord = true; + } + root->isEndofWord = true; } // search a string exists inside the trie -bool search(trie *root, char* str, int index) -{ - if (index == strlen(str)) - { - if (!root->isEndofWord) - return false; - return true; - } - int j = str[index] - 'a'; - if (!root->arr[j]) - return false; - return search(root->arr[j], str, index + 1); +bool search(trie* root, char* str, int index) { + if (index == strlen(str)) { + if (!root->isEndofWord) + return false; + return true; + } + int j = str[index] - 'a'; + if (!root->arr[j]) + return false; + return search(root->arr[j], str, index + 1); } -/* 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 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) -{ - if (index == strlen(str)) - { - if (!root->isEndofWord) - return false; - root->isEndofWord = false; - for (int i = 0; i < 26; i++) - return false; - return true; - } - int j = str[index] - 'a'; - if (!root->arr[j]) - return false; - bool var = deleteString (root, str, index + 1); - if (var) - { - root->arr[j] = NULL; - if (root->isEndofWord) - return false; - else - { - int i; - for (i = 0; i < 26; i++) - if (root->arr[i]) - return false; - return true; - } +bool deleteString(trie* root, char* str, int index) { + if (index == strlen(str)) { + if (!root->isEndofWord) + return false; + root->isEndofWord = false; + for (int i = 0; i < 26; i++) + return false; + return true; + } + int j = str[index] - 'a'; + if (!root->arr[j]) + return false; + bool var = deleteString(root, str, index + 1); + if (var) { + root->arr[j] = NULL; + if (root->isEndofWord) + return false; + else { + int i; + for (i = 0; i < 26; i++) + if (root->arr[i]) + return false; + return true; } + } } -int main() -{ - trie *root = createNode(); - insert(root, "hello"); - insert(root, "world"); - int a = search(root, "hello", 0); - int b = search(root, "word", 0); - printf("%d %d ", a, b); - return 0; +int main() { + trie* root = createNode(); + insert(root, "hello"); + insert(root, "world"); + int a = search(root, "hello", 0); + int b = search(root, "word", 0); + printf("%d %d ", a, b); + return 0; } \ No newline at end of file diff --git a/Data Structure/linkedList_implentation_usingArray.cpp b/Data Structure/linkedList_implentation_usingArray.cpp index ca08653de81..149c7f13ba1 100644 --- a/Data Structure/linkedList_implentation_usingArray.cpp +++ b/Data Structure/linkedList_implentation_usingArray.cpp @@ -1,109 +1,104 @@ -/* The difference between the pointer implementation of linked list and array implementation of linked list: +/* The difference between the pointer implementation of linked list and array + implementation of linked list: 1. The NULL is represented by -1; - 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. + 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{ - int data; - int next; +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; -void initialise_list() -{ - for(int i=0;i<=98;i++) - { - AvailArray[i].next=i+1; - } - AvailArray[99].next=-1; //indicating the end of the linked list. - +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++) { + AvailArray[i].next = i + 1; + } + 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; - return NodeIndexToBeReturned; + 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) - { - temp=AvailArray[temp].next; - - } - //temp is now pointing to the end node. - AvailArray[newNode].data=data; - AvailArray[newNode].next=-1; - AvailArray[temp].next=newNode; +void insertAtTheEnd(int data) { + int newNode = getnode(); + int temp = head; + while (AvailArray[temp].next != -1) { + temp = AvailArray[temp].next; + } + // temp is now pointing to the end node. + AvailArray[newNode].data = data; + AvailArray[newNode].next = -1; + AvailArray[temp].next = newNode; } - -void display() -{ - int temp=head; - while(temp!=-1) - { - cout<"; - temp=AvailArray[temp].next; - } - cout<<"-1"<"; + temp = AvailArray[temp].next; + } + cout << "-1" << endl; + ; } -int main() -{ initialise_list(); - int x,y,z; - for(;;) - { - cout<<"1. Insert At The Beginning"<>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"<> z; + switch (z) { + case 1: + cout << "Enter the number you want to enter" << endl; + cin >> x; + insertAtTheBeginning(x); + break; + case 2: + cout << "Enter the number you want to enter" << endl; + cin >> y; + insertAtTheEnd(y); + break; + case 3: + cout << "The linked list contains the following element in order" + << endl; + display(); + break; + case 4: + exit(0); + default: + cout << "The entered choice is not correct" << endl; } + } } diff --git a/Decimal To Binary.cpp b/Decimal To Binary.cpp index b8eaba1f154..c493178fb2a 100644 --- a/Decimal To Binary.cpp +++ b/Decimal To Binary.cpp @@ -1,24 +1,23 @@ -// This function convert decimal to binary number +// This function convert decimal to binary number // #include using namespace std; -int main() -{ - int number; - cout << "Enter a number:"; - cin >> number; - int remainder, binary = 0, var = 1; +int main() { + int number; + cout << "Enter a number:"; + cin >> number; + int remainder, binary = 0, var = 1; - do { - remainder = number % 2; - number = number / 2; - binary = binary + (remainder*var); - var = var * 10; + do { + remainder = number % 2; + number = number / 2; + binary = binary + (remainder * var); + var = var * 10; - } while (number>0); - cout << "the binary is :"; - cout << binary; - cout << endl; - return 0; + } while (number > 0); + cout << "the binary is :"; + cout << binary; + cout << endl; + return 0; } diff --git a/Decimal To Hexadecimal .cpp b/Decimal To Hexadecimal .cpp index 39333ca00f5..bfdb4cb0a39 100644 --- a/Decimal To Hexadecimal .cpp +++ b/Decimal To Hexadecimal .cpp @@ -2,25 +2,25 @@ using namespace std; -int main(void){ - int valueToConvert = 0; //Holds user input - int hexArray[8]; //Contains hex values backwards - int i = 0; //counter - char HexValues[] = "0123456789ABCDEF"; +int main(void) { + int valueToConvert = 0; // Holds user input + 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 + cout << "Enter a Decimal Value" << endl; // Displays request to stdout + cin >> valueToConvert; // Stores value into valueToConvert via user input - while (valueToConvert > 15){ //Dec to Hex Algorithm - hexArray[i++] = valueToConvert % 16; //Gets remainder - valueToConvert /= 16; - } - hexArray[i] = valueToConvert; //Gets last value - - cout << "Hex Value: "; - while (i >= 0) - cout< 15) { // Dec to Hex Algorithm + hexArray[i++] = valueToConvert % 16; // Gets remainder + valueToConvert /= 16; + } + hexArray[i] = valueToConvert; // Gets last value + + cout << "Hex Value: "; + while (i >= 0) + cout << HexValues[hexArray[i--]]; + + cout << endl; + return 0; } diff --git a/Decimal to Roman Numeral.cpp b/Decimal to Roman Numeral.cpp index 446aa0433d1..e502d00e178 100644 --- a/Decimal to Roman Numeral.cpp +++ b/Decimal to Roman Numeral.cpp @@ -1,68 +1,90 @@ -//This Programme Converts a given decimal number in the range [0,4000) -//to both Lower case and Upper case Roman Numeral +// This Programme Converts a given decimal number in the range [0,4000) +// to both Lower case and Upper case Roman Numeral #include #include -#include #include +#include using namespace std; -//This functions fills a string with character c, n times and returns it -string fill( char c, int n ) -{ - string s; - while( n-- ) s += c; - return s; +// This functions fills a string with character c, n times and returns it +string fill(char c, int n) { + string s; + while (n--) + s += c; + return s; } -//to convert to lowercase Roman Numeral +// to convert to lowercase Roman Numeral -string tolowerRoman( int n ) -{ - if( n < 4 ) return fill( 'i', n ); - if( n < 6 ) return fill( 'i', 5 - n ) + "v"; - if( n < 9 ) return string( "v" ) + fill( 'i', n - 5 ); - if( n < 11 ) return fill( 'i', 10 - n ) + "x"; - if( n < 40 ) return fill( 'x', n / 10 ) + tolowerRoman( n % 10 ); - if( n < 60 ) return fill( 'x', 5 - n / 10 ) + 'l' + tolowerRoman( n % 10 ); - if( n < 90 ) return string( "l" ) + fill( 'x', n / 10 - 5 ) + tolowerRoman( n % 10 ); - if( n < 110 ) return fill( 'x', 10 - n / 10 ) + "c" + tolowerRoman( n % 10 ); - if( n < 400 ) return fill( 'c', n / 100 ) + tolowerRoman( n % 100 ); - if( n < 600 ) return fill( 'c', 5 - n / 100 ) + 'd' + tolowerRoman( n % 100 ); - if( n < 900 ) return string( "d" ) + fill( 'c', n / 100 - 5 ) + tolowerRoman( n % 100 ); - if( n < 1100 ) return fill( 'c', 10 - n / 100 ) + "m" + tolowerRoman( n % 100 ); - if( n < 4000 ) return fill( 'm', n / 1000 ) + tolowerRoman( n % 1000 ); - return "?"; +string tolowerRoman(int n) { + if (n < 4) + return fill('i', n); + if (n < 6) + return fill('i', 5 - n) + "v"; + if (n < 9) + return string("v") + fill('i', n - 5); + if (n < 11) + return fill('i', 10 - n) + "x"; + if (n < 40) + return fill('x', n / 10) + tolowerRoman(n % 10); + if (n < 60) + return fill('x', 5 - n / 10) + 'l' + tolowerRoman(n % 10); + if (n < 90) + return string("l") + fill('x', n / 10 - 5) + tolowerRoman(n % 10); + if (n < 110) + return fill('x', 10 - n / 10) + "c" + tolowerRoman(n % 10); + if (n < 400) + return fill('c', n / 100) + tolowerRoman(n % 100); + if (n < 600) + return fill('c', 5 - n / 100) + 'd' + tolowerRoman(n % 100); + if (n < 900) + return string("d") + fill('c', n / 100 - 5) + tolowerRoman(n % 100); + if (n < 1100) + return fill('c', 10 - n / 100) + "m" + tolowerRoman(n % 100); + if (n < 4000) + return fill('m', n / 1000) + tolowerRoman(n % 1000); + return "?"; } -//to convert to uppercase Roman Numeral +// to convert to uppercase Roman Numeral -string toupperRoman( int n ) -{ - if( n < 4 ) return fill( 'I', n ); - if( n < 6 ) return fill( 'I', 5 - n ) + "V"; - if( n < 9 ) return string( "V" ) + fill( 'I', n - 5 ); - if( n < 11 ) return fill( 'I', 10 - n ) + "X"; - if( n < 40 ) return fill( 'X', n / 10 ) + toupperRoman( n % 10 ); - if( n < 60 ) return fill( 'X', 5 - n / 10 ) + 'L' + toupperRoman( n % 10 ); - if( n < 90 ) return string( "L" ) + fill( 'X', n / 10 - 5 ) + toupperRoman( n % 10 ); - if( n < 110 ) return fill( 'X', 10 - n / 10 ) + "C" + toupperRoman( n % 10 ); - if( n < 400 ) return fill( 'C', n / 100 ) + toupperRoman( n % 100 ); - if( n < 600 ) return fill( 'C', 5 - n / 100 ) + 'D' + toupperRoman( n % 100 ); - if( n < 900 ) return string( "D" ) + fill( 'C', n / 100 - 5 ) + toupperRoman( n % 100 ); - if( n < 1100 ) return fill( 'C', 10 - n / 100 ) + "M" + toupperRoman( n % 100 ); - if( n < 4000 ) return fill( 'M', n / 1000 ) + toupperRoman( n % 1000 ); - return "?"; +string toupperRoman(int n) { + if (n < 4) + return fill('I', n); + if (n < 6) + return fill('I', 5 - n) + "V"; + if (n < 9) + return string("V") + fill('I', n - 5); + if (n < 11) + return fill('I', 10 - n) + "X"; + if (n < 40) + return fill('X', n / 10) + toupperRoman(n % 10); + if (n < 60) + return fill('X', 5 - n / 10) + 'L' + toupperRoman(n % 10); + if (n < 90) + return string("L") + fill('X', n / 10 - 5) + toupperRoman(n % 10); + if (n < 110) + return fill('X', 10 - n / 10) + "C" + toupperRoman(n % 10); + if (n < 400) + return fill('C', n / 100) + toupperRoman(n % 100); + if (n < 600) + return fill('C', 5 - n / 100) + 'D' + toupperRoman(n % 100); + if (n < 900) + return string("D") + fill('C', n / 100 - 5) + toupperRoman(n % 100); + if (n < 1100) + return fill('C', 10 - n / 100) + "M" + toupperRoman(n % 100); + if (n < 4000) + return fill('M', n / 1000) + toupperRoman(n % 1000); + return "?"; } -//main function - -int main() -{ +// main function -int n; -cin >> n; -cout << n << " in Upper Roman Numerals is " << toupperRoman(n) << "\n"; -cout << n << " in Lower Roman Numerals is " << tolowerRoman(n) << "\n"; -return 0; +int main() { + int n; + 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/Doubly Linked List.cpp b/Doubly Linked List.cpp index db550d4225b..a1535d948e5 100644 --- a/Doubly Linked List.cpp +++ b/Doubly Linked List.cpp @@ -1,125 +1,114 @@ -#include +#include using namespace std; -struct node -{ - int val; - node *prev; - node *next; +struct node { + int val; + node* prev; + node* next; }; -node *start; +node* start; -void insert(int x) -{ - node *t=start; - if (start!=NULL) - { - while(t->next!=NULL) - { - t=t->next; - } - 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; - } +void insert(int x) { + node* t = start; + if (start != NULL) { + while (t->next != NULL) { + t = t->next; + } + 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; + } } -void remove(int x) -{ - node *t=start; - while(t->val!=x) - { - t=t->next; - } - t->prev->next=t->next; - t->next->prev=t->prev; - delete t; +void remove(int x) { + node* t = start; + while (t->val != x) { + t = t->next; + } + 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) - { - if(t->val==x) - { - cout<<"\nFound"; - found=1; - break; - } - t=t->next; - } - if(found==0) - { - cout<<"\nNot Found"; - } +void search(int x) { + node* t = start; + int found = 0; + while (t != NULL) { + if (t->val == x) { + cout << "\nFound"; + found = 1; + break; + } + t = t->next; + } + if (found == 0) { + cout << "\nNot Found"; + } } -void show() -{ - node *t=start; - while(t!=NULL) - { - cout<val<<"\t"; - t=t->next; - } - +void show() { + node* t = start; + while (t != NULL) { + cout << t->val << "\t"; + t = t->next; + } } -void reverseShow() -{ - node *t=start; - while(t->next!=NULL) - { - t=t->next; - } - while(t!=NULL) - { - cout<val<<"\t"; - t=t->prev; - } +void reverseShow() { + node* t = start; + while (t->next != NULL) { + t = t->next; + } + while (t != NULL) { + cout << t->val << "\t"; + t = t->prev; + } } -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; - 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; - } - } - while(choice!=0); +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; + 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; + } + } while (choice != 0); - return 0; + return 0; } diff --git a/Dynamic Programming/0-1 Knapsack.cpp b/Dynamic Programming/0-1 Knapsack.cpp index 4bed36fb219..74cebdbc24a 100644 --- a/Dynamic Programming/0-1 Knapsack.cpp +++ b/Dynamic Programming/0-1 Knapsack.cpp @@ -1,9 +1,9 @@ -//0-1 Knapsack problem - Dynamic programming +// 0-1 Knapsack problem - Dynamic programming //#include -#include +#include using namespace std; -//void Print(int res[20][20], int i, int j, int capacity) +// void Print(int res[20][20], int i, int j, int capacity) //{ // if(i==0 || j==0) // { @@ -15,7 +15,7 @@ using namespace std; // { // cout<res[i][j-1]) @@ -28,43 +28,39 @@ using namespace std; // } //} -int Knapsack(int capacity,int n,int weight[],int value[]){ - int res[20][20]; - for (int i = 0; i < n+1; ++i) - { - for (int j = 0; j < capacity+1; ++j) - { - 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 - res[i][j] = res[i-1][j]; - } - } -// Print(res, n, capacity, capacity); -// cout<<"\n"; - return res[n][capacity]; +int Knapsack(int capacity, int n, int weight[], int value[]) { + int res[20][20]; + for (int i = 0; i < n + 1; ++i) { + for (int j = 0; j < capacity + 1; ++j) { + 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 + res[i][j] = res[i - 1][j]; + } + } + // Print(res, n, capacity, capacity); + // cout<<"\n"; + return res[n][capacity]; } -int main() -{ - int n; - cout<<"Enter number of items: "; - cin>>n; - int weight[n], value[n]; - cout<<"Enter weights: "; - for (int i = 0; i < n; ++i) - { - cin>>weight[i]; - } - cout<<"Enter values: "; - for (int i = 0; i < n; ++i) - { - cin>>value[i]; - } - int capacity; - cout<<"Enter capacity: "; - cin>>capacity; - cout<> n; + int weight[n], value[n]; + cout << "Enter weights: "; + for (int i = 0; i < n; ++i) { + cin >> weight[i]; + } + cout << "Enter values: "; + for (int i = 0; i < n; ++i) { + cin >> value[i]; + } + int capacity; + cout << "Enter capacity: "; + cin >> capacity; + cout << Knapsack(capacity, n, weight, value); + return 0; } diff --git a/Dynamic Programming/Armstrong Number.cpp b/Dynamic Programming/Armstrong Number.cpp index 18d625e1edb..0fdd7046b83 100644 --- a/Dynamic Programming/Armstrong Number.cpp +++ b/Dynamic Programming/Armstrong Number.cpp @@ -1,20 +1,18 @@ -//program to check whether a number is an armstrong number or not -#include -#include -int main() -{ - 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; +// program to check whether a number is an armstrong number or not +#include +#include +int main() { + 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; } - if(s==n) - cout< -#include +#include +#include using namespace std; -//Wrapper class for storing an edge -class Edge{ - public: int src,dst,weight; +// Wrapper class for storing an edge +class Edge { + public: + int src, dst, weight; }; -//Wrapper class for storing a graph -class Graph{ - public: - int vertexNum,edgeNum; - Edge* edges; - - //Constructs a graph with V vertices and E edges - Graph(int V,int E){ - this->vertexNum = V; - this->edgeNum = E; - this->edges =(Edge*) malloc(E * sizeof(Edge)); - } - - //Adds the given edge to the graph - void addEdge(int src, int dst, int weight){ - static int edgeInd = 0; - if(edgeInd < this->edgeNum){ - Edge newEdge; - newEdge.src = src; - newEdge.dst = dst; - newEdge.weight = weight; - this->edges[edgeInd++] = newEdge; - } - - } - +// Wrapper class for storing a graph +class Graph { + public: + int vertexNum, edgeNum; + Edge* edges; + + // Constructs a graph with V vertices and E edges + Graph(int V, int E) { + this->vertexNum = V; + this->edgeNum = E; + this->edges = (Edge*)malloc(E * sizeof(Edge)); + } + + // Adds the given edge to the graph + void addEdge(int src, int dst, int weight) { + static int edgeInd = 0; + 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; - G.addEdge(src, dst, weight); - } - cout<<"\nEnter source: "; - cin>>gsrc; - BellmanFord(G,gsrc); - - return 0; +// Driver Function +int main() { + int V, E, gsrc; + int src, dst, weight; + cout << "Enter number of vertices: "; + cin >> V; + cout << "Enter number of edges: "; + cin >> E; + Graph G(V, E); + for (int i = 0; i < E; i++) { + cout << "\nEdge " << i + 1 << "\nEnter source: "; + cin >> src; + cout << "Enter destination: "; + cin >> dst; + cout << "Enter weight: "; + cin >> weight; + G.addEdge(src, dst, weight); + } + 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 a086ae6c181..f906d5f3f99 100644 --- a/Dynamic Programming/Catalan-Numbers.cpp +++ b/Dynamic Programming/Catalan-Numbers.cpp @@ -9,56 +9,52 @@ #include using namespace std; -int *cat; // global array to hold catalan numbers - -unsigned long int catalan_dp(int n) -{ - /** Using the tabulation technique in dynamic programming, - this function computes the first `n+1` Catalan numbers - - Parameter - --------- - n: The number of catalan numbers to be computed. - - Returns - ------- - cat[n]: An array containing the first `n+1` Catalan numbers - */ - - // By definition, the first two Catalan numbers are 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 - } - - // Return the result - return cat[n]; +int* cat; // global array to hold catalan numbers + +unsigned long int catalan_dp(int n) { + /** Using the tabulation technique in dynamic programming, + this function computes the first `n+1` Catalan numbers + + Parameter + --------- + n: The number of catalan numbers to be computed. + + Returns + ------- + cat[n]: An array containing the first `n+1` Catalan numbers +*/ + + // By definition, the first two Catalan numbers are 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 + } + + // Return the result + return cat[n]; } -int main(int argc, char *argv[]) -{ - int n; - cout << "Enter n: "; - cin >> n; - - cat = new int[n+1]; - - 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` - // repeatedly will not recompute the the values already computed - // as in case of pre-computed values, the array will simply return them, - // instead of recomputing them. - } - - return 0; +int main(int argc, char* argv[]) { + int n; + cout << "Enter n: "; + cin >> n; + + cat = new int[n + 1]; + + 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` + // repeatedly will not recompute the the values already computed + // as in case of pre-computed values, the array will simply return them, + // instead of recomputing them. + } + + return 0; } /** Sample Test Case: diff --git a/Dynamic Programming/Cut Rod.cpp b/Dynamic Programming/Cut Rod.cpp index 90e12a53242..d206a30ca64 100644 --- a/Dynamic Programming/Cut Rod.cpp +++ b/Dynamic Programming/Cut Rod.cpp @@ -1,29 +1,25 @@ -/*Given a rod of length n inches and an array of prices that -contains prices of all pieces of size smaller than n. Determine -the maximum value obtainable by cutting up the rod and selling +/*Given a rod of length n inches and an array of prices that +contains prices of all pieces of size smaller than n. Determine +the maximum value obtainable by cutting up the rod and selling the pieces.*/ #include using namespace std; -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 @@ -25,63 +25,65 @@ int min(int x, int y, int z){ * 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); + 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) { + // Create Table for SubProblems + int dp[m + 1][n + 1]; - //Create Table for SubProblems - 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++) { - //If str1 empty. Then add all of str2 - if(i==0) - dp[i][j] = j; + // Fill d[][] in bottom up manner + 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) + dp[i][j] = j; - //If str2 empty. Then add all of str1 - else if(j==0) - dp[i][j] = i; + // 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 - ); - } + else + 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]; + return dp[m][n]; } 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; + string str1 = "sunday"; + string str2 = "saturday"; + + cout << editDist(str1, str2, str1.length(), str2.length()) << endl; + cout << editDistDP(str1, str2, str1.length(), str2.length()) << endl; - return 0; + return 0; } diff --git a/Dynamic Programming/Egg-Dropping-Puzzle.cpp b/Dynamic Programming/Egg-Dropping-Puzzle.cpp index 5b277be2693..b47677416e1 100644 --- a/Dynamic Programming/Egg-Dropping-Puzzle.cpp +++ b/Dynamic Programming/Egg-Dropping-Puzzle.cpp @@ -1,45 +1,45 @@ -/* Function to get minimun number of trials needed - * in worst case with n eggs and k floors +/* Function to get minimun number of trials needed + * in worst case with n eggs and k floors */ -#include #include +#include using namespace std; int eggDrop(int n, int k) { - int eggFloor[n+1][k+1]; - int result; + int eggFloor[n + 1][k + 1]; + int result; - 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++) { - eggFloor[1][j] = j; - } + 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++) { + eggFloor[1][j] = 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++) { - // 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]) - eggFloor[i][j] = result; - } - } + 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++) { + // 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]) + eggFloor[i][j] = result; + } } - - return eggFloor[n][k]; + } + + return eggFloor[n][k]; } int main() { - int n, k; - cout << "Enter number of eggs and floors: "; - cin>>n>>k; - cout << "Minimum number of trials in worst case: " << eggDrop(n, k) << endl; - return 0; + int n, k; + cout << "Enter number of eggs and floors: "; + 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 cbd0912e8fe..6e42848c7f0 100644 --- a/Dynamic Programming/Fibonacci_Bottom_Up.cpp +++ b/Dynamic Programming/Fibonacci_Bottom_Up.cpp @@ -1,19 +1,19 @@ #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]; - } - return res[n]; +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 65788189290..35a1071e920 100644 --- a/Dynamic Programming/Fibonacci_Top_Down.cpp +++ b/Dynamic Programming/Fibonacci_Top_Down.cpp @@ -1,24 +1,22 @@ #include using namespace std; int arr[1000000]; -int fib(int n){ - if(arr[n]==-1){ - if(n<=1) - arr[n] = n; - else - arr[n] = fib(n-1) + fib(n-2); - } - return arr[n]; +int fib(int n) { + if (arr[n] == -1) { + if (n <= 1) + arr[n] = n; + else + 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) - { - arr[i] = -1; - } - cout<<"Fibonacci number is "<> n; + for (int i = 0; i < n + 1; ++i) { + arr[i] = -1; + } + cout << "Fibonacci number is " << fib(n) << endl; + return 0; } \ No newline at end of file diff --git a/Dynamic Programming/Floyd-Warshall.cpp b/Dynamic Programming/Floyd-Warshall.cpp index 9f037a64df4..88da448d5b7 100644 --- a/Dynamic Programming/Floyd-Warshall.cpp +++ b/Dynamic Programming/Floyd-Warshall.cpp @@ -1,106 +1,103 @@ -#include -#include -#include +#include +#include +#include using namespace std; -//Wrapper class for storing a graph -class Graph{ - public: - int vertexNum; - int** edges; +// Wrapper class for storing a graph +class Graph { + public: + int vertexNum; + int** edges; - //Constructs a graph with V vertices and E edges - 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[i][j] = INT_MAX; - this->edges[i][i] = 0; - } - } - - //Adds the given edge to the graph - void addEdge(int src, int dst, int weight){ - this->edges[src][dst] = weight; - } - + // Constructs a graph with V vertices and E edges + Graph(int V) { + this->vertexNum = V; + this->edges = (int**)malloc(V * sizeof(int*)); + for (int i = 0; i < V; i++) { + this->edges[i] = (int*)malloc(V * sizeof(int)); + for (int j = 0; j < V; j++) + this->edges[i][j] = INT_MAX; + this->edges[i][i] = 0; + } + } + // Adds the given edge to the graph + void addEdge(int src, int dst, int weight) { + this->edges[src][dst] = weight; + } }; +// Utility function to print distances +void print(int dist[], int V) { + cout << "\nThe Distance matrix for Floyd - Warshall" << endl; + for (int i = 0; i < V; i++) { + for (int j = 0; j < V; j++) { + if (dist[i * V + j] != INT_MAX) + cout << dist[i * V + j] << "\t"; + else + cout << "INF" + << "\t"; + } + cout << endl; + } +} -//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; - Graph G(V); - for(int i=0; i>src; - cout<<"Enter destination: "; - cin>>dst; - cout<<"Enter weight: "; - cin>>weight; - G.addEdge(src, dst, weight); - } - FloydWarshall(G); +// Driver Function +int main() { + int V, E; + int src, dst, weight; + cout << "Enter number of vertices: "; + cin >> V; + cout << "Enter number of edges: "; + cin >> E; + Graph G(V); + for (int i = 0; i < E; i++) { + cout << "\nEdge " << i + 1 << "\nEnter source: "; + cin >> src; + cout << "Enter destination: "; + cin >> dst; + cout << "Enter weight: "; + cin >> weight; + G.addEdge(src, dst, weight); + } + FloydWarshall(G); - return 0; + return 0; } diff --git a/Dynamic Programming/Longest Common Subsequence.cpp b/Dynamic Programming/Longest Common Subsequence.cpp index aba1eeb5478..9c911304b70 100644 --- a/Dynamic Programming/Longest Common Subsequence.cpp +++ b/Dynamic Programming/Longest Common Subsequence.cpp @@ -1,87 +1,63 @@ -//Longest common subsequence - Dynamic Programming +// Longest common subsequence - Dynamic Programming #include using namespace std; -void Print(int trace[20][20], int m, int n, string a) -{ - if (m==0 || n==0) - { - return; - } - if (trace[m][n]==1) - { - Print(trace, m-1, n-1, a); - cout<res[i][j-1]) - { - 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. - } - } + } + + for (int i = 0; i < m + 1; ++i) { + for (int j = 0; j < n + 1; ++j) { + if (i == 0 || j == 0) { + res[i][j] = 0; + trace[i][j] = 0; + } + + else if (a[i - 1] == b[j - 1]) { + res[i][j] = 1 + res[i - 1][j - 1]; + trace[i][j] = + 1; // 1 means trace the matrix in upper left diagonal direction. + } else { + 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. + } else { + res[i][j] = res[i][j - 1]; + trace[i][j] = 3; // means trace the matrix in left direction. } + } } - Print(trace, m, n, a); - return res[m][n]; + } + Print(trace, m, n, a); + 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 e2d6111c8bf..1946184b994 100644 --- a/Dynamic Programming/Longest Increasing Subsequence.cpp +++ b/Dynamic Programming/Longest Increasing Subsequence.cpp @@ -1,38 +1,32 @@ -//Program to calculate length of longest increasing subsequence in an array +// Program to calculate length of longest increasing subsequence in an array #include using namespace std; -int LIS(int a[],int n){ - int lis[n]; - for (int i = 0; i < n; ++i) - { - lis[i] = 1; - } - for (int i = 0; i < n; ++i) - { - 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]); + } + return res; } -int main(int argc, char const *argv[]) -{ - int n; - cout<<"Enter size of array: "; - cin>>n; - int a[n]; - cout<<"Enter array elements: "; - for (int i = 0; i < n; ++i) - { - cin>>a[i]; - } - cout<> n; + int a[n]; + cout << "Enter array elements: "; + for (int i = 0; i < n; ++i) { + cin >> a[i]; + } + cout << LIS(a, n) << endl; + return 0; } \ No newline at end of file diff --git a/GCD_of_n_numbers.cpp b/GCD_of_n_numbers.cpp index 3e9e9ce170e..9d1543a730d 100644 --- a/GCD_of_n_numbers.cpp +++ b/GCD_of_n_numbers.cpp @@ -1,23 +1,21 @@ -//This program aims at calculating the GCD of n numbers by division method +// This program aims at calculating the GCD of n numbers by division method #include 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 +#include using namespace std; -class graph{ - int v; - list *adj; - public: - graph(int v); - void addedge(int src,int dest); - void printgraph(); - void bfs(int s); +class graph { + int v; + list* adj; + + public: + graph(int v); + void addedge(int src, int dest); + void printgraph(); + void bfs(int s); }; -graph::graph(int v){ - this->v = v; - this->adj = new list[v]; +graph::graph(int v) { + this->v = v; + this->adj = new list[v]; } -void graph::addedge(int src,int dest){ - src--;dest--; - adj[src].push_back(dest); - //adj[dest].push_back(src); +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 "<::iterator it; - for(it=adj[i].begin();it!=adj[i].end();++it){ - cout<<*it+1<<" "; - } - cout<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 << " "; + } + cout << endl; + } } -void graph::bfs(int s){ - bool *visited = new bool[this->v+1]; - memset(visited,false,sizeof(visited)); - visited[s]=true; - list q; - q.push_back(s); - list::iterator it; - while(!q.empty()){ - int u = q.front(); - cout<v + 1]; + memset(visited, false, sizeof(visited)); + visited[s] = true; + list q; + q.push_back(s); + list::iterator it; + while (!q.empty()) { + int u = q.front(); + cout << u << " "; + q.pop_front(); + for (it = adj[u].begin(); it != adj[u].end(); ++it) { + if (visited[*it] == false) { + visited[*it] = true; + q.push_back(*it); + } + } + } } -int main(){ - graph g(4); - g.addedge(1,2); - g.addedge(2,3); - g.addedge(3,4); - g.addedge(1,4); - g.addedge(1,3); - //g.printgraph(); - g.bfs(2); - return 0; +int main() { + graph g(4); + g.addedge(1, 2); + g.addedge(2, 3); + g.addedge(3, 4); + g.addedge(1, 4); + g.addedge(1, 3); + // g.printgraph(); + g.bfs(2); + return 0; } \ No newline at end of file diff --git a/Graph/DFS.cpp b/Graph/DFS.cpp index 66a5f2b3c90..ac531b0f73f 100644 --- a/Graph/DFS.cpp +++ b/Graph/DFS.cpp @@ -1,27 +1,26 @@ #include using namespace std; int v = 4; -void DFSUtil_(int graph[4][4],bool visited[],int s){ - visited[s] = true; - cout< -#include #include #include +#include +#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; - // source distance to zero. - pq.push(make_pair(0,s)); - dis[s] = 0; - int u; - 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]) { - dis[it->second] = dis[u] + it->first; - pq.push(make_pair(dis[it->second],it->second)); - } - } +vector> graph[5 * 100001]; +int dis[5 * 100001]; +int dij(vector>* v, int s, int* dis) { + priority_queue< + pair, + vector>, + greater>> + pq; + // source distance to zero. + pq.push(make_pair(0, s)); + dis[s] = 0; + int u; + 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]) { + dis[it->second] = dis[u] + it->first; + pq.push(make_pair(dis[it->second], it->second)); + } } + } } 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++) { - // 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 - } - // start node. - scanf("%d",&s); - // intialise all distances to infinity. - 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 "; - else - cout< number of nodes , m --> number of edges + 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 + } + // start node. + scanf("%d", &s); + // intialise all distances to infinity. + 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 "; + else + cout << dis[i] << " "; + return 0; } diff --git a/Graph/Kruskal.cpp b/Graph/Kruskal.cpp index df83afc08e2..61ec10716aa 100644 --- a/Graph/Kruskal.cpp +++ b/Graph/Kruskal.cpp @@ -1,92 +1,116 @@ #include "bits/stdc++.h" //#include -//using namespace boost::multiprecision; -const int mx = 1e6+5; +// using namespace boost::multiprecision; +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; +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; } -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; -void initial() -{ - int i; - rep(i,node+edge) - parent[i] = i; +ll parent[mx], arr[mx], node, edge; +vector>> v; +void initial() { + int i; + rep(i, node + edge) parent[i] = i; } -int root(int i) -{ - while(parent[i] != i) - { - parent[i] = parent[parent[i]]; - i = parent[i]; - } - return i; +int root(int i) { + while (parent[i] != i) { + parent[i] = parent[parent[i]]; + i = parent[i]; + } + return i; } -void join(int x,int y) -{ - int root_x = root(x); //Disjoint set union by rank - int root_y = root(y); - parent[root_x] = root_y; +void join(int x, int y) { + 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) - { - x = v[i].second.first; - y = v[i].second.second; - if(root(x) != root(y)) - { - mincost += v[i].first; - join(x,y); - } - } - return mincost; +ll kruskal() { + ll mincost = 0, i, x, y; + rep(i, edge) { + x = v[i].second.first; + y = v[i].second.second; + if (root(x) != root(y)) { + mincost += v[i].first; + join(x, y); + } + } + return mincost; } -int main(){ - fast; - 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) - { - cin>>from>>to>>cost; - v.pb(mp(cost,mp(from,to))); - totalcost += cost; - } - sort(v.begin(),v.end()); - // rep(i,v.size()) - // cout<> 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))); + totalcost += cost; + } + sort(v.begin(), v.end()); + // rep(i,v.size()) + // cout< #include +#include using namespace std; -//Wrapper class for storing a graph -class Graph -{ -public: - int vertexNum; - int **edges; - - //Constructs a graph with V vertices and E edges - Graph(const int V) - { - - // initializes the array edges. - this->edges = new int*[V]; - for (int i = 0; i < V; i++) - { - edges[i] = new int[V]; - } - - // fills the array with zeros. - for (int i = 0; i < V; i++) - { - for (int j = 0; j < V; j++) - { - edges[i][j] = 0; - } - } - - this->vertexNum = V; - +// Wrapper class for storing a graph +class Graph { + public: + int vertexNum; + int** edges; + + // Constructs a graph with V vertices and E edges + Graph(const int V) { + // initializes the array edges. + this->edges = new int*[V]; + for (int i = 0; i < V; i++) { + edges[i] = new int[V]; } - //Adds the given edge to the graph - void addEdge(int src, int dst, int weight) - { - this->edges[src][dst] = weight; + // fills the array with zeros. + for (int i = 0; i < V; i++) { + for (int j = 0; j < V; j++) { + edges[i][j] = 0; + } } + this->vertexNum = V; + } + // Adds the given edge to the graph + void addEdge(int src, int dst, int weight) { + 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; - Graph G(V); - for(int i=0; i>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) - { - G.addEdge(src, dst, weight); - } - else - { - cout << "source and/or destination out of bounds" << endl; - i--; - continue; - } +// Driver Function +int main() { + int V, E, gsrc; + int src, dst, weight; + cout << "Enter number of vertices: "; + cin >> V; + cout << "Enter number of edges: "; + cin >> E; + Graph G(V); + 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; + + // makes sure source and destionation are in the proper bounds. + if (src >= 0 && src < V && dst >= 0 && dst < V) { + G.addEdge(src, dst, weight); + } else { + cout << "source and/or destination out of bounds" << endl; + i--; + continue; } - cout<<"\nEnter source:"; - cin>>gsrc; - Dijkstra(G,gsrc); + } + cout << "\nEnter source:"; + cin >> gsrc; + Dijkstra(G, gsrc); - return 0; + return 0; } diff --git a/Greedy Algorithms/Knapsack.cpp b/Greedy Algorithms/Knapsack.cpp index 41ce4cc9b31..b480eacc3a3 100644 --- a/Greedy Algorithms/Knapsack.cpp +++ b/Greedy Algorithms/Knapsack.cpp @@ -1,97 +1,79 @@ -#include +#include using namespace std; -struct Item -{ - int weight; - int profit; +struct Item { + int weight; + int profit; }; - -float profitPerUnit(Item x) -{ - return (float)x.profit/(float)x.weight; -} - -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 : "; - int 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; - } +int main() { + cout << "\nEnter the capacity of the knapsack : "; + float capacity; + cin >> capacity; + cout << "\n Enter the number of Items : "; + int n; + cin >> n; + Item itemArray[n]; + for (int i = 0; i < n; i++) { + cout << "\nEnter the weight and profit of item " << i + 1 << " : "; + cin >> itemArray[i].weight; + cin >> itemArray[i].profit; + } - quickSort(itemArray, 0, n-1); + quickSort(itemArray, 0, n - 1); - // show(itemArray, n); + // show(itemArray, n); - float maxProfit=0; - int i=n; - while(capacity>0 && --i>=0) - { - if(capacity>=itemArray[i].weight) - { - maxProfit+=itemArray[i].profit; - capacity-=itemArray[i].weight; - cout<<"\n\t"< 0 && --i >= 0) { + if (capacity >= itemArray[i].weight) { + maxProfit += itemArray[i].profit; + capacity -= itemArray[i].weight; + cout << "\n\t" << itemArray[i].weight << "\t" << itemArray[i].profit; + } else { + maxProfit += profitPerUnit(itemArray[i]) * capacity; + cout << "\n\t" << capacity << "\t" + << profitPerUnit(itemArray[i]) * capacity; + capacity = 0; + break; + } + } - cout<<"\nMax Profit : "< using namespace std; -int main() -{ - int n,k,s=0,d; +int main() { + int n, k, s = 0, d; cout << "Enter a number:"; cin >> n; - s=0;k=n; - while(k>9) - { - while(k!=0) - { - d=k%10; - s+=d; - k/=10; + s = 0; + k = n; + while (k > 9) { + while (k != 0) { + 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/Hashing/Chaining.cpp b/Hashing/Chaining.cpp index 09350f4de87..5920517947e 100644 --- a/Hashing/Chaining.cpp +++ b/Hashing/Chaining.cpp @@ -1,123 +1,121 @@ -#include -#include +#include +#include using namespace std; struct Node { - int data; - struct Node *next; -} *head[100],*curr; + int data; + struct Node* next; +} * head[100], *curr; void init() { - for(int i=0;i<100;i++) - head[i]=NULL; + for (int i = 0; i < 100; i++) + head[i] = NULL; } -void add(int x,int h) { - struct Node *temp = new Node; - temp->data = x; - temp->next = NULL; - if(!head[h]) { - head[h] = temp; - curr = head[h]; - } - else { - curr=head[h]; - while(curr->next) - curr = curr->next; - curr->next = temp; - } +void add(int x, int h) { + struct Node* temp = new Node; + temp->data = x; + temp->next = NULL; + if (!head[h]) { + head[h] = temp; + curr = head[h]; + } else { + curr = head[h]; + while (curr->next) + curr = curr->next; + curr->next = temp; + } } void display(int mod) { - struct Node *temp; - int i; - for(i=0;inext; - } - cout<data; - cout<next; + } + cout << temp->data; + cout << endl; + } + } } -int hash(int x,int mod) { - return x%mod; +int hash(int x, int mod) { + return x % mod; } -void find(int x,int h) { - struct Node *temp =head[h]; - if(!head[h]) { - cout<<"Element not found"; - return; - } - 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"; - } -} +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"; + else + cout << "Element not found"; + } +} int main(void) { - init(); - 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 << endl; + } + /*add(1,&head1); + add(2,&head1); + add(3,&head2); + add(5,&head1); + display(&head1); + display(&head2);*/ + return 0; } \ No newline at end of file diff --git a/Intersection_of_2_arrays.cpp b/Intersection_of_2_arrays.cpp index e2c064e1ba1..649e6d30f5a 100644 --- a/Intersection_of_2_arrays.cpp +++ b/Intersection_of_2_arrays.cpp @@ -1,28 +1,26 @@ #include -int main() -{ - int i,j,m,n; - cout <<"Enter size of array 1:"; +int main() { + 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((ib[j]) - j++; - else - { - cout << a[i++]<<" "; + cout << "Enter elements of array 1:"; + for (i = 0; i < m; i++) + cin >> a[i]; + for (i = 0; i < n; i++) + cin >> b[i]; + i = 0; + j = 0; + while ((i < m) && (j < n)) { + if (a[i] < b[j]) + i++; + else if (a[i] > b[j]) + j++; + else { + cout << a[i++] << " "; j++; } } diff --git a/Linear Search.cpp b/Linear Search.cpp index fd381756db4..13b65510aab 100644 --- a/Linear Search.cpp +++ b/Linear Search.cpp @@ -1,48 +1,39 @@ -#include +#include using namespace std; -int LinearSearch(int *array, int size, int key) -{ - for (int i = 0; i < size; ++i) - { - if (array[i]==key) - { - return i; - } - } - - return -1; +int LinearSearch(int* array, int size, int key) { + for (int i = 0; i < size; ++i) { + if (array[i] == key) { + return i; + } + } + + return -1; } +int main() { + int size; + cout << "\nEnter the size of the Array : "; + cin >> size; + + int array[size]; + int key; + + // Input array + cout << "\nEnter the Array of " << size << " numbers : "; + for (int i = 0; i < size; i++) { + cin >> array[i]; + } + + cout << "\nEnter the number to be searched : "; + cin >> key; + + int index = LinearSearch(array, size, key); + if (index != -1) { + cout << "\nNumber found at index : " << index; + } else { + cout << "\nNot found"; + } -int main() -{ - int size; - cout<<"\nEnter the size of the Array : "; - cin >> size; - - int array[size]; - int key; - - //Input array - cout<<"\nEnter the Array of " << size << " numbers : "; - for (int i = 0; i < size; i++) - { - cin>>array[i]; - } - - cout<<"\nEnter the number to be searched : "; - cin>>key; - - int index=LinearSearch(array, size, key); - if (index!=-1) - { - cout<<"\nNumber found at index : "< +#include using namespace std; -struct node -{ - int val; - node *next; +struct node { + int val; + node* next; }; -node *start; +node* start; -void insert(int x) -{ - node *t=start; - if (start!=NULL) - { - while(t->next!=NULL) - { - t=t->next; - } - 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; - } +void insert(int x) { + node* t = start; + if (start != NULL) { + while (t->next != NULL) { + t = t->next; + } + 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; + } } -void remove(int x) -{ - node *t=start; - node *p; - while(t->val!=x) - { - p=t; - t=t->next; - } - p->next=t->next; - delete t; +void remove(int x) { + node* t = start; + node* p; + while (t->val != x) { + p = t; + t = t->next; + } + p->next = t->next; + delete t; } -void search(int x) -{ - node *t= start; - int found =0; - while(t!=NULL) - { - if(t->val==x) - { - cout<<"\nFound"; - found=1; - break; - } - t=t->next; - } - if(found==0) - { - cout<<"\nNot Found"; - } +void search(int x) { + node* t = start; + int found = 0; + while (t != NULL) { + if (t->val == x) { + cout << "\nFound"; + found = 1; + break; + } + t = t->next; + } + if (found == 0) { + cout << "\nNot Found"; + } } -void show() -{ - node *t=start; - while(t!=NULL) - { - cout<val<<"\t"; - t=t->next; - } - +void show() { + node* t = start; + while (t != NULL) { + cout << t->val << "\t"; + t = t->next; + } } -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; - 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; - } - } - while(choice!=0); +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; + 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; + } + } while (choice != 0); - return 0; + return 0; } diff --git a/List Array.cpp b/List Array.cpp index 21f5c6ae53c..a2f4c5cb33e 100644 --- a/List Array.cpp +++ b/List Array.cpp @@ -1,185 +1,153 @@ -#include +#include using namespace std; -struct list -{ - int data[50]; - 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)); - } - - int LinarSearch(int *array, int x) - { - for (int i = 0; i < top; i++) - { - if (array[i]==x) - { - return i; - } - } - - return -1; - } - - int Search(int x) - { - int pos=-1; - - if (isSorted) - { - pos=BinarySearch(data, 0, top-1, x); - } - - else - { - pos=LinarSearch(data, x); - } - - if (pos!=-1) - { - cout<<"\nElement found at position : "< pos; i--) - { - data[i]=data[i-1]; - } - top++; - data[pos]=x; - } - } - - void Remove(int x) - { - int pos=Search(x); - cout<<"\n"< 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) { + return i; + } + } + + return -1; + } + + int Search(int x) { + int pos = -1; + + if (isSorted) { + pos = BinarySearch(data, 0, top - 1, x); + } + + else { + pos = LinarSearch(data, x); + } + + if (pos != -1) { + cout << "\nElement found at position : " << pos; + } else { + cout << "\nElement not found"; + } + return pos; + } + + void Sort() { + int i, j, pos; + for (i = 0; i < top; i++) { + int min = data[i]; + for (j = i + 1; j < top; j++) { + if (data[j] < min) { + pos = j; + min = data[pos]; + } + } + + int temp = data[i]; + data[i] = data[pos]; + data[pos] = temp; + } + isSorted = true; + } + + void insert(int x) { + if (!isSorted) { + if (top == 49) { + cout << "\nOverflow"; + } else { + data[top] = x; + top++; + } + } + + else { + int pos = 0; + + for (int i = 0; i < top - 1; i++) { + if (data[i] <= x && x <= data[i + 1]) { + pos = i + 1; + break; + } + } + if (pos == 0) { + pos = top - 1; + } + + for (int i = top; i > pos; i--) { + data[i] = data[i - 1]; + } + top++; + data[pos] = x; + } + } + + void Remove(int x) { + int pos = Search(x); + cout << "\n" << data[pos] << " deleted"; + for (int i = pos; i < top; i++) { + data[i] = data[i + 1]; + } + top--; + } + + void Show() { + for (int i = 0; i < top; i++) { + cout << data[i] << "\t"; + } + } }; -int main() -{ - list L; - int choice; - int x; - do - { - cout<<"\n1.Insert"; - cout<<"\n2.Delete"; - cout<<"\n3.Search"; - cout<<"\n4.Sort"; - cout<<"\n5.Print"; - cout<<"\n\nEnter Your Choice : "; - cin>>choice; - 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; - } - } - while(choice!=0); - return 0; +int main() { + list L; + int choice; + int x; + do { + cout << "\n1.Insert"; + cout << "\n2.Delete"; + cout << "\n3.Search"; + cout << "\n4.Sort"; + cout << "\n5.Print"; + cout << "\n\nEnter Your Choice : "; + cin >> choice; + 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; + } + } while (choice != 0); + return 0; } diff --git a/Math/Prime_Factorization/primefactorization.cpp b/Math/Prime_Factorization/primefactorization.cpp index b903a166a62..9832d4d4601 100644 --- a/Math/Prime_Factorization/primefactorization.cpp +++ b/Math/Prime_Factorization/primefactorization.cpp @@ -1,84 +1,71 @@ +#include #include #include -#include using namespace std; -// Declaring variables for maintaing prime numbers and to check whether a number is prime or not +// Declaring variables for maintaing prime numbers and to check whether a number +// is prime or not bool isprime[1000006]; vector prime_numbers; -vector > factors; +vector> factors; // Calculating prime number upto a given range -void SieveOfEratosthenes(int N) -{ - // initializes the array isprime - memset(isprime, true, sizeof isprime); - - for(int i=2; i<=N ; i++) - { - if(isprime[i]) - { - for(int j=2*i; j<=N; j+=i) - isprime[j]=false; - } - } - - for(int i=2; i<=N; i++) - { - if(isprime[i]) - prime_numbers.push_back(i); +void SieveOfEratosthenes(int N) { + // initializes the array isprime + memset(isprime, true, sizeof isprime); + + for (int i = 2; i <= N; i++) { + if (isprime[i]) { + for (int j = 2 * i; j <= N; j += i) + isprime[j] = false; } + } + for (int i = 2; i <= N; i++) { + if (isprime[i]) + prime_numbers.push_back(i); + } } // Prime factorization of a number -void prime_factorization(int num) -{ +void prime_factorization(int num) { + int number = num; - int number = num; + for (int i = 0; prime_numbers[i] <= num; i++) { + int count = 0; - for(int i=0; prime_numbers[i]<=num; i++) - { - int count=0; - - // termination condition - if (number == 1) - { - break; - } - - while(number%prime_numbers[i] == 0) - { - count++; - number = number/prime_numbers[i]; - } - - if(count) - factors.push_back(make_pair(prime_numbers[i],count)); + // termination condition + if (number == 1) { + break; } + while (number % prime_numbers[i] == 0) { + count++; + number = number / prime_numbers[i]; + } + if (count) + factors.push_back(make_pair(prime_numbers[i], count)); + } } /* I added a simple UI. */ -int main() -{ - int num; - cout << "\t\tComputes the prime factorization\n\n"; - cout << "Type in a number: "; - cin>>num; +int main() { + int num; + cout << "\t\tComputes the prime factorization\n\n"; + cout << "Type in a number: "; + cin >> num; - SieveOfEratosthenes(num); + SieveOfEratosthenes(num); - prime_factorization(num); + prime_factorization(num); - // Prime factors with their powers in the given number in new line - for(auto it: factors) - { - cout< -#include -#include +#include +#include +#include using namespace std; -bool NumericSort(string a,string b) -{ - while(a[0]=='0') - { +bool NumericSort(string a, string b) { + 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; - -vector v(n); -cout << "Enter the string of Numbers\n"; -for(int i=0;i> v[i]; -} +int main() { + int n; + cout << "Enter number of elements to be sorted Numerically\n"; + cin >> n; -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(),NumericSort); -cout << "Elements sorted Numerically \n"; -for(int i=0;i +#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 a[n]; - cout<<"Enter elements of array=\t"; - for(int i=0;i>a[i]; - } - int temp=0; - for(int i=0;i> n; + cout << "Enter Number of indeces u want to rotate the array to left=\t"; + cin >> k; + int a[n]; + cout << "Enter elements of array=\t"; + for (int i = 0; i < n; i++) { + cin >> a[i]; + } + int temp = 0; + for (int i = 0; i < k; i++) { + temp = a[0]; + for (int j = 0; j < n; j++) { + if (j == n - 1) { + a[n - 1] = temp; + } else { + a[j] = a[j + 1]; + } + } + } + cout << "Your rotated array is=\t"; + for (int j = 0; j < n; j++) { + cout << a[j] << " "; + } + getchar(); + return 0; } diff --git a/Operations on Datastructures/Array Right Rotation.cpp b/Operations on Datastructures/Array Right Rotation.cpp index 9f3e7603786..d46554ee229 100644 --- a/Operations on Datastructures/Array Right Rotation.cpp +++ b/Operations on Datastructures/Array Right Rotation.cpp @@ -1,31 +1,28 @@ #include 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; - } - else{ - a[j]=a[j-1];} - - } - +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]; + } } - cout<<"Your rotated array is=\t"; - for(int i=0;i +#include using namespace std; -struct node -{ - int val; - node *next; +struct node { + int val; + node* next; }; -node *start; +node* start; -void insert(int x) -{ - node *t=start; - - if (start!=NULL) - { - while(t->next!=start) - { - t=t->next; - } - 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; - } -} +void insert(int x) { + node* t = start; -void remove(int x) -{ - node *t=start; - node *p; - while(t->val!=x) - { - p=t; - t=t->next; - } - p->next=t->next; - delete t; + if (start != NULL) { + while (t->next != start) { + t = t->next; + } + 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; + } } -void search(int x) -{ - node *t= start; - int found =0; - while(t->next!=start) - { - if(t->val==x) - { - cout<<"\nFound"; - found=1; - break; - } - t=t->next; - } - if(found==0) - { - cout<<"\nNot Found"; - } +void remove(int x) { + node* t = start; + node* p; + while (t->val != x) { + p = t; + t = t->next; + } + p->next = t->next; + delete t; } -void show() -{ - node *t=start; - do - { - cout<val<<"\t"; - t=t->next; - } - while(t!=start); +void search(int x) { + node* t = start; + int found = 0; + while (t->next != start) { + if (t->val == x) { + cout << "\nFound"; + found = 1; + break; + } + t = t->next; + } + if (found == 0) { + cout << "\nNot Found"; + } +} +void show() { + node* t = start; + do { + cout << t->val << "\t"; + t = t->next; + } while (t != start); } -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; - 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; - } - } - while(choice!=0); +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; + 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; + } + } while (choice != 0); - return 0; + return 0; } diff --git a/Operations on Datastructures/Circular Queue Using Array.cpp b/Operations on Datastructures/Circular Queue Using Array.cpp index d91f31af3dc..a1b205046a4 100644 --- a/Operations on Datastructures/Circular Queue Using Array.cpp +++ b/Operations on Datastructures/Circular Queue Using Array.cpp @@ -1,77 +1,57 @@ -#include +#include using namespace std; int queue[10]; -int front=0; -int rear=0; -int count=0; - -void Enque(int x) -{ - if(count==10) - { - cout<<"\nOverflow"; - } - else - { - queue[rear]=x; - rear=(rear+1)%10; - count++; - } +int front = 0; +int rear = 0; +int count = 0; + +void Enque(int x) { + if (count == 10) { + cout << "\nOverflow"; + } else { + queue[rear] = x; + rear = (rear + 1) % 10; + count++; + } } -void Deque() -{ - if (front==rear) - { - cout<<"\nUnderflow"; - } - - else - { - cout<<"\n"<>ch; - if (ch==1) - { - cout<<"\nInsert : "; - cin>>x; - Enque(x); - } - else if (ch==2) - { - Deque(); - } - else if (ch==3) - { - show(); - } - } - while(ch!=0); - - return 0; +int main() { + int ch, x; + do { + cout << "\n1. Enque"; + cout << "\n2. Deque"; + cout << "\n3. Print"; + cout << "\nEnter Your Choice : "; + cin >> ch; + if (ch == 1) { + cout << "\nInsert : "; + cin >> x; + Enque(x); + } else if (ch == 2) { + Deque(); + } else if (ch == 3) { + show(); + } + } while (ch != 0); + + return 0; } - diff --git a/Operations on Datastructures/Intersection_of_2_arrays.cpp b/Operations on Datastructures/Intersection_of_2_arrays.cpp index e2c064e1ba1..649e6d30f5a 100644 --- a/Operations on Datastructures/Intersection_of_2_arrays.cpp +++ b/Operations on Datastructures/Intersection_of_2_arrays.cpp @@ -1,28 +1,26 @@ #include -int main() -{ - int i,j,m,n; - cout <<"Enter size of array 1:"; +int main() { + 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((ib[j]) - j++; - else - { - cout << a[i++]<<" "; + cout << "Enter elements of array 1:"; + for (i = 0; i < m; i++) + cin >> a[i]; + for (i = 0; i < n; i++) + cin >> b[i]; + i = 0; + j = 0; + while ((i < m) && (j < n)) { + if (a[i] < b[j]) + i++; + else if (a[i] > b[j]) + j++; + else { + 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 daefa18e85a..46d827b60b0 100644 --- a/Operations on Datastructures/Reverse a Linked List using Recusion.cpp +++ b/Operations on Datastructures/Reverse a Linked List using Recusion.cpp @@ -1,80 +1,63 @@ -#include +#include using namespace std; -struct node -{ - int val; - node *next; +struct node { + int val; + node* next; }; -node *start; - -void insert(int x) -{ - node *t=start; - if (start!=NULL) - { - while(t->next!=NULL) - { - t=t->next; - } - 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* start; + +void insert(int x) { + node* t = start; + if (start != NULL) { + while (t->next != NULL) { + t = t->next; + } + 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; + } } -void reverse(node *p, node *q) -{ - if (q->next == NULL) - { - q->next=p; - p->next=NULL; - start=q; - return; - } - else - { - reverse(q, q->next); - q->next=p; - p->next=NULL; - } - +void reverse(node* p, node* q) { + if (q->next == NULL) { + q->next = p; + p->next = NULL; + start = q; + return; + } else { + reverse(q, q->next); + q->next = p; + p->next = NULL; + } } - -void show() -{ - node *t=start; - while(t!=NULL) - { - cout<val<<"\t"; - t=t->next; - } - +void show() { + node* t = start; + while (t != NULL) { + cout << t->val << "\t"; + t = t->next; + } } -int main() -{ - insert(1); - insert(2); - insert(3); - insert(4); - insert(5); - insert(6); - - reverse(start, start->next); +int main() { + insert(1); + insert(2); + insert(3); + insert(4); + insert(5); + insert(6); - show(); + reverse(start, start->next); + show(); - return 0; + return 0; } diff --git a/Operations on Datastructures/Union_of_2_arrays.cpp b/Operations on Datastructures/Union_of_2_arrays.cpp index 4046e1ae8b9..5664a0a562b 100644 --- a/Operations on Datastructures/Union_of_2_arrays.cpp +++ b/Operations on Datastructures/Union_of_2_arrays.cpp @@ -1,33 +1,31 @@ #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++] <<" "; - else - { + 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; -int main() -{ - int n,t; +int main() { + int n, t; cin >> 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; + 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; } return 0; } diff --git a/Others/Decimal To Binary.cpp b/Others/Decimal To Binary.cpp index 3794d2a9697..cc1a9c5ce8b 100644 --- a/Others/Decimal To Binary.cpp +++ b/Others/Decimal To Binary.cpp @@ -1,20 +1,16 @@ -#include +#include using namespace std; -int main() -{ - int number; - cin>>number; - int remainder,binary=0,var=1; +int main() { + int number; + cin >> number; + int remainder, binary = 0, var = 1; -do{ - - remainder=number%2; - number=number/2; - binary=binary+(remainder*var); - var=var*10; + do { + remainder = number % 2; + number = number / 2; + binary = binary + (remainder * var); + var = var * 10; - -} -while(number>0); - cout< 0); + cout << binary; } diff --git a/Others/Decimal To Hexadecimal .cpp b/Others/Decimal To Hexadecimal .cpp index fadddfd74d2..821ccdda942 100644 --- a/Others/Decimal To Hexadecimal .cpp +++ b/Others/Decimal To Hexadecimal .cpp @@ -2,50 +2,48 @@ using namespace std; -void main(void) -{ - int valueToConvert = 0; //Holds user input - int hexArray[8]; //Contains hex values backwards - int i = 0; //counter - int lValue = 0; //Last Value of Hex result +void main(void) { + int valueToConvert = 0; // Holds user input + int hexArray[8]; // Contains hex values backwards + int i = 0; // counter + int lValue = 0; // Last Value of Hex result - cout << "Enter a Decimal Value" << endl; //Displays request to stdout - cin >> valueToConvert; //Stores value into valueToConvert via user input + cout << "Enter a Decimal Value" << endl; // Displays request to stdout + cin >> valueToConvert; // Stores value into valueToConvert via user input - while (valueToConvert > 0) //Dec to Hex Algorithm - { - lValue = valueToConvert % 16; //Gets remainder - valueToConvert = valueToConvert / 16; - hexArray[i] = lValue; //Stores converted values into an array - i++; - } - cout << "Hex Value: "; - while (i > 0) - { - //Displays Hex Letters to stdout - switch (hexArray[i - 1]) { - case 10: - cout << "A"; - break; - case 11: - cout << "B"; - break; - case 12: - cout << "C"; - break; - case 13: - cout << "D"; - break; - case 14: - cout << "E"; - break; - case 15: - cout << "F"; - break; - default: - cout << hexArray[i - 1]; //if not an int 10 - 15, displays int value - } - i--; - } - cout << endl; + while (valueToConvert > 0) // Dec to Hex Algorithm + { + lValue = valueToConvert % 16; // Gets remainder + valueToConvert = valueToConvert / 16; + hexArray[i] = lValue; // Stores converted values into an array + i++; + } + cout << "Hex Value: "; + while (i > 0) { + // Displays Hex Letters to stdout + switch (hexArray[i - 1]) { + case 10: + cout << "A"; + break; + case 11: + cout << "B"; + break; + case 12: + cout << "C"; + break; + case 13: + cout << "D"; + break; + case 14: + cout << "E"; + break; + case 15: + cout << "F"; + break; + default: + cout << hexArray[i - 1]; // if not an int 10 - 15, displays int value + } + i--; + } + cout << endl; } diff --git a/Others/Decimal to Roman Numeral.cpp b/Others/Decimal to Roman Numeral.cpp index a0c0fe95520..b941b16f667 100644 --- a/Others/Decimal to Roman Numeral.cpp +++ b/Others/Decimal to Roman Numeral.cpp @@ -1,70 +1,92 @@ -//This Programme Converts a given decimal number in the range [0,4000) -//to both Lower case and Upper case Roman Numeral +// This Programme Converts a given decimal number in the range [0,4000) +// to both Lower case and Upper case Roman Numeral #include #include -#include #include +#include using namespace std; -//This functions fills a string with character c, n times and returns it -string fill( char c, int n ) -{ - string s = ""; - while( n-- ) s += c; - return s; +// This functions fills a string with character c, n times and returns it +string fill(char c, int n) { + string s = ""; + while (n--) + s += c; + return s; } -//to convert to lowercase Roman Numeral +// to convert to lowercase Roman Numeral // the function works recursively -string tolowerRoman( int n ) -{ - if( n < 4 ) return fill( 'i', n ); - if( n < 6 ) return fill( 'i', 5 - n ) + "v"; - if( n < 9 ) return string( "v" ) + fill( 'i', n - 5 ); - if( n < 11 ) return fill( 'i', 10 - n ) + "x"; - if( n < 40 ) return fill( 'x', n / 10 ) + tolowerRoman( n % 10 ); - if( n < 60 ) return fill( 'x', 5 - n / 10 ) + 'l' + tolowerRoman( n % 10 ); - if( n < 90 ) return string( "l" ) + fill( 'x', n / 10 - 5 ) + tolowerRoman( n % 10 ); - if( n < 110 ) return fill( 'x', 10 - n / 10 ) + "c" + tolowerRoman( n % 10 ); - if( n < 400 ) return fill( 'c', n / 100 ) + tolowerRoman( n % 100 ); - if( n < 600 ) return fill( 'c', 5 - n / 100 ) + 'd' + tolowerRoman( n % 100 ); - if( n < 900 ) return string( "d" ) + fill( 'c', n / 100 - 5 ) + tolowerRoman( n % 100 ); - if( n < 1100 ) return fill( 'c', 10 - n / 100 ) + "m" + tolowerRoman( n % 100 ); - if( n < 4000 ) return fill( 'm', n / 1000 ) + tolowerRoman( n % 1000 ); - return "?"; +string tolowerRoman(int n) { + if (n < 4) + return fill('i', n); + if (n < 6) + return fill('i', 5 - n) + "v"; + if (n < 9) + return string("v") + fill('i', n - 5); + if (n < 11) + return fill('i', 10 - n) + "x"; + if (n < 40) + return fill('x', n / 10) + tolowerRoman(n % 10); + if (n < 60) + return fill('x', 5 - n / 10) + 'l' + tolowerRoman(n % 10); + if (n < 90) + return string("l") + fill('x', n / 10 - 5) + tolowerRoman(n % 10); + if (n < 110) + return fill('x', 10 - n / 10) + "c" + tolowerRoman(n % 10); + if (n < 400) + return fill('c', n / 100) + tolowerRoman(n % 100); + if (n < 600) + return fill('c', 5 - n / 100) + 'd' + tolowerRoman(n % 100); + if (n < 900) + return string("d") + fill('c', n / 100 - 5) + tolowerRoman(n % 100); + if (n < 1100) + return fill('c', 10 - n / 100) + "m" + tolowerRoman(n % 100); + if (n < 4000) + return fill('m', n / 1000) + tolowerRoman(n % 1000); + return "?"; } -//to convert to uppercase Roman Numeral +// to convert to uppercase Roman Numeral // the function works recursively -string toupperRoman( int n ) -{ - if( n < 4 ) return fill( 'I', n ); - if( n < 6 ) return fill( 'I', 5 - n ) + "V"; - if( n < 9 ) return string( "V" ) + fill( 'I', n - 5 ); - if( n < 11 ) return fill( 'I', 10 - n ) + "X"; - if( n < 40 ) return fill( 'X', n / 10 ) + toupperRoman( n % 10 ); - if( n < 60 ) return fill( 'X', 5 - n / 10 ) + 'L' + toupperRoman( n % 10 ); - if( n < 90 ) return string( "L" ) + fill( 'X', n / 10 - 5 ) + toupperRoman( n % 10 ); - if( n < 110 ) return fill( 'X', 10 - n / 10 ) + "C" + toupperRoman( n % 10 ); - if( n < 400 ) return fill( 'C', n / 100 ) + toupperRoman( n % 100 ); - if( n < 600 ) return fill( 'C', 5 - n / 100 ) + 'D' + toupperRoman( n % 100 ); - if( n < 900 ) return string( "D" ) + fill( 'C', n / 100 - 5 ) + toupperRoman( n % 100 ); - if( n < 1100 ) return fill( 'C', 10 - n / 100 ) + "M" + toupperRoman( n % 100 ); - if( n < 4000 ) return fill( 'M', n / 1000 ) + toupperRoman( n % 1000 ); - return "?"; +string toupperRoman(int n) { + if (n < 4) + return fill('I', n); + if (n < 6) + return fill('I', 5 - n) + "V"; + if (n < 9) + return string("V") + fill('I', n - 5); + if (n < 11) + return fill('I', 10 - n) + "X"; + if (n < 40) + return fill('X', n / 10) + toupperRoman(n % 10); + if (n < 60) + return fill('X', 5 - n / 10) + 'L' + toupperRoman(n % 10); + if (n < 90) + return string("L") + fill('X', n / 10 - 5) + toupperRoman(n % 10); + if (n < 110) + return fill('X', 10 - n / 10) + "C" + toupperRoman(n % 10); + if (n < 400) + return fill('C', n / 100) + toupperRoman(n % 100); + if (n < 600) + return fill('C', 5 - n / 100) + 'D' + toupperRoman(n % 100); + if (n < 900) + return string("D") + fill('C', n / 100 - 5) + toupperRoman(n % 100); + if (n < 1100) + return fill('C', 10 - n / 100) + "M" + toupperRoman(n % 100); + if (n < 4000) + return fill('M', n / 1000) + toupperRoman(n % 1000); + return "?"; } -//main function - -int main() -{ +// main function -int n; -cout << "\t\tRoman numbers converter\n\n"; -cout << "Type in decimal number between 0 up to 4000 (exclusive): "; -cin >> n; -cout << n << " in Upper Roman Numerals is " << toupperRoman(n) << "\n"; -cout << n << " in Lower Roman Numerals is " << tolowerRoman(n) << "\n"; -return 0; +int main() { + int n; + cout << "\t\tRoman numbers converter\n\n"; + cout << "Type in decimal number between 0 up to 4000 (exclusive): "; + cin >> n; + cout << n << " in Upper Roman Numerals is " << toupperRoman(n) << "\n"; + cout << n << " in Lower Roman Numerals is " << tolowerRoman(n) << "\n"; + return 0; } diff --git a/Others/GCD_of_n_numbers.cpp b/Others/GCD_of_n_numbers.cpp index 3e9e9ce170e..9d1543a730d 100644 --- a/Others/GCD_of_n_numbers.cpp +++ b/Others/GCD_of_n_numbers.cpp @@ -1,23 +1,21 @@ -//This program aims at calculating the GCD of n numbers by division method +// This program aims at calculating the GCD of n numbers by division method #include 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 using namespace std; -int main() -{ - int n,k,s=0,d; +int main() { + int n, k, s = 0, d; cout << "Enter a number:"; cin >> n; - s=0;k=n; - while(k>9) - { - while(k!=0) - { - d=k%10; - s+=d; - k/=10; + s = 0; + k = n; + while (k > 9) { + while (k != 0) { + 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; } diff --git a/Others/Paranthesis Matching.cpp b/Others/Paranthesis Matching.cpp index 25ee7287b87..fc8dbcee405 100644 --- a/Others/Paranthesis Matching.cpp +++ b/Others/Paranthesis Matching.cpp @@ -1,5 +1,5 @@ -#include -#include +#include +#include using namespace std; @@ -10,56 +10,52 @@ 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(){ - - string exp; - int valid = 1, i = 0; - 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++; - } - - // makes sure the stack is empty after processsing (above) - if (valid == 1 && top == -1){ - cout<<"\nCorrect Expression"; - } - else{ - cout<<"\nWrong Expression"; - } - - return 0; +int main() { + string exp; + int valid = 1, i = 0; + 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++; + } + + // makes sure the stack is empty after processsing (above) + if (valid == 1 && top == -1) { + cout << "\nCorrect Expression"; + } else { + cout << "\nWrong Expression"; + } + + return 0; } diff --git a/Others/Sparse matrix.cpp b/Others/Sparse matrix.cpp index 40073c3451b..d40df26d671 100644 --- a/Others/Sparse matrix.cpp +++ b/Others/Sparse matrix.cpp @@ -3,10 +3,9 @@ where m and n are the dimensions of the matrix.*/ #include using namespace std; -int main() -{ - int m,n; - int counterZeros=0; +int main() { + int m, n; + int counterZeros = 0; cout << "Enter dimensions of matrix (seperated with space): "; cin >> m >> n; int a[m][n]; @@ -14,28 +13,24 @@ int main() cout << "\n"; // reads the matrix from stdin - for(int i=0;i> a[i][j]; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; 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 1cb398a62e3..51949f19a04 100644 --- a/Others/Strassen Matrix Multiplication.cpp +++ b/Others/Strassen Matrix Multiplication.cpp @@ -1,60 +1,47 @@ #include using namespace std; -Multiply(int A[][], int B[][], int n) -{ - 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 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[][]; - } - else - { - - } - +Multiply(int A[][], int B[][], int n) { + 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 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[][]; + } 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"; - for (int i = 0; i < n; i++) - { - for (int j = 0; j >A[i][j]; - } - } - - - cout<<"Enter the elements of Matrix B"; - for (int i = 0; i < n; i++) - { - for (int j = 0; j >B[i][j]; - } - } - - Multiply(A, B, n); - return 0; +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"; + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + cin >> A[i][j]; + } + } + + cout << "Enter the elements of Matrix B"; + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + cin >> B[i][j]; + } + } + + Multiply(A, B, n); + return 0; } \ No newline at end of file diff --git a/Others/String Fibonacci.cpp b/Others/String Fibonacci.cpp index 8027b966859..ea3dde8fd04 100644 --- a/Others/String Fibonacci.cpp +++ b/Others/String Fibonacci.cpp @@ -1,85 +1,71 @@ -//This Programme returns the Nth fibonacci as a string. -//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 - +// This Programme returns the Nth fibonacci as a string. +// 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 using namespace std; -string add(string a, string b) -{ - string temp = ""; +string add(string a, string b) { + string temp = ""; - // carry flag - int carry = 0; + // carry flag + int carry = 0; - // fills up with zeros - while ((int)a.length() < (int)b.length()) - { - a = "0" + a; - } + // fills up with zeros + while ((int)a.length() < (int)b.length()) { + a = "0" + a; + } - // fills up with zeros - while ((int)b.length() < (int)a.length()) - { - b = "0" + b; - } + // fills up with zeros + while ((int)b.length() < (int)a.length()) { + b = "0" + b; + } - // adds the numbers a and b - for (int i = a.length() - 1; i >= 0; i--) - { - char val = (char)(((a[i] - 48) + (b[i] - 48)) + 48 + carry); - if (val > 57) - { - carry = 1; - val -= 10; - } - else - { - carry = 0; - } - temp = val + temp; + // adds the numbers a and b + for (int i = a.length() - 1; i >= 0; i--) { + char val = (char)(((a[i] - 48) + (b[i] - 48)) + 48 + carry); + if (val > 57) { + carry = 1; + val -= 10; + } else { + carry = 0; } + temp = val + temp; + } - // processes the carry flag - if (carry == 1) - { - temp = "1" + temp; - } + // processes the carry flag + if (carry == 1) { + temp = "1" + temp; + } - // removes leading zeros. - while (temp[0] == '0' && temp.length() > 1) - { - temp = temp.substr(1); - } + // removes leading zeros. + while (temp[0] == '0' && temp.length() > 1) { + temp = temp.substr(1); + } - return temp; + return temp; } -void fib_Accurate(long long n) -{ - string tmp = ""; - string fibMinus1 = "1"; - string fibMinus2 = "0"; - for (long long i = 0; i < n; i++) - { - tmp = add(fibMinus1, fibMinus2); - fibMinus2 = fibMinus1; - fibMinus1 = tmp; - } - cout << fibMinus2; +void fib_Accurate(long long n) { + string tmp = ""; + string fibMinus1 = "1"; + string fibMinus2 = "0"; + for (long long i = 0; i < n; i++) { + tmp = add(fibMinus1, fibMinus2); + fibMinus2 = fibMinus1; + fibMinus1 = tmp; + } + cout << fibMinus2; } +int main() { + int n; + cout << "Enter whatever number N you want to find the fibonacci of\n"; + cin >> n; + cout << n << " th Fibonacci is \n"; + fib_Accurate(n); -int main() -{ - int n; - cout << "Enter whatever number N you want to find the fibonacci of\n"; - cin >> n; - cout << n << " th Fibonacci is \n"; - fib_Accurate(n); - - return 0; + return 0; } diff --git a/Others/Tower of Hanoi.cpp b/Others/Tower of Hanoi.cpp index f9b3637844b..c933d628699 100644 --- a/Others/Tower of Hanoi.cpp +++ b/Others/Tower of Hanoi.cpp @@ -1,88 +1,61 @@ -#include +#include using namespace std; -struct tower -{ - int values[10]; - int top; -}F, U, T; - - - -void show() -{ - cout<<"\n\n\tF : "; - for(int i=0; i> no; -int main() -{ - F.top=0; - U.top=0; - T.top=0; - - int no; - - cout << "\nEnter number of discs : " ; - cin >> no; - - for (int i = no; i >0; i--) - { - F.values[F.top++]=i; - }; - - - - - - show(); - TH(no, F, U, T); - + for (int i = no; i > 0; i--) { + F.values[F.top++] = i; + }; - + show(); + TH(no, F, U, T); - - return 0; + return 0; } diff --git a/Others/fibonacci.cpp b/Others/fibonacci.cpp index 82b1fd3227b..4538e6c798b 100644 --- a/Others/fibonacci.cpp +++ b/Others/fibonacci.cpp @@ -1,47 +1,40 @@ -//An efficient way to calculate nth fibonacci number faster and simpler than O(nlogn) method of matrix exponentiation -//This works by using both recursion and dynamic programming. -//as 93rd fibonacci exceeds 19 digits, which cannot be stored in a single long long variable, we can only use it till 92nd fibonacci -//we can use it for 10000th fibonacci etc, if we implement bigintegers. -//This algorithm works with the fact that nth fibonacci can easily found if we have already found n/2th or (n+1)/2th fibonacci -//It is a property of fibonacci similar to matrix exponentiation. - +// An efficient way to calculate nth fibonacci number faster and simpler than +// O(nlogn) method of matrix exponentiation This works by using both recursion +// and dynamic programming. as 93rd fibonacci exceeds 19 digits, which cannot be +// stored in a single long long variable, we can only use it till 92nd fibonacci +// we can use it for 10000th fibonacci etc, if we implement bigintegers. +// This algorithm works with the fact that nth fibonacci can easily found if we +// have already found n/2th or (n+1)/2th fibonacci 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) -{ - - if (n == 0) - 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 fib(long long n) { + if (n == 0) + 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; -int main() -{ - //Main Function - for(long long i=1;i<93;i++) - { - cout << i << " th fibonacci number is " << fib(i) << "\n"; - } - return 0; + 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; +} diff --git a/Others/sieve_of_Eratosthenes.cpp b/Others/sieve_of_Eratosthenes.cpp index e20aec6ae85..8e55d7772ba 100644 --- a/Others/sieve_of_Eratosthenes.cpp +++ b/Others/sieve_of_Eratosthenes.cpp @@ -1,5 +1,5 @@ /* - * Sieve of Eratosthenes is an algorithm to find the primes + * Sieve of Eratosthenes is an algorithm to find the primes * that is between 2 to N (as defined in main). * * Time Complexity : O(N) @@ -13,46 +13,41 @@ using namespace std; int primes[MAX]; - /* - * This is the function that finds the primes and eliminates + * This is the function that finds the primes and eliminates * the multiples. */ -void sieve(int N) -{ +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; + } } /* * This function prints out the primes to STDOUT */ -void print(int N) -{ - for(int i=0;i<=N;i++) - if(primes[i] == 0) +void print(int N) { + for (int i = 0; i <= N; i++) + if (primes[i] == 0) cout << i << ' '; cout << '\n'; } /* - * NOTE: This function is important for the + * NOTE: This function is important for the * initialization of the array. */ -void init() -{ - for(int i=0;i #include +#include using namespace std; -int main() -{ - int num; - cout << "Enter number = "; - cin >> num; +int main() { + int num; + cout << "Enter number = "; + cin >> num; - string s1 = to_string(num); - string s2 = s1; + string s1 = to_string(num); + string s2 = s1; - reverse(s1.begin(),s1.end()); + reverse(s1.begin(), s1.end()); - if(s1 == s2) - cout<<"true"; - else - cout<<"false"; + if (s1 == s2) + cout << "true"; + else + cout << "false"; - return 0; + return 0; } diff --git a/Paranthesis Matching.cpp b/Paranthesis Matching.cpp index 5d37a161eda..269b85d13e7 100644 --- a/Paranthesis Matching.cpp +++ b/Paranthesis Matching.cpp @@ -1,65 +1,50 @@ -#include -#include -#include -#include +#include +#include +#include +#include using namespace std; char stack[100]; -int top=0; +int top = 0; -void push(char ch) -{ - stack[top++]=ch; +void push(char ch) { + stack[top++] = ch; } -char pop() -{ - return stack[--top]; +char pop() { + return stack[--top]; } -bool check(char x, char y) -{ - if ((x=='(' && y==')') || (x=='{' && y=='}') || (x=='[' && y==']') || (x=='<' && y=='>')) - { - return true; - } - else - { - return false; - } +bool check(char x, char y) { + if ((x == '(' && y == ')') || (x == '{' && y == '}') || + (x == '[' && y == ']') || (x == '<' && y == '>')) { + return true; + } else { + return false; + } } - - -int main() -{ - char exp[100]; - cout<<"Enter The Expression : "; - gets(exp); - for (int i = 0; i < strlen(exp); i++) - { - if (exp[i]=='(' || exp[i]=='{' || exp[i]=='[' || exp[i]=='<') - { - push(exp[i]); - } - else if (exp[i]==')' || exp[i]=='}' || exp[i]==']' || exp[i]=='>') - { - if(!check(pop(), exp[i])) - { - cout<<"\nWrong Expression"; - exit(0); - } - } - } - - if(top==0) - { - cout<<"Correct Expression"; - } - else - { - cout<<"\nWrong Expression"; - } - - return 0; +int main() { + char exp[100]; + cout << "Enter The Expression : "; + gets(exp); + for (int i = 0; i < strlen(exp); i++) { + if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[' || exp[i] == '<') { + push(exp[i]); + } else if ( + exp[i] == ')' || exp[i] == '}' || exp[i] == ']' || exp[i] == '>') { + if (!check(pop(), exp[i])) { + cout << "\nWrong Expression"; + exit(0); + } + } + } + + if (top == 0) { + cout << "Correct Expression"; + } else { + cout << "\nWrong Expression"; + } + + return 0; } diff --git a/Primality Test.cpp b/Primality Test.cpp index 0b4bb67de1c..5b744fd74a3 100644 --- a/Primality Test.cpp +++ b/Primality Test.cpp @@ -1,33 +1,31 @@ #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) ) + +// 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/Queue Using Array.cpp b/Queue Using Array.cpp index 7b5816f84b5..548d0c031f5 100644 --- a/Queue Using Array.cpp +++ b/Queue Using Array.cpp @@ -1,78 +1,57 @@ -#include +#include using namespace std; int queue[10]; -int front=0; -int rear=0; - -void Enque(int x) -{ - if(rear==10) - { - cout<<"\nOverflow"; - } - else - { - queue[rear++]=x; - } +int front = 0; +int rear = 0; + +void Enque(int x) { + if (rear == 10) { + cout << "\nOverflow"; + } else { + queue[rear++] = x; + } } -void Deque() -{ - if (front==rear) - { - cout<<"\nUnderflow"; - } - - else - { - cout<<"\n"<>ch; - if (ch==1) - { - cout<<"\nInsert : "; - cin>>x; - Enque(x); - } - else if (ch==2) - { - Deque(); - } - else if (ch==3) - { - show(); - } - } - while(ch!=0); - - return 0; +int main() { + int ch, x; + do { + cout << "\n1. Enque"; + cout << "\n2. Deque"; + cout << "\n3. Print"; + cout << "\nEnter Your Choice : "; + cin >> ch; + if (ch == 1) { + cout << "\nInsert : "; + cin >> x; + Enque(x); + } else if (ch == 2) { + Deque(); + } else if (ch == 3) { + show(); + } + } while (ch != 0); + + return 0; } - diff --git a/Queue Using Linked List.cpp b/Queue Using Linked List.cpp index acf32ebd503..8ada3092cdc 100644 --- a/Queue Using Linked List.cpp +++ b/Queue Using Linked List.cpp @@ -1,90 +1,68 @@ -#include +#include using namespace std; -struct node -{ - int val; - node *next; +struct node { + int val; + node* next; }; - node *front, *rear; +void Enque(int x) { + if (rear == NULL) { + node* n = new node; + n->val = x; + n->next = NULL; + rear = n; + front = n; + } -void Enque(int x) -{ - if (rear==NULL) - { - node *n= new node; - n->val=x; - n->next=NULL; - rear=n; - front=n; - } - - else - { - - node *n = new node; - n->val=x; - n->next=NULL; - rear->next=n; - rear=n; - } + else { + node* n = new node; + n->val = x; + n->next = NULL; + rear->next = n; + rear = n; + } } -void Deque() -{ - if (rear==front) - { - cout<<"\nUnderflow"; - } - else - { - node *t = front; - cout<<"\n"<val<<" deleted"; - front=front->next; - delete t; - } +void Deque() { + if (rear == front) { + cout << "\nUnderflow"; + } else { + node* t = front; + cout << "\n" << t->val << " deleted"; + front = front->next; + delete t; + } } -void show() -{ - node *t=front; - while(t!=NULL) - { - cout<val<<"\t"; - t=t->next; - } +void show() { + node* t = front; + while (t != NULL) { + cout << t->val << "\t"; + t = t->next; + } } -int main() -{ - int ch, x; - do - { - cout<<"\n1. Enque"; - cout<<"\n2. Deque"; - cout<<"\n3. Print"; - cout<<"\nEnter Your Choice : "; - cin>>ch; - if (ch==1) - { - cout<<"\nInsert : "; - cin>>x; - Enque(x); - } - else if (ch==2) - { - Deque(); - } - else if (ch==3) - { - show(); - } - } - while(ch!=0); +int main() { + int ch, x; + do { + cout << "\n1. Enque"; + cout << "\n2. Deque"; + cout << "\n3. Print"; + cout << "\nEnter Your Choice : "; + cin >> ch; + if (ch == 1) { + cout << "\nInsert : "; + cin >> x; + Enque(x); + } else if (ch == 2) { + Deque(); + } else if (ch == 3) { + show(); + } + } while (ch != 0); - return 0; + return 0; } - diff --git a/Range queries/MO.cpp b/Range queries/MO.cpp index 2a2cbfffdd5..f1be59c9956 100644 --- a/Range queries/MO.cpp +++ b/Range queries/MO.cpp @@ -1,75 +1,66 @@ #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) - ans++; +void add(int index) { + cnt[a[index]]++; + if (cnt[a[index]] == 1) + ans++; } -void remove(int index) -{ - cnt[a[index]]--; - if(cnt[a[index]] == 0) - ans--; +void remove(int index) { + cnt[a[index]]--; + 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) - { - add(left-1); - left--; - } - while(right<=R) - { - add(right); - right++; - } - while(right>R+1) - { - remove(right-1); - right--; - } - bucket[q[i].i] = ans; - } - for(i=0;i L) { + add(left - 1); + left--; + } + while (right <= R) { + add(right); + right++; + } + while (right > R + 1) { + remove(right - 1); + right--; + } + bucket[q[i].i] = ans; + } + for (i = 0; i < t; i++) + printf("%d\n", bucket[i]); + return 0; } diff --git a/Range queries/segTree.cpp b/Range queries/segTree.cpp index 594c2791eb3..41c344fd53a 100644 --- a/Range queries/segTree.cpp +++ b/Range queries/segTree.cpp @@ -2,89 +2,84 @@ #define MAX 4000000 using namespace std; typedef long long ll; -void ConsTree(ll arr[],ll segtree[],ll low,ll high,ll pos) -{ - if(low == high) - { - segtree[pos] = arr[low]; - return; - } - ll mid = (low+high)/2; - ConsTree(arr,segtree,low,mid,2*pos+1); - ConsTree(arr,segtree,mid+1,high,2*pos+2); - segtree[pos] = segtree[2*pos+1] + segtree[2*pos+2]; +void ConsTree(ll arr[], ll segtree[], ll low, ll high, ll pos) { + if (low == high) { + segtree[pos] = arr[low]; + return; + } + ll mid = (low + high) / 2; + ConsTree(arr, segtree, low, mid, 2 * pos + 1); + ConsTree(arr, segtree, mid + 1, high, 2 * pos + 2); + segtree[pos] = segtree[2 * pos + 1] + segtree[2 * pos + 2]; } -ll query(ll segtree[],ll lazy[],ll qlow,ll qhigh,ll low,ll high,ll pos) -{ - if(low > high) - return 0; - if(qlow>high || 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 query(ll segtree[], ll lazy[], ll qlow, ll qhigh, ll low, ll high, ll pos) { + if (low > high) + return 0; + if (qlow > high || qhigh < low) + return 0; + if (lazy[pos] != 0) { + segtree[pos] += lazy[pos] * (high - low + 1); + if (low != high) { + lazy[2 * pos + 1] += lazy[pos]; + lazy[2 * pos + 2] += lazy[pos]; + } + lazy[pos] = 0; + } + 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); } -void update(ll segtree[],ll lazy[],ll start,ll end,ll delta,ll low,ll high,ll pos) -{ - if(low>high) - return; - if(lazy[pos] != 0) - { - segtree[pos] += lazy[pos]*(high-low+1); - if(low!=high) - { - lazy[2*pos+1] += lazy[pos]; - lazy[2*pos+2] += lazy[pos]; - } - lazy[pos] = 0; - } - if(start > high || end < low) - return; - if(start <= low && end >= high) - { - segtree[pos] += delta*(high-low+1); - if(low != high) - { - 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]; +void update( + ll segtree[], + ll lazy[], + ll start, + ll end, + ll delta, + ll low, + ll high, + ll pos) { + if (low > high) + return; + if (lazy[pos] != 0) { + segtree[pos] += lazy[pos] * (high - low + 1); + if (low != high) { + lazy[2 * pos + 1] += lazy[pos]; + lazy[2 * pos + 2] += lazy[pos]; + } + lazy[pos] = 0; + } + if (start > high || end < low) + return; + if (start <= low && end >= high) { + segtree[pos] += delta * (high - low + 1); + if (low != high) { + 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]; } 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 %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; + 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 %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/Reverse a Linked List using Recusion.cpp b/Reverse a Linked List using Recusion.cpp index daefa18e85a..46d827b60b0 100644 --- a/Reverse a Linked List using Recusion.cpp +++ b/Reverse a Linked List using Recusion.cpp @@ -1,80 +1,63 @@ -#include +#include using namespace std; -struct node -{ - int val; - node *next; +struct node { + int val; + node* next; }; -node *start; - -void insert(int x) -{ - node *t=start; - if (start!=NULL) - { - while(t->next!=NULL) - { - t=t->next; - } - 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* start; + +void insert(int x) { + node* t = start; + if (start != NULL) { + while (t->next != NULL) { + t = t->next; + } + 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; + } } -void reverse(node *p, node *q) -{ - if (q->next == NULL) - { - q->next=p; - p->next=NULL; - start=q; - return; - } - else - { - reverse(q, q->next); - q->next=p; - p->next=NULL; - } - +void reverse(node* p, node* q) { + if (q->next == NULL) { + q->next = p; + p->next = NULL; + start = q; + return; + } else { + reverse(q, q->next); + q->next = p; + p->next = NULL; + } } - -void show() -{ - node *t=start; - while(t!=NULL) - { - cout<val<<"\t"; - t=t->next; - } - +void show() { + node* t = start; + while (t != NULL) { + cout << t->val << "\t"; + t = t->next; + } } -int main() -{ - insert(1); - insert(2); - insert(3); - insert(4); - insert(5); - insert(6); - - reverse(start, start->next); +int main() { + insert(1); + insert(2); + insert(3); + insert(4); + insert(5); + insert(6); - show(); + reverse(start, start->next); + show(); - return 0; + return 0; } diff --git a/Search/Binary Search.cpp b/Search/Binary Search.cpp index cb67e3a077f..7c4f79a1bba 100644 --- a/Search/Binary Search.cpp +++ b/Search/Binary Search.cpp @@ -1,34 +1,32 @@ #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]) - return m; - else if(key>n; - cout<<"Enter array elements: "; - int a[n]; - for (int i = 0; i < n; ++i) - { - cin>>a[i]; - } - cout<<"Enter search key: "; - cin>>key; - int res = binary_search(a,0,n-1,key); - if(res != -1) - cout<> n; + cout << "Enter array elements: "; + int a[n]; + for (int i = 0; i < n; ++i) { + cin >> a[i]; + } + cout << "Enter search key: "; + cin >> key; + int res = binary_search(a, 0, n - 1, key); + if (res != -1) + cout << key << " found at index " << res << endl; + else + cout << key << " not found" << endl; + return 0; } \ No newline at end of file diff --git a/Search/Linear Search.cpp b/Search/Linear Search.cpp index fd381756db4..13b65510aab 100644 --- a/Search/Linear Search.cpp +++ b/Search/Linear Search.cpp @@ -1,48 +1,39 @@ -#include +#include using namespace std; -int LinearSearch(int *array, int size, int key) -{ - for (int i = 0; i < size; ++i) - { - if (array[i]==key) - { - return i; - } - } - - return -1; +int LinearSearch(int* array, int size, int key) { + for (int i = 0; i < size; ++i) { + if (array[i] == key) { + return i; + } + } + + return -1; } +int main() { + int size; + cout << "\nEnter the size of the Array : "; + cin >> size; + + int array[size]; + int key; + + // Input array + cout << "\nEnter the Array of " << size << " numbers : "; + for (int i = 0; i < size; i++) { + cin >> array[i]; + } + + cout << "\nEnter the number to be searched : "; + cin >> key; + + int index = LinearSearch(array, size, key); + if (index != -1) { + cout << "\nNumber found at index : " << index; + } else { + cout << "\nNot found"; + } -int main() -{ - int size; - cout<<"\nEnter the size of the Array : "; - cin >> size; - - int array[size]; - int key; - - //Input array - cout<<"\nEnter the Array of " << size << " numbers : "; - for (int i = 0; i < size; i++) - { - cin>>array[i]; - } - - cout<<"\nEnter the number to be searched : "; - cin>>key; - - int index=LinearSearch(array, size, key); - if (index!=-1) - { - cout<<"\nNumber found at index : "< #include #include -#include using namespace std; char paragraph; -int main() -{ - string paragraph; - cout << "Please enter your paragraph: \n"; - getline (cin,paragraph); - cout << "\nHello, your paragraph is:\n " << paragraph << "!\n"; - cout << "\nThe size of your paragraph = " << paragraph.size() << " characters. \n\n"; - - if (paragraph.empty()) - { - cout << "\nThe paragraph is empty" << endl; - } - else - { - while (true) { - string word; - cout << "Please enter the word you are searching for: "; - getline (cin,word); - cout << "Hello, your word is " << word << "!\n"; - if (paragraph.find(word) == string::npos) - { - cout << word << " does not exist in the sentence" << endl; - } - else - { - cout << "The word " << word << " is now found at location " << paragraph.find(word) << endl << endl; - } - system("pause"); - } +int main() { + string paragraph; + cout << "Please enter your paragraph: \n"; + getline(cin, paragraph); + cout << "\nHello, your paragraph is:\n " << paragraph << "!\n"; + cout << "\nThe size of your paragraph = " << paragraph.size() + << " characters. \n\n"; - } + if (paragraph.empty()) { + cout << "\nThe paragraph is empty" << endl; + } else { + while (true) { + string word; + cout << "Please enter the word you are searching for: "; + getline(cin, word); + cout << "Hello, your word is " << word << "!\n"; + if (paragraph.find(word) == string::npos) { + cout << word << " does not exist in the sentence" << endl; + } else { + cout << "The word " << word << " is now found at location " + << paragraph.find(word) << endl + << endl; + } + system("pause"); + } + } } diff --git a/Search/ternary_search.cpp b/Search/ternary_search.cpp index 4d126f09d5c..7b5e0f33307 100644 --- a/Search/ternary_search.cpp +++ b/Search/ternary_search.cpp @@ -3,7 +3,7 @@ * It does this by dividing the search space by 3 parts and * using its property (usually monotonic property) to find * the desired index. - * + * * Time Complexity : O(log3 n) * Space Complexity : O(1) (without the array) */ @@ -12,7 +12,7 @@ using namespace std; /* - * The absolutePrecision can be modified to fit preference but + * The absolutePrecision can be modified to fit preference but * it is recommended to not go lower than 10 due to errors that * may occur. * @@ -25,92 +25,95 @@ using namespace std; #define MAX 10000000 int N = 21; -int A[MAX] = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,3,4,10}; +int A[MAX] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 10}; /* * get_input function is to receive input from standard IO */ -void get_input() -{ +void get_input() { // TODO: Get input from STDIO or write input to memory as done above. } - /* - * This is the iterative method of the ternary search which returns the index of the element. + * This is the iterative method of the ternary search which returns the index of + * the element. */ -int it_ternary_search(int left, int right, int A[],int target) -{ - while (1) - { - if(left A[twoThird]) left = twoThird+1; - else if(target < A[oneThird]) right = oneThird-1; - - else left = oneThird+1, right = twoThird-1; - } - else return -1; - } +int it_ternary_search(int left, int right, int A[], int target) { + while (1) { + if (left < right) { + if (right - left < absolutePrecision) { + for (int i = left; i <= right; i++) + if (A[i] == target) + return i; + + return -1; + } + + int oneThird = (left + right) / 3 + 1; + int twoThird = (left + right) * 2 / 3 + 1; + + if (A[oneThird] == target) + return oneThird; + else if (A[twoThird] == target) + return twoThird; + + else if (target > A[twoThird]) + left = twoThird + 1; + else if (target < A[oneThird]) + right = oneThird - 1; + + else + left = oneThird + 1, right = twoThird - 1; + } else + return -1; + } } -/* - * This is the recursive method of the ternary search which returns the index of the element. +/* + * 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) -{ - if(left A[twoThird]) return rec_ternary_search(twoThird+1, right, A, target); - - return rec_ternary_search(oneThird+1, twoThird-1, A, target); +int rec_ternary_search(int left, int right, int A[], int target) { + if (left < right) { + if (right - left < absolutePrecision) { + for (int i = left; i <= right; i++) + if (A[i] == target) + return i; + + 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. + * You could either use it_ternary_search or rec_ternary_search according to + * preference. */ -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'; +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 << '\n'; } -int main() -{ +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 e03e4fc14c2..33550530f2e 100644 --- a/Sorting/BitonicSort.cpp +++ b/Sorting/BitonicSort.cpp @@ -1,76 +1,69 @@ // Source : https://www.geeksforgeeks.org/bitonic-sort/ -/* C++ Program for Bitonic Sort. Note that this program +/* 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; - -/*The parameter dir indicates the sorting direction, ASCENDING - or DESCENDING; if (a[i] > a[j]) agrees with the direction, + +#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]); -} - -/*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, +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); - } -} - -/* Caller of bitonicSort for sorting the entire array of +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: "; - cin >> n; - vector numbers; - cout << "Enter " << n << " numbers: "; - int num; +int main() { + int n; + 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); - } + // Input + for (int i = 0; i < n; i++) { + cin >> num; + numbers.push_back(num); + } - //Bubble Sorting - for(int i=0; inumbers[j+1]) - { - swap_check=1; - swap(numbers[j], numbers[j+1]); - } - } - if(swap_check == 0) - { - break; - } - } + // Bubble Sorting + for (int i = 0; i < n; i++) { + swap_check = 0; + for (int j = 0; j < n - 1 - i; j++) { + if (numbers[j] > numbers[j + 1]) { + swap_check = 1; + swap(numbers[j], numbers[j + 1]); + } + } + 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) -{ - while(low<=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) - { - maximum=vec[i]; - maximumindex=i; +// Iterative Version + +void CocktailSelectionSort(vector& vec, int low, int high) { + while (low <= 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) { + maximum = vec[i]; + maximumindex = i; + } + if (vec[i] <= minimum) { + minimum = vec[i]; + minimumindex = i; + } } - if(vec[i]<=minimum) - { - minimum=vec[i]; - minimumindex=i; + if (low != maximumindex || high != minimumindex) { + swap(vec[low], vec[minimumindex]); + swap(vec[high], vec[maximumindex]); + } else { + swap(vec[low], vec[high]); } + + low++; + high--; } - if(low!=maximumindex||high!=minimumindex) - { - swap(vec[low],vec[minimumindex]); - swap(vec[high],vec[maximumindex]); - } - else - { - swap(vec[low],vec[high]); - } - - low++; - high--; -} - } +// Recursive Version -//Recursive Version +void CocktailSelectionSort(vector& vec, int low, int high) { + if (low >= high) + return; -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; + 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) - { - maximum=vec[i]; - maximumindex=i; + for (int i = low; i <= high; i++) { + if (vec[i] >= maximum) { + maximum = vec[i]; + maximumindex = i; } - if(vec[i]<=minimum) - { - minimum=vec[i]; - minimumindex=i; + if (vec[i] <= minimum) { + minimum = vec[i]; + minimumindex = i; } } - if(low!=maximumindex||high!=minimumindex) - { - swap(vec[low],vec[minimumindex]); - swap(vec[high],vec[maximumindex]); + if (low != maximumindex || high != minimumindex) { + swap(vec[low], vec[minimumindex]); + swap(vec[high], vec[maximumindex]); + } else { + swap(vec[low], vec[high]); } - else - { - 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 -//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 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]; + } - 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 2dbf499e760..84d9ddd0992 100644 --- a/Sorting/CountingSortString.cpp +++ b/Sorting/CountingSortString.cpp @@ -1,44 +1,37 @@ -// C++ Program for counting sort +// C++ Program for counting sort #include - + using namespace std; -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]]; - } - - for (i = 0; arr[i]; ++i) - arr[i] = output[i]; - - cout<<"Sorted character array is "<>arr; - - countSort(arr); - - return 0; -} +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]]; + } + + for (i = 0; arr[i]; ++i) + arr[i] = output[i]; + + cout << "Sorted character array is " << arr; +} + +int main() { + string arr; + cin >> arr; + + countSort(arr); + + return 0; +} diff --git a/Sorting/Counting_Sort.cpp b/Sorting/Counting_Sort.cpp index bea604a982d..5535dae0216 100644 --- a/Sorting/Counting_Sort.cpp +++ b/Sorting/Counting_Sort.cpp @@ -1,55 +1,60 @@ -#include +#include using namespace std; -int Max(int Arr[], int N){ - int max = Arr[0]; - for(int i=1; i max) - max = Arr[i]; - return max; +int Max(int Arr[], int N) { + int max = Arr[0]; + for (int i = 1; i < N; i++) + if (Arr[i] > max) + max = Arr[i]; + return max; } -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]--; - } - - return Sorted_Arr; +int* Counting_Sort(int Arr[], int N) { + int max = Max(Arr, N); + int min = Min(Arr, N); + int* Sorted_Arr = new int[N]; + + int* Count = new int[max - min + 1]; + + for (int i = 0; i < N; i++) + Count[Arr[i] - min]++; + + for (int i = 1; i < (max - min + 1); i++) + Count[i] += Count[i - 1]; + + for (int i = N - 1; i >= 0; i--) { + Sorted_Arr[Count[Arr[i] - min] - 1] = Arr[i]; + Count[Arr[i] - min]--; + } + + return Sorted_Arr; } -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); - Sorted_Arr = Counting_Sort(Arr, N); - cout<<"\n\t Sorted Array = ";Print(Sorted_Arr, N); - cout<> n; - int a[20]; - for (i = 1; i <= n; i++) - { - cout << "Enter Element " << (i) << endl; - cin >> a[i]; - } - build_maxheap(a, n); - heapsort(a, n); - cout << "Sorted Output\n"; - for (i = 1; i <= n; i++) - { - cout << a[i] << endl; - } - getch(); +int main() { + int n, i, x; + cout << "Enter number of elements of array\n"; + cin >> n; + int a[20]; + for (i = 1; i <= n; i++) { + cout << "Enter Element " << (i) << endl; + cin >> a[i]; + } + build_maxheap(a, n); + heapsort(a, n); + cout << "Sorted Output\n"; + for (i = 1; i <= n; i++) { + cout << a[i] << endl; + } + getch(); } diff --git a/Sorting/Insertion Sort.cpp b/Sorting/Insertion Sort.cpp index af66550ec99..458563b5ab7 100644 --- a/Sorting/Insertion Sort.cpp +++ b/Sorting/Insertion Sort.cpp @@ -1,41 +1,35 @@ -//Insertion Sort +// Insertion Sort -#include +#include using namespace std; -int main() -{ - int n; - cout<<"\nEnter the length of your array : "; - cin>>n; - int Array[n]; - cout<<"\nEnter any "<>Array[i]; - } - - //Sorting - for(int i=1; i=0 && temp> n; + int Array[n]; + cout << "\nEnter any " << n << " Numbers for Unsorted Array : "; + + // Input + for (int i = 0; i < n; i++) { + cin >> Array[i]; + } + + // Sorting + for (int i = 1; i < n; i++) { + int temp = Array[i]; + int j = i - 1; + while (j >= 0 && temp < Array[j]) { + Array[j + 1] = Array[j]; + j--; + } + Array[j + 1] = temp; + } + + // Output + cout << "\nSorted Array : "; + for (int i = 0; i < n; i++) { + cout << Array[i] << "\t"; + } return 0; } - diff --git a/Sorting/Merge Sort.cpp b/Sorting/Merge Sort.cpp index 9891b8630ad..f17dcee4cb4 100644 --- a/Sorting/Merge Sort.cpp +++ b/Sorting/Merge Sort.cpp @@ -1,99 +1,80 @@ -#include +#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 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]; - - i = 0; - j = 0; - k = l; - while (i < n1 && j < n2) - { - if (L[i] <= R[j]) - { - arr[k] = L[i]; - i++; - } - else - { - arr[k] = R[j]; - j++; - } - k++; - } - - while (i < n1) - { - arr[k] = L[i]; - i++; - k++; - } - +void merge(int arr[], int l, int m, int r) { + int i, j, k; + int n1 = m - l + 1; + 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]; - while (j < n2) - { - arr[k] = R[j]; - j++; - k++; + i = 0; + j = 0; + k = l; + while (i < n1 && j < n2) { + if (L[i] <= R[j]) { + arr[k] = L[i]; + i++; + } else { + arr[k] = R[j]; + j++; } + k++; + } + + while (i < n1) { + arr[k] = L[i]; + i++; + k++; + } + + while (j < n2) { + arr[k] = R[j]; + j++; + k++; + } } - - -void mergeSort(int arr[], int l, int r) -{ - if (l < r) - { - - int m = l+(r-l)/2; - - - mergeSort(arr, l, m); - mergeSort(arr, m+1, r); - - merge(arr, l, m, r); - } + +void mergeSort(int arr[], int l, int r) { + if (l < r) { + int m = l + (r - l) / 2; + + mergeSort(arr, l, m); + 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 : "; + int arr[size]; - for (int i = 0; i < size; ++i) - { - cout<<"\n"; - cin>>arr[i]; - } + cout << "\nEnter the unsorted elements : "; + + for (int i = 0; i < size; ++i) { + cout << "\n"; + cin >> arr[i]; + } + + mergeSort(arr, 0, size); - mergeSort(arr, 0, size); - - cout<<"Sorted array\n"; - show(arr, size); - return 0; + cout << "Sorted array\n"; + show(arr, size); + return 0; } diff --git a/Sorting/OddEven Sort.cpp b/Sorting/OddEven Sort.cpp index 6319cca9104..58c81099faa 100644 --- a/Sorting/OddEven Sort.cpp +++ b/Sorting/OddEven Sort.cpp @@ -4,59 +4,51 @@ using namespace std; -void oddEven(vector &arr, int size) -{ - bool sorted = false; - while( ! sorted ) - { - sorted = true; - for(int i = 1; i < size-1; i += 2)//Odd - { - if(arr[i] > arr[i+1]) - { - swap(arr[i], arr[i+1]); - sorted = false; - } - } - - for(int i = 0; i < size-1; i += 2)//Even - { - if(arr[i] > arr[i+1]) - { - swap(arr[i], arr[i+1]); - sorted = false; - } - } - } +void oddEven(vector& arr, int size) { + bool sorted = false; + while (!sorted) { + sorted = true; + for (int i = 1; i < size - 1; i += 2) // Odd + { + if (arr[i] > arr[i + 1]) { + swap(arr[i], arr[i + 1]); + sorted = false; + } + } + + for (int i = 0; i < size - 1; i += 2) // Even + { + if (arr[i] > arr[i + 1]) { + swap(arr[i], arr[i + 1]); + sorted = false; + } + } + } } -void show(vector A, int size) -{ - int i; - for (i = 0; i < size; i++) - cout << A[i] << "\n"; +void show(vector A, int size) { + int i; + for (i = 0; i < size; i++) + cout << A[i] << "\n"; } +int main() { + int size, temp; + cout << "\nEnter the number of elements : "; + cin >> size; -int main() -{ - int size, temp; - cout << "\nEnter the number of elements : "; - cin >> size; + vector arr; - vector arr; + cout << "\nEnter the unsorted elements : \n"; - cout<<"\nEnter the unsorted elements : \n"; + for (int i = 0; i < size; ++i) { + cin >> temp; + arr.push_back(temp); + } - for (int i = 0; i < size; ++i) - { - cin >> temp; - arr.push_back(temp); - } + oddEven(arr, size); - oddEven(arr, size); - - cout<<"Sorted array\n"; - show(arr, size); - return 0; + cout << "Sorted array\n"; + show(arr, size); + return 0; } diff --git a/Sorting/Quick Sort.cpp b/Sorting/Quick Sort.cpp index b2bb21a7737..1736bb6276b 100644 --- a/Sorting/Quick Sort.cpp +++ b/Sorting/Quick Sort.cpp @@ -1,69 +1,58 @@ /* C implementation QuickSort */ -#include +#include using namespace std; - -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 : "; + int arr[size]; - for (int i = 0; i < size; ++i) - { - cout<<"\n"; - cin>>arr[i]; - } - quickSort(arr, 0, size); - cout<<"Sorted array\n"; - show(arr, size); - return 0; + cout << "\nEnter the unsorted elements : "; + + for (int i = 0; i < size; ++i) { + cout << "\n"; + cin >> arr[i]; + } + quickSort(arr, 0, size); + cout << "Sorted array\n"; + show(arr, size); + return 0; } diff --git a/Sorting/Radix Sort.cpp b/Sorting/Radix Sort.cpp index eb3f12a575a..997278367e8 100644 --- a/Sorting/Radix Sort.cpp +++ b/Sorting/Radix Sort.cpp @@ -1,60 +1,55 @@ -#include -#include #include +#include #include +#include using namespace std; -void radixsort(int a[],int n){ - int count[10]; - int output[n]; - memset(output,0,sizeof(output)); - memset(count,0,sizeof(count)); - int max = 0; - for (int i = 0; i < n; ++i) - { - if (a[i]>max) - { - max = a[i]; - } - } - int maxdigits = 0; - while(max){ - maxdigits++; - max/=10; - } - for(int j=0;j max) { + max = a[i]; + } + } + int maxdigits = 0; + while (max) { + maxdigits++; + max /= 10; + } + for (int j = 0; j < maxdigits; j++) { + for (int i = 0; i < n; i++) { + int t = pow(10, j); + count[(a[i] % (10 * t)) / t]++; + } + int k = 0; + for (int p = 0; p < 10; p++) { + for (int i = 0; i < n; i++) { + int t = pow(10, j); + if ((a[i] % (10 * t)) / t == p) { + output[k] = a[i]; + k++; + } + } + } + memset(count, 0, sizeof(count)); + for (int i = 0; i < n; ++i) { + a[i] = output[i]; + } + } } -void print(int a[],int n){ - for (int i = 0; i < n; ++i) - { - cout< +#include using namespace std; -int main() -{ - int Array[6]; - cout<<"\nEnter any 6 Numbers for Unsorted Array : "; - - //Input - for(int i=0; i<6; i++) - { - cin>>Array[i]; - } - - //Selection Sorting - for(int i=0; i<6; i++) - { - int min=i; - for(int j=i+1; j<6; j++) - { - if(Array[j]> Array[i]; + } + + // Selection Sorting + for (int i = 0; i < 6; i++) { + int min = i; + for (int j = i + 1; j < 6; j++) { + if (Array[j] < Array[min]) { + min = j; // Finding the smallest number in Array + } + } + int temp = Array[i]; + Array[i] = Array[min]; + Array[min] = temp; + } + + // Output + cout << "\nSorted Array : "; + for (int i = 0; i < 6; i++) { + cout << Array[i] << "\t"; + } } diff --git a/Sorting/Shell Sort.cpp b/Sorting/Shell Sort.cpp index bcda66d4edd..e0569efec17 100644 --- a/Sorting/Shell Sort.cpp +++ b/Sorting/Shell Sort.cpp @@ -1,45 +1,36 @@ -#include +#include using namespace std; -int main() -{ - 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 : "; - for (int i = 0; i < size; i++) - { - cin>>array[i]; - } +int main() { + 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 : "; + for (int i = 0; i < size; i++) { + cin >> array[i]; + } - // Sorting - for (int i = size/2; i>0 ; i=i/2) - { - for (int j = i; j =0; k=k-i) - { - if (array[k] 0; i = i / 2) { + for (int j = i; j < size; j++) { + for (int k = j - i; k >= 0; k = k - i) { + if (array[k] < array[k + i]) { + break; + } else { + int temp = array[k + i]; + array[k + i] = array[k]; + array[k] = temp; + } + } + } + } - // Output - cout<<"\nSorted array : "; - for (int i = 0; i < size; ++i) - { - cout< +// Returns the sorted vector after performing SlowSort +// It is a sorting algorithm that is of humorous nature and not useful. +// It's based on the principle of multiply and surrender, a tongue-in-cheek joke +// of divide and conquer. It was published in 1986 by Andrei Broder and Jorge +// Stolfi in their paper Pessimal Algorithms and Simplexity Analysis. This +// algorithm multiplies a single problem into multiple subproblems It is +// interesting because it is provably the least efficient sorting algorithm that +// can be built asymptotically, and with the restriction that such an algorithm, +// while being slow, must still all the time be working towards a result. + +#include using namespace std; -void SlowSort(int a[], int i, int j) -{ - if(i>=j) +void SlowSort(int a[], int i, int 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; - - int arr[size]; - - cout<<"\nEnter the unsorted elements : "; - - 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; +// Sample Main function + +int main() { + int size; + cout << "\nEnter the number of elements : "; + + cin >> size; + + int arr[size]; + + cout << "\nEnter the unsorted elements : "; + + 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/Tim Sort.cpp b/Sorting/Tim Sort.cpp index a97a123a1a3..288dd043584 100644 --- a/Sorting/Tim Sort.cpp +++ b/Sorting/Tim Sort.cpp @@ -1,116 +1,104 @@ // C++ program to perform TimSort. -#include +#include using namespace std; const int RUN = 32; - -// this function sorts array from left index to to right index which is of size atmost RUN -void insertionSort(int arr[], int left, int right) -{ - for (int i = left + 1; i <= right; i++) - { - int temp = arr[i]; - int j = i - 1; - while (arr[j] > temp && j >= left) - { - arr[j+1] = arr[j]; - j--; - } - arr[j+1] = temp; + +// this function sorts array from left index to to right index which is of size +// atmost RUN +void insertionSort(int arr[], int left, int right) { + for (int i = left + 1; i <= right; i++) { + int temp = arr[i]; + int j = i - 1; + while (arr[j] > temp && j >= left) { + arr[j + 1] = arr[j]; + j--; } + arr[j + 1] = temp; + } } - + // merge function merges the sorted runs -void merge(int arr[], int l, int m, int r) -{ - // original array is broken in two parts, left and right array - int len1 = m - l + 1, len2 = r - m; - int left[len1], right[len2]; - for (int i = 0; i < len1; i++) - left[i] = arr[l + i]; - for (int i = 0; i < len2; i++) - right[i] = arr[m + 1 + i]; - - int i = 0; - int j = 0; - int k = l; - - // after comparing, we merge those two array in larger sub array - while (i < len1 && j < len2) - { - if (left[i] <= right[j]) - { - arr[k] = left[i]; - i++; - } - else - { - arr[k] = right[j]; - j++; - } - k++; - } - - // copy remaining elements of left, if any - while (i < len1) - { - arr[k] = left[i]; - k++; - i++; - } - - // copy remaining element of right, if any - while (j < len2) - { - arr[k] = right[j]; - k++; - j++; +void merge(int arr[], int l, int m, int r) { + // original array is broken in two parts, left and right array + int len1 = m - l + 1, len2 = r - m; + int left[len1], right[len2]; + for (int i = 0; i < len1; i++) + left[i] = arr[l + i]; + for (int i = 0; i < len2; i++) + right[i] = arr[m + 1 + i]; + + int i = 0; + int j = 0; + int k = l; + + // after comparing, we merge those two array in larger sub array + while (i < len1 && j < len2) { + if (left[i] <= right[j]) { + arr[k] = left[i]; + i++; + } else { + arr[k] = right[j]; + j++; } + k++; + } + + // copy remaining elements of left, if any + while (i < len1) { + arr[k] = left[i]; + k++; + i++; + } + + // copy remaining element of right, if any + while (j < len2) { + arr[k] = right[j]; + k++; + j++; + } } - + // iterative Timsort function to sort the array[0...n-1] (similar to merge sort) -void timSort(int arr[], int n) -{ - // Sort individual subarrays of size RUN - for (int i = 0; i < n; i+=RUN) - insertionSort(arr, i, min((i+31), (n-1))); - - // start merging from size RUN (or 32). It will merge to form size 64, then 128, 256 and so on .... - for (int size = RUN; size < n; size = 2*size) - { - // pick starting point of left sub array. We are going to merge arr[left..left+size-1] and arr[left+size, left+2*size-1] - // After every merge, we increase left by 2*size - for (int left = 0; left < n; left += 2*size) - { - // find ending point of left sub array - // mid+1 is starting point of right sub array - int mid = left + size - 1; - int right = min((left + 2*size - 1), (n-1)); - - // merge sub array arr[left.....mid] & arr[mid+1....right] - merge(arr, left, mid, right); - } +void timSort(int arr[], int n) { + // Sort individual subarrays of size RUN + for (int i = 0; i < n; i += RUN) + insertionSort(arr, i, min((i + 31), (n - 1))); + + // start merging from size RUN (or 32). It will merge to form size 64, then + // 128, 256 and so on .... + for (int size = RUN; size < n; size = 2 * size) { + // pick starting point of left sub array. We are going to merge + // arr[left..left+size-1] and arr[left+size, left+2*size-1] After every + // merge, we increase left by 2*size + for (int left = 0; left < n; left += 2 * size) { + // find ending point of left sub array + // mid+1 is starting point of right sub array + int mid = left + size - 1; + int right = min((left + 2 * size - 1), (n - 1)); + + // merge sub array arr[left.....mid] & arr[mid+1....right] + merge(arr, left, mid, right); } + } } - + // utility function to print the Array -void printArray(int arr[], int n) -{ - for (int i = 0; i < n; i++) - printf("%d ", arr[i]); - printf("\n"); +void printArray(int arr[], int n) { + for (int i = 0; i < n; i++) + printf("%d ", arr[i]); + printf("\n"); } - + // Driver program to test above function -int main() -{ - int arr[] = {5, 21, 7, 23, 19}; - int n = sizeof(arr)/sizeof(arr[0]); - printf("Given Array is\n"); - printArray(arr, n); - - timSort(arr, n); - - printf("After Sorting Array is\n"); - printArray(arr, n); - return 0; +int main() { + int arr[] = {5, 21, 7, 23, 19}; + int n = sizeof(arr) / sizeof(arr[0]); + printf("Given Array is\n"); + printArray(arr, n); + + timSort(arr, n); + + printf("After Sorting Array is\n"); + printArray(arr, n); + return 0; } diff --git a/Sorting/bucketSort.cpp b/Sorting/bucketSort.cpp index 278da92bd94..16cddb087cb 100644 --- a/Sorting/bucketSort.cpp +++ b/Sorting/bucketSort.cpp @@ -1,42 +1,39 @@ // C++ program to sort an array using bucket sort -#include #include +#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 -int main() -{ - int m,n,i,j,c=0; +int main() { + int m, n, i, j, c = 0; cout << "Enter dimensions of matrix:"; cin >> m >> n; int a[m][n]; cout << "Enter matrix elements:"; - for(i=0;> a[i][j]; + for (i = 0; < m; i++) { + for (j = 0; j < n; j++) + cin >> a[i][j]; } - for(i=0;i((m*n)/2)) //Checking for sparse matrix - cout << "Sparse matrix"; + if (c > ((m * n) / 2)) // Checking for sparse matrix + cout << "Sparse matrix"; else - cout << "Not a sparse matrix"; + cout << "Not a sparse matrix"; } diff --git a/Stack Using Array.cpp b/Stack Using Array.cpp index 944258ed4b0..337d77eefd7 100644 --- a/Stack Using Array.cpp +++ b/Stack Using Array.cpp @@ -1,77 +1,55 @@ -#include +#include using namespace std; int stack[10]; -int top=0; +int top = 0; -void push(int x) -{ - if(top==10) - { - cout<<"\nOverflow"; - } - else - { - stack[top++]=x; - } +void push(int x) { + if (top == 10) { + cout << "\nOverflow"; + } else { + stack[top++] = x; + } } -void pop() -{ - if (top==0) - { - cout<<"\nUnderflow"; - } - else - { - cout<<"\n"<>ch; - if (ch==1) - { - cout<<"\nInsert : "; - cin>>x; - push(x); - } - else if (ch==2) - { - pop(); - } - else if (ch==3) - { - show(); - } - else if(ch==4) - { - topmost(); - } - } - while(ch!=0); +int main() { + 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 << "\nInsert : "; + cin >> x; + push(x); + } else if (ch == 2) { + pop(); + } else if (ch == 3) { + show(); + } else if (ch == 4) { + topmost(); + } + } while (ch != 0); - return 0; + return 0; } - diff --git a/Stack Using Linked List.cpp b/Stack Using Linked List.cpp index 753fda8ed9e..abea4b9e06a 100644 --- a/Stack Using Linked List.cpp +++ b/Stack Using Linked List.cpp @@ -1,75 +1,57 @@ -#include +#include using namespace std; -struct node -{ - int val; - node *next; +struct node { + int val; + node* next; }; +node* top; -node *top; - -void push(int x) -{ - node *n = new node; - n->val=x; - n->next=top; - top=n; +void push(int x) { + node* n = new node; + n->val = x; + n->next = top; + top = n; } -void pop() -{ - if (top==NULL) - { - cout<<"\nUnderflow"; - } - else - { - node *t = top; - cout<<"\n"<val<<" deleted"; - top=top->next; - delete t; - } +void pop() { + if (top == NULL) { + cout << "\nUnderflow"; + } else { + node* t = top; + cout << "\n" << t->val << " deleted"; + top = top->next; + delete t; + } } -void show() -{ - node *t=top; - while(t!=NULL) - { - cout<val<<"\n"; - t=t->next; - } +void show() { + node* t = top; + while (t != NULL) { + cout << t->val << "\n"; + t = t->next; + } } -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<<"\nInsert : "; - cin>>x; - push(x); - } - else if (ch==2) - { - pop(); - } - else if (ch==3) - { - show(); - } - } - while(ch!=0); - - return 0; +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 << "\nInsert : "; + cin >> x; + push(x); + } else if (ch == 2) { + pop(); + } else if (ch == 3) { + show(); + } + } while (ch != 0); + + return 0; } - diff --git a/Strassen Matrix Multiplication.cpp b/Strassen Matrix Multiplication.cpp index 1cb398a62e3..51949f19a04 100644 --- a/Strassen Matrix Multiplication.cpp +++ b/Strassen Matrix Multiplication.cpp @@ -1,60 +1,47 @@ #include using namespace std; -Multiply(int A[][], int B[][], int n) -{ - 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 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[][]; - } - else - { - - } - +Multiply(int A[][], int B[][], int n) { + 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 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[][]; + } 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"; - for (int i = 0; i < n; i++) - { - for (int j = 0; j >A[i][j]; - } - } - - - cout<<"Enter the elements of Matrix B"; - for (int i = 0; i < n; i++) - { - for (int j = 0; j >B[i][j]; - } - } - - Multiply(A, B, n); - return 0; +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"; + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + cin >> A[i][j]; + } + } + + cout << "Enter the elements of Matrix B"; + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + cin >> B[i][j]; + } + } + + Multiply(A, B, n); + return 0; } \ No newline at end of file diff --git a/Tower of Hanoi.cpp b/Tower of Hanoi.cpp index f9b3637844b..c933d628699 100644 --- a/Tower of Hanoi.cpp +++ b/Tower of Hanoi.cpp @@ -1,88 +1,61 @@ -#include +#include using namespace std; -struct tower -{ - int values[10]; - int top; -}F, U, T; - - - -void show() -{ - cout<<"\n\n\tF : "; - for(int i=0; i> no; -int main() -{ - F.top=0; - U.top=0; - T.top=0; - - int no; - - cout << "\nEnter number of discs : " ; - cin >> no; - - for (int i = no; i >0; i--) - { - F.values[F.top++]=i; - }; - - - - - - show(); - TH(no, F, U, T); - + for (int i = no; i > 0; i--) { + F.values[F.top++] = i; + }; - + show(); + TH(no, F, U, T); - - return 0; + return 0; } diff --git a/Tree.cpp b/Tree.cpp index 963779abe6a..406ff26e0a5 100644 --- a/Tree.cpp +++ b/Tree.cpp @@ -1,160 +1,130 @@ -#include +#include using namespace std; - -struct node -{ - int val; - node *left; - node *right; +struct node { + int val; + node* left; + node* right; }; -struct queue -{ - node *t[100]; - int front; - int rear; +struct queue { + node* t[100]; + int front; + int rear; }; queue q; - -void enqueue(node *n) -{ - q.t[q.rear++]=n; +void enqueue(node* n) { + q.t[q.rear++] = n; } -node * dequeue() -{ - return (q.t[q.front++]); +node* dequeue() { + return (q.t[q.front++]); } - - -void CreateTree(node *curr, node *n, int x, char pos) -{ - if(n!=NULL) - { - char ch; - cout<<"\nLeft or Right of "<val<<" : "; - cin>>ch; - if(ch=='l') - CreateTree(n, n->left, x, ch); - else if(ch=='r') - CreateTree(n, n->right, x, ch); - } - - else - { - node *t=new node; - t->val=x; - t->left=NULL; - t->right=NULL; - if (pos=='l') - { - curr->left=t; - } - else if(pos=='r') - { - curr->right=t; - } - } +void CreateTree(node* curr, node* n, int x, char pos) { + if (n != NULL) { + char ch; + cout << "\nLeft or Right of " << n->val << " : "; + cin >> ch; + if (ch == 'l') + CreateTree(n, n->left, x, ch); + else if (ch == 'r') + CreateTree(n, n->right, x, ch); + } + + else { + node* t = new node; + t->val = x; + t->left = NULL; + t->right = NULL; + if (pos == 'l') { + curr->left = t; + } else if (pos == 'r') { + curr->right = t; + } + } } - -void BFT(node *n) -{ - if(n!=NULL) - { - cout<val<<" "; - enqueue(n->left); - enqueue(n->right); - BFT(dequeue()); - } +void BFT(node* n) { + if (n != NULL) { + cout << n->val << " "; + enqueue(n->left); + enqueue(n->right); + BFT(dequeue()); + } } -void Pre(node *n) -{ - if (n!=NULL) - { - cout<val<<" "; - Pre(n->left); - Pre(n->right); - } +void Pre(node* n) { + if (n != NULL) { + cout << n->val << " "; + Pre(n->left); + Pre(n->right); + } } -void In(node *n) -{ - if (n!=NULL) - { - In(n->left); - cout<val<<" "; - In(n->right); - } +void In(node* n) { + if (n != NULL) { + In(n->left); + cout << n->val << " "; + In(n->right); + } } - -void Post(node *n) -{ - if (n!=NULL) - { - Post(n->left); - Post(n->right); - cout<val<<" "; - } +void Post(node* n) { + if (n != NULL) { + Post(n->left); + Post(n->right); + cout << n->val << " "; + } } - - -int main() -{ - 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; - do - { - cout<<"\n1. Insert : "; - cout<<"\n2. Breadth First"; - cout<<"\n3. Preorder Depth First"; - cout<<"\n4. Inorder Depth First"; - cout<<"\n5. Postorder Depth First"; - - cout<<"\nEnter Your Choice : "; - cin>>ch; - switch(ch) - { - case 1: - int x; - char pos; - cout<<"\nEnter the value to be Inserted : "; - cin>>x; - cout<<"\nLeft or Right of Root : "; - cin>>pos; - if(pos=='l') - CreateTree(root, root->left, x, pos); - else if(pos=='r') - CreateTree(root, root->right, x, pos); - break; - case 2: - BFT(root); - break; - case 3: - Pre(root); - break; - case 4: - In(root); - break; - case 5: - Post(root); - break; - } - } - while(ch!=0); +int main() { + 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; + do { + cout << "\n1. Insert : "; + cout << "\n2. Breadth First"; + cout << "\n3. Preorder Depth First"; + cout << "\n4. Inorder Depth First"; + cout << "\n5. Postorder Depth First"; + + cout << "\nEnter Your Choice : "; + cin >> ch; + switch (ch) { + case 1: + int x; + char pos; + cout << "\nEnter the value to be Inserted : "; + cin >> x; + cout << "\nLeft or Right of Root : "; + cin >> pos; + if (pos == 'l') + CreateTree(root, root->left, x, pos); + else if (pos == 'r') + CreateTree(root, root->right, x, pos); + break; + case 2: + BFT(root); + break; + case 3: + Pre(root); + break; + case 4: + In(root); + break; + case 5: + Post(root); + break; + } + } while (ch != 0); } diff --git a/Union_of_2_arrays.cpp b/Union_of_2_arrays.cpp index 4046e1ae8b9..5664a0a562b 100644 --- a/Union_of_2_arrays.cpp +++ b/Union_of_2_arrays.cpp @@ -1,33 +1,31 @@ #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++] <<" "; - else - { + 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 +#include using namespace std; -struct node{ - int data; - struct node *next; +struct node { + int data; + struct node* next; }; -class Queue{ - node *front; - node *rear; -public: - Queue(){ - front = NULL; - rear = NULL; - } - void createNode(int val){ - node *ptr; - node *nn; - nn = new node; - ptr = front; - nn->data = val; - nn->next = NULL; - front=nn; - rear=nn; - } - void enqueue(int val){ - if(front==NULL || rear==NULL){ - createNode(val); - } - else{ - node *ptr; - node *nn; - ptr=front; - nn = new node; - nn->data = val; - rear->next = nn; - nn->next = front; - rear = nn; - } - } - void dequeue(){ - node *n; - n = front; - front = front->next; - delete(n); - } - void traverse(){ - node *ptr; - ptr=front; - do{ - cout<data<<" "; - ptr=ptr->next; - }while(ptr!=rear->next); - cout<data; - cout<data = val; + nn->next = NULL; + front = nn; + rear = nn; + } + void enqueue(int val) { + if (front == NULL || rear == NULL) { + createNode(val); + } else { + node* ptr; + node* nn; + ptr = front; + nn = new node; + nn->data = val; + rear->next = nn; + nn->next = front; + rear = nn; } + } + void dequeue() { + node* n; + n = front; + front = front->next; + delete (n); + } + void traverse() { + node* ptr; + ptr = front; + do { + cout << ptr->data << " "; + ptr = ptr->next; + } while (ptr != rear->next); + cout << front->data; + cout << endl; + } }; -int main(void){ - Queue q; - q.enqueue(10); - q.enqueue(20); - q.enqueue(30); - q.enqueue(40); - q.enqueue(50); - q.enqueue(60); - q.enqueue(70); - q.traverse(); - q.dequeue(); - q.traverse(); - return 0; +int main(void) { + Queue q; + q.enqueue(10); + q.enqueue(20); + q.enqueue(30); + q.enqueue(40); + q.enqueue(50); + q.enqueue(60); + q.enqueue(70); + q.traverse(); + q.dequeue(); + q.traverse(); + return 0; } \ No newline at end of file diff --git a/combsort.cpp b/combsort.cpp index 7aa65ab80c2..a47b14af9b1 100644 --- a/combsort.cpp +++ b/combsort.cpp @@ -1,7 +1,6 @@ -//Kind of better version of Bubble sort. -//While Bubble sort is comparering adjacent value, Combsort is using gap larger than 1 -//Best case: O(n) -//Worst case: O(n ^ 2) +// Kind of better version of Bubble sort. +// While Bubble sort is comparering adjacent value, Combsort is using gap larger +// than 1 Best case: O(n) Worst case: O(n ^ 2) #include @@ -11,41 +10,43 @@ int a[100005]; int n; int FindNextGap(int x) { - x = (x * 10) / 13; + x = (x * 10) / 13; - return max(1, x); + return max(1, x); } void CombSort(int a[], int l, int r) { - //Init gap - int gap = n; - - //Initialize swapped as true to make sure that loop runs - bool swapped = true; - - //Keep running until gap = 1 or none elements were swapped - while (gap != 1 || swapped) { - //Find next gap - gap = FindNextGap(gap); - - swapped = false; - - // Compare all elements with current gap - for(int i = l; i <= r - gap; ++i) { - if (a[i] > a[i + gap]) { - swap(a[i], a[i + gap]); - swapped = true; - } - } + // Init gap + int gap = n; + + // Initialize swapped as true to make sure that loop runs + bool swapped = true; + + // Keep running until gap = 1 or none elements were swapped + while (gap != 1 || swapped) { + // Find next gap + gap = FindNextGap(gap); + + swapped = false; + + // Compare all elements with current gap + for (int i = l; i <= r - gap; ++i) { + if (a[i] > a[i + gap]) { + swap(a[i], a[i + gap]); + swapped = true; + } } + } } int main() { - cin >> n; - for(int i = 1; i <= n; ++i) cin >> a[i]; + cin >> n; + for (int i = 1; i <= n; ++i) + cin >> a[i]; - CombSort(a, 1, n); + CombSort(a, 1, n); - for(int i = 1; i <= n; ++i) cout << a[i] << ' '; - return 0; + for (int i = 1; i <= n; ++i) + cout << a[i] << ' '; + return 0; } diff --git a/fibonacci.cpp b/fibonacci.cpp index d753d8dfed1..4538e6c798b 100644 --- a/fibonacci.cpp +++ b/fibonacci.cpp @@ -1,46 +1,40 @@ -//An efficient way to calculate nth fibonacci number faster and simpler than O(nlogn) method of matrix exponentiation -//This works by using both recursion and dynamic programming. -//as 93rd fibonacci exceeds 19 digits, which cannot be stored in a single long long variable, we can only use it till 92nd fibonacci -//we can use it for 10000th fibonacci etc, if we implement bigintegers. -//This algorithm works with the fact that nth fibonacci can easily found if we have already found n/2th or (n+1)/2th fibonacci -//It is a property of fibonacci similar to matrix exponentiation. - +// An efficient way to calculate nth fibonacci number faster and simpler than +// O(nlogn) method of matrix exponentiation This works by using both recursion +// and dynamic programming. as 93rd fibonacci exceeds 19 digits, which cannot be +// stored in a single long long variable, we can only use it till 92nd fibonacci +// we can use it for 10000th fibonacci etc, if we implement bigintegers. +// This algorithm works with the fact that nth fibonacci can easily found if we +// have already found n/2th or (n+1)/2th fibonacci 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) -{ - - if (n == 0) - 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 fib(long long n) { + if (n == 0) + 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); + 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; +int main() { + // Main Function + for (long long i = 1; i < 93; i++) { + cout << i << " th fibonacci number is " << fib(i) << "\n"; + } + return 0; } diff --git a/searching.cpp b/searching.cpp index eab40e4e862..af3ceae4c84 100644 --- a/searching.cpp +++ b/searching.cpp @@ -1,39 +1,34 @@ +#include #include #include -#include using namespace std; char paragraph; -int main() -{ - string paragraph; - cout << "Please enter your paragraph: \n"; - getline (cin,paragraph); - cout << "\nHello, your paragraph is:\n " << paragraph << "!\n"; - cout << "\nThe size of your paragraph = " << paragraph.size() << " characters. \n\n"; - - if (paragraph.empty()) - { - cout << "\nThe paragraph is empty" << endl; - } - else - { - while (true) { - string word; - cout << "Please enter the word you are searching for: "; - getline (cin,word); - cout << "Hello, your word is " << word << "!\n"; - if (paragraph.find(word) == string::npos) - { - cout << word << " does not exist in the sentence" << endl; - } - else - { - cout << "The word " << word << " is now found at location " << paragraph.find(word) << endl << endl; - } - system("pause"); - } +int main() { + string paragraph; + cout << "Please enter your paragraph: \n"; + getline(cin, paragraph); + cout << "\nHello, your paragraph is:\n " << paragraph << "!\n"; + cout << "\nThe size of your paragraph = " << paragraph.size() + << " characters. \n\n"; - } + if (paragraph.empty()) { + cout << "\nThe paragraph is empty" << endl; + } else { + while (true) { + string word; + cout << "Please enter the word you are searching for: "; + getline(cin, word); + cout << "Hello, your word is " << word << "!\n"; + if (paragraph.find(word) == string::npos) { + cout << word << " does not exist in the sentence" << endl; + } else { + cout << "The word " << word << " is now found at location " + << paragraph.find(word) << endl + << endl; + } + system("pause"); + } + } } diff --git a/sleep sort.c b/sleep sort.c index e0217ca25b0..0eb3e2c3aa7 100644 --- a/sleep sort.c +++ b/sleep sort.c @@ -1,41 +1,38 @@ +#include #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) -{ + +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]); - + 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() -{ + } + + // 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 + + sleepSort(arr, n); + + return (0); + } \ No newline at end of file diff --git a/smallest-circle.cpp b/smallest-circle.cpp index f48af5e63f4..c4fcf8c8cbc 100644 --- a/smallest-circle.cpp +++ b/smallest-circle.cpp @@ -1,121 +1,128 @@ +#include #include #include -#include using namespace std; struct Point { - double x, y; - Point(double a = 0.0, double b = 0.0) - { - x = a; - y = b; - } + double x, y; + Point(double a = 0.0, double b = 0.0) { + x = a; + y = b; + } }; -double LenghtLine(Point A, Point B) -{ - return sqrt(abs((B.x - A.x)*(B.x - A.x)) + abs((B.y - A.y)*(B.y - A.y))); +double LenghtLine(Point A, Point B) { + return sqrt(abs((B.x - A.x) * (B.x - A.x)) + abs((B.y - A.y) * (B.y - A.y))); } -double TriangleArea(Point A, Point B, Point C) -{ - double a = LenghtLine(A, B); - double b = LenghtLine(B, C); - double c = LenghtLine(C, A); - double p = (a + b + c) / 2; - return sqrt(p*(p - a)*(p - b)*(p - c)); +double TriangleArea(Point A, Point B, Point C) { + double a = LenghtLine(A, B); + double b = LenghtLine(B, C); + double c = LenghtLine(C, A); + double p = (a + b + c) / 2; + return sqrt(p * (p - a) * (p - b) * (p - c)); } -bool PointInCircle(vector &P, Point Center, double R) -{ - for (size_t i = 0; i < P.size(); i++) - { - if (LenghtLine(P[i], Center) > R) - return false; - } - return true; +bool PointInCircle(vector& P, Point Center, double R) { + for (size_t i = 0; i < P.size(); i++) { + if (LenghtLine(P[i], Center) > R) + return false; + } + return true; } -double circle(vector P) -{ - double minR = INT8_MAX; - double R; - 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++) - { - 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; - } - if (R <= minR) - { - minR = R; - minC = C; - } - - } - for (size_t i = 0; i < P.size() - 1; i++) - for (size_t j = i + 1; j < P.size(); j++) - { - C.x = (P[i].x + P[j].x) / 2; - C.y = (P[i].y + P[j].y) / 2; - R = LenghtLine(C, P[i]); - if (!PointInCircle(P, C, R)) - { - continue; - } - if (R <= minR) - { - minR = R; - minC = C; - } +double circle(vector P) { + double minR = INT8_MAX; + double R; + 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++) { + 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; + } + if (R <= minR) { + minR = R; + minC = C; } - cout << minC.x << " " << minC.y << endl; - return minR; + } + for (size_t i = 0; i < P.size() - 1; i++) + for (size_t j = i + 1; j < P.size(); j++) { + C.x = (P[i].x + P[j].x) / 2; + C.y = (P[i].y + P[j].y) / 2; + R = LenghtLine(C, P[i]); + if (!PointInCircle(P, C, R)) { + continue; + } + if (R <= minR) { + minR = R; + minC = C; + } + } + cout << minC.x << " " << minC.y << endl; + return minR; } -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)); - cout << circle(Pv) << endl; +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)); + 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)); - 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)); + 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)); - 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)); + cout << circle(Pv) << endl; } -int main() -{ - test(); - cout << endl; - test2(); - cout << endl; - test3(); - return 0; +int main() { + test(); + cout << endl; + test2(); + cout << endl; + test3(); + return 0; } diff --git a/spiral_print.cpp b/spiral_print.cpp index 03ea074e98d..d58c9d3f733 100644 --- a/spiral_print.cpp +++ b/spiral_print.cpp @@ -1,68 +1,63 @@ -#include +#include using namespace std; -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){ - break; - } - for(int i=endRow;i>=startRow;i--,cnt++){ - cout<= startRow; i--, cnt++) { + cout << a[i][startCol] << " "; + } + startCol++; + } } -int main() -{ - int a[10][10]; - - int r,c; - cin>>r>>c; - genArray(a,r,c); - spiralPrint(a,r,c); +int main() { + int a[10][10]; + int r, c; + cin >> r >> c; + genArray(a, r, c); + spiralPrint(a, r, c); -return 0; + return 0; } diff --git a/ternary_search.cpp b/ternary_search.cpp index 0a2ffbd2a4b..0c2e96ab4d4 100644 --- a/ternary_search.cpp +++ b/ternary_search.cpp @@ -1,19 +1,18 @@ -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; +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; + 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 (x < a[m2]) + return three_part_binary_search(a, x, m1 + 1, m2 - 1); + else if (x > a[m2]) + return three_part_binary_search(a, x, m2 + 1, high); + } else + return -1; } \ No newline at end of file