[
  {
    "path": ".gitignore",
    "content": "build*/\n\n# ----------- C++ ------------------\n# Prerequisites\n*.d\n\n# Compiled Object files\n*.slo\n*.lo\n*.o\n*.obj\n\n# Precompiled Headers\n*.gch\n*.pch\n\n# Compiled Dynamic libraries\n*.so\n*.dylib\n*.dll\n\n# Fortran module files\n*.mod\n*.smod\n\n# Compiled Static libraries\n*.lai\n*.la\n*.a\n*.lib\n\n# Executables\n*.exe\n*.out\n*.app\n\n# ----------- CMake ------------------\nCMakeCache.txt\nCMakeFiles\nCMakeScripts\nTesting\nMakefile\ncmake_install.cmake\ninstall_manifest.txt\ncompile_commands.json\nCTestTestfile.cmake\n\n# files to check the functionality\ncheck_*.cpp\n\n.DS_STORE\n"
  },
  {
    "path": "BST/BinarySearchTree.java",
    "content": "/*\n* @author Nikunj Khokhar\n*/\npublic class BinarySearchTree {\n\n\n    class Node {\n        int key;\n        Node left, right;\n\n        public Node(int item) {\n            key = item;\n            left = right = null;\n        }\n    }\n\n\n    Node root;\n\n\n    BinarySearchTree() {\n        this.root = null;\n    }\n\n\n    void insert(int key) {\n        root = insertRec(root, key);\n    }\n\n\n    Node insertRec(Node root, int key) {\n\n\n        if (root == null) {\n            root = new Node(key);\n            return root;\n        }\n\n\n        if (key < root.key)\n            root.left = insertRec(root.left, key);\n        else if (key > root.key)\n            root.right = insertRec(root.right, key);\n\n\n        return root;\n    }\n\n\n    void inorder()  {\n        inorderRec(root);\n    }\n\n\n    void inorderRec(Node root) {\n        if (root != null) {\n            inorderRec(root.left);\n            System.out.println(root.key);\n            inorderRec(root.right);\n        }\n    }\n\n\n\n    void preorder()  {\n        preorderRec(root);\n    }\n\n\n    void preorderRec(Node root) {\n        if (root != null) {\n            System.out.println(root.key);\n            preorderRec(root.left);\n            preorderRec(root.right);\n        }\n    }\n\n\n\n    void postorder()  {\n        postorderRec(root);\n    }\n\n\n    void postorderRec(Node root) {\n        if (root != null) {\n\n            postorderRec(root.left);\n            postorderRec(root.right);\n            System.out.println(root.key);\n        }\n    }\n\n\n}\n\npublic class Main {\n    public static void main(String args[])\n    {\n        BinarySearchTree tree = new BinarySearchTree();\n        tree.insert(50);\n        tree.insert( 30);\n        tree.insert( 20);\n        tree.insert( 40);\n        tree.insert( 70);\n        tree.insert( 60);\n        tree.insert(80);\n\n\n        System.out.println(\"Inorder traversal of the given tree : \");\n        tree.inorder();\n        System.out.print(\"\\n\\n\");\n\n\n        System.out.println(\"Postorder traversal of the given tree : \");\n        tree.postorder();\n        System.out.print(\"\\n\\n\");\n\n        \n        System.out.println(\"Preorder traversal of the given tree : \");\n        tree.preorder();\n    }\n}\n"
  },
  {
    "path": "BST/Delete.c",
    "content": "#include<stdio.h>\n#include<stdlib.h>\n\nstruct tree{\n\t\tint data;\n\t\tstruct tree *left;\n\t\tstruct tree *right;\n}*root=NULL,*newn;\n\nstruct tree* create(int n)\n{\n\tnewn=(struct tree*)malloc(sizeof(struct tree));\n\tnewn->data=n;\n\tnewn->left=NULL;\n\tnewn->right=NULL;\n\treturn newn;\n}\n\nstruct tree* ins(struct tree*r,int dat)\n{\n\tif(r==NULL)\n\t\treturn create(dat);\n\tif(dat < r->data)\n\t\tr->left=ins(r->left,dat);\n\telse if(dat > r->data)\n\t\tr->right=ins(r->right,dat);\n\treturn r;\n}\n\nint max=-10000,min=10000;\n\nvoid preorder(struct tree* n)\n{\n\tif(n==NULL)\n\t\treturn;\n\telse\n\t{\n\tpreorder(n->left);\n\tpreorder(n->right);\n\tprintf(\"Deleting Node:%d\\n\",n->data);\n\tfree(n);\n\t}\n}\nint flag=0;\n\nvoid main()\n{\n\tint choice=1,t,ne, exit;\n\tprintf(\"Enter Root Node:\\n\");\n\tscanf(\"%d\",&ne);\n\troot=ins(root,ne);\n\twhile(choice!=0)\n\t{\n\t\tprintf(\"Enter Value:\\n\");\n\t\tscanf(\"%d\",&t);\n\t\tins(root,t);\n\t\tprintf(\"Want to Continue the tree:1 or 0...?\\n\");\n\t\tscanf(\"%d\",&choice);\n\t}\n\tpreorder(root);\n\tscanf(\"%d\", exit);\n}\n"
  },
  {
    "path": "BST/Height.c",
    "content": "#include<stdio.h>\n#include<stdlib.h>\n\nstruct tree{\n\t\tint data;\n\t\tstruct tree* left;\n\t\tstruct tree* right;\n};\n\nstruct tree* create(int dat)\n{\n\tstruct tree* n=(struct tree*)malloc(sizeof(struct tree));\n\tn->data=dat;\n\tn->left=NULL;\n\tn->right=NULL;\n\treturn n;\n}\n\nint height(struct tree* n)\n{\n\tint l,r;\n\tif(n==NULL)\n\t\treturn 0;\n\telse\n\t{\n\t\tl=height(n->left);\n\t\tr=height(n->right);\n\t\tif(l>r)\n\t\t\treturn(l+1);\n\t\telse\n\t\t\treturn (r+1);\n\t}\n}\n\nint count=0;\n\nint node(struct tree* n)\n{\n\tif(n==NULL)\n\t\treturn count;\n\telse\n\t{\n\t\tnode(n->left);\n\t\tnode(n->right);\n\t\tcount++;\n\t}\n\t\n}\n\nvoid main()\n{\n\tstruct tree* root;\n\tint ans, exit;\n\troot=create(30);\n\tans=height(root);\n\tprintf(\"Height of tree after first insertion: %d\\n\",ans);\n\troot->left=create(20);\n\troot->right=create(40);\n\troot->left->left=create(60);\n\tans=height(root);\n\tprintf(\"Height of given tree: %d\\n\",ans);\n\tans=node(root);\n\tprintf(\"No. of nodes: %d\\n\",ans);\n\tscanf(\"%d\", exit);\n}\n"
  },
  {
    "path": "BST/Insert & Search.cpp",
    "content": "/******************************************\r\n*    AUTHOR         :   VIVEK SHAH        *\r\n*    INSTITUTION    :   NIT SURAT         *\r\n******************************************/\r\n\r\n#include <bits/stdc++.h>\r\n#define boost ios_base::sync_with_stdio(false);cin.tie(NULL)\r\n#define ll long long int\r\n#define mod 1000000007\r\n#define rep(i,a,b) for (ll i = a; i<b; ++i)\r\n\r\nusing namespace std;\r\n\r\nstruct node\r\n{\r\n\tint data;\r\n\tstruct node* left;\r\n\tstruct node* right;\r\n};\r\n\r\nstruct node* getNode(int data){\r\n\tstruct node* tmp = new node();\r\n\ttmp->data = data;\r\n\ttmp->left = NULL;\r\n\ttmp->right = NULL;\r\n\treturn tmp;\r\n}\r\n\r\nstruct node* insert(struct node* root,int data){\r\n\tif (root==NULL)\r\n\t{\r\n\t\troot = getNode(data);\r\n\t}\r\n\telse if (data <= root->data)\r\n\t{\r\n\t\troot->left = insert(root->left,data); \r\n\t}\r\n\telse{\r\n\t\troot->right = insert(root->right,data);\r\n\t}\r\n\treturn root;\r\n}\r\n\r\nint search(struct node* root, int data){\r\n\tif (root==NULL)\r\n\t{\r\n\t\treturn 0;\r\n\t}\r\n\telse if (root->data = data)\r\n\t{\r\n\t\treturn 1;\r\n\t}\r\n\telse if (data<=root->data)\r\n\t{\r\n\t\treturn search(root->left,data);\r\n\t}\r\n\telse{\r\n\t\treturn search(root->right,data);\r\n\t}\r\n}\r\n\r\nint main()\r\n{\r\n\tboost;\r\n\tstruct node* root = NULL;\r\n\troot = insert(root,15);\r\n\troot = insert(root,10);\r\n\troot = insert(root,20);\r\n\tif(search(root,15)){\r\n\t\tcout<<\"Found\";\r\n\t}\r\n\telse cout<<\"Not Found\";\r\n\treturn 0;\r\n}"
  },
  {
    "path": "BST/MinMax_8.c",
    "content": "#include<stdio.h>\n#include<stdlib.h>\nstruct tree{\n\t\tint data;\n\t\tstruct tree *left;\n\t\tstruct tree *right;\n}*root=NULL,*newn;\nstruct tree* create(int n)\n{\n\tnewn=(struct tree*)malloc(sizeof(struct tree));\n\tnewn->data=n;\n\tnewn->left=NULL;\n\tnewn->right=NULL;\n\treturn newn;\n}\nstruct tree* ins(struct tree*r,int dat)\n{\n\tif(r==NULL)\n\t\treturn create(dat);\n\tif(dat < r->data)\n\t\tr->left=ins(r->left,dat);\n\telse if(dat > r->data)\n\t\tr->right=ins(r->right,dat);\n\treturn r;\n}\nint max=-10000,min=10000;\nvoid Preo(struct tree* n)\n{\n\tif(n==NULL)\n\t\treturn;\n\tif(n->data>max)\n\t\tmax=n->data;\n\tif(n->data<min)\n\t\tmin=n->data;\n\t//printf(\"%d \",n->data);\n\tPreo(n->left);\n\tPreo(n->right);\n}\nvoid main()\n{\n\tint choice=1,t,ne, exit;\n\tprintf(\"Enter Root Node:\\n\");\n\tscanf(\"%d\",&ne);\n\troot=ins(root,ne);\n\twhile(choice!=0)\n\t{\n\t\tprintf(\"Enter Data:\\n\");\n\t\tscanf(\"%d\",&t);\n\t\tins(root,t);\n\t\tprintf(\"Want to Continue the tree:1 or 0...?\\n\");\n\t\tscanf(\"%d\",&choice);\n\t}\n\tPreo(root);\n\tprintf(\"Minimum:%d\\n\",min);\n\tprintf(\"Maximum:%d\\n\",max);\n\tscanf(\"%d\", exit);\n}\n"
  },
  {
    "path": "BST/checkbst",
    "content": "/ C++ program to check if a given tree is BST.\n#include <bits/stdc++.h>\nusing namespace std;\n \n/* A binary tree node has data, pointer to\n   left child and a pointer to right child */\nstruct Node\n{\n    int data;\n    struct Node* left, *right;\n};\n \n// Returns true if given tree is BST.\nbool isBST(Node* root, Node* l=NULL, Node* r=NULL)\n{\n    // Base condition\n    if (root == NULL)\n        return true;\n \n    // if left node exist that check it has\n    // correct data or not\n    if (l != NULL and root->data < l->data)\n        return false;\n \n    // if right node exist that check it has\n    // correct data or not\n    if (r != NULL and root->data > r->data)\n        return false;\n \n    // check recursively for every node.\n    return isBST(root->left, l, root) and\n           isBST(root->right, root, r);\n}\n \n/* Helper function that allocates a new node with the\n   given data and NULL left and right pointers. */\nstruct Node* newNode(int data)\n{\n    struct Node* node = new Node;\n    node->data = data;\n    node->left = node->right = NULL;\n    return (node);\n}\n \n/* Driver program to test above functions*/\nint main()\n{\n    struct Node *root = newNode(3);\n    root->left        = newNode(2);\n    root->right       = newNode(5);\n    root->left->left  = newNode(1);\n    root->left->right = newNode(4);\n \n    if (isBST(root))\n        cout << \"Is BST\";\n    else\n        cout << \"Not a BST\";\n \n    return 0;\n}\n"
  },
  {
    "path": "BST/createBST.cpp",
    "content": "#include<stdio.h>\n#include<stdlib.h>\n \ntypedef struct BST\n{\n    int data;\n    struct BST *left;\n    struct BST *right;\n}node;\n \nnode *create();\nvoid insert(node *,node *);\nvoid preorder(node *);\n \nint main()\n{\n    char ch;\n    node *root=NULL,*temp;\n    \n    do\n    {\n        temp=create();\n        if(root==NULL)\n            root=temp;\n        else    \n            insert(root,temp);\n            \n        printf(\"nDo you want to enter more(y/n)?\");\n        getchar();\n        scanf(\"%c\",&ch);\n    }while(ch=='y'|ch=='Y');\n    \n    printf(\"nPreorder Traversal: \");\n    preorder(root);\n    return 0;\n}\n \nnode *create()\n{\n    node *temp;\n    printf(\"nEnter data:\");\n    temp=(node*)malloc(sizeof(node));\n    scanf(\"%d\",&temp->data);\n    temp->left=temp->right=NULL;\n    return temp;\n}\n \nvoid insert(node *root,node *temp)\n{\n    if(temp->data<root->data)\n    {\n        if(root->left!=NULL)\n            insert(root->left,temp);\n        else\n            root->left=temp;\n    }\n    \n    if(temp->data>root->data)\n    {\n        if(root->right!=NULL)\n            insert(root->right,temp);\n        else\n            root->right=temp;\n    }\n}\n \nvoid preorder(node *root)\n{\n    if(root!=NULL)\n    {\n        printf(\"%d \",root->data);\n        preorder(root->left);\n        preorder(root->right);\n    }\n}\n"
  },
  {
    "path": "BST/lca.cpp",
    "content": "/*\n\tAuthor: Pritish Thakkar\n\tCodechef : joe001\n\tBlog : http://sleepincode.blogspot.com\n*/\n\n/// SUMMARY: \n/// The lowest common ancestor between two nodes n1 \n/// and n2 is defined as the lowest node in BST that \n/// has both n1 and n2 as descendants (where we allow\n/// a node to be a descendant of itself).\n\n// This contains almost all headers required during \n// competitive programming contests, and that's why used\n// by every best coder out there..\n#include<bits/stdc++.h>\n\nusing namespace std;\n\n// Structure if a node in BST\nstruct node{\n\tint data;\n\tstruct node* left;\n\tstruct node* right;\n};\n\n// Returns a new whenever required\nstruct node* getNode(int data){\n\tstruct node* tmp = new node();\n\ttmp->data = data;\n\ttmp->left = NULL;\n\ttmp->right = NULL;\n\treturn tmp;\n}\n\n// Function to insert the elements in a BST\nstruct node* insert(struct node* root,int data){\n\tif (root==NULL)\n\t{\n\t\troot = getNode(data);\n\t}\n\telse if (data <= root->data)\n\t{\n\t\troot->left = insert(root->left,data); \n\t}\n\telse{\n\t\troot->right = insert(root->right,data);\n\t}\n\treturn root;\n}\n\n\n// Returns the value of LCA node.\nint lca(node* root, int val1, int val2){\n\t// If boths values are smaller than current node value\n\t// it means LCA is present in left subtree.\n\tif(root->data > val1 && root->data > val2){\n\t\treturn lca(root->left, val1, val2);\n\t}\n\n\t// If boths values are greater than current node value\n\t// it means LCA is present in right subtree.\n\tif(root->data < val1 && root->data < val2){\n\t\treturn lca(root->right, val1, val2);\n\t}\n\n\t// Now, one is in left subtree and other in right subtree\n\t// return current node value.\n\treturn root->data;\n}\n\nint main(){\n\tstruct node* root = NULL;\n\t\n\t// Inserting the values in the BST\n\troot = insert(root,15);\n\troot = insert(root,10);\n\troot = insert(root,20);\n\troot = insert(root,16);\n\troot = insert(root,17);\n\troot = insert(root,12);\n\n\tcout << lca(root, 12, 17) << endl;\n\n\t// OUTPUT : 15\n}"
  },
  {
    "path": "BST/spiraltransversal.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n#include <stdbool.h>\r\n#include<malloc.h>\r\n//structure of node\r\nstruct node{\r\nint data;\r\nstruct node* left;\r\nstruct node* right;\r\n};\r\nstruct node* root;\r\n//insertion into bst\r\nstruct node* insert(struct node *rootptr,int data)\r\n{\r\n    if(rootptr==NULL)\r\n    {\r\n        rootptr=(struct node*)malloc(sizeof(struct node));\r\n        rootptr->data=data;\r\n        rootptr->left=NULL;\r\n        rootptr->right=NULL;\r\n        return;\r\n    }\r\n    else if(data<=rootptr->data)\r\n    {\r\n        rootptr->left=insert(rootptr->left,data);\r\n    }\r\n    else if(data>= rootptr->data)\r\n    {\r\n        rootptr->right=insert(rootptr->right,data);\r\n    }\r\n    return rootptr;\r\n}\r\n//inorder transversal of tree\r\nvoid inorder(struct node* rootptr)\r\n{\r\n    if(rootptr==NULL)\r\n    return;\r\n    inorder(rootptr->left);\r\n    printf(\"%d \",rootptr->data);\r\n    inorder(rootptr->right);\r\n}\r\n//to print a level of tree\r\nvoid printGivenLevel(struct node* root, int level, int ltr)\r\n{\r\n    if(root == NULL)\r\n        return;\r\n    if(level == 1)\r\n        printf(\"%d \", root->data);\r\n    else if (level > 1)\r\n    {\r\n        if(ltr)\r\n        {\r\n            printGivenLevel(root->left, level-1, ltr);\r\n            printGivenLevel(root->right, level-1, ltr);\r\n        }\r\n        else\r\n        {\r\n            printGivenLevel(root->right, level-1, ltr);\r\n            printGivenLevel(root->left, level-1, ltr);\r\n        }\r\n    }\r\n}\r\n//to find height of tree\r\nint height(struct node* node)\r\n{\r\n    if (node==NULL)\r\n        return 0;\r\n    else\r\n    {\r\n\r\n        int lheight = height(node->left);//to find height of left subtree\r\n        int rheight = height(node->right);//to find height of right subtree\r\n\r\n\r\n        if (lheight > rheight)\r\n            return(lheight+1);\r\n        else return(rheight+1);\r\n    }\r\n}\r\n//for spiral transversal of tree\r\nvoid printSpiral(struct node* root)\r\n{\r\n    int h = height(root);\r\n    int i;\r\n\r\n    /*ltr -> Left to Right. If this variable is set,\r\n      then the given level is traverseed from left to right. */\r\n    bool ltr = false;\r\n    for(i=1; i<=h; i++)\r\n    {\r\n        printGivenLevel(root, i, ltr);\r\n\r\n        /*Revert ltr to traverse next level in opposite order*/\r\n        ltr = !ltr;\r\n    }\r\n}\r\n\r\nmain()\r\n{\r\n    root=NULL;\r\n    int n,data;\r\n    while(1)\r\n   {\r\n    printf(\"1.insert\\n2.display\\n3.Spiral Order traversal\\n4.exit\\nenter choice\\n\");\r\n    scanf(\"%d\",&n);\r\n    switch(n)\r\n    {\r\n        case 1: printf(\"enter data\");\r\n                scanf(\"%d\",&data);\r\n                root=insert(root,data);\r\n                break;\r\n        case 2:inorder(root);\r\n                break;\r\n        case 3:printf(\"Spiral Order traversal of binary tree is \\n\");\r\n                printSpiral(root);\r\n\r\n        case 4:return;\r\n    }\r\n   }\r\n}\r\n"
  },
  {
    "path": "Backtrack/NQueen.cpp",
    "content": "#include <iostream>\nusing namespace std;\n\nbool isSafe(char board[][100], int row, int column, int n){\n\t\n\t//check that whole row should not have a queen\n\tfor(int i=0; i<n; i++){\n\t\tif(board[row][i] == 'Q')\n\t\t\treturn false;\n\t}\n\n\t//check that whole column should not have a queen\n\tfor(int i=0; i<n; i++){\n\t\tif(board[i][column] == 'Q')\n\t\t\treturn false;\n\t}\n\n\t//check that left diagonal to the current cell should not have queen\n\tint p=row, q=column;\n\twhile(p>=0 && q>=0){\n\t\tif(board[p][q] == 'Q')\n\t\t\treturn false;\n\t\tp--; q--;\n\t}\n\n\t//check that right diagonal to the current cell should not have queen\n\tp=row; q=column;\n\twhile(p>=0 && q<=n-1){\n\t\tif(board[p][q] == 'Q')\n\t\t\treturn false;\n\t\tp--; q++;\n\t}\n\n\treturn true;\n}\n\nbool nqueen(char board[][100], int n, int i=0){\n\tif(i == n){\n\t\t//board is filled with the n-queens, just print the board\n\t\tfor(int i=0; i<n; i++){\n\t\t\tfor(int j=0; j<n; j++){\n\t\t\t\tcout << board[i][j] << \" \";\n\t\t\t}\n\t\t\tcout << endl;\n\t\t}\n\t\treturn true;\n\t}\n\n\tfor(int j=0; j<n; j++){\n\t\tif(isSafe(board, i, j, n)){ //check that cell is safe or not\n\t\t\tboard[i][j] = 'Q'; //if it's safe, then place a queen at that cell\n\t\t\tif(nqueen(board, n, i+1)) //now searching place for queen in next row\n\t\t\t\treturn true;\n\t\t\tboard[i][j] = '.'; //since, not safe, so again mark that cell with '.'\n\t\t}\n\t}\n\treturn false;\n}\n\nint main(){\n\tint n;\n\tcin >> n;\n\n\tchar board[100][100];\n\tfor(int i=0; i<n; i++){\n\t\tfor(int j=0; j<n; j++){\n\t\t\tboard[i][j] = '.';\n\t\t}\n\t}\n\n\tif(!nqueen(board, n))\n\t\tcout << \"No state possible!\";\n\n\treturn 0;\n}"
  },
  {
    "path": "Backtrack/Rat_Maze_Recurssion_Backtracking.c",
    "content": "#include<stdio.h>\n#define N 4\n\nvoid display(int sol[N][N])\n{\n\tint i,j;\n\tfor(i=0;i<N;i++)\n\t{\n\t\tfor(j=0;j<N;j++)\n\t\t\tprintf(\"%d \",sol[i][j]);\n\t\tprintf(\"\\n\");\n\t}\n}\n\n\nint issafe(int maze[N][N],int x,int y)\n{\n\tif((x>=0 && x<4) && (y>=0 && y<3) && maze[x][y]==1)\n\t\treturn 1;\n\telse\n\t\treturn 0;\n}\n\nint solvemaze(int maze[N][N],int x,int y,int sol[N][N])\n{\n\tif(x==N-1 && y==N-1)\n\t{\n\t\tsol[x][y]=1;\n\t\treturn 1;\n\t}\n\t\n\t\tif(issafe(maze,x,y)==1)\n\t\t{\n\t\t\tsol[x][y]=1;\n\t\t\t\n\t\t\tif(solvemaze(maze,x+1,y,sol)==1)\n\t\t\t\treturn 1;\n\t\t\t\n\t\t\tif(solvemaze(maze,x,y+1,sol)==1)\n\t\t\t\treturn 1;\n\t\t\t\n\t\t\tsol[x][y]=0;\n\t\t\treturn 0;\n\t\t}\n\treturn 0;\n}\n\nvoid solve(int maze[N][N])\n{\n\tint sol[N][N]={{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}};\n\tif(solvemaze(maze,0,0,sol)==0)\n\t{\n\t\tprintf(\"No Solution possible\\n\");\n\t}\n\telse\n\t{\n\t\tdisplay(sol);\n\t}\n}\nvoid main()\n{\n\tint maze[N][N]={{1,0,0,0},{1,1,0,1},{0,1,0,0},{1,1,1,1}};\n\tsolve(maze);\n}\n"
  },
  {
    "path": "Backtrack/nqueen_allsol.py",
    "content": "def initialize(board,n):\r\n    keys=['queen','row','col','pdiag','sdiag']\r\n    for i in keys:\r\n        board[i]={}\r\n    for i in range(n):\r\n        board['queen'][i]=-1\r\n        board['row'][i]=0\r\n        board['col'][i]=0\r\n    for i in range(-(n-1),n):\r\n        board['pdiag'][i]=0\r\n    for i in range(0,2*n-1):\r\n        board['sdiag'][i]=0\r\n\r\ndef placequeen(r,board,n):\r\n    return True\r\n\r\ndef printboard(board,n):\r\n    for row in board['queen'].keys():\r\n        print('(',row,',',board['queen'][row],')',end=' ')\r\n    print('')\r\n\r\ndef isfree(i,j,board):\r\n    return (board['row'][i]==0 and board['col'][j]==0 and board['pdiag'][j-i]==0 and board['sdiag'][j+i]==0)\r\n\r\ndef addqueen(i,j,board):\r\n    board['queen'][i]=j\r\n    board['row'][i]=1\r\n    board['col'][j]=1\r\n    board['pdiag'][j-i]=1\r\n    board['sdiag'][j+i]=1\r\n\r\ndef undoqueen(i,j,board):\r\n    board['queen'][i]=-1\r\n    board['row'][i]=0\r\n    board['col'][j]=0\r\n    board['pdiag'][j-i]=0\r\n    board['sdiag'][j+i]=0\r\n\r\ndef placequeen(i,board,n):\r\n    for j in range(n):\r\n        if isfree(i,j,board):\r\n            addqueen(i,j,board)\r\n            if i==n-1:\r\n                printboard(board,n)\r\n            else:\r\n                extend=placequeen(i+1,board,n)\r\n            undoqueen(i,j,board)\r\n   \r\n#main\r\nn=int(input('Enter the number of queens:'))\r\nboard={}\r\ninitialize(board,n)\r\nplacequeen(0,board,n)\r\n"
  },
  {
    "path": "Backtrack/permutations_of_string.cpp",
    "content": "// Solution for printing all the permutations of a string.\n#include<bits/stdc++.h>\n\n/* Function to swap values at two pointers */\nvoid swap(char *x, char *y)\n{\n    char temp;\n    temp = *x;\n    *x = *y;\n    *y = temp;\n}\n\n/* Function to print permutations of string\n   This function takes three parameters:\n   1. String\n   2. Starting index of the string\n   3. Ending index of the string. */\nvoid permute(char *a, int l, int r)\n{\n    int i;\n    if (l == r)\n        cout<<a;\n    else\n    {\n        for (i = l; i <= r; i++)\n        {\n            swap((a+l), (a+i));\n            permute(a, l+1, r);\n            swap((a+l), (a+i)); //backtrack\n        }\n    }\n}\n\nint main()\n{\n    char str[] = \"ABC\";\n    int n = strlen(str);\n    permute(str, 0, n-1);\n    return 0;\n}\n/*Output\nABC\nACB\nBAC\nBCA\nCBA\nCAB*/\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "<h1>Contributing Guidelines for Algo_Ds</h1>\n\n<p>Thanks for taking the time to contribute to this project. Before making PRs, please note the following:</p>\n\n<h3>A few norms you should follow</h3>\n  <ul>\n    <li>Proper intendation is must!</li>\n    <li>Include ample comments so that code is understandable and easy to follow.</li>\n    <li>Mention the complexity of a function in a comment.</li>\n      <ul>\n        <li>Time complexity : </li>\n        <li>Space complexity : </li>\n      </ul>\n    <li>Place your code in right directory.</li>\n    <li>Give your files names that are relevant and meaningful.</li>\n  </ul>\n\n<h4>You may add your solved questions on spoj, codechef, interviewbit, hackerearth, hackerrank and codeforces.</h4>\n  <ul>\n    <li>First line of your code must begin with a comment mentioning the link of the question</li>\n    <li>Place the solutions in seperate folder \"ques\" in relevant directory</li>\n  </ul>\n\n<h4>DESCRIPTION.md</h4>\n  <p>If not already present, you are free to create a DESCRIPTION.md file in a folder: </p>\n  <ul>\n    <li>Please write a brief description of your algorithm in DESCRIPTION.md file</li>\n    <li>Suggestions of things to include in DESCRIPTION.md file:</li>\n      <ul>\n        <li>Description of algorithm</li>\n        <li>Time and space complexity of algorithm</li>\n        <li>Links to your favourite online questions solvable by that algorithm</li>\n          <ui>\n            <li>You may also provide solution to related questions in \"ques\" folder in the same directory.</li>\n            <li>Also, mention link of solution (if available) along with the question link.</li>\n          </ui>\n      </ul>\n  </ul>\n\n<h4>Best Practices for opening a Pull Request</h4>\n<ul>\n  <li>Give the PR a meaningful name.</li>\n  <li>For e.g. 'Fixes #(issue-number): PR name, fixing the particular bug' (without commas)</li>\n  <li>There should be always 1 commit for 1 PR.</li>\n  <li>If there are more than 1 commit in a PR, squash them.</li>\n  <li>Pull Request details should be descriptive.</li>\n  <li>Commit message should meaningful.</li>\n</ul>\n\n<h4>please have a look at <a href=\"https://github.com/srbcheema1/Algo_Ds/blob/master/STRUCTURE.md\">STRUCTURE.md</a> for file structure</h4>\n"
  },
  {
    "path": "Competitive Programming Challenges/C:C++/HackerEarth:CodeForces/buy_max_with_given_money.cpp",
    "content": "//https://www.hackerrank.com/contests/gs-codesprint/challenges/buy-maximum-stock////i///////i/s\n#include<bits/stdc++.h>\n\n#define F0(i,t) for(int i=0; i<t; i++)\n#define F1(i,t) for(int i=1; i<=t; i++)\n#define Si(x) scanf(\"%d\",&x)\n#define Si2(x,y) scanf(\"%d %d\",&x,&y)\n#define Sl(x) scanf(\"%lld\",&x)\n#define Sl2(x,y) scanf(\"%lld %lld\",&x,&y)\n#define dout if(debugg)cout<<\" \"\n\n   /* * * * * * * * * * * * * * * * * * * * * * * *\n    *                                             *\n    *            _/_/_/            _/             *\n    *         _/        _/  _/_/  _/_/_/          *\n    *          _/_/    _/_/      _/    _/         *\n    *             _/  _/        _/    _/          *\n    *      _/_/_/    _/        _/_/_/             * \n    *                                             *\n    * * * * * * * * * * * * * * * * * * * * * * * */\n\nusing namespace std;\n\ntypedef unsigned long long int ulli;\ntypedef unsigned int ui;\ntypedef pair<lli,lli> mp;\n\nint debugg = 0;\n\nbool sort_fxn(mp a,mp b){\n    return a.second < b.second;\n}\n\n/*\n * return maximum number of elements we can buy...\n * we can buy max i elements at i day\n * vector a is 0 based\n * a[i] contains price of that elem\n * k = max amount to be spent\n */\nulli buyMaximumProducts(ulli n, ulli k, vector <ulli> a) {\n    vector<mp > vec(n);\n    for(int i=0;i<n;i++)\n        vec[i]=mp(i+1,a[i]);\n    sort(vec.begin(),vec.end(),sort_fxn);\n\n    ulli amount = k;\n    ulli bought = 0;\n    ulli buy;\n    for(int i=0;i<n;i++){\n        buy = min(vec[i].first,amount/vec[i].second);\n        bought += buy;\n        amount -= buy*vec[i].second;\n        if(vec[i].second > amount) break;\n    }\n    return bought;\n}\n\nint main() {\n    ulli n,k;\n    cin >> n;\n    vector<ulli> arr(n);\n\n    for(ulli i = 0; i < n; i++)\n       cin >> arr[i];\n\n    ulli k;\n    cin >> k;\n\n    ulli result = buyMaximumProducts(n, k, arr);\n    cout << result << endl;\n}\n// a code by srbcheema1\n"
  },
  {
    "path": "Competitive Programming Challenges/C:C++/HackerEarth:CodeForces/median searching efficientalgo.cpp",
    "content": "#include<iostream>\n#include<vector>\n#include<algorithm>\n#include<array>\nusing namespace std;\nint median(int *a,int s,int r,int k);\nint pivot(int *a,int s,int r);\nint main()\n{\nint *a;\nint n;\ncin>>n;\na=new int[n];\nfor(int i=0;i<n;i++)\n{\ncin>>a[i];\n\n}\nint k;\ncin>>k;\nint x=median(a,0,n-1,k);\ncout<<\"kth smallest element is\\n\"<<x;\nreturn 0;\n\n}\nint median(int *a,int s,int r,int k)\n{\nint p=pivot(a,s,r);\nint v1[r+1],v2[r+1],v3[r+1];\nint s1=0,s2=0,s3=0;\nint r=0,v=0,t=0;\nfor(int i=0;i<r+1;i++)\n{\nif(a[i]<p)\n{\nv1[r]=a[i];\ncout<<v1[i]<<\" \";\ns1++;\nr++;\ncout<<s1;\n}\nelse if(a[i]==p)\n{\nv2[v]=a[i];\ns2++;v++;\n}\nelse{\nv3[t]=a[i];\ns3++;t++;\n}\n}\n\n\n\nif(s1>k)\n{\nmedian(v1,s,s1-1,k);\n\n}\nelse if(s1+s2>k)\n{\nreturn p;\n}\nelse{\nmedian(v3,s1+s2-1,r,k-s1-s2);\n}\n}\n\nint pivot(int *a,int s,int r)\n{\n    int t;\n    if((r+1)%5==0)\n    {\n        t=(r+1)/5;\n    }\n   else{\n       t=((r+1)/5)+1;\n   }\nint b[t][5];\n\nint p;\nint k=0;\nfor(int i=0;i<t;i++)\n{\nfor(int j=0;j<5;j++)\n{\nb[i][j]=a[k];\nk++;\n}\n}\n\nfor(int i=0;i<t;i++)\n{\n  int *q=*(b+i);\n  int *w=(*(b+i)+5);\nsort(q,w);\n}\np=b[t/2-1][2];\ncout<<p<<endl;\nreturn p;\n\n}\n"
  },
  {
    "path": "Competitive Programming Challenges/C:C++/HackerEarth:CodeForces/ques/volcano.cpp",
    "content": "//https://www.hackerrank.com/contests/university-codesprint-3/challenges/erupting-volcanoes\n#include<bits/stdc++.h>\n\n#define F0(i,t) for(int i=0; i<t; i++)\n#define F1(i,t) for(int i=1; i<=t; i++)\n#define Si(x) scanf(\"%d\",&x)\n#define Si2(x,y) scanf(\"%d %d\",&x,&y)\n#define Sl(x) scanf(\"%lld\",&x)\n#define Sl2(x,y) scanf(\"%lld %lld\",&x,&y)\n#define dout if(debugg)cout<<\" \"\n\n   /* * * * * * * * * * * * * * * * * * * * * * * *\n    *                                             *\n    *            _/_/_/            _/             *\n    *         _/        _/  _/_/  _/_/_/          *\n    *          _/_/    _/_/      _/    _/         *\n    *             _/  _/        _/    _/          *\n    *      _/_/_/    _/        _/_/_/             * \n    *                                             *\n    * * * * * * * * * * * * * * * * * * * * * * * */\n\nusing namespace std;\n\ntypedef unsigned long long int ulli;\ntypedef unsigned int ui;\ntypedef pair<int,int> mp;\ntypedef vector<vector<int> > matrix;\n\nstruct elem{\n    int x;\n    int y;\n    int w;\n    elem(int x,int y,int w){\n        this->x = x;\n        this->y = y;\n        this->w = w;\n    }\n};\n\nint debugg = 0;\n\nvoid fill(int x,int y,int w,int n,matrix& mat,matrix& filled){\n\n    queue<elem> q;\n    q.push(elem(x,y,w));\n        \n    while(!q.empty()){\n        elem temp = q.front();\n        x = temp.x; y = temp.y; w = temp.w;\n        q.pop();\n\n        if(x<0 || y<0 || x>=n || y>=n || w<=0 )continue;\n        if(filled[x][y]==1) continue;\n\n        filled[x][y]=1;\n        mat[x][y] += w;\n\n        q.push(elem(x+1,y,w-1));\n        q.push(elem(x,y+1,w-1));\n        q.push(elem(x-1,y,w-1));\n        q.push(elem(x,y-1,w-1));\n        \n        q.push(elem(x-1,y+1,w-1));\n        q.push(elem(x-1,y-1,w-1));\n        q.push(elem(x+1,y+1,w-1));\n        q.push(elem(x+1,y-1,w-1));\n    }\n}\n\nint main(){\n\tint t=1;\n    ios_base::sync_with_stdio(0);cin.tie(0);\n\twhile(t--){\n        int n,m,x,y,w,maxx=0;\n        cin>>n>>m;\n        matrix mat(n,vector<int>(n,0));\n\n        while(m--){\n            cin>>x>>y>>w; \n            matrix filled(n,vector<int>(n,0));\n            fill(x,y,w,n,mat,filled);\n        }\n\n        for(int i=0;i<n;i++){\n            for(int j=0;j<n;j++){\n                if(mat[i][j] >maxx){\n                    maxx=mat[i][j];\n                }\n            }\n        }\n        cout<<maxx<<endl;\n\t}\n}\n// a code by srbcheema1\n"
  },
  {
    "path": "Competitive Programming Challenges/C:C++/HackerEarth:CodeForces/ques-beat_the_clock/spiral_matrix.cpp",
    "content": "#include<bits/stdc++.h>\n\n#define F0(i,t) for(int i=0; i<t; i++)\n#define F1(i,t) for(int i=1; i<=t; i++)\n#define Si(x) scanf(\"%d\",&x)\n#define Si2(x,y) scanf(\"%d %d\",&x,&y)\n#define Sl(x) scanf(\"%lld\",&x)\n#define Sl2(x,y) scanf(\"%lld %lld\",&x,&y)\n#define dout if(debugg)cout<<\" \"\n\n   /* * * * * * * * * * * * * * * * * * * * * * * *\n    *                                             *\n    *            _/_/_/            _/             *\n    *         _/        _/  _/_/  _/_/_/          *\n    *          _/_/    _/_/      _/    _/         *\n    *             _/  _/        _/    _/          *\n    *      _/_/_/    _/        _/_/_/             * \n    *                                             *\n    * * * * * * * * * * * * * * * * * * * * * * * */\n\nusing namespace std;\n\ntypedef unsigned long long int ulli;\ntypedef unsigned int ui;\ntypedef pair<int,int> mp;\n\nint debugg = 0;\n\n/*\n * func to return matrix in a vector such that it is unfolded \n * vec is vector of vectors containing the matrix\n * m and n are dimentions\n */\nvector<int> func(vector<vector<int> > vec,int m,int n){\n    vector<int> ans;\n    int l=0,r=n-1,u=0,d=m-1;\n    int row=0;int col=0;\n\n    while(true){\n        if(l>r || u>d) break;\n        for(int i=l;i<=r;i++){//     >>>\n            dout<<\"> \";\n            ans.push_back(vec[row][i]);\n        }\n        col = r;\n        u = u+1;\n        if(l>r || u>d) break;\n        for(int i=u;i<=d;i++){//     V\n            dout<<\"V \";\n            ans.push_back(vec[i][col]);\n        }\n        row = d;\n        r = r-1;\n        if(l>r || u>d) break;\n        for(int i=r;i>=l;i--){//   <<<\n            dout<<\"< \";\n            ans.push_back(vec[row][i]);\n        }\n        col=l;\n        d = d-1;\n        if(l>r || u>d) break;\n        for(int i=d;i>=u;i--){//  ^\n            dout<<\"^ \";\n            ans.push_back(vec[i][col]);\n        }\n        row = u;\n        l = l+1;\n        if(l>r || u>d) break;\n    }\n    return ans;\n}\n\nint main(){\n\tint t=1,n,m,temp;\n    ios_base::sync_with_stdio(0);cin.tie(0);\n\tcin>>t;\n\twhile(t--){\n        cin>>m>>n;\n        vector<vector<int> > vec(m);\n        for(int i=0;i<m;i++)\n            for(int j=0;j<n;j++){\n                cin>>temp;\n                vec[i].push_back(temp); \n            }\n\n        vector<int> ans = func(vec,m,n);\n        for(int i=0;i<ans.size();i++)\n            cout<<ans[i]<<\" \";\n        cout<<endl;\n\t}\n}\n// a code by srbcheema1\n"
  },
  {
    "path": "Competitive Programming Challenges/C:C++/HackerEarth:CodeForces/ques-l1/codeforces_426_2.cpp",
    "content": "//http://codeforces.com/problemset/problem/834/B\n#include<bits/stdc++.h>\n\nusing namespace std;\n\nint main(){\n    int g,k;\n    int start[27];\n    int last[27];\n    \n    cin>>g>>k;\n    string str;\n    cin>>str;\n\n    int alot=0,free=0,gate=0;\n    memset(start,-1,sizeof(start));\n    memset(last,-1,sizeof(last));\n    for(int i=0;i<g;i++){\n        gate=str[i]-'A'+1;\n\n        if(start[gate]==-1)start[gate]=i;\n\n        last[gate]=i;\n    }\n\n    for(int i=0;i<g;i++){\n        gate=str[i]-'A'+1;\n\n        if(start[gate]==i){\n            if(free==0){\n                alot++;\n            }\n            else{\n                free--;\n                alot++;\n            }\n        }\n        if(last[gate]==i){\n            alot--;\n            free++;\n        }\n    }\n    if(free>k) cout<<\"YES\"<<endl;\n    else cout<<\"NO\"<<endl;\n}\n"
  },
  {
    "path": "Competitive Programming Challenges/C:C++/HackerEarth:CodeForces/ques-l1/positions.cpp",
    "content": "//https://www.hackerearth.com/problem/algorithm/attack-on-daleks/\n#include<bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    int n;\n    long long int sum;\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    cin>>n;\n    int arr1[n],arr2[n];\n    for(int i=0;i<n;i++)\n        cin>>arr1[i];\n        \n    for(int i=0;i<n;i++)\n        cin>>arr2[i];\n\n    sort(arr1,arr1+n);\n    sort(arr2,arr2+n);\n    sum=0;\n    for(int i=0;i<n;i++){\n        sum+=abs(arr2[i]-arr1[i]);\n    }\n    cout<<sum<<endl;\n}\n"
  },
  {
    "path": "Competitive Programming Challenges/C:C++/HackerEarth:CodeForces/ques-l1/snake/snake.cpp",
    "content": "//https://www.hackerrank.com/contests/university-codesprint-3/challenges/the-snake-vs-the-wind\n#include<bits/stdc++.h>\n\n#define F0(i,t) for(int i=0; i<t; i++)\n#define F1(i,t) for(int i=1; i<=t; i++)\n#define Si(x) scanf(\"%d\",&x)\n#define Si2(x,y) scanf(\"%d %d\",&x,&y)\n#define Sl(x) scanf(\"%lld\",&x)\n#define Sl2(x,y) scanf(\"%lld %lld\",&x,&y)\n#define dout if(debugg)cout<<\" \"\n\n   /* * * * * * * * * * * * * * * * * * * * * * * *\n    *                                             *\n    *            _/_/_/            _/             *\n    *         _/        _/  _/_/  _/_/_/          *\n    *          _/_/    _/_/      _/    _/         *\n    *             _/  _/        _/    _/          *\n    *      _/_/_/    _/        _/_/_/             * \n    *                                             *\n    * * * * * * * * * * * * * * * * * * * * * * * */\n\nusing namespace std;\n\ntypedef unsigned long long int ulli;\ntypedef unsigned int ui;\ntypedef pair<int,int> mp;\ntypedef vector<vector<int> > matrix;\n\nint debugg = 0;\n\nvoid fill(matrix& mat,int x,int y,int d,int n){\n    int num=1;\n    if(d==1){//^\n        while(true){\n            mat[x][y]=num;\n            num++;\n            if(x-1>=0 && mat[x-1][y]==0){\n                x = x-1;\n            }\n            else if(y-1>=0 && mat[x][y-1]==0){\n                y=y-1;\n            }\n            else if(y+1<n && mat[x][y+1]==0){\n                y=y+1;\n            }\n            else if(x+1<n && mat[x+1][y]==0){\n                x=x+1; \n            }\n            else{\n                break;\n            }\n        } \n    }\n    if(d==2){//v\n        while(true){\n            mat[x][y]=num;\n            num++;\n            if(x+1<n && mat[x+1][y]==0){\n                x = x+1;\n            }\n            else if(y-1>=0 && mat[x][y-1]==0){\n                y=y-1;\n            }\n            else if(y+1<n && mat[x][y+1]==0){\n                y=y+1;\n            }\n            else if(x-1>=0 && mat[x-1][y]==0){\n                x=x-1; \n            }\n            else{\n                break;\n            }\n        }\n    }\n    if(d==3){//>\n        while(true){\n            mat[x][y]=num;\n            num++;\n            if(y+1<n && mat[x][y+1]==0){\n                y=y+1;\n            }\n            else if(x-1>=0 && mat[x-1][y]==0){\n                x = x-1;\n            }\n            else if(x+1<n && mat[x+1][y]==0){\n                x=x+1; \n            }\n            else if(y-1>=0 && mat[x][y-1]==0){\n                y=y-1;\n            }\n            else{\n                break;\n            }\n        }\n    }\n    if(d==4){//<\n        while(true){\n            mat[x][y]=num;\n            num++;\n            if(y-1>=0 && mat[x][y-1]==0){\n                y=y-1;\n            }\n            else if(x-1>=0 && mat[x-1][y]==0){\n                x = x-1;\n            }\n            else if(x+1<n && mat[x+1][y]==0){\n                x=x+1; \n            }\n            else if(y+1<n && mat[x][y+1]==0){\n                y=y+1;\n            }\n            else{\n                break;\n            }\n        }\n    }\n}\n\nint main(){\n\tint t=1;\n    ios_base::sync_with_stdio(0);cin.tie(0);\n\twhile(t--){\n        int n,x,y,d;\n        cin>>n;\n        string dir;\n        cin>>dir>>x>>y;\n        \n        if(dir[0]=='n')d=1;//^\n        if(dir[0]=='s')d=2;//v\n        if(dir[0]=='e')d=3;//>\n        if(dir[0]=='w')d=4;//<\n        \n        matrix mat(n,vector<int>(n,0));\n        fill(mat,x,y,d,n);\n\n        for(int i=0;i<n;i++){\n            for(int j=0;j<n;j++)\n                cout<<mat[i][j]<<\" \";\n            cout<<endl;\n        }\n\t}\n}\n// a code by srbcheema1\n"
  },
  {
    "path": "Competitive Programming Challenges/C:C++/HackerEarth:CodeForces/ques-l1/snake/wrong_snake.cpp",
    "content": "//https://www.hackerrank.com/contests/university-codesprint-3/challenges/the-snake-vs-the-wind\n#include<bits/stdc++.h>\n\n#define F0(i,t) for(int i=0; i<t; i++)\n#define F1(i,t) for(int i=1; i<=t; i++)\n#define Si(x) scanf(\"%d\",&x)\n#define Si2(x,y) scanf(\"%d %d\",&x,&y)\n#define Sl(x) scanf(\"%lld\",&x)\n#define Sl2(x,y) scanf(\"%lld %lld\",&x,&y)\n#define dout if(debugg)cout<<\" \"\n\n   /* * * * * * * * * * * * * * * * * * * * * * * *\n    *                                             *\n    *            _/_/_/            _/             *\n    *         _/        _/  _/_/  _/_/_/          *\n    *          _/_/    _/_/      _/    _/         *\n    *             _/  _/        _/    _/          *\n    *      _/_/_/    _/        _/_/_/             * \n    *                                             *\n    * * * * * * * * * * * * * * * * * * * * * * * */\n\nusing namespace std;\n\ntypedef unsigned long long int ulli;\ntypedef unsigned int ui;\ntypedef pair<int,int> mp;\ntypedef vector<vector<int> > matrix;\n\nint debugg = 0;\n\nvoid movehu(matrix& mat,int x,int y,int num,int n){\n    if(y==0)\n    for(int i=n-1;i>=0;i--){\n        for(int j=0;j<n;j++){\n            mat[i][j]=num;\n            num++;\n        }\n        i--;\n        if(i<0)break;\n        for(int j=n-1;j>=0;j--){\n            mat[i][j]=num;\n            num++;\n        }\n    }\n    else\n    for(int i=n-1;i>=0;i--){\n        for(int j=n-1;j>=0;j--){\n            mat[i][j]=num;\n            num++;\n        }\n        i--;\n        if(i<0)break;\n        for(int j=0;j<n;j++){\n            mat[i][j]=num;\n            num++;\n        }\n    }\n}\nvoid movehd(matrix& mat,int x,int y,int num,int n){\n    if(y==0)\n    for(int i=0;i<n;i++){\n        for(int j=0;j<n;j++){\n            mat[i][j]=num;\n            num++;\n        }\n        i++;\n        if(i>=n)break;\n        for(int j=n-1;j>=0;j--){\n            mat[i][j]=num;\n            num++;\n        }\n    }\n    else\n    for(int i=0;i<n;i++){\n        for(int j=n-1;j>=0;j--){\n            mat[i][j]=num;\n            num++;\n        }\n        i++;\n        if(i>=n)break;\n        for(int j=0;j<n;j++){\n            mat[i][j]=num;\n            num++;\n        }\n    }\n}\nvoid movevl(matrix& mat,int x,int y,int num,int n){\n    if(x==0)\n    for(int j=n-1;j>=0;j--){\n        for(int i=0;i<n;i++){\n            mat[i][j]=num;\n            num++;\n        }\n        j--;\n        if(j<0)break;\n        for(int i=n-1;i>=0;i--){\n            mat[i][j]=num;\n            num++;\n        }\n    }\n    else\n    for(int j=n-1;j>=0;j--){\n        for(int i=n-1;i>=0;i--){\n            mat[i][j]=num;\n            num++;\n        }\n        j--;\n        if(j<0)break;\n        for(int i=0;i<n;i++){\n            mat[i][j]=num;\n            num++;\n        }\n    }\n}\nvoid movevr(matrix& mat,int x,int y,int num,int n){\n    if(x==0)\n    for(int j=0;j<n;j++){\n        for(int i=0;i<n;i++){\n            mat[i][j]=num;\n            num++;\n        }\n        j++;\n        if(j>=n)break;\n        for(int i=n-1;i>=0;i--){\n            mat[i][j]=num;\n            num++;\n        }\n    }\n    else\n    for(int j=0;j<n;j++){\n        for(int i=n-1;i>=0;i--){\n            mat[i][j]=num;\n            num++;\n        }\n        j++;\n        if(j>=n)break;\n        for(int i=0;i<n;i++){\n            mat[i][j]=num;\n            num++;\n        }\n    }\n}\n\n\nvoid fill(matrix& mat,int x,int y,int d,int n){ \n    if(d==1 || d==2){//n  or s  ... move horizontally\n        if(x==n-1){//horizontally up\n            movehu(mat,x,y,1,n) ;\n        }\n        else{//horizontally down\n            movehd(mat,x,y,1,n) ;\n        }\n    }\n    else{//e or w ... move vertically\n        if(y==n-1){//vertically left\n            movevl(mat,x,y,1,n) ; \n        } \n        else{//vertically right\n            movevr(mat,x,y,1,n) ;\n        }\n    }\n}\n\nint main(){\n\tint t=1;\n    ios_base::sync_with_stdio(0);cin.tie(0);\n\twhile(t--){\n        int n,x,y,d;\n        cin>>n;\n        string dir;\n        cin>>dir>>x>>y;\n        \n        if(dir[0]=='n')d=1;//^\n        if(dir[0]=='s')d=2;//v\n        if(dir[0]=='e')d=3;//>\n        if(dir[0]=='w')d=4;//<\n        \n        matrix mat(n,vector<int>(n,0));\n        fill(mat,x,y,d,n);\n\n        for(int i=0;i<n;i++){\n            for(int j=0;j<n;j++)\n                cout<<mat[i][j]<<\" \";\n            cout<<endl;\n        }\n\t}\n}\n// a code by srbcheema1\n"
  },
  {
    "path": "Competitive Programming Challenges/C:C++/HackerEarth:CodeForces/searchmat.cpp",
    "content": "// A program to search for an element in a 2D matrix in which each row and coloumn is sorted in ascending order\n#include <iostream>\nusing namespace std;\n\nint main(){\n  // Number of test cases\n  int test;\n  cin >> test;\n  while(test--){\n    // Number of rows and coloumns in the matrix\n    int a, b;\n    cin >> a >> b;\n    int ar[a][b];\n    // Array of arrays to store the values of 2D-Matrix\n    for (int i = 0; i < a * b; ++i) {\n      cin >> ar[i % a][i % b];\n    }\n    // Number to be searched for\n    int x;\n    cin >> x;\n    // Start from top right\n    int i = 0, j = b - 1;\n    while(1){\n      // Problem solved if element is found\n      if(ar[i][j] == x){\n\tcout << 1;\n\tbreak;\n      }\n      // Move down if element is less than key\n      else if(ar[i][j]<x){\n\ti++;\n      }\n      // Move left if element is greater than key\n      else if(ar[i][j]>x){\n\tj--;\n      }\n      // If element is not found return 0\n      // as we reach the bottom-left of the matrix\n      // The element was not present\n      if(i >= a || j <0){\n\tcout << 0 << endl;\n\tbreak;\n      }\n    }\n  }\n  return 0;\n}\n\n// Sample test case:\n// 1\n// 3 3\n// 2 6 8\n// 3 9 12\n// 4 10 13\n// 9\n"
  },
  {
    "path": "Competitive Programming Challenges/C:C++/Patterns/pattern1.cpp",
    "content": "#include <iostream>\nusing namespace std;\n\nint main(){\n\n\tint n;\n\tcin >> n;\n\n\tfor( int i = 0; i < n; i++ ){\n\t\tfor( int j = 0; j < n; j++ ){\n\t\t\tcout << \"*\";\n\t\t}\n\t\tcout << endl;\n\t}\n    return 0;\n\n}\n\n/*\n5\n\n*****\n*****\n*****\n*****\n*/\n"
  },
  {
    "path": "Competitive Programming Challenges/C:C++/Patterns/pattern2.cpp",
    "content": "#include <iostream>\nusing namespace std;\n\nint main(){\n\n\tint n;\n\tcin >> n;\n\n\tfor( int i = 0; i < n; i++ ){\n\t\tfor( int j = 0; j <= i; j++ ){\n\t\t\tcout << \"*\";\n\t\t}\n\t\tcout << endl;\n\t}\n\n    return 0;\n\n}\n\n/*\n5\n\n*\n**\n***\n****\n*****\n*/\n"
  },
  {
    "path": "Competitive Programming Challenges/C:C++/Patterns/pattern3.cpp",
    "content": "#include <iostream>\nusing namespace std;\n\nint main(){\n\n\tint n;\n\tcin >> n;\n\n\tfor( int i = n; i > 0; i-- ){\n\t\tfor( int j = 0; j < i; j++ ){\n\t\t\tcout << \"*\";\n\t\t}\n\t\tcout << endl;\n\t}\n\n    return 0;\n}\n\n/*\n5\n\n*****\n****\n***\n**\n*\n\n*/\n"
  },
  {
    "path": "Competitive Programming Challenges/C:C++/Patterns/pattern4.cpp",
    "content": "#include <iostream>\nusing namespace std;\n\nint main(){\n\n\tint n;\n\tcin >> n;\n\n\tfor( int i = 0; i < n; i++ ){\n\t\tfor( int j = 0; j <= i; j++ ){\n\t\t\tcout << \"*\";\n\t\t}\n\t\tcout << endl;\n\t}\n\n\tfor( int i = n-1; i > 0; i-- ){\n\t\tfor( int j = 0; j < i; j++ ){\n\t\t\tcout << \"*\";\n\t\t}\n\t\tcout << endl;\n\t}\n\n    return 0;\n\n}\n\n/*\n\n5\n\n*\n**\n***\n****\n*****\n****\n***\n**\n*\n\n*/\n"
  },
  {
    "path": "Competitive Programming Challenges/C:C++/Patterns/pattern6.cpp",
    "content": "#include <iostream>\nusing namespace std;\n\nint main(){\n\n\tint n;\n\tcin >> n;\n\n\tfor( int i = 1; i <= n; i++ ){\n\t\tfor( int j = 1; j <= i; j++ ){\n\t\t\tcout << i;\n\t\t}\n\t\tcout << endl;\n\t}\n\n    return 0;\n}\n\n/*\n\n5\n\n1\n22\n333\n4444\n55555\n\n*/\n"
  },
  {
    "path": "Competitive Programming Challenges/C:C++/Patterns/pattern7.cpp",
    "content": "#include <iostream>\nusing namespace std;\n\nint main(){\n\tint n;\n\tcin >> n;\n\n\tint count = 1;\n\tfor( int i = 0; i < n; i++ ){\n\t\tfor( int j = 0; j <= i; j++ ){\n\t\t\tcout << count << \" \";\n\t\t\tcount++;\n\t\t}\n\t\tcout << endl;\n\t}\n    return 0;\n\n}\n\n/*\n\n5\n\n1\n2 3\n4 5 6\n7 8 9 10\n11 12 13 14 15\n\n*/\n"
  },
  {
    "path": "Conversions/C:C++/binary2octal.c",
    "content": "// Binary number to octal number conversion\r\n#include<stdio.h>\r\n\r\n//Function that returns the last three digits\r\nint three_digits(int n)\r\n{\r\n    int r, d = 0, p=1;\r\n\r\n    for(int i=0; i<3; i++)\r\n    {\r\n        r = n%10;\r\n        d = d + r * p;\r\n        p = p * 10;\r\n        n = n / 10;\r\n    }\r\n    return d;\r\n}\r\n\r\nint main(void)\r\n{\r\n    int binary_num, d=0, base=1, remainder, td, res=0, ord=1;\r\n\r\n    printf(\"Enter the binary no: \");\r\n    scanf(\"%d\", &binary_num);\r\n\r\n    while(binary_num > 0)\r\n    {\r\n        if(binary_num > 111) //Checking if binary number is greater than three digits\r\n            td = three_digits(binary_num);\r\n\r\n        else td = binary_num;\r\n\r\n        binary_num = binary_num / 1000;\r\n\r\n        d = 0, base =1;\r\n\r\n        // Converting the last three digits to decimal\r\n        while(td > 0)\r\n        {\r\n            remainder = td % 10;\r\n            td = td / 10;\r\n            d = d + (base * remainder);\r\n            base = base * 2;\r\n        }\r\n\r\n        res = res + d * ord; // Calculating the octal value\r\n        ord = ord * 10;\r\n    }\r\n\r\n    printf(\"\\nOctal equivalent is: %d\", res);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Data Structures/C:C++/Applications/Evaluating Postfix Expression.c",
    "content": "#include <stdio.h>\r\n#include <string.h>\r\n#define MAX 200\r\n\r\nint isoperator(char c){\r\n\treturn (c=='*' || c=='/' || c=='+' || c=='-');\r\n}\r\n\r\nstruct stack\r\n{\r\n\tint top;\r\n\tdouble a[MAX];\r\n}s;\r\n\r\nvoid push(double c){\r\n\ts.a[++s.top]=c;\r\n}\r\n\r\ndouble pop(){\r\n\treturn s.a[s.top--];\r\n}\r\n\r\ndouble perform(double a, double b, char c){\r\n\tif (c=='*')\r\n\t{\r\n\t\treturn a*b;\r\n\t}\r\n\telse if (c=='+')\r\n\t{\r\n\t\treturn a+b;\r\n\t}\r\n\telse if (c=='/')\r\n\t{\r\n\t\treturn a/b;\r\n\t}\r\n\telse return a-b;\r\n}\r\n\r\nvoid post_infix(char a[],int l){\r\n\tint i;\r\n\tfor(i=0;i<l;i++){\r\n\t\tif (isoperator(a[i]))\r\n\t\t{\r\n\t\t\tdouble sec = pop(); \r\n\t\t\t//printf(\"%f\",sec);\r\n\t\t\tdouble fir = pop(); \r\n\t\t\t//printf(\"%f\",fir);\r\n\t\t\tdouble res = perform(fir,sec,a[i]); \r\n\t\t\t//printf(\"%f\",res);\r\n\t\t\tpush(res);\r\n\t\t}\r\n\t\telse{\r\n\t\t\tpush(a[i]-'0');\r\n\t\t}\r\n\t}\r\n}\r\n\r\nint main()\r\n{\r\n\tprintf(\"Enter a postfix expression :\\n\");\r\n\tchar post[100];\r\n\ts.top=-1;\r\n\tscanf(\"%s\",post);\r\n\tint n=strlen(post);\r\n\tpost_infix(post,n);\r\n\tprintf(\"%f\",s.a[s.top]);\r\n\treturn 0;\r\n}\r\n"
  },
  {
    "path": "Data Structures/C:C++/Applications/Infix to Postfix.c",
    "content": "#include<stdio.h>\r\n\r\nint j;\r\nstruct temp{\r\n\tchar a[200];\r\n\tint top;\r\n};\r\nstruct temp s;\r\n\r\nvoid push(char item){\r\n\ts.a[++s.top]=item;\r\n}\r\n\r\nint isempty(){\r\n\treturn s.top==-1;\r\n}\r\n\r\nchar pop(){\r\n\tif(!isempty())return s.a[s.top--];\r\n}\r\n\r\nint isoperator(char c){\r\n\tif(c=='*'||c=='/'|| c=='+'|| c=='-')return 1;\r\n\treturn 0;\r\n}\r\nint precedence(char c){\r\n\tif(c=='+' || c=='-')return 1;\r\n\telse if(c=='*' || c=='/')return 2;\r\n\telse if(c=='^')return 3;\r\n\treturn 0;\r\n}\r\nchar *infix_postfix(char *p){\r\n\tint i;\r\n\tj=0;\r\n\tchar *p1 = (char *)malloc(100*sizeof(char));\r\n\tfor(i=0;p[i]!='\\0';i++){\r\n\t\t//printf(\"%d\\n\",j);\r\n\t\tif(isalpha(p[i]) || isdigit(p[i])){\r\n\t\t\tp1[j++]=p[i];\r\n\t\t}\r\n\t\telse if(isoperator(p[i])){//printf(\"%c\\n\",p[i]);\r\n\t\t\twhile(!isempty() && /*s.a[s.top]!='(' &&*/ (precedence(p[i]) <= precedence(s.a[s.top]))){\r\n\t\t\t\tp1[j++] = s.a[s.top];\r\n\t\t\t\tpop();\r\n\t\t\t}\t\r\n\t\t\tpush(p[i]);\r\n\t\t}\r\n\t\telse if(p[i]=='(')push(p[i]);\r\n\t\telse if(p[i]==')'){\r\n\t\t\twhile(!isempty() && s.a[s.top]!='('){\r\n\t\t\t\tp1[j++]=s.a[s.top];\r\n\t\t\t\tpop();\r\n\t\t\t}\r\n\t\t\tpop();\r\n\t\t}\r\n\t}\r\n\twhile(!isempty()){\r\n\t\t//printf(\"%c \",s.a[s.top]);\r\n\t\tp1[j++]=s.a[s.top];\r\n\t\tpop();\r\n\t}\r\n\t//for(i=0;i<j;i++)printf(\"%c\",p[i]);\r\n\treturn p1;\r\n}\r\n\r\nint main(){\r\n\ts.top = -1;\r\n\tchar *p = (char *)malloc(100*sizeof(char));\r\n\twhile(1){\r\n\t\tprintf(\"Enter expression : \\n\");\r\n\t\tgets(p);\r\n\t\tchar *p1 = infix_postfix(p);\r\n\t\t//infix_postfix(exp);\r\n\t\tint i;\r\n\t\tfor(i=0;i<j;i++)printf(\"%c\",p1[i]);\r\n\t\tprintf(\"\\n\");\r\n\t}\r\n\treturn 0;\r\n}\r\n"
  },
  {
    "path": "Data Structures/C:C++/Applications/balance parenthesis.cpp",
    "content": "#include<iostream>\r\n#include<bits/stdc++.h>\r\n#include<string.h>\r\n#include<stack>\r\nusing namespace std;\r\n\r\nint main(){\r\n\tstring str;\r\n\tprintf(\"Enter a String\");\r\n\tcin>>str;\r\n\tint l = str.length();\r\n\tstack <char> s;\r\n\tfor(int i=0;i<l;i++){\r\n\t\tif(str[i]=='{' || str[i]=='[' || str[i]=='('){\r\n\t\t\ts.push(str[i]);\r\n\t\t}\r\n\t\telse if(str[i]=='}' || str[i]==']' || str[i]==')'){\r\n\t\t\tif(s.empty()){\r\n\t\t\t\tprintf(\"\\nNot Balanced\\n\");\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t\telse{\r\n\t\t\t\tif(str[i]=='}' && s.top()=='{'){\r\n\t\t\t\t\ts.pop();\r\n\t\t\t\t}\r\n\t\t\t\telse if(str[i]==']' && s.top()=='['){\r\n\t\t\t\t\ts.pop();\r\n\t\t\t\t}\r\n\t\t\t\telse if(str[i]=='(' && s.top()==')'){\r\n\t\t\t\t\ts.pop();\r\n\t\t\t\t}\r\n\t\t\t\telse{\r\n\t\t\t\t\tprintf(\"\\nNot Balanced\\n\");return false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif(s.empty()){\r\n\t\tprintf(\"\\nBalanced\\n\");\r\n\t}\r\n\telse{\r\n\t\tprintf(\"\\nNot Balanced\\n\");\r\n\t}\r\n}\r\n"
  },
  {
    "path": "Data Structures/C:C++/Applications/stack_and_its_implementation.c",
    "content": "//Auhor : VIVEK SHAH\r\n/*Performs Push, Pop, Peep and Displays elements of Stack*/\r\n\r\n\r\n#include<stdio.h>\r\n\r\nstruct stack{\r\n\tchar book_name[200][200];\r\n\tint book_id[20];\r\n\tint book_price[20];\r\n\tint top;\r\n};\r\n\r\nstruct stack *p;\r\nint size;\r\n\r\nvoid push(){\r\n\tif((p->top)==size-1){\r\n\t\tprintf(\"Overflow\");\r\n\t\treturn;\r\n\t}\r\n\tp->top = p->top +1;\r\n\t//printf(\"p->top = %d\",p->top);\r\n\tprintf(\"\\nEnter elements to be pushed : \");\r\n\tprintf(\"\\nEnter book name:\");\r\n\tscanf(\"%s\",p->book_name[p->top]);\r\n\tprintf(\"\\nEnter book id:\");\r\n\tscanf(\"%d\",&p->book_id[p->top]);\r\n\tprintf(\"\\nEnter book price:\");\r\n\tscanf(\"%d\",&p->book_price[p->top]);\r\n}\r\n\r\nvoid pop(){\r\n\tif(p->top==-1){\r\n\t\tprintf(\"Underflow\\n\");\r\n\t}\r\n\telse{\r\n\t\tp->top = p->top - 1;\r\n\t}\r\n}\r\n\r\nvoid peep(){\r\n\tint i= p->top;\r\n\t\tprintf(\"\\nBook Name : %s\",p->book_name[i]);\r\n\t\tprintf(\"\\nBook ID : %d\",p->book_id[i]);\r\n\t\tprintf(\"\\nBook Price : %d\",p->book_price[i]);\r\n\t\tprintf(\"\\n\");\r\n}\r\n\r\nvoid print(){\r\n\tint x = p->top;\r\n\tif(x==-1){\r\n\t\tprintf(\"Nothing to be displayed\\n\");\r\n\t}\r\n\tint i;\r\n\tfor(i=0;i<=x;i++){\r\n\t\tprintf(\"\\nBook Name : %s\",p->book_name[i]);\r\n\t\tprintf(\"\\nBook ID : %d\",p->book_id[i]);\r\n\t\tprintf(\"\\nBook Price : %d\",p->book_price[i]);\r\n\t\tprintf(\"\\n\");\r\n\t}\t\r\n}\r\n\r\nint main(){\r\n\tprintf(\"********************************\\t\\n\");\r\n\tprintf(\"Enter stack size : \");\r\n\tscanf(\"%d\",&size);\r\n\tp = (struct stack*)malloc(sizeof(struct stack));\r\n\tp->top = -1;\r\n\twhile(1){\r\n\t\tprintf(\"\\n1.Push\\n2.Pop\\n3.Peep\\n4.Display all elements\\n5.Exit\\n\");\r\n\t\tint ch;\r\n\t\tscanf(\"%d\",&ch);\r\n\t\tif(ch==1){\r\n\t\t\t//p->top = p->top + 1;\r\n\t\t\tpush();\r\n\t\t}\r\n\t\telse if(ch==2){\r\n\t\t\tpop();\r\n\t\t}\r\n\t\telse if(ch==3){\r\n\t\t\tpeep();\r\n\t\t}\r\n\t\telse if(ch==4){\r\n\t\t\tprint();\r\n\t\t}\r\n\t\telse{\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n}\r\n"
  },
  {
    "path": "Data Structures/C:C++/Graph/FloydWarshall.cpp",
    "content": "//Floyd Warshall Algorithm for All Pair Shortest Path Problem\n#include <bits/stdc++.h>\n#define FOR(i,n) for(size_t i=0;i<n;++i)\n#define endl '\\n'\n#define ll long long\n#define pb push_back\n#define mp make_pair\nusing namespace std;\n\nll gcd(ll a , ll b){return a==0?b:gcd(b%a,a);}\n\nint main(){\n\t//Floyd Warshall algorithm for all pair shortest path algorithm\n\t//NOTE - Vertices in this are from 0 to V-1. For 1 to V, modify the code!!\n\t//Complexity is O(V*V*V). Thi\n\tint e,v,a,b,weight, floyd_warshall [1000][1000],i,j,k,temp;\n\tcin>>v>>e;\n\tFOR(i,v){\n\t\tFOR(j,v)\n\t\t{\n\t\t\tif(i!=j)\n\t\t\t\tfloyd_warshall[i][j] = 99999999;\n\t\t\telse floyd_warshall[i][j] = 0;\n\t\t}\n\t}\n\n\tFOR(i,e){\n\t\tcin>>a>>b>>weight;\n\t\tfloyd_warshall[a][b] = weight;\n\t}\n\t\n\tFOR(k,v){\n\t\tFOR(i,v){\n\t\t\tFOR(j,v){\n\t\t\t\ttemp = floyd_warshall[i][k] + floyd_warshall[k][j];\n\t\t\t\tif(temp <  floyd_warshall[i][j])\n\t\t\t\t\tfloyd_warshall[i][j] = temp;\n\t\t\t}\n\t\t}\n\t}\n\tcout<<floyd_warshall[2][3];\n\treturn 0;\n}\n"
  },
  {
    "path": "Data Structures/C:C++/Graph/adjacency_list.hpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include \"../queue/queue.hpp\"\r\nusing namespace std;\r\n\r\ntemplate<typename T>\r\nclass graph_al {\r\nprivate:\r\n\tint count;\r\n\tmap< int, vector<T> > connections;\r\n\tvector<T> vertices;\r\n\tbool *visited;\r\npublic:\r\n\tgraph_al(T vertices[], int count) : count(count), visited(new bool[count]) {\r\n\t\tfor(int i=0;i<count;i++){\r\n\t\t\tthis->vertices.push_back(vertices[i]);\r\n\t\t}\r\n\t}\r\n\r\n\tvoid connect(int i, int j){\r\n\t\tconnections[i].push_back(j);\r\n\t}\r\n\r\n\tvoid connect_both_sides(int i, int j){\r\n\t\tconnect(i, j);\r\n\t\tconnect(j, i);\r\n\t}\r\n\r\n\tbool contains(vector<int> v, int n){\r\n\t\treturn find(v.begin(), v.end(), n) != v.end();\r\n\t}\r\n\r\n\tbool bfs(int i, int j){\r\n\t\tqueuemp<int> *q = new queuemp<int>();\r\n\t\t// else, try seraching though the connections\r\n\t\tfor(int w=0;w<this->count;w++) visited[w] = false;\r\n\t\tq->push(i);\r\n\t\tvisited[i] = true;\r\n\t\twhile(q->size){\r\n\t\t\tint v = q->pop();\r\n\t\t\tfor(int w = 0; w < connections[v].size();w++){\r\n\t\t\t\tif(!visited[connections[v][w]]){\r\n\t\t\t\t\tif(connections[v][w] == j) return true;\r\n\t\t\t\t\tq->push(connections[v][w]);\r\n\t\t\t\t\tvisited[connections[v][w]] = true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\r\n\tvoid dfs(int i){\r\n\t\tfor(int j=0;j<connections[i].size();j++){\r\n\t\t\tif(!visited[connections[i][j]]){\r\n\t\t\t\tvisited[connections[i][j]] = true;\r\n\t\t\t\tdfs(connections[i][j]);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t// check if the vertices at i and j are connected.\r\n\tbool connected(int i, int j){\r\n\t\treturn bfs(i, j);\r\n\t}\r\n\r\n\tvoid print_graph(){\r\n\t\tcout << \"Printing adjacency list of graph:\" << endl;\r\n\t\tfor(int i=0;i<count;i++){\r\n\t\t\tvector<int> v = connections[i];\r\n\t\t\tcout << \"vertices connected to \" << i << \":\" << endl;\r\n\t\t\tfor(int j=0;j<v.size();j++){\r\n\t\t\t\tcout << connections[i][j] << \" \";\r\n\t\t\t}\r\n\t\t\tcout << endl;\r\n\t\t}\r\n\t}\r\n\r\n\tint connected_components(){\r\n\t\tfor(int i=0;i<count;i++) visited[i] = false;\r\n\t\tint components = 0;\r\n\t\tfor(int i=0;i<count;i++){\r\n\t\t\tif(!visited[i]){\r\n\t\t\t\tvisited[i] = true;\r\n\t\t\t\tdfs(i);\r\n\t\t\t\tcomponents++;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn components;\r\n\t}\r\n};\r\n"
  },
  {
    "path": "Data Structures/C:C++/Graph/adjacency_matrix.hpp",
    "content": "#include <iostream>\r\n#include \"../queue/queue.hpp\"\r\nusing namespace std;\r\n\r\ntemplate<typename T>\r\nclass graph_am {\r\nprivate:\r\n\tint count;\r\n\tbool **connections;\r\n\tT *vertices;\r\n\tbool *visited;\r\npublic:\r\n\tgraph_am(T vertices[], int count) : count(count), vertices(new T[count]), visited(new bool[count]) {\r\n\t\tconnections = new bool*[count];\r\n\t\tfor(int i=0;i<count;i++){\r\n\t\t\tconnections[i] = new bool[count];\r\n\t\t}\r\n\t\tfor(int i=0;i<count;i++){\r\n\t\t\tthis->vertices[i] = vertices[i];\r\n\t\t\tfor(int j=0;j<count;j++){\r\n\t\t\t\tconnections[i][j] = (i==j);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tvoid connect(int i, int j){\r\n\t\tconnections[i][j] = true;\r\n\t}\r\n\r\n\tvoid connect_both_sides(int i, int j){\r\n\t\tconnect(i, j);\r\n\t\tconnect(j, i);\r\n\t}\r\n\r\n\tbool bfs(int i, int j){\r\n\t\tqueuemp<int> *q = new queuemp<int>();\r\n\t\tif(connections[i][j]) return true;\r\n\t\t// else, try seraching though the connections\r\n\t\tfor(int w=0;w<this->count;w++) visited[w] = false;\r\n\t\tq->push(i);\r\n\t\tvisited[i] = true;\r\n\t\twhile(q->size){\r\n\t\t\tint v = q->pop();\r\n\t\t\tfor(int w = 0; w < this->count; w++){\r\n\t\t\t\tif(!visited[w] && connections[v][w]){\r\n\t\t\t\t\tif(w == j) return true;\r\n\t\t\t\t\tq->push(w);\r\n\t\t\t\t\tvisited[w] = true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\r\n\tvoid dfs(int i){\r\n\t\tfor(int j=0;j<count;j++){\r\n\t\t\tif(!visited[j] && connections[i][j]){\r\n\t\t\t\tvisited[j] = true;\r\n\t\t\t\tdfs(j);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t// check if the vertices at i and j are connected.\r\n\tbool connected(int i, int j){\r\n\t\treturn bfs(i, j);\r\n\t}\r\n\r\n\tint connected_components(){\r\n\t\tfor(int i=0;i<count;i++) visited[i] = false;\r\n\t\tint components = 0;\r\n\t\tfor(int i=0;i<count;i++){\r\n\t\t\tif(!visited[i]){\r\n\t\t\t\tdfs(i);\r\n\t\t\t\tcomponents++;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn components;\r\n\t}\r\n};\r\n"
  },
  {
    "path": "Data Structures/C:C++/Graph/bfs_dfs/bfs/BFS.java",
    "content": "/**\n * Input file example:\n *\n *\n * 8\n * INF 1 1 INF INF INF INF INF\n * 1 INF INF 1 1 INF INF INF\n * 1 INF INF INF INF 1 1 INF\n * INF 1 INF INF INF INF INF INF\n * INF 1 INF INF INF INF INF 1\n * INF INF 1 INF INF INF INF INF\n * INF INF 1 INF INF INF INF INF\n * INF INF INF INF 1 INF INF INF\n * 1\n *\n * First line is number of elements in graph\n * Next n-lines is graph\n * Last line is begin point\n *\n * Output file:\n * 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8\n *\n */\n\nimport java.io.BufferedWriter;\nimport java.io.FileInputStream;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.util.*;\n\nclass BFS {\n\n    private static final String INPUT_FILE_PATH = \"input.txt\";\n\n    private static final String OUTPUT_FILE_PATH = \"output.txt\";\n\n    private static final int INF = Integer.MAX_VALUE / 2;\n\n    private static int begin;\n\n    public static void main(String[] args) {\n        int[][] matrix = readMatrixFromFile();\n        List<Integer> way = bfs(matrix);\n        printSolution(way);\n    }\n\n    private static int[][] readMatrixFromFile() {\n        int[][] matrix = null;\n\n        try (Scanner scanner = new Scanner(new FileInputStream(INPUT_FILE_PATH))) {\n            int matrixSize = Integer.parseInt(scanner.nextLine());\n            matrix = new int[matrixSize][matrixSize];\n\n            for (int row = 0; row < matrixSize; row++) {\n                String[] numbers = scanner.nextLine().split(\" \");\n                for (int col = 0; col < matrixSize; col++) {\n                    if (numbers[col].equals(\"INF\")) {\n                        matrix[row][col] = INF;\n                    } else {\n                        matrix[row][col] = Integer.parseInt(numbers[col]);\n                    }\n                }\n            }\n\n            begin = scanner.nextInt() - 1;\n        } catch (IOException e) {\n            e.printStackTrace();\n        }\n\n        return matrix;\n    }\n\n    private static List<Integer> bfs(int[][] matrix) {\n        boolean[] used = new boolean[matrix.length];\n        List<Integer> way = new ArrayList<>();\n        Queue<Integer> queue = new LinkedList<>();\n        queue.offer(begin);\n\n        while (!queue.isEmpty()) {\n            int v = queue.poll();\n            used[v] = true;\n            way.add(v + 1);\n\n            for (int nv = 0; nv < matrix.length; nv++) {\n                if (!used[nv] && matrix[v][nv] != INF) {\n                    queue.offer(nv);\n                }\n            }\n        }\n        return way;\n    }\n\n    private static void printSolution(List<Integer> way) {\n        try (BufferedWriter writer = new BufferedWriter(new FileWriter(OUTPUT_FILE_PATH))) {\n            writer.write(Integer.toString(way.get(0)));\n\n            for (int i = 1; i < way.size(); i++) {\n                writer.write(\" -> \" + way.get(i));\n            }\n        } catch (IOException e) {\n            e.printStackTrace();\n        }\n    }\n\n}"
  },
  {
    "path": "Data Structures/C:C++/Graph/bfs_dfs/bfs/bfs.Py",
    "content": "# Program to print BFS traversal from a given source\n# vertex. BFS(int s) traverses vertices reachable\n# from s.\nfrom collections import defaultdict\n \n# This class represents a directed graph using adjacency\n# list representation\nclass Graph:\n \n    # Constructor\n    def __init__(self):\n \n        # default dictionary to store graph\n        self.graph = defaultdict(list)\n \n    # function to add an edge to graph\n    def addEdge(self,u,v):\n        self.graph[u].append(v)\n \n    # Function to print a BFS of graph\n    def BFS(self, s):\n \n        # Mark all the vertices as not visited\n        visited = [False]*(len(self.graph))\n \n        # Create a queue for BFS\n        queue = []\n \n        # Mark the source node as visited and enqueue it\n        queue.append(s)\n        visited[s] = True\n \n        while queue:\n \n            # Dequeue a vertex from queue and print it\n            s = queue.pop(0)\n            print s,\n \n            # Get all adjacent vertices of the dequeued\n            # vertex s. If a adjacent has not been visited,\n            # then mark it visited and enqueue it\n            for i in self.graph[s]:\n                if visited[i] == False:\n                    queue.append(i)\n                    visited[i] = True\n \n \n# Driver code\n# Create a graph given in the above diagram\ng = Graph()\ng.addEdge(0, 1)\ng.addEdge(0, 2)\ng.addEdge(1, 2)\ng.addEdge(2, 0)\ng.addEdge(2, 3)\ng.addEdge(3, 3)\n \nprint \"Following is Breadth First Traversal (starting from vertex 2)\"\ng.BFS(2)\n# contributed by   drunk-maester\n"
  },
  {
    "path": "Data Structures/C:C++/Graph/bfs_dfs/ques/graph_connected_components.cpp",
    "content": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nvector <int> adj[12];\nbool visited[12];\n\nvoid dfs(int s) {\n    visited[s] = true;\n    for(int i = 0;i < adj[s].size();++i)    {\n     if(visited[adj[s][i]] == false)\n         dfs(adj[s][i]);\n    }\n}\n\nvoid initialize() {\n    for(int i = 0;i < 10;++i)\n         visited[i] = false;\n}\n\nint main() {\n    int nodes, edges, x, y, connectedComponents = 0;\n    cin >> nodes;                       \n    cin >> edges;                       \n    for(int i = 0;i < edges;++i) {\n     cin >> x >> y;     \n     adj[x].push_back(y);               \n     adj[y].push_back(x);               \n    }\n    initialize();                        \n    for(int i = 1;i <= nodes;++i) {\n     if(visited[i] == false)     {\n         dfs(i);\n         connectedComponents++;\n     }\n    }\n    cout << \"Number of connected components: \" << connectedComponents << endl;\n    return 0;\n}\n"
  },
  {
    "path": "Data Structures/C:C++/Graph/bfs_dfs/ques/tbbfs.cpp",
    "content": "//http://www.spoj.com/problems/TDBFS/\n#include<bits/stdc++.h>\n#define dout if(debugg) cout<<\" \"\nusing namespace std;\n\nint debugg = 1;\nclass Node{\n    public:\n    vector<int> adj;\n    int visited; \n\n    Node(){\n        clear();\n    }\n    void clear(){\n        visited = 0;\n        adj.clear();\n    }\n};\n\nvoid dfs_rec(vector<Node> &node,int a){\n    cout<<a<<\" \";\n    for(auto i : node[a].adj){\n        if(node[i].visited==0){\n            node[i].visited=1;\n            dfs_rec(node,i);\n        }\n    }\n}\nvoid dfs(vector<Node> &node,int a){\n    for(auto &i : node){\n        i.visited=0;\n    }\n\n    node[a].visited=1;\n    dfs_rec(node,a);\n\n    cout<<endl;\n}\n\nvoid bfs(vector<Node> &node,int a){\n    for(auto &i : node)\n        i.visited=0;\n\n    queue<int> q;\n    q.push(a);\n    node[a].visited=1;\n\n    while(!q.empty()){\n        int temp = q.front();\n        for(auto i : node[temp].adj){\n            if(node[i].visited==0){\n                node[i].visited=1;\n                q.push(i);\n            }\n        }\n        q.pop();\n        cout<<temp<<\" \";\n    }\n    cout<<endl;\n}\n\nint main(){\n    int t,temp;\n    cin>>t;\n    for(int x=1; x<=t; x++){\n        int n;\n        cin>>n;\n        vector<Node> node(n+1);\n\n        for(int i=1; i<=n; i++){//insert adj nodes\n            int m,faltu;\n            cin>>faltu>>m;\n            while(m--){\n                cin>>temp;\n                node[i].adj.push_back(temp); \n            }\n        }\n\n        cout<<\"graph \"<<x<<endl;\n        while(true){\n            int a,type;\n            cin>>a>>type;\n            if(a==0)break;\n\n            if(type)\n                bfs(node,a);\n            else\n                dfs(node,a);\n        }\n    }\n}\n"
  },
  {
    "path": "Data Structures/C:C++/Graph/dijakstra/Dijkstra.java",
    "content": "import java.io.BufferedWriter;\nimport java.io.FileInputStream;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.Scanner;\nimport java.util.Stack;\n\n/**\n * Input file example:\n *\n * 6\n * INF 7 9 INF INF 14\n * 7 INF 10 15 INF INF\n * 9 10 INF 11 INF 2\n * INF 15 11 INF 6 INF\n * INF INF INF 6 INF 9\n * 14 INF 2 INF 9 INF\n * 5 1\n *\n * First line is number of elements inn graph\n * Next n-lines is graph\n * Last line is begin and end point\n *\n * Output file:\n * Way from 5 to 1:\n * 5 -> 6 -> 3 -> 1\n * Length: 20\n *\n */\npublic class Dijkstra {\n\n    private static final String INPUT_FILE_PATH = \"input.txt\";\n\n    private static final String OUTPUT_FILE_PATH = \"output.txt\";\n\n    private static final int INF = Integer.MAX_VALUE / 2;\n\n    private static int begin;\n\n    private static int end;\n\n    public static void main(String[] args) {\n        int[][] matrix = readMatrixFromFile();\n        dijkstra(matrix);\n    }\n\n    private static int[][] readMatrixFromFile() {\n        int[][] matrix = null;\n\n        try (Scanner scanner = new Scanner(new FileInputStream(INPUT_FILE_PATH))) {\n            int matrixSize = Integer.parseInt(scanner.nextLine());\n            matrix = new int[matrixSize][matrixSize];\n\n            for (int row = 0; row < matrixSize; row++) {\n                String[] numbers = scanner.nextLine().split(\" \");\n                for (int col = 0; col < matrixSize; col++) {\n                    if (numbers[col].equals(\"INF\")) {\n                        matrix[row][col] = INF;\n                    } else {\n                        matrix[row][col] = Integer.parseInt(numbers[col]);\n                    }\n                }\n            }\n\n            begin = scanner.nextInt();\n            end = scanner.nextInt();\n        } catch (IOException e) {\n            e.printStackTrace();\n        }\n\n        return matrix;\n    }\n\n    private static void dijkstra(int[][] matrix) {\n        boolean[] used = new boolean[matrix.length];\n        int[] dist = new int[matrix.length];\n        int[] way = new int[matrix.length];\n\n        begin -= 1;\n        end -= 1;\n\n        Arrays.fill(dist, INF);\n        Arrays.fill(way, 0);\n        dist[begin] = 0;\n\n        while (true) {\n            int v = -1;\n            for (int nv = 0; nv < matrix.length; nv++) {\n                if (!used[nv] && (v == -1 || dist[nv] < dist[v])) {\n                    v = nv;\n                }\n            }\n\n            if (v == -1) {\n                break;\n            }\n\n            used[v] = true;\n\n            for (int nv = 0; nv < matrix.length; nv++) {\n                if (!used[nv] && matrix[v][nv] + dist[v] < dist[nv]) {\n                    dist[nv] = matrix[v][nv] + dist[v];\n                    way[nv] = v;\n                }\n            }\n        }\n\n        printSolution(way, dist);\n    }\n\n    private static void printSolution(int[] trip, int[] dist) {\n        Stack<Integer> stack = new Stack<>();\n        StringBuilder answer = new StringBuilder();\n        answer.append(String.format(\"Way from %d to %d:\\n\", begin + 1, end + 1));\n\n        int lastPoint = end;\n\n        while (lastPoint != begin) {\n            stack.push(lastPoint);\n            lastPoint = trip[lastPoint];\n        }\n\n        answer.append(begin + 1);\n        while (!stack.isEmpty()) {\n            answer.append(\" -> \").append(stack.pop() + 1);\n        }\n\n        answer.append(String.format(\"\\nLength: %d\\n\", dist[end]));\n\n        try (BufferedWriter writer = new BufferedWriter(new FileWriter(OUTPUT_FILE_PATH))) {\n            writer.write(answer.toString());\n        } catch (IOException e) {\n            e.printStackTrace();\n        }\n    }\n\n}\n"
  },
  {
    "path": "Data Structures/C:C++/Graph/dijakstra/dist_from_source.cpp",
    "content": "//https://www.codechef.com/problems/BUG2K17B\n#include<bits/stdc++.h>\n#define mp pair<int,int>\nusing namespace std;\n\nint debugg=0;\nclass Node{\n    public:\n    int dist;\n    vector<pair<int,int> > next;//first contains city index .. second contains distance\n    \n    void clear(){\n        dist=INT_MAX;\n        next.clear();\n    }\n} node[100002];\n\nstruct priority_fxn{\n    bool operator() (int a,int b){\n       return node[a].dist > node[b].dist; \n    }\n};\nvoid dijakstra(int source){\n    int n,d,temp;\n    priority_queue<int,vector<int>,priority_fxn> q;\n    \n    //init queue\n    node[source].dist=0;\n    q.push(source);\n    \n    while(!q.empty()){\n        temp=q.top();\n        for(auto elem : node[temp].next){\n            n=elem.first;\n            d=elem.second;\n            if(node[n].dist > node[temp].dist + d){\n                node[n].dist = node[temp].dist + d;\n                q.push(n);\n            }    \n        }\n        q.pop();\n    }\n}\n\nint main(){\n    int t,a,b,c,n,p;\n    cin>>t;\n    while(t--){\n        cin>>n>>p;\n        for(int i=1;i<=n;i++)\n            node[i].clear();\n        while(p--){\n            cin>>a>>b>>c;\n            node[a].next.push_back(mp(b,c));\n            node[b].next.push_back(mp(a,c));\n        }\n        dijakstra(1);\n        if(node[n].dist==INT_MAX)cout<<\"NONE\"<<endl;\n        else\n            cout<<node[n].dist<<endl;\n    }\n}\n"
  },
  {
    "path": "Data Structures/C:C++/Graph/dijakstra/dist_from_source_oops.cpp",
    "content": "//https://www.codechef.com/APRIL17/problems/CLIQUED\n//  only dijastra ques not complete\n#include<bits/stdc++.h>\n#define ulli long long int\n#define ui unsigned int\n\nusing namespace std;\n\nclass Road{\n    public:\n    int dist;\n    int left;\n    int right;\n    \n    Road(int l,int r,int d){\n        left=l;\n        right=r;\n        dist=d;\n    }\n};\n\nclass Node{\n    public:\n    ulli dist;\n    vector<Road> linked;\n    \n    Node(){\n        dist=LLONG_MAX;\n    }\n};\n\ntypedef pair<int,vector<Node>&> node_info;//stores node index and vector reference\n\nstruct priority_fxn{\n    bool operator() (node_info a,node_info b){\n        return a.second[a.first].dist > b.second[b.first].dist;\n    }\n};\n\n/*\n * set value of dist in each node relative to root\n * ct ==> vector of Nodes \n * root ==> source node\n */\nvoid dijakstra(vector<Node> &ct,int root){\n    priority_queue<node_info,vector<node_info>,priority_fxn> pq;//priority queue\n    int ind;//contains index\n    ulli temp_dist;\n    \n    ct[root].dist=0;\n    pq.push(node_info(root,ct));\n    \n    while(!pq.empty()){\n        root = pq.top().first;\n        pq.pop();\n        \n        for(auto elem : ct[root].linked){\n            ind = elem.left==root ? elem.right : elem.left;//select other than root\n            temp_dist = ct[root].dist + (ulli)elem.dist;//calculate temp_dist \n            \n            if(temp_dist < ct[ind].dist){\n                ct[ind].dist=temp_dist;\n                pq.push(node_info(ind,ct));\n            }\n        }\n    }\n}\n\nint main()\n{\n\tint t=1,n,r,s,a,b;\n\tulli d;\n\tcin>>t;\n\twhile(t--)\n\t{    \n\t    cin>>n>>r>>s;//num of cities  , roads , source\n\t    vector<Node> city(n+1,Node());\n\t    for(int i=1;i<=r;i++){\n\t        cin>>a>>b>>d;\n\t\t    city[a].linked.push_back(Road(a,b,d));\n\t\t    city[b].linked.push_back(Road(a,b,d));\n\t    }\n\t    \n\t    dijakstra(city,s);\n\t    \n\t    for(int i=1;i<=n;i++){\n\t        cout<<city[i].dist<<\" \";\n\t    }\n\t    cout<<endl;\n\t}\n\treturn 0;\n}\n"
  },
  {
    "path": "Data Structures/C:C++/Graph/dijakstra/ques/min_path.cpp",
    "content": "//https://www.codechef.com/SEPT17/problems/QGRID\n#include<bits/stdc++.h>\n#define ulli long long int\n#define dout if(debugg)cout<<\" \"\nusing namespace std;\ntypedef pair<ulli,ulli> mp; \ntypedef pair<mp,ulli> mpp;\n\nint debugg=0;\n\nclass Node{\n    public:\n    ulli dist;\n    ulli weight;\n    ulli parentx,parenty;\n    vector<pair<mp,ulli> > next;\n    void clear(){\n        weight=0;\n        dist=LONG_MAX;\n        next.clear();\n    }\n    Node(){\n        clear();\n    }\n    void setparent(ulli px,ulli py){\n        parentx=px;\n        parenty=py;\n    }\n} node[5][100009];\n \nstruct priority_fxn{\n    bool operator() (mp a,mp b){\n       return node[a.first][a.second].dist > node[b.first][b.second].dist; \n    }\n};\nvoid dijakstra(ulli sx,ulli sy,ulli ex,ulli ey,ulli update){\n    priority_queue<mp ,vector<mp >,priority_fxn> q;\n    queue<mp> dist_sett;//so that i can again set dist as intmax;\n    ulli d,n1,n2;\n    mp temp;\n\n    node[sx][sy].dist=0;\n    node[sx][sy].setparent(sx,sy);\n    q.push(mp(sx,sy));\n    dist_sett.push(mp(sx,sy));\n   \n    while(!q.empty()){\n        n1=q.top().first;\n        n2=q.top().second;\n        if(n1==ex && n2==ey)break;//reached the point\n        for(ulli i=0;i<node[n1][n2].next.size();i++){\n            temp=node[n1][n2].next[i].first;\n            d=node[n1][n2].next[i].second;\n            if(node[temp.first][temp.second].dist > node[n1][n2].dist + d){\n                node[temp.first][temp.second].dist = node[n1][n2].dist + d;\n                node[temp.first][temp.second].setparent(n1,n2);\n                dist_sett.push(temp);\n                q.push(temp);\n            }    \n        }\n        q.pop();\n    }//end while loop\n\n    //set dist back to INT_MAX\n    while(!dist_sett.empty()){\n        mp elem = dist_sett.front();\n        node[elem.first][elem.second].dist=LONG_MAX;\n        dist_sett.pop();\n        \n    }\n\n    int n1_;\n    while(n1!=sx || n2!=sy){\n       node[n1][n2].weight+=update;\n       n1_=node[n1][n2].parentx;\n       n2=node[n1][n2].parenty;\n       n1=n1_;\n       dout<<n1<<\" \"<<n2<<endl;\n    }\n    node[n1][n2].weight+=update;\n}\n \nint main(){\n    ulli m,n,q,d,type;\n    cin>>m>>n>>q;\n    for(ulli i=1;i<m;i++){\n        for(ulli j=1;j<=n;j++){\n            cin>>d;\n            node[i][j].next.push_back(mpp(mp(i+1,j),d));\n            node[i+1][j].next.push_back(mpp(mp(i,j),d));\n        }\n    }\n    for(ulli i=1;i<=m;i++){\n        for(ulli j=1;j<n;j++){\n            cin>>d;\n            node[i][j].next.push_back(mpp(mp(i,j+1),d));\n            node[i][j+1].next.push_back(mpp(mp(i,j),d));\n        }\n    }\n\n    ulli sx,sy,ex,ey,update;\n    while(q--){\n        cin>>type;\n        if(type==1){\n            cin>>sx>>sy>>ex>>ey>>update;\n            dijakstra(sx,sy,ex,ey,update);\n        }\n        else{\n            cin>>sx>>sy;\n            cout<<node[sx][sy].weight<<endl;\n        }\n    }\n}\n"
  },
  {
    "path": "Data Structures/C:C++/Graph/dijakstra/ques/qgrid_11.cpp",
    "content": "#include<bits/stdc++.h>\n#define ulli long long int\nusing namespace std;\ntypedef pair<ulli,ulli> mp; \ntypedef pair<mp,ulli> mpp;\n \n \nclass Node{\n    public:\n    ulli dist;\n    ulli weight;\n    ulli parentx,parenty;\n    vector<pair<mp,ulli> > next;\n    void clear(){\n        weight=0;\n        dist=LONG_MAX;\n        next.clear();\n    }\n    Node(){\n        clear();\n    }\n    void setparent(ulli px,ulli py){\n        parentx=px;\n        parenty=py;\n    }\n} node[5][100009];\n \nstruct priority_fxn{\n    bool operator() (mp a,mp b){\n       return node[a.first][a.second].dist > node[b.first][b.second].dist; \n    }\n};\n \nvoid update_weight(ulli l,ulli r,ulli update){\n    ulli a = min(r,l);\n    ulli b = max(r,l);\n    for(ulli i=a;i<=b;i++){\n        node[1][i].weight+=update;\n    } \n}\nvoid dijakstra(ulli sx,ulli sy,ulli ex,ulli ey,ulli update){\n    priority_queue<mp ,vector<mp >,priority_fxn> q;\n    queue<mp> dist_sett;//so that i can again set dist as intmax;\n    ulli d,n1,n2;\n    mp temp;\n \n    node[sx][sy].dist=0;\n    node[sx][sy].setparent(sx,sy);\n    q.push(mp(sx,sy));\n    dist_sett.push(mp(sx,sy));\n   \n    while(!q.empty()){\n        n1=q.top().first;\n        n2=q.top().second;\n        if(n1==ex && n2==ey)break;//reached the point\n        for(ulli i=0;i<node[n1][n2].next.size();i++){\n            temp=node[n1][n2].next[i].first;\n            d=node[n1][n2].next[i].second;\n            if(node[temp.first][temp.second].dist > node[n1][n2].dist + d){\n                node[temp.first][temp.second].dist = node[n1][n2].dist + d;\n                node[temp.first][temp.second].setparent(n1,n2);\n                dist_sett.push(temp);\n                q.push(temp);\n            }    \n        }\n        q.pop();\n    }//end while loop\n \n    //set dist back to INT_MAX\n    while(!dist_sett.empty()){\n        mp elem = dist_sett.front();\n        node[elem.first][elem.second].dist=LONG_MAX;\n        dist_sett.pop();\n    }\n \n    int n1_;\n    while(n1!=sx || n2!=sy){\n       node[n1][n2].weight+=update;\n       n1_=node[n1][n2].parentx;\n       n2=node[n1][n2].parenty;\n       n1=n1_;\n    }\n    node[n1][n2].weight+=update;\n}\n \nint main(){\n    ulli m,n,q,d,type;\n    cin>>m>>n>>q;\n    //make graph\n    for(ulli i=1;i<m;i++){\n        for(ulli j=1;j<=n;j++){\n            cin>>d;\n            node[i][j].next.push_back(mpp(mp(i+1,j),d));\n            node[i+1][j].next.push_back(mpp(mp(i,j),d));\n        }\n    }\n    for(ulli i=1;i<=m;i++){\n        for(ulli j=1;j<n;j++){\n            cin>>d;\n            node[i][j].next.push_back(mpp(mp(i,j+1),d));\n            node[i][j+1].next.push_back(mpp(mp(i,j),d));\n        }\n    }\n    //querries\n    ulli sx,sy,ex,ey,update;\n    while(q--){\n        cin>>type;\n        if(type==1){\n            cin>>sx>>sy>>ex>>ey>>update;\n            if(m==1)\n                update_weight(sy,ey,update);\n            else\n                dijakstra(sx,sy,ex,ey,update);\n        }\n        else{\n            cin>>sx>>sy;\n            cout<<node[sx][sy].weight<<endl;\n        }\n    }\n}\n \n"
  },
  {
    "path": "Data Structures/C:C++/Graph/shortest_paths.hpp",
    "content": "#include <vector>\r\n#include <queue>\r\n#include <utility> // for pair, make_pair etc\r\nusing namespace std;\r\n\r\n/*\r\n * Shortest path in Unweighted graph \r\n */\r\npair< vector<int>, vector<int> > unweighted_shortest_path(vector< vector<int> > graph, int s){\r\n\tvector<int> distance(graph.size(), -1);\r\n\tvector<int> path(graph.size());\r\n\tqueue<int> q;\r\n\tint v, w;\r\n\tq.push(s);\r\n\tdistance[s] = 0;\r\n\r\n\twhile(!q.empty()) {\r\n\t\tv = q.front();\r\n\t\tq.pop();\r\n\t    for(int k = 0; k < graph[v].size(); k++){\r\n\t    \tw = graph[v][k];\r\n\t    \tif(distance[w] == -1){\r\n\t    \t\tdistance[w] = distance[v] + 1;\r\n\t    \t\tpath[w] = v;\r\n\t    \t\tq.push(w);\r\n\t    \t}\r\n\t    }\r\n\t}\r\n\treturn make_pair(distance, path);\r\n}\r\n\r\n"
  },
  {
    "path": "Data Structures/C:C++/Graph/topological_sort.hpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <stack>\r\nusing namespace std;\r\n\r\n// util function\r\nvoid _ts(int v, bool visited[], stack<int> *st, vector< vector<int> > graph){\r\n\tvisited[v] = true;\r\n\r\n\t// go to all verices adjacent to this one\r\n\tfor(int w=0;w<graph[v].size();w++){\r\n\t\tint new_node = graph[v][w];\r\n\t\tif(!visited[new_node]) _ts(new_node, visited, st, graph);\r\n\t}\r\n\r\n\tst->push(v);\r\n}\r\n\r\nstack<int> topological_sort(vector< vector<int> > graph){\r\n\tint vertices = graph.size();\r\n\tstack<int> st;\r\n\t\r\n\t// mark all vertices as not visited\r\n\tbool *visited = new bool[vertices];\r\n\tfor(int i=0;i<vertices;i++) visited[i] = false;\r\n\r\n\t// call helper function to store topological sort\r\n\t// starting from all vertices one by one\r\n\tfor(int i=0;i<vertices;i++){\r\n\t\tif(!visited[i]) _ts(i, visited, &st, graph);\r\n\t}\r\n\r\n\tstack<int> st2;\r\n\tst2 = st;\r\n\r\n\tcout << \"Printing graph after topological sort: \" << endl;\r\n\twhile(!st.empty()){\r\n\t\tcout << st.top() << \" \";\r\n\t\tst.pop();\r\n\t}\r\n\tcout << endl;\r\n\r\n\treturn st2;\r\n}"
  },
  {
    "path": "Data Structures/C:C++/Graph/tree/binarySearchTree/bsTree.cpp",
    "content": "// This a program to demonstrate insert in a binary tree through recursion it also keeps count of all child of a node and also deletes nodes by recursion. It is basically a spoj question orderset. \n\n#include<bits/stdc++.h>\nusing namespace std;\n#define mp make_pair\n#define FOR(i,n) for(int i=0;i<n;i++)\n#define REP(i, a, b) for(int i=a;i<=b;i++)\n#define FORb(i, n) for(int i=n-1; i>=0; i--)\n#define lli long long int\n#define ulli unsigned long long int\n#define dout if(debug)cout<<\" \"\n\nint debug = 0;\n\nstruct tree{\n    int data;\n    int childcnt;\n    tree *left;\n    tree *right;\n};\n\ntree *root = NULL;\n\n//This is the \nvoid insert(tree *curr, tree *node){\n    int sum = 0;\n    if(node->data < curr->data){\n\n        if(curr -> left == NULL){\n            curr -> left = node;\n            sum++;\n            \n        }\n        \n        else{\n            insert(curr -> left, node);\n            sum += curr -> left -> childcnt + 1;   \n        }\n                \n        if(curr -> right != NULL){\n            sum += curr -> right -> childcnt + 1;\n        }\n        \n        curr -> childcnt = sum;\n        return;\n    }\n\n    else if(node->data > curr->data){\n\n        if(curr -> right == NULL){\n            curr -> right = node;\n            sum++;\n        }\n        \n        else{\n           insert(curr -> right, node);\n           sum += curr -> right -> childcnt + 1;\n        }\n                \n        if(curr -> left != NULL){\n            sum += curr -> left -> childcnt + 1;\n        }\n        \n        curr -> childcnt = sum;\n        return ;\n    }\n    \n}\n\ntree * minValueNode( tree *curr){\n    tree *current= curr;\n\n    while(current -> left != NULL)\n        current = current -> left;\n\n    return current;\n}\n\ntree* deleteNode(tree *root, int key){\n    root -> childcnt--;\n\n    if (root == NULL)\n        return root;\n\n    if (key  < root -> data){\n        root -> left = deleteNode(root -> left, key);\n    }\n\n    else if (key > root -> data){\n        root -> right = deleteNode( root -> right, key);\n    }\n\n    else{ \n\n        if (root -> left == NULL){\n            tree *temp = root -> right;\n            free(root);\n            return temp;\n        }\n        \n        else if (root -> right == NULL){\n            tree *temp = root -> left;\n            free(root);\n            return temp;\n        }\n         \n        tree *temp = minValueNode(root -> right);\n\n        root -> data =temp -> data;\n        root -> right = deleteNode(root -> right, temp -> data);\n    }\n    return root;\n}\n\nint Kpify(tree *curr, int pos, int target){\n    int count = pos + 1;\n\n    if( curr -> left != NULL){\n        count += curr -> left -> childcnt + 1;\n\n        if (target < count){\n            return Kpify(curr -> left, pos, target); \n        }\n    }\n    \n    if ( target == count )\n    {\n        return curr -> data;\n    }\n\n    else if (target > count )\n    {\n        return Kpify(curr -> right, count, target);\n    }\n}\n\nint main(){\n\n\tios_base::sync_with_stdio(false);\n\tcin.tie(NULL);\n    \n    int Q;\n    cin >> Q;\n\n    set<int> myset;\n\n    while (Q--){\n        char type;\n        cin >> type;\n        int num;\n        set<int> :: iterator its;\n\n        if (type == 'I'){\n            cin >> num;\n\n            if (myset.find(num) == myset.end())\n                myset.insert(num);\n\n            tree *n =new tree;\n            n->left = NULL;\n            n->right = NULL;\n            n->data = num;\n            n->childcnt = 0;    \n\n            if ( root == NULL){\n                root = n;\n            }\n            \n            else{\n                insert(root, n);\n            }\n        }\n        \n        if (type == 'D'){\n            cin >> num;\n            its = myset.find(num);\n\n            if (its != myset.end()){\n                myset.erase(num);\n                root = deleteNode(root, num);\n            }\n        }\n        \n        if (type == 'C'){\n            cin >> num;\n            its = myset.lower_bound(num);\n            cout << distance(myset.begin(), its) << endl;\n        }\n\n        if (type == 'K'){\n            cin >> num;\n\n            if (num <= myset.size() ){\n                cout << Kpify(root, 0, num) << endl; \n            }\n\n            else\n                cout << \"invalid\" << endl;\n        }\n    }\n\treturn 0;\n}\n"
  },
  {
    "path": "Data Structures/C:C++/Linked List/Circular_LL.c",
    "content": "/*\r\n\t***********************\r\n\tAuthor   : Vivek Shah\r\n\tQuestion : Circular LL\r\n\t***********************\r\n*/\r\n\r\n#include<stdio.h>\r\n#include<stdlib.h>\r\n#include <string.h>\r\n\r\nstruct node\r\n{\r\n\tchar name[100];\r\n\tint roll;\r\n\tfloat cgpa;\r\n\tstruct node* next;\r\n};\r\n\r\nstruct node* head;\r\nvoid display();\r\n\r\nstruct node* getNode(){\r\n\tchar name[100];\r\n\tint roll;\r\n\tfloat cgpa;\r\n\tprintf(\"Enter name to be inserted\\n\");\r\n\tprintf(\"Enter Roll to be inserted\\n\");\r\n\tprintf(\"Enter CGPA to be inserted\\n\");\r\n\tscanf(\"%s\",name);\r\n\tscanf(\"%d\",&roll);\r\n\tscanf(\"%f\",&cgpa);\r\n\tstruct node* temp = (struct node*)malloc(sizeof(struct node)) ;\r\n\tstrcpy(temp->name,name);\r\n\ttemp->roll=roll;\r\n\ttemp->cgpa=cgpa;\r\n\ttemp->next=NULL;\r\n\treturn temp;\r\n}\r\n\r\nint countNode(){\r\n\tstruct node* temp = head;\r\n\tint c = 0;\r\n\r\n\tif (head==NULL)\r\n\t{\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tdo{\r\n\t\tc++;\r\n\t\ttemp = temp->next;\r\n\t}while(temp!=head);\r\n\r\n\treturn c;\r\n}\r\n\r\n\r\nvoid insert_beg(){\r\n\tstruct node* temp = getNode();\r\n\ttemp->next = head;\r\n\r\n\tif (head==NULL)\r\n\t\ttemp->next = temp;\r\n\r\n\telse{\r\n\t\tstruct node* tm = head;\r\n\t\tdo{\r\n\t\t\ttm = tm->next;\r\n\t\t}while(tm->next!=head);\t\t\t//traverse through entire list\r\n\t\ttm->next = temp;\r\n\t}\r\n\thead = temp;\r\n\tdisplay();\r\n}\r\n\r\nvoid insert_btw(){\r\n\tprintf(\"Enter the Node no. after wise Node is to be inserted\\n\");\r\n\tint ch;\r\n\tscanf(\"%d\",&ch);\r\n\tint count = 0;\r\n\tif (ch<=0 || ch>countNode())\r\n\t{\r\n\t\tprintf(\"INVALID NODE No.\\n\");\r\n\t\treturn;\r\n\t}\r\n    else{\r\n\tstruct node* temp = getNode();\r\n\tstruct node* tempor = head;\r\n\r\n\tdo{\r\n\t\tcount++;\r\n\t\ttempor = tempor->next;\r\n\t}while(tempor->next!=head && ch!=count);\r\n\r\n\ttemp->next = tempor->next;\r\n\ttempor->next = temp;\r\n    display();\r\n    }\r\n}\r\n\r\nvoid insert_end(){\r\n\tstruct node* temp = getNode();\r\n\r\n\tif (head == NULL)\r\n\t{\r\n\t\ttemp->next = temp;\r\n\t\thead = temp;\r\n\t}\r\n\r\n\telse{\r\n\t\tstruct node* t = head;\r\n\t\tdo{\r\n\t\t\tt = t->next;\r\n\t\t}while(t->next!=head);\r\n\t\tt->next = temp;\r\n\t}\r\n\ttemp->next = head;\r\n\tdisplay();\r\n}\r\n\r\n\r\nvoid delete_beg(){\r\n\tif (head==NULL)\r\n\t{\r\n\t\tprintf(\"Nothing to Delete\\n\");\r\n\t}\r\n\telse{\r\n\t\tstruct node* temp = head;\r\n\t\tdo{\r\n\t\t\ttemp = temp->next;\r\n\r\n\t\t}while(temp->next!=head);\r\n\t\thead = head->next;\r\n\t\ttemp->next = head;\r\n\t}\r\n}\r\n\r\n\r\nvoid delete_btw(){\r\n\tprintf(\"Enter the Node no. to be deleted\\n\");\r\n\tint ch;\r\n\tscanf(\"%d\",&ch);\r\n\tint count = 0;\r\n\tif (ch<=0 || ch>countNode())\r\n\t{\r\n\t\tprintf(\"INVALID NODE No.\\n\");\r\n\t\treturn;\r\n\t}\r\n    else{\r\n    \tint c=0;\r\n\t\tstruct node* tempor = head;\r\n\t\tdo{\r\n\t\t\tc++;\r\n\t\t\ttempor = tempor->next;\r\n\t\t}while(tempor->next!=head && c==ch-1);\r\n\t\tif (tempor->next==head && ch==countNode())\r\n\t\t{\r\n\t\t\ttempor->next=head;\r\n\t\t}\r\n\t\telse{\r\n\t\t\ttempor->next = tempor->next->next;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid delete_end(){\r\n\tif (head==NULL)printf(\"Nothing to Delete\\n\");\r\n\telse if(head->next==NULL)head=NULL;\r\n\telse{\r\n\t\tstruct node* temp = head;\r\n\t\tdo{\r\n\t\t\ttemp = temp->next;\r\n\t\t}while(temp->next->next!=head);\r\n\t\ttemp->next = head;\r\n\t}\r\n}\r\n\r\n\r\nvoid search(){\r\n\tint sc;\r\n\tprintf(\"Enter a roll no to be Searched\\n\");\r\n\tscanf(\"%d\",&sc);\r\n\tif (head==NULL)\r\n\t{\r\n\t\tprintf(\"No data to search\\n\");\r\n\t\treturn;\r\n\t}\r\n\telse{\r\n\t\tstruct node* temp = head;\r\n\t\tint f=0;\r\n\t\tdo{\r\n\t\t\tif(temp->roll==sc){f=1;break;}\r\n\t\t\ttemp = temp->next;\r\n\t\t}while(temp!=head);\r\n\t\tif(f==0)printf(\"No data found\\n\");\r\n\t\telse{\r\n\t\t\tprintf(\"FOUND THE DATA\\n\");\r\n\t\t\tprintf(\"\\n%s\\n%d\\n%f\\n\",temp->name,temp->roll,temp->cgpa);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid display(){\r\n\tif(head==NULL){printf(\"Nothing to display\\n\");return;}\r\n\tstruct node* temp = head;\r\n\tdo{\r\n\t\tprintf(\"\\n************************************************\\n\");\r\n\t\tprintf(\"Name    : %s\\n\",temp->name);\r\n\t\tprintf(\"Roll No : %d\\n\",temp->roll);\r\n\t\tprintf(\"CGPA \t: %f\\n\",temp->cgpa);\r\n\t\ttemp = temp->next;\r\n\t}while(temp!=head);\r\n\tprintf(\"\\n************************************************\\n\\n\");\r\n}\r\n\r\nint main()\r\n{\r\n\thead = NULL;\r\n\tint i,ch;\r\n\twhile(1){\r\n        printf(\"1.Insert\\n2.Delete\\n3.Search\\n4.Display\\n\");\r\n        scanf(\"%d\",&i);\r\n        if (i==1)\r\n        {\r\n            printf(\"1.Insert Begin\\n2.Insert Between\\n3.Insert End\\n\");\r\n            scanf(\"%d\",&ch);\r\n            if (ch==1)\r\n                insert_beg();\r\n            else if (ch==2)\r\n            \tinsert_btw();\r\n            else if(ch==3)\r\n                insert_end();\r\n            else printf(\"Invalid Choice\\n\");\r\n\r\n        }\r\n        else if (i==2)\r\n        {\r\n            printf(\"1.Delete Begin\\n2.Delete Between\\n3.Delete End\\n\");\r\n            scanf(\"%d\",&ch);\r\n            if (ch==1)\r\n                delete_beg();\r\n            else if (ch==2)\r\n            \tdelete_btw();\r\n            else if(ch==3)\r\n                delete_end();\r\n            else printf(\"Invalid Choice\\n\");\r\n        }\r\n        else if(i==3){\r\n        \tsearch();\r\n        }\r\n\r\n        else if(i==4){\r\n            display();\r\n        }\r\n        else printf(\"Invalid Choice\\n\");\r\n\t}\r\n\treturn 0;\r\n}\r\n"
  },
  {
    "path": "Data Structures/C:C++/Linked List/Circular_ll.cpp",
    "content": "/*\n * C++ Program to Implement Circular Linked List \n */\n#include<iostream>\n#include<cstdio>\n#include<cstdlib>\nusing namespace std;\n/*\n * Node Declaration\n */\nstruct node\n{\n    int info;\n    struct node *next;\n}*last;\n \n/*\n * Class Declaration\n */\nclass circular_llist\n{\n    public:\n        void create_node(int value);\n        void add_begin(int value);\n        void add_after(int value, int position);\n        void delete_element(int value);\n        void search_element(int value);\n        void display_list();\n        void update();\n        void sort();\n        circular_llist()\n        {\n            last = NULL;           \n        }\n};\n \n/*\n * Main :contains menu \n */\nint main()\n{\n    int choice, element, position;\n    circular_llist cl;\n    while (1)\n    {\n        cout<<endl<<\"---------------------------\"<<endl;\n        cout<<endl<<\"Circular singly linked list\"<<endl;\n        cout<<endl<<\"---------------------------\"<<endl;     \n        cout<<\"1.Create Node\"<<endl;\n        cout<<\"2.Add at beginning\"<<endl;\n        cout<<\"3.Add after\"<<endl;\n        cout<<\"4.Delete\"<<endl;\n        cout<<\"5.Search\"<<endl;\n        cout<<\"6.Display\"<<endl;\n        cout<<\"7.Update\"<<endl;\n        cout<<\"8.Sort\"<<endl;\n        cout<<\"9.Quit\"<<endl;\n        cout<<\"Enter your choice : \";\n        cin>>choice;\n        switch(choice)\n        {\n        case 1:\n            cout<<\"Enter the element: \";\n            cin>>element;\n            cl.create_node(element);\n            cout<<endl;\n            break;\n        case 2:\n            cout<<\"Enter the element: \";\n            cin>>element;\n            cl.add_begin(element);\n            cout<<endl;\n            break;\n        case 3:\n            cout<<\"Enter the element: \";\n            cin>>element;\n            cout<<\"Insert element after position: \";\n            cin>>position;\n            cl.add_after(element, position);\n            cout<<endl;\n            break;\n        case 4:\n            if (last == NULL)\n            {\n                cout<<\"List is empty, nothing to delete\"<<endl;\n                break;\n            }\n            cout<<\"Enter the element for deletion: \";\n            cin>>element;\n            cl.delete_element(element);\n            cout<<endl;\n            break;\n        case 5:\n            if (last == NULL)\n            {\n                cout<<\"List Empty!! Can't search\"<<endl;\n                break;\n            }\n            cout<<\"Enter the element to be searched: \";\n            cin>>element;\n            cl.search_element(element);\n            cout<<endl;\n            break;\n        case 6:\n            cl.display_list();\n            break;\n        case 7:\n            cl.update();\n            break;\n        case 8:\n            cl.sort();\n            break;                      \n        case 9:\n            exit(1);\n            break;\n        default:\n            cout<<\"Wrong choice\"<<endl;\n        }\n    }\n    return 0;\n}\n \n/*\n * Create Circular Link List\n */\nvoid circular_llist::create_node(int value)\n{\n    struct node *temp;\n    temp = new(struct node);\n    temp->info = value;\n    if (last == NULL)\n    {\n        last = temp;\n        temp->next = last;   \n    }\n    else\n    {\n        temp->next = last->next; \n        last->next = temp;\n        last = temp;\n    }\n}\n \n/*\n * Insertion of element at beginning \n */\nvoid circular_llist::add_begin(int value)\n{\n    if (last == NULL)\n    {\n        cout<<\"First Create the list.\"<<endl;\n        return;\n    }\n    struct node *temp;\n    temp = new(struct node);\n    temp->info = value;\n    temp->next = last->next;\n    last->next = temp;\n}\n \n/*\n * Insertion of element at a particular place \n */\nvoid circular_llist::add_after(int value, int pos)\n{\n    if (last == NULL)\n    {\n        cout<<\"First Create the list.\"<<endl;\n        return;\n    }\n    struct node *temp, *s;\n    s = last->next;\n    for (int i = 0;i < pos-1;i++)\n    {\n        s = s->next;\n        if (s == last->next)\n        {\n            cout<<\"There are less than \";\n            cout<<pos<<\" in the list\"<<endl;\n            return;\n        }\n    }\n    temp = new(struct node);\n    temp->next = s->next;\n    temp->info = value;\n    s->next = temp;\n    /*Element inserted at the end*/\n    if (s == last)\n    { \n        last=temp;\n    }\n}\n \n/*\n * Deletion of element from the list\n */\nvoid circular_llist::delete_element(int value)\n{\n    struct node *temp, *s;\n    s = last->next;\n      /* If List has only one element*/\n    if (last->next == last && last->info == value)  \n    {\n        temp = last;\n        last = NULL;\n        free(temp);\n        return;\n    }\n    if (s->info == value)  /*First Element Deletion*/\n    {\n        temp = s;\n        last->next = s->next;\n        free(temp);\n        return;\n    }\n    while (s->next != last)\n    {\n        /*Deletion of Element in between*/\n        if (s->next->info == value)    \n        {\n            temp = s->next;\n            s->next = temp->next;\n            free(temp);\n            cout<<\"Element \"<<value;\n            cout<<\" deleted from the list\"<<endl;\n            return;\n        }\n        s = s->next;\n    }\n    /*Deletion of last element*/\n    if (s->next->info == value)    \n    {\n        temp = s->next;\n        s->next = last->next;\n        free(temp);\t\t\n        last = s;\n        return;\n    }\n    cout<<\"Element \"<<value<<\" not found in the list\"<<endl;\n}\n \n/*\n * Search element in the list \n */\nvoid circular_llist::search_element(int value)\n{\n    struct node *s;\n    int counter = 0;\n    s = last->next;\n    while (s != last)\n    {\n        counter++;\n        if (s->info == value)    \n        {\n            cout<<\"Element \"<<value; \n            cout<<\" found at position \"<<counter<<endl;\n            return;\n        }\n        s = s->next;\n    }\n    if (s->info == value)    \n    {\n        counter++;             \n        cout<<\"Element \"<<value;\n        cout<<\" found at position \"<<counter<<endl;\n        return;\n    }\n    cout<<\"Element \"<<value<<\" not found in the list\"<<endl;\n}\n \n/*\n * Display Circular Link List \n */\nvoid circular_llist::display_list()\n{\n    struct node *s;\n    if (last == NULL)\n    {\n        cout<<\"List is empty, nothing to display\"<<endl;\n        return;\n    }\n    s = last->next;\n    cout<<\"Circular Link List: \"<<endl;\n    while (s != last)\n    {\n        cout<<s->info<<\"->\";\n        s = s->next;\n    }\n    cout<<s->info<<endl;\n}\n \n/*\n * Update Circular Link List \n */\nvoid circular_llist::update()\n{\n    int value, pos, i;\n    if (last == NULL)\n    {\n        cout<<\"List is empty, nothing to update\"<<endl;\n        return;\n    }\n    cout<<\"Enter the node position to be updated: \";\n    cin>>pos;\n    cout<<\"Enter the new value: \";\n    cin>>value;\n    struct node *s;\n    s = last->next;\n    for (i = 0;i < pos - 1;i++)\n    {\n        if (s == last)\n        {\n            cout<<\"There are less than \"<<pos<<\" elements.\";\n            cout<<endl;\n            return;\n        }\n        s = s->next;\n    }\n    s->info = value;  \n    cout<<\"Node Updated\"<<endl;\n} \n \n/*\n * Sort Circular Link List \n */\nvoid circular_llist::sort()\n{\n    struct node *s, *ptr;\n    int temp;\n    if (last == NULL) \n    {\n        cout<<\"List is empty, nothing to sort\"<<endl;\n        return;\n    }\n    s = last->next;\n    while (s != last)\n    {\n        ptr = s->next;\n        while (ptr != last->next)\n        {\n            if (ptr != last->next)\n            {\n                if (s->info > ptr->info)\n                {\n                    temp = s->info;\n                    s->info = ptr->info;\n                    ptr->info = temp;\n                }\n            }\n            else\n            {\n                break;\n            }\n            ptr = ptr->next;    \n        }\n        s = s->next;         \n    }\n}\n"
  },
  {
    "path": "Data Structures/C:C++/Linked List/Doubly LL.c",
    "content": "/*\r\n\t***********************\r\n\tAuthor   : Vivek Shah\r\n\tQuestion : Doubly LL\r\n\t***********************\r\n*/\r\n\r\n#include<stdio.h>\r\n#include<stdlib.h>\r\n#include <string.h>\r\n\r\nstruct node\r\n{\r\n\tchar name[100];\r\n\tint roll;\r\n\tfloat cgpa;\r\n\tstruct node* next;\r\n\tstruct node* pre;\r\n};\r\n\r\nstruct node* head;\r\nvoid display();\r\n\r\nstruct node* getNode(){\r\n\tchar name[100];\r\n\tint roll;\r\n\tfloat cgpa;\r\n\tprintf(\"Enter name to be inserted\\n\");\r\n\tprintf(\"Enter Roll to be inserted\\n\");\r\n\tprintf(\"Enter CGPA to be inserted\\n\");\r\n\tscanf(\"%s\",name);\r\n\tscanf(\"%d\",&roll);\r\n\tscanf(\"%f\",&cgpa);\r\n\tstruct node* temp = (struct node*)malloc(sizeof(struct node)) ;\r\n\tstrcpy(temp->name,name);\r\n\ttemp->roll=roll;\r\n\ttemp->cgpa=cgpa;\r\n\ttemp->next = NULL;\r\n\ttemp->pre = NULL;\r\n\treturn temp;\r\n}\r\n\r\nint countNode(){\r\n\tstruct node* temp = head;\r\n\tint c = 0;\r\n\r\n\tif (head==NULL)\r\n\t{\r\n\t\treturn 0;\r\n\t}\r\n\r\n\twhile(temp!=NULL){\r\n\t\tc++;\r\n\t\ttemp = temp->next;\r\n\t}\r\n\r\n\treturn c;\r\n}\r\n\r\n\r\nvoid insert_beg(){\r\n\tstruct node* temp = getNode();\r\n\ttemp->next = head;\r\n\tif(head!=NULL){\r\n\t\thead->pre = temp;\r\n\t}\r\n\thead = temp;\r\n\tdisplay();\r\n}\r\n\r\nvoid insert_btw(){\r\n\tprintf(\"Enter the Node no. after wise Node is to be inserted\\n\");\r\n\tint ch;\r\n\tscanf(\"%d\",&ch);\r\n\tint count = 0;\r\n\tif (ch<=0 || ch>countNode())\r\n\t{\r\n\t\tprintf(\"INVALID NODE No.\\n\");\r\n\t\treturn;\r\n\t}\r\n    else{\r\n\t\tstruct node* temp = getNode();\r\n\t\tstruct node* t = head;\r\n\r\n\t\twhile(t!=NULL && t!=ch){\r\n\t\t\tt=t->next;\r\n\t\t}\t\r\n\t\ttemp->pre = t;\r\n\t\ttemp->next = t->next;\r\n\t\tt->pre->next = temp;\r\n\t\tif(t->next!=NULL)t->next->pre = temp;\r\n\t    display();\r\n    }\r\n}\r\n\r\nvoid insert_end(){\r\n\tstruct node* temp = getNode();\r\n\r\n\tif (head == NULL)\r\n\t\thead = temp;\r\n\r\n\telse{\r\n\t\tstruct node* t = head;\r\n\t\twhile(t->next!=NULL)\r\n\t\t\tt = t->next;\r\n\t\tt->next = temp;\r\n\t\ttemp->pre = NULL;\r\n\t}\r\n\tdisplay();\r\n}\r\n\r\n\r\nvoid delete_beg(){\r\n\tif (head==NULL)\r\n\t{\r\n\t\tprintf(\"Nothing to Delete\\n\");\r\n\t}\r\n\telse{\r\n\t\thead=head->next;\r\n\t\thead->pre=NULL;\r\n\t}\r\n}\r\n\r\n\r\nvoid delete_btw(){\r\n\tprintf(\"Enter the Node no. to be deleted\\n\");\r\n\tint ch;\r\n\tscanf(\"%d\",&ch);\r\n\tint count = 0;\r\n\tif (ch<=0 || ch>countNode())\r\n\t{\r\n\t\tprintf(\"INVALID NODE No.\\n\");\r\n\t\treturn;\r\n\t}\r\n    else{\r\n    \tif(ch==1){\r\n    \t\thead=NULL;\r\n    \t\treturn;\r\n\t\t}\r\n    \tint c=0;\r\n\t\tstruct node* t = head;\r\n\t\tint f=0;\r\n\t\twhile(t!=NULL){\r\n\t\t\tc++;\r\n\t\t\tif (c==ch)\r\n\t\t\t{\r\n\t\t\t\tf=1;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tt = t->next;\r\n\t\t}\r\n\t\tif (f==0)\r\n\t\t{\r\n\t\t\tprintf(\"NOT FOUND\\n\");\r\n\t\t}\r\n\t\telse if (t->next!=NULL)\r\n\t\t{\r\n\t\t\tt->pre->next = t->next;\r\n\t\t\tt->next->pre = t->pre;\r\n\t\t}\r\n\t\telse{\r\n\t\t\tt->pre->next = NULL;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid delete_end(){\r\n\tif (head==NULL)printf(\"Nothing to Delete\\n\");\r\n\telse if(head->next==NULL)head=NULL;\r\n\telse{\r\n\t\tstruct node* t = head;\r\n\t\twhile(t->next->next!=NULL)\r\n\t\t\tt = t->next;\r\n\t\tt->next=NULL;\r\n\t}\r\n}\r\n\r\n\r\nvoid search(){\r\n\tint sc;\r\n\tprintf(\"Enter a roll no to be Searched\\n\");\r\n\tscanf(\"%d\",&sc);\r\n\tif (head==NULL)\r\n\t{\r\n\t\tprintf(\"No data to search\\n\");\r\n\t\treturn;\r\n\t}\r\n\telse{\r\n\t\tstruct node* temp = head;\r\n\t\tint f=0;\r\n\t\twhile(temp!=NULL){\r\n\t\t\tif(temp->roll==sc){f=1;break;}\r\n\t\t\ttemp = temp->next;\r\n\t\t}\r\n\t\tif(f==0)printf(\"No data found\\n\");\r\n\t\telse{\r\n\t\t\tprintf(\"FOUND THE DATA\\n\");\r\n\t\t\tprintf(\"\\n%s\\n%d\\n%f\\n\",temp->name,temp->roll,temp->cgpa);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid display(){\r\n\tif(head==NULL){printf(\"Nothing to display\\n\");return;}\r\n\tstruct node* temp = head;\r\n\twhile(temp!=NULL){\r\n\t\tprintf(\"\\n************************************************\\n\");\r\n\t\tprintf(\"Name    : %s\\n\",temp->name);\r\n\t\tprintf(\"Roll No : %d\\n\",temp->roll);\r\n\t\tprintf(\"CGPA \t: %f\\n\",temp->cgpa);\r\n\t\ttemp = temp->next;\r\n\t}\r\n\tprintf(\"\\n************************************************\\n\\n\");\r\n}\r\n\r\nint main()\r\n{\r\n\thead = NULL;\r\n\tint i,ch;\r\n\twhile(1){\r\n        printf(\"1.Insert\\n2.Delete\\n3.Search\\n4.Display\\n\");\r\n        scanf(\"%d\",&i);\r\n        if (i==1)\r\n        {\r\n            printf(\"1.Insert Begin\\n2.Insert Between\\n3.Insert End\\n\");\r\n            scanf(\"%d\",&ch);\r\n            if (ch==1)\r\n                insert_beg();\r\n            else if (ch==2)\r\n            \tinsert_btw();\r\n            else if(ch==3)\r\n                insert_end();\r\n            else printf(\"Invalid Choice\\n\");\r\n\r\n        }\r\n        else if (i==2)\r\n        {\r\n            printf(\"1.Delete Begin\\n2.Delete Between\\n3.Delete End\\n\");\r\n            scanf(\"%d\",&ch);\r\n            if (ch==1)\r\n                delete_beg();\r\n            else if (ch==2)\r\n            \tdelete_btw();\r\n            else if(ch==3)\r\n                delete_end();\r\n            else printf(\"Invalid Choice\\n\");\r\n        }\r\n        else if(i==3){\r\n        \tsearch();\r\n        }\r\n\r\n        else if(i==4){\r\n            display();\r\n        }\r\n        else printf(\"Invalid Choice\\n\");\r\n\t}\r\n\treturn 0;\r\n}\r\n"
  },
  {
    "path": "Data Structures/C:C++/Linked List/Insertion_Deletion_SinglyLL.c",
    "content": "#include<stdio.h>\r\n\r\nstruct node{\r\n\tint item;\r\n\tstruct node* next;\r\n};\r\n\r\nstruct node* head;\r\n\r\nvoid Insert(){\r\n\tstruct node* temp;\r\n\ttemp = (struct node*)malloc(sizeof(struct node));\r\n\tint x;\r\n\tprintf(\"\\nEnter element to be inserted : \");\r\n\tscanf(\"%d\",&x);\r\n\tprintf(\"\\n\");\r\n\ttemp->item = x;\r\n\ttemp->next = NULL;\r\n\ttemp->next = head;\r\n\thead = temp;\r\n}\r\n\r\nvoid delete(){\r\n\tint x;\r\n\tif(head==NULL){\r\n\t\tprintf(\"Nothing to be deleted\\n\");\r\n\t\treturn;\r\n\t}\r\n\tprintf(\"Enter the position to be deleted : \");\r\n\tscanf(\"%d\",&x);printf(\"\\n\");\r\n\tif(head->next==NULL){//only a single element is present\r\n\t\thead=NULL;\r\n\t\treturn;\r\n\t}\t\r\n\tstruct node* temp;\r\n\ttemp = head;\r\n\tint i;\r\n\tfor(i=0;i<x-2;i++){\r\n\t\ttemp = temp->next;\r\n\t}//came to n-1th node\r\n\ttemp = temp->next->next;\r\n\ttemp->next = NULL;\r\n}\r\n\r\nvoid Print(){\r\n\tstruct node* temp = head;\r\n\twhile(temp!=NULL){\r\n\t\tprintf(\"%d  \",temp->item);\r\n\t\ttemp = temp->next;\r\n\t}\r\n\tprintf(\"\\n\");\r\n}\r\n\r\nint main(){\r\n\thead = NULL;\r\n\tprintf(\"Enter number of Items : \");\r\n\tint n;\r\n\tscanf(\"%d\",&n);\r\n\tprintf(\"\\n\");\r\n\tint i;\r\n\tfor(i=0;i<n;i++){\r\n\t\tint ch;\r\n\t\tprintf(\"What would you like to perform:\");\r\n\t\tscanf(\"%d\",&ch);\r\n\t\tif(ch==1){\r\n\t\t\t\tInsert();\r\n\t\t}\r\n\t\telse if(ch==3){\r\n\t\t\tPrint();\r\n\t\t}\r\n\t\telse if(ch==2){\r\n\t\t\tdelete();\r\n\t\t}\t\r\n\t}\r\n}\r\n"
  },
  {
    "path": "Data Structures/C:C++/Linked List/Queue using LinkedList.cpp",
    "content": "/******************************************\n*    AUTHOR         :   VIVEK SHAH        *\n*    INSTITUTION    :   NIT SURAT         *\n******************************************/\n\n/*Queue - Linked List implementation*/\n#include<stdio.h>\n#include<stdlib.h>\n\nstruct Node {\n\tint data;\n\tstruct Node* next;\n};\n// Two glboal variables to store address of front and rear nodes. \nstruct Node* front = NULL;\nstruct Node* rear = NULL;\n\n// To Enqueue an integer\nvoid Enqueue(int x) {\n\tstruct Node* temp = \n\t\t(struct Node*)malloc(sizeof(struct Node));\n\ttemp->data =x; \n\ttemp->next = NULL;\n\tif(front == NULL && rear == NULL){\n\t\tfront = rear = temp;\n\t\treturn;\n\t}\n\trear->next = temp;\n\trear = temp;\n}\n\n// To Dequeue an integer.\nvoid Dequeue() {\n\tstruct Node* temp = front;\n\tif(front == NULL) {\n\t\tprintf(\"Queue is Empty\\n\");\n\t\treturn;\n\t}\n\tif(front == rear) {\n\t\tfront = rear = NULL;\n\t}\n\telse {\n\t\tfront = front->next;\n\t}\n\tfree(temp);\n}\n\nint Front() {\n\tif(front == NULL) {\n\t\tprintf(\"Queue is empty\\n\");\n\t\treturn;\n\t}\n\treturn front->data;\n}\n\nvoid Print() {\n\tstruct Node* temp = front;\n\twhile(temp != NULL) {\n\t\tprintf(\"%d \",temp->data);\n\t\ttemp = temp->next;\n\t}\n\tprintf(\"\\n\");\n}\n\nint main(){\n\t/* Drive code to test the implementation. */\n\t// Printing elements in Queue after each Enqueue or Dequeue \n\tEnqueue(2); Print(); \n\tEnqueue(4); Print();\n\tEnqueue(6); Print();\n\tDequeue();  Print();\n\tEnqueue(8); Print();\n}\n"
  },
  {
    "path": "Data Structures/C:C++/Linked List/Queue_using_linkedlist.c",
    "content": "#include<stdio.h>\r\n\r\n//insert at beginning and remove at the end\r\n\r\nstruct node{\r\n\tint item;\r\n\tstruct node* next;\r\n};\r\n\r\nstruct node* head;\r\n\r\nvoid push(){//insert at the beginning\r\n\tstruct node* ptr = (struct node*)malloc(sizeof(struct node));\r\n\tprintf(\"Enter element to be inserted : \");\r\n\tscanf(\"%d\",&ptr->item);\r\n\tptr->next = NULL;\r\n\tif(head == NULL){\r\n\t\thead = ptr;\r\n\t\treturn;\r\n\t}\r\n\tptr->next = head;\r\n\thead = ptr; \t\r\n}\r\n\r\nvoid pop(){\r\n\tstruct node* temp = head;\r\n\tif(head == NULL){\r\n\t\tprintf(\"Nothing to Pop\\n\");\r\n\t\treturn;\r\n\t}\r\n\telse if(head->next == NULL){\r\n\t\thead = NULL;\r\n\t\treturn;\r\n\t}\r\n\twhile(temp->next->next!=NULL){\r\n\t\ttemp = temp->next;\r\n\t}\t\r\n\t\r\n\ttemp->next = NULL;\r\n}\r\n\r\nvoid display(){\r\n\tstruct node* temp = head;\r\n\tif(temp==NULL){\r\n\t\tprintf(\"Nothing to display\\n\");\r\n\t}\r\n\twhile(temp!=NULL){\r\n\t\tprintf(\"%d \",temp->item);\r\n\t\ttemp = temp->next;\r\n\t}\r\n\tprintf(\"\\n\");\r\n}\r\n\r\nint main(){\r\n\thead = NULL;\r\n\twhile(1){\r\n\t\tprintf(\"\\n1.Push\\n2.Pop\\n3.Display\\nAny other number to Exit\\n\\n\");\r\n\t\tprintf(\"Enter your choice : \");\r\n\t\tint ch;\r\n\t\tscanf(\"%d\",&ch);\r\n\t\tprintf(\"\\n\");\r\n\t\tif(ch==1){\r\n\t\t\tpush();\r\n\t\t}\r\n\t\telse if(ch==2){\r\n\t\t\tpop();\r\n\t\t}\r\n\t\telse if(ch==3){\r\n\t\t\tdisplay();\r\n\t\t}\r\n\t\telse{\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n}\r\n"
  },
  {
    "path": "Data Structures/C:C++/Linked List/Reverse_SinglyLL.c",
    "content": "#include<stdio.h>\r\n\r\nstruct node{\r\n\tint item;\r\n\tstruct node* next;\r\n};\r\n\r\nstruct node* head;\r\n\r\nstruct node* reverse(){\r\n\tstruct node* pre;\r\n\tstruct node* current;\r\n\tstruct node* post;\r\n\tcurrent = head;\r\n\tpre = NULL;\r\n\twhile(current!=NULL){\r\n\t\tpost = current->next;\r\n\t\tcurrent->next = pre;\r\n\t\tpre = current;\r\n\t\tcurrent = post; \t\t\r\n\t}\r\n\thead = pre;\r\n\treturn head;\r\n}\r\n\r\nvoid insert(int item,int n){\r\n\tstruct node* temp;\r\n\ttemp = (struct node*)malloc(sizeof(struct node));\r\n\ttemp->item = item;\r\n\ttemp->next = NULL;\r\n\tif(n==1){\r\n\t\ttemp->next = head;\r\n\t\thead = temp;\r\n\t\treturn;\r\n\t}\r\n\tstruct node* temp1;\r\n\ttemp1 = head;\r\n\tint i;\r\n\tfor( i = 0;i<n-2;i++){\r\n\t\ttemp1 = temp1->next;\r\n\t}\r\n\ttemp->next = temp1->next;\r\n\ttemp1->next = temp;\r\n}\r\n\r\nvoid print(){\r\n\tstruct node* temp = head;\r\n\twhile(temp!=NULL){\r\n\t\tprintf(\"%d \",temp->item);\r\n\t\ttemp = temp->next;\r\n\t}\r\n\tprintf(\"\\n\");\r\n}\r\n\r\nint main(){\r\n\thead = NULL;\r\n\tinsert(8,1);\r\n\tinsert(51,2);\r\n\tinsert(21,3);\r\n\tprint();\r\n\treverse();\r\n\tprint();\r\n}\r\n"
  },
  {
    "path": "Data Structures/C:C++/Linked List/all_operations_of_Doubly_ll.cpp",
    "content": "/*\n * C++ Program to Implement Doubly Linked List \n */\n#include<iostream>\n#include<cstdio>\n#include<cstdlib>\n/*\n * Node Declaration\n */\nusing namespace std;\nstruct node\n{\n    int info;\n    struct node *next;\n    struct node *prev;\n}*start;\n \n/*\n Class Declaration \n */\nclass double_llist\n{\n    public:\n        void create_list(int value);\n        void add_begin(int value);\n        void add_after(int value, int position);\n        void delete_element(int value);\n        void search_element(int value);\n        void display_dlist();\n        void count();\n        void reverse();\n        double_llist()\n        {\n            start = NULL;  \n        }\n};\n \n/*\n * Main: Conatins Menu\n */\nint main()\n{\n    int choice, element, position;\n    double_llist dl;\n    while (1)\n    {\n        cout<<endl<<\"----------------------------\"<<endl;\n        cout<<endl<<\"Operations on Doubly linked list\"<<endl;\n        cout<<endl<<\"----------------------------\"<<endl;         \n        cout<<\"1.Create Node\"<<endl;\n        cout<<\"2.Add at begining\"<<endl;\n        cout<<\"3.Add after position\"<<endl;\n        cout<<\"4.Delete\"<<endl;\n        cout<<\"5.Display\"<<endl;\n        cout<<\"6.Count\"<<endl;\n        cout<<\"7.Reverse\"<<endl;\n        cout<<\"8.Quit\"<<endl;\n        cout<<\"Enter your choice : \";\n        cin>>choice;\n        switch ( choice )\n        {\n        case 1:\n            cout<<\"Enter the element: \";\n            cin>>element;\n            dl.create_list(element);\n            cout<<endl;\n            break;\n        case 2:\n            cout<<\"Enter the element: \";\n            cin>>element;\n            dl.add_begin(element);\n            cout<<endl;\n            break;\n        case 3:\n            cout<<\"Enter the element: \";\n            cin>>element;\n            cout<<\"Insert Element after postion: \";\n            cin>>position;\n            dl.add_after(element, position);\n            cout<<endl;\n            break;\n        case 4:\n            if (start == NULL)\n            {                      \n                cout<<\"List empty,nothing to delete\"<<endl;   \n                break;\n            }\n            cout<<\"Enter the element for deletion: \";\n            cin>>element;\n            dl.delete_element(element);\n            cout<<endl;\n            break;\n        case 5:\n            dl.display_dlist();\n            cout<<endl;\n            break;\n        case 6:\n            dl.count();\n            break;    \n        case 7:\n            if (start == NULL)\n            {\n                cout<<\"List empty,nothing to reverse\"<<endl;\n                break;\n            }\n            dl.reverse();\n            cout<<endl;\n            break;\n        case 8:\n            exit(1);\n        default:\n            cout<<\"Wrong choice\"<<endl;\n        }\n    }\n    return 0;\n}\n \n/*\n * Create Double Link List\n */\nvoid double_llist::create_list(int value)\n{\n    struct node *s, *temp;\n    temp = new(struct node); \n    temp->info = value;\n    temp->next = NULL;\n    if (start == NULL)\n    {\n        temp->prev = NULL;\n        start = temp;\n    }\n    else\n    {\n        s = start;\n        while (s->next != NULL)\n            s = s->next;\n        s->next = temp;\n        temp->prev = s;\n    }\n}\n \n/*\n * Insertion at the beginning\n */\nvoid double_llist::add_begin(int value)\n{\n    if (start == NULL)\n    {\n        cout<<\"First Create the list.\"<<endl;\n        return;\n    }\n    struct node *temp;\n    temp = new(struct node);\n    temp->prev = NULL;\n    temp->info = value;\n    temp->next = start;\n    start->prev = temp;\n    start = temp;\n    cout<<\"Element Inserted\"<<endl;\n}\n \n/*\n * Insertion of element at a particular position\n */\nvoid double_llist::add_after(int value, int pos)\n{\n    if (start == NULL)\n    {\n        cout<<\"First Create the list.\"<<endl;\n        return;\n    }\n    struct node *tmp, *q;\n    int i;\n    q = start;\n    for (i = 0;i < pos - 1;i++)\n    {\n        q = q->next;\n        if (q == NULL)\n        {\n            cout<<\"There are less than \";\n            cout<<pos<<\" elements.\"<<endl;\n            return;\n        }\n    }\n    tmp = new(struct node);\n    tmp->info = value;\n    if (q->next == NULL)\n    {\n        q->next = tmp;\n        tmp->next = NULL;\n        tmp->prev = q;      \n    }\n    else\n    {\n        tmp->next = q->next;\n        tmp->next->prev = tmp;\n        q->next = tmp;\n        tmp->prev = q;\n    }\n    cout<<\"Element Inserted\"<<endl;\n}\n \n/*\n * Deletion of element from the list\n */\nvoid double_llist::delete_element(int value)\n{\n    struct node *tmp, *q;\n     /*first element deletion*/\n    if (start->info == value)\n    {\n        tmp = start;\n        start = start->next;  \n        start->prev = NULL;\n        cout<<\"Element Deleted\"<<endl;\n        free(tmp);\n        return;\n    }\n    q = start;\n    while (q->next->next != NULL)\n    {   \n        /*Element deleted in between*/\n        if (q->next->info == value)  \n        {\n            tmp = q->next;\n            q->next = tmp->next;\n            tmp->next->prev = q;\n            cout<<\"Element Deleted\"<<endl;\n            free(tmp);\n            return;\n        }\n        q = q->next;\n    }\n     /*last element deleted*/\n    if (q->next->info == value)    \n    { \t\n        tmp = q->next;\n        free(tmp);\n        q->next = NULL;\n        cout<<\"Element Deleted\"<<endl;\n        return;\n    }\n    cout<<\"Element \"<<value<<\" not found\"<<endl;\n}\n \n/*\n * Display elements of Doubly Link List\n */\nvoid double_llist::display_dlist()\n{\n    struct node *q;\n    if (start == NULL)\n    {\n        cout<<\"List empty,nothing to display\"<<endl;\n        return;\n    }\n    q = start;\n    cout<<\"The Doubly Link List is :\"<<endl;\n    while (q != NULL)\n    {\n        cout<<q->info<<\" <-> \";\n        q = q->next;\n    }\n    cout<<\"NULL\"<<endl;\n}\n \n/*\n * Number of elements in Doubly Link List\n */\nvoid double_llist::count()\n{ \t\n    struct node *q = start;\n    int cnt = 0;\n    while (q != NULL)\n    {\n        q = q->next;\n        cnt++;\n    }\n    cout<<\"Number of elements are: \"<<cnt<<endl;\n}\n \n/*\n * Reverse Doubly Link List\n */\nvoid double_llist::reverse()\n{\n    struct node *p1, *p2;\n    p1 = start;\n    p2 = p1->next;\n    p1->next = NULL;\n    p1->prev = p2;\n    while (p2 != NULL)\n    {\n        p2->prev = p2->next;\n        p2->next = p1;\n        p1 = p2;\n        p2 = p2->prev; \n    }\n    start = p1;\n    cout<<\"List Reversed\"<<endl; \n}\n"
  },
  {
    "path": "Data Structures/C:C++/Linked List/concatinate.c",
    "content": "#include<stdio.h>\r\n#include<conio.h>\r\n#include<malloc.h>\r\nstruct node\r\n{\r\n    int data;\r\n    struct node *next;\r\n};\r\nstruct node*p=NULL;\r\nstruct node*q=NULL;\r\nint j=0,k=0;\r\n\r\nstruct node* create(struct node*current)\r\n{\r\n  struct node *new_node;\r\n  new_node=(struct node *)malloc(sizeof(struct node));\r\n\r\n  printf(\"\\nEnter the data : \");\r\n  scanf(\"%d\",&new_node->data);\r\n  new_node->next=NULL;\r\n  j=j+1;\r\n\r\n  if(p==NULL)\r\n  {\r\n    p=new_node;\r\n    current=new_node;\r\n  }\r\n  else\r\n  {\r\n  current->next=new_node;\r\n  current=new_node;\r\n  }\r\n  return current;\r\n\r\n}\r\n\r\nstruct node* create2(struct node*current)\r\n{\r\n  struct node *new_node;\r\n  new_node=(struct node *)malloc(sizeof(struct node));\r\n\r\n  printf(\"\\nEnter the data : \");\r\n  scanf(\"%d\",&new_node->data);\r\n  new_node->next=NULL;\r\n  k=k+1;\r\n\r\n  if(q==NULL)\r\n  {\r\n    q=new_node;\r\n    current=new_node;\r\n  }\r\n  else\r\n  {\r\n    current->next=new_node;\r\n    current=new_node;\r\n  }\r\n  return current;\r\n\r\n}\r\n\r\n\r\nvoid display(struct node*start)\r\n{\r\n    struct node *new_node;\r\n    printf(\"\\nThe Linked List : \\n\");\r\n    new_node=start;\r\n    while(new_node!=NULL)\r\n    {\r\n        printf(\"%d--->\",new_node->data);\r\n        new_node=new_node->next;\r\n    }\r\n    printf(\"NULL\");\r\n}\r\nstruct node* sort(struct node*s)\r\n{\r\n    int i;\r\n    struct node *temp;\r\n    for(i=0;i<j+k;i++)\r\n    {\r\n        s=p;\r\n        while(s->next!=NULL)\r\n        {\r\n            if(s->data>s->next->data)\r\n            {\r\n                temp->data=s->data;\r\n                s->data=s->next->data;\r\n                s->next->data=temp->data;\r\n            }\r\n            s=s->next;\r\n        }\r\n\r\n   }\r\n\r\n}\r\nvoid con(struct node*p,struct node*q)\r\n{\r\n    while(p->next!=NULL)\r\n    p=p->next;\r\n    p->next=q;\r\n}\r\n\r\n\r\nmain()\r\n{\r\n    int n;\r\n    struct node* current1,*current2;\r\n    current1=NULL;\r\n    current2=NULL;\r\n    while(1)\r\n    {\r\n        printf(\"1.insert list 1\\n2.insert list 2\\n3.display list 1\\n4.display list 2\\n5.sort\\n6.display final list\\n7.concatinate\\n8.exit \\nenter choice\\n\");\r\n        scanf(\"%d\",&n);\r\n\r\n    switch(n){\r\n    case 1: current1=create(current1);\r\n            //p=current;\r\n            break;\r\n    case 2: current2=create2(current2);\r\n            //q=current;\r\n            break;\r\n    case 3: display(p);\r\n            break;\r\n    case 4:display(q);\r\n            break;\r\n    case 5:sort(p);\r\n            break;\r\n    case 6: display(p);\r\n            break;\r\n    case 7:con(p,q);\r\n            break;\r\n    case 8: return;\r\n    }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Data Structures/C:C++/Linked List/doubly circular.c",
    "content": "/*\r\n\t***********************\r\n\tAuthor   : Vivek Shah\r\n\tQuestion : Doubly Circular LL\r\n\t***********************\r\n*/\r\n\r\n#include<stdio.h>\r\n#include<stdlib.h>\r\n#include <string.h>\r\n\r\nstruct node\r\n{\r\n\tchar name[100];\r\n\tint roll;\r\n\tfloat cgpa;\r\n\tstruct node* next;\r\n\tstruct node* pre;\r\n};\r\n\r\nstruct node* head;\r\nstruct node* last;\r\nvoid display();\r\n\r\nstruct node* getNode(){\r\n\tchar name[100];\r\n\tint roll;\r\n\tfloat cgpa;\r\n\tprintf(\"Enter name to be inserted\\n\");\r\n\tprintf(\"Enter Roll to be inserted\\n\");\r\n\tprintf(\"Enter CGPA to be inserted\\n\");\r\n\tscanf(\"%s\",name);\r\n\tscanf(\"%d\",&roll);\r\n\tscanf(\"%f\",&cgpa);\r\n\tstruct node* temp = (struct node*)malloc(sizeof(struct node)) ;\r\n\tstrcpy(temp->name,name);\r\n\ttemp->roll=roll;\r\n\ttemp->cgpa=cgpa;\r\n\ttemp->next = NULL;\r\n\ttemp->pre = NULL;\r\n\treturn temp;\r\n}\r\n\r\nint countNode(){\r\n\tstruct node* temp = head;\r\n\tint c = 0;\r\n\r\n\tif (head==NULL)\r\n\t{\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tdo{\r\n\t\tc++;\r\n\t\ttemp = temp->next;\r\n\t}while(temp!=head);\r\n\r\n\treturn c;\r\n}\r\n\r\n\r\nvoid insert_beg(){\r\n\tstruct node* temp = getNode();\r\n\tif (head==NULL)\r\n\t{\r\n\t\ttemp->next=temp;\r\n\t\ttemp->pre=temp;\r\n\t}\r\n\telse{\r\n\t\ttemp->next=head;\r\n\t\thead->pre = temp;\r\n\t\ttemp->pre = last;\r\n\t\tlast->next=temp;\r\n\t}\r\n\thead = temp;\r\n\tlast = head->pre;\r\n\t/*struct node* temp = getNode();\r\n\ttemp->next = head;\r\n    struct node* last = head->pre; \r\n    struct node* new_node = getNode();\r\n    new_node->next = head;\r\n    new_node->pre = last;\r\n    last->next = head->pre = new_node;\r\n    head = new_node;*/\r\n    \r\n\tdisplay();\r\n}\r\n\r\nvoid insert_btw(){//problem hai...\r\n\tprintf(\"Enter the Node no. after wise Node is to be inserted\\n\");\r\n\tint ch;\r\n\tscanf(\"%d\",&ch);\r\n\tprintf(\"The total count of nodes is %d\",countNode());\r\n\tint count = 0;\r\n\tif (ch<=0 || ch>countNode())\r\n\t{\r\n\t\tprintf(\"INVALID NODE No.\\n\");\r\n\t\treturn;\r\n\t}\r\n\t\r\n\tstruct node* temp = getNode();\r\n\tstruct node* t = head;\r\n\r\n\tdo{\r\n\t\tcount++;\r\n\t\tt=t->next;\r\n\t}while(t!=head || count!=ch-1);\r\n/*\r\n\tprintf(\"The value of count is %d\",count);\r\n\tprintf(\"\\n************************************************\\n\");\r\n\tprintf(\"Name    : %s\\n\",t->name);\r\n\tprintf(\"Roll No : %d\\n\",t->roll);\r\n\tprintf(\"CGPA \t: %f\\n\",t->cgpa);\r\n*/\r\n\ttemp->pre = t;\r\n\ttemp->next = t->next;\r\n\tif(t==last){\r\n\t\ttemp->next=head;\r\n\t\tlast=temp;\r\n\t}\r\n\telse t->next->pre = temp;\r\n\tt->next = temp;\r\n    display();\r\n}\r\n\r\nvoid insert_end(){\r\n\tstruct node* temp = getNode();\r\n\r\n\tif (head == NULL){\r\n\t\ttemp->next=temp;\r\n\t\ttemp->pre=temp;\r\n\t\thead = temp;\r\n\t\tlast = head->pre;\r\n\t}\r\n\r\n\telse{\r\n\t\ttemp->next=last->next;\r\n\t\ttemp->pre = last;\r\n\t\tlast->next = temp;\r\n\t\tlast = temp;\r\n\t\tlast->next = head;\r\n\t}\r\n\tdisplay();\r\n}\r\n\r\n\r\nvoid delete_beg(){\r\n\tif (head==NULL)\r\n\t{\r\n\t\tprintf(\"Nothing to Delete\\n\");\r\n\t}\r\n\telse if (head==last)\r\n\t{\r\n\t\thead=NULL;\r\n\t\tlast=NULL;\r\n\t}\r\n\telse{\r\n\t\thead=head->next;\r\n\t\thead->pre=NULL;\r\n\t\tlast->next=head;\r\n\t}\r\n\tdisplay();\r\n}\r\n\r\n\r\nvoid delete_btw(){\r\n\tprintf(\"Enter the Node no. to be deleted\\n\");\r\n\tint ch;\r\n\tscanf(\"%d\",&ch);\r\n\tint count = 0;\r\n\tif (ch<=0 || ch>countNode())\r\n\t{\r\n\t\tprintf(\"INVALID NODE No.\\n\");\r\n\t\treturn;\r\n\t}\r\n    else{\r\n    \tif(ch==1){\r\n    \t\thead=NULL;\r\n    \t\tlast=NULL;\r\n    \t\treturn;\r\n\t\t}\r\n    \tint c=0;\r\n\t\tstruct node* t = head;\r\n\t\tint f=0;\r\n\t\twhile(t!=NULL){\r\n\t\t\tc++;\r\n\t\t\tif (c==ch)\r\n\t\t\t{\r\n\t\t\t\tf=1;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tt = t->next;\r\n\t\t}\r\n\t\tif (f==0)\r\n\t\t{\r\n\t\t\tprintf(\"NOT FOUND\\n\");\r\n\t\t}\r\n\t\tif (t==last)\r\n\t\t{\r\n\t\t\tlast = last->pre;\r\n\t\t\tlast->next=head;\r\n\t\t}\r\n\t\telse \r\n\t\t{\r\n\t\t\tt->pre->next = t->next;\r\n\t\t\tt->next->pre = t->pre;\r\n\t\t}\r\n\t}\r\n\tdisplay();\r\n}\r\n\r\nvoid delete_end(){\r\n\tif (last==NULL)printf(\"Nothing to Delete\\n\");\r\n\telse if(head==last){\r\n\t\thead=NULL;\r\n\t\tlast=NULL;\r\n\t}\r\n\telse{\r\n\t\tlast = last->pre;\r\n\t\tlast->next = head;\r\n\t}\r\n\tdisplay();\r\n}\r\n\r\n\r\nvoid search(){\r\n\tint sc;\r\n\tprintf(\"Enter a roll no to be Searched\\n\");\r\n\tscanf(\"%d\",&sc);\r\n\tif (head==NULL)\r\n\t{\r\n\t\tprintf(\"No data to search\\n\");\r\n\t\treturn;\r\n\t}\r\n\telse{\r\n\t\tstruct node* temp = head;\r\n\t\tint f=0;\r\n\t\tdo{\r\n\t\t\tif(temp->roll==sc){f=1;break;}\r\n\t\t\ttemp = temp->next;\r\n\t\t}while(temp!=head);\r\n\t\tif(f==0)printf(\"No data found\\n\");\r\n\t\telse{\r\n\t\t\tprintf(\"FOUND THE DATA\\n\");\r\n\t\t\tprintf(\"\\n%s\\n%d\\n%f\\n\",temp->name,temp->roll,temp->cgpa);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid display(){\r\n\tif(head==NULL){printf(\"Nothing to display\\n\");return;}\r\n\tstruct node* temp = head;\r\n\tdo{\r\n\t\tprintf(\"\\n************************************************\\n\");\r\n\t\tprintf(\"Name    : %s\\n\",temp->name);\r\n\t\tprintf(\"Roll No : %d\\n\",temp->roll);\r\n\t\tprintf(\"CGPA \t: %f\\n\",temp->cgpa);\r\n\t\ttemp = temp->next;\r\n\t}while(temp!=head);\r\n\tprintf(\"\\n************************************************\\n\\n\");\r\n}\r\n\r\nint main()\r\n{\r\n\thead = NULL;\r\n\tlast = NULL;\r\n\tint i,ch;\r\n\twhile(1){\r\n        printf(\"1.Insert\\n2.Delete\\n3.Search\\n4.Display\\n\");\r\n        scanf(\"%d\",&i);\r\n        if (i==1)\r\n        {\r\n            printf(\"1.Insert Begin\\n2.Insert Between\\n3.Insert End\\n\");\r\n            scanf(\"%d\",&ch);\r\n            if (ch==1)\r\n                insert_beg();\r\n            else if (ch==2)\r\n            \tinsert_btw();\r\n            else if(ch==3)\r\n                insert_end();\r\n            else printf(\"Invalid Choice\\n\");\r\n\r\n        }\r\n        else if (i==2)\r\n        {\r\n            printf(\"1.Delete Begin\\n2.Delete Between\\n3.Delete End\\n\");\r\n            scanf(\"%d\",&ch);\r\n            if (ch==1)\r\n                delete_beg();\r\n            else if (ch==2)\r\n            \tdelete_btw();\r\n            else if(ch==3)\r\n                delete_end();\r\n            else printf(\"Invalid Choice\\n\");\r\n        }\r\n        else if(i==3){\r\n        \tsearch();\r\n        }\r\n\r\n        else if(i==4){\r\n            display();\r\n        }\r\n        else printf(\"Invalid Choice\\n\");\r\n\t}\r\n\treturn 0;\r\n}\r\n"
  },
  {
    "path": "Data Structures/C:C++/Linked List/doubly linked list.c",
    "content": "#include<stdio.h>\r\n\r\nstruct node{\r\n\tint item;\r\n\tstruct node* pre;\r\n\tstruct node* next;\r\n};\r\n\r\nstruct node *head, *ptr;\r\n\r\nstruct node* getNode(){\r\n\tptr = (struct node*)malloc(sizeof(struct node));\r\n\tprintf(\"Enter element to be inserted in Doubly Linked List : \");\r\n\tint x;\r\n\tscanf(\"%d\",&x);\r\n\tptr->item = x;\r\n\tptr->pre = NULL;\r\n\tptr->next = NULL;\r\n\treturn ptr;\r\n}\r\n\r\nvoid insert(){\r\n\tstruct node* ptr = getNode();\r\n\tptr->next = head;\r\n\tif(head == NULL){\r\n\t\thead = ptr;\r\n\t\treturn;\r\n\t}\t\r\n\thead->pre = ptr;\r\n\thead = ptr;\r\n}\r\n\r\nvoid insert1(){\r\n\tstruct node* ptr = getNode();\r\n\tif(head==NULL){\r\n\t\thead = ptr;\r\n\t\treturn;\r\n\t}\r\n\tstruct node* temp;\r\n\ttemp=head;\r\n\twhile(temp->next!=NULL){\r\n\t\ttemp = temp->next;\r\n\t}//temp is last element\r\n\t\r\n\ttemp->next = ptr;\r\n\tptr->pre = temp;\r\n\tptr->next = NULL;\t\t\r\n}\r\n\r\n\r\nvoid print(){\r\n\tstruct node* temp;\r\n\ttemp = head;\r\n\twhile(temp!=NULL){\r\n\t\tprintf(\"%d \",temp->item);\r\n\t\ttemp = temp->next;\r\n\t}\r\n}\r\n\r\nint main(){\r\n\thead = NULL;\r\n\tinsert();//insert inserts at beginning\r\n\tinsert();\r\n\tinsert1();//insert1 inserts at end\r\n\tinsert1();\r\n\tprint();\r\n}\r\n"
  },
  {
    "path": "Data Structures/C:C++/Linked List/linked_list.c",
    "content": "#include <stdio.h>\r\n#include<stdlib.h>\r\n#include<string.h>\r\nstruct node\r\n{\r\n\tint roll;\r\n\tchar name[100];\r\n\tfloat cgpa;\r\n\tstruct node* next;\r\n};\r\n\r\nstruct node* head;\r\n\r\nstruct node* getNode(int roll1,char name1[], float cgpa1){\r\n\tstruct node* p = (struct node*)malloc(sizeof(struct node));\r\n\tp->roll=roll1;\r\n\tstrcpy(p->name,name1);\r\n\tp->cgpa=cgpa1;\r\n\treturn p;\r\n}\r\n\r\nstruct node* getLastNode(){\r\n\tstruct node* temp = head;\r\n\twhile(temp->next!=NULL)\r\n\t\ttemp=temp->next;\r\n\treturn temp;\r\n}\r\n\r\nint countNode(){\r\n\tstruct node* temp = head;\r\n\tint count=0;\r\n\twhile(temp!=NULL){\r\n\t\tcount++;\r\n\t\ttemp = temp->next;\r\n\t}\r\n\treturn count;\r\n}\r\n\r\nvoid ins_beg(int roll,char name[], float cgpa){\r\n\tstruct node* p =getNode(roll,name,cgpa);\r\n\tp->next = head;\r\n\thead = p;\r\n}\r\n\r\nvoid ins_btw(int roll,char name[], float cgpa,int pos){\r\n\tif (pos>0 && pos<=countNode())\r\n\t{\r\n\t\tstruct node* temp = head;\r\n\t\tint count=0;\r\n\t\twhile(count!=(pos-1)){\r\n\t\t\ttemp = temp->next;\r\n\t\t}\r\n\t\tstruct node* p = getNode(roll,name,cgpa);\r\n\t\tp->next = temp->next;\r\n\t\ttemp->next=p;\r\n\t}\r\n\telse{\r\n\t\tprintf(\"INVALID POSITIONS\\n\");\r\n\t}\r\n}\r\n\r\nvoid ins_end(int roll,char name[], float cgpa){\r\n\tstruct node* p =getNode(roll,name,cgpa);\r\n\tif (head==NULL)//list is empty\r\n\t{\r\n\t\thead=p;\r\n\t}\r\n\telse{\r\n\t\tstruct node* temp = head;\r\n\t\twhile(temp->next!=NULL)\r\n\t\t\ttemp=temp->next;\r\n\t\ttemp->next = p;\r\n\t}\r\n}\r\n\r\nvoid del_beg(){\r\n\tif(head==NULL)printf(\"NOTHING TO BE DELETED\\n\");\r\n\telse{\r\n\t\thead = head->next;\t\r\n\t}\r\n}\r\n\r\nvoid del_btw(int pos){\t\r\n\tif (pos>0 && pos<=countNode())\r\n\t{\r\n\t\tstruct node* temp = head;\r\n\t\tint count=0;\r\n\t\twhile(count!=(pos-1)){\r\n\t\t\ttemp = temp->next;\r\n\t\t}\t\t\t\r\n\t\ttemp->next=temp->next->next;\r\n\t}\r\n\telse{\r\n\t\tprintf(\"INVALID POSITIONS\\n\");\r\n\t}\r\n\r\n}\r\n\r\nvoid del_end(){\r\n\tif(head==NULL)printf(\"NOTHING TO BE DELETED\\n\");\r\n\telse if(head->next==NULL)head=NULL;\r\n\telse{\r\n\t\tstruct node* temp = head;\r\n\t\twhile(temp->next->next!=NULL)temp = temp->next;\t\t\r\n\t\ttemp->next = NULL;\t\r\n\t}\r\n}\r\n\r\nvoid search(int roll){\r\n\tstruct node* temp = head;\r\n\tint count=1,flag=0;\r\n\twhile(temp!=NULL){\r\n\t\tif(temp->roll==roll){\r\n\t\t\tprintf(\"POSITION at %d\\n\",count);\r\n\t\t\tprintf(\"FOLLOWING DATA OF ROLL NO. :\\n\");\t\r\n\t\t\tprintf(\"ROLL NO. : %d\\nNAME : %s\\nCGPA : %f\\n\\n\",temp->roll,temp->name,temp->cgpa);\r\n\t\t\tflag=1;\t\t\t\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\t++count;\r\n\t\ttemp = temp->next;\r\n\t}\r\n\tif(flag==0)printf(\"NOT FOUND\\n\");\r\n}\r\n\r\nvoid DISPLAY(){\r\n\tstruct node* temp = head;\r\n\tif(temp==NULL)printf(\"NOTHING TO DISPLAY\\n\");\r\n\telse{\r\n\t\twhile(temp!=NULL){\r\n\t\t\tprintf(\"ROLL NO: %d\\nNAME: %s\\nCGPA:%f\\n\\n\",temp->roll,temp->name,temp->cgpa);\r\n\t\t\ttemp=temp->next;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nint main()\r\n{\r\n\thead = NULL;\r\n\twhile(1){\t\r\n\t\tprintf(\"1.INSERT : \\n2.DELETE : \\n3.SEARCH : \\n4.DISPLAY : \\n\");\r\n\t\tint ch;\r\n\t\tscanf(\"%d\",&ch);\r\n\t\tif (ch==1)\r\n\t\t{\r\n\t\t\tint ch1;\r\n\t\t\tprintf(\"1.INSERT at BEGINNING: \\n2.INSERT at END: \\n3.INSERT at BETWEEN:\\n\");\r\n\t\t\tscanf(\"%d\",&ch1);\r\n\t\t\tint roll;\r\n\t\t\tchar name[100];\r\n\t\t\tfloat cgpa;\r\n\t\t\tprintf(\"Enter UNIQUE ROLL NO. to be inserted\\n\");\r\n\t\t\tscanf(\"%d\",&roll);\r\n\t\t\tprintf(\"Enter NAME to be inserted\\n\");\r\n\t\t\tgets(name);\r\n\t\t\tprintf(\"Enter CGPA to be inerted\\n\");\r\n\t\t\tscanf(\"%f\",&cgpa);\r\n\t\t\tif (ch1==1)\r\n\t\t\t{\r\n\t\t\t\tins_beg(roll,name,cgpa);\r\n\t\t\t}\r\n\t\t\telse if (ch1==2)\r\n\t\t\t{\r\n\t\t\t\tins_end(roll,name,cgpa);\r\n\t\t\t}\r\n\t\t\telse if (ch1==3)\r\n\t\t\t{\r\n\t\t\t\tprintf(\"Enter the POSITION where node is to be inserted\\n\");\r\n\t\t\t\tint k;\r\n\t\t\t\tscanf(\"%d\",&k);\r\n\t\t\t\tins_btw(roll,name,cgpa,k);\r\n\t\t\t}\r\n\t\t\telse printf(\"INVALID INPUT\\n\");\r\n\t\t}\r\n\t\telse if(ch==2){\r\n\t\t\tint ch1;\r\n\t\t\tprintf(\"1.DELETE at BEGINNING: \\n2.DELETE at END: \\n3.DELETE at BETWEEN:\\n\");\r\n\t\t\tscanf(\"%d\",&ch1);\r\n\t\t\tif(ch1==1){\r\n\t\t\t\tdel_beg();\r\n\t\t\t}\r\n\t\t\telse if(ch1==2){\r\n\t\t\t\tdel_end();\r\n\t\t\t}\r\n\t\t\telse if(ch1==3){\r\n\t\t\t\tprintf(\"Enter the POSITION at which node is to be DELETED\\n\");\r\n\t\t\t\tint k;\r\n\t\t\t\tdel_btw(scanf(\"%d\",&k));\t\t\r\n\t\t\t}\r\n\t\t\telse printf(\"INVALID POSITION\");\r\n\r\n\t\t}\r\n\t\telse if(ch==3){\r\n\t\t\tint roll;\r\n\t\t\tprintf(\"Enter UNIQUE ROLL NO. to be searched\\n\");\r\n\t\t\tscanf(\"%d\",&roll);\r\n\t\t\tsearch(roll);\r\n\t\t}\r\n\t\telse if(ch==4)DISPLAY();\r\n\t\telse {printf(\"INVALID INPUT\\n\");break;}\r\n\t}\r\n\treturn 0;\r\n}\r\n"
  },
  {
    "path": "Data Structures/C:C++/Linked List/ordered_linked.c",
    "content": "#include <stdio.h>\n#include<stdlib.h>\n#include<string.h>\nstruct node\n{\n\tint roll;\n\tchar name[100];\n\tfloat cgpa;\n\tstruct node* next;\n};\n\nstruct node* head;\n\nstruct node* getNode(int roll1,char name1[], float cgpa1){\n\tstruct node* p = (struct node*)malloc(sizeof(struct node));\n\tp->roll=roll1;\n\tstrcpy(p->name,name1);\n\tp->cgpa=cgpa1;\n\tp->next=NULL;\n\treturn p;\n}\n\nstruct node* getLastNode(){\n\tstruct node* temp = head;\n\twhile(temp->next!=NULL)\n\t\ttemp=temp->next;\n\treturn temp;\n}\n\nint countNode(){\n\tstruct node* temp = head;\n\tint count=0;\n\twhile(temp!=NULL){\n\t\tcount++;\n\t\ttemp = temp->next;\n\t}\n\treturn count;\n}\n\nvoid insert(int roll,char name[], float cgpa){\n\tstruct node* p =getNode(roll,name,cgpa);\n\tif(head==NULL){\n\t\thead = p;\t\n\t}\n\telse if(head->roll > roll){\n\t\tp->next=head;\n\t\thead=p;\n\t}\n\telse{\n\t\tstruct node* temp = head;\n\t\tstruct node* pre = NULL;\n\t\twhile(temp->roll < roll && temp!=NULL){\n\t\t\tpre = temp;\t\n\t\t\ttemp=temp->next;\n\t\t}\t\n\t\tp->next = temp;\n\t\tpre->next = p;\n\t}\n}\n/*void ins_beg(int roll,char name[], float cgpa){\n\tstruct node* p =getNode(roll,name,cgpa);\n\tp->next = head;\n\thead = p;\n}\n\nvoid ins_btw(int roll,char name[], float cgpa,int pos){\n\tif (pos>0 && pos<=countNode())\n\t{\n\t\tstruct node* temp = head;\n\t\tint count=0;\n\t\twhile(count!=(pos-1)){\n\t\t\ttemp = temp->next;\n\t\t}\n\t\tstruct node* p = getNode(roll,name,cgpa);\n\t\tp->next = temp->next;\n\t\ttemp->next=p;\n\t}\n\telse{\n\t\tprintf(\"INVALID POSITIONS\\n\");\n\t}\n}\n\nvoid ins_end(int roll,char name[], float cgpa){\n\tstruct node* p =getNode(roll,name,cgpa);\n\tif (head==NULL)//list is empty\n\t{\n\t\thead=p;\n\t}\n\telse{\n\t\tstruct node* temp = head;\n\t\twhile(temp->next!=NULL)\n\t\t\ttemp=temp->next;\n\t\ttemp->next = p;\n\t}\n}*/\n\nvoid del_beg(){\n\tif(head==NULL)printf(\"NOTHING TO BE DELETED\\n\");\n\telse head = head->next;\t\n}\n\nvoid del_btw(int pos){\t\n\tif (pos>0 && pos<=countNode())\n\t{\n\t\tstruct node* temp = head;\n\t\tint count=0;\n\t\twhile(count!=(pos-1)){\n\t\t\ttemp = temp->next;\n\t\t}\t\t\t\n\t\ttemp->next=temp->next->next;\n\t}\n\telse printf(\"INVALID POSITIONS\\n\");\n}\n\nvoid del_end(){\n\tif(head==NULL)printf(\"NOTHING TO BE DELETED\\n\");\n\telse if(head->next==NULL)head=NULL;\n\telse{\n\t\tstruct node* temp = head;\n\t\twhile(temp->next->next!=NULL)temp = temp->next;\t\t\n\t\ttemp->next = NULL;\t\n\t}\n}\n\nvoid search(int roll){\n\tstruct node* temp = head;\n\tint count=1,flag=0;\n\twhile(temp!=NULL){\n\t\tif(temp->roll==roll){\n\t\t\tprintf(\"POSITION at %d\\n\",count);\n\t\t\tprintf(\"FOLLOWING DATA OF ROLL NO. :\\n\");\t\n\t\t\tprintf(\"ROLL NO. : %d\\nNAME : %s\\nCGPA : %f\\n\\n\",temp->roll,temp->name,temp->cgpa);\n\t\t\tflag=1;\t\t\t\n\t\t\tbreak;\n\t\t}\n\t\ttemp = temp->next;\n\t\t++count;\n\t}\n\tif(flag==0)printf(\"NOT FOUND\\n\");\n}\n\nvoid DISPLAY(){\n\tstruct node* temp = head;\n\tif(temp==NULL)printf(\"NOTHING TO DISPLAY\\n\");\n\telse{\n\t\twhile(temp!=NULL){\n\t\t\tprintf(\"ROLL NO: %d\\nNAME: %s\\nCGPA:%f\\n\\n\",temp->roll,temp->name,temp->cgpa);\n\t\t\ttemp=temp->next;\n\t\t}\n\t}\n}\n\nint main()\n{\n\thead = NULL;\n\twhile(1){\t\n\t\tprintf(\"1.INSERT : \\n2.DELETE : \\n3.SEARCH : \\n4.DISPLAY : \\n\");\n\t\tint ch;\n\t\tscanf(\"%d\",&ch);\n\t\tif (ch==1)\n\t\t{\n\t\t\tint roll;\n\t\t\tchar name[100];\n\t\t\tfloat cgpa;\n\t\t\tprintf(\"Enter ROLL NO. to be inserted\\n\");\n\t\t\tscanf(\"%d\",&roll);\n\t\t\tprintf(\"Enter NAME to be inserted\\n\");\n\t\t\tgets(name);\n\t\t\tprintf(\"Enter CGPA to be inerted\\n\");\n\t\t\tscanf(\"%f\",&cgpa);\n\t\t\tinsert(roll,name,cgpa);\n\t\t}\n\t\telse if(ch==2){\n\t\t\tint ch1;\n\t\t\tprintf(\"1.DELETE at BEGINNING: \\n2.DELETE at END: \\n3.DELETE at BETWEEN:\\n\");\n\t\t\tscanf(\"%d\",&ch1);\n\t\t\tif(ch1==1){\n\t\t\t\tdel_beg();\n\t\t\t}\n\t\t\telse if(ch1==2){\n\t\t\t\tdel_end();\n\t\t\t}\n\t\t\telse if(ch1==3){\n\t\t\t\tprintf(\"Enter the POSITION at which node is to be DELETED\\n\");\n\t\t\t\tint k;\n\t\t\t\tdel_btw(scanf(\"%d\",&k));\t\t\n\t\t\t}\n\t\t\telse printf(\"INVALID INPUT\");\n\n\t\t}\n\t\telse if(ch==3){\n\t\t\tint roll;\n\t\t\tprintf(\"Enter ROLL NO. to be searched\\n\");\n\t\t\tscanf(\"%d\",&roll);\n\t\t\tsearch(roll);\n\t\t}\n\t\telse if(ch==4)DISPLAY();\n\t\telse {printf(\"INVALID INPUT\\n\");break;}\n\t}\n\treturn 0;\n}\n"
  },
  {
    "path": "Data Structures/C:C++/Linked List/reverse.cpp",
    "content": "#include<iostream>\r\n#include<malloc.h>\r\nusing namespace std;\r\n//structure of node\r\nstruct node\r\n{\r\n    int data;\r\n    struct node *next;\r\n}*start=NULL;\r\n//function to create linked list\r\nstruct node* create(struct node*current)\r\n{\r\n  struct node *new_node;//pointer to node\r\n  new_node=(struct node *)malloc(sizeof(struct node));\r\n\r\n  cout<<\"\\nEnter the data : \";\r\n  cin>>new_node->data;\r\n  new_node->next=NULL;\r\n\r\n  if(start==NULL)//to check if the root node is null or not\r\n  {\r\n    start=new_node;\r\n    current=new_node;\r\n  }\r\n  else\r\n  {\r\n    current->next=new_node;\r\n    current=new_node;\r\n  }\r\n  return current;\r\n\r\n}\r\n//function to display linked list\r\nvoid display()\r\n{\r\n    struct node *new_node;\r\n    cout<<\"\\nThe Linked List : \"<<endl;\r\n    new_node=start;\r\n    while(new_node!=NULL)//condition to point to the last node\r\n    {\r\n        cout<<new_node->data<<\"--->\";\r\n        new_node=new_node->next;\r\n    }\r\n    cout<<\"NULL\"<<endl;\r\n}\r\n//function to reverse linked list\r\nvoid reverse()\r\n{\r\n    struct node *prev,*curr,*nextt;//prev for pointing to previous node,curr for pointing to current node,nextt for pointing to next node\r\n    curr=start;//pointing to the root node\r\n    prev=NULL;\r\n    while(curr!=NULL)\r\n    {\r\n        nextt=curr->next;\r\n        curr->next=prev;\r\n        prev=curr;\r\n        curr=nextt;\r\n\r\n\r\n    }\r\n    start=prev;\r\n    display();\r\n}\r\nint main()\r\n{\r\n    int n;\r\n    struct node*current;\r\n    current=NULL;\r\n    while(1)\r\n    {\r\n        cout<<\"1.to insert\\n2.display\\n3.reverse\\n4.exit\\nenter choice\"<<endl;\r\n        cin>>n;\r\n\r\n        switch(n)\r\n        {\r\n            case 1: current=create(current);//passing current pointer to create function\r\n                    break;\r\n            case 2: display();\r\n                    break;\r\n            case 3:reverse();\r\n                    break;\r\n            case 4: return 0;\r\n        }\r\n    }\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Data Structures/C:C++/Linked List/stackLinkedList.cpp",
    "content": "#include<bits/stdc++.h>\r\n\r\nstruct node{\r\n\tint item;\r\n\tstruct node* next;\r\n};\r\n\r\nstruct node* head;\r\nint size;\r\n\r\nvoid insertathead(){\r\n\tstruct node* ptr;\r\n\tptr = (struct node*)malloc(sizeof(struct node));\r\n\tprintf(\"Enter data : \");\r\n\tscanf(\"%d\",&ptr->item);\r\n\tprintf(\"\\n\");\r\n\tptr->next = NULL;\r\n\tif(head == NULL){\r\n\t\thead = ptr;\r\n\t\treturn;\r\n\t}\r\n\tptr->next = head;\r\n\thead = ptr;\r\n}\r\n\r\nvoid pop(){\r\n\tif(head==NULL){\r\n\t\tprintf(\"UnderFlow\\n\");\r\n\t\treturn;\r\n\t}\r\n\tif(head->next == NULL){\r\n\t\thead=NULL;\r\n\t\treturn;\r\n\t}\r\n\tstruct node* temp;\r\n\ttemp = head;\r\n\thead = head->next;\r\n\ttemp->next = NULL;\r\n}\r\nvoid print(){\r\n\tstruct node* temp;\r\n\ttemp = head;\r\n\tprintf(\"List : \");\r\n\twhile(temp!=NULL){\r\n\t\tprintf(\"%d \",temp->item);\r\n\t\ttemp = temp->next;\r\n\t}\r\n\tprintf(\"\\n\");\r\n}\r\n\r\nint main(){\r\n\thead=NULL;\r\n\tprintf(\"Enter the size of array\\n\");\r\n\tscanf(\"%d\",&size);\r\n\twhile(1){\r\n\t\tprintf(\"Enter choice\\n1.Insert\\n2.Pop\\n3.Print\\n\");\r\n\t\tint ch;\r\n\t\tscanf(\"%d\",&ch);\r\n\t\tif(ch==1){\r\n\t\tinsertathead();\r\n\t\t}\r\n\t\telse if(ch==2){\r\n\t\t\tpop();\t\r\n\t\t}\r\n\t\telse if(ch==3){\r\n\t\t\tprint();\r\n\t\t}\r\n\t}\r\n}\r\n"
  },
  {
    "path": "Data Structures/C:C++/Linked List/stack_Linked_List.c",
    "content": "/*Implementation of stack using linked list */\r\n\r\n/*Stack is a LIFO (Last In Fast Out Data Structure */\r\n\r\n/*\r\n * push operation \tO(1)\r\n * pop operation\tO(1)\r\n * top operation\tO(1)\r\n * isEmpty operation \tO(1)\r\n*/\r\n\r\n#include <stdio.h>\r\n#include <stdlib.h>\r\nstruct node{\r\n\tint item;\r\n\tstruct node* next;\r\n};\r\n\r\nstruct stack{\r\n\tstruct node *tos;\r\n};\r\n\r\ntypedef struct node node;\r\ntypedef struct stack stack;\r\n\r\n/*Function to create stack*/\r\nstack* createStack(){\r\n\tstack *temp=(stack*)malloc(sizeof(stack));\r\n\ttemp->tos=NULL;\r\n\treturn temp;\r\n}\r\n\r\n\r\n/*Function to push in a stack */\r\nvoid push(stack *s,int data){\r\n\tnode *temp=(node*)malloc(sizeof(node));\r\n\t/*checking if the memory was allocated to temp*/\r\n\tif(temp==NULL){\r\n\t\tprintf(\"OVERFLOW\\n\");\r\n\t\texit(0);\r\n\t}\r\n\ttemp->item=data;\r\n\tif(s->tos==NULL){\r\n\t\ts->tos=temp;\r\n\t\ttemp->next=NULL;\r\n\t\treturn;\r\n\t}\r\n\telse{\r\n\t\ttemp->next=s->tos;\r\n\t\ts->tos=temp;\r\n\t\treturn;\r\n\t}\r\n}\r\n\r\n/*Function to pop an element from a stack */\r\nint pop(stack *s){\r\n\tnode *temp;\r\n\tint valueToReturn;\r\n\tif(s->tos==NULL){\r\n\t\tprintf(\"UNDERFLOW\\n\");\r\n\t\texit(0);\r\n\t}\r\n\telse{\r\n\t\ttemp=s->tos;\r\n\t\ts->tos=temp->next;\r\n\t\tvalueToReturn=temp->item;\r\n\t\tfree(temp);\r\n\t\treturn valueToReturn;\r\n\t}\r\n}\r\n\r\n/*function to check wheather the stack is empty */\r\nint isEmpty(stack *s){\r\n\treturn s->tos==NULL;\r\n}\r\n\r\n\r\n/*Functiont that returns the top of the stack */\r\nint top(stack *s){\r\n\tif(!isEmpty(s))\r\n\t\treturn s->tos->item;\r\n\telse\r\n\t\treturn -1;\r\n}\r\n\r\n\r\n\r\nint main(){\r\n\tstack *s=createStack();\r\n\tint temp,ch,cont;\r\n\tdo{\r\n\t\tprintf(\"Enter choice\\t1.Push\\t2.Pop\\t3.top :\");\r\n\t\tscanf(\"%d\",&ch);\r\n\t\tswitch(ch){\r\n\t\t\tcase 1:\r\n\t\t\t\tprintf(\"Enter value :\");\r\n\t\t\t\tscanf(\"%d\",&temp);\r\n\t\t\t\tpush(s,temp);\r\n\t\t\t\tbreak;\r\n\t\t\tcase 2:\r\n\t\t\t\tprintf(\"%d popped \\n\",pop(s));\r\n\t\t\t\tbreak;\r\n\t\t\tcase 3:\r\n\t\t\t\tprintf(\"top : %d\\n\",top(s));\r\n\t\t\t\tbreak;\r\n\t\t}\r\n\t\tprintf(\"\\nContinue (1/0)\\n\");\r\n\t\tscanf(\"%d\",&cont);\r\n\t}while(cont != 0);\r\nreturn 0;\r\n}\r\n"
  },
  {
    "path": "Data Structures/C:C++/Stack/Balanced_Brackets.cpp",
    "content": "/*This program checks whether an entered string is Bracket Balanced ot not.By Bracket balanced we mean a opening bracket ('(','{','[') to be complemented by a closing bracket (')','}',']').\nTime Complexity :O(n)\nAuxiliary Space :O(n)\nSimilar quesion(s) for practice :https://www.hackerrank.com/challenges/balanced-brackets/problem\n*/\n#include<bits/stdc++.h>\nusing namespace std;\nint main()\n{\n\tstring str;\n\tgetline(cin,str);\n    stack<char> s;\n    \n    char a,b,c;\n    int flag=1;\n\n\tfor(int i=0;i<str.length();i++)\n\t{\n\t\tif (str[i]=='('||str[i]=='['||str[i]=='{')\n        {\n            // Push the element in the stack\n            s.push(str[i]);\n        }\n        else\n        {\n            switch (str[i])\n            {\n            case ')':\n \n                // Store the top element in a\n                a = s.top();\n                s.pop();\n                if (a=='{'||a=='[')\n                {\n                  \n                    flag=0;\n                }\n                break;\n            case '}':\n \n                // Store the top element in b\n                b = s.top();\n                s.pop();\n                if (b=='('||b=='[')\n                {\n                   \n                    flag=0;\n                }\n                break;\n            case ']':\n \n                // Store the top element in c\n                c=s.top();\n                s.pop();\n                if (c=='('||c=='{')\n                {\n                \n                    flag=0;\n                }\n                break;\n            }\n        }\n\t}\n    if (s.empty() && flag==1)\n        cout<<\"Balanced\";\n    else\n        cout<<\"Unbalanced\";\n}\n\t\n\n"
  },
  {
    "path": "Data Structures/C:C++/Stack/Reverse_Queue.cpp",
    "content": "/*\nAn effective CPP program to reverse a Queue.In this program,\na Queue is populated with values and then it is reversed using the use of Stack.\nTime Complexity:O(n)\nSpace Complexity:Extra Space for Stack\n#include <bits/stdc++.h>\n*/\nusing namespace std; \nvoid Print(queue<int>& Queue)\n{\n    while (!Queue.empty()) {\n        cout << Queue.front() << \" \";\n        Queue.pop();\n    }\n}\n \n// Function to reverse the queue\nvoid reverseQueue(queue<int>& Queue)\n{\n    stack<int> Stack;\n    while (!Queue.empty()) {\n        Stack.push(Queue.front());\n        Queue.pop();\n    }\n    while (!Stack.empty()) {\n        Queue.push(Stack.top());\n        Stack.pop();\n    }\n}\n \n// Main Function\nint main()\n{\n    queue<int> Queue;\n    Queue.push(1);\n    Queue.push(2);\n    Queue.push(3);\n    Queue.push(4);\n    Queue.push(5);\n    Queue.push(6);\n    Queue.push(7);\n    Queue.push(8);\n    Queue.push(9);\n    Queue.push(10);\n \n    reverseQueue(Queue);\n    Print(Queue);\n}"
  },
  {
    "path": "Data Structures/C:C++/Stack/Stack_as_linked_list.cpp",
    "content": "C++ Program to implement Stack using Linked List:\n\n#include<iostream>\nusing namespace std;\n\n\n//   Creating a NODE Structure\nstruct node\n{\n    int data;\n    struct node *next;\n};\n\n// Creating a class STACK\nclass stack\n{\n    struct node *top;\n    public:\n    stack() // constructure\n    {\n        top=NULL;\n    }\n    void push(); // to insert an element\n    void pop();  // to delete an element\n    void show(); // to show the stack\n};\n// PUSH Operation\nvoid stack::push()\n{\n    int value;\n    struct node *ptr;\n    cout<<\"\\nPUSH Operationn\";\n    cout<<\"Enter a number to insert: \";\n    cin>>value;\n    ptr=new node;\n    ptr->data=value;\n    ptr->next=NULL;\n    if(top!=NULL)\n        ptr->next=top;\n    top=ptr;\n    cout<<\"\\nNew item is inserted to the stack!!!\";\n\n}\n\n// POP Operation\nvoid stack::pop()\n{\n    struct node *temp;\n    if(top==NULL)\n    {\n        cout<<\"\\nThe stack is empty!!!\";\n    }\n    temp=top;\n    top=top->next;\n    cout<<\"\\nPOP Operation........\\nPoped value is \"<<temp->data;\n    delete temp;\n}\n\n// Show stack\nvoid stack::show()\n{\n    struct node *ptr1=top;\n    cout<<\"\\nThe stack is\\n\";\n    while(ptr1!=NULL)\n    {\n        cout<<ptr1->data<<\" ->\";\n        ptr1=ptr1->next;\n    }\n    cout<<\"NULL\\n\";\n}\n\n// Main function\nint main()\n{\n    stack s;\n    int choice;\n    while(1)\n    {\n        cout<<\"\\n-----------------------------------------------------------\";\n        cout<<\"\\n\\t\\tSTACK USING LINKED LIST\\n\\n\";\n        cout<<\"1:PUSH\\n2:POP\\n3:DISPLAY STACK\\n4:EXIT\";\n        cout<<\"\\nEnter your choice(1-4): \";\n        cin>>choice;\n        switch(choice)\n        {\n            case 1:\n                s.push();\n                break;\n            case 2:\n                s.pop();\n                break;\n            case 3:\n                s.show();\n                break;\n            case 4:\n                return 0;\n                break;\n            default:\n                cout<<\"\\nPlease enter correct choice(1-4)!!\";\n                break;\n        }\n    }\n    return 0;\n}\n\n"
  },
  {
    "path": "Data Structures/C:C++/Stack/largestRectangleHistogram.cpp",
    "content": "#include<iostream>\n#include<stack>\n#include<climits>\nusing namespace std;\nint main() {\n    int n;\n    int a[]={6,2,5,4,5,1,6};  //input array\n    n = sizeof(a)/sizeof(a[0]);\n    int i,q;\n    stack <int> s;  // stack to calculate max area\n    i=0;\n    int area,maxarea=INT_MIN;\n    while(i<n){\n        if(s.empty()||a[s.top()]<=a[i])\n        s.push(i++);\n        else{\n            q=s.top();\n            s.pop();\n            area=a[q]*(s.empty()?i:i-s.top()-1);\n            if(maxarea<area)\n                maxarea=area;\n        }\n    }\n    while(!s.empty()){\n        q=s.top();\n        s.pop();\n        area=a[q]*(s.empty()?i:i-s.top()-1);\n        if(maxarea<area)\n            maxarea=area;\n    }\n    cout<<maxarea;\n\treturn 0;\n}\n"
  },
  {
    "path": "Data Structures/C:C++/Stack/nextgreaterelement",
    "content": "//http://www.geeksforgeeks.org/next-greater-element/\n\n//The problem is from geekforgeeks and it is my implementation of it.\n#include<bits/stdc++.h>\nusing namespace std;\n\n\n\nint main(){\n\tint n;\n\tcin>>n;\n\tint a[n];\n\tint ans[n];\n\tfor(int i=0;i<n;i++){\n\t\tans[i]=-1;\n\t}\n\tfor(int i=0;i<n;i++){\n\t\tcin>>a[i];\n\t}\n\tstack<int> s;\n\tfor(int i=0;i<n;i++){\n\t\t\n\t\twhile(!s.empty()&&a[i]>a[s.top()]){\n\t\t\tans[s.top()]=a[i];\n\t\t\ts.pop();\n\t\t}\n\t\ts.push(i);\n\t}\n\tfor(int i=0;i<n;i++){\n\t\tcout<<a[i]<<\" \"<<ans[i]<<endl;\n\t}\n}\n"
  },
  {
    "path": "Data Structures/C:C++/Stack/stack.hpp",
    "content": "#include <bits/stdc++.h>\r\n#include \"../linked_list/ll.hpp\"\r\nusing namespace std;\r\n\r\ntemplate<class T>\r\nstruct stackmp{\r\n\tll_node<T> *top;\r\n\tint capacity; // number of elements the stack can contain\r\n\tint size; // number of elements in the stack\r\n\r\n\tstackmp(int cap) : capacity(cap),size(0) {}\r\n\r\n\tvoid push(T new_data){\r\n\t\tif(size == capacity){\r\n\t\t\tcout << \"Stack is full! Cannot push new element\" << endl;\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tll_node<T> *new_node = create_node(new_data);\r\n\t\tll_node<T> *temp_node = this->top;\r\n\t\tnew_node->next = temp_node;\r\n\t\tthis->top = new_node; // here \"this\" pointer is used to access the current class's object's parameters\r\n\t\tsize++;\r\n\t}\r\n\r\n\tvoid print(){\r\n\t\tll_node<T> *temp_node = this->top;\r\n\t\tif(size == 0){\r\n\t\t\tcout << \"Stack is empty\" << endl;\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tcout << \"Printing stack:\" << endl;\r\n\t\tfor(int i=0;i<this->size;i++){\r\n\t\t\tcout << temp_node->data << ' ';\r\n\t\t\ttemp_node = temp_node->next;\r\n\t\t}\r\n\t\tcout << endl;\r\n\t}\r\n\r\n\tT pop(){\r\n\t\tif(size == 0){\r\n\t\t\tcout << \"Stack is empty, can't pop\" << endl;\r\n\t\t\treturn '\\0';\r\n\t\t}\r\n\t\tT data = this->top->data;\r\n\t\tthis->top = this->top->next;\r\n\t\tsize--;\r\n\t\treturn data;\r\n\t}\r\n\r\n\tT peek(){\r\n\t\treturn this->top->data;\r\n\t}\r\n};\r\n\r\ntemplate<class T>\r\nint get_size(stackmp<T> *s){\r\n\treturn s->size;\r\n}\r\n\r\ntemplate<class T>\r\nint get_capacity(stackmp<T> *s){\r\n\treturn s->capacity;\r\n}\r\n\r\n"
  },
  {
    "path": "Data Structures/C:C++/Trees/segment_tree/segment_tree.cpp",
    "content": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid createMinSegmentTree(int arr[],int sg[],int index,int begin,int end){\n\t//create the segment tree.\n\tif(begin == end){\n\t\tsg[index] = arr[begin];\n\t\treturn;\n\t}\n\tint mid = (begin+end)/2;\n\tcreateMinSegmentTree(arr,sg,2*index,begin,mid);\n\tcreateMinSegmentTree(arr,sg,2*index+1,mid+1,end);\n\tsg[index] = min(sg[2*index],sg[2*index+1]);\n\treturn;\n\n}\n\nint queryMinSegmentTree(int sg[],int l,int r,int index,int begin,int end){\n\t//querying the segment tree\n\n\t//complete overlap\n\tif(l <= begin && r >= end){\n\t\treturn sg[index];\n\t}\n\t//no overlap\n\telse if(r<begin || l> end){\n\t\treturn INT_MAX;\n\t}\n\t//partial overlap\n\telse{\n\t\tint mid = (begin+end)/2;\n\t\treturn min(queryMinSegmentTree(sg,l,r,2*index,begin,mid),queryMinSegmentTree(sg,l,r,2*index+1,mid+1,end));\n\t}\n\n}\n\nvoid updateMinSegmentTree(int sg[],int l,int r,int index,int begin,int end,int update){\n\n\tif(begin == end && begin>=l && begin<=r){\n\t\tsg[index]+=update;\n\t\treturn;\n\t}\n\tif(l>end || r<begin){\n\t\treturn;\n\t}\n\tint mid = (begin+end)/2;\n\tupdateMinSegmentTree(sg,l,r,2*index,begin,mid,update);\n\tupdateMinSegmentTree(sg,l,r,2*index+1,mid+1,end,update);\n\tsg[index] = min(sg[2*index],sg[2*index+1]);\n\treturn;\n\n\n}\n\nint main(){\n\n\tint n; cin >> n;\n\n\tint arr[n];\n\n\tfor(int i=0;i<n;i++){\n\t\tarr[i] = rand()%n+1;\t\n\t}\n\n\tint sg[4*n]={};\n\tcreateMinSegmentTree(arr,sg,1,0,n-1);\n\n\t//print the original array\n\tfor(int i =0;i<n;i++){\n\t\tcout << arr[i]<<\" \";\n\t}\n\tcout << endl;\n\n\tint q; cin >> q;\n\n\tint l,r,option;\n\twhile(q--){\n\t\tcin >> option;\t\n\n\t\t//option 1 to query the segment tree with range [l,r].\n\t\tif(option == 1){\n\t\t\tcin >> l >> r;\n\t\t\tcout << queryMinSegmentTree(sg,l,r,1,0,n-1)<<endl;\n\t\t}\n\t\t//option 2 to update the segment tree in range [l,r].\n\t\telse if(option == 2){\n\t\t\tint update;\n\t\t\tcin >> l >> r >> update;\n\t\t\tupdateMinSegmentTree(sg,l,r,1,0,n-1,update);\n\t\t}\n\t}\n\n\n\treturn 0;\n}"
  },
  {
    "path": "Data Structures/C:C++/Trees/segment_tree/segment_trees_lazy.cpp.cpp",
    "content": "/**\n * In this code we have a very large array called arr, and very large set of operations\n * Operation #1: Increment the elements within range [i, j] with value val\n * Operation #2: Get max element within range [i, j]\n * Build tree: build_tree(1, 0, N-1)\n * Update tree: update_tree(1, 0, N-1, i, j, value)\n * Query tree: query_tree(1, 0, N-1, i, j)\n * Actual space required by the tree = 2*2^ceil(log_2(n)) - 1\n */\n\n#include<iostream>\n#include<algorithm>\nusing namespace std;\n\n#include<string.h>\n#include<math.h>\n\n#define N 20\n#define MAX (1+(1<<6)) // Why? :D\n#define inf 0x7fffffff\n\nint arr[N];\nint tree[MAX];\nint lazy[MAX];\n\n/**\n * Build and init tree\n */\nvoid build_tree(int node, int a, int b) {\n    if(a > b) return; // Out of range\n\n    if(a == b) { // Leaf node\n        tree[node] = arr[a]; // Init value\n        return;\n    }\n\n    build_tree(node*2, a, (a+b)/2); // Init left child\n    build_tree(node*2+1, 1+(a+b)/2, b); // Init right child\n\n    tree[node] = max(tree[node*2], tree[node*2+1]); // Init root value\n}\n\n/**\n * Increment elements within range [i, j] with value value\n */\nvoid update_tree(int node, int a, int b, int i, int j, int value) {\n\n    if(lazy[node] != 0) { // This node needs to be updated\n        tree[node] += lazy[node]; // Update it\n\n        if(a != b) {\n            lazy[node*2] += lazy[node]; // Mark child as lazy\n            lazy[node*2+1] += lazy[node]; // Mark child as lazy\n        }\n\n        lazy[node] = 0; // Reset it\n    }\n\n    if(a > b || a > j || b < i) // Current segment is not within range [i, j]\n        return;\n\n    if(a >= i && b <= j) { // Segment is fully within range\n        tree[node] += value;\n\n        if(a != b) { // Not leaf node\n            lazy[node*2] += value;\n            lazy[node*2+1] += value;\n        }\n\n        return;\n    }\n\n    update_tree(node*2, a, (a+b)/2, i, j, value); // Updating left child\n    update_tree(1+node*2, 1+(a+b)/2, b, i, j, value); // Updating right child\n\n    tree[node] = max(tree[node*2], tree[node*2+1]); // Updating root with max value\n}\n\n/**\n * Query tree to get max element value within range [i, j]\n */\nint query_tree(int node, int a, int b, int i, int j) {\n\n    if(a > b || a > j || b < i) return -inf; // Out of range\n\n    if(lazy[node] != 0) { // This node needs to be updated\n        tree[node] += lazy[node]; // Update it\n\n        if(a != b) {\n            lazy[node*2] += lazy[node]; // Mark child as lazy\n            lazy[node*2+1] += lazy[node]; // Mark child as lazy\n        }\n\n        lazy[node] = 0; // Reset it\n    }\n\n    if(a >= i && b <= j) // Current segment is totally within range [i, j]\n        return tree[node];\n\n    int q1 = query_tree(node*2, a, (a+b)/2, i, j); // Query left child\n    int q2 = query_tree(1+node*2, 1+(a+b)/2, b, i, j); // Query right child\n\n    int res = max(q1, q2); // Return final result\n\n    return res;\n}\n\nint main() {\n    for(int i = 0; i < N; i++) arr[i] = 1;\n\n    build_tree(1, 0, N-1);\n\n    memset(lazy, 0, sizeof lazy);\n\n    update_tree(1, 0, N-1, 0, 6, 5); // Increment range [0, 6] by 5. here 0, N-1 represent the current range.\n    update_tree(1, 0, N-1, 7, 10, 12); // Incremenet range [7, 10] by 12. here 0, N-1 represent the current range.\n    update_tree(1, 0, N-1, 10, N-1, 100); // Increment range [10, N-1] by 100. here 0, N-1 represent the current range.\n\n    cout << query_tree(1, 0, N-1, 0, N-1) << endl; // Get max element in range [0, N-1]\n}"
  },
  {
    "path": "Data Structures/C:C++/Trees/tree/Fenwick_tree.cpp",
    "content": "#include<iostream>\nusing namespace std;\nint BIT[1000], arr[1000],l,r,n,s;\nvoid update(int x, int delta)\n{\n      for( ;x<=n;x+=x&-x)\n        BIT[x]+=delta;\n}\nint query(int x)\n{\n     int sum=0;\n     for(;x>0;x-=x&-x)\n        sum+=BIT[x];\n     return sum;\n}\n\nint main()\n{\n     cin>>n;\n     cout<<\"Enter \"<<n<<\" elemets and more than 8 elemets\\n\";\n     for(int i = 1; i <= n; i++)\n     {\n       cin>>arr[i];\n           update(i,arr[i]);\n     }\n     cout<<\"Give the number of elemets you want sum for\\n\";\n     cin>>s;\n     cout<<\"Sum of first \"<<s<<\" elements is \"<<query(s)<<endl;\n     cout<<\"Sum of all elements in range [2,8] is \"<<query(8)-query(2-1)<<endl;\n     return 0;\n}\n"
  },
  {
    "path": "Data Structures/C:C++/Trees/tree/bst.hpp",
    "content": "#include <bits/stdc++.h>\n#include \"../queue/queue.hpp\"\nusing namespace std;\n\ntemplate<class T>\nstruct bst_node{\n\tT data;\n\tbst_node *left_child;\n\tbst_node *right_child;\n\n\tbst_node(T new_data) : data(new_data), left_child(NULL), right_child(NULL) {};\n};\n\ntemplate<class T>\nclass BST{\nprivate:\n\tbst_node<T> *node;\n\n\t// helper functions \n\tint _get_length(bst_node<T> *node){\n\t\tif(node == NULL) return 0;\n\t\treturn 1 + max(_get_length(node->left_child), _get_length(node->right_child));\n\t}\n\n\tvoid _insert(bst_node<T> *node, T new_data){\n\t\t// if node exists\n\t\tif(node->data > new_data){\n\t\t\t// go left\n\t\t\tif(node->left_child){\n\t\t\t\t_insert(node->left_child, new_data);\n\t\t\t}else{\n\t\t\t\tnode->left_child = new bst_node<T>(new_data);\n\t\t\t}\n\t\t}else{\n\t\t\t// right\n\t\t\tif(node->right_child){\n\t\t\t\t_insert(node->right_child, new_data);\n\t\t\t}else{\n\t\t\t\tnode->right_child = new bst_node<T>(new_data);\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid _print(bst_node<T> *node){\n\t\tif(!node) return;\n\t\t_print(node->left_child);\n\t\tcout << node->data << \" \";\n\t\t_print(node->right_child);\n\t}\n\n\tvoid _print_post_order(bst_node<T> *node){\n\t\tif(!node) return;\n\t\t_print_post_order(node->left_child);\n\t\t_print_post_order(node->right_child);\n\t\tcout << node->data << \" \";\n\t}\n\n\tvoid _print_pre_order(bst_node<T> *node){\n\t\tif(!node) return;\n\t\tcout << node->data << \" \";\n\t\t_print_pre_order(node->left_child);\n\t\t_print_pre_order(node->right_child);\n\t}\n\n\tint _count_nodes(bst_node<T> *node){\n\t\tif(!node) return 0;\n\t\treturn 1 + _count_nodes(node->left_child) + _count_nodes(node->right_child);\n\t}\n\n\tbool _find(bst_node<T> *node, T data){\n\t\tif(node){\n\t\t\tif(node->data == data){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif(node->data > data){\n\t\t\t\t// go left\n\t\t\t\treturn _find(node->left_child, data);\n\t\t\t}else{\n\t\t\t\treturn _find(node->right_child, data);\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tvoid _print_max_path(bst_node<T> *node){\n\t\tif(!node) return;\n\t\tcout << node->data << ' ';\n\t\tif(_get_length(node->left_child)){\n\t\t\t_print_max_path(node->left_child);\n\t\t}else{\n\t\t\t_print_max_path(node->right_child);\n\t\t}\n\t}\n\n\tT _get_max(bst_node<T> *node){\n\t\tif(node == NULL) return '\\0';\n\t\tbst_node<T> *temp_node = node;\n\t\twhile(temp_node->right_child){\n\t\t\ttemp_node = temp_node->right_child;\n\t\t}\n\t\treturn temp_node->data;\n\t}\n\n\tT _get_min(bst_node<T> *node){\n\t\tif(node == NULL) return '\\0';\n\t\tbst_node<T> *temp_node = node;\n\t\twhile(temp_node->left_child){\n\t\t\ttemp_node = temp_node->left_child;\n\t\t}\n\t\treturn temp_node->data;\n\t}\n\n\tbst_node<T> *_get_min_node(bst_node<T> *node){\n\t\tif(node == NULL) return NULL;\n\t\tbst_node<T> *temp_node = node;\n\t\twhile(temp_node->left_child){\n\t\t\ttemp_node = temp_node->left_child;\n\t\t}\n\t\treturn temp_node;\n\t}\n\n\tbst_node<T> *_delete_value(bst_node<T> *root, T del_data){\n\t\tif(root == NULL) return root;\n\n\t\tif(del_data < root->data){\n\t\t\troot->left_child = _delete_value(root->left_child, del_data);\n\t\t}else if(del_data > root->data){\n\t\t\troot->right_child = _delete_value(root->right_child, del_data);\n\t\t}else{\n\t\t\t// check if one child is NULL\n\t\t\tif(root->left_child == NULL){\n\t\t\t\tbst_node<T> *temp_node = root->right_child;\n\t\t\t\tdelete root;\n\t\t\t\treturn temp_node;\n\t\t\t}else if(root->right_child == NULL){\n\t\t\t\tbst_node<T> *temp_node = root->left_child;\n\t\t\t\tdelete root;\n\t\t\t\treturn temp_node;\n\t\t\t}\n\n\t\t\t// if the node has both the \n\t\t\tbst_node<T> *temp_node = _get_min_node(root->right_child);\n\t\t\tcout << \"min node \" << temp_node->data << endl; \n\t\t\troot->data = temp_node->data;\n\t\t\troot->right_child = _delete_value(root->right_child, temp_node->data);\n\t\t}\n\t\treturn root;\n\t}\n\n\tint _get_count(bst_node<T> *node){\n\t\tif(node == NULL) return 0;\n\t\treturn 1 + _get_count(node->left_child) + _get_count(node->right_child);\n\t}\n\n\tvoid _level_order(bst_node<T> *node){\n\t\tif(node == NULL) return;\n\t\tcout << \"Level order traversal:\" << endl;\n\t\tqueuemp<bst_node<T> *> *q = new queuemp<bst_node<T> *>();\n\t\tq->push(node);\n\t\twhile(q->size){\n\t\t\tbst_node<T> *temp = q->pop();\n\t\t\tif(temp->left_child) q->push(temp->left_child);\n\t\t\tif(temp->right_child) q->push(temp->right_child); \n\t\t\tcout << temp->data << \" \";\n\t\t}\n\t\tcout << endl;\n\t\tdelete q;\n\t}\npublic:\n\tBST() : node(NULL) {}\n\tBST(T new_data) : node(new bst_node<T>(new_data)) {}\n\t~BST();\n\n\tT data(){\n\t\treturn this->node->data;\n\t}\n\n\tvoid insert(T new_data){\n\t\tbst_node<T> *new_node = new bst_node<T>(new_data);\n\t\tif(node == NULL){\n\t\t\tnode = new bst_node<T>(new_data);\n\t\t\treturn;\n\t\t}\n\t\t_insert(node, new_data);\n\t}\n\n\tint get_length(){\n\t\treturn _get_length(node);\n\t}\n\n\tvoid print(){\n\t\tcout << \"Printing BST (in order):\" << endl;\n\t\t_print(node);\n\t\tcout << endl;\n\t}\n\n\tvoid print_post_order(){\n\t\tcout << \"Printing BST (post order):\" << endl;\n\t\t_print_post_order(node);\n\t\tcout << endl;\n\t}\n\n\tvoid print_pre_order(){\n\t\tcout << \"Printing BST (pre order):\" << endl;\n\t\t_print_pre_order(node);\n\t\tcout << endl;\n\t}\n\n\tT get_max(){\n\t\treturn _get_max(node);\n\t}\n\n\tT get_min(){\n\t\treturn _get_min(node);\n\t}\n\n\tint count_nodes(){\n\t\treturn _count_nodes(node);\n\t}\n\n\tbool find(T data){\n\t\treturn _find(node, data);\n\t}\n\n\tvoid print_max_path(){\n\t\tcout << \"Max path:\" << endl;\n\t\t_print_max_path(node);\n\t\tcout << endl;\n\t}\n\n\tvoid delete_value(T del_data){\n\t\tthis->node = _delete_value(this->node, del_data);\n\t}\n\n\tint get_count(){\n\t\treturn _get_count(this->node);\n\t}\n\n\tvoid level_order(){\n\t\t_level_order(this->node);\n\t}\n};\n"
  },
  {
    "path": "Data Structures/C:C++/Trees/tree/segment_tree.hpp",
    "content": "#include <iostream>\n#include <math.h>\n\nclass segment_tree{\nprivate:\n    int *st;\n    int *ar;\n    int len;\n    int sz; //size of segment tree\n\n    // function to get middle of a segment\n    int _get_mid(int start, int end){\n        return start + (end - start) / 2;                \n    }\n\n    // util function to contruct segment tree\n    int _construct(int *v, int start, int end, int current){\n    \t// if there is 1 element in stray, store in current \n    \t// node and return\n    \tif(start == end){\n    \t\tst[current] = v[start];\n    \t\treturn v[start];\n    \t}\n\n    \t// for more elements, recur for left & right subtrees\n    \t// store the sum for values in this node\n    \tint mid = _get_mid(start, end);\n    \tst[current] = _construct(v, start, mid, current*2 + 1) + \n    \t\t\t\t\t_construct(v, mid + 1, end, current*2 + 2);\n    \treturn st[current];\n    }\n\n    // utility to update a value in segment tree\n    void _update_value(int start, int end, int i, int difference, int current){\n  \t\tif(i<start || i>end) return;\n  \t\tst[current] = st[current] + difference;\n  \t\tif(end != start){\n  \t\t\tint mid = _get_mid(start, end);\n  \t\t\t_update_value(start, mid, i, difference, 2*current+1);\n  \t\t\t_update_value(mid+1, end, i, difference, 2*current+2);\n  \t\t}\n    }\n\n    int _get_sum(int start, int end, int q_start, int q_end, int current){\n    \tif(q_start <= start && q_end >= end) return st[current];\n\n    \t// outside range\n    \tif(end < q_start || start > q_end) return 0;\n\n    \tint mid = _get_mid(start, end);\n    \treturn _get_sum(start, mid, q_start, q_end, 2*current+1) + \n    \t\t\t_get_sum(mid+1, end, q_start, q_end, 2*current+2);\n    }\npublic:\n    segment_tree(int *v, int n){\n    \tar = new int[n];\n    \tthis->len = n;\n    \tfor(int i=0;i<n;i++) ar[i] = v[i];\n    \t// construct tree\n    \t// height of tree\n    \tthis->sz = 0;\n    \tint h = (int)ceil(log2(n));\n    \tint max_size = 2 * (int)pow(2, h) - 1;\n    \tthis->sz = max_size;\n\n    \t// allocate memory\n    \tst = new int[max_size];\n    \t_construct(v, 0, n-1, 0);\n    }\n\n    // update value in \n    void update(int i, int new_val){\n    \tif(i<0 || i>this->len-1) return;\n    \tint difference = new_val - ar[i];\n    \tar[i] = new_val;\n\n    \t// update segment tree\n    \t_update_value(0, this->len-1, i, difference, 0);\n    }\n\n    //get sum of range\n    int get_sum(int start, int end){\n    \tif(start < 0 || end > this->len-1 || start > end) return -1;\n    \treturn _get_sum(0, this->len-1, start, end, 0);\n    }\n\n    int get(int n){\n    \treturn st[n];\n    }\n    void print(){\n    \tcout << \"Printing segment tree\" << endl;\n    \tint n = this->sz;\n    \tfor(int i=0;i<n;i++) cout << st[i] << \" \";\n    \tcout << endl;\n    }\n};"
  },
  {
    "path": "Data Structures/C:C++/Trees/tree/tree.hpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n\ntemplate<class T>\nstruct tree_node{\n\tT data;\n\ttree_node *left_child;\n\ttree_node *right_child;\n\n\ttree_node(T new_data) : data(new_data), left_child(NULL), right_child(NULL) {};\n\n\tvoid insert_left(T new_data){\n\t\ttree_node<T> *new_node = new tree_node<T>(new_data);\n\t\tthis->left_child = new_node;\n\t}\n\n\tvoid insert_right(T new_data){\n\t\ttree_node<T> *new_node = new tree_node<T>(new_data);\n\t\tthis->right_child = new_node;\n\t}\n};\n\ntemplate<class T>\nint get_length(tree_node<T> *top){\n\tif(top == NULL) return 0;\n\treturn 1 + max(get_length(top->left_child), get_length(top->right_child));\n}\n"
  },
  {
    "path": "Data Structures/C:C++/Trees/tree/trie.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef long long int ll;\nint ii,i,at;\nstruct no{\n\tno* nxt[26];\n\tno *root;\n\tll fim,qtdNo;\n\t\n\tinline no(char k){\n\t\tfor(ii=0;ii<26;ii++) nxt[ii] = NULL;\n\t\troot = this;\n\t\tfim = qtdNo = 0;\n\t}\n\tinline bool insert(const string s, ll i){\n\t\tif(i == s.size()){\n\t\t\tfim = 1;\n\t\t\treturn false;\n\t\t}\n\t\tat = s[i] - 'a';\n\t\tif(!nxt[at]){\n\t\t\tnxt[at] = new no(s[i]);\n\t\t\tnxt[at] -> root = root;\n\t\t\troot -> qtdNo++;\n\t\t}\n\t\telse if(nxt[at] -> fim) return true;\n\t\treturn nxt[at] -> insert(s,i+1);\n\t}\n};\n main(){}\n"
  },
  {
    "path": "Data Structures/C:C++/queue/queue.hpp",
    "content": "#include <bits/stdc++.h>\r\n#include \"../linked_list/ll.hpp\"\r\nusing namespace std;\r\n\r\ntemplate<class T>\r\nstruct queuemp{\r\n\tll_node<T> *head;\r\n\tint size; // number of elements in the queue\r\n\r\n\tqueuemp() : size(0) {}\r\n\r\n\tvoid push(T new_data){\r\n\t\tll_node<T> *new_node = create_node(new_data);\r\n\t\tll_node<T> *temp_node = this->head;\r\n\t\tnew_node->next = temp_node;\r\n\t\tthis->head = new_node;\r\n\t\tthis->size++;\r\n\t}\r\n\r\n\tvoid print(){\r\n\t\tif(this->size == 0){\r\n\t\t\tcout << \"queue is empty\" << endl;\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tll_node<T> *temp_node = this->head;\r\n\t\tcout << \"Printing queue:\" << endl;\r\n\t\tfor(int i=0;i<this->size;i++){\r\n\t\t\tcout << temp_node->data << \" \";\r\n\t\t\ttemp_node = temp_node->next;\r\n\t\t}\r\n\t\tcout << endl;\r\n\t}\r\n\r\n\tT pop(){\r\n\t\tif(this->size == 0){\r\n\t\t\tcout << \"queue is empty, can't pop\" << endl;\r\n\t\t\treturn '\\0';\r\n\t\t}\r\n\t\tif(this->size == 1){\r\n\t\t\tT data = this->head->data;\r\n\t\t\tthis->head = NULL;\r\n\t\t\tthis->size = 0;\r\n\t\t\treturn data;\r\n\t\t}\r\n\t\tll_node<T> *new_node = this->head;\r\n\t\t// move to second last element\r\n\t\tfor(int i=0;i<this->size-2;i++) new_node = new_node->next;\r\n\t\t//cout << new_node->data << endl;\r\n\t\tT data = new_node->next->data;\r\n\t\tnew_node->next = NULL;\r\n\t\tthis->size--;\r\n\t\treturn data;\r\n\t}\r\n\r\n\tT peek(){\r\n\t\treturn this->head->data;\r\n\t}\r\n};\r\n\r\ntemplate<class T>\r\nint get_size(queuemp<T> *s){\r\n\treturn s->size;\r\n}\r\n"
  },
  {
    "path": "Data Structures/Java/Stack/Stack.java",
    "content": "import java.lang.IndexOutOfBoundsException;\nimport java.util.Arrays;\n\npublic class Stack<E> {\n    private int max;\n    private int top;\n    private Object[] list;\n\n    public Stack() {\n        max = 512;\n        top = 0;\n        list = new Object[max];\n    }\n\n    public Stack(int size) {\n        max = size;\n        top = 0;\n        list = new Object[max];\n    }\n\n    @SuppressWarnings(\"unchecked\")\n    public boolean isEmpty() {\n        for(E t : (E[]) list) {\n            if(t != null) {\n                return false;\n            }\n        }\n\n        return true;\n    }\n\n    @SuppressWarnings(\"unchecked\")\n    public E peek() {\n        return (E) list[top];\n    }\n\n    @SuppressWarnings(\"unchecked\")\n    public int size() {\n        if(top == 0) {\n            return 0;\n        }\n\n        int count = 0;\n        for(E t : (E[]) list) {\n            if(t != null) {\n                count++;\n            }\n        }\n\n        return count;\n    }\n\n    @SuppressWarnings(\"unchecked\")\n    public E pop() {\n        if(isEmpty()) {\n            throw new IndexOutOfBoundsException(\"This stack is empty; nothing to pop.\");\n        }\n\n        E data = (E) list[top];\n\n        top = (top == 0 ? 0 : top - 1);\n        return data; \n    }\n\n    public void push(E data) {\n        if(top == max - 1) {\n            list = Arrays.copyOf(list, list.length * 2);\n        }\n\n        top++;\n        list[top] = data;\n    }\n}\n"
  },
  {
    "path": "Data Structures/Python/Graphs/Graph.py",
    "content": "from collections import defaultdict\n\n\nclass Graph(object):\n\n\n    def __init__(self, connections, directed=False):#undirected by default\n        self._graph = defaultdict(set)\n        self._directed = directed\n        self.add_connections(connections)\n\n    def add_connections(self, connections):\n        \"\"\" Add connections (list of tuple pairs) to graph \"\"\"\n\n        for node1, node2 in connections:\n            self.add(node1, node2)\n\n    def add(self, node1, node2):\n        \"\"\" Add connection between node1 and node2 \"\"\"\n\n        self._graph[node1].add(node2)\n        if not self._directed:\n            self._graph[node2].add(node1)\n\n    def remove(self, node):\n        \"\"\" Remove all references to node \"\"\"\n\n        for n, cxns in self._graph.iteritems():\n            try:\n                cxns.remove(node)\n            except KeyError:\n                pass\n        try:\n            del self._graph[node]\n        except KeyError:\n            pass\n\n    def is_connected(self, node1, node2):\n        \"\"\" Is node1 directly connected to node2 \"\"\"\n\n        return node1 in self._graph and node2 in self._graph[node1]\n\n    def find_path(self, node1, node2, path=[]):\n        \"\"\" Find any path between node1 and node2 (may not be shortest) \"\"\"\n\n        path = path + [node1]\n        if node1 == node2:\n            return path\n        if node1 not in self._graph:\n            return None\n        for node in self._graph[node1]:\n            if node not in path:\n                new_path = self.find_path(node, node2, path)\n                if new_path:\n                    return new_path\n        return None\n\n    def __str__(self):\n        return '{}({})'.format(self.__class__.__name__, dict(self._graph))\n"
  },
  {
    "path": "Data Structures/Python/Graphs/dfs.py",
    "content": "import collections\n\nclass Graph:\n    def __init__(self):\n        self.adjList = collections.defaultdict(set)\n\n    def addEdge(self, node1, node2):\n        self.adjList[node1].add(node2)\n        self.adjList[node2].add(node1)\n\ndef dfsHelper(current, graph, visited, visitFunc):\n    if (visited[current]):\n        return\n    \n    visited[current] = True;\n    \n    visitFunc(current)\n    \n    for neighbor in graph.adjList[current]:\n        dfsHelper(neighbor, graph, visited, visitFunc)\n    \n\ndef dfs(current, graph, visitFunc):\n    visited = collections.defaultdict(bool)\n    dfsHelper(current, graph, visited, visitFunc)\n\ndef visitPrint(i):\n    print(i)\n\n# Testing the depth first search implementation\nif __name__ == \"__main__\":\n\n    # Testing on this tree\n    #      1\n    #     / \\\n    #    /   \\\n    #   2     3\n    #  / \\   / \\\n    # 4   5 6   7\n    \n    g = Graph()\n    g.addEdge(1, 2)\n    g.addEdge(1, 3)\n    g.addEdge(2, 4)\n    g.addEdge(2, 5)\n    g.addEdge(3, 6)\n    g.addEdge(3, 7)\n\n    print(\"Test 1:\")\n    dfs(1, g, visitPrint)\n    \n    print(\"\\nTest2:\")\n    dfs(2, g, visitPrint)\n"
  },
  {
    "path": "Data Structures/Python/Linked List/singly_linked_list.py",
    "content": "class Node(object):\n \n    def __init__(self, data, next):\n        self.data = data\n        self.next = next\n \n \nclass SingleList(object):\n \n    head = None\n    tail = None\n \n    def show(self):\n        print \"Showing list data:\"\n        current_node = self.head\n        while current_node is not None:\n            print current_node.data, \" -> \",\n            current_node = current_node.next\n        print None\n \n    def append(self, data):\n        node = Node(data, None)\n        if self.head is None:\n            self.head = self.tail = node\n        else:\n            self.tail.next = node\n        self.tail = node\n \n    def remove(self, node_value):\n        current_node = self.head\n        previous_node = None\n        while current_node is not None:\n            if current_node.data == node_value:\n                # if this is the first node (head)\n                if previous_node is not None:\n                    previous_node.next = current_node.next\n                else:\n                    self.head = current_node.next\n \n            # needed for the next iteration\n            previous_node = current_node\n            current_node = current_node.next\n \n \ns = SingleList()\ns.append(31)\ns.append(2)\ns.append(3)\ns.append(4)\n \ns.show()\ns.remove(31)\ns.remove(3)\ns.remove(2)\ns.show()\n"
  },
  {
    "path": "Data Structures/Python/Queue/Queue.py",
    "content": "#List Based Implementation Of Queue in Python.\n\n\n#Defining a python Class named Queue.\n\n# isEmpty -> Returns True or False.\n# enqueue -> Enter the element in Queue.\n# dequeue -> Remove the element from Queue.\n# size    -> Returns the size of Queue\n\nclass Queue:\n\t\n   def __init__(self):\n\t    self.items = []\n\t\n   def isEmpty(self):\n\t    return self.items == []\n\t\n   def enqueue(self, item):\n\t    self.items.insert(0,item)\n\t\n   def dequeue(self):\n        return self.items.pop()\n\t\n   def size(self):\n        return len(self.items)\n\t\n\nq=Queue()\n#Create an object of Class Queue\n#Calling the functions\n\nq.enqueue(4)\nq.enqueue('dog')\nq.enqueue(True)\nprint(q.size())\n"
  },
  {
    "path": "Data Structures/Python/Stack/stack.py",
    "content": "\n#Make a class Stack\nclass Stack:\n   def __init__(self):\n\t         self.items = []\n\t\n\t  def isEmpty(self):\n\t         return self.items == []\n\t\n    def push(self, item):\n\t         self.items.insert(0,item)\n\t\n\t   def pop(self):\n\t         return self.items.pop(0)\n\t\n     def peek(self):\n\t         return self.items[0]\n           \n      def size(self):\n\t         return len(self.items)\n\t\n\t#Calling Object of class Stack\n  s = Stack()\n\t\n  #Calling the function\n  s.push('hello')\n\ts.push('true')\n\tprint(s.pop())\n"
  },
  {
    "path": "Data Structures/Python/Trees/m-coloring-problem.py",
    "content": "class Graph:\n    def __init__(self,m,v):\n        self.adj=m\n        self.V=v\n\ndef mColoring(k,m,g,x):\n\n    while(True):\n        \n        x[k]=getNodeColor(k,m,g,x)\n        if(x[k]==0):\n            return\n        if(k==g.V-1):\n            print(x) \n        else:\n            mColoring(k+1,m,g,x)\n    \ndef getNodeColor(k,m,g,x):\n\n    while(True):\n        \n        x[k]=(x[k]+1)%(m+1)   #bcoz any vertex should be assigned from 1 to m\n        \n        if(x[k]==0):\n            return x[k]\n\n        #checking for any collisions of color\n        for j in range(g.V):\n            if(g.adj[k][j]==1 and x[k]==x[j]):   #same color\n                break\n        else:\n            return x[k]\n            \n        \n\n\ndef main():\n    matrix=[[0,1,1,1],\n            [1,0,1,0],\n            [1,1,0,1],\n            [1,0,1,0] ]\n    g=Graph(matrix,4)\n\n    m=3  #Number of colors\n    x=[0 for i in range(g.V)]\n    mColoring(0,m,g,x)\n\nif __name__=='__main__':\n    main()\n\n\n'''\nPossible Coloring:\n[1, 2, 3, 2]\n[1, 3, 2, 3]\n[2, 1, 3, 1]\n[2, 3, 1, 3]\n[3, 1, 2, 1]\n[3, 2, 1, 2]\n'''\n"
  },
  {
    "path": "Dynamic Programing/Dynamic_fibonacci.py",
    "content": "# Function for nth fibonacci number - Dynamic Programing\n# Taking 1st two fibonacci nubers as 0 and 1\n \nFibArray = [0,1]\n \ndef fibonacci(n):\n    if n<0:\n        print(\"Incorrect input\")\n    elif n<=len(FibArray):\n        return FibArray[n-1]\n    else:\n        temp_fib = fibonacci(n-1)+fibonacci(n-2)\n        FibArray.append(temp_fib)\n        return temp_fib\n \n# Driver Program\n#Suppose we wan't to print the 9th fibonacci number\n#You can ask for user input and substitute in place of 9\n\nprint(fibonacci(9))\n"
  },
  {
    "path": "Dynamic Programing/Edit Distance.Py",
    "content": "memo={}\n\ndef DP(x,y,i,j):\n    if i>=len(x):\n        memo[(i,j)]=len(y)-j\n        return len(y)-j\n    if j>=len(y):\n        memo[(i,j)]=len(x)-i\n        return len(x)-i\n    if (i,j) in memo:\n        return memo[(i,j)]\n    if x[i]==y[j]:\n        memo[(i,j)]=min(DP(x,y,i,j+1),DP(x,y,i+1,j),DP(x,y,i+1,j+1))\n        return memo[(i,j)]\n    else:\n        res=1+min(DP(x,y,i,j+1),DP(x,y,i+1,j),DP(x,y,i+1,j+1))\n        memo[(i,j)]=res\n        return res\n\n\n'''Driver PRogram'''\nx='MICHAELANGELO'\ny='HIEROGLYPHOLOGY'\ns1='a'\ns2='ab'\nr=DP(x,y,0,0)\nprint(r)\n"
  },
  {
    "path": "Dynamic Programing/Knapsack.py",
    "content": "######'''Knapsack problem'''#####\n\nmemo={}\nincluded={}\ndef DP(val,s,i,x):\n    if i==len(val) or x==0:\n        return 0\n    if i in memo:\n        return memo[(i,x)]\n    #Not Possible to be added\n    if s[i]>x:\n        memo[(i,x)]=DP(val,s,i+1,x)\n        included[i]=0\n        return memo[(i,x)]\n    else:\n        #Not Added\n        if DP(val,s,i+1,x)>val[i]+DP(val,s,i+1,x-s[i]):\n            memo[(i,x)]=DP(val,s,i+1,x)\n            included[i]=0\n        #Added\n        else:\n            memo[(i,x)]=val[i]+DP(val,s,i+1,x-s[i])\n            included[i]=1\n        return memo[(i,x)]\n        \n\n'''Driver Program'''\nval=[4,10,2]\ns=[12,4,2]\nsize=15\nvalue=DP(val,s,0,size)\nprint('Maximum Value:',value)\nprint('Subset:',end=' ')\nfor i in included:\n    if included[i]:\n        print(val[i],end=' ')\n"
  },
  {
    "path": "Dynamic Programing/Memoized Cut Rod.Py",
    "content": "import math\nmemo={}\npiece={}\n\ndef cut_rod(p,n):\n    if n==0:\n        return 0\n    if n in memo:\n        return memo[n]\n    else:\n        q=-1\n        for i in range(1,n+1):\n            #q=max(q,p[i]+cut_rod(p,n-i))\n            if q<p[i]+cut_rod(p,n-i):\n                q=p[i]+cut_rod(p,n-i)\n                piece[n]=i\n        memo[n]=q\n        return q\n        \n'''Driver Program'''\np={1:1,2:5,3:8,4:9,5:10,6:17,7:17,8:20,9:24,10:30}\nn=5\ncut_rod(p,n)\n\nwhile(n>0):\n    print (piece[n])\n    n-=piece[n]\n"
  },
  {
    "path": "Dynamic Programing/Word_Wrap.Py",
    "content": "import math\nmemo={}\nparent={}\ndef badness(i,j,m):\n    totsize=0\n    extra=0\n    for x in range(i,j):\n        totsize+=len(ls[x])\n        extra+=1\n    totsize+=extra-1\n    if m>=totsize:\n        return ((m-totsize)**3)\n    else:\n        return math.inf\n\ndef minimum(i,ls,w,n):\n    p=[]\n    for j in range(i+1,n+1):\n        p+=[DP(j,ls,w,n)+badness(i,j,w)]\n    parent[i]=p.index(min(p))+i+1\n    return min(p)\n\ndef DP(i,ls,w,n):\n    if i in memo:\n        return memo[i]\n    if i==n:\n        parent[n]=None\n        return 0\n    else:\n        #t= min(DP(j,ls,w,n)+badness(i,j,w) for j in range(i+1,n+1))\n        t=minimum(i,ls,w,n)\n        memo[i]=t\n        return t\n\n'''Driver Code'''\n\ns='aaa bb cc ddddd'\nls=s.split()\nprint('Sample Text:',s)\nwords=len(ls)\nwidth=6\nDP(0,ls,width,words)\n\n#printing text\n\np=0\nwhile parent[p]!=None:\n    print(*ls[p:parent[p]])\n    p=parent[p]\n"
  },
  {
    "path": "Dynamic Programing/longest_increasing_subsequence.cpp",
    "content": "#include <iostream>\nusing namespace std;\nint longestIncreasingSubsequence(int A[],int size){\n    int dp[size];\n    for(int i=0;i<size;i++) dp[i] = 1;\n    for(int i=1;i<size;i++){\n        for(int j=0;j<i;j++){\n            if(A[j]<A[i]){\n                dp[i] = max(dp[i],dp[j]+1);\n            }\n        }\n    }\n    int lis = 0;\n    for(int i=0;i<size;i++) {\n    \tlis = max(lis,dp[i]);\n    }\n    \n    return lis;\n}\nint main() {\n\t\n\tint A[] = {1,3,5,9,8};\n\tcout<<longestIncreasingSubsequence(A,5);\n\treturn 0;\n}\n"
  },
  {
    "path": "Mathematical Challenges/C:C++/Fibonacci/Fibonacci Test.cpp",
    "content": "/*\nThis code illustrates an easier and faster way to check whether a number is\na Fibonacci Number or not.\n*/\n#include <iostream>\n#include <math.h>\nusing namespace std;\nint main()\n{\n    int num;                                //Number to be tested\n    float chk;\n    for (num = 1; num < 100 ; num++)\n    {\n        chk = sqrt(5*pow(num,2) + 4);\n        if(chk - (int)chk == 0)\n            cout<<num<<endl;\n        chk = sqrt(5*pow(num,2) - 4);\n        if(chk - (int)chk == 0)\n            cout<<num<<endl;\n    }\n    return 0;\n}\n"
  },
  {
    "path": "Mathematical Challenges/C:C++/Square Root Decomposition/MO's Algorithm/MOAlgo.cpp",
    "content": "//Problem : http://www.spoj.com/problems/DQUERY/\n//Time Complexity : O((n+q)*sqrt(n))\n\n#include <bits/stdc++.h>\n \n#define ll long long int\n#define mod 1000000007\n#define show(a) for(i=0;i<a.size();i++) cout<<a[i]<<\" \";\n#define fi first\n#define se second\n#define vi vector<int>\n#define vs vector<string>\n#define vll vector<long long int>\n#define pb push_back\n#define pi pair<int,int>\n#define si set<int>\n#define sll set<ll>\n#define maxheap priority_queue<int>\n#define minheap priority_queue<int,vector<int>,greater<int>>\n#define mp make_pair\n#define fast_io() cin.sync_with_stdio(false);cout.sync_with_stdio(false);\n#define long_zero 0ll\n#define long_one 1ll\ninline int sbt(int x){return __builtin_popcount(x);}\nusing namespace std;\nint freq[1111111];\nint BLOCK;\n//Mo Sorting\nbool f(pair<int,pi> a, pair<int,pi> b){\n    if(a.se.fi/BLOCK == b.se.fi/BLOCK)\n        return a.se.se>b.se.se;\n    return a.se.fi/BLOCK>b.se.fi/BLOCK;\n}\nint main() {\n    //fast_io()\n    int n;\n    scanf(\"%d\",&n);\n    int a[n+3];\n    for(int i=0;i<n;i++)\n        scanf(\"%d\",&a[i]);\n    int l,r,s=0,e=0;\n    int Q;\n    vector<pair<int,pi>>q;\n    scanf(\"%d\",&Q);\n    //block size:SQRT(N)\n    BLOCK = floor(sqrt(1.0*double(n)));\n    for(int i=0;i<Q;i++){\n        scanf(\"%d%d\",&l,&r);\n        q.pb(mp(i,mp(l-1,r-1)));\n    }\n    int v[Q+4],ans=0;\n    sort(q.begin(),q.end(),f);  //f is comparator\n\tfor(int i=0;i<Q;i++){\n\t    l=q[i].se.fi;\n\t    r=q[i].se.se;\n\t    while(s<l){\n\t        freq[a[s]]--;\n\t        if(!freq[a[s]])\n\t            ans--;\n\t        s++;\n\t    }\n\t    while(s>l){\n\t        freq[a[s-1]]++;\n\t        if(freq[a[s-1]]==1)\n\t            ans++;\n\t        s--;\n\t    }\n\t    while(e<=r){\n\t        freq[a[e]]++; // mantains frequency\n\t        if(freq[a[e]]==1)\n\t            ans++;\n\t        e++;\n\t    }\n\t    while(e>r+1){\n\t        freq[a[e-1]]--;\n\t        if(freq[a[e-1]]==0)\n\t            ans--;\n\t        e--;\n\t    }\n\t    v[q[i].fi]=ans;\n\t}\n\tfor(int i=0;i<Q;i++)\n\t    printf(\"%d\\n\",v[i]);\n\treturn 0;\n}\n"
  },
  {
    "path": "Mathematical Challenges/C:C++/armstrong_number/C/armstrong.c",
    "content": "#include<stdio.h>\r\n#include<math.h>\r\n\r\nint main(void)\r\n{\r\n\tint n,r,a=0,t,c=0,z;\r\n\tprintf(\"Enter a number: \");\r\n\tscanf(\"%d\",&n);\r\n\tt=n; z=n;\r\n\twhile(z>0)\r\n    {\r\n       z=z/10;\r\n       c++;\r\n    }\r\n\twhile(n>0)\r\n    {\r\n        r=n%10;\r\n        a=a+pow(r,c);\r\n        n=n/10;\r\n    }\r\n    if(a==t)\r\n        printf(\"\\nThe number is armstrong\\n\");\r\n    else printf(\"\\nThe number is not armstrong\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Mathematical Challenges/C:C++/armstrong_number/README.md",
    "content": "### Armstrong number\r\n\r\nGiven a number x, determine whether the given number is Armstrong number or not. A positive integer of n digits is called an Armstrong number of order n (order is number of digits) if :\r\n\r\n>**abcd... = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + ....**\r\n\r\n#### Example:\r\n\r\nInput : 1634 <br/>\r\nOutput : The number is armstrong <br/>\r\n1<sup>4</sup> + 6<sup>4</sup> + 3<sup>4</sup> + 4<sup>4</sup> = 1634\r\n"
  },
  {
    "path": "Mathematical Challenges/C:C++/convexHull/ConvexHullScan.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <set>\n#include <utility>\n#include <algorithm>\n\nusing namespace std;\n\n//This function decides if 3 points form a right turn or not\nbool Is_Right_Turn(vector <pair<int,int>> Hull){\n\tpair <int,int> P1, P2, P3;\n\tint Determinant;\n\n\t//P1, P2 and P3 are the last 3 points in the given Hull\n\tP1 = Hull[Hull.size() - 3];\n\tP2 = Hull[Hull.size() - 2];\n\tP3 = Hull[Hull.size() - 1];\n\n\t/*Cross Product is given by the determinant of the following 3x3 matrix - \n\t1    P1.x    P1.y\n\t1    P2.x    P2.y\n    1    P3.x    P3.y\n\t*/\n\tDeterminant = ((P2.first - P1.first) * (P3.second - P1.second) - (P2.second - P1.second) * (P3.first - P1.first));\n\n\t//Points form right turn only if the determinant is less than 0 (Equal to zero means colinear)\n\treturn (Determinant < 0);\n}\n\n\nint main(){\n\t#ifndef ONLINE_JUDGE\n    freopen(\"input.txt\", \"r\", stdin);\n    freopen(\"output.txt\", \"w\", stdout);\n\t#endif\n\n\tint Number_of_Points, X, Y, i;\n\n\tvector <pair<int,int>> Points, Upper_Hull, Lower_Hull;\n\n\tset <pair <int,int>> Convex_Hull;\n\n\tcin>>Number_of_Points;\n\n\t//Enter the points as (X,Y) coordinates\n\tfor(i = 0; i < Number_of_Points; i++){\n\t\tcin>>X>>Y;\n\t\tPoints.push_back(make_pair(X,Y));\n\t}\n\n\t//Sort the points first by X coordinate and then by Y coordinate\n\tsort(Points.begin(),Points.end());\n\n\t//Form the upper half of convex hull\n\tUpper_Hull.push_back(Points[0]);\n\tUpper_Hull.push_back(Points[1]);\n\n\tfor(i = 2; i < Number_of_Points; i++){\n\t\tUpper_Hull.push_back(Points[i]);\n\t\twhile(Upper_Hull.size() >= 3){\n\t\t\tif(Is_Right_Turn(Upper_Hull))\n\t\t\t\tbreak;\n\t\t\telse\n\t\t\t\t//Remove the middle point from the hull\n\t\t\t\tUpper_Hull.erase(Upper_Hull.end() - 2);\n\t\t}\n\t}\n\n\t//Form the lower half of the hull\n\tLower_Hull.push_back(Points[Number_of_Points - 1]);\n\tLower_Hull.push_back(Points[Number_of_Points - 2]);\n\n\tfor(i = Number_of_Points-3; i>= 0; i--){\n\t\tLower_Hull.push_back(Points[i]);\n\t\twhile(Lower_Hull.size() >= 3){\n\t\t\tif(Is_Right_Turn(Lower_Hull))\n\t\t\t\tbreak;\n\t\t\telse\n\t\t\t\t//Remove the middle point from the hull\n\t\t\t\tLower_Hull.erase(Lower_Hull.end() - 2);\n\t\t}\n\t}\n\n\t//Merge the Upper and Lower Hulls\n\tfor(auto &upper:Upper_Hull)\n\t\tConvex_Hull.insert(upper);\n\tfor(auto &lower:Lower_Hull)\n\t\tConvex_Hull.insert(lower);\n\n\t//Print the Convex Hull\n\tfor(auto &point:Convex_Hull)\n\t\tcout<<\"(\"<<point.first<<\", \"<<point.second<<\")\\n\";\n\n\treturn 0;\n\n}\n"
  },
  {
    "path": "Mathematical Challenges/C:C++/factorial/factorial.c",
    "content": "#include<stdio.h>\nint main(){\nint x;\nprintf(\"Enter the number\");\nscanf(\"%d\",&x);\n\nint fact=1;\n\nfor(fact=1;x>1;x--){\nfact=fact*x;\n}\nprintf(\"%d\",fact);\nreturn 0;\n\n\n\n\n}\n"
  },
  {
    "path": "Mathematical Challenges/C:C++/fibbinacci/fibbinacci.c",
    "content": "\n#include<stdio.h>\nint main(){\nint x,y,z;\nprintf(\"Enter the number\\n\");\nscanf(\"%d\",&x);\n\nint temp=0;\nfor(int i=0;i<=x;i++){\ntemp+=i;\n\n\n}\nprintf(\"%d\",temp);\n\n\nreturn 0;\n\n\n}\n"
  },
  {
    "path": "Mathematical Challenges/C:C++/gcd/extended_gcd.cpp",
    "content": "#include<bits/stdc++.h>\n\n#define F0(i,t) for(int i=0; i<t; i++)\n#define F1(i,t) for(int i=1; i<=t; i++)\n#define Si(x) scanf(\"%d\",&x)\n#define Si2(x,y) scanf(\"%d %d\",&x,&y)\n#define Sl(x) scanf(\"%lld\",&x)\n#define Sl2(x,y) scanf(\"%lld %lld\",&x,&y)\n#define dout if(debugg)cout<<\" \"\n\n   /* * * * * * * * * * * * * * * * * * * * * * * *\n    *                                             *\n    *            _/_/_/            _/             *\n    *         _/        _/  _/_/  _/_/_/          *\n    *          _/_/    _/_/      _/    _/         *\n    *             _/  _/        _/    _/          *\n    *      _/_/_/    _/        _/_/_/             * \n    *                                             *\n    * * * * * * * * * * * * * * * * * * * * * * * */\n\nusing namespace std;\n\ntypedef unsigned long long int ulli;\ntypedef unsigned int ui;\ntypedef pair<int,int> mp;\n\nint debugg = 0;\n\nstruct Res_gcd{\n    int gcd,x,y;\n    Res_gcd(int gcd, int x, int y){\n        this -> gcd = gcd;\n        this -> x   = x;\n        this -> y   = y;\n    }\n};\n/*\n * return object of Res_gcd\n * Res_gcd.gcd ==> gcd of a,b\n * Res_gcd.x and Res_gcd.y ==> x and y such that ax + by = gcd(a,b)\n * NOTE : a must not be 0 ==> if so ans is b,0,1 \n */\nRes_gcd gcd_extended(int a,int b){\n    if(b%a==0)\n        return Res_gcd(a,1,0);    //coz 1*a + 0*b = a { == gcd(a,b)}\n\n    Res_gcd temp = gcd_extended(b%a,a);\n    return Res_gcd( temp.gcd , temp.y - (b/a)*temp.x , temp.x );\n}\n\nint main(){\n\tint t=1;\n    ios_base::sync_with_stdio(0);cin.tie(0);\n    Res_gcd ans(1,1,1);\n\tcin>>t;\n\twhile(t--){\n        int a,b;\n        cin>>a>>b;\n        if(a==0)//fxn throw divide by 0 exception on a = 0\n            ans = Res_gcd(b,0,1);\n        else\n            ans = gcd_extended(a,b);\n        cout<<ans.gcd<<\" \"<<ans.x<<\" \"<<ans.y<<endl;\n\t}\n}\n// a code by srbcheema1\n"
  },
  {
    "path": "Mathematical Challenges/C:C++/gcd/gcd.cpp",
    "content": "#include<stdio.h>\n\n/*\n * be careful a must not be zero\n * if so then ans is b\n */\nint gcd(int a,int b){\n    if(b%a==0)\n        return a;\n    return gcd(b%a,a);\n}\n\nint main()\n{\n\tint t=1,a,b,ans;\n\tscanf(\"%d\",&t);\n\twhile(t--)\n\t{\n\t\tscanf(\"%d %d\",&a,&b);\n\t\tif(a==0)//gcd throw exception on a = 0\n\t        ans = b;\n\t    else ans=gcd(a,b);\n\t\tprintf(\"%d\\n\",ans);\n\t}\n\treturn 0;\n}\n"
  },
  {
    "path": "Mathematical Challenges/C:C++/gcd/mod_inverse.cpp",
    "content": "#include<bits/stdc++.h>\n\n#define F0(i,t) for(int i=0; i<t; i++)\n#define F1(i,t) for(int i=1; i<=t; i++)\n#define Si(x) scanf(\"%d\",&x)\n#define Si2(x,y) scanf(\"%d %d\",&x,&y)\n#define Sl(x) scanf(\"%lld\",&x)\n#define Sl2(x,y) scanf(\"%lld %lld\",&x,&y)\n#define dout if(debugg)cout<<\" \"\n\n   /* * * * * * * * * * * * * * * * * * * * * * * *\n    *                                             *\n    *            _/_/_/            _/             *\n    *         _/        _/  _/_/  _/_/_/          *\n    *          _/_/    _/_/      _/    _/         *\n    *             _/  _/        _/    _/          *\n    *      _/_/_/    _/        _/_/_/             * \n    *                                             *\n    * * * * * * * * * * * * * * * * * * * * * * * */\n\nusing namespace std;\n\ntypedef unsigned long long int ulli;\ntypedef unsigned int ui;\ntypedef pair<int,int> mp;\n\nint debugg = 0;\n\nstruct Res_gcd{\n    int gcd,x,y;\n    Res_gcd(int gcd, int x, int y){\n        this -> gcd = gcd;\n        this -> x   = x;\n        this -> y   = y;\n    }\n};\n/*\n * return object of Res_gcd\n * Res_gcd.gcd ==> gcd of a,b\n * Res_gcd.x and Res_gcd.y ==> x and y such that ax + by = gcd(a,b)\n * NOTE : a must not be 0 ==> if so ans is b,0,1 \n */\nRes_gcd gcd_extended(int a,int b){\n    if(b%a==0)\n        return Res_gcd(a,1,0);    //coz 1*a + 0*b = a { == gcd(a,b)}\n\n    Res_gcd temp = gcd_extended(b%a,a);\n    return Res_gcd( temp.gcd , temp.y - (b/a)*temp.x , temp.x );\n}\n\n/*\n * i created this function because in cpp\n * -1%7 give -1 not 6\n *  this fxn give +ve values for even -ve values of num\n */\nint modd(int num,int m){\n    return (num%m + m)%m;\n}\n/*\n *\n */\nint mod_inverse(int a,int m){\n    Res_gcd temp = gcd_extended(a,m);\n    if(temp.gcd != 1)\n        return -1;\n    else{\n        return modd(temp.gcd,m);\n    }\n}\n\nint main(){\n\tint t=1;\n    ios_base::sync_with_stdio(0);cin.tie(0);\n    Res_gcd ans(1,1,1);\n\tcin>>t;\n\twhile(t--){\n        int a,m;\n        cin>>a>>m;\n        cout<<mod_inverse(a,m)<<endl;\n\t}\n}\n// a code by srbcheema1\n"
  },
  {
    "path": "Mathematical Challenges/C:C++/largestoutof3/largestoutof3.c",
    "content": "#include<stdio.h>\nint main(){\nint x,y,z;\nprintf(\"Enter 1st number\");\nscanf(\"%d\",&x);\n\nprintf(\"Enter 2nd number\");\nscanf(\"%d\",&y);\n\nprintf(\"Enter 3rd number\");\nscanf(\"%d\",&z);\nint big=(x>y)?((x>z)?x:z):(y>z)?y:z;\nprintf(\"%d\",big);\n}\n"
  },
  {
    "path": "Mathematical Challenges/C:C++/mathpuzzle.c/matchstick game",
    "content": "//21 matchstick game in C\n#include <stdio.h>\nint main (int argc, const char * argv[])\n{\n    int matchstick = 21;\n    int user,computer;\n   \n    while (matchstick>=1)\n    {\n       \n        if (matchstick==1)\n        {\n            printf(\"\\nMatch stick status:%d\",matchstick);\n            printf(\"\\nYou loose!!!!!!:(:(\");             \n              break;\n        }\n       \n        printf(\"\\nMatch stick status:%d\",matchstick);       \n        printf(\"\\nEnter the choice (1,2,3,4)):\");       \n         scanf(\"%d\",&user);\n       \n        printf(\"\\nYou picked %d\",user);       \n        if (user>=5 || user <=0)\n        {\n            printf(\"\\nInvalid value\");            continue;\n        }\n       \n        computer = 5 - user;\n       \n        printf(\"\\nComputer picked%d\",computer);       \n        matchstick = matchstick - computer - user;\n       \n    }\n    return 0;\n}\n"
  },
  {
    "path": "Mathematical Challenges/C:C++/multiplication/multiply 2 numbers greater than 10^6.cpp",
    "content": "/*\nThis program can be used to multiply 2 numbers grater than 10^5, usually a major hurdle in languages like C/C++\nin competitive programming, using this as a template one can perform implementations like Factorials of 100 etc\n*/\n\n#include <iostream>\nusing namespace std;\nint main()\n\t{\n\t\tios_base::sync_with_stdio(false);\n\t\tint n1, n2;\n\t\tcin>>n1>>n2;\n\t\tint c = 0, ans[100000] = {0}, i = 0, basei = 0, temp = n2, dig = 0, tmp;\n\t\twhile(n1)\n\t\t    {\n\t\t        if(n2)\n\t\t            {\n\t\t                c = ( (n1%10)*(n2%10) );\n\t\t                ans[i] += c;\n\t\t                if(ans[i]>9)\n\t\t                    {\n\t\t                        ans[i+1] += ans[i]/10;\n\t\t                        ans[i] = ans[i]%10;\n\t\t                    }\n\t\t                c /= 10;\n\t\t                n2 /= 10;\n\t\t                dig++;\n\t\t                i++;\n\t\t            }\n                else\n                    {\n                        tmp = dig;\n                        n2 = temp;\n                        n1 /= 10;\n                        i = ++basei;\n                        c=0;\n                        dig = basei;\n                    }\n\t\t    }\n        for(int k = tmp-1 ;k>=0;k--)\n            cout<<ans[k];\n\t\treturn 0;\n}\n"
  },
  {
    "path": "Mathematical Challenges/C:C++/power/modular_exponention.cpp",
    "content": "#include<bits/stdc++.h>\n#define ui unsigned long long int\n#define mod 1000000007\nusing namespace std;\n\n//faster wayy to calc (b^p)%mod in log(p) \n//it is fast as it dont use recursion\nui modular_expo_no_rec(int base,int p){\n    ui ans = 1,fact = base;\n    while(p){\n        if(p & 1)\n            ans = (ans * fact)%mod;\n        fact = (fact * fact)%mod;\n        p = p>>1;\n    }\n    return ans%mod;\n}\n\n//return (b^p)%mod in log(p)\nui modular_expo_rec(ui b,ui p){\n    if(p==1) return b;\n    \n    ui temp = modular_expo_rec(b,p/2);\n    temp = (temp*temp)%mod;\n    \n    if(p & 1)//odd\n        return (temp * b)%mod;\n    else return temp;\n}\n\nint main(){\n    int t,base,pow;\n    ui ans;\n    cin>>t;\n    while(t--){\n        cin>>base>>pow;\n        cout<<modular_expo_no_rec(base,pow)<<endl;\n    }\n}\n"
  },
  {
    "path": "Mathematical Challenges/C:C++/power/ques/summation.cpp",
    "content": "//http://www.spoj.com/problems/SUMMATION/\n#include<bits/stdc++.h>\n#define ui unsigned long long int\n#define mod 100000007\n\nusing namespace std;\n\nui two_pow(int n){\n    ui ans = 1,fact = 2;\n    while(n){\n        if(n & 1)\n            ans = (ans * fact)%mod;\n        fact = (fact * fact)%mod;\n        n = n>>1;\n    }\n    return ans%mod;\n}\n\n//return b^p\nui modular_expo(ui b,ui p){\n    if(p==1) return b;\n    if(p & 1)\n        return ((modular_expo(b,p/2)*modular_expo(b,p/2))%mod * b)%mod;\n    else return (modular_expo(b,p/2)*modular_expo(b,p/2))%mod;\n}\n\nint main(){\n    int t,n;\n    ui ans=0,pow,sum,a;\n    cin>>t;\n    for (int i=1;i<=t;i++){\n        sum=0;\n        cin>>n;\n        pow = modular_expo(2,n-1);\n        while(n--){\n            cin>>a;\n            sum+=a;\n        }\n        sum=sum%mod;\n        ans = (sum*pow)%mod;\n        cout<<\"Case \"<<i<<\": \"<<ans<<endl;\n    }\n}\n"
  },
  {
    "path": "Mathematical Challenges/C:C++/power/two_pow.cpp",
    "content": "#include<bits/stdc++.h>\n\n#define F0(i,t) for(int i=0; i<t; i++)\n#define F1(i,t) for(int i=1; i<=t; i++)\n#define Si(x) scanf(\"%d\",&x)\n#define Si2(x,y) scanf(\"%d %d\",&x,&y)\n#define Sl(x) scanf(\"%lld\",&x)\n#define Sl2(x,y) scanf(\"%lld %lld\",&x,&y)\n#define dout if(debugg)cout<<\" \"\n\n   /* * * * * * * * * * * * * * * * * * * * * * * *\n    *                                             *\n    *            _/_/_/            _/             *\n    *         _/        _/  _/_/  _/_/_/          *\n    *          _/_/    _/_/      _/    _/         *\n    *             _/  _/        _/    _/          *\n    *      _/_/_/    _/        _/_/_/             * \n    *                                             *\n    * * * * * * * * * * * * * * * * * * * * * * * */\n\nusing namespace std;\n\ntypedef unsigned long long int ulli;\ntypedef unsigned int ui;\ntypedef pair<int,int> mp;\n\nint debugg = 0;\n\nint two_pow(int p){\n    int ans = 1,fact =2;\n    while(p){\n        if( p&1 )//p is odd\n            ans = ans * fact;\n        fact = fact * fact;\n        p = p>>1;\n    } \n    return ans;\n}\n\nint main(){\n\tint t=1;\n    ios_base::sync_with_stdio(0);cin.tie(0);\n\tcin>>t;\n\twhile(t--){\n        int p;\n        cin>>p;\n        cout<<two_pow(p)<<endl;\n\t}\n}\n// a code by srbcheema1\n"
  },
  {
    "path": "Mathematical Challenges/C:C++/powerset/PowerSet.java",
    "content": "import java.util.*;\npublic class PowerSet {\n    \n        public static <T> Set<Set<T>> powerSet( Set<T> set ) {\n            T[] element = (T[]) set.toArray();\n            final int SET_LENGTH = 1 << element.length;\n            Set<Set<T>> powerSet = new HashSet<>();\n            for( int binarySet = 0; binarySet < SET_LENGTH; binarySet++ ) {\n                Set<T> subset = new HashSet<>();\n                for( int bit = 0; bit < element.length; bit++ ) {\n                    int mask = 1 << bit;\n                    if( (binarySet & mask) != 0 ) {\n                        subset.add( element[bit] );\n                    }\n                }\n                powerSet.add( subset );\n            }\n            return powerSet;\n        }\n    \n        public static void main(String[] args) {\n            Set<Character> test = new HashSet<>();\n            test.add( 'a' );\n            test.add( 'b' );\n            test.add( 'c' );\n            System.out.println(\"test = \" + test);\n            Set<Set<Character>> result = powerSet( test );\n            System.out.println( result );\n        }\n    }"
  },
  {
    "path": "Mathematical Challenges/C:C++/prime/PrimeCheck.py",
    "content": "#Simple way to check for primes using Pyton.\n\n#Prompt user for a integer\nNumber = int(input(\"Enter any integer to check if prime number \"))\n#Set starting divisor to 2\nDivisor = 2\nfor Divisor in range (Divisor, Number) : #Test every number between 2 and the integer\n        if Number % Divisor == 0:\n            prime = False # Tell computer to make prime false\n            break #End loop\n        Divisor += 1 #Add 1 to the divisor\n            \nelse:\n    prime = True # If number % divisor does not equal 0, number must be a prime, so mark as true\n#Print results\nif prime == True :\n    print(\"Your number is a prime\")\nif prime == False :\n    print(\"Your number is not a prime\")\n"
  },
  {
    "path": "Mathematical Challenges/C:C++/prime/PrimeToNumber.py",
    "content": "#Python Prime checker. Not the most efficient way to check for primes, but very easy to code!\n\nnum = int(input(\"Enter a integer to get primes up to \")) #Get highest number for prime\ndiv=2 #Set divisor to intitally 2\nfor num in range(2,num): #Check if prime\n    prime = True #If prime is true set flag.\n    for div in range(2,num): #If number can be divided by any number, from 2 to the number-1\n        if (num % div == 0):#If evenly divided, the number will therefore be notprime.\n            prime = False #set prime to false\n    if prime: \n       print (num)\n"
  },
  {
    "path": "Mathematical Challenges/C:C++/prime/prime.c",
    "content": "#include<stdio.h>\nint main(){\nint x,y,z;\nprintf(\"Enter the number\\n\");\nscanf(\"%d\",&x);\ny=x/2;\nif(x%2==0 && x!=2){\nprintf(\"It is not a  prime\\n\");\n}\n\nelse{\nfor(z=3;z<=y;z++)\n{\n\nif(x%z==0){\nprintf(\"it is not a prime number \");\n}\nelse{\nprintf(\"it is a  prime\");\nbreak;\n}\n\n}\n\n\n\n\n\nreturn 0;\n\n\n}\n"
  },
  {
    "path": "Mathematical Challenges/C:C++/prime/sieveOferatosthenes.cpp",
    "content": "#include <iostream>\n#include <vector>\nusing namespace std;\nvoid sieve_of_eratosthenes(std::vector<int>& primes, const int max) {\n\tvector<bool> isPrime;\n\t// Initially, all the numbers are considered to be prime\n\tfor (int i = 0; i <= max; i++) {\n\t\tisPrime.push_back(true);\n\t}\n\t// 0 and 1 are obviously not prime, so we set it in the isPrime vector\n\tisPrime[0] = isPrime[1] = false;\n\n\t// Iterate from 2 up to the square root of max\n\tfor (int i = 2; i*i <= max; i++) {\n\t\tif (isPrime[i]) {\n\t\t\t// If the current number is prime, then set i^2, i^2+i, i^2+2i, ... as not prime\n\t\t\tfor (int j = i * i; j <= max; j += i) {\n\t\t\t\tisPrime[j] = false;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Iterate from 2 to max again. All the numbers, that are still set to true, are prime\n\tfor (int i = 2; i <= max; i++) {\n\t\tif (isPrime[i]) {\n\t\t\tprimes.push_back(i);\n\t\t}\n\t}\n}\n\nint main() {\n\tint n = 100;\n\tvector<int> primes;\n\t// Find primes up to n\n\tsieve_of_eratosthenes(primes, n);\n\tcout << \"Primes up to \"<<n<<\" are:\"<<endl;\n\tfor (auto prime : primes) {\n\t\tcout << prime << \" \";\n\t}\n\treturn 0;\n}\n"
  },
  {
    "path": "Mathematical Challenges/C:C++/prime number tricks/List all primes.cpp",
    "content": "/*\nThis code illustrates that all primes are of the form (6k +- 1)\nPlease note this also includes some non-prime numbers such as 25 (6*4 + 1)\nBut ALL primes greater than 2 and 3 are included in this form and the non-primes\ncan be weeded out with a simple IF statement.\nIf the user needs to operate on (lets say 100) primes, instead of doing primality test on\nall 1 to 100 numbers it will only have to test on 34 numbers.\n*/\n\n#include <iostream>\nusing namespace std;\nint main()\n{\n    int numofprimes = 10, prime;\n    for (int i = 2; i<numofprimes; i++)\n    {\n        prime = ((6*i) - 1);\n        cout<<prime<<endl;\n        prime = ((6*i) + 1);\n        cout<<prime<<endl;\n    }\n    return 0;\n}\n"
  },
  {
    "path": "Mathematical Challenges/C:C++/ques/cpcrc1c.cpp",
    "content": "//http://www.spoj.com/problems/CPCRC1C/\n#include<bits/stdc++.h>\n#define ui unsigned long long int\n\nusing namespace std;\n\nui arr[10]={0,1,3,6,10,15,21,28,36,45};\nui sum[11];\n\nui sum_of_digits(string str){\n    ui ans =0;\n    for(int i=0;i<str.length();i++)\n        ans+=str[i]-'0';\n    return (ui)ans;\n}\n\nui digit_sum(string str){\n    ui ans;\n    ui len = str.length();\n    if(len==1){\n        return arr[str[0]-'0'];\n    }\n    string left = str.substr(0,len-1);\n    if(str[len-1]=='9'){\n        ui n = stoi(str);\n        ans = ((n+1)/10)*45 + digit_sum(left)*10;\n        return ans;\n    }\n    else{\n        ui d = (str[len-1]-'0');\n        ans = (d+1)*sum_of_digits(left)+digit_sum(str.substr(len-1,1));\n        ans += digit_sum(to_string(stoi(str)-d-1));\n        return ans;\n    }\n}\n\nint main(){\n    int a,b;\n    string aa,bb;\n    ui ans_a,ans_b;\n    cin>>a>>b;\n    while(a>=0){\n        if(a==0)a++;\n        aa=to_string(a-1);\n        bb=to_string(b);\n        \n        ans_a=digit_sum(aa);\n        ans_b=digit_sum(bb);\n//        cout<<ans_b<<\" \"<<ans_a<<\" \";\n        cout<<ans_b-ans_a<<endl;\n        cin>>a>>b;\n    }\n}\n"
  },
  {
    "path": "Mathematical Challenges/python/pernicious_prime/pernicious.py",
    "content": "'''This is a proposed brute force algorithm writtem in python \nto test whether a given input positive integer other than 1 and 2 \nis a pernicious prime or not''' \n\n#OUTPUT FORMAT :- if pernicious number , output yes else no \n#INPUT FORMAT  :- A positive integer other than 1 and 2  \n\n'''According to number theory , a positive number is pernicious number if \nsum of the digit of this number in binary form is prime'''\n\n'''Basic Outline Of Algorithm:- We count the set bits of a number and check \nwhether that count is prime or not'''\n\n\n#################### Overall complexity is O(sqrt(n)*log(n))  ############################\n\nimport math\n\n\ndef isprime(num): #function to check whether a number is prime or not \n\n#A simple solution is to iterate through all numbers from 2 to n-1 \n#and for every number check if it divides n. If we find any number that \n#divides, we return false. We can do following optimizations:\n#Instead of checking till n, we can check till sqrt(n) because a larger \n#factor of n must be a multiple of smaller factor that has been already \n#checked.The algorithm can be improved further by observing that all \n#primes are of the form 6k + 1 or 6k - 1, with the exception of 2 and 3. \n#This is because all integers can be expressed as (6k + i) for some \n#integer k and for i = -1, 0, 1, 2, 3, or 4.This is because since 2 \n#divides (6k + 0), (6k + 2), (6k + 4); and 3 divides (6k + 3). So a more \n#efficient method is to test if n is divisible by 2 or 3, then to check \n#through all the numbers of form 6k + 1 or 6k - 1\t\n\t\n        if num<3 or num==3:\n\t\treturn 1\n\tif num%2==0 or num%3==0:\n\t\treturn 0\n\tfor i in range(5,int(math.sqrt(num))+1,6):\n\t\tif num%i==0 or num%(i+2)==0:\n\t\t\treturn 0\n\treturn 1\t\t########## O(sqrt(n))\t\t\n\ndef count_ones(num): #function to calculate the number of set bits in a number\n\n#Loop through all bits in an integer, check if a bit is set and if it is \n#then increment the set bit count. But we can also do it in more efficient way :- \n#Subtraction of 1 from a number toggles all the bits (from right to left) till \n#the rightmost set bit(including the righmost set bit). So if we subtract a \n#number by 1 and do bitwise & with itself (n & (n-1)), we unset the righmost \n#set bit. If we do n & (n-1) in a loop and count the no of times loop executes \n#we get the set bit count.Beauty of the this solution is number of times it loops \n#is equal to the number of set bits in a given integer.\n\tcount=0\n\twhile num:\n\t\tnum = (num&(num-1))\n\t\tcount+=1\n\n\treturn count\t########## O(log(n))\n\nwhile 1:\n\n\tnum = input(\"Enter any positive integer: \") #other than 1 and 2 \n\tif num!=1 and num!=2:\n\n\t\ttotal_set_bits = count_ones(num) #since sum of set bits is equivalent to counting those bits \n\t\tflag=isprime(total_set_bits)\n\t\tif flag==1:\n\t\t\tprint \"yes\\n\"\n\t\telse:\n\t\t\tprint \"no\\n\"\t\n\telse:\n\t\tprint \"Please enter any number other tha 1 or 2\\n\"\n"
  },
  {
    "path": "Mathematical Challenges/python/sieve_of_eratoshthenes.py",
    "content": "import sys\nimport array\nimport math\nisprime=array.array('i',(0 for i in range(0,1001)))\ndef sieve():\n    for i in range(2,math.sqrt(1000)):\n        for j in range(2,sys.maxsize**10):\n            if(i*j >1000):\n                break\n            isprime[i*j]=1\nsieve()\nn=int(input())\nfor i in range(2,n+1):\n    if(isprime[i] is 0):\n        print(i,end=\" \")"
  },
  {
    "path": "Patterns/pattern10.cpp",
    "content": "#include <iostream>\nusing namespace std;\n\nint main(){\n\n\tint n;\n\tcin >> n;\n\n\tint count = 1;\n\n\tchar spaces = ' ';\n\tfor( int i = 1; i <= n; i++ ){\n\t\tfor( int j = n - i; j > 0; j-- ){\n\t\t\tcout << spaces;\n\t\t}\n\t\tfor( int j = 1; j <= i; j++ ){\n\t\t\tcout << count;\n\t\t\tcount++;\n\t\t}\n\t\tcout << endl;\n\t}\n\n    return 0;\n\n}\n\n/*\n4\n\n    1\n   23\n  456\n78910\n\n*/\n\n"
  },
  {
    "path": "Patterns/pattern11.cpp",
    "content": "#include <iostream>\nusing namespace std;\n\nint main(){\n\n\tint n;\n\tcin >> n;\n\n\tint count = 1;\n\n\tchar spaces = ' ';\n\tfor( int i = 1; i <= n; i++ ){\n\t\tfor( int j = n - i; j > 0; j-- ){\n\t\t\tcout << spaces;\n\t\t}\n\t\tfor( int j = 1; j <= i; j++ ){\n\t\t\tcout << count << \" \";\n\t\t\tcount++;\n\t\t}\n\t\tcout << endl;\n\t}\n\n    return 0;\n\n}\n\n/*\n4 \n\n\n     1\n    2 3\n   4 5 6\n 7 8 9 10\n\n*/\n"
  },
  {
    "path": "Patterns/pattern12.cpp",
    "content": "#include <iostream>\nusing namespace std;\n\nint main(){\n\n\tint n;\n\tcin >> n;\n\n\tint count = 1;\n\n\tchar spaces = ' ';\n\tfor( int i = 1; i <= n; i++ ){\n\t\tfor( int j = 1; j < i; j++ ){\n\t\t\tcout << spaces;\n\t\t}\n\t\tfor( int j = n; j >= i; j-- ){\n\t\t\tcout << count << \" \";\n\t\t\tcount++;\n\t\t}\n\t\t\n\t\tcout << endl;\n\t}\n\n    return 0;\n\n}\n\n/*\n3 \n\n 1 2 3\n  4 5\n   6\n\n*/\n"
  },
  {
    "path": "Patterns/pattern13.cpp",
    "content": "#include <iostream>\nusing namespace std;\n\nint main(){\n\n\tint n;\n\tcin >> n;\n\tint count = 1;\n\n\tchar spaces = ' ';\n\tfor( int i = 1; i <= n; i++ ){\n\t\tfor( int j = 1; j < i; j++ ){\n\t\t\tcout << spaces;\n\t\t}\n\t\tfor( int j = n; j >= i; j-- ){\n\t\t\tcout << count;\n\t\t\tcount++;\n\t\t}\n\t\tcout << endl;\n\t}\n\n    return 0;\n\n}\n\n/* \n3 \n \n123\n 45\n  6\n\n*/\n"
  },
  {
    "path": "Patterns/pattern14.cpp",
    "content": "#include <iostream>\nusing namespace std;\n\nint main(){\n\n\tint n;\n\tcin >> n;\n\n\tint count = 1;\n\n\tchar spaces = ' ';\n\tfor( int i = 1; i <= n; i++ ){\n\t\tfor( int j = n - i; j > 0; j-- ){\n\t\t\tcout << spaces;\n\t\t}\n\t\tfor( int j = 1; j <= i; j++ ){\n\t\t\tcout << count << \" \";\n\t\t\tcount++;\n\t\t}\n\t\tcout << endl;\n\t}\n\tcount--;\n\tfor( int i = 1; i <= n; i++ ){\n\t\tfor( int j = 1; j < i; j++ ){\n\t\t\tcout << spaces;\n\t\t}\n\t\tfor( int j = n; j >= i; j-- ){\n\t\t\tcount--;\n\t\t\tcout << count << \" \";\n\t\t}\n\t\tcout << endl;\n\t}\n\n    return 0;\n\n}\n\n/*\n4\n\n       1\n      2 3\n     4 5 6\n    7 8 9 10\n     6 5 4\n      3 2\n       1\n\n*/\n"
  },
  {
    "path": "Patterns/pattern15.cpp",
    "content": "#include <iostream>\nusing namespace std;\n\nint main(){\n\n\tint n;\n\tcin >> n;\n\n\tint count = 1;\n\n\tchar spaces = ' ';\n\tfor( int i = 1; i <= n; i++ ){\n\t\tfor( int j = n - i; j > 0; j-- ){\n\t\t\tcout << spaces;\n\t\t}\n\t\tfor( int j = 1; j <= i; j++ ){\n\t\t\tcout << count << \" \";\n\t\t\tcount++;\n\t\t}\n\t\tcout << endl;\n\t}\n\tfor( int i = 1; i <= n; i++ ){\n\t\tfor( int j = 1; j < i; j++ ){\n\t\t\tcout << spaces;\n\t\t}\n\t\tfor( int j = n; j >= i; j-- ){\n\t\t\tcout << count;\n\t\t\tcount++;\n\t\t}\n\t\tcout << endl;\n\t}\n\n    return 0;\n\n}\n\n/*\n4\n\n    1\n   2 3\n  4 5 6\n 7 8 9 10\n 11 12 13\n   14 15\n    16\n\n*/\n"
  },
  {
    "path": "Patterns/pattern16.cpp",
    "content": "#include <iostream>\nusing namespace std;\n\nint main(){\n\n\tint n;\n\tcin >> n;\n\n\tint count = 1;\n\n\tchar spaces = ' ';\n\tfor( int i = 1; i <= n; i++ ){\n\t\tfor( int j = n - i; j > 0; j-- ){\n\t\t\tcout << spaces;\n\t\t}\n\t\tfor( int j = 1; j <= i; j++ ){\n\t\t\tcout << count << \" \";\n\t\t\tcount++;\n\t\t}\n\t\tcout << endl;\n\t}\n\tcount--;\n\tfor( int i = 1; i <= n-1; i++ ){\n\t\tfor( int j = 1; j <= i; j++ ){\n\t\t\tcout << spaces;\n\t\t}\n\t\tfor( int j = n-1; j >= i; j-- ){\n\t\t\tcount--;\n\t\t\tcout << count << \" \";\n\t\t}\n\t\tcout << endl;\n\t}\n\n    return 0;\n\n}\n"
  },
  {
    "path": "Patterns/pattern8.cpp",
    "content": "#include <iostream>\nusing namespace std;\n\nint main(){\n\tint n;\n\tcin >> n;\n\n\tint count = 1;\n\tfor( int i = 0; i < n; i++ ){\n\t\tfor( int j = 0; j <= i; j++ ){\n\t\t\tif ( n < count){\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tcout << count << \" \";\n\t\t\tcount++;\n\t\t}\n\t\tcout << endl;\n\t}\n\tcout << endl;\n    return 0;\n\n}\n\n/*\n10 \n\n1\n23\n456\n78910\n\n*/\n"
  },
  {
    "path": "Patterns/pattern9.cpp",
    "content": "#include <iostream>\nusing namespace std;\n\nint main(){\n\n\tint n;\n\tcin >> n;\n\n\tchar spaces = ' ';\n\tfor( int i = 1; i <= 5; i++ ){\n\t\tfor( int j = n - i; j > 0; j-- ){\n\t\t\tcout << spaces;\n\t\t}\n\t\tfor( int j = 1; j <= i; j++ ){\n\t\t\tcout << i;\n\t\t}\n\t\tcout << endl;\n\t}\n\n    return 0;\n\n}\n\n/*\n5\n\n    1\n   22\n  333\n 4444\n55555\n\n*/\n"
  },
  {
    "path": "README.md",
    "content": "# Algo_Ds\n\n\n## Overview:\nThis repo is a conglomeration of algorithms for competitive programming, data structure, sorting and related areas. It currently features C/C++, Python and some Java implementations. It contains many advanced algorithms like greedy, graph traversal algorithms, including Dijkstra's algorithm and Floyd Warshal algorithm, and data structures like queues, stacks, and binary search trees.\n\nUse this repo to study or review your knowledge and don't forget to star and collaborate!\n\n## Contents:\n\n### Search Algorithms\n - Linear Search\n - binary search\n - Ternary search\n\n### Sorting Algorithms\n\n - Bubble Sort\n - Selection Sort\n - Insertion sort\n - Merge sort\n - Quick sort\n - Radix sort\n - Bogo sort\n\n### Shortest Path Algorithms\n\n - Dijkstra\n - Floyd Warshall\n\n### Common Data Structures\n\n - heap\n - queue\n - stack\n - Array\n - Linked List\n\n## Languages Used:\n\n - C/C++\n - Python\n - Java \n - More to come\n\n## How to contribute:\n\nPlease comment your code thoroughly as to make it possible for anyone to understand.\nIf possible, check your code using unit tests. \nAvoid all the bad implementations, make your code as clean as possible.\nAfter that, find the folder that fits the category of your code and submit a PR.\n*Star* this repo if the information here is useful to you.\n\n### Please have a look at these :\n - [CONTRIBUTING.md](https://github.com/srbcheema1/Algo_Ds/blob/master/CONTRIBUTING.md) for quick quidelines\n - [STRUCTURE.md](https://github.com/srbcheema1/Algo_Ds/blob/master/STRUCTURE.md) for structure of directories\n"
  },
  {
    "path": "STL C++/STACK_with_Application/Evaluating Postfix Expression.c",
    "content": "#include <stdio.h>\r\n#include <string.h>\r\n#define MAX 200\r\n\r\nint isoperator(char c){\r\n\treturn (c=='*' || c=='/' || c=='+' || c=='-');\r\n}\r\n\r\nstruct stack\r\n{\r\n\tint top;\r\n\tdouble a[MAX];\r\n}s;\r\n\r\nvoid push(double c){\r\n\ts.a[++s.top]=c;\r\n}\r\n\r\ndouble pop(){\r\n\treturn s.a[s.top--];\r\n}\r\n\r\ndouble perform(double a, double b, char c){\r\n\tif (c=='*')\r\n\t{\r\n\t\treturn a*b;\r\n\t}\r\n\telse if (c=='+')\r\n\t{\r\n\t\treturn a+b;\r\n\t}\r\n\telse if (c=='/')\r\n\t{\r\n\t\treturn a/b;\r\n\t}\r\n\telse return a-b;\r\n}\r\n\r\nvoid post_infix(char a[],int l){\r\n\tint i;\r\n\tfor(i=0;i<l;i++){\r\n\t\tif (isoperator(a[i]))\r\n\t\t{\r\n\t\t\tdouble sec = pop(); \r\n\t\t\t//printf(\"%f\",sec);\r\n\t\t\tdouble fir = pop(); \r\n\t\t\t//printf(\"%f\",fir);\r\n\t\t\tdouble res = perform(fir,sec,a[i]); \r\n\t\t\t//printf(\"%f\",res);\r\n\t\t\tpush(res);\r\n\t\t}\r\n\t\telse{\r\n\t\t\tpush(a[i]-'0');\r\n\t\t}\r\n\t}\r\n}\r\n\r\nint main()\r\n{\r\n\tprintf(\"Enter a postfix expression :\\n\");\r\n\tchar post[100];\r\n\ts.top=-1;\r\n\tscanf(\"%s\",post);\r\n\tint n=strlen(post);\r\n\tpost_infix(post,n);\r\n\tprintf(\"%f\",s.a[s.top]);\r\n\treturn 0;\r\n}\r\n"
  },
  {
    "path": "STL C++/STACK_with_Application/Infix to Postfix.c",
    "content": "#include<stdio.h>\r\n\r\nint j;\r\nstruct temp{\r\n\tchar a[200];\r\n\tint top;\r\n};\r\nstruct temp s;\r\n\r\nvoid push(char item){\r\n\ts.a[++s.top]=item;\r\n}\r\n\r\nint isempty(){\r\n\treturn s.top==-1;\r\n}\r\n\r\nchar pop(){\r\n\tif(!isempty())return s.a[s.top--];\r\n}\r\n\r\nint isoperator(char c){\r\n\tif(c=='*'||c=='/'|| c=='+'|| c=='-')return 1;\r\n\treturn 0;\r\n}\r\nint precedence(char c){\r\n\tif(c=='+' || c=='-')return 1;\r\n\telse if(c=='*' || c=='/')return 2;\r\n\telse if(c=='^')return 3;\r\n\treturn 0;\r\n}\r\nchar *infix_postfix(char *p){\r\n\tint i;\r\n\tj=0;\r\n\tchar *p1 = (char *)malloc(100*sizeof(char));\r\n\tfor(i=0;p[i]!='\\0';i++){\r\n\t\t//printf(\"%d\\n\",j);\r\n\t\tif(isalpha(p[i]) || isdigit(p[i])){\r\n\t\t\tp1[j++]=p[i];\r\n\t\t}\r\n\t\telse if(isoperator(p[i])){//printf(\"%c\\n\",p[i]);\r\n\t\t\twhile(!isempty() && /*s.a[s.top]!='(' &&*/ (precedence(p[i]) <= precedence(s.a[s.top]))){\r\n\t\t\t\tp1[j++] = s.a[s.top];\r\n\t\t\t\tpop();\r\n\t\t\t}\t\r\n\t\t\tpush(p[i]);\r\n\t\t}\r\n\t\telse if(p[i]=='(')push(p[i]);\r\n\t\telse if(p[i]==')'){\r\n\t\t\twhile(!isempty() && s.a[s.top]!='('){\r\n\t\t\t\tp1[j++]=s.a[s.top];\r\n\t\t\t\tpop();\r\n\t\t\t}\r\n\t\t\tpop();\r\n\t\t}\r\n\t}\r\n\twhile(!isempty()){\r\n\t\t//printf(\"%c \",s.a[s.top]);\r\n\t\tp1[j++]=s.a[s.top];\r\n\t\tpop();\r\n\t}\r\n\t//for(i=0;i<j;i++)printf(\"%c\",p[i]);\r\n\treturn p1;\r\n}\r\n\r\nint main(){\r\n\ts.top = -1;\r\n\tchar *p = (char *)malloc(100*sizeof(char));\r\n\twhile(1){\r\n\t\tprintf(\"Enter expression : \\n\");\r\n\t\tgets(p);\r\n\t\tchar *p1 = infix_postfix(p);\r\n\t\t//infix_postfix(exp);\r\n\t\tint i;\r\n\t\tfor(i=0;i<j;i++)printf(\"%c\",p1[i]);\r\n\t\tprintf(\"\\n\");\r\n\t}\r\n\treturn 0;\r\n}\r\n"
  },
  {
    "path": "STL C++/STACK_with_Application/balance parenthesis.cpp",
    "content": "#include<iostream>\r\n#include<bits/stdc++.h>\r\n#include<string.h>\r\n#include<stack>\r\nusing namespace std;\r\n\r\nint main(){\r\n\tstring str;\r\n\tprintf(\"Enter a String\");\r\n\tcin>>str;\r\n\tint l = str.length();\r\n\tstack <char> s;\r\n\tfor(int i=0;i<l;i++){\r\n\t\tif(str[i]=='{' || str[i]=='[' || str[i]=='('){\r\n\t\t\ts.push(str[i]);\r\n\t\t}\r\n\t\telse if(str[i]=='}' || str[i]==']' || str[i]==')'){\r\n\t\t\tif(s.empty()){\r\n\t\t\t\tprintf(\"\\nNot Balanced\\n\");\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t\telse{\r\n\t\t\t\tif(str[i]=='}' && s.top()=='{'){\r\n\t\t\t\t\ts.pop();\r\n\t\t\t\t}\r\n\t\t\t\telse if(str[i]==']' && s.top()=='['){\r\n\t\t\t\t\ts.pop();\r\n\t\t\t\t}\r\n\t\t\t\telse if(str[i]=='(' && s.top()==')'){\r\n\t\t\t\t\ts.pop();\r\n\t\t\t\t}\r\n\t\t\t\telse{\r\n\t\t\t\t\tprintf(\"\\nNot Balanced\\n\");return false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif(s.empty()){\r\n\t\tprintf(\"\\nBalanced\\n\");\r\n\t}\r\n\telse{\r\n\t\tprintf(\"\\nNot Balanced\\n\");\r\n\t}\r\n}\r\n"
  },
  {
    "path": "STL C++/STACK_with_Application/stack_and_its_implementation.c",
    "content": "//Auhor : VIVEK SHAH\r\n/*Performs Push, Pop, Peep and Displays elements of Stack*/\r\n\r\n\r\n#include<stdio.h>\r\n\r\nstruct stack{\r\n\tchar book_name[200][200];\r\n\tint book_id[20];\r\n\tint book_price[20];\r\n\tint top;\r\n};\r\n\r\nstruct stack *p;\r\nint size;\r\n\r\nvoid push(){\r\n\tif((p->top)==size-1){\r\n\t\tprintf(\"Overflow\");\r\n\t\treturn;\r\n\t}\r\n\tp->top = p->top +1;\r\n\t//printf(\"p->top = %d\",p->top);\r\n\tprintf(\"\\nEnter elements to be pushed : \");\r\n\tprintf(\"\\nEnter book name:\");\r\n\tscanf(\"%s\",p->book_name[p->top]);\r\n\tprintf(\"\\nEnter book id:\");\r\n\tscanf(\"%d\",&p->book_id[p->top]);\r\n\tprintf(\"\\nEnter book price:\");\r\n\tscanf(\"%d\",&p->book_price[p->top]);\r\n}\r\n\r\nvoid pop(){\r\n\tif(p->top==-1){\r\n\t\tprintf(\"Underflow\\n\");\r\n\t}\r\n\telse{\r\n\t\tp->top = p->top - 1;\r\n\t}\r\n}\r\n\r\nvoid peep(){\r\n\tint i= p->top;\r\n\t\tprintf(\"\\nBook Name : %s\",p->book_name[i]);\r\n\t\tprintf(\"\\nBook ID : %d\",p->book_id[i]);\r\n\t\tprintf(\"\\nBook Price : %d\",p->book_price[i]);\r\n\t\tprintf(\"\\n\");\r\n}\r\n\r\nvoid print(){\r\n\tint x = p->top;\r\n\tif(x==-1){\r\n\t\tprintf(\"Nothing to be displayed\\n\");\r\n\t}\r\n\tint i;\r\n\tfor(i=0;i<=x;i++){\r\n\t\tprintf(\"\\nBook Name : %s\",p->book_name[i]);\r\n\t\tprintf(\"\\nBook ID : %d\",p->book_id[i]);\r\n\t\tprintf(\"\\nBook Price : %d\",p->book_price[i]);\r\n\t\tprintf(\"\\n\");\r\n\t}\t\r\n}\r\n\r\nint main(){\r\n\tprintf(\"********************************\\t\\n\");\r\n\tprintf(\"Enter stack size : \");\r\n\tscanf(\"%d\",&size);\r\n\tp = (struct stack*)malloc(sizeof(struct stack));\r\n\tp->top = -1;\r\n\twhile(1){\r\n\t\tprintf(\"\\n1.Push\\n2.Pop\\n3.Peep\\n4.Display all elements\\n5.Exit\\n\");\r\n\t\tint ch;\r\n\t\tscanf(\"%d\",&ch);\r\n\t\tif(ch==1){\r\n\t\t\t//p->top = p->top + 1;\r\n\t\t\tpush();\r\n\t\t}\r\n\t\telse if(ch==2){\r\n\t\t\tpop();\r\n\t\t}\r\n\t\telse if(ch==3){\r\n\t\t\tpeep();\r\n\t\t}\r\n\t\telse if(ch==4){\r\n\t\t\tprint();\r\n\t\t}\r\n\t\telse{\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n}\r\n"
  },
  {
    "path": "STL C++/sorting_a_vector.cpp",
    "content": "#include<iostream>\r\n#include<cstring>\r\n#include<vector>\r\n#include<algorithm>\r\nusing namespace std;\r\n\r\nbool compare(int a,int b){\r\n    return a>b;\r\n}\r\n\r\nint main(){\r\n\r\n    vector<int> v;\r\n\r\n    for(int i=1;i<5;i++){\r\n        v.push_back(i);\r\n    }\r\n    int p;\r\n    cin>>p;\r\n\r\n    int d;\r\n    cin>>d;\r\n\r\n    v.insert(v.begin() + p,d);\r\n\r\n    for(int i=0;i<v.size();i++){\r\n        cout<<v[i]<<\" \";\r\n    }\r\n    cout<<endl;\r\n    ///Sort a vector\r\n    sort(v.begin(),v.end(),compare);\r\n\r\n     for(int i=0;i<v.size();i++){\r\n        cout<<v[i]<<\" \";\r\n    }\r\n\r\n\r\n\r\nreturn 0;\r\n}\r\n"
  },
  {
    "path": "STL C++/stack/Stack.java",
    "content": "import java.lang.IndexOutOfBoundsException;\nimport java.util.Arrays;\n\npublic class Stack<E> {\n    private int max;\n    private int top;\n    private Object[] list;\n\n    public Stack() {\n        max = 512;\n        top = 0;\n        list = new Object[max];\n    }\n\n    public Stack(int size) {\n        max = size;\n        top = 0;\n        list = new Object[max];\n    }\n\n    @SuppressWarnings(\"unchecked\")\n    public boolean isEmpty() {\n        for(E t : (E[]) list) {\n            if(t != null) {\n                return false;\n            }\n        }\n\n        return true;\n    }\n\n    @SuppressWarnings(\"unchecked\")\n    public E peek() {\n        return (E) list[top];\n    }\n\n    @SuppressWarnings(\"unchecked\")\n    public int size() {\n        if(top == 0) {\n            return 0;\n        }\n\n        int count = 0;\n        for(E t : (E[]) list) {\n            if(t != null) {\n                count++;\n            }\n        }\n\n        return count;\n    }\n\n    @SuppressWarnings(\"unchecked\")\n    public E pop() {\n        if(isEmpty()) {\n            throw new IndexOutOfBoundsException(\"This stack is empty; nothing to pop.\");\n        }\n\n        E data = (E) list[top];\n\n        top = (top == 0 ? 0 : top - 1);\n        return data; \n    }\n\n    public void push(E data) {\n        if(top == max - 1) {\n            list = Arrays.copyOf(list, list.length * 2);\n        }\n\n        top++;\n        list[top] = data;\n    }\n}\n"
  },
  {
    "path": "STL C++/stack/largestRectangleHistogram.cpp",
    "content": "#include<iostream>\n#include<stack>\n#include<climits>\nusing namespace std;\nint main() {\n    int n;\n    int a[]={6,2,5,4,5,1,6};  //input array\n    n = sizeof(a)/sizeof(a[0]);\n    int i,q;\n    stack <int> s;  // stack to calculate max area\n    i=0;\n    int area,maxarea=INT_MIN;\n    while(i<n){\n        if(s.empty()||a[s.top()]<=a[i])\n        s.push(i++);\n        else{\n            q=s.top();\n            s.pop();\n            area=a[q]*(s.empty()?i:i-s.top()-1);\n            if(maxarea<area)\n                maxarea=area;\n        }\n    }\n    while(!s.empty()){\n        q=s.top();\n        s.pop();\n        area=a[q]*(s.empty()?i:i-s.top()-1);\n        if(maxarea<area)\n            maxarea=area;\n    }\n    cout<<maxarea;\n\treturn 0;\n}\n"
  },
  {
    "path": "STL C++/stack/stack.hpp",
    "content": "#include <bits/stdc++.h>\r\n#include \"../linked_list/ll.hpp\"\r\nusing namespace std;\r\n\r\ntemplate<class T>\r\nstruct stackmp{\r\n\tll_node<T> *top;\r\n\tint capacity; // number of elements the stack can contain\r\n\tint size; // number of elements in the stack\r\n\r\n\tstackmp(int cap) : capacity(cap),size(0) {}\r\n\r\n\tvoid push(T new_data){\r\n\t\tif(size == capacity){\r\n\t\t\tcout << \"Stack is full! Cannot push new element\" << endl;\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tll_node<T> *new_node = create_node(new_data);\r\n\t\tll_node<T> *temp_node = this->top;\r\n\t\tnew_node->next = temp_node;\r\n\t\tthis->top = new_node;\r\n\t\tsize++;\r\n\t}\r\n\r\n\tvoid print(){\r\n\t\tll_node<T> *temp_node = this->top;\r\n\t\tif(size == 0){\r\n\t\t\tcout << \"Stack is empty\" << endl;\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tcout << \"Printing stack:\" << endl;\r\n\t\tfor(int i=0;i<this->size;i++){\r\n\t\t\tcout << temp_node->data << ' ';\r\n\t\t\ttemp_node = temp_node->next;\r\n\t\t}\r\n\t\tcout << endl;\r\n\t}\r\n\r\n\tT pop(){\r\n\t\tif(size == 0){\r\n\t\t\tcout << \"Stack is empty, can't pop\" << endl;\r\n\t\t\treturn '\\0';\r\n\t\t}\r\n\t\tT data = this->top->data;\r\n\t\tthis->top = this->top->next;\r\n\t\tsize--;\r\n\t\treturn data;\r\n\t}\r\n\r\n\tT peek(){\r\n\t\treturn this->top->data;\r\n\t}\r\n};\r\n\r\ntemplate<class T>\r\nint get_size(stackmp<T> *s){\r\n\treturn s->size;\r\n}\r\n\r\ntemplate<class T>\r\nint get_capacity(stackmp<T> *s){\r\n\treturn s->capacity;\r\n}\r\n\r\n"
  },
  {
    "path": "STL C++/using_map.cpp",
    "content": "map <int, int> m;\nmap <int, int> :: iterator it;\n\nm[1] = 2;\nm[2] = 3;\nm[6] = 4;\nm[5] = 5;\n\nit = m.find(5);\nif (it != m.end())\n    cout << \"5 is present as key\" << endl;\nelse\n    cout << \"5 is not present as key\" << endl;\n/* Output: 5 is present as key */\n\n\nit = m.find(3);\nif (it != m.end())\n    cout << \"3 is present as key\" << endl;\nelse\n    cout << \"3 is not present as key\" << endl;\n/* Output: 3 is not present as key */\n"
  },
  {
    "path": "STL C++/using_set.cpp",
    "content": "set <int> s;\ns.insert(5); // 5 is inserted into set\ns.insert(2); // 2 is inserted into set\ns.insert(3); // 3 is inserted into set\ns.insert(2); // no new element inserted\n\nset <int> :: iterator it;\nit = s.find(5)\nif (it != s.end())\n    cout << \"Element is present in set\" << endl;\nelse\n    cout << \"Element is not present in set\" << endl;\n/* Output : Element is present in set */\n\nit = s.find(9)\nif (it != s.end())\n    cout << \"Element is present in set\" << endl;\nelse\n    cout << \"Element is not present in set\" << endl;\n/* Output : Element is not present in set */\n"
  },
  {
    "path": "STRUCTURE.md",
    "content": "\n# Directory Structure Example\n\n## please maintain the directory structure as in this example\n\n- Data structures\n   - stack\n      - DESCRIPTION.md\n      - Python\n         - Applications\n      - Cpp\n         - Applications\n         - ques\n      - Java\n- Sorting Algorithms\n   - bubblesort\n      - DESCRIPTION.md\n      - Python\n         - Applications\n         - ques\n      - Cpp\n        - ques\n      - Java\n- Graph\n  - Dijakstra\n      - DESCRIPTION.md\n      - Cpp\n        - Applications\n        - ques\n      - java\n      - Python\n  \n"
  },
  {
    "path": "Searching Algorithms/Bogo_sort.cpp",
    "content": "// C Program to Implement BogoSort in an Integer Array\n#include <stdio.h>\n#include <stdlib.h>\n \n#define size 7\n/* Function Prototypes */\n \nint is_sorted(int *, int);\nvoid shuffle(int *, int); \nvoid bogosort(int *, int);\n \nint main()\n{\n    int numbers[size];\n    int i;\n \n    printf(\"Enter the elements of array:\");\n    for (i = 0; i < size;i++)\n    {\n        scanf(\"%d\", &numbers[i]);\n    }\n    bogosort(numbers, size);\n    printf(\"The array after sorting is:\");\n    for (i = 0;i < size;i++)\n    {\n        printf(\"%d\\n\", numbers[i]);\n    }\n    printf(\"\\n\");\n}\n \n/* Code to check if the array is sorted or not */\nint is_sorted(int *a, int n)\n{\n    while (--n >= 1)\n    {\n        if (a[n] < a[n - 1])\n        {\n            return 0;\n          }\n    }\n      return 1;\n}\n \n/* Code to shuffle the array elements */\nvoid shuffle(int *a, int n)\n{\n    int i, t, temp;\n    for (i = 0;i < n;i++)\n    {\n        t = a[i];\n        temp = rand() % n;    /* Shuffles the given array using Random function */\n        a[i] = a[temp];\n        a[temp] = t;\n    }\n}\n \n/* Code to check if the array is sorted or not and if not sorted calls the shuffle function to shuffle the array elements */\nvoid bogosort(int *a, int n)\n{\n    while (!is_sorted(a, n))\n    {\n        shuffle(a, n);\n    }\n}\n"
  },
  {
    "path": "Searching Algorithms/C:C++/Binary_Search.cpp",
    "content": "//Time Complexity: O(logn)\n#include<bits/stdc++.h>\nusing namespace std;\nint main()\n{\n\n    int a[100],n,i,beg,end,mid,item;\n    cout<<\"Enter No. of Elements= \";\n    cin>>n;\n    cout<<\"Enter Elements in Sorted Order=\\n\";\n    for(i=1;i<=n;i++)\n    cin>>a[i];\n\n    cout<<\"Enter Item you want to Search= \";\n    cin>>item;\n\n    beg=1;\n    end=n;\n\n    mid=(beg+end)/2;\n\n    while(beg<=end && a[mid]!=item)\n    {\n        if(a[mid]<item)\n            beg=mid+1;\n        else\n            end=mid-1;\n        mid=(beg+end)/2;\n    }\n    if(a[mid]==item)\n        cout<<\"Data is Found at Location : \"<<mid;\n    else\n        cout<<\"Data is Not Found\";\n\nreturn 0;\n}\n"
  },
  {
    "path": "Searching Algorithms/C:C++/Binary_search.cpp",
    "content": "/* C++ Program - Binary Search */\n\t\n#include<iostream.h>\n#include<conio.h>\nvoid main()\n{\n\tclrscr();\n\tint n, i, arr[50], search, first, last, middle;\n\tcout<<\"Enter total number of elements :\";\n\tcin>>n;\n\tcout<<\"Enter \"<<n<<\" number :\";\n\tfor (i=0; i<n; i++)\n\t{\n\t\tcin>>arr[i];\n\t}\n\tcout<<\"Enter a number to find :\";\n\tcin>>search;\n\tfirst = 0;\n\tlast = n-1;\n\tmiddle = (first+last)/2;\n\twhile (first <= last)\n\t{\n\t\tif(arr[middle] < search)\n\t\t{\n\t\t\tfirst = middle + 1;\n\n\t\t}\n\t\telse if(arr[middle] == search)\n\t\t{\n\t\t\tcout<<search<<\" found at location \"<<middle+1<<\"\\n\";\n\t\t\tbreak;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t last = middle - 1;\n\t\t}\n\t\tmiddle = (first + last)/2;\n\t}\n\tif(first > last)\n\t{\n\t\tcout<<\"Not found! \"<<search<<\" is not present in the list.\";\n\t}\n\tgetch();\n}\n"
  },
  {
    "path": "Searching Algorithms/C:C++/Interpolation Search",
    "content": "//Time Complexity : O(log(logn))\n\n#include<iostream>\nusing namespace std;\n\n\nint main(){\n\n    int N,x;\n\n    cin>>N;\n    int arr[N];\n    for(int i=0;i<N;i++)\n    {\n        cin>>arr[i];\n    }\n    \n    //Taking the number to be searched.\n    cin>>x;\n    \n    //Getting first and last index of the array.\n    int lo = 0, hi = (N - 1);\n    int flag=0;\n    \n    //If the element is present in the sorted array, it must be in the range defined by 'hi' and 'lo'.\n    while (lo <= hi && x >= arr[lo] && x <= arr[hi])\n    {\n        // The idea of formula is to return higher value of pos\n        // when element to be searched is closer to arr[hi], and\n        // smaller value when closer to arr[lo]\n        int pos = lo + (((double)(hi-lo) /\n              (arr[hi]-arr[lo]))*(x - arr[lo]));\n\n        if (arr[pos] == x)\n          {\n          cout<<pos;\n          //Number found at pos\n          flag=1;\n          }\n\n        if (arr[pos] < x)\n            lo = pos + 1;\n\n\n        else\n            hi = pos - 1;\n    }\n    if(flag == 0)\n        cout<<-1;\n}\n\n\n"
  },
  {
    "path": "Searching Algorithms/C:C++/Interpolation_search.cpp",
    "content": "//Time Complexity: O(log(logn))\n\n#include<iostream>\n#include<algorithm>\nusing namespace std;\n\n// If x is present in arr[0..n-1], then returns\n// index of it, else returns -1.\n\nlong long int interpolation_search(int arr[],int n,int x)\n{\n\tint low=0,high=n-1;\n\n\t//Beacuse the array is sorted, element has to be present in range\n\t//made by corner i.e low and high\n\n\twhile ((low<=high) and (x>=arr[low]) and (x<=arr[high]))\n\t{\n\t\t// Now we will enquire the position keeping in mind the uniform distribution in mind\n\t\tint pos=low+(((double)(high-low)/(arr[high]-arr[low]))*(x-arr[low]));\n\n        // If x is larger, x is in upper part\n        if (arr[pos]<x)\n            low=pos+1;\n\n        // If x is smaller, x is in lower part\n        else if(arr[pos]>x)\n            high=pos-1;\n\n        // Target found\n        else\n            return pos;\n\t}\n\treturn -1;\n}\n\nint main()\n{\n\tint n;\n\tcout<<\"Please enter the number of elements in array\\n\";\n\tcin>>n;\n\tint arr[n];\n\n\tcout<<\"Please enter \"<<n<<\" numbers for arrays\\n\";\n\tfor(int i=0;i<n;i++)\n\t{\n\t\tcin>>arr[i];\n\t}\n\n\t// For Interpolation search we need to sort the array\n\tsort(arr,arr+n);\n\n\tcout<<\"Enter the number you want to search\\n\";\n\tint x;// Target number\n\tcin>>x;\n\n\t int index=interpolation_search(arr, n, x);\n\n    // If element was found\n    if (index != -1)\n        cout<<\"Element found at index \"<<index<<\" in sorted array\\n\";\n    else\n        cout<<\"Element not found.\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "Searching Algorithms/C:C++/Jump_Search.cpp",
    "content": "//Time Complexity: O(sqrt(n))\n\n#include <bits/stdc++.h>\nusing namespace std;\n \nint jumpSearch(int arr[], int x, int n)\n{\n    // Finding block size to be jumped\n    int step = sqrt(n);\n \n    // Finding the block where element is\n    // present (if it is present)\n    int prev = 0;\n    while (arr[min(step, n)-1] < x)\n    {\n        prev = step;\n        step += sqrt(n);\n        if (prev >= n)\n            return -1;\n    }\n \n    // Doing a linear search for x in block\n    // beginning with prev.\n    while (arr[prev] < x)\n    {\n        prev++;\n \n        // If we reached next block or end of\n        // array, element is not present.\n        if (prev == min(step, n))\n            return -1;\n    }\n    // If element is found\n    if (arr[prev] == x)\n        return prev;\n \n    return -1;\n}\n \n// Driver program to test function\nint main()\n{\n    int arr[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21,\n                 34, 55, 89, 144, 233, 377, 610 };\n    int x = 55;\n    int n = sizeof(arr) / sizeof(arr[0]);\n     \n    // Find the index of 'x' using Jump Search\n    int index = jumpSearch(arr, x, n);\n \n    // Print the index where 'x' is located\n    cout << \"\\nNumber \" << x << \" is at index \" << index;\n    return 0;\n}\n \n"
  },
  {
    "path": "Searching Algorithms/C:C++/Liear_search.cpp",
    "content": "/* C++ Program - Linear Search */\n\t\t\n#include<iostream.h>\n#include<conio.h>\nvoid main()\n{\n\tclrscr();\n\tint arr[10], i, num, n, c=0, pos;\n\tcout<<\"Enter the array size : \";\n\tcin>>n;\n\tcout<<\"Enter Array Elements : \";\n\tfor(i=0; i<n; i++)\n\t{\n\t\tcin>>arr[i];\n\t}\n\tcout<<\"Enter the number to be search : \";\n\tcin>>num;\n\tfor(i=0; i<n; i++)\n\t{\n\t\tif(arr[i]==num)\n\t\t{\n\t\t\tc=1;\n\t\t\tpos=i+1;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif(c==0)\n\t{\n\t\tcout<<\"Number not found..!!\";\n\t}\n\telse\n\t{\n\t\tcout<<num<<\" found at position \"<<pos;\n\t}\n\tgetch();\n}\n"
  },
  {
    "path": "Searching Algorithms/C:C++/MEDIAN_SEARCH.cpp",
    "content": "//Libraries Included\n#include<iostream>\n#include<algorithm>\nusing namespace std;\n \n\n/* \n\nint findMedian()  -> Returns the median of the input array.\nint partition()   -> The partition work is done by this function.\nint kthSmallest() -> The recursive function that performs the major calculations\n                     of finding the kthSmallest element only on the condition that the \n                     value of k is less than the size of the array produced after after \n                     every recursive cycle. \nint main()        -> Driver Function.\n*/\n\n\n/*\npredefined stuff ->\n\nsort()\nswap()\nINT_MAX\n*/\nint findMedian(int arr[], int size_of_array)\n{\n    sort(arr, arr+size_of_array);  // Sort the array\n    return arr[size_of_array/2];   // Return middle element\n}\n\nint partition(int arr[], int low, int high, int variable_to_be_found)\n{\n    // Search for variable_to_find in arr[low..high] and move it to end\n    int i;\n    for (i=low; i<high; i++)\n        if (arr[i] == x)\n           break;\n    swap(&arr[i], &arr[high]);\n \n    // Standard partition algorithm\n    i = l;\n    for (int j = low; j <= high - 1; j++)\n    {\n        if (arr[j] <= x)\n        {\n            swap(&arr[i], &arr[j]);\n            i++;\n        }\n    }\n    swap(&arr[i], &arr[high]);\n    return i;\n}\n\n \nint kthSmallest(int arr[], int low, int high, int k)\n{   \n    // If k is smaller than number of elements in array\n    if (k > 0 && k <= high - low + 1)\n    {\n        int n = high-low+1; // Number of elements in arr[low..high]\n \n        // Divide arr[] in groups of size 5, calculate median\n        // of every group and store it in median[] array.\n        int i, median[(n+4)/5]; // There will be floor((n+4)/5) groups;\n        for (i=0; i<n/5; i++)\n            median[i] = findMedian(arr+low+i*5, 5);\n        if (i*5 < n) //For last group with less than 5 elements\n        {\n            median[i] = findMedian(arr+low+i*5, n%5); \n            i++;\n        }    \n \n        // Find median of all medians using recursive call.\n        // If median[] has only one element, then no need\n        // of recursive call\n        int medOfMed = (i == 1)? median[i-1]:\n                                 kthSmallest(median, 0, i-1, i/2);\n \n        // Partition the array around a random element and\n        // get position of pivot element in sorted array\n        int pos = partition(arr, low, high, medOfMed);\n \n        // If position is same as k\n        if (pos-l == k-1)\n            return arr[pos];\n        if (pos-l > k-1)  // If position is more, recur for left\n            return kthSmallest(arr, low, pos-1, k);\n \n        // Else recur for right subarray\n        return kthSmallest(arr, pos+1, high, k-pos+l-1);\n    }\n \n    // If k is more than number of elements in array\n    return INT_MAX;\n}\n \n// It searches for x in arr[l..r], and partitions the array \n// around x.\n\n int main()\n{\n    int arr[] = {12, 3, 5, 7, 4, 19, 26};\n    int n = sizeof(arr)/sizeof(arr[0]), k = 3;\n    cout << \"K'th smallest element is \"\n         << kthSmallest(arr, 0, n-1, k);\n    return 0;\n}"
  },
  {
    "path": "Searching Algorithms/C:C++/Selection_sort.cpp",
    "content": "/* C++ Program - Selection Sort */\n\t\t\n#include<iostream.h>\n#include<conio.h>\nvoid main()\n{\n\tclrscr();\n\tint size, arr[50], i, j, temp;\n\tcout<<\"Enter Array Size : \";\n\tcin>>size;\n\tcout<<\"Enter Array Elements : \";\n\tfor(i=0; i<size; i++)\n\t{\n\t\tcin>>arr[i];\n\t}\n\tcout<<\"Sorting array using selection sort...\\n\";\n\tfor(i=0; i<size; i++)\n\t{\n\t\tfor(j=i+1; j<size; j++)\n\t\t{\n\t\t\tif(arr[i]>arr[j])\n\t\t\t{\n\t\t\t\ttemp=arr[i];\n\t\t\t\tarr[i]=arr[j];\n\t\t\t\tarr[j]=temp;\n\t\t\t}\n\t\t}\n\t}\n\tcout<<\"Now the Array after sorting is :\\n\";\n\tfor(i=0; i<size; i++)\n\t{\n\t\tcout<<arr[i]<<\" \";\n\t}\n\tgetch();\n}\n"
  },
  {
    "path": "Searching Algorithms/C:C++/Ternary_search.cpp",
    "content": "#include <iostream>\nusing namespace std;\n\n#define s 12 //I gave space in the array as 12,but you can give the number you want.\n\nint ternary_search (int v[],int n, int left, int right, int x);\nint main()\n{\n    int v[s];\n    short x;\n    for(int i = 1; i <= s; i++)\n    {\n        v[i-1] = i;\n    }\n    cout << \"Enter number for research:\\n\";\n    cin >> x;\n\n    int left = s/3;\n    int right = (s/3)*2;\n\n    if(ternary_search(v,s,left-1,right-1,x) == -1)\n    {\n        cout<<\"Number does not exist in array.\\n\";\n    }\n    else\n    {\n        cout<<\"The index is:\"<<ternary_search(v,s,left-1,right-1,x)<<\"\\n\";\n    }\n    return 0;\n}\nint ternary_search (int v[],int n, int left, int right, int x)\n{\n\n    if(left < 0 || right > n-1 || left > right)\n    {\n        return -1;\n    }\n    if(x == v[left])\n    {\n        return left;\n    }\n\n    if(x == v[right])\n    {\n        return right;\n    }\n\n   // Update the two index left and right if the element is not found.\n\n\n    if(x < v[left])\n    {\n        return ternary_search(v,n,left-1,right,x);\n    }\n\n    if (x > v[left] && x < v[right])\n    {\n\n        return ternary_search(v,n,left+1,right-1,x);\n    }\n\n    if(x > v[right])\n    {\n        return ternary_search(v,n,left,right+1,x);\n    }\n}\n"
  },
  {
    "path": "Searching Algorithms/C:C++/b_search.cpp",
    "content": "#include<iostream>\nusing namespace std;\nint b_search(int a[],int l,int u,int s)\n{\n    int m=(l+u)/2;\n      if(l>=u)\n       return -1;\n       \n      if(a[m]>s)\n        return b_search(a,l,m-1,s);\n      else if(a[m]<s)\n        return b_search(a,m+1,u,s);\n      else\n        return m;\n }\n int main()\n {\n   int arr[100],n,s,i;           // n is the size of the array , s is the element to search in the array, i is the index of the element found  \n          .\n          .\n          .\n          .\n          .\n          .\n    i=b_search(arr,0,n,s);       // assuming every variable has value assigned \n     if ( i==-1)\n      cout<<\"\\n The Element was not found \");\n     else\n      cout<<\"\\n The Element was found at index \"<<i;\n    \n    return 0;\n    }\n"
  },
  {
    "path": "Searching Algorithms/C:C++/fibonacci_search.cpp",
    "content": "#include <algorithm>\n\n\nusing namespace std;\n\nint _fibonacci_search(int n, int arr[], int x)\n{\n    /*Assuming the Input array is sorted*/\n    /*Fibonacci Searching algorithm */\n    /* Initialize fibonacci numbers */\n    int fibMMm2 = 0;   // (m-2)'th Fibonacci No.\n    int fibMMm1 = 1;   // (m-1)'th Fibonacci No.\n    int fibM = fibMMm2 + fibMMm1;  // m'th Fibonacci\n \n    /* fibM is going to store the smallest Fibonacci\n       Number greater than or equal to n */\n    while (fibM < n)\n    {\n        fibMMm2 = fibMMm1;\n        fibMMm1 = fibM;\n        fibM  = fibMMm2 + fibMMm1;\n    }\n \n    // Marks the eliminated range from front\n    int offset = -1;\n \n    /* while there are elements to be inspected. Note that\n       we compare arr[fibMm2] with x. When fibM becomes 1,\n       fibMm2 becomes 0 */\n    while (fibM > 1)\n    {\n        // Check if fibMm2 is a valid location\n        int index = min(offset+fibMMm2, n-1);\n \n        /* If x is greater than the value at index fibMm2,\n           cut the subarray array from offset to i */\n        if (arr[index] < x)\n        {\n            fibM  = fibMMm1;\n            fibMMm1 = fibMMm2;\n            fibMMm2 = fibM - fibMMm1;\n            offset = index;\n        }\n \n        /* If x is greater than the value at index fibMm2,\n           cut the subarray after i+1  */\n        else if (arr[index] > x)\n        {\n            fibM  = fibMMm2;\n            fibMMm1 = fibMMm1 - fibMMm2;\n            fibMMm2 = fibM - fibMMm1;\n        }\n \n        /* element found. return index */\n        else return index;\n    }\n \n    /* comparing the last element with x */\n    if(fibMMm1 && arr[offset+1]==x)return offset+1;\n \n    /*element not found. return -1 */\n    return -1; \n\n\n\n}\n\n"
  },
  {
    "path": "Searching Algorithms/C:C++/seaching algorithms [rename]/binary_search.cpp",
    "content": "/*\nThis code illustrates a recursive implementation of binary search in a sorted array.\n*/\n#include <iostream>\nusing namespace std;\n\nint binarySearch(int array[], int left, int right, int search)\n{\n    if (right >= 1)\n    {\n        int mid = ((right-1)-left)/2;\n        if (array[mid] == search)                                   //Checks if the element is present at the middle\n            return mid;\n        if (array[mid] > search)                                    //Since this is a sorted array, therefore if value of element is less than middle\n            return binarySearch(array, left, mid-1, search);        //element, it lies in left part of array. Recursively searching again the left part.\n\n        return binarySearch(array, mid+1, right, search);           //If element was neither in Middle nor in left part, it can only be in the right.\n    }\n\n    return -1;                                                      //If element was not found, return -1\n}\nint main()\n{\n    int array [] = {1,2,3,4,5,6,7,8,9,10}, search = 5, position;\n    int size = sizeof(array)/ sizeof(array[0]);\n    position = binarySearch(array, 0, size-1, search);            //here left index for binary search is sent as 0, while right as size - 1\n    if(position == -1)                                                //therefore for an array of size 10, 9 will be sent (since arrays are 0 indexed)\n        cout<<\"Element is not present in array\";\n    else\n        cout<<\"Element is present at \"<<position+1<<\"th position\";\n    return 0;\n}\n"
  },
  {
    "path": "Searching Algorithms/C:C++/seaching algorithms [rename]/binary_search_extras/position_in_sorted_array/eq_less_than.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n\n/*\n * return position of last elem less than or equal to num\n * best is best position till now\n * every elem is atleast greater than 0th elem (-1) so initially best is 0\n */\nint binary_search(vector<int> &vec,int l,int r,int num,int best){\n    if(r<l) return best;//search ends\n\n    int m = (l+r)/2;\n\n    if(vec[m]<=num){//got one good ans but still hungary .. go forward\n        best=m;//atleast it is good\n        return binary_search(vec,m+1,r,num,best);//search for better\n    }\n    else{//out of reach ... go back\n        return binary_search(vec,l,m-1,num,best);\n    }\n}\n\n/*\n * program to print number of elems less or equal to num\n */\nint main(){\n    int n;\n    cin>>n;\n    vector<int> vec(n+1);\n    vec[0]=-1;\n    for(int i=1;i<=n;i++){\n        cin>>vec[i]; \n    }\n    sort(vec.begin()+1,vec.end());\n\n    int q;//querries\n    cin>>q;\n    while(q--){\n        int num;\n        cin>>num;\n        cout<<binary_search(vec,1,n,num,0)<<endl;\n    }\n}\n"
  },
  {
    "path": "Searching Algorithms/C:C++/seaching algorithms [rename]/binary_search_extras/position_in_sorted_array/first_occurance.cpp",
    "content": "\n#include<bits/stdc++.h>\nusing namespace std;\n\n/*\n * return position of last elem less than or equal to num\n * best is best position till now\n */\nint binary_search(vector<int> &vec,int l,int r,int num,int best){\n    if(r<l) return best;//search ends\n\n    int m = (l+r)/2;\n\n    if(vec[m]<num){//num is small.. go forward\n        return binary_search(vec,m+1,r,num,best);//search for bigger\n    }\n    if(vec[m]==num){//got the number \n        best=m;//this is best ans till now \n        return binary_search(vec,l,m-1,num,best);//go for even better\n    }\n    if(vec[m]>num){//out of reach ... go back\n        return binary_search(vec,l,m-1,num,best);\n    }\n}\n\n/*\n * program to find first occurance of num in sorted array\n * if not there print -1\n */\nint main(){\n    int n;\n    cin>>n;\n    vector<int> vec(n+1);\n    vec[0]=-1;\n    for(int i=1;i<=n;i++){\n        cin>>vec[i]; \n    }\n    sort(vec.begin()+1,vec.end());\n\n    int q;//querries\n    cin>>q;\n    while(q--){\n        int num;\n        cin>>num;\n        cout<<binary_search(vec,1,n,num,-1)<<endl;\n    }\n}\n"
  },
  {
    "path": "Searching Algorithms/C:C++/seaching algorithms [rename]/binary_search_extras/position_in_sorted_array/just_less_than_num.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n\n/*\n * return position of elem just less than num\n * best is best position till now\n * every elem is atleast greater than 0th elem (-1) so initially best is 0\n */\nint binary_search(vector<int> &vec,int l,int r,int num,int best){\n    if(r<l) return best;\n\n    int m = (l+r)/2;\n\n    if(vec[m]<num){//got one good ... still hungary ... go forward\n        best=m;//atleast it is good\n        return binary_search(vec,m+1,r,num,best);//search for more\n    }\n    else{//out of reach .. move back\n        return binary_search(vec,l,m-1,num,best);//move back\n    }\n}\n\n/*\n * program to find number just less than num\n */\nint main(){\n    int n;\n    cin>>n;\n    vector<int> vec(n+1);\n    vec[0]=-1;\n    for(int i=1;i<=n;i++){\n        cin>>vec[i]; \n    }\n    sort(vec.begin()+1,vec.end());\n\n    int q;//querries\n    cin>>q;\n    while(q--){\n        int num;\n        cin>>num;\n        cout<<vec[binary_search(vec,1,n,num,0)]<<endl;\n    }\n}\n"
  },
  {
    "path": "Searching Algorithms/C:C++/seaching algorithms [rename]/binary_search_extras/position_in_sorted_array/position_in_sorted_array.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n\n/*\n * return position of num in sorted array\n * if not there then return -1\n */\nint binary_search(vector<int> &vec, int l, int r, int num){\n    if(r<l) return -1;    \n\n    int m = (l+r)/2;\n    if(vec[m]<num){\n        return binary_search(vec,m+1,r,num);\n    }\n    else if(vec[m]>num){\n        return binary_search(vec,l,m-1,num);\n    }\n    else{\n        return m;\n    }\n}\n\nint main(){\n    int n;\n    cin>>n;\n    vector<int> vec(n+1);\n    for(int i=1;i<=n;i++){\n        cin>>vec[i]; \n    }\n    sort(vec.begin()+1,vec.end());\n\n    int q;//num of querries\n    cin>>q;\n    while(q--){\n        int num;\n        cin>>num;\n        cout<<binary_search(vec,1,n,num)<<endl;\n    }\n}\n"
  },
  {
    "path": "Searching Algorithms/C:C++/seaching algorithms [rename]/binary_search_extras/ques/aggrcow.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\nint arr[100002];\nint np,nc;\nint ans;\nint find(int l,int r){ \n    int m=(l+r)/2;\n    int cnt=1,last=1;\n    for(int i=2;i<=np;i++){\n        if(arr[i]-arr[last]>=m){\n            cnt++;\n            last=i;\n        }    \n    }\n    if(l==r){\n        if(m>ans && cnt>=nc)ans=m;\n        return ans;\n    }\n    if(cnt<nc){\n        return find(l,m-1);//both ways are correct find(l,m);\n    }\n    else{\n        if(m>ans)ans=m;\n        return find(m+1,r);\n    }\n}\n\nint main(){\n    int t;\n    cin>>t;\n    while(t--){\n        ans=1;\n        cin>>np>>nc;\n        for(int i=1;i<=np;i++)\n            cin>>arr[i];\n        sort(arr+1,arr+np+1);\n\n        cout<<find(1,arr[np])<<endl;\n    }\n}\n"
  },
  {
    "path": "Searching Algorithms/C:C++/seaching algorithms [rename]/jump_search.cpp",
    "content": "/*\nThis code illustrates implementation of Jump Search in a sorted array.\n*/\n#include <iostream>\n#include <math.h>\nusing namespace std;\n\nint jumpSearch(int array[], int search, int size)\n{\n    int step = sqrt(size);                                  //Best Jump block size is sqrt(size) [Reference: http://www.geeksforgeeks.org/jump-search/]\n\n    int location = 0;                                       //Store nearest found result while searching\n\n    while (array[step-1] < search)                          //search for the element by jumping blocks while the current element is less that the one we\n        {                                                   //are searching for.\n            location = step;\n            step += sqrt(size);\n            if (location >= size)                           //If element not found till the end of array, return -1\n                return -1;\n        }\n\n    while (array[location] < search)                        //If array element was greater than the element we are searching for, do a linear\n        {                                                   //search from last known location.\n            location++;\n            if (location == step)\n                return -1;\n        }\n    if (array[location] == search)\n        return location;\n\n    return -1;\n}\nint main()\n{\n    int array [] = {1,2,3,4,5,6,7,8,9,10}, search = 5, position;\n    int size = sizeof(array)/ sizeof(array[0]);\n    position = jumpSearch(array, search, size);\n    if(position == -1)\n        cout<<\"Element is not present in array\";\n    else\n        cout<<\"Element is present at \"<<position+1<<\"th position\";\n    return 0;\n}\n"
  },
  {
    "path": "Searching Algorithms/C:C++/seaching algorithms [rename]/linear.cpp",
    "content": "/*\nThis code illustrates how Linear Search works\n*/\n#include <iostream>\nusing namespace std;\nint main()\n{\n    int array [] = {1,2,3,4,5,6,7,8,9,10}, search = 5, position;\n    for(position = 0 ; position < 10 ; position++)\n        if(search == array[position])\n            cout<<search<<\" was found at \"<<position+1<<\"th position in the given array.\";\n    return 0;\n}\n"
  },
  {
    "path": "Searching Algorithms/C:C++/ternarySearch.cpp",
    "content": "//Time Complexity : O(log3(n))\n\n//Ternary Search Uses Divide And Conquer Technique\n#include<iostream>\n\n/*\n * Part of Cosmos by OpenGenus Foundation\n*/\n\nusing namespace std;\nint ternarySearch(int arr[],int l,int r, int x){\n    if(r>=l){\n        int mid1 = l + (r-l)/3;\n        int mid2 = r - (r-l)/3;\n        if(arr[mid1] == x)\n            return mid1;\n        /*\n            In this search, after each iteration it neglects (1/3)rd part of the array and repeats the same operations on the remaining 2/3rd \t\t    part of array \n        */\n        if(arr[mid2] == x)\n            return mid2;\n        if(x<arr[mid1])\n            return ternarySearch(arr,l,mid1-1,x);\n        else if(x>arr[mid2])\n            return ternarySearch(arr,mid2+1,r,x);\n        else\n            return ternarySearch(arr,mid1+1,mid2-1,x);\n    }\n    return -1; // if x is not found in array arr\n}\nint main(){\n   int arr[] = {1, 2, 3, 5};\n   int size = sizeof(arr)/ sizeof(arr[0]);\n   int find = 3;\n   cout<<\"Position of \"<<find<<\" is \"<<ternarySearch(arr,0,size-1,find);\n   return 0;\n}\n"
  },
  {
    "path": "Searching Algorithms/C:C++/ternary_search.c",
    "content": "//Time Complexity : O(log3(n))\n\n//Ternary Search Uses Divide And Conquer Technique\n#include<stdio.h>\n\nint ternarySearch(int arr[],int l,int r, int x){\n    if(r>=l){\n        int mid1 = l + (r-l)/3;\n        int mid2 = r - (r-l)/3;\n        if(arr[mid1] == x)\n            return mid1;\n        /*\n            In this search, after each iteration it neglects (1/3)rd part of the array \n            and repeats the same operations on the remaining 2/3rd part of array\n        */\n        if(arr[mid2] == x)\n            return mid2;\n        if(x<arr[mid1])\n            return ternarySearch(arr,l,mid1-1,x);\n        else if(x>arr[mid2])\n            return ternarySearch(arr,mid2+1,r,x);\n        else\n            return ternarySearch(arr,mid1+1,mid2-1,x);\n    }\n    return -1; // if x is not found in array arr\n}\nint main(){\n   int arr[] = {1, 2, 3, 5};\n   int size = sizeof(arr)/ sizeof(arr[0]);\n   int find = 3;\n   printf(\"Position of %d is %d\",find,ternarySearch(arr,0,size-1,find));\n   return 0;\n}\n"
  },
  {
    "path": "Searching Algorithms/Java/TODO",
    "content": "* Write all the search algorithms in different classes.\n* Make one driving program containing the main to access all the search classes.\n* Use java packages.\n\nTo continue adding the search algorithm:\n* Make a class name of that algorithm name.\n* include in the package asset as: package asset;\n* write the .java files in algos directory.\n* Compile the .java files as: `javac -d ../ <filename.java>`.\n* Check if the .class file get added in the asset folder.\n* To run these class files, include: `import asset.<file/algo_name>` in the **driving.java** (the driving program).\n"
  },
  {
    "path": "Searching Algorithms/Java/algos/BinarySearch.java",
    "content": "package asset;\n\npublic class BinarySearch{\n\tpublic static int binarySearch(int [] arr, int key, int low, int high) {\n\t\tint index = Integer.MAX_VALUE;\n\t\t\n\t\twhile (low <= high) {\n\t\t\tint mid = (low + high) / 2;\n\t\t\tif(arr[mid] < key) {\n\t\t\t\tlow = mid + 1;\n\t\t\t}\n\t\t\telse if (arr[mid] > key) {\n\t\t\t\thigh = mid - 1;\n\t\t\t}\n\t\t\telse if (arr[mid] == key) {\n\t\t\t\tindex = mid;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse\n\t\t\t\treturn -1;\n\t\t}\n\t\treturn index;\n\t}\n}\n"
  },
  {
    "path": "Searching Algorithms/Java/algos/LinearSearch.java",
    "content": "package asset;\n\npublic class LinearSearch{\n\tpublic static int linearSearch(int [] arr, int key) {\n\t\tint size = arr.length;\n\t\tfor(int i = 0; i < size; i++) {\n\t\t\tif(arr[i] == key) {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t\treturn -1;\n\t}\n}\n"
  },
  {
    "path": "Searching Algorithms/Java/driving.java",
    "content": "package pkg;\n\npublic class LinearSearch{\n\tpublic static int linearSearch(int [] arr, int key) {\n\t\tint size = arr.length;\n\t\tfor(int i = 0; i < size; i++) {\n\t\t\tif(arr[i] == key) {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t\treturn -1;\n\t}\n\n\tpublic static void main(String a[]) {\n\t\tint[] arr1 = {1, 4, 12, 435, 76};\n\t\tint searchKey = 4;\n\t\tSystem.out.println(\"Key \" + searchKey + \" found at index: \" + linearSearch(arr1, searchKey));\n\t}\n}\n"
  },
  {
    "path": "Searching Algorithms/Python/binarysearch.py",
    "content": "def binary_search(item_list,item):\r\n\tfirst = 0\r\n\tlast = len(item_list)-1\r\n\tfound = False\r\n\twhile( first<=last and not found):\r\n\t\tmid = (first + last)//2\r\n\t\tif item_list[mid] == item :\r\n\t\t\tfound = True\r\n\t\telse:\r\n\t\t\tif item < item_list[mid]:\r\n\t\t\t\tlast = mid - 1\r\n\t\t\telse:\r\n\t\t\t\tfirst = mid + 1\t\r\n\treturn found\r\n\t\r\nprint(binary_search([1,2,3,5,8], 6))\r\nprint(binary_search([1,2,3,5,8], 5))\r\n\r\n\r\n\"\"\"\r\nTIME COMPLEXITY\r\n\r\nBest-case performance\t        O(1)\r\nAverage performance\t        O(log n)\r\nWorst-case space complexity\tO(1)\r\n\r\nSPACE COMPLEXITY\r\n\r\nBest-case performance\t        O(1)\r\nAverage performance\t        O(log n)\r\nWorst-case space complexity\tO(1)\r\n\r\n\"\"\"\r\n"
  },
  {
    "path": "Searching Algorithms/Python/bst.py",
    "content": "#Time Complexity : O(height)\n\n# Python program to demonstrate insert operation in binary search tree \n \n# A utility class that represents an individual node in a BST\nclass Node:\n    def __init__(self,key):\n        self.left = None\n        self.right = None\n        self.val = key\n \n# A utility function to insert a new node with the given key\ndef insert(root,node):\n    if root is None:\n        root = node\n    else:\n        if root.val < node.val:\n            if root.right is None:\n                root.right = node\n            else:\n                insert(root.right, node)\n        else:\n            if root.left is None:\n                root.left = node\n            else:\n                insert(root.left, node)\n \n# A utility function to do inorder tree traversal\ndef inorder(root):\n    if root:\n        inorder(root.left)\n        print(root.val)\n        inorder(root.right)\n \n \n# Driver program to test the above functions\n# Let us create the following BST\n#      50\n#    /    \\\n#   30     70\n#   / \\    / \\\n#  20 40  60 80\nr = Node(50)\ninsert(r,Node(30))\ninsert(r,Node(20))\ninsert(r,Node(40))\ninsert(r,Node(70))\ninsert(r,Node(60))\ninsert(r,Node(80))\ninsert(r,Node(100))\ninsert(r,Node(200))\n# Print inoder traversal of the BST\ninorder(r)\n \n"
  },
  {
    "path": "Segment Trees/ADA/README.md",
    "content": "# Compile and run an ADA program\ngnatmake nome_do_programa.adb\n./nome_do_programa\n\nor\n\ngcc-4.9 -c nome_do_programa.adb\ngnatbind -x nome_do_programa.adb\ngnatlink nome_do_programa.adb\n./nome_do_programa\n\n# Definition\n\nSegment tree can be used to do preprocessing and query in moderate time. With segment tree, preprocessing time is O(n) and time to for range minimum query is O(Logn). The extra space required is O(n) to store the segment tree.\n\nRepresentation of Segment trees\n* Leaf Nodes are the elements of the input array.\n* Each internal node represents minimum of all leaves under it.\n\nAn array representation of tree is used to represent Segment Trees. For each node at index i, the left child is at index 2*i+1, right child at 2*i+2 and the parent is at floor of (i - 1)/2.\n\n## Construction of Segment Tree from given array\n\nWe start with a segment arr[0 . . . n-1]. and every time we divide the current segment into two halves(if it has not yet become a segment of length 1), and then call the same procedure on both halves, and for each such segment, we store the minimum value in a segment tree node.\nAll levels of the constructed segment tree will be completely filled except the last level. Also, the tree will be a Full Binary Tree because we always divide segments in two halves at every level. Since the constructed tree is always full binary tree with n leaves, there will be n-1 internal nodes. So total number of nodes will be 2*n – 1.\n\n[Credits](http://www.geeksforgeeks.org/segment-tree-set-1-range-minimum-query/)\n\n"
  },
  {
    "path": "Segment Trees/ADA/segmentree.adb",
    "content": "with Ada.Integer_Text_IO, Ada.Text_IO;\nuse Ada.Integer_Text_IO, Ada.Text_IO;\n\n--To compile an ADA program you have to install gnat on your computer\n--  sudo apt-get install gnat-5\n--  gnatmake segmentree.adb\n--  ./segmentree\n\n--or\n\n--  gcc-4.9 -c segmentree.adb\n--  gnatbind -x segmentree.adb\n--  gnatlink segmentree.adb\n--  ./segmentree\n\nprocedure segmentree is\n\nINT_MAX: constant integer := 999999;\nMAXN : constant integer := 100005;\nv : array(0..MAXN) of integer;\ntree: array(0..4*MAXN) of integer;\nn : integer;\nq : integer;\na : integer;\nb : integer;\nc : integer;\n\nfunction min(a: integer; b: integer) return integer is\n\nbegin\n\t\n\tif a < b then return a;\n\telse return b;\n\tend if;\nend min;\n\nprocedure build(node: integer; l: integer; r: integer) is\n\n\tmid: integer;\n\nbegin\n\n\tmid := (l + r)/2;\n\t\n\tif l = r then\n\t\ttree(node) := v(l);\n\t\treturn;\n\tend if;\n\n\tbuild(2 * node, l, mid);\n\tbuild(2*node+1,mid+1,r);\n\ttree(node) := min( tree(2*node), tree(2*node + 1)); \nend build;\n\n\n-- Update procedure\nprocedure update(node: integer; l: integer; r: integer; pos: integer; val: integer) is\n\n\tmid: integer := (l + r)/2;\n\nbegin\n\t\n\tif l > pos or r < pos or l > r then\n\t\treturn;\n\tend if;\n\n\tif(l = r) then\n\t\ttree(node) := val;\n\t\treturn;\n\tend if;\n\n\tif pos <= mid then\n\t\tupdate(2*node,l,mid,pos,val);\n\telse\n\t\tupdate(2*node+1,mid+1,r,pos,val);\n\tend if;\n\ttree(node) := min( tree(2*node), tree(2*node + 1)); \nend update;\n\n\n-- Query function\nfunction query(node : integer; l: integer; r: integer; x: integer; y: integer) return integer is\n\t\n\tmid: integer := (l + r)/2;\n\tp1: integer; \n\tp2: integer; \nbegin\n\n\tif l > r or l > y or r < x then\n\t\treturn INT_MAX;\n\tend if;\n\tif x <= l and r <= y then\n\t\treturn tree(node);\n\tend if;\n\n\tp1 := query(2*node,l,mid,x,y);\n\tp2 := query(2*node+1,mid+1,r,x,y);\n\n\tif p1 = INT_MAX then \n\t\treturn p2;\n\tend if;\n\n\tif p2 = INT_MAX then\n\t\treturn p1;\n\tend if;\n\n\treturn min(p1, p2);\n\nend query;\n\n\nbegin\n\tPut_Line(\"Input the array range\");\n\tGet(n);\n\tPut_Line(\"Input the values\");\n\tfor i in 1..n loop\n\t\tGet(v(i));\n\tend loop;\n\n\n\tbuild(1,0,n-1);\n\n\tPut_Line(\"Input the number of operations\");\n\n\tGet(q);\n\t\n\twhile q > 0 loop\n\t\tPut_Line(\"Input 0 to query and 1 to update\");\n\t\tGet(a);\n\t\tPut_Line(\"Input the STARTING index of the query range\");\n\t\tGet(b);\n\t\tPut_Line(\"Input the ENDING index of the query range\");\n\t\tGet(c);\n\n\t\tif a = 0 then \n\t\t\tPut_Line(\"Minimum value of the given range\");\n\t\t\tPut(query(1,1,n,b,c));\n\t\t\tPut_Line(\"\");\n\t\telsif a = 1 then\n\t\t\tupdate(1,1,n,b,c);\n\t\telse\n\t\t\tPut_Line(\"Invalid Operation\");\n\t\t\tq := q + 1;\n\t\tend if;\n\t\tq := q - 1;\n\n\tend loop;\nend segmentree;\n\n\n\n"
  },
  {
    "path": "Segment Trees/C++/RangeMinimumQuery.cpp",
    "content": "//Following code calculates the minimum value in the range l to r\n#include <bits/stdc++.h>\nusing namespace std;\n\nint rmq(int *st, int n, int ss, int se, int qs, int qe, int si) {\n\n\t\tif(qs < 0 || qs > qe || qe >= n) {\n\t\t\treturn -1;\n\t\t}\t\n\n\t\tif(ss >= qs && se <= qe) { //segment range fully within query range\n\t\t\treturn st[si];\n\t\t}\n\t\tif(se < qs || ss > qe) {//segment range has not intersection\n\t\t\treturn INT_MAX;\n\t\t}\n\n\t\tint mid = (ss + se)/2;\n\t\treturn min(rmq(st, n, ss ,mid, qs, qe, 2*si+1), rmq(st, n, mid+1 ,se, qs, qe, 2*si+2));\n\t}\n\n\tint buildTree(int a[], int n, int ss, int se, int *st, int si) {\n\n\t\tif(ss == se) {\n\t\t\tst[si] = a[ss];\n\t\t\treturn a[ss];\n\t\t}\n\n\t\tint mid = (ss + se)/2;\n\t\tst[si] = min(buildTree(a,n,ss, mid,st, 2*si + 1), buildTree(a, n, mid+1, se,st,2*si+2));\n\n\t\treturn st[si];\n\t}\n\n\tint *constructTree(int a[], int n) {\n\n\t\tint x = (int)(ceil(log2(n)));\n\n\t\tint max_size = 2*(int)pow(2,x) - 1;\n\n\t\tint *st = new int[max_size];\n\n\t\tbuildTree(a, n, 0, n-1, st, 0);\n\n\t\treturn st;\n\t}\n\n\tint main()\n\t{\n\t\tint n;\n\t\tcin>>n;\n\t\tint a[n], i;\n\t\tfor(i=0;i<n;i++) {\n\t\t\tcin>>a[i];\n\t\t}\n\t\tint *st = constructTree(a, n);\n\t\tint qs, qe;\n\t\tcin>>qs>>qe;\n\t\tcout<<rmq(st, n, 0, n-1, qs, qe, 0)<<endl;\n\t\treturn 0;\n\t}"
  },
  {
    "path": "Segment Trees/C++/SumInGivenRange.cpp",
    "content": "//Following  is the code where in you can update the value in the array and Query for the sum in l to r\n#include <bits/stdc++.h>\nusing namespace std;\n\nint getSum(int *st, int n, int ss, int se, int qs, int qe, int si) {\n\n\tif(qs < 0 || qs > qe || qe >= n) {\n\t\treturn -1;\n\t}\t\n\n\t\tif(ss >= qs && se <= qe) { //segment range fully within query range\n\t\t\treturn st[si];\n\t\t}\n\t\tif(se < qs || ss > qe) {//segment range has not intersection\n\t\t\treturn 0;\n\t\t}\n\n\t\tint mid = (ss + se)/2;\n\t\treturn getSum(st, n, ss ,mid, qs, qe, 2*si+1) + getSum(st, n, mid+1 ,se, qs, qe, 2*si+2);\n\t}\n\n\tvoid UpdateUtil(int *st, int ss, int se, int i, int diff, int si) {\n\n\t\tif(i < ss || i > se) {\n\t\t\treturn;\n\t\t}\n\n\t\tst[si] += diff;\n\n\t\tif(ss != se) {\n\t\t\tint mid = (ss + se)/2;\n\t\t\tUpdateUtil(st, ss, mid, i, diff, 2*si+1);\n\t\t\tUpdateUtil(st, mid+1, se, i, diff, 2*si+2);\n\t\t} \n\t}\n\n\tvoid UpdateValue(int a[], int *st, int n, int i, int new_value) {\n\n\t\tif(i < 0 || i > n -1) {\n\t\t\treturn;\n\t\t}\n\n\t\tint diff = new_value - a[i];\n\n\t\ta[i] = new_value;\n\n\t\tUpdateUtil(st, 0, n-1, i, diff, 0);\n\n\t}\n\n\tint buildTree(int a[], int n, int ss, int se, int *st, int si) {\n\n\t\tif(ss == se) {\n\t\t\tst[si] = a[ss];\n\t\t\treturn a[ss];\n\t\t}\n\n\t\tint mid = (ss + se)/2;\n\t\tst[si] = buildTree(a, n, ss, mid,st, 2*si + 1) + buildTree(a, n, mid+1, se,st,2*si+2);\n\n\t\treturn st[si];\n\t}\n\n\tint *constructTree(int a[], int n) {\n\n\t\tint x = (int)(ceil(log2(n)));\n\n\t\tint max_size = 2*(int)pow(2,x) - 1;\n\n\t\tint *st = new int[max_size];\n\n\t\tbuildTree(a, n, 0, n-1, st, 0);\n\n\t\treturn st;\n\t}\n\n\tint main()\n\t{\n\t\tint n;\n\t\tcin>>n;\n\t\tint a[n], i;\n\t\tfor(i=0;i<n;i++) {\n\t\t\tcin>>a[i];\n\t\t}\n\t\tint *st = constructTree(a, n);\n\t\tint qs, qe;\n\t\tcin>>qs>>qe;\n\t\tcout<<getSum(st, n, 0, n-1, qs, qe, 0)<<endl;\n\t\tUpdateValue(a, st, n, 2, 10);\n\t\tcin>>qs>>qe;\n\t\tcout<<getSum(st, n, 0, n-1, qs, qe, 0)<<endl;\n\t\treturn 0;\n\t}"
  },
  {
    "path": "Segment Trees/Java/SegementTree.java",
    "content": "import java.util.Scanner;\n/*\n* @author Nikunj Khokhar\n*/\npublic class SegmentTree {\n\n    static int MAX = 1000005;\n    static int arr[] ;\n    static int tree[] ;\n   public static void main(String args[])\n   {\n       Scanner sc = new Scanner(System.in);\n\n       //Enter the value of the n which is the numner of element in the\n       System.out.println(\"Enter the numbers of elements in Array : \");\n       int n = sc.nextInt();\n       arr = new int[MAX];\n       tree = new int[MAX];\n\n\n\n        System.out.println(\"Enter the Array elements :\");\n       for(int i=1;i<=n;i++)\n       {\n           arr[i] = sc.nextInt();\n       }\n\n\n\n       //Building the SegmentTree....\n       build(1,1,n);\n\n\n       //FInding the Minimum element between the range x to y......\n\n       System.out.println(\"Enter the Range :\");\n       System.out.println(\"Enter the L : \");\n       \n       int x = sc.nextInt();\n       System.out.println(\"Enter the R : \");\n       int y = sc.nextInt();\n\n       System.out.println(\"The Minimum element between the ranege \" + x + \"and \"+ y +\" :\");\n       System.out.println(query(1,1,n,x,y));\n\n\n\n       //for updateing the Segment tree\n\n\n       System.out.println(\"Enter the index which you want to change :\");\n       x = sc.nextInt();\n       System.out.println(\"Enter the number :\");\n       y = sc.nextInt();\n\n       //Update the value at x with y....\n       update(1,1,n,x,y);\n\n\n\n   }\n\n\n    public static void build(int node, int start, int end)\n    {\n        if(start == end)\n        {\n            tree[node] = arr[start];\n        }\n        else\n        {\n            int mid = (start + end) / 2;\n            build(2*node, start, mid);\n            build(2*node+1, mid+1, end);\n            tree[node] = Math.min(tree[2*node],tree[2*node+1]);\n        }\n    }\n\n    public static int query(int node, int start, int end, int l, int r)\n    {\n        if(r < start || end < l)\n        {\n\n            return MAX;\n        }\n        if(l <= start && end <= r)\n        {\n\n            return tree[node];\n        }\n\n        int mid = (start + end) / 2;\n        int p1 = query(2*node, start, mid, l, r);\n        int p2 = query(2*node+1, mid+1, end, l, r);\n        return Math.min(p1,p2);\n    }\n\n    public static void update(int node, int start, int end, int idx, int val)\n    {\n        if(start == end)\n        {\n            // Leaf node\n            arr[idx] = val;\n            tree[node] = val;\n        }\n        else\n        {\n            int mid = (start + end) / 2;\n            if(start <= idx && idx <= mid)\n            {\n\n                update(2*node, start, mid, idx, val);\n            }\n            else\n            {\n\n                update(2*node+1, mid+1, end, idx, val);\n            }\n\n\n            tree[node] = Math.min(tree[2*node], tree[2*node +1]);\n        }\n    }\n\n}\n\n\n"
  },
  {
    "path": "Segment Trees/Java/SegementTreeLazyPropagation.java",
    "content": "/*\n* @author Nikunj Khokhar\n*/\n\n// Java program to demonstrate lazy propagation in segment tree\nclass LazySegmentTree\n{\n    final int MAX = 1000;        // Max tree size\n    int tree[] = new int[MAX];  // To store segment tree\n    int lazy[] = new int[MAX];  // To store pending updates\n \n    /*  si -> index of current node in segment tree\n        ss and se -> Starting and ending indexes of elements for\n                     which current nodes stores sum.\n        us and eu -> starting and ending indexes of update query\n        ue  -> ending index of update query\n        diff -> which we need to add in the range us to ue */\n    void updateRangeUtil(int si, int ss, int se, int us,\n                         int ue, int diff)\n    {\n        // If lazy value is non-zero for current node of segment\n        // tree, then there are some pending updates. So we need\n        // to make sure that the pending updates are done before\n        // making new updates. Because this value may be used by\n        // parent after recursive calls (See last line of this\n        // function)\n        if (lazy[si] != 0)\n        {\n            // Make pending updates using value stored in lazy\n            // nodes\n            tree[si] += (se - ss + 1) * lazy[si];\n \n            // checking if it is not leaf node because if\n            // it is leaf node then we cannot go further\n            if (ss != se)\n            {\n                // We can postpone updating children we don't\n                // need their new values now.\n                // Since we are not yet updating children of si,\n                // we need to set lazy flags for the children\n                lazy[si * 2 + 1] += lazy[si];\n                lazy[si * 2 + 2] += lazy[si];\n            }\n \n            // Set the lazy value for current node as 0 as it\n            // has been updated\n            lazy[si] = 0;\n        }\n \n        // out of range\n        if (ss > se || ss > ue || se < us)\n            return;\n \n        // Current segment is fully in range\n        if (ss >= us && se <= ue)\n        {\n            // Add the difference to current node\n            tree[si] += (se - ss + 1) * diff;\n \n            // same logic for checking leaf node or not\n            if (ss != se)\n            {\n                // This is where we store values in lazy nodes,\n                // rather than updating the segment tree itelf\n                // Since we don't need these updated values now\n                // we postpone updates by storing values in lazy[]\n                lazy[si * 2 + 1] += diff;\n                lazy[si * 2 + 2] += diff;\n            }\n            return;\n        }\n \n        // If not completely in rang, but overlaps, recur for\n        // children,\n        int mid = (ss + se) / 2;\n        updateRangeUtil(si * 2 + 1, ss, mid, us, ue, diff);\n        updateRangeUtil(si * 2 + 2, mid + 1, se, us, ue, diff);\n \n        // And use the result of children calls to update this\n        // node\n        tree[si] = tree[si * 2 + 1] + tree[si * 2 + 2];\n    }\n \n    // Function to update a range of values in segment\n    // tree\n    /*  us and eu -> starting and ending indexes of update query\n        ue  -> ending index of update query\n        diff -> which we need to add in the range us to ue */\n    void updateRange(int n, int us, int ue, int diff)  {\n        updateRangeUtil(0, 0, n - 1, us, ue, diff);\n    }\n \n    /*  A recursive function to get the sum of values in given\n        range of the array. The following are parameters for\n        this function.\n        si --> Index of current node in the segment tree.\n               Initially 0 is passed as root is always at'\n               index 0\n        ss & se  --> Starting and ending indexes of the\n                     segment represented by current node,\n                     i.e., tree[si]\n        qs & qe  --> Starting and ending indexes of query\n                     range */\n    int getSumUtil(int ss, int se, int qs, int qe, int si)\n    {\n        // If lazy flag is set for current node of segment tree,\n        // then there are some pending updates. So we need to\n        // make sure that the pending updates are done before\n        // processing the sub sum query\n        if (lazy[si] != 0)\n        {\n            // Make pending updates to this node. Note that this\n            // node represents sum of elements in arr[ss..se] and\n            // all these elements must be increased by lazy[si]\n            tree[si] += (se - ss + 1) * lazy[si];\n \n            // checking if it is not leaf node because if\n            // it is leaf node then we cannot go further\n            if (ss != se)\n            {\n                // Since we are not yet updating children os si,\n                // we need to set lazy values for the children\n                lazy[si * 2 + 1] += lazy[si];\n                lazy[si * 2 + 2] += lazy[si];\n            }\n \n            // unset the lazy value for current node as it has\n            // been updated\n            lazy[si] = 0;\n        }\n \n        // Out of range\n        if (ss > se || ss > qe || se < qs)\n            return 0;\n \n        // At this point sure, pending lazy updates are done\n        // for current node. So we can return value (same as\n        // was for query in our previous post)\n \n        // If this segment lies in range\n        if (ss >= qs && se <= qe)\n            return tree[si];\n \n        // If a part of this segment overlaps with the given\n        // range\n        int mid = (ss + se) / 2;\n        return getSumUtil(ss, mid, qs, qe, 2 * si + 1) +\n               getSumUtil(mid + 1, se, qs, qe, 2 * si + 2);\n    }\n \n    // Return sum of elements in range from index qs (query\n    // start) to qe (query end).  It mainly uses getSumUtil()\n    int getSum(int n, int qs, int qe)\n    {\n        // Check for erroneous input values\n        if (qs < 0 || qe > n - 1 || qs > qe)\n        {\n            System.out.println(\"Invalid Input\");\n            return -1;\n        }\n \n        return getSumUtil(0, n - 1, qs, qe, 0);\n    }\n \n    /* A recursive function that constructs Segment Tree for\n      array[ss..se]. si is index of current node in segment\n      tree st. */\n    void constructSTUtil(int arr[], int ss, int se, int si)\n    {\n        // out of range as ss can never be greater than se\n        if (ss > se)\n            return;\n \n        /* If there is one element in array, store it in\n         current node of segment tree and return */\n        if (ss == se)\n        {\n            tree[si] = arr[ss];\n            return;\n        }\n \n        /* If there are more than one elements, then recur\n           for left and right subtrees and store the sum\n           of values in this node */\n        int mid = (ss + se) / 2;\n        constructSTUtil(arr, ss, mid, si * 2 + 1);\n        constructSTUtil(arr, mid + 1, se, si * 2 + 2);\n \n        tree[si] = tree[si * 2 + 1] + tree[si * 2 + 2];\n    }\n \n    /* Function to construct segment tree from given array.\n       This function allocates memory for segment tree and\n       calls constructSTUtil() to fill the allocated memory */\n    void constructST(int arr[], int n)\n    {\n        // Fill the allocated memory st\n        constructSTUtil(arr, 0, n - 1, 0);\n    }\n \n \n    // Driver program to test above functions\n    public static void main(String args[])\n    {\n        int arr[] = {1, 3, 5, 7, 9, 11};\n        int n = arr.length;\n        LazySegmentTree tree = new LazySegmentTree();\n \n        // Build segment tree from given array\n        tree.constructST(arr, n);\n \n        // Print sum of values in array from index 1 to 3\n        System.out.println(\"Sum of values in given range = \" +\n                           tree.getSum(n, 1, 3));\n \n        // Add 10 to all nodes at indexes from 1 to 5.\n        tree.updateRange(n, 1, 5, 10);\n \n        // Find sum after the value is updated\n        System.out.println(\"Updated sum of values in given range = \" +\n                           tree.getSum(n, 1, 3));\n    }\n}\n"
  },
  {
    "path": "Sorting Algorithms/C:C++/Counting_Sort.cpp",
    "content": "#include<iostream>\nusing namespace std;\n\nint main()\n{\n int N,x;\n\n    cin>>N;\n    int A[N];\n    //The elements of the array must not exceed the size of the array.\n    //This algo is ideally suited for numbers within a range with repetitions.\n    for(int i=0;i<N;i++)\n    {\n        cin>>A[i];\n    }\n\n     // Find the maximum value in A[]\n    int K = 0;\n    for(int i=0; i<N; i++) {\n        K = max(K, A[i]);\n    }\n\n    int Aux[N];\n      // Initialize the elements of Aux[] with 0\n    for(int i=0 ; i<=K; i++) {\n        Aux[i] = 0;\n    }\n\n     // Store the frequencies of each element of A[],\n    // by mapping its value as the index of Aux[] array\n    for(int i=0; i<N; i++) {\n        Aux[A[i]]++;\n    }\n\n    int sortedA[N];\n    int j = 0;\n    for(int i=0; i<=K; i++) {\n        int tmp = Aux[i];\n        // Aux stores which element occurs how many times,\n        // Add i in sortedA[] according to the number of times i occured in A[]\n        while(tmp--) {\n\n            sortedA[j] = i;\n            j++;\n        }\n    }\n    for(int i=0;i<N; i++)\n    {\n        cout<<sortedA[i]<<\" \";\n\n    }\n\n\n\n}\n"
  },
  {
    "path": "Sorting Algorithms/C:C++/Insertion_sort.cpp",
    "content": "/* C++ Program - Insertion Sort */\n\t\t\n#include<iostream.h>\n#include<conio.h>\nvoid main()\n{\n\tclrscr();\n\tint size, arr[50], i, j, temp;\n\tcout<<\"Enter Array Size : \";\n\tcin>>size;\n\tcout<<\"Enter Array Elements : \";\n\tfor(i=0; i<size; i++)\n\t{\n\t\tcin>>arr[i];\n\t}\n\tcout<<\"Sorting array using selection sort ... \\n\";\n\tfor(i=1; i<size; i++)\n\t{\n\t\ttemp=arr[i];\n\t\tj=i-1;\n\t\twhile((temp<arr[j]) && (j>=0))\n\t\t{\n\t\t\tarr[j+1]=arr[j];\n\t\t\tj=j-1;\n\t\t}\n\t\tarr[j+1]=temp;\n\t}\n\tcout<<\"Array after sorting : \\n\";\n\tfor(i=0; i<size; i++)\n\t{\n\t\tcout<<arr[i]<<\" \";\n\t}\n\tgetch();\n}\n"
  },
  {
    "path": "Sorting Algorithms/C:C++/Merge_sort.cpp",
    "content": "#include <iostream>\n \nusing namespace std;\n \n// A function to merge the two half into a sorted data.\nvoid Merge(int *a, int low, int high, int mid)\n{\n\t// We have low to mid and mid+1 to high already sorted.\n\tint i, j, k, temp[high-low+1];\n\ti = low;\n\tk = 0;\n\tj = mid + 1;\n \n\t// Merge the two parts into temp[].\n\twhile (i <= mid && j <= high)\n\t{\n\t\tif (a[i] < a[j])\n\t\t{\n\t\t\ttemp[k] = a[i];\n\t\t\tk++;\n\t\t\ti++;\n\t\t}\n\t\telse\n\t\t{\n\t\t\ttemp[k] = a[j];\n\t\t\tk++;\n\t\t\tj++;\n\t\t}\n\t}\n \n\t// Insert all the remaining values from i to mid into temp[].\n\twhile (i <= mid)\n\t{\n\t\ttemp[k] = a[i];\n\t\tk++;\n\t\ti++;\n\t}\n \n\t// Insert all the remaining values from j to high into temp[].\n\twhile (j <= high)\n\t{\n\t\ttemp[k] = a[j];\n\t\tk++;\n\t\tj++;\n\t}\n \n \n\t// Assign sorted data stored in temp[] to a[].\n\tfor (i = low; i <= high; i++)\n\t{\n\t\ta[i] = temp[i-low];\n\t}\n}\n \n// A function to split array into two parts.\nvoid MergeSort(int *a, int low, int high)\n{\n\tint mid;\n\tif (low < high)\n\t{\n\t\tmid=(low+high)/2;\n\t\t// Split the data into two half.\n\t\tMergeSort(a, low, mid);\n\t\tMergeSort(a, mid+1, high);\n \n\t\t// Merge them to get sorted output.\n\t\tMerge(a, low, high, mid);\n\t}\n}\n \nint main()\n{\n\tint n, i;\n\tcout<<\"\\nEnter the number of data element to be sorted: \";\n\tcin>>n;\n \n\tint arr[n];\n\tfor(i = 0; i < n; i++)\n\t{\n\t\tcout<<\"Enter element \"<<i+1<<\": \";\n\t\tcin>>arr[i];\n\t}\n \n\tMergeSort(arr, 0, n-1);\n \n\t// Printing the sorted data.\n\tcout<<\"\\nSorted Data \";\n\tfor (i = 0; i < n; i++)\n        cout<<\"->\"<<arr[i];\n \n\treturn 0;\n}\n"
  },
  {
    "path": "Sorting Algorithms/C:C++/QuickSort.c",
    "content": "/***********************************************************\n* You can use all the programs on  www.c-program-example.com\n* for personal and learning purposes. For permissions to use the\n* programs for commercial purposes,\n* contact info@c-program-example.com\n* To find more C programs, do visit www.c-program-example.com\n* and browse!\n* \n*                                  Happy Coding\n***********************************************************/\n\n\n#include<stdio.h>\n\nvoid swap (int a[], int left, int right)\n{\n int temp;\n temp=a[left];\n a[left]=a[right];\n a[right]=temp; \n}//end swap\n\nvoid quicksort( int a[], int low, int high )\n{\n int pivot;\n // Termination condition! \n if ( high > low )\n {\n  pivot = partition( a, low, high );\n  quicksort( a, low, pivot-1 );\n  quicksort( a, pivot+1, high );\n }\n} //end quicksort\n\nint partition( int a[], int low, int high )\n{\n int left, right;\n int pivot_item;\n int pivot = left = low; \n pivot_item = a[low]; \n right = high;\n while ( left < right ) \n {\n  // Move left while item < pivot \n  while( a[left] <= pivot_item ) \n   left++;\n  // Move right while item > pivot \n  while( a[right] > pivot_item ) \n   right--;\n  if ( left < right ) \n   swap(a,left,right);\n }\n // right is final position for the pivot \n a[low] = a[right];\n a[right] = pivot_item;\n return right;\n}//end partition\n\n// void quicksort(int a[], int, int);\nvoid printarray(int a[], int);\n\nint main()\n{\n int a[50], i, n;\n printf(\"nEnter no. of elements: \"); \n scanf(\"%d\", &n);\n printf(\"nEnter the elements: n\");\n for (i=0; i<n; i++)\n  scanf (\"%d\", &a[i]);\n printf(\"nUnsorted elements: n\");\n printarray(a,n);\n quicksort(a,0,n-1);\n printf(\"nSorted elements: n\");\n printarray(a,n);\n\n}//end main\n\n\nvoid printarray(int a[], int n)\n{\n int i;\n for (i=0; i<n; i++)\n  printf(\" %d \", a[i]);\n printf(\"n\");\n}//end printarray\n"
  },
  {
    "path": "Sorting Algorithms/C:C++/Quick_sort.cpp",
    "content": "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n21\n22\n23\n24\n25\n26\n27\n28\n29\n30\n31\n32\n33\n34\n35\n36\n37\n38\n39\n40\n41\n42\n43\n44\n45\n46\n47\n48\n49\n50\n51\n52\n53\n54\n55\n56\n57\n58\n59\n60\n61\n62\n63\n64\n65\n66\n67\n68\n#include <iostream>\n \nusing namespace std;\n \nvoid quick_sort(int[],int,int);\nint partition(int[],int,int);\n \nint main()\n{\n    int a[50],n,i;\n    cout<<\"How many elements?\";\n    cin>>n;\n    cout<<\"\\nEnter array elements:\";\n    \n    for(i=0;i<n;i++)\n        cin>>a[i];\n        \n    quick_sort(a,0,n-1);\n    cout<<\"\\nArray after sorting:\";\n    \n    for(i=0;i<n;i++)\n        cout<<a[i]<<\" \";\n    \n    return 0;        \n}\n \nvoid quick_sort(int a[],int l,int u)\n{\n    int j;\n    if(l<u)\n    {\n        j=partition(a,l,u);\n        quick_sort(a,l,j-1);\n        quick_sort(a,j+1,u);\n    }\n}\n \nint partition(int a[],int l,int u)\n{\n    int v,i,j,temp;\n    v=a[l];\n    i=l;\n    j=u+1;\n    \n    do\n    {\n        do\n            i++;\n            \n        while(a[i]<v&&i<=u);\n        \n        do\n            j--;\n        while(v<a[j]);\n        \n        if(i<j)\n        {\n            temp=a[i];\n            a[i]=a[j];\n            a[j]=temp;\n        }\n    }while(i<j);\n    \n    a[l]=a[j];\n    a[j]=v;\n    \n    return(j);\n}\n"
  },
  {
    "path": "Sorting Algorithms/C:C++/Radix_sort.cpp",
    "content": "#include <iostream.h>\n#include <conio.h>\n#define MAX 10\n\nclass radixsort{\n    int arr[MAX],n;\n    public:\n    void getdata();\n    void showdata();\n    void sortLogic();\n};\n\nvoid radixsort :: getdata(){\n    cout<<\"How many elements you require : \";\n    cin>>n;\n    for(int i=0;i<n;i++)\n        cin>>arr[i];\n}\n\nvoid radixsort :: showdata(){\n    cout<<\"\\n--Display--\\n\";\n    for(int i=0;i<n;i++)\n        cout<<arr[i]<<\"   \";\n}\n\nvoid radixsort :: sortLogic(){\n    //for base 10int temp;\n    int bucket[10][20], buck_count[10], b[10];\n    int i,j,k,r,no_of_passes=0,divisor=1,largest,pass_no;\n\n    largest=arr[0];\n\n    for(i=1;i<n;i++)  //Find the largest Number\n    {\n        if(arr[i] > largest)\n            largest=arr[i];\n    }\n\n    while(largest > 0)  //Find number of digits in largest number\n    {\n        no_of_passes++;\n        largest /= 10;\n    }\n\n    for(pass_no=0; pass_no < no_of_passes; pass_no++){\n\n        for(k=0; k<10; k++)\n            buck_count[k]=0; //Initialize bucket countfor(i=0;i<n;i++){\n            r=(arr[i]/divisor) % 10;\n            bucket[r][buck_count[r]++]=arr[i];\n        }\n        i=0; //collect elements from bucketfor(k=0; k<10; k++){\n            for(j=0; j<buck_count[k]; j++)\n                arr[i++] = bucket[k][j];\n        }\n\n        divisor *= 10;\n    }\n}\n\nvoid main(){\n    clrscr();\n    cout<<\"\\n*****Radix Sort*****\\n\";\n    radixsort obj;\n    obj.getdata();\n    obj.sortLogic();\n    obj.showdata();\n    getch();\n    }\n"
  },
  {
    "path": "Sorting Algorithms/C:C++/bubblesort.c",
    "content": "#include<iostream>\nusing namespace std;\n\n\nint main(){\n\n    int a[10]; ///Creates an array of 10 integers\n    int n,key;\n\n    cin>>n;\n    ///Read n numbers;\n    for(int i=0;i<n;i++){\n        cin>>a[i];\n    }\n\n    ///Bubble Sort - Optimised\n    for(int times=0;times<n-1;times++){\n\n        bool swaps=0;\n        ///Pair Wise Swapping starting from 0th positon\n\n        for(int j=0;j<=n-times-2;j++){\n            if(a[j]>a[j+1]){\n                ///Inbuild Swap Fn\n                swap(a[j],a[j+1]);\n                swaps++;\n            }\n        }\n        if(swaps==0){\n            break;\n        }\n    }\n\n    ///Print\n    for(int i=0;i<n;i++){\n        cout<<a[i]<<endl;\n    }\n\nreturn 0;\n}\n\n"
  },
  {
    "path": "Sorting Algorithms/C:C++/bubblesort.cpp",
    "content": "/* C++ Program - Bubble Sort */\n\t\t\n#include<iostream.h>\n#include<conio.h>\nvoid main()\n{\n\tclrscr();\n\tint n, i, arr[50], j, temp;\n\tcout<<\"Enter total number of elements :\";\n\tcin>>n;\n\tcout<<\"Enter \"<<n<<\" numbers :\";\n\tfor(i=0; i<n; i++)\n\t{\n\t\tcin>>arr[i];\n\t}\n\tcout<<\"Sorting array using bubble sort technique...\\n\";\n\tfor(i=0; i<(n-1); i++)\n\t{\n\t\tfor(j=0; j<(n-i-1); j++)\n\t\t{\n\t\t\tif(arr[j]>arr[j+1])\n\t\t\t{\n\t\t\t\ttemp=arr[j];\n\t\t\t\tarr[j]=arr[j+1];\n\t\t\t\tarr[j+1]=temp;\n\t\t\t}\n\t\t}\n\t}\n\tcout<<\"Elements sorted successfully..!!\\n\";\n\tcout<<\"Sorted list in ascending order :\\n\";\n\tfor(i=0; i<n; i++)\n\t{\n\t\tcout<<arr[i]<<\" \";\n\t}\n\tgetch();\n}\n"
  },
  {
    "path": "Sorting Algorithms/C:C++/bucketsort.c",
    "content": "#include<stdio.h>\n \n#define SIZE 10\n \nvoid bucketSort(int a[], int n) {\n    int i, j, k, buckets[SIZE];\n    \n    for(i = 0; i < SIZE; ++i)\n        buckets[i] = 0;\n    \n    for(i = 0; i < n; ++i)\n        ++buckets[a[i]];\n        \n    for(i = 0, j = 0; j < SIZE; ++j)\n        for(k = buckets[j]; k > 0; --k)\n            a[i++] = j;\n}\n \nint main() {\n    int i, a[] = {3, 6, 5, 1, 8, 4, 3, 1}, n = 8;\n    \n    printf(\"Before sorting:\\n\");\n    for(i = 0; i < n; ++i)\n        printf(\"%d \", a[i]);\n    \n    bucketSort(a, n);\n    \n    printf(\"\\n\\nAfter sorting:\\n\");\n    for(i = 0; i < n; ++i)\n        printf(\"%d \", a[i]);\n    \n    return 0;\n}\n"
  },
  {
    "path": "Sorting Algorithms/C:C++/heapSort.c",
    "content": "#include <stdio.h>\n\nint heapify(int* a, int i, int n)\n{\n\tint j=(2*i+1),k=(2*i+2),x;\n\tif(j<=n)\n\t{\n\t\tif(k<=n)\n\t\t\tif(a[k]>a[j])\n\t\t\t\tj=k;\n\t\tif(a[j]>a[i])\n\t\t{\n\t\t\tx=a[j];\n\t\t\ta[j]=a[i];\n\t\t\ta[i]=x;\n\t\t\theapify(a,j,n);\n\t\t}\n\t}\n\treturn 0;\n}\nint buildheap(int *a, int n)\n{\n\tint i;\n\tfor(i=n/2;i>=0;i--)\n\t\theapify(a,i,n-1);\n\treturn 0;\n}\nint sort(int* a, int n)\n{\n\tint x,i;\n\tbuildheap(a,n);\n\tx=a[0];\n\ta[0]=a[n-1];\n\ta[n-1]=x;\n\tfor(i=n-2;i>=0;i--)\n\t{\n\t\theapify(a,0,i);\n\t\tx=a[0];\n\t\ta[0]=a[i];\n\t\ta[i]=x;\n\t}\n\treturn 0;\n}\nint main()\n{\n \n    return 0;\n}"
  },
  {
    "path": "Sorting Algorithms/C:C++/insertion.hpp",
    "content": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nvoid insertion_sort(int length, int v[]){\r\n\tfor(int i=0;i<length;i++){\r\n\t\tint j = i;\r\n\t\twhile(j>0 && v[j] < v[j-1]){\r\n\t\t\tswap(v[j], v[j-1]);\r\n\t\t\tj--;\r\n\t\t}\r\n\t}\r\n}\r\n"
  },
  {
    "path": "Sorting Algorithms/C:C++/merge.hpp",
    "content": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nvoid _merge(int v[], int left, int mid, int right){\r\n\tint i, j, k;\r\n\tint n1 = mid - left + 1; // size of first subarray\r\n    int n2 =  right - mid; // size of second subarray\r\n \r\n    // create temp arrays\r\n    int L[n1], R[n2];\r\n \r\n    // Copy data to temp arrays L[] and R[]\r\n    for (i = 0; i < n1; i++)\r\n        L[i] = v[left + i];\r\n    for (j = 0; j < n2; j++)\r\n        R[j] = v[mid + 1+ j];\r\n \r\n    /* Merge the temp arrays back into arr[l..r]*/\r\n    i = 0; // Initial index of first subarray\r\n    j = 0; // Initial index of second subarray\r\n    k = left; // Initial index of merged subarray\r\n    while (i < n1 && j < n2){\r\n        if (L[i] <= R[j]){\r\n            v[k] = L[i];\r\n            i++;\r\n        }else{\r\n            v[k] = R[j];\r\n            j++;\r\n        }\r\n        k++;\r\n    }\r\n \r\n    /* Copy the remaining elements of L[], if there\r\n       are any */\r\n    while (i < n1){\r\n        v[k] = L[i];\r\n        i++;\r\n        k++;\r\n    }\r\n \r\n    /* Copy the remaining elements of R[], if there\r\n       are any */\r\n    while (j < n2){\r\n        v[k] = R[j];\r\n        j++;\r\n        k++;\r\n    }\r\n}\r\n\r\nvoid _merge_sort(int v[], int left, int right){\r\n\tif(left < right){\r\n\t\t// same as (left + right) / 2, but avoids overflow due to large values of left and right\r\n\t\tint mid = left + (right - left) / 2;\r\n\t\t_merge_sort(v, left, mid);\r\n\t\t_merge_sort(v, mid + 1, right);\r\n\r\n\t\t_merge(v, left, mid, right);\r\n\t}\r\n}\r\n\r\nvoid merge_sort(int length, int v[]){\r\n\t_merge_sort(v, 0, length-1);\r\n}"
  },
  {
    "path": "Sorting Algorithms/C:C++/quick.hpp",
    "content": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nint _partition(int v[], int left, int right){\r\n\tint pivot = v[right];\r\n\tint i = left-1;\r\n\tfor(int j=left;j<right-1;j++){\r\n\t\tif(v[j] <= pivot){\r\n\t\t\ti++;\r\n\t\t\tswap(v[i], v[j]);\r\n\t\t}\r\n\t}\r\n\ti++;\r\n\tswap(v[i], v[right]);\r\n\treturn i;\r\n}\r\n\r\nvoid _quick(int v[], int left, int right){\r\n\tif(left < right){\r\n\t\tint partition_index = _partition(v, left, right);\r\n\t\t_quick(v, left, partition_index - 1);\r\n\t\t_quick(v, partition_index + 1, right);\r\n\t}\r\n}\r\n\r\nvoid quick_sort(int length, int v[]){\r\n\t_quick(v, 0, length - 1);\r\n}"
  },
  {
    "path": "Sorting Algorithms/C:C++/quick_sort.c",
    "content": "#include<stdio.h>\nvoid quicksort(int number[25],int first,int last){\n   int i, j, pivot, temp;\n\n   if(first<last){\n      pivot=first;\n      i=first;\n      j=last;\n\n      while(i<j){\n         while(number[i]<=number[pivot]&&i<last)\n            i++;\n         while(number[j]>number[pivot])\n            j--;\n         if(i<j){\n            temp=number[i];\n            number[i]=number[j];\n            number[j]=temp;\n         }\n      }\n\n      temp=number[pivot];\n      number[pivot]=number[j];\n      number[j]=temp;\n      quicksort(number,first,j-1);\n      quicksort(number,j+1,last);\n\n   }\n}\n\nint main(){\n   int i, count, number[25];\n\n   printf(\"How many elements are u going to enter?: \");\n   scanf(\"%d\",&count);\n\n   printf(\"Enter %d elements: \", count);\n   for(i=0;i<count;i++)\n      scanf(\"%d\",&number[i]);\n\n   quicksort(number,0,count-1);\n\n   printf(\"Order of Sorted elements: \");\n   for(i=0;i<count;i++)\n      printf(\" %d\",number[i]);\n\n   return 0;\n}\n"
  },
  {
    "path": "Sorting Algorithms/C:C++/radix.hpp",
    "content": "#include <bits/stdc++.h>\r\nusing namespace std;\r\n\r\nvoid _count_sort(int arr[], int length, int exp){\r\n    int output[length]; // output array\r\n    int i, count[10] = {0};\r\n \r\n    // Store count of occurrences in count[]\r\n    for (i = 0; i < length; i++) count[ (arr[i]/exp)%10 ]++;\r\n \r\n    // Change count[i] so that count[i] now contains actual\r\n    //  position of this digit in output[]\r\n    for (i = 1; i < 10; i++) count[i] += count[i - 1];\r\n \r\n    // Build the output array\r\n    for (i = length - 1; i >= 0; i--){\r\n        output[ count[ (arr[i]/exp)%10 ] - 1] = arr[i];\r\n        count[ (arr[i]/exp)%10 ]--;\r\n    }\r\n \r\n    // Copy the output array to arr[], so that arr[] now\r\n    // contains sorted numbers according to current digit\r\n    for (i = 0; i < length; i++) arr[i] = output[i];\r\n}\r\n\r\nvoid radix_sort(int length, int v[]){\r\n\tint mx = *max_element(v, v+length);\r\n\tfor(int i = 1; mx / i > 0; i *= 10){\r\n\t\t_count_sort(v, length, i);\r\n\t}\r\n}"
  },
  {
    "path": "Sorting Algorithms/C:C++/selectionsort.c",
    "content": "/*Take as input N, the size of array. Take N more inputs and store that in an array. \nWrite a function that selection sorts the array. Print the elements of sorted array.\n\n1.It reads a number N.\n2.Take Another N numbers as input and store them in an Array.\n3.Sort the array using Selection Sort and print that Array. */\n\n// C program for implementation of selection sort\n#include <stdio.h>\n \nvoid swap(int *xp, int *yp)\n{\n    int temp = *xp;\n    *xp = *yp;\n    *yp = temp;\n}\n \nvoid selectionSort(int arr[], int n)\n{\n    int i, j, min_idx;\n \n    // One by one move boundary of unsorted subarray\n    for (i = 0; i < n-1; i++)\n    {\n        // Find the minimum element in unsorted array\n        min_idx = i;\n        for (j = i+1; j < n; j++)\n          if (arr[j] < arr[min_idx])\n            min_idx = j;\n \n        // Swap the found minimum element with the first element\n        swap(&arr[min_idx], &arr[i]);\n    }\n}\n \n/* Function to print an array */\nvoid printArray(int arr[], int size)\n{\n    int i;\n    for (i=0; i < size; i++)\n        printf(\"%d \", arr[i]);\n    printf(\"\\n\");\n}\n \n// Driver program to test above functions\nint main()\n{\n    int arr[] = {64, 25, 12, 22, 11};\n    int n = sizeof(arr)/sizeof(arr[0]);\n    selectionSort(arr, n);\n    printf(\"Sorted array: \\n\");\n    printArray(arr, n);\n    return 0;\n}\n"
  },
  {
    "path": "Sorting Algorithms/C:C++/shell_sort.h",
    "content": "#ifndef ALGO_SHELL_SORT_H__\n#define ALGO_SHELL_SORT_H__\n\nnamespace alg {\n\t/**\n\t * shell sort an array\n\t */\n\ttemplate<typename T>\n\t\tstatic void shell_sort(T *array, int len) {\n\t\t\tint h = 1;\n\t\t\twhile (h < len / 3) {\n\t\t\t\th = 3 * h + 1; // 1, 4, 13, 40, 121, ...\n\t\t\t}\n\t\t\twhile (h >= 1) {\n\t\t\t\tfor (int i = h; i < len; i++) {\n\t\t\t\t\tint cur = array[i];\n\t\t\t\t\tint j = i - h;\n\t\t\t\t\twhile (j >= 0 && array[j] > cur) {\n\t\t\t\t\t\tarray[j + h] = array[j];\n\t\t\t\t\t\tj = j - h;\n\t\t\t\t\t}\n\t\t\t\t\tarray[j + h] = cur;\n\t\t\t\t}\n\t\t\t\th = h / 3;\n\t\t\t}\n\t\t}\n}\n\n#endif //\n"
  },
  {
    "path": "Sorting Algorithms/C:C++/slow.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid _slow_sort(int v[], int i, int j) {\n  if (i >= j) return;\n  int m = i + (j-i)/2;\n  _slow_sort(v, i, m);\n  _slow_sort(v, m+1, j);\n  if (v[j] < v[m])\n    swap(v[j], v[m]);\n  _slow_sort(v, i, j-1);\n}\n\nvoid slow_sort(int length, int v[]) {\n  _slow_sort(v, 0, length-1);\n}\n\n"
  },
  {
    "path": "Sorting Algorithms/C:C++/sorting_a_vector.cpp",
    "content": "#include<iostream>\r\n#include<cstring>\r\n#include<vector>\r\n#include<algorithm>\r\nusing namespace std;\r\n\r\nbool compare(int a,int b){\r\n    return a>b;\r\n}\r\n\r\nint main(){\r\n\r\n    vector<int> v;\r\n\r\n    for(int i=1;i<5;i++){\r\n        v.push_back(i);\r\n    }\r\n    int p;\r\n    cin>>p;\r\n\r\n    int d;\r\n    cin>>d;\r\n\r\n    v.insert(v.begin() + p,d);\r\n\r\n    for(int i=0;i<v.size();i++){\r\n        cout<<v[i]<<\" \";\r\n    }\r\n    cout<<endl;\r\n    ///Sort a vector\r\n    sort(v.begin(),v.end(),compare);\r\n\r\n     for(int i=0;i<v.size();i++){\r\n        cout<<v[i]<<\" \";\r\n    }\r\n\r\n\r\n\r\nreturn 0;\r\n}\r\n"
  },
  {
    "path": "Sorting Algorithms/Java/Countsort.java",
    "content": "public class CountingSort\n{\n    public static void sort(char arr[])\n    {\n        int n = arr.length;\n \n        // The output character array that will have sorted arr\n        char output[] = new char[n];\n \n        // Create a count array to store count of inidividul\n        // characters and initialize count array as 0\n        int count[] = new int[256];\n        for (int i = 0; i < 256; ++i)\n            count[i] = 0;\n \n        // store count of each character\n        for (int i=0; i<n; ++i)\n            ++count[arr[i]];\n \n        // Change count[i] so that count[i] now contains actual\n        // position of this character in output array\n        for (int i = 1; i <= 255; ++i)\n            count[i] += count[i-1];\n \n        // Build the output character array\n        for (int i = 0; i < n; ++i)\n        {\n            output[count[arr[i]] - 1] = arr[i];\n            --count[arr[i]];\n        }\n \n        // Copy the output array to arr, so that arr now\n        // contains sorted characters\n        for (int i = 0; i<n; ++i)\n            arr[i] = output[i];\n    }\n \n    public static void main(String args[])\n    {\n        char arr[] = {'h','a','c','k','t','o','b','e','r','f','e','s','t'};\n        \n        sort(arr);\n        System.out.print(\"Sorted character array is \");\n        for (int i=0; i<arr.length; ++i)\n            System.out.print(arr[i]);\n    }\n}"
  },
  {
    "path": "Sorting Algorithms/Java/HeapSort.java",
    "content": "import java.util.*;\n/*\n * Part of Cosmos by OpenGenus Foundation\n*/\npublic class HeapSort {\n    \n    public static void main(String[] args) {\n        // array used for testing\n        int[] a = {5, 11, 1234, 2, 6};\n        System.out.println(Arrays.toString(a));\n        sort(a);\n        System.out.println(Arrays.toString(a));\n    }\n\n    public static void sort(int[] a) {\n        int n = a.length;\n        // create the heap\n        for (int i = n / 2 - 1; i >= 0; i--)\n            heapify(a, n, i);\n \n        // extract element from the heap\n        for (int i=n-1; i>=0; i--)\n        {\n            int temp = a[0];\n            a[0] = a[i];\n            a[i] = temp;\n \n            // rebuild the heap\n            heapify(a, i, 0);\n        }\n    }\n\n    public static void heapify(int arr[], int n, int i)\n    {\n        int largest = i;\n        int l = 2*i + 1;\n        int r = 2*i + 2;   \n\n        // If left child is larger than root\n        if (l < n && arr[l] > arr[largest])\n            largest = l;\n \n        // If right child is larger than largest so far\n        if (r < n && arr[r] > arr[largest])\n            largest = r;\n \n        // If largest is not root\n        if (largest != i)\n        {\n            int swap = arr[i];\n            arr[i] = arr[largest];\n            arr[largest] = swap;\n \n            // Recursively heapify the affected sub-tree\n            heapify(arr, n, largest);\n        }\n    }\n}\n"
  },
  {
    "path": "Sorting Algorithms/Java/MergeSort.java",
    "content": "package test;\n\npublic class test {\n\n\tpublic static void main(String[] args) {\n\n\t\tString[] nums = { \"AB\", \"DD\", \"CC\", \"BB\", \"CA\", \"AA\" };\n\n\t\tmergeSort(nums, 0, nums.length - 1);\n\n\t\tSystem.out.println(\"Sorted character strings : \");\n\t\tfor (String i : nums) {\n\t\t\tSystem.out.println(i);\n\t\t}\n\t}\n\n\tpublic static void mergeSort(String[] a, int low, int high) {\n\t\tint mid;\n\t\tif (low < high) {\n\t\t\tmid = (low + high) / 2;\n\t\t\tmergeSort(a, low, mid);\n\t\t\tmergeSort(a, mid + 1, high);\n\t\t\tmerge(a, low, mid, high);\n\t\t}\n\t}\n\n\tpublic static void merge(String[] a, int low, int mid, int high) {\n\n\t\tint i, l, r, k;\n\t\tString[] temp = new String[a.length];\n\t\ti = low;\n\t\tl = low;\n\t\tr = mid + 1;\n\n\t\twhile (l <= mid && r <= high) {\n\t\t\tint letter = 0;\n\t\t\tboolean elementAdded = false;\n\t\t\twhile (letter < a[l].length() && letter < a[r].length()) {\n\t\t\t\tif (a[l].charAt(letter) < a[r].charAt(letter)) {\n\t\t\t\t\ttemp[i] = a[l];\n\t\t\t\t\telementAdded = true;\n\t\t\t\t\tl++;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\telse if (a[l].charAt(letter) > a[r].charAt(letter)) {\n\t\t\t\t\ttemp[i] = a[r];\n\t\t\t\t\telementAdded = true;\n\t\t\t\t\tr++;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tletter++;\n\t\t\t}\n\n\t\t\tif (!elementAdded) {\n\t\t\t\tif (a[l].length() < a[r].length()) {\n\t\t\t\t\ttemp[i] = a[l];\n\t\t\t\t\tl++;\n\t\t\t\t} else {\n\t\t\t\t\ttemp[i] = a[r];\n\t\t\t\t\tr++;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ti++;\n\t\t}\n\n\t\tif (l > mid) {\n\t\t\tfor (k = r; k <= high; k++) {\n\t\t\t\ttemp[i] = a[k];\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\n\t\telse {\n\t\t\tfor (k = l; k <= mid; k++) {\n\t\t\t\ttemp[i] = a[k];\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\n\t\tfor (k = low; k <= high; k++) {\n\t\t\ta[k] = temp[k];\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "Sorting Algorithms/Javascript/bubblesort.js",
    "content": "//function takes in array\nconst bubblesort = (array) => {\n  let length = array.length;\n  \n \n  for (let i=0;i<length-1;i++){\n    //no need to check last value of previous loop\n    for (let j=0;j<(length-i-1);j++){\n      //compare adjacent values\n      if (array[j] > array[j+1]){\n        //do the swap\n        let temp = array[j];\n        array[j] = array[j+1];\n        array[j+1] = temp;\n      } \n    }\n  }\n  \n  return array;\n}\n\n//test array\nconsole.log(bubblesort([3,17,24,4,5,1,4,2,3]));"
  },
  {
    "path": "Sorting Algorithms/Python/QuickSort.py",
    "content": "def partition(arr,low,high):\n    i = ( low-1 )         # index of smaller element\n    pivot = arr[high]     # pivot\n \n    for j in range(low , high):\n \n        # If current element is smaller than or\n        # equal to pivot\n        if   arr[j] <= pivot:\n         \n            # increment index of smaller element\n            i = i+1\n            arr[i],arr[j] = arr[j],arr[i]\n \n    arr[i+1],arr[high] = arr[high],arr[i+1]\n    return ( i+1 )\n \n# The main function that implements QuickSort\n# arr[] --> Array to be sorted,\n# low  --> Starting index,\n# high  --> Ending index\n \n# Function to do Quick sort\ndef quickSort(arr,low,high):\n    if low < high:\n \n        # pi is partitioning index, arr[p] is now\n        # at right place\n        pi = partition(arr,low,high)\n \n        # Separately sort elements before\n        # partition and after partition\n        quickSort(arr, low, pi-1)\n        quickSort(arr, pi+1, high)\n \n# Driver code to test above\narr = [10, 7, 8, 9, 1, 5]\nn = len(arr)\nquickSort(arr,0,n-1)\nprint (\"Sorted array is:\")\nfor i in range(n):\n    print (\"%d\" %arr[i]),\n"
  },
  {
    "path": "Sorting Algorithms/Python/bogosort.py",
    "content": "from random import shuffle\n\n# Sorting algorithm that relies solely on shuffling all\n# numbers until the array is sorted. Worst case scenario\n# is when it never sorts :(\n\ndef bogosort(my_array):\n    pos = 0\n    while True:\n        if(pos == (len(my_array)-1)):\n            break\n        while (my_array[pos] > my_array[pos+1]):\n            shuffle(my_array)\n            pos = 0\n        pos= 1)\n    return my_array\n"
  },
  {
    "path": "Sorting Algorithms/Python/bubblesort.py",
    "content": "def bubble_sort(arr):\n    changed = True\n    while changed:\n        changed = False\n        for i in range(len(arr) - 1):\n            if arr[i] > arr[i+1]:\n                arr[i], arr[i+1] = arr[i+1], arr[i]\n                changed = True\n    return None\n"
  },
  {
    "path": "Sorting Algorithms/Python/cocktailsort.py",
    "content": "# Cocktail sorting\n\n\n\n\ndef cocktailsort(a):\n\tn=len(a)\n\tswapped=True\n\tstart=0\n\tend=n-1\n\twhile(swapped==True):\n\t\tswapped=False\n\n\t\tfor i in range(start,end):\n\t\t\tif (a[i] > a[i+1]) :\n\t\t\t\ta[i], a[i+1]= a[i+1], a[i]\n\t\t\t\tswapped=True\n\t\tif (swapped==False) :\n\t\t\tbreak\n\t\tswapped=False\n\t\tend=end-1\n\t\tfor i in range(end-1,start-1,-1) :\n\t\t\tif (a[i] > a[i+1]) :\n\t\t\t\ta[i], a[i+1]= a[i+1], a[i]\n\t\t\t\tswapped=True\n\t\tstart=start+1\n\na=[8,2,1,3,4]\ncocktailsort(a)\nprint(\"Sorted array is:\")\nfor i in range(len(a)):\n\tprint (\"%d\" %a[i]),\n\n"
  },
  {
    "path": "Sorting Algorithms/Python/insertionsort.py",
    "content": "def insertion_sort(my_array):\n    ordered_array = []\n    for pos in range(len(my_array)):\n        new_pos = pos\n        while(new_pos > 0 and (my_array[new_pos] < my_array[new_pos-1])):\n            temp = my_array[new_pos]\n            my_array[new_pos] = my_array[new_pos-1]\n            my_array[new_pos-1] = temp\n            new_pos -= 1\n    return my_array\n"
  },
  {
    "path": "Sorting Algorithms/Python/mergesort.py",
    "content": "def mergeSort(nlist):\r\n\r\n    if len(nlist)>1:\r\n        mid = len(nlist)//2\r\n        lefthalf = nlist[:mid]\r\n        righthalf = nlist[mid:]\r\n\r\n        mergeSort(lefthalf)\r\n        mergeSort(righthalf)\r\n        i=j=k=0       \r\n        while i < len(lefthalf) and j < len(righthalf):\r\n            if lefthalf[i] < righthalf[j]:\r\n                nlist[k]=lefthalf[i]\r\n                i=i+1\r\n            else:\r\n                nlist[k]=righthalf[j]\r\n                j=j+1\r\n            k=k+1\r\n\r\n        while i < len(lefthalf):\r\n            nlist[k]=lefthalf[i]\r\n            i=i+1\r\n            k=k+1\r\n\r\n        while j < len(righthalf):\r\n            nlist[k]=righthalf[j]\r\n            j=j+1\r\n            k=k+1\r\n\r\nnlist = [14,46,43,27,57,41,45,21,70]\r\nmergeSort(nlist)\r\nprint(nlist)\r\n\r\n# time complexity : O(nlogn)\r\n# space complexity: O(logn)\r\n"
  },
  {
    "path": "Sorting Algorithms/Python/quicksort.py",
    "content": "def quickSort(data_list):\r\n   quickSortHlp(data_list,0,len(data_list)-1)\r\n\r\ndef quickSortHlp(data_list,first,last):\r\n   if first < last:\r\n\r\n       splitpoint = partition(data_list,first,last)\r\n\r\n       quickSortHlp(data_list,first,splitpoint-1)\r\n       quickSortHlp(data_list,splitpoint+1,last)\r\n\r\n\r\ndef partition(data_list,first,last):\r\n   pivotvalue = data_list[first]\r\n\r\n   leftmark = first+1\r\n   rightmark = last\r\n\r\n   done = False\r\n   while not done:\r\n\r\n       while leftmark <= rightmark and data_list[leftmark] <= pivotvalue:\r\n           leftmark = leftmark + 1\r\n\r\n       while data_list[rightmark] >= pivotvalue and rightmark >= leftmark:\r\n           rightmark = rightmark -1\r\n\r\n       if rightmark < leftmark:\r\n           done = True\r\n       else:\r\n           temp = data_list[leftmark]\r\n           data_list[leftmark] = data_list[rightmark]\r\n           data_list[rightmark] = temp\r\n\r\n   temp = data_list[first]\r\n   data_list[first] = data_list[rightmark]\r\n   data_list[rightmark] = temp\r\n\r\n\r\n   return rightmark\r\n\r\ndata_list = [54,26,93,17,77,31,44,55,20]\r\nquickSort(data_list)\r\nprint(data_list)\r\n"
  },
  {
    "path": "Sorting Algorithms/Python/topological_sort.py",
    "content": "#Python program to print topological sorting of a DAG\nfrom collections import defaultdict\n \n#Class to represent a graph\nclass Graph:\n    def __init__(self,vertices):\n        self.graph = defaultdict(list) #dictionary containing adjacency List\n        self.V = vertices #No. of vertices\n \n    # function to add an edge to graph\n    def addEdge(self,u,v):\n        self.graph[u].append(v)\n \n    # A recursive function used by topologicalSort\n    def topologicalSortUtil(self,v,visited,stack):\n \n        # Mark the current node as visited.\n        visited[v] = True\n \n        # Recur for all the vertices adjacent to this vertex\n        for i in self.graph[v]:\n            if visited[i] == False:\n                self.topologicalSortUtil(i,visited,stack)\n \n        # Push current vertex to stack which stores result\n        stack.insert(0,v)\n \n    # The function to do Topological Sort. It uses recursive \n    # topologicalSortUtil()\n    def topologicalSort(self):\n        # Mark all the vertices as not visited\n        visited = [False]*self.V\n        stack =[]\n \n        # Call the recursive helper function to store Topological\n        # Sort starting from all vertices one by one\n        for i in range(self.V):\n            if visited[i] == False:\n                self.topologicalSortUtil(i,visited,stack)\n \n        # Print contents of stack\n        print stack\n \ng= Graph(6)\ng.addEdge(5, 2);\ng.addEdge(5, 0);\ng.addEdge(4, 0);\ng.addEdge(4, 1);\ng.addEdge(2, 3);\ng.addEdge(3, 1);\n \nprint \"Following is a Topological Sort of the given graph\"\ng.topologicalSort()\n"
  },
  {
    "path": "Sorting Algorithms/sleep sort.c",
    "content": "#include <stdio.h>\r\n#include <windows.h>\r\n#include <process.h>\r\n \r\nvoid routine(void *a)\r\n{\r\n    int n = *(int *) a; // typecasting from void to int\r\n \r\n    // Sleeping time is proportional to the number\r\n    // More precisely this thread sleep for 'n' milliseconds\r\n    Sleep(n);\r\n \r\n    // After the sleep, print the number\r\n    printf(\"%d \", n);\r\n\r\nvoid sleepSort(int arr[], int n)\r\n{\r\n    // An array of threads, one for each of the elements\r\n    // in the input array\r\n    HANDLE threads[n];\r\n \r\n    // Create the threads for each of the input array elements\r\n    for (int i = 0; i < n; i++)\r\n        threads[i] = (HANDLE)_beginthread(&routine, 0,  &arr[i]);\r\n \r\n    // Process these threads\r\n    WaitForMultipleObjects(n, threads, TRUE, INFINITE);\r\n    return;\r\n}\r\n \r\n// Driver program to test above functions\r\nint main()\r\n{\r\n    // Doesn't work for negative numbers\r\n    int arr[] = {34, 23, 122, 9};\r\n    int n = sizeof(arr) / sizeof(arr[0]);\r\n \r\n    sleepSort (arr, n);\r\n \r\n    return(0);\r\n}"
  },
  {
    "path": "String Manipulation/C:C++/String_algo/KMP.cpp",
    "content": "/* \n   Time-Complexity :- O(length of string)\n   Used for outputing indices where a particular text appears in a given string\n*/\n#include<bits/stdc++.h>\n#include<sstream>\n#include<ext/pb_ds/tree_policy.hpp>\nusing namespace std;\n#define mod 1000000007\n#define all(v) v.begin(),v.end()\n#define loop(i,a,b) for(i=(int)a;i<(int)b;i++)\n#define revloop(i,a,b) for(i=(int)a;i>=(int)b;i--)\n#define stloop(it,v) for(it=v.begin();it!=v.end();++it)\n#define ii pair<int,int>\n#define MP make_pair\n#define pb push_back\n#define ll long long int\n#define fill(v,d) memset(v,d,sizeof(v))\n#define INF 1000000005\n#define PI acos(-1.0)\nvector<int> b;\nstring p,t;\nint i;\nvoid preprocess(string a)\n{\n  int i = 1,j = 0;\n  b[0] = 0;\n  while(i < (int)a.length())\n  {\n   while(j > 0 && a[i] != a[j])\n   { j--;\n     j= b[j];\n   }\n   if(a[i] == a[j])\n    j++;\n   b[i] = j;\n   i++;\n  }\n}\nvoid kmp(string a,string t)\n{\n  int i=0,j=0;\n  while(i<(int)a.length())\n  {\n    while(j > 0 && a[i] != t[j])\n    { j--;\n      j= b[j];\n    }\n    if(a[i] == t[j])\n     j++;\n    if(j == (int)t.length())\n    { cout<<i-j+1<<\" \";\n      j=b[t.length()-1];\n    }\n    i++;\n  }\n}\nint main()\n{  std::ios_base::sync_with_stdio(false); cin.tie(NULL);\n   cin>>t>>p;\n   b.resize(p.length());\n   preprocess(p);\n   loop(i,0,b.size())\n    cout<<b[i]<<\" \";\n   cout<<endl;\n   kmp(t,p);\n   return 0;\n}\n"
  },
  {
    "path": "String Manipulation/C:C++/String_algo/SUFFIX-ARRAY.cpp",
    "content": "/* \n   Time-Complexity :- O(nlog(n)^2),where n is the length of string\n   Used for outputing all the suffixes in a sorted way\n*/\n#include<bits/stdc++.h>\n#include<sstream>\n#include<ext/pb_ds/tree_policy.hpp>\nusing namespace std;\n#define mod 1000000007\n#define all(v) v.begin(),v.end()\n#define loop(i,a,b) for(i=(int)a;i<(int)b;i++)\n#define revloop(i,a,b) for(i=(int)a;i>=(int)b;i--)\n#define stloop(it,v) for(it=v.begin();it!=v.end();++it)\n#define ii pair<int,string>\n#define MP make_pair\n#define pb push_back\n#define ll long long int\n#define fill(v,d) memset(v,d,sizeof(v))\n#define INF 1000000005\n#define PI acos(-1.0)\nvector<vector<int> > sa;\nstruct mytuple{\n int orig;\n int first;\n int second;\n};\nbool cmp(mytuple a,mytuple b)\n{\n  if(a.first == b.first)\n    return a.second < b.second;\n  return a.first < b.first;\n}\nint main()\n{  std::ios_base::sync_with_stdio(false); cin.tie(NULL);\n   string a;\n   int i,n,curr,cnt,stp;\n   cin>>a;\n   n = a.length();\n   stp = log(n)/log(2) + 2;\n   sa.assign(stp,vector<int>(n));\n   loop(i,0,n)\n    sa[0][i] = a[i]-'a';\n   mytuple L[n];\n   stp = 1;\n   for(cnt = 1;cnt < n; cnt*=2)\n   {\n     for(i=0;i<n;i++)\n     {\n      L[i].first = sa[stp-1][i];\n      L[i].orig=i;\n      if(i+cnt<n)\n       L[i].second = sa[stp-1][i+cnt];\n      else\n       L[i].second = -1;\n     }\n     sort(L,L+n,cmp);\n     sa[stp][L[0].orig] = curr = 0;\n     for(i=1;i<n;i++)\n     {\n       if((L[i].first != L[i-1].first) || (L[i].second != L[i-1].second))\n        curr++;\n       sa[stp][L[i].orig] = curr;\n     }\n     stp++;\n   }\n   loop(i,0,n)\n   { stp = L[i].orig;\n     cout<<stp<<\" \"<<a.substr(stp,n-stp)<<endl;\n   }\n   return 0;\n}\n"
  },
  {
    "path": "String Manipulation/C:C++/String_algo/z_algorithm.cpp",
    "content": "/*\n  Complexity = O(length of string)\n  s = aaabaab => z[] = {-1,2,1,0,2,1,0}\n  s = aaaaa => z[] = {-1,4,3,2,1}\n  s = abacaba => z[] = {-1,0,1,0,3,0,1}\n*/\n#include<bits/stdc++.h>\nusing namespace std;\n#define mod 1000000007\n#define all(v) v.begin(),v.end()\n#define rep(i,a,b) for(i=(ll)a;i<(ll)b;i++)\n#define revrep(i,a,b) for(i=(ll)a;i>=(ll)b;i--)\n#define strep(it,v) for(it=v.begin();it!=v.end_();++it)\n#define ii pair<ll,ll>\n#define MP make_pair\n#define pb push_back\n#define f first\n#define se second\n#define ll long long int\n#define vi vector<ll>\nll modexp(ll a,ll b){ ll res = 1; while(b > 0){  if(b & 1) res = (res * a);  a = (a * a);  b/=2;  }  return res; }\n#define rs resize\nlong long readLI(){  register char c;  for(c = getchar(); !(c>='0' && c<='9'); c = getchar());  register long long a=c-'0';\n    for(c = getchar(); c>='0' && c<='9'; c = getchar())\n        a = (a<<3)+(a<<1)+c-'0';\n    return a;\n}\nconst int N = 100009;\nstring a;\nll i,z[N];\nvoid z_function(string s)\n{\n   ll l = 0,r = 0,n = s.length();\n   rep(i,1,n){\n       if(i <= r) z[i] = min(r - i + 1,z[i - l]);\n       while(i + z[i] < n and s[z[i]] == s[i + z[i]])\n        z[i]++;\n       if(i + z[i] - 1 > r)\n         l = i, r = i + z[i] - 1;\n   }\n}\nint main()\n{\n   std::ios_base::sync_with_stdio(false); cin.tie(NULL);\n   cin>>a;\n   z[0] = -1; //Not possible of zero length\n   z_function(a);\n   rep(i,0,a.length()) cout<<z[i]<<\" \";\n   return 0;\n}\n"
  },
  {
    "path": "String Manipulation/C:C++/tokens/token_break.cpp",
    "content": "// strings and c-strings\n#include <iostream>\n#include <cstring>\n#include <string>\n\nint main ()\n{\n  std::string str (\"        Please split this sentence into tokens    \");\n  char * cstr = new char [str.length()+1];\n  std::strcpy (cstr, str.c_str());\n\n  // cstr now contains a c-string copy of str\n\n  char * p = std::strtok (cstr,\" \");\n  std::cout<<p<<std::endl;\n  while (p!=0)\n  {\n    std::cout << p << '\\n';\n    p = std::strtok(NULL,\" \");\n  }\n\n  delete[] cstr;\n  return 0;\n}\n"
  },
  {
    "path": "String Manipulation/C:C++/tokens/word_break.cpp",
    "content": "#include <iostream>\nusing namespace std;\n \n/* A utility function to check whether a word\n  is present in dictionary or not.  An array of\n  strings is used for dictionary.*/\nint dictionaryContains(string &word)\n{\n    string dictionary[] = {\"mobile\",\"samsung\",\"nokia\",\"apple\",\"car\",\"book\",\"ball\",\"bat\",\"hello\",\"boy\",\"girl\",\n                            \"red\",\"good\",\"bad\",\"lovely\", \"nice\",\"and\",\"bad\",\"bad\",\"bad\",\"bad\",\"bad\",\"bad\",\"bad\",\"bad\",\"bad\",\n                            \"go\",\"are\",\"love\",\"ice\",\"cream\" \n                            };\n                            \n    int n = sizeof(dictionary)/sizeof(dictionary[0]);\n    for (int i = 0; i < n; i++)\n        if (dictionary[i].compare(word) == 0)\n            return true;\n    return false;\n}\n \nvoid wordBreakUtil(string str, int size, string result);\n \nvoid wordBreak(string str)\n{\n    // last argument is prefix\n    wordBreakUtil(str, str.size(), \"\");\n}\n \n// result store the current prefix with spaces between words\nvoid wordBreakUtil(string str, int n, string result)\n{\n    cout<<\"here\";\n    //Process all prefixes one by one\n    for (int i=1; i<=n; i++)\n    {\n        //extract substring from 0 to i in prefix\n        string prefix = str.substr(0, i);\n \n        // if dictionary conatins this prefix, then\n        // we check for remaining string. Otherwise\n        // we ignore this prefix (there is no else for\n        // this if) and try next\n        if (dictionaryContains(prefix))\n        {\n            // if no more elements are there, print it\n            if (i == n)\n            {\n                // add this element to previous prefix\n                result += prefix;\n                cout << result << endl; //print result\n                return;\n            }\n            wordBreakUtil(str.substr(i, n-i), n-i,result + prefix + \" \");\n        }\n    }//end for\n}//end function\n \nint main()\n{\n    cout << \"First Test:\\n\";\n    wordBreak(\"iloveicecreamandmango\");\n \n    cout << \"\\nSecond Test:\\n\";\n    wordBreak(\"ilovesamsungmobile\");\n    return 0;\n}\n"
  },
  {
    "path": "String Manipulation/Python/LCS.py",
    "content": "def lcs(a, b):\n    lengths = [[0 for j in range(len(b)+1)] for i in range(len(a)+1)]\n    \n    # row 0 and column 0 are initialized to 0 already\n    \n    for i, x in enumerate(a):\n        for j, y in enumerate(b):\n            if x == y:\n                lengths[i+1][j+1] = lengths[i][j] + 1\n            else:\n                lengths[i+1][j+1] = max(lengths[i+1][j], lengths[i][j+1])\n                \n    # read the substring out from the matrix\n    result = \"\"\n    x, y = len(a), len(b)\n    while x != 0 and y != 0:\n        if lengths[x][y] == lengths[x-1][y]:\n            x -= 1\n        elif lengths[x][y] == lengths[x][y-1]:\n            y -= 1\n        else:\n            assert a[x-1] == b[y-1]\n            result = a[x-1] + result\n            x -= 1\n            y -= 1\n    return result\n"
  },
  {
    "path": "backtrack/sudoku/code2.cpp",
    "content": "//http://www.spoj.com/problems/EASUDOKU/\n#include<bits/stdc++.h>\n\nusing namespace std;\n\ntypedef vector<vector<int> > matrix;\n\nbool check_possibility(matrix& vec,int num,int row,int col){\n    //check in row && col\n    for(int i=0;i<9;i++){\n        if(i!=col && vec[row][i]==num) return false;\n        if(i!=row && vec[i][col]==num) return false;\n    }\n\n    //check in 3*3 matrix\n    int row_ = row - row%3;\n    int col_ = col - col%3;\n    \n    for(int i=row_;i<row_+3;i++)\n        for(int j=col_;j<col_+3;j++)\n            if(i!=row && j!=col)\n                if(vec[i][j]==num) return false;\n\n    return true;\n}\n\nbool isGood(matrix& vec,int num,int row,int col){\n    int temp = vec[row][col];\n    if(temp){//fix\n        if(num==temp)//if num is same then check for its possibility\n            return check_possibility(vec,num,row,col); \n        else// no ther number can replace a fixed number\n            return false; \n    }\n    else \n        return check_possibility(vec,num,row,col); \n}\n\nbool back_track(matrix& vec,int row,int col){\n    vector<int> poss;\n    int temp = vec[row][col];\n\n    for(int i=1;i<=9;i++)//collect all possibilities\n        if(isGood(vec,i,row,col))\n            poss.push_back(i);\n    \n    if(row==9-1 && col==9-1 )//last elem\n        if(poss.size()==1){//last elem with single possibility\n            vec[row][col]=poss[0];return true;\n        }\n        else return false;\n     \n    for(int i : poss){\n            vec[row][col]=i;\n            if(col==9-1){//move to next row\n                if(back_track(vec,row+1,0))\n                    return true;\n            }\n            else{\n                if(back_track(vec,row,col+1))\n                    return true;\n            }\n    }\n    \n    //backtrack\n    vec[row][col]=temp;\n    \n    return false;\n}\n\n\nint main(){\n\tint t=1;\n    ios_base::sync_with_stdio(0);cin.tie(0);\n\tcin>>t;\n\twhile(t--){\n        matrix vec(9,vector<int>(9,0));             \n        for(int i=0;i<9;i++)\n            for(int j=0;j<9;j++){\n                cin>>vec[i][j];\n            }\n\n        if( back_track(vec,0,0) ){\n            for(int i=0;i<9;i++){\n                for(int j=0;j<9;j++){\n                    cout<<vec[i][j]<<\" \";\n                } \n                cout<<endl;\n            }\n        } else {\n            cout<<\"No solution\\n\";\n        }\n\t}\n}\n// a code by srbcheema1\n"
  },
  {
    "path": "backtrack/sudoku/sudoku.cpp",
    "content": "#include<bits/stdc++.h>\n\nusing namespace std;\n\ntypedef vector<vector<int> > matrix;\n\nbool check_possibility(matrix& vec,int num,int row,int col){\n    //check in row && col\n    for(int i=0;i<9;i++){\n        if(i!=col && vec[row][i]==num) return false;\n        if(i!=row && vec[i][col]==num) return false;\n    }\n\n    //check in 3*3 matrix\n    int row_ = row - row%3;\n    int col_ = col - col%3;\n    \n    for(int i=row_;i<row_+3;i++)\n        for(int j=col_;j<col_+3;j++)\n            if(i!=row && j!=col)\n                if(vec[i][j]==num) return false;\n\n    return true;\n}\n\nbool isGood(matrix& vec,int num,int row,int col){\n    int temp = vec[row][col];\n    if(temp){//fix\n        if(num==temp)//if num is same then check for its possibility\n            return check_possibility(vec,num,row,col); \n        else// no ther number can replace a fixed number\n            return false; \n    }\n    else \n        return check_possibility(vec,num,row,col); \n}\n\nbool back_track(matrix& vec,int row,int col){\n    vector<int> poss;\n    int temp = vec[row][col];\n\n    for(int i=1;i<=9;i++)//collect all possibilities\n        if(isGood(vec,i,row,col))\n            poss.push_back(i);\n    \n    if(row==9-1 && col==9-1 )//last elem\n        if(poss.size()==1){//last elem with single possibility\n            vec[row][col]=poss[0];return true;\n        }\n        else return false;\n     \n    for(int i : poss){\n            vec[row][col]=i;\n            if(col==9-1){//move to next row\n                if(back_track(vec,row+1,0))\n                    return true;\n            }\n            else{\n                if(back_track(vec,row,col+1))\n                    return true;\n            }\n    }\n    \n    //backtrack\n    vec[row][col]=temp;\n    \n    return false;\n}\n\n\nint main(){\n    matrix vec(9,vector<int>(9,0));             \n\n    for(int i=0;i<9;i++)\n        for(int j=0;j<9;j++){\n            cin>>vec[i][j];\n        }\n\n    if( back_track(vec,0,0) ){//soln exists\n        cout<<\"ans : \\n\";\n        for(int i=0;i<9;i++){\n            for(int j=0;j<9;j++){\n                cout<<vec[i][j]<<\" \";\n                if((j+1)%3==0)cout<<\" \";\n            } \n            if((i+1)%3==0)cout<<endl;\n            cout<<endl;\n        }\n    }\n    else {//no soln exist\n        cout<<\"wrong sudoku\\n\";\n    }\n}\n// a code by srbcheema1\n"
  },
  {
    "path": "binary_tree/binarytree.java",
    "content": "class Node{\n\tint data;\n\tNode left;\n\tNode right;\t\n\tpublic Node(int data){\n\t\tthis.data = data;\n\t\tleft = null;\n\t\tright = null;\n\t}\n}public class BinarySearchTree {\n\tpublic static  Node root;\n\tpublic BinarySearchTree(){\n\t\tthis.root = null;\n\t}\n\t\n\tpublic boolean find(int id){\n\t\tNode current = root;\n\t\twhile(current!=null){\n\t\t\tif(current.data==id){\n\t\t\t\treturn true;\n\t\t\t}else if(current.data>id){\n\t\t\t\tcurrent = current.left;\n\t\t\t}else{\n\t\t\t\tcurrent = current.right;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\tpublic boolean delete(int id){\n\t\tNode parent = root;\n\t\tNode current = root;\n\t\tboolean isLeftChild = false;\n\t\twhile(current.data!=id){\n\t\t\tparent = current;\n\t\t\tif(current.data>id){\n\t\t\t\tisLeftChild = true;\n\t\t\t\tcurrent = current.left;\n\t\t\t}else{\n\t\t\t\tisLeftChild = false;\n\t\t\t\tcurrent = current.right;\n\t\t\t}\n\t\t\tif(current ==null){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\t//if i am here that means we have found the node\n\t\t//Case 1: if node to be deleted has no children\n\t\tif(current.left==null && current.right==null){\n\t\t\tif(current==root){\n\t\t\t\troot = null;\n\t\t\t}\n\t\t\tif(isLeftChild ==true){\n\t\t\t\tparent.left = null;\n\t\t\t}else{\n\t\t\t\tparent.right = null;\n\t\t\t}\n\t\t}\n\t\t//Case 2 : if node to be deleted has only one child\n\t\telse if(current.right==null){\n\t\t\tif(current==root){\n\t\t\t\troot = current.left;\n\t\t\t}else if(isLeftChild){\n\t\t\t\tparent.left = current.left;\n\t\t\t}else{\n\t\t\t\tparent.right = current.left;\n\t\t\t}\n\t\t}\n\t\telse if(current.left==null){\n\t\t\tif(current==root){\n\t\t\t\troot = current.right;\n\t\t\t}else if(isLeftChild){\n\t\t\t\tparent.left = current.right;\n\t\t\t}else{\n\t\t\t\tparent.right = current.right;\n\t\t\t}\n\t\t}else if(current.left!=null && current.right!=null){\n\t\t\t\n\t\t\t//now we have found the minimum element in the right sub tree\n\t\t\tNode successor\t = getSuccessor(current);\n\t\t\tif(current==root){\n\t\t\t\troot = successor;\n\t\t\t}else if(isLeftChild){\n\t\t\t\tparent.left = successor;\n\t\t\t}else{\n\t\t\t\tparent.right = successor;\n\t\t\t}\t\t\t\n\t\t\tsuccessor.left = current.left;\n\t\t}\t\t\n\t\treturn true;\t\t\n\t}\n\t\n\tpublic Node getSuccessor(Node deleleNode){\n\t\tNode successsor =null;\n\t\tNode successsorParent =null;\n\t\tNode current = deleleNode.right;\n\t\twhile(current!=null){\n\t\t\tsuccesssorParent = successsor;\n\t\t\tsuccesssor = current;\n\t\t\tcurrent = current.left;\n\t\t}\n\t\t//check if successor has the right child, it cannot have left child for sure\n\t\t// if it does have the right child, add it to the left of successorParent.\n//\t\tsuccesssorParent\n\t\tif(successsor!=deleleNode.right){\n\t\t\tsuccesssorParent.left = successsor.right;\n\t\t\tsuccesssor.right = deleleNode.right;\n\t\t}\n\t\treturn successsor;\n\t}\n\tpublic void insert(int id){\n\t\tNode newNode = new Node(id);\n\t\tif(root==null){\n\t\t\troot = newNode;\n\t\t\treturn;\n\t\t}\n\t\tNode current = root;\n\t\tNode parent = null;\n\t\twhile(true){\n\t\t\tparent = current;\n\t\t\tif(id<current.data){\t\t\t\t\n\t\t\t\tcurrent = current.left;\n\t\t\t\tif(current==null){\n\t\t\t\t\tparent.left = newNode;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\tcurrent = current.right;\n\t\t\t\tif(current==null){\n\t\t\t\t\tparent.right = newNode;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tpublic void display(Node root){\n\t\tif(root!=null){\n\t\t\tdisplay(root.left);\n\t\t\tSystem.out.print(\" \" + root.data);\n\t\t\tdisplay(root.right);\n\t\t}\n\t}\n\tpublic static void main(String arg[]){\n\t\tBinarySearchTree b = new BinarySearchTree();\n\t\tb.insert(3);b.insert(8);\n\t\tb.insert(1);b.insert(4);b.insert(6);b.insert(2);b.insert(10);b.insert(9);\n\t\tb.insert(20);b.insert(25);b.insert(15);b.insert(16);\n\t\tSystem.out.println(\"Original Tree : \");\n\t\tb.display(b.root);\t\t\n\t\tSystem.out.println(\"\");\n\t\tSystem.out.println(\"Check whether Node with value 4 exists : \" + b.find(4));\n\t\tSystem.out.println(\"Delete Node with no children (2) : \" + b.delete(2));\t\t\n\t\tb.display(root);\n\t\tSystem.out.println(\"\\n Delete Node with one child (4) : \" + b.delete(4));\t\t\n\t\tb.display(root);\n\t\tSystem.out.println(\"\\n Delete Node with Two children (10) : \" + b.delete(10));\t\t\n\t\tb.display(root);\n\t}\n}\n\nclass Node{\n\tint data;\n\tNode left;\n\tNode right;\t\n\tpublic Node(int data){\n\t\tthis.data = data;\n\t\tleft = null;\n\t\tright = null;\n\t}\n}\n"
  },
  {
    "path": "btree.cpp",
    "content": "\n\n#ifndef ALGO_BTREE_H__\n#define ALGO_BTREE_H__\n\n#include <stdio.h>\n#include <assert.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <string.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <memory>\n\n#define BLOCKSIZE\t4096\n#define T \t\t\t255\n#define LEAF \t\t0x0001\n#define ONDISK\t\t0x0002\n#define MARKFREE\t0x0004\n\nnamespace alg {\n\tclass BTree {\n\t\tprivate:\n\t\t\t// 4K node, 4096 bytes to write\n\t\t\t// t = 255\n\t\t\tstruct node_t {\n\t\t\t\tuint16_t n;\t\t\t\t// num key\n\t\t\t\tuint16_t flag;\t\t\t// flags\n\t\t\t\tuint32_t offset;\t\t// lseek offset related to file beginning\n\t\t\t\tchar padding[12];\t\t// padding to 4096\n\t\t\t\tint32_t key[509];\t\t// key\n\t\t\t\tint32_t c[510];\t\t\t// childs pointers (represented as file offsets)\n\t\t\t} __attribute__ ((packed));\n\t\t\ttypedef struct node_t *node;\n\n\t\tpublic:\n\t\t\t// node and index\n\t\t\tstruct Res {\n\t\t\t\tuint32_t offset;\n\t\t\t\tint32_t idx;\n\t\t\t};\n\t\tprivate:\n\t\t\tint fd;\n\t\tprivate:\n\t\t\tBTree(const BTree &);\n\t\t\tBTree& operator=(const BTree&);\n\t\tpublic:\n\t\t\tBTree(const char * path) {\n\t\t\t\tfd = open(path, O_RDWR|O_CREAT, 0640);\n\t\t\t\tif (fd == -1)\n\t\t\t\t\treturn;\n\t\t\t\tnode x = (node)ALLOCBLK();\n\t\t\t\tint n = read(fd,x,BLOCKSIZE);\n\t\t\t\tif (n != BLOCKSIZE) {\t// init new btree\n\t\t\t\t\tx->flag |= LEAF;\n\t\t\t\t\tWRITE(x);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t~BTree() {\n\t\t\t\tclose(fd);\n\t\t\t}\n\n\t\t\tRes Search(int32_t x) {\n\t\t\t\tnode root = ROOT();\n\t\t\t\treturn search(root, x);\n\t\t\t}\n\n\t\t\tvoid Insert(int32_t k) {\n\t\t\t\tnode r = ROOT();\n\t\t\t\tif (r->n == 2*T - 1) {\n\t\t\t\t\t// place the old root node to the end of the file\n\t\t\t\t\tr->flag &= ~ONDISK;\n\t\t\t\t\tWRITE(r);\n\t\t\t\t\t// new root\n\t\t\t\t\tnode s = (node)ALLOCBLK();\n\t\t\t\t\ts->flag &= ~LEAF;\n\t\t\t\t\ts->flag |= ONDISK;\t// write to offset 0\n\t\t\t\t\ts->offset = 0;\n\t\t\t\t\ts->n = 0;\n\t\t\t\t\ts->c[0] = r->offset;\n\t\t\t\t\tsplit_child(s, 0);\t// split_child with write s\n\t\t\t\t\tinsert_nonfull(s, k);\n\t\t\t\t} else {\n\t\t\t\t\tinsert_nonfull(r, k);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvoid DeleteKey(int32_t k) {\n\t\t\t\tnode root = ROOT();\n\t\t\t\tdelete_op(root, k);\n\t\t\t}\n\n\t\tprivate:\n\t\t\t/**\n\t\t\t * search a key, returns node and index\n\t\t\t */\n\t\t\tRes search(node x, int32_t k) {\n\t\t\t\tint32_t i = 0;\n\t\t\t\tRes ret;\n\t\t\t\twhile (i<x->n && k > x->key[i]) i++;\n\n\t\t\t\tif (i<x->n && k == x->key[i]) {\t// search in [0,n-1]\n\t\t\t\t\tret.offset = x->offset;\n\t\t\t\t\tret.idx = i;\n\t\t\t\t\treturn ret;\n\t\t\t\t} else if (x->flag & LEAF) {\t// leaf, no more childs\n\t\t\t\t\tret.offset = 0;\n\t\t\t\t\tret.idx = -1;\n\t\t\t\t\treturn ret;\n\t\t\t\t} else {\n\t\t\t\t\tstd::auto_ptr<node_t> xi(READ(x, i));\t// search in a child\n\t\t\t\t\treturn search(xi.get(), k);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * insert into non-full node\n\t\t\t */\n\t\t\tvoid insert_nonfull(node x, int32_t k) {\n\t\t\t\tint32_t i = x->n-1;\n\t\t\t\tif (x->flag & LEAF) {\t// insert into this leaf\n\t\t\t\t\twhile (i>=0 && k < x->key[i]) {\t// right shift to\n\t\t\t\t\t\tx->key[i+1] = x->key[i];\t// make place for k\n\t\t\t\t\t\ti = i - 1;\n\t\t\t\t\t}\n\t\t\t\t\tx->key[i+1] = k;\n\t\t\t\t\tx->n = x->n + 1;\n\t\t\t\t\tWRITE(x);\n\t\t\t\t} else {\n\t\t\t\t\twhile(i>=0 && k < x->key[i]) {\n\t\t\t\t\t\ti = i-1;\n\t\t\t\t\t}\n\t\t\t\t\ti=i+1;\n\t\t\t\t\tnode xi = READ(x, i);\t\t// insert the key into one child.\n\t\t\t\t\tif (xi->n == 2*T-1) {\n\t\t\t\t\t\tsplit_child(x, i);\n\t\t\t\t\t\tif (k > x->key[i]) {\n\t\t\t\t\t\t\ti = i+1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// NOTICE!\n\t\t\t\t\t\t// reload x[i] after split_child.\n\t\t\t\t\t\txi = READ(x, i);\n\t\t\t\t\t}\n\t\t\t\t\tinsert_nonfull(xi, k);\n\t\t\t\t\tdelete xi;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * split a node into 2.\n\t\t\t */\n\t\t\tvoid split_child(node x, int32_t i) {\n\t\t\t\tstd::auto_ptr<node_t> z((node)ALLOCBLK());\n\t\t\t\tstd::auto_ptr<node_t> y(READ(x, i));\n\t\t\t\tz->flag &= ~LEAF;\n\t\t\t\tz->flag |= (y->flag & LEAF);\n\t\t\t\tz->n = T - 1;\n\n\t\t\t\tint32_t j;\n\t\t\t\tfor (j=0;j<T-1;j++) {\t// init z, t-1 keys\n\t\t\t\t\tz->key[j] = y->key[j+T];\n\t\t\t\t}\n\n\t\t\t\tif (!(y->flag & LEAF)) {\t// if not leaf, copy childs too.\n\t\t\t\t\tfor (j=0;j<T;j++) {\n\t\t\t\t\t\tz->c[j] = y->c[j+T];\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\ty->n = T-1;\t// shrink y to t-1 elements\n\t\t\t\tWRITE(y.get());\n\t\t\t\tWRITE(z.get());\n\n\t\t\t\tfor (j=x->n;j>=i+1;j--) { // make place for the new child in x\n\t\t\t\t\tx->c[j+1] = x->c[j];\n\t\t\t\t}\n\n\t\t\t\tx->c[i+1] = z->offset; // make z the child of x\n\t\t\t\tfor (j=x->n-1;j>=i;j--) { // move keys in x\n\t\t\t\t\tx->key[j+1] = x->key[j];\n\t\t\t\t}\n\t\t\t\tx->key[i] = y->key[T-1];\t// copy the middle element of y into x\n\t\t\t\tx->n = x->n+1;\n\t\t\t\tWRITE(x);\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * recursive deletion.\n\t\t\t */\n\t\t\tvoid delete_op(node x, int32_t k) {\n\t\t\t\tint32_t i;\n\t\t\t\t/*\n\t\t\t\t   int t;\n\t\t\t\t   printf(\"key:%d n:%d\\n\",k, x->n);\n\t\t\t\t   for (t=0;t<x->n;t++) {\n\t\t\t\t   printf(\"=%d=\", x->key[t]);\n\t\t\t\t   }\n\t\t\t\t   printf(\"\\n\");\n\t\t\t\t */\n\n\t\t\t\tif (x->n == 0) {\t// emtpy node\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\ti = x->n - 1;\n\t\t\t\twhile (i>=0 && k < x->key[i]) { // search the key.\n\t\t\t\t\ti = i - 1;\n\t\t\t\t}\n\n\t\t\t\tif (i >= 0 && x->key[i] == k) {\t// key exists in this node.\n\t\t\t\t\tif (x->flag & LEAF) {\n\t\t\t\t\t\t//printf(\"in case 1 [%d] [%d]\\n\", i,x->n);\n\t\t\t\t\t\tcase1(x, i, k);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t//printf(\"in case 2 [%d] [%d]\\n\", i,x->n);\n\t\t\t\t\t\tcase2(x, i, k);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// case 3. on x.c[i+1]\n\t\t\t\t\tcase3(x, i+1, k);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * case 1.\n\t\t\t * If the key k is in node x and x is a leaf, delete the key k from x.\n\t\t\t */\n\t\t\tvoid case1(node x, int32_t i, int32_t k) {\n\t\t\t\tint j;\n\t\t\t\tfor (j = i;j<x->n-1;j++) {\t// shifting the keys only, no childs available.\n\t\t\t\t\tx->key[j] = x->key[j+1];\n\t\t\t\t}\n\t\t\t\tx->n = x->n - 1;\n\t\t\t\tWRITE(x);\n\t\t\t}\n\n\t\t\tvoid case2(node x, int32_t i, int32_t k) {\n\t\t\t\t// case 2a:\n\t\t\t\t// If the child y that precedes k in node x has at least t\n\t\t\t\t// keys, then find the predecessor k0 of k in the subtree\n\t\t\t\t// rooted at y. Recursively delete k0, and replace k by k0 in x.\n\t\t\t\t// (We can find k0 and delete it in a single downward pass.)\n\t\t\t\tstd::auto_ptr<node_t> y(READ(x, i));\n\t\t\t\tif (y->n >= T) {\n\t\t\t\t\tint32_t k0 = y->key[y->n-1];\n\t\t\t\t\t//printf(\"case2a %d %d\\n\", k0, x->key[i]);\n\t\t\t\t\tx->key[i] = k0;\n\t\t\t\t\tWRITE(x);\n\t\t\t\t\tdelete_op(y.get(), k0);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// case 2b.\n\t\t\t\t// If y has fewer than t keys, then, symmetrically, examine\n\t\t\t\t// the child z that follows k in node x. If z has at least t keys,\n\t\t\t\t// then find the successor k0 of k in the subtree rooted at z.\n\t\t\t\t// Recursively delete k0, and replace k by k0 in x. (We can find k0\n\t\t\t\t// and delete it in a single downward pass.)\n\t\t\t\tstd::auto_ptr<node_t> z(READ(x, i+1));\n\t\t\t\tif (z->n >= T) {\n\t\t\t\t\tint32_t k0 = z->key[0];\n\t\t\t\t\t//printf(\"case2b %d %d\\n\", k0, x->key[i]);\n\t\t\t\t\tx->key[i] = k0;\n\t\t\t\t\tWRITE(x);\n\t\t\t\t\tdelete_op(z.get(), k0);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// case 2c:\n\t\t\t\t// Otherwise, if both y and z have only t-1 keys,\n\t\t\t\t// merge k and all of z into y,  so that x loses both k and the\n\t\t\t\t// pointer to z, and y now contains 2t - 1 keys.\n\t\t\t\t// Then free z and recursively delete k from y.\n\t\t\t\tif (y->n == T-1 && z->n == T-1) {\n\t\t\t\t\t//printf(\"case2c\");\n\t\t\t\t\t// merge k & z into y\n\t\t\t\t\ty->key[y->n] = k;\n\n\t\t\t\t\tint j;\n\t\t\t\t\tfor (j=0;j<z->n;j++) {\t\t// merge keys of z\n\t\t\t\t\t\ty->key[y->n+1+j] = z->key[j];\n\t\t\t\t\t}\n\t\t\t\t\tfor (j=0;j<z->n+1;j++) {\t// merge childs of z\n\t\t\t\t\t\ty->c[y->n+1+j] = z->c[j];\n\t\t\t\t\t}\n\n\t\t\t\t\t// mark free z\n\t\t\t\t\tz->flag |= MARKFREE;\n\t\t\t\t\ty->n = y->n + z->n + 1; // size after merge\n\t\t\t\t\tWRITE(z.get());\n\t\t\t\t\tWRITE(y.get());\n\n\t\t\t\t\tfor (j=i;j<x->n-1;j++) { // delete k from node x\n\t\t\t\t\t\tx->key[j] = x->key[j+1];\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (j=i+1;j<x->n;j++){\t// delete pointer to z --> (i+1)th\n\t\t\t\t\t\tx->c[j] = x->c[j+1];\n\t\t\t\t\t}\n\t\t\t\t\tx->n = x->n - 1;\n\t\t\t\t\tWRITE(x);\n\n\t\t\t\t\t// recursive delete k\n\t\t\t\t\tdelete_op(y.get(), k);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// cannot reach here\n\t\t\t\tassert(false);\n\t\t\t}\n\n\t\t\tvoid case3(node x, int32_t i, int32_t k) {\n\t\t\t\tstd::auto_ptr<node_t> ci(READ(x, i));\n\t\t\t\tif (ci->n > T-1) {\t// ready to delete in child.\n\t\t\t\t\tdelete_op(ci.get(), k);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// case 3a.\n\t\t\t\t// If x.c[i] has only t - 1 keys but has an immediate sibling with at least t keys,\n\t\t\t\t// give x.c[i] an extra key by moving a key from x down into x.c[i], moving a\n\t\t\t\t// key from x.c[i]’s immediate left or right sibling up into x, and moving the\n\t\t\t\t// appropriate child pointer from the sibling into x.c[i].\n\t\t\t\tstd::auto_ptr<node_t> left(READ(x, i-1));\n\t\t\t\tif (i-1>=0 && left->n >= T) {\n\t\t\t\t\t// printf(\"case3a, left\");\n\t\t\t\t\t// right shift keys and childs of x.c[i] to make place for a key\n\t\t\t\t\t// right shift ci childs\n\t\t\t\t\tint j;\n\t\t\t\t\tfor (j=ci->n-1;j>0;j--) {\n\t\t\t\t\t\tci->key[j] = ci->key[j-1];\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (j=ci->n;j>0;j--) {\n\t\t\t\t\t\tci->c[j] = ci->c[j-1];\n\t\t\t\t\t}\n\t\t\t\t\tci->n = ci->n+1;\n\t\t\t\t\tci->key[0] = x->key[i-1];\t\t\t// copy key from x[i-1] to ci[0]\n\t\t\t\t\tci->c[0] = left->c[left->n];\t\t// copy child from left last child.\n\t\t\t\t\tx->key[i] = left->key[left->n-1];\t// copy left last key into x[i]\n\t\t\t\t\tleft->n = left->n-1;\t\t\t\t// decrease left size\n\n\t\t\t\t\tWRITE(ci.get());\n\t\t\t\t\tWRITE(x);\n\t\t\t\t\tWRITE(left.get());\n\t\t\t\t\tdelete_op(ci.get(), k);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// case 3a. right sibling\n\t\t\t\tstd::auto_ptr<node_t> right(READ(x, i+1));\n\t\t\t\tif (i+1<=x->n && right->n >= T) {\n\t\t\t\t\t// printf(\"case3a, right\");\n\t\t\t\t\tci->key[ci->n] = x->key[i];\t\t// append key from x\n\t\t\t\t\tci->c[ci->n+1] = right->c[0];\t// append child from right\n\t\t\t\t\tci->n = ci->n+1;\n\t\t\t\t\tx->key[i] = right->key[0];\t\t// subsitute key in x\n\n\t\t\t\t\tint j;\n\t\t\t\t\tfor (j=0;j<right->n-1;j++) { // remove key[0] from right sibling\n\t\t\t\t\t\tright->key[j] = right->key[j+1];\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (j=0;j<right->n;j++) { // and also the child c[0] of the right sibling.\n\t\t\t\t\t\tright->c[j] = right->c[j+1];\n\t\t\t\t\t}\n\t\t\t\t\tright->n = right->n - 1;\t// reduce the size of the right sibling.\n\n\t\t\t\t\tWRITE(ci.get());\n\t\t\t\t\tWRITE(x);\n\t\t\t\t\tWRITE(right.get());\n\t\t\t\t\tdelete_op(ci.get(), k); \t// recursive delete key in x.c[i]\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// case 3b.\n\t\t\t\t// If x.c[i] and both of x.c[i]’s immediate siblings have t-1 keys, merge x.c[i]\n\t\t\t\t// with one sibling, which involves moving a key from x down into the new\n\t\t\t\t// merged node to become the median key for that node.\n\t\t\t\tif ((i-1<0 ||left->n == T-1) && (i+1 <=x->n || right->n == T-1)) {\n\t\t\t\t\tif (left->n == T-1) {\n\t\t\t\t\t\t// copy x[i] to left\n\t\t\t\t\t\tleft->key[left->n] = x->key[i];\n\t\t\t\t\t\tleft->n = left->n + 1;\n\n\t\t\t\t\t\t// remove key[i] from x and also the child\n\t\t\t\t\t\t// shrink the size & set the child-0 to left\n\t\t\t\t\t\tdelete_i(x, i);\n\n\t\t\t\t\t\tint j;\n\t\t\t\t\t\t// append x.c[i] into left sibling\n\t\t\t\t\t\tfor (j=0;j<ci->n;j++) {\n\t\t\t\t\t\t\tleft->key[left->n + j] = ci->key[j];\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor (j=0;j<ci->n+1;j++) {\n\t\t\t\t\t\t\tleft->c[left->n + j] = ci->c[j];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tleft->n += ci->n;\t// left became 2T-1\n\t\t\t\t\t\tci->flag |= MARKFREE;\t// free ci\n\t\t\t\t\t\tci->n = 0;\n\t\t\t\t\t\tWRITE(ci.get());\n\t\t\t\t\t\tWRITE(x);\n\t\t\t\t\t\t// root check\n\t\t\t\t\t\tif (x->n == 0 && x->offset ==0) {\n\t\t\t\t\t\t\tleft->flag |= MARKFREE;\n\t\t\t\t\t\t\tWRITE(left.get());\n\t\t\t\t\t\t\tleft->flag &= ~MARKFREE;\n\t\t\t\t\t\t\tleft->offset = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tWRITE(left.get());\n\t\t\t\t\t\tdelete_op(left.get(), k);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t} else if (right->n == T-1) {\n\t\t\t\t\t\t// copy x[i] to x.c[i]\n\t\t\t\t\t\tci->key[ci->n] = x->key[i];\n\t\t\t\t\t\tci->n = ci->n + 1;\n\t\t\t\t\t\t// remove key[i] from x and also the child\n\t\t\t\t\t\t// shrink the size & set the child-0 to ci\n\t\t\t\t\t\tdelete_i(x, i);\n\n\t\t\t\t\t\tint j;\n\t\t\t\t\t\t// append right sibling into x.c[i]\n\t\t\t\t\t\tfor (j=0;j<right->n;j++) {\n\t\t\t\t\t\t\tci->key[ci->n + j] = right->key[j];\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor (j=0;j<right->n+1;j++) {\n\t\t\t\t\t\t\tci->c[ci->n + j] = right->c[j];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tci->n += right->n;\t\t\t// ci became 2T-1\n\t\t\t\t\t\tright->flag |= MARKFREE;\t// free right\n\t\t\t\t\t\tright->n = 0;\n\t\t\t\t\t\tWRITE(right.get());\n\t\t\t\t\t\tWRITE(x);\n\t\t\t\t\t\t// root check\n\t\t\t\t\t\tif (x->n == 0 && x->offset ==0) {\n\t\t\t\t\t\t\tci->flag |= MARKFREE;\n\t\t\t\t\t\t\tWRITE(ci.get());\n\t\t\t\t\t\t\tci->flag &= ~MARKFREE;\n\t\t\t\t\t\t\tci->offset = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tWRITE(ci.get());\n\t\t\t\t\t\tdelete_op(ci.get(), k);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * delete ith key & child.\n\t\t\t */\n\t\t\tvoid delete_i(node x, int32_t i)  {\n\t\t\t\tint j;\n\t\t\t\tfor (j=i;j<x->n-1;j++) {\n\t\t\t\t\tx->key[j] = x->key[j+1];\n\t\t\t\t}\n\n\t\t\t\tfor (j=i+1;j<x->n;j++) {\n\t\t\t\t\tx->c[j] = x->c[j+1];\n\t\t\t\t}\n\t\t\t\tx->n = x->n - 1;\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * Allocate empty node struct.\n\t\t\t * A better allocator should be consider in practice, such as\n\t\t\t * re-cycling the freed up blocks on disk, so used blocks\n\t\t\t * should be traced in some data strucuture, file header maybe.\n\t\t\t */\n\t\t\tvoid * ALLOCBLK() {\n\t\t\t\tnode x = new node_t;\n\t\t\t\tx->n = 0;\n\t\t\t\tx->offset = 0;\n\t\t\t\tx->flag = 0;\n\t\t\t\tmemset(x->key, 0, sizeof(x->key));\n\t\t\t\tmemset(x->c, 0, sizeof(x->c));\n\t\t\t\tmemset(x->padding, 0xcc, sizeof(x->padding));\n\t\t\t\treturn x;\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * Load the root block\n\t\t\t */\n\t\t\tnode ROOT() {\n\t\t\t\tvoid *root = ALLOCBLK();\n\t\t\t\tlseek(fd, 0, SEEK_SET);\n\t\t\t\tread(fd, root, BLOCKSIZE);\n\t\t\t\treturn (node)root;\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * Read a 4K-block from disk, and returns the node struct.\n\t\t\t */\n\t\t\tnode READ(node x, int32_t i) {\n\t\t\t\tvoid *xi = ALLOCBLK();\n\t\t\t\tif (i >=0 && i <= x->n) {\n\t\t\t\t\tlseek(fd, x->c[i], SEEK_SET);\n\t\t\t\t\tread(fd, xi, BLOCKSIZE);\n\t\t\t\t}\n\t\t\t\treturn (node)xi;\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * \tupdate a node struct to file, create if offset is -1.\n\t\t\t */\n\t\t\tvoid WRITE(node x) {\n\t\t\t\tif (x->flag & ONDISK) {\n\t\t\t\t\tlseek(fd, x->offset, SEEK_SET);\n\t\t\t\t} else {\n\t\t\t\t\tx->offset = lseek(fd,0, SEEK_END);\n\t\t\t\t}\n\t\t\t\tx->flag |= ONDISK;\n\t\t\t\twrite(fd, x, BLOCKSIZE);\n\t\t\t}\n\t};\n}\n"
  },
  {
    "path": "cryptography/Python/porta.py",
    "content": "from pycipher.base import Cipher\n\n####################################################################################\nclass Porta(Cipher):\n    \"\"\"The Porta Cipher is a polyalphabetic substitution cipher, and has a key consisting of a word e.g. 'FORTIFICATION'.\n    \n    :param key: The keyword, any word or phrase will do. Must consist of alphabetical characters only, no punctuation of numbers.          \n    \"\"\"\n    def __init__(self,key='FORTIFICATION'):\n        self.key = [k.upper() for k in key]\n        \n    def encipher(self,string):\n        \"\"\"Encipher string using Porta cipher according to initialised key. Punctuation and whitespace\n        are removed from the input.       \n        Example::\n            ciphertext = Porta('HELLO').encipher(plaintext)     \n        :param string: The string to encipher.\n        :returns: The enciphered string.\n        \"\"\"            \n        string = self.remove_punctuation(string)\n        ret = ''\n        for (i,c) in enumerate(string):\n            i = i%len(self.key)\n            if   self.key[i] in 'AB': ret += 'NOPQRSTUVWXYZABCDEFGHIJKLM'[self.a2i(c)]\n            elif self.key[i] in 'YZ': ret += 'ZNOPQRSTUVWXYBCDEFGHIJKLMA'[self.a2i(c)]\n            elif self.key[i] in 'WX': ret += 'YZNOPQRSTUVWXCDEFGHIJKLMAB'[self.a2i(c)]\n            elif self.key[i] in 'UV': ret += 'XYZNOPQRSTUVWDEFGHIJKLMABC'[self.a2i(c)]\n            elif self.key[i] in 'ST': ret += 'WXYZNOPQRSTUVEFGHIJKLMABCD'[self.a2i(c)]\n            elif self.key[i] in 'QR': ret += 'VWXYZNOPQRSTUFGHIJKLMABCDE'[self.a2i(c)]\n            elif self.key[i] in 'OP': ret += 'UVWXYZNOPQRSTGHIJKLMABCDEF'[self.a2i(c)]\n            elif self.key[i] in 'MN': ret += 'TUVWXYZNOPQRSHIJKLMABCDEFG'[self.a2i(c)]\n            elif self.key[i] in 'KL': ret += 'STUVWXYZNOPQRIJKLMABCDEFGH'[self.a2i(c)]\n            elif self.key[i] in 'IJ': ret += 'RSTUVWXYZNOPQJKLMABCDEFGHI'[self.a2i(c)]\n            elif self.key[i] in 'GH': ret += 'QRSTUVWXYZNOPKLMABCDEFGHIJ'[self.a2i(c)]\n            elif self.key[i] in 'EF': ret += 'PQRSTUVWXYZNOLMABCDEFGHIJK'[self.a2i(c)]\n            elif self.key[i] in 'CD': ret += 'OPQRSTUVWXYZNMABCDEFGHIJKL'[self.a2i(c)]\n        return ret    \n\n    def decipher(self,string):\n        \"\"\"Decipher string using Porta cipher according to initialised key. Punctuation and whitespace\n        are removed from the input. For the Porta cipher, enciphering and deciphering are the same operation.\n        Example::\n            plaintext = Porta('HELLO').decipher(ciphertext)     \n        :param string: The string to decipher.\n        :returns: The deciphered string.\n        \"\"\"   \n        return self.encipher(string)    \n\nif __name__ == '__main__': \n    print('use \"import pycipher\" to access functions')\n"
  },
  {
    "path": "cryptography/des/java/Converter.java",
    "content": "/**\n * Convert to binary code russian letters.\n */\n\npackage cryptography.des.java;\n\nimport java.io.UnsupportedEncodingException;\n\npublic class Converter {\n\n    public static String convertToBinaryCode(String text) {\n        StringBuilder binaryCode = new StringBuilder();\n\n        for (int i = 0; i < text.length(); i++) {\n            byte[] bytes = getBytes(text.substring(i, i+ 1));\n            int[] m = new int[bytes.length];\n\n            for (int j = 0; j < bytes.length; j++) {\n                m[j] = bytes[j];\n            }\n\n            for (int k = 0; k < m.length; k++) {\n                StringBuilder str = new StringBuilder(Integer.toBinaryString(m[k]));\n\n                for (int n = str.length(); n < 32; n++) {\n                    str.insert(0, \"0\");\n                }\n\n                binaryCode.append(str.toString().substring(24));\n            }\n        }\n\n        return binaryCode.toString();\n    }\n\n    private static byte[] getBytes (String text) {\n        try {\n            return text.getBytes(\"Cp1251\");\n        } catch (UnsupportedEncodingException e) {\n            e.printStackTrace();\n        }\n\n        return null;\n    }\n\n}\n"
  },
  {
    "path": "cryptography/des/java/DES.java",
    "content": "package cryptography.des.java;\n\npublic class DES {\n\n\tprivate String key;\n\n\tprivate String message;\n\n\tprivate String[] keys = new String[17];\n\n\tpublic String getKey() {\n\t\treturn key;\n\t}\n\n\tpublic void setKey(String key) {\n\t\tthis.key = Converter.convertToBinaryCode(key);\n\t}\n\n\tpublic String getMessage() {\n\t\treturn message;\n\t}\n\n\tpublic void setMessage(String message) {\n\t\tthis.message = Converter.convertToBinaryCode(message);\n\t}\n\n\tpublic String encrypt() {\n\t\tString messageAfterPermutation = messagePermutation(message);\n\n\t\tString[] L = new String[17];\n\t\tString[] R = new String[17];\n\t\tString[] Rtemp = new String[17];\n\n\t\tL[0] = messageAfterPermutation.substring(0, 32);\n\t\tR[0] = messageAfterPermutation.substring(32);\n\n\t\tString[] B = new String[9];\n\n\t\tgenerateKeys(key);\n\n\t\tfor (int i = 1; i <= 16; i++) {\n\t\t\tL[i] = R[i-1];\n\t\t\tString Er = E(R[i-1]);\n\n\t\t\tRtemp[i] = xor(Er, keys[i]);\n\t\t\tB[1] = Rtemp[i].substring(0, 6);\n\t\t\tB[2] = Rtemp[i].substring(6, 12);\n\t\t\tB[3] = Rtemp[i].substring(12, 18);\n\t\t\tB[4] = Rtemp[i].substring(18, 24);\n\t\t\tB[5] = Rtemp[i].substring(24, 30);\n\t\t\tB[6] = Rtemp[i].substring(30, 36);\n\t\t\tB[7] = Rtemp[i].substring(36, 42);\n\t\t\tB[8] = Rtemp[i].substring(42);\n\n\t\t\tString[] C = new String[9];\n\n\t\t\tfor (int j = 1; j < 9; j++) {\n\t\t\t\tC[j] = sBox(j, B[j]);\n\n\t\t\t\tif (C[j].length() == 3) {\n\t\t\t\t\tC[j] = \"0\" + C[j];\n\t\t\t\t} else if (C[j].length() == 2) {\n\t\t\t\t\tC[j] = \"00\" + C[j];\n\t\t\t\t} else if (C[j].length() == 1) {\n\t\t\t\t\tC[j] = \"000\" + C[j];\n\t\t\t\t} else if (C[j].length() == 0) {\n\t\t\t\t\tC[j] = \"0000\" + C[j];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tString cFinal = \"\";\n\t\t\tfor (int j = 1; j < C.length; j++) {\n\t\t\t\tcFinal += C[j];\n\t\t\t}\n\n\t\t\tcFinal = cPermute(cFinal);\n\n\t\t\tR[i] = xor(L[i-1], cFinal);\n\t\t}\n\n\t\treturn lastInverse(R[16]+L[16]);\n\t}\n\n\tprivate String messagePermutation(String input) {\n\t\tint[] positionTable = { 58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4,\n\t\t\t\t\t\t\t\t62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8,\n\t\t\t\t\t\t\t\t57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3,\n\t\t\t\t\t\t\t\t61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7 };\n\n\t\tStringBuilder newMessage = new StringBuilder();\n\n\t\tfor (int position : positionTable) {\n\t\t\tnewMessage.append(input.substring(position - 1, position));\n\t\t}\n\n\t\treturn newMessage.toString();\n\t}\n\n\tprivate void generateKeys(String key) {\n\t\tkey = beginKeyPermutation(key);\n\n\t\tString c = key.substring(0, 28);\n\t\tString d = key.substring(28, key.length());\n\n\t\tfor (int i = 1; i < 17; i++) {\n\t\t\tc = leftShiftBits(c, i);\n\t\t\td = leftShiftBits(d, i);\n\t\t\tkeys[i] = finishKeyPermutation(c + d);\n\t\t}\n\t}\n\n\tprivate String beginKeyPermutation(String input) {\n\t\tint[] positionTable = { 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18,\n\t\t\t\t\t\t\t\t10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36,\n\t\t\t\t\t\t\t\t63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22,\n\t\t\t\t\t\t\t\t14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4 };\n\n\t\tStringBuilder newKey = new StringBuilder();\n\n\t\tfor (int position : positionTable) {\n\t\t\tnewKey.append(input.substring(position - 1, position));\n\t\t}\n\n\t\treturn newKey.toString();\n\t}\n\n\tprivate String leftShiftBits(String input, int step) {\n\t\tint[] shift = { 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 };\n\t\tString shifted = input;\n\n\t\tfor (int j = 0; j < shift[step - 1]; j++) {\n\t\t\tshifted = shifted.substring(1, shifted.length()) + shifted.substring(0, 1);\n\t\t}\n\n\t\treturn shifted;\n\t}\n\n\tprivate String finishKeyPermutation(String input) {\n\t\tint[] positionTable = { 14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4,\n\t\t\t\t\t\t\t\t26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40,\n\t\t\t\t\t\t\t\t51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32 };\n\n\t\tStringBuilder newKey = new StringBuilder();\n\n\t\tfor (int position : positionTable) {\n\t\t\tnewKey.append(input.substring(position - 1, position));\n\t\t}\n\t\treturn newKey.toString();\n\t}\n\n\tprivate String E(String input) {\n\t\tint[] positionTable = { 32, 1, 2, 3, 4, 5,\n\t\t\t\t\t\t\t\t4, 5, 6, 7, 8, 9,\n\t\t\t\t\t\t\t\t8, 9, 10, 11, 12, 13,\n\t\t\t\t\t\t\t\t12, 13, 14, 15, 16, 17,\n\t\t\t\t\t\t\t\t16, 17, 18, 19, 20, 21,\n\t\t\t\t\t\t\t\t20, 21, 22, 23, 24, 25,\n\t\t\t\t\t\t\t\t24, 25, 26, 27, 28, 29,\n\t\t\t\t\t\t\t\t28, 29, 30, 31, 32, 1 };\n\n\t\tStringBuilder newR = new StringBuilder();\n\n\t\tfor (int position : positionTable) {\n\t\t\tnewR.append(input.substring(position - 1, position));\n\t\t}\n\n\t\treturn newR.toString();\n\t}\n\n\tprivate static String xor(String x1, String x2) {\n\t\tStringBuilder out = new StringBuilder();\n\t\tint len;\n\t\tint start;\n\n\t\tif (x1.length() < x2.length()) {\n\t\t\tlen = x1.length();\n\t\t\tstart = x2.length() - x1.length();\n\t\t\tout.append(x2.substring(0, start));\n\t\t\tx2 = x2.substring(start);\n\t\t} else {\n\t\t\tlen = x2.length();\n\t\t\tstart = x1.length() - x2.length();\n\t\t\tout.append(x1.substring(0, start));\n\t\t\tx1 = x1.substring(start);\n\t\t}\n\n\t\tfor (int i = 0; i < len; i++) {\n\t\t\tString s1 = x1.substring(i, i + 1);\n\t\t\tString s2 =x2.substring(i, i + 1);\n\t\t\tout.append(Integer.parseInt(x1.substring(i, i + 1)) ^ Integer.parseInt(x2.substring(i, i + 1)));\n\t\t}\n\n\t\treturn out.toString();\n\t}\n\n\tprivate String sBox(int boxNumber, String b) {\n\t\tint[] sbox1 = { 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7,\n\t\t\t\t\t\t0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8,\n\t\t\t\t\t\t4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0,\n\t\t\t\t\t\t15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13 };\n\n\t\tint[] sBox2 = { 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10,\n\t\t\t\t\t\t3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5,\n\t\t\t\t\t\t0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15,\n\t\t\t\t\t\t13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9 };\n\n\t\tint[] sBox3 = { 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8,\n\t\t\t\t\t\t13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1,\n\t\t\t\t\t\t13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7,\n\t\t\t\t\t\t1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12 };\n\n\t\tint[] sBox4 = { 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15,\n\t\t\t\t\t\t13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9,\n\t\t\t\t\t\t10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4,\n\t\t\t\t\t\t3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14 };\n\n\t\tint[] sBox5 = { 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9,\n\t\t\t\t\t\t14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6,\n\t\t\t\t\t\t4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14,\n\t\t\t\t\t\t11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3 };\n\n\t\tint[] sBox6 = { 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11,\n\t\t\t\t\t\t10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8,\n\t\t\t\t\t\t9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6,\n\t\t\t\t\t\t4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13 };\n\n\t\tint[] sBox7 = { 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1,\n\t\t\t\t\t\t13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6,\n\t\t\t\t\t\t1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2,\n\t\t\t\t\t\t6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12 };\n\n\t\tint[] sBox8 = { 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7,\n\t\t\t\t\t\t1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2,\n\t\t\t\t\t\t7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8,\n\t\t\t\t\t\t2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11 };\n\n\t\tString temp = b.substring(0, 1) + b.substring(5);\n\t\tint row = Integer.parseInt(temp,2);\n\t\tint col = Integer.parseInt(b.substring(1, 5), 2);\n\n\t\trow = row * 16;\n\n\t\tswitch (boxNumber) {\n\t\t\tcase 1:\n\t\t\t\treturn Integer.toBinaryString(sbox1[(row + col)]);\n\t\t\tcase 2:\n\t\t\t\treturn Integer.toBinaryString(sBox2[(row + col)]);\n\t\t\tcase 3:\n\t\t\t\treturn Integer.toBinaryString(sBox3[(row + col)]);\n\t\t\tcase 4:\n\t\t\t\treturn Integer.toBinaryString(sBox4[(row + col)]);\n\t\t\tcase 5:\n\t\t\t\treturn Integer.toBinaryString(sBox5[(row + col)]);\n\t\t\tcase 6:\n\t\t\t\treturn Integer.toBinaryString(sBox6[(row + col)]);\n\t\t\tcase 7:\n\t\t\t\treturn Integer.toBinaryString(sBox7[(row + col)]);\n\t\t\tcase 8:\n\t\t\t\treturn Integer.toBinaryString(sBox8[(row + col)]);\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tprivate String cPermute(String input) {\n\t\tint[] positionTable = { 16, 7, 20, 21, 29, 12, 28, 17,\n\t\t\t\t\t1, 15, 23, 26, 5, 18, 31, 10,\n\t\t\t\t\t2, 8, 24, 14, 32, 27, 3, 9,\n\t\t\t\t\t19, 13, 30, 6, 22, 11, 4, 25 };\n\n\t\tStringBuilder newC = new StringBuilder();\n\n\t\tfor (int position : positionTable) {\n\t\t\tnewC.append(input.substring(position - 1, position));\n\t\t}\n\n\t\treturn newC.toString();\n\t}\n\n\tprivate String lastInverse(String input) {\n\t\tint[] positionTable = { 40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31,\n\t\t\t\t\t\t\t\t38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29,\n\t\t\t\t\t\t\t\t36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27,\n\t\t\t\t\t\t\t\t34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25 };\n\n\t\tStringBuilder inverse = new StringBuilder();\n\n\t\tfor (int position : positionTable) {\n\t\t\tinverse.append(input.substring(position - 1, position));\n\t\t}\n\n\t\treturn inverse.toString();\n\t}\n\n}\n"
  },
  {
    "path": "cryptography/des/java/IO.java",
    "content": "package cryptography.des.java;\n\nimport java.io.*;\n\npublic class IO {\n\n    private final String INPUT_FILE_PATH;\n\n    private final String OUTPUT_FILE_PATH;\n\n    public IO(String inputFilePath, String outputFilePath) {\n        this.INPUT_FILE_PATH = inputFilePath;\n        this.OUTPUT_FILE_PATH = outputFilePath;\n    }\n\n    public String readMessageFromFile() {\n        try (BufferedReader reader = new BufferedReader(new FileReader(INPUT_FILE_PATH))) {\n            return reader.readLine();\n        } catch (IOException e) {\n            e.printStackTrace();\n        }\n\n        return null;\n    }\n\n    public String readKeyFromFile() {\n        try (BufferedReader reader = new BufferedReader(new FileReader(INPUT_FILE_PATH))) {\n            reader.readLine();\n            return reader.readLine();\n        } catch (IOException e) {\n            e.printStackTrace();\n        }\n\n        return null;\n    }\n\n    public void writeStringInFile(String text) {\n        try (BufferedWriter writer = new BufferedWriter(new FileWriter(OUTPUT_FILE_PATH))) {\n            writer.write(text);\n            writer.flush();\n        } catch (IOException e) {\n            e.printStackTrace();\n        }\n    }\n\n}\n"
  },
  {
    "path": "cryptography/des/java/Main.java",
    "content": "/**\n * In input file write message and password on new line.\n */\n\npackage cryptography.des.java;\n\npublic class Main {\n\n    public static void main(String[] args) {\n        IO IO = new IO(\"input.txt\", \"output.txt\");\n        String message = IO.readMessageFromFile();\n        String key = IO.readKeyFromFile();\n\n        DES DES = new DES();\n        DES.setMessage(message);\n        DES.setKey(key);\n\n        String cypherText = DES.encrypt();\n\n        IO.writeStringInFile(cypherText);\n    }\n\n}\n"
  },
  {
    "path": "dfs.cpp",
    "content": "#include<stdio.h>\n \nvoid DFS(int);\nint G[10][10],visited[10],n;    //n is no of vertices and graph is sorted in array G[10][10]\n \nvoid main()\n{\n    int i,j;\n    printf(\"Enter number of vertices:\");\n   \n    scanf(\"%d\",&n);\n \n    //read the adjecency matrix\n    printf(\"\\nEnter adjecency matrix of the graph:\");\n   \n    for(i=0;i<n;i++)\n       for(j=0;j<n;j++)\n            scanf(\"%d\",&G[i][j]);\n \n    //visited is initialized to zero\n   for(i=0;i<n;i++)\n        visited[i]=0;\n \n    DFS(0);\n}\n \nvoid DFS(int i)\n{\n    int j;\n    printf(\"\\n%d\",i);\n    visited[i]=1;\n    \n    for(j=0;j<n;j++)\n       if(!visited[j]&&G[i][j]==1)\n            DFS(j);\n}"
  },
  {
    "path": "disjoint_set/disjoint_set.hpp",
    "content": "#include <iostream>\r\nusing namespace std;\r\n\r\nclass disjoint_set {\r\nprivate:\r\n\tint *id, *size, count;\r\npublic:\r\n\tdisjoint_set(int n) : id(new int[n]), size(new int[n]), count(n) {\r\n\t\t// set ids for all e;ements, size = 1\r\n\t\tfor(int i=0;i<n;i++){\r\n\t\t\tid[i] = i;\r\n\t\t\tsize[i] = 1;\r\n\t\t}\r\n\t}\r\n\r\n\t~disjoint_set(){\r\n\t\tdelete [] id;\r\n\t\tdelete [] size;\r\n\t}\r\n\r\n\tint get_count(){\r\n\t\treturn this->count;\r\n\t}\r\n\r\n\t// return id of component corresponding to object n\r\n\tint find(int n){\r\n\t\tint root = n;\r\n\t\twhile(root != this->id[root]) root = this->id[root];\r\n\t\twhile(n != root){\r\n\t\t\tint new_n = this->id[n];\r\n\t\t\tthis->id[n] = root;\r\n\t\t\tn = new_n;\r\n\t\t}\r\n\t\treturn root;\r\n\t}\r\n\r\n\tvoid merge(int x, int y){\r\n\t\tint i = this->find(x);\r\n\t\tint j = this->find(y);\r\n\t\tif(i == j) return;\r\n\r\n\t\t// make smaller root opint to larger one\r\n\t\tif(this->size[i] < this->size[j]){\r\n\t\t\tthis->id[i] = j;\r\n\t\t\tthis->size[j] += this->size[i];\r\n\t\t}else{\r\n\t\t\tthis->id[j] = i;\r\n\t\t\tthis->size[i] += this->size[j];\r\n\t\t}\r\n\r\n\t\tthis->count--;\r\n\t}\r\n\r\n\tbool connected(int x, int y){\r\n\t\treturn this->find(x) == this->find(y);\r\n\t}\r\n};\r\n"
  },
  {
    "path": "divide_and_conquer/maximum_sub_array.cpp",
    "content": "/**\n*\tImplementation of finding maximum subarray which consists of finding range and sum of the subarray\n*   Using divide and conquer \n*/\n\n#include<bits/stdc++.h>\nusing namespace std;\n\n// vector array \nvector<int> a;\n\nint resM[3];\nint resR[3];\nint resL[3];\nint res[3];\n\n// find maximum subarray\nint * findMaxSubArray(int, int);\n\n// find subarray in the middle of two halves\nint * findMiddleSubArray(int, int, int);\n\nint main(){\n\t\n\t// size of array\n\tint n;\n\tcin>>n;\n\t\n\t\n\tint foo;\n\tfor (int i = 0; i < n; i++){\n\t\tcin>>foo;\n\t\t// add elements to vector a\n\t\ta.push_back(foo);\n\t}\n\t\n\n\t\n\tint *x = findMaxSubArray(0, n - 1);\n\t\n\t// left position\n\tcout<<\"(\"<<x[0]<<\",\";\n\t// right position\n\tcout<<x[1]<<\")\"<<endl;\n\t// max sum\n\tcout<<x[2]<<endl;\n\t\t\n}\n\nint * findMaxSubArray(int low, int high){\n\t\n\tif (high == low){\n\t// base case\n\t\t\n\t\t// return if only one element id present \n\n\t\tres[0] = low;\n\t\tres[1] = high;\n\t\tres[2] = a[low];\n\t\treturn res;\n\t\t\n\t}\n\telse{\n\t\n\t\t// find middle of vector\n\t\tint mid = (low + high)/2;\n\t\t\n\t\tint *res1L, *res1R, *res1M;\n\t\t\n\t\t// find maximum subarray in the left half\n\t\tres1L = findMaxSubArray(low, mid);\n\t\t\n\t\t// find maximum sub array in the right half\n\t\tres1R = findMaxSubArray(mid + 1, high);\n\t\t\n\t\t// find maximum subarray in the middle of the partition\n\t\tres1M = findMiddleSubArray(low, mid, high);\n\t\t\n\t\t// return maximum of 3 results comparing their sums\n\t\tif ((res1L[2] >= res1R[2]) && (res1L[2] >= res1M[2])){\n\t\t\n\t\t\tresL[0] = res1L[0];\n\t\t\tresL[1] = res1L[1];\n\t\t\tresL[2] = res1L[2];\n\t\t\treturn resL;\n\t\t}\n\t\telse if ((res1R[2] >= res1L[2]) && (res1R[2] >= res1M[2])){\n\t\t\t\n\t\t\tresM[0] = res1R[0];\n\t\t\tresM[1] = res1R[1];\n\t\t\tresM[2] = res1R[2];\n\t\t\treturn resR;\n\t\t}\n\t\telse{\n\t\t\n\t\t\treturn res1M;\n\t\t}\n\t\t\n\t\t\n\t}\n}\n\nint * findMiddleSubArray(int low, int mid, int high){\n\t\n\tint lSum = INT_MIN, rSum = INT_MIN;\n\tint sum = 0;\n\t\n\n\t\n\t// move through the left sub array starting from the middle to find the longest sub array\n\tfor (int i = mid; i >= low; i--){\n\t\tsum += a[i];\n\t\tif (sum > lSum){\n\t\t\tlSum = sum;\n\t\t\tresM[0] = i;\n\t\t}\n\t}\n\t\n\tsum = 0;\n\t// move through the right sub array starting from middle to find the longest sub array\n\tfor (int i = mid + 1; i <= high; i++){\n\t\tsum += a[i];\n\t\tif (sum > rSum){\n\t\t\trSum = sum;\n\t\t\tresM[1] = i;\n\t\t}\n\t}\n\t\n\t// find sum of the combined middle sub array\n\tresM[2] = lSum + rSum;\n\t\n\treturn resM;\n}\n\n"
  },
  {
    "path": "divide_and_conquer/strassen.cpp",
    "content": "#include<iostream>\r\n#include<cstdlib>\r\n#include<ctime>\r\nusing namespace std;\r\n\r\n\r\nvoid createMatrix(int **A4,int size);\r\nvoid output(int **A, int size);\r\nvoid standardMult(int **A, int **B, int **C, int size);\r\nvoid strassens(int **A, int **B, int **C, int size);\r\nvoid Add(int **A, int **B, int **T, int n);\r\nvoid Sub(int **A, int **B, int **T, int n);\r\n\r\n\r\n\r\n\r\nint main() {\r\n\tint size = 8;\r\n\t\r\n\t\r\n\tint **A, **B, **C;\r\n\r\n\tfor(int size=16;size<2048;size*=2){\r\n\r\n\tA = new int *[size];\r\n\tB = new int *[size];\r\n\tC = new int *[size];\r\n\r\n\t\r\n\tfor(int i=0; i<size; i++) {\r\n\t\tA[i] = new int[size];\r\n\t\tB[i] = new int[size];\r\n\t\tC[i] = new int[size];\r\n\t}\r\n\r\n\t//Matrices for i,j as i*j%1000\r\n\tcreateMatrix(A,size);\r\n\tcreateMatrix(B,size);\r\n\r\n\r\n\t\r\n\tcout<<\"Size of the matrix : \"<<size<<\"*\"<<size<<endl<<endl;\r\n\t//Multiplying Matrices using Standard Method\r\n\t\r\n\tint time = clock();\r\n\tstandardMult(A,B,C,size);\r\n\tint now=clock();\r\n\t//output(C,size);\r\n\tcout<<\"Standard Multiplication: \"<<(now-time)/1000000.0<<\" Seconds\"<<endl; \r\n\r\n\t//Multiplying Matrices using Strassen's Algorithm\r\n\t//cout<<endl<<endl<<\"Strassen's way\" <<endl;\r\n\ttime = clock();\r\n\tstrassens(A,B,C,size);\r\n\tnow=clock();\r\n\t//output(C,size);\r\n\tcout<<\"Stressen's multiplication : \"<<(now-time)/1000000.0<<\" Seconds\"<<endl<<endl; \r\n\r\n}}\r\n\r\n\r\n\r\n//Add matrices\r\nvoid Add(int **A, int **B, int **T, int n) {\r\n\tfor(int i=0; i<n; i++) {\r\n\t\tfor(int j=0; j<n; j++) {\r\n\t\t\tT[i][j] = A[i][j] + B[i][j];\r\n\t\t}\r\n\t}\r\n}\r\n\r\n//Subtract matricess\r\nvoid Sub(int **A, int **B, int **T, int n) {\r\n\tfor(int i=0; i<n; i++) {\r\n\t\tfor(int j=0; j<n; j++) {\r\n\t\t\tT[i][j] = A[i][j] - B[i][j];\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\r\n//method for matrix generation\r\nvoid createMatrix(int **A,int size) {\r\n\tfor(int i=0; i<size; i++) {\r\n\t\tfor(int j=0; j<size; j++) {\r\n\t\t\tA[i][j] = (i+1)*(j+1) % 1000;\r\n\t\t}\r\n\t}\r\n}\r\n\r\n//method to print a matrix\r\nvoid output(int **A, int size) {\r\n\tcout<<endl;\r\n\tfor(int i=0; i<size; i++) {\r\n\t\tfor(int j=0; j<size; j++) {\r\n\t\t\tcout<<A[i][j]<<\" \";\r\n\t\t}\r\n\t\tcout<<endl;\r\n\t}\r\n}\r\n\r\n//traditional method of multiplying two square matrices\r\nvoid standardMult(int **A, int **B, int **C, int size) {\r\n\tfor(int i=0; i<size; i++) {\r\n\t\tfor(int j=0; j<size; j++) {\r\n\t\t\tC[i][j] = 0;\r\n\t\t\tfor(int k=0; k<size; k++) {\r\n\t\t\t\tC[i][j] += A[i][k] * B [k][j];\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\n//strassen's product\r\nvoid strassens(int **A, int **B, int **C, int size) {\r\n\tif ( size <= 100)\r\n\t{\r\n\t\tstandardMult(A,B,C,size);\r\n\t}\r\n\telse \r\n\t{\r\n\t\t//Divide and conquer step\r\n\t\tint n = size/2;\r\n\t\tint N = size/2;\r\n\t\tint newsize = size/2;\r\n\r\n\t\t//Smaller matrices\r\n\t\tint **A11, **A12, **A21, **A22, **B11, **B12, **B21, **B22, **C11, **C12, **C21, **C22;\r\n\r\n\t\t//Matrices for Strassens\r\n\t\tint **M1, **M2, **M3, **M4, **M5, **M6, **M7;\r\n\r\n\t\r\n\t\tint **P, **Q;\r\n\r\n\t\t//memory allocation for columns\r\n\t\tA11 = new int *[n];A12 = new int *[n];A21 = new int *[n];A22 = new int *[n];\r\n\t\tB11 = new int *[n];B12 = new int *[n];B21 = new int *[n];B22 = new int *[n];\r\n\t\tC11 = new int *[n];C12 = new int *[n];C21 = new int *[n];C22 = new int *[n];\r\n\t\t\r\n\t\t//stressens matrices\r\n\t\tM1 = new int *[n];\r\n\t\tM2 = new int *[n];\r\n\t\tM3 = new int *[n];\r\n\t\tM4 = new int *[n];\r\n\t\tM5 = new int *[n];\r\n\t\tM6 = new int *[n];\r\n\t\tM7 = new int *[n];\r\n\r\n\t\tP = new int *[n];\r\n\t\tQ = new int *[n];\r\n\r\n\t\t//memory allocation for columns\r\n\t\tfor(int i=0; i<N; i++) {\r\n\t\t\tA11[i] = new int[N];A12[i] = new int[N];A21[i] = new int[N];A22[i] = new int[N];\r\n\t\t\tB11[i] = new int[N];B12[i] = new int[N];B21[i] = new int[N];B22[i] = new int[N];\r\n\t\t\tC11[i] = new int[N];C12[i] = new int[N];C21[i] = new int[N];C22[i] = new int[N];\r\n\r\n\t\t\tM1[i] = new int[N];\r\n\t\t\tM2[i] = new int[N];\r\n\t\t\tM3[i] = new int[N];\r\n\t\t\tM4[i] = new int[N];\r\n\t\t\tM5[i] = new int[N];\r\n\t\t\tM6[i] = new int[N];\r\n\t\t\tM7[i] = new int[N];\r\n\r\n\t\t\tP[i] = new int[N];\r\n\t\t\tQ[i] = new int[N];\r\n\r\n\t\t}\r\n\r\n\t\t//Dividing input matrices A and B into 4 submatrices each.\r\n\t\tfor (int i = 0; i < newsize; i++) {\r\n\t\t\tfor (int j = 0; j < newsize; j++) {\r\n\t\t\t\tA11[i][j] = A[i][j];\r\n\t\t\t\tA12[i][j] = A[i][j + newsize];\r\n\t\t\t\tA21[i][j] = A[i + newsize][j];\r\n\t\t\t\tA22[i][j] = A[i + newsize][j + newsize];\r\n\r\n\t\t\t\tB11[i][j] = B[i][j];\r\n\t\t\t\tB12[i][j] = B[i][j + newsize];\r\n\t\t\t\tB21[i][j] = B[i + newsize][j];\r\n\t\t\t\tB22[i][j] = B[i + newsize][j + newsize];\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t//M1\r\n\t\tSub(B12,B22,P,n);strassens(A11,P,M1,n);\r\n\r\n\t\t//M2\r\n\t\tAdd(A11,A12,P,n);strassens(P,B22,M2,n);\r\n\r\n\t\t//M3\r\n\t\tAdd(A21,A22,P,n);strassens(P,B11,M3,n);\r\n\r\n\t\t//M4\r\n\t\tSub(B21,B11,P,n);strassens(A22,P,M4,n);\r\n\r\n\t\t//M5\r\n\t\tAdd(A11,A22,P,n);Add(B11,B22,Q,n);strassens(P,Q,M5,n);\r\n\r\n\t\t//M6\r\n\t\tSub(A12,A22,P,n);Add(B21,B22,Q,n);strassens(P,Q,M6,n);\r\n\r\n\t\t//M7\r\n\t\tSub(A11,A21,P,n);Add(B11,B12,Q,n);strassens(P,Q,M7,n);\r\n\r\n\t\t//C11\r\n\t\tAdd(M4,M5,P,n);Sub(M6,M2,Q,n);Add(P,Q,C11,n);\r\n\r\n\t\t//C12\r\n\t\tAdd(M1,M2,C12,n);\r\n\r\n\t\t//C21\r\n\t\tAdd(M3,M4,C21,n);\r\n\r\n\t\t//C22\r\n\t\tAdd(M1,M5,P,n);\tAdd(M3,M7,Q,n);\tSub(P,Q,C22,n);\r\n\r\n\t\t//algorithm part\r\n\t\tfor (int i = 0; i < n ; i++) {\r\n\t\t\tfor (int j = 0 ; j < n ; j++) {\r\n\t\t\t\tC[i][j] = C11[i][j];\r\n\t\t\t\tC[i][j + n] = C12[i][j];\r\n\t\t\t\tC[i + n][j] = C21[i][j];\r\n\t\t\t\tC[i + n][j + n] = C22[i][j];\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n"
  },
  {
    "path": "dp/0-1knapsack.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n\nint knapsack(int n, int w, int weight[], int val[])\n{\n    int K[n+1][w+1];\n    for(int i=0;i<=n;i++)\n    {\n        for(int j=0;j<=w;j++)\n        {\n            if(i==0||j==0)\n                K[i][j]=0;\n            else\n            {\n                if(weight[i-1]<=j)\n                    K[i][j] = max(val[i-1] + K[i-1][j-weight[i-1]],  K[i-1][j]);\n                else\n                    K[i][j] = K[i-1][j];\n            }\n        }\n    }\n    return K[n][w];\n}\n\nint main() {\n\tint t,n,w;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t    cin>>n;\n\t    cin>>w;\n\t    int val[n], weight[n];\n\t    for(int i=0;i<n;i++)\n\t    {\n\t        cin>>val[i];\n\t    }\n\t    for(int i=0;i<n;i++)\n\t    {\n\t        cin>>weight[i];\n\t    }\n\t    cout<<knapsack(n,w,weight,val)<<\"\\n\";\n\t}\n\treturn 0;\n}\n"
  },
  {
    "path": "dp/Digit_dp.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n\nlong long int dp[20][180][2];\n\nlong long int getDigits(long long int x, vector <int> &digits) {\n\twhile(x) {\n\t\tdigits.push_back(x%10);\n\t\tx = x/10;\n\t}\n}\n\nlong long int digitSum(int idx, int sum, int tight, vector <int> &digit) {\n\n\tif(idx == -1) {\n\t\treturn sum;\n\t}\n\n\tif(dp[idx][sum][tight] != -1 && tight != 1) {\n\t\treturn dp[idx][sum][tight];\n\t}\n\n\tlong long int ret = 0;\n\n\n\tint k = (tight)?digit[idx]:9;\n\n\tint i;\n\n\tfor(i=0;i<=k;i++) {\n\n\t\tint newTight = (digit[idx] == i)?tight:0;\n\n\t\tret += digitSum(idx - 1, sum + i, newTight, digit);\n\t}\n\n\treturn ret;\n}\n\nlong long int rangeDigitSum(int a, int b) {\n\n\tmemset(dp, -1, sizeof(dp));\n\n\tvector <int> digitA;\n\tgetDigits(a-1, digitA);\n\n\tlong long int ans1 = digitSum(digitA.size() - 1, 0, 1, digitA);\n\n\tvector <int> digitB;\n\tgetDigits(b, digitB);\n\n\n\tlong long int ans2 = digitSum(digitB.size() - 1, 0, 1, digitB);\n\n\treturn (ans2 - ans1);\n}\n\nint main()\n{\n\tint a,b;\n\tcin>>a>>b;\n\tcout<<(rangeDigitSum(a,b));\n\treturn 0;\n}"
  },
  {
    "path": "dp/coinchange.cpp",
    "content": "#include<iostream>\nusing namespace std;\n\n///Coin Change Problem \n///Top Down DP\nint dp[100] = {0};\nint coinWaysTD(int amt,int coins[],int n){\n    if(amt==0){\n        dp[0] = 1;\n        return 1;\n    }\n    ///Recursive Case\n    int ans = 0;\n    \n    if(dp[amt]!=0){\n        return dp[amt];\n    }\n    for(int i=0;i<n;i++){\n        if(amt-coins[i]>=0){\n            ans += coinWaysTD(amt-coins[i],coins,n);\n        }\n    }\n    ///Store and return for the first time\n    dp[amt] = ans;\n    return ans;\n}\n\n///Bottom Up DP\nint coinWaysBU(int amt,int coins[],int n){\n    int dp[100] = {0};\n    dp[0] = 1;\n\n    for(int i=1;i<=amt;i++){\n        for(int j=0;j<n;j++){\n           if(i-coins[j]>=0){\n                dp[i] += dp[i-coins[j]];\n           }\n        }\n    }\n    return dp[amt];\n}\n\n\nint main(){\n\n    int coins[] = {1,2,3,8};\n    int amount = 3;\n    cout<<coinWaysTD(amount,coins,4)<<endl;\n    cout<<coinWaysBU(amount,coins,4)<<endl;\nreturn 0;\n}\n"
  },
  {
    "path": "dp/editDistance.cpp",
    "content": "#include<iostream>\n#include<string>\n#include<cstring>\n#include<algorithm>\n\nusing namespace std;\n\ninline int min(int a,int b,int c){\n    return min(a,min(b,c));\n}\n\nint dp[100][100];\n\nint editDistance(string a,string b,int m,int n){\n    if(m==0)\n        return n;\n    if(n==0)\n        return m;\n    if(dp[m][n]!=-1)\n        return dp[m][n];\n    int ans=0;\n    if(a[m-1]==b[n-1])\n        ans=editDistance(a,b,m-1,n-1);\n    else\n        ans=1+min(editDistance(a,b,m-1,n),editDistance(a,b,m,n-1),editDistance(a,b,m-1,n-1));\n    return dp[m][n]=ans;\n}\nint main(){\n    memset(dp,-1,sizeof(dp));\n    string a,b;\n    a=\"coding\";\n    b=\"hacking\";\n    cout<<editDistance(a,b,a.length(),b.length());\n}\n"
  },
  {
    "path": "dp/eggdropping.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n\nint eggdrop(int n, int k)\n{\n    int eggs[n+1][k+1];\n    for(int i=1;i<=n;i++)\n    {\n        eggs[i][0]=0;\n        eggs[i][1]=1;\n    }\n    for(int i=1;i<=k;i++)\n    {\n        eggs[1][i]=i;\n    }\n    for(int i=2;i<=n;i++)\n    {\n        for(int j=2;j<=k;j++)\n        {\n            eggs[i][j]=INT_MAX;\n            for(int x=1; x<=j; x++)\n            {\n                int res = 1+max(eggs[i-1][x-1], eggs[i][j-x]);\n                if(res<eggs[i][j])\n                eggs[i][j]=res;\n            }\n        }\n    }\n    return eggs[n][k];\n}\n\nint main() {\n    int t, n, k;\n    cin>>t;\n    while(t--)\n    {\n        cin>>n>>k;\n        cout<<eggdrop(n,k)<<\"\\n\";\n    }\n\treturn 0;\n}\n"
  },
  {
    "path": "dp/kadane.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n\tint t,n,cur_max,max_fin;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t    \n\t\tcin>>n;\n\t\tint arr[n];\n\t\tfor(int i=0;i<n;i++)\n\t\tcin>>arr[i];\n\t\tcur_max=arr[0];max_fin=arr[0];\n\t\tfor(int i=1;i<n;i++)\n\t\t{\n\t\t\tcur_max=max(arr[i],cur_max+arr[i]);\n\t\t\tmax_fin=max(max_fin, cur_max);\n\t\t}\n\t\tcout<<max_fin<<\"\\n\";\n\t}\n\treturn 0;\n}\n"
  },
  {
    "path": "dp/lcs.cpp",
    "content": "#include<iostream>\n#include<cstring>\nusing namespace std;\n\nint lcs(string s1,string s2,int i,int j){\n    if(i==0||j==0){\n        return 0;\n    }\n\n    if(s1[i-1]==s2[j-1]){\n        return  1 + lcs(s1,s2,i-1,j-1);\n    }\n    return max(lcs(s1,s2,i,j-1),lcs(s1,s2,i-1,j));\n}\n\nint lcsMatrix(string s1,string s2) {\n    int dp[100][100];\n    int l1 = s1.length();\n    int l2 = s2.length();\n\n    for(int i=0;i<=l1;i++){\n        for(int j=0;j<=l2;j++){\n            if(i==0||j==0){\n                dp[i][j] = 0;\n                continue;\n            }\n            else if(s1[i-1]==s2[j-1]){\n                dp[i][j] = 1 + dp[i-1][j-1];\n            }\n            else {\n                dp[i][j] = max(dp[i-1][j],dp[i][j-1]);\n            }\n        }\n    }\n\n    for(int i=0;i<=l1;i++){\n        for(int j=0;j<=l2;j++){\n            cout<<dp[i][j]<<\" \";\n        }\n        cout<<endl;\n    }\n    int x = l1;\n    int y = l2;\n    while(x>0 && y>0){\n        if(dp[x][y]==dp[x-1][y-1]+1){\n            cout<<s1[x-1]<<\" \";\n            x--;\n            y--;\n        }\n        else if(dp[x][y]==dp[x-1][y]){\n            x = x - 1;\n        }\n        else{\n            y = y - 1;\n        }\n    }\n\n\nreturn dp[l1][l2];\n}\nint main(){\n    string s1 = \"Apple\";\n    string s2 = \"anarpAplist\";\n\n    int i = s1.length();\n    int j = s2.length();\n\n    cout<<lcs(s1,s2,i,j)<<endl;\n    cout<<lcsMatrix(s1,s2)<<endl;\n\nreturn 0;\n}\n"
  },
  {
    "path": "dp/lis.cpp",
    "content": "#include <iostream>\nusing namespace std;\n\nint main() {\n\tint t,n;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t    cin>>n;\n\t    int arr[n],lis[n];\n\t    for(int i=0;i<n;i++)\n\t    {\n\t        cin>>arr[i];\n\t        lis[i]=1;\n\t    }\n\t    int max=1;\n\t    for(int i=1;i<n;i++)\n\t    {\n\t        for(int j=0;j<i;j++)\n\t        {\n\t            if(arr[j]<arr[i]&&lis[i]<lis[j]+1)\n\t            {\n\t                lis[i]=lis[j]+1;\n\t            }\n\t        }\n\t        if(lis[i]>max)\n\t        max=lis[i];\n\t    }\n\t    cout<<max<<\"\\n\";\n\t}\n\treturn 0;\n}\n"
  },
  {
    "path": "dp/mcm.cpp",
    "content": "#include<stdio.h>\n#include<iostream>\n#include<ctime>\n#include <fstream>\n\nusing namespace std;\n//random matrix sizes\nint mat[]={10,5,2,8,16,10,5,3,8,9,18,15,3,6,11,5,3,2,8,3,9,7,4,9,3};\n//5 15 and 25 as number of matrices\nint nn[]={5,10,25};\n\n//funtion for matrix chain multiplication using div and cnquer\nint mcmdnc(int a,int b)\n{\n  int cost;\n    //base Case\n       if(a==b)\n        cost=0;\n       else\n      {\n     for(int i=a;i<b;i++)\n      {\n            if(i==a)\n                cost=mcmdnc(a,i)+mcmdnc(i+1,b)+mat[a-1]*mat[i]*mat[b];\n            else\n                cost=min(cost,(mcmdnc(a,i)+mcmdnc(i+1,b)+mat[a-1]*mat[i]*mat[b]));\n      }\n    }\n    return  cost;\n}\n   \n\n//function for matrix chain multiplication using dp\nint mcmdp(int p[], int n){\n    int m[n][n];\n    int i, j, k, L, q;\n    for (i = 1; i < n; i++)\n        m[i][i] = 0;\n    for (L=2; L<n; L++)   {\n        for (i=1; i<=n-L+1; i++){\n            j = i+L-1;\n            m[i][j] = 100000;\n            for (k=i; k<=j-1; k++){\n                q = m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j];\n                if (q < m[i][j])\n                    m[i][j] = q;\n            }\n        }\n    }\n    return m[1][n-1];\n}\nint main(){\n    int val;\n    \n    for (int i=0;i<3; i++){\n\nint t=clock();\n\tval= mcmdp(mat,nn[i]);\n    cout<<\"Optimised cost for \"<<nn[i]<<\" matrices is \"<<val<<\"(DP)\"<<endl<<\" time taken :\"<< ((float)(clock()-t))/CLOCKS_PER_SEC<<endl;\n\n         t=clock();\n  \n\n\tval=mcmdnc(1,nn[i]-1);\n    cout<<\"Optimised cost for \"<<nn[i]<<\" matrices is \"<<val<<\"(DivAndConq)\"<<endl<<\" time taken :\"<< ((float)(clock()-t))/CLOCKS_PER_SEC<<endl;\n\n\t}\n    return 0;\n}\n"
  },
  {
    "path": "euler_totent_function",
    "content": "//N is the limit, upto which we need to find ETF values\n//phi[x] stores the ETF value of number x.\n//Euler's totient function counts the positive integers up to a given integer N that are relatively prime to N. It is written using the Greek letter phi as φ(N) or ϕ(N), and may also be called Euler's phi function.\n\n//In other words φ(N) is defined as number of integers K in the range 1 ≤ K ≤ N for which the greatest common divisor gcd(N, K) is equal to 1. The integers K of this form are called totatives of N. \n\n\nint phi[N+1];\n\nvoid sieve()\n{\n\tint i,j;\n\n\tfor(i = 1; i <= N; i++)\n\t\tphi[i] = i;\n\n\tfor(i = 2; i <= N; i++) {\n\t\tif(phi[i] == i) {\n\t\t\tfor(j = i; j <= N; j += i) {\n\t\t\t\tphi[j] /= i;\n\t\t\t\tphi[j] *= (i-1);\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n"
  },
  {
    "path": "genome_sort.py",
    "content": "def gnomeSort( arr, n):\n    index = 0\n    while index < n:\n        if index == 0:\n            index = index + 1\n        if arr[index] >= arr[index - 1]:\n            index = index + 1\n        else:\n            arr[index], arr[index-1] = arr[index-1], arr[index]\n            index = index - 1\n \n    return arr\n \n\nn=int(input())\narr=[]\nfor i in range(n):\n    c=int(input())\n    arr.append(c)\n\narr = gnomeSort(arr, n)\nprint \"Sorted sequence after applying Gnome Sort :\",\nfor i in arr:\n    print(i)\n"
  },
  {
    "path": "graph/Kosaraju_algorithm",
    "content": "#include <iostream>\n#include <list>\n#include <stack>\nusing namespace std;\n\nclass Graph\n{\n    int V;    // No. of vertices\n    list<int> *adj;    // An array of adjacency lists\n\n    // Fills Stack with vertices (in increasing order of finishing\n    // times). The top element of stack has the maximum finishing\n    // time\n    void fillOrder(int v, bool visited[], stack<int> &Stack);\n\n    // A recursive function to print DFS starting from v\n    void DFSUtil(int v, bool visited[]);\npublic:\n    Graph(int V);\n    void addEdge(int v, int w);\n\n    // The main function that finds and prints strongly connected\n    // components\n    void printSCCs();\n\n    // Function that returns reverse (or transpose) of this graph\n    Graph getTranspose();\n};\n\nGraph::Graph(int V)\n{\n    this->V = V;\n    adj = new list<int>[V];\n}\n\n// A recursive function to print DFS starting from v\nvoid Graph::DFSUtil(int v, bool visited[])\n{\n    // Mark the current node as visited and print it\n    visited[v] = true;\n    cout << v << \" \";\n\n    // Recur for all the vertices adjacent to this vertex\n    list<int>::iterator i;\n    for (i = adj[v].begin(); i != adj[v].end(); ++i)\n        if (!visited[*i])\n            DFSUtil(*i, visited);\n}\n\nGraph Graph::getTranspose()\n{\n    Graph g(V);\n    for (int v = 0; v < V; v++)\n    {\n        // Recur for all the vertices adjacent to this vertex\n        list<int>::iterator i;\n        for(i = adj[v].begin(); i != adj[v].end(); ++i)\n        {\n            g.adj[*i].push_back(v);\n        }\n    }\n    return g;\n}\n\nvoid Graph::addEdge(int v, int w)\n{\n    adj[v].push_back(w); // Add w to v’s list.\n}\n\nvoid Graph::fillOrder(int v, bool visited[], stack<int> &Stack)\n{\n    // Mark the current node as visited and print it\n    visited[v] = true;\n\n    // Recur for all the vertices adjacent to this vertex\n    list<int>::iterator i;\n    for(i = adj[v].begin(); i != adj[v].end(); ++i)\n        if(!visited[*i])\n            fillOrder(*i, visited, Stack);\n\n    // All vertices reachable from v are processed by now, push v\n    Stack.push(v);\n}\n\n// The main function that finds and prints all strongly connected\n// components\nvoid Graph::printSCCs()\n{\n    stack<int> Stack;\n\n    // Mark all the vertices as not visited (For first DFS)\n    bool *visited = new bool[V];\n    for(int i = 0; i < V; i++)\n        visited[i] = false;\n\n    // Fill vertices in stack according to their finishing times\n    for(int i = 0; i < V; i++)\n        if(visited[i] == false)\n            fillOrder(i, visited, Stack);\n\n    // Create a reversed graph\n    Graph gr = getTranspose();\n\n    // Mark all the vertices as not visited (For second DFS)\n    for(int i = 0; i < V; i++)\n        visited[i] = false;\n\n    // Now process all vertices in order defined by Stack\n    while (Stack.empty() == false)\n    {\n        // Pop a vertex from stack\n        int v = Stack.top();\n        Stack.pop();\n\n        // Print Strongly connected component of the popped vertex\n        if (visited[v] == false)\n        {\n            gr.DFSUtil(v, visited);\n            cout << endl;\n        }\n    }\n}\n\n// Driver program to test above functions\nint main()\n{\n    // Create a graph given in the above diagram\n    int n ;\n    cout << \"Enter how many vertices your graph will have?\" << endl ;\n    cin >> n ;\n\n    Graph g(n) ;\n    char ch = 'y' ;\n\n    while(ch=='y'){\n        int src ;\n        int dst ;\n        cout << \"Enter the originating vertice and the destination vertice with a space\" << endl ;\n        cin >> src >> dst ;\n\n        g.addEdge(src, dst) ;\n\n        cout << \"Do you want to add another edge? type 'y' for yes, 'n' for no\" << endl ;\n        cin >> ch ;\n        cout << endl ;\n    }\n\n\n    cout << \"Following are strongly connected components in \"\n            \"given graph \\n\";\n    g.printSCCs();\n\n    return 0;\n}\n"
  },
  {
    "path": "graph/bfs_dfs/bfs/BFS.cpp",
    "content": "// Program to print BFS traversal from a given source vertex (s). \n// BFS(int s) traverses vertices reachable from s.\n#include<iostream>\n#include <list>\n \nusing namespace std;\n \n// This class represents a directed graph using adjacency list representation\nclass Graph\n{\n    int V;    // No. of vertices\n \n    // Pointer to an array containing adjacency list.\n    list<int> *adj;   \npublic:\n    Graph(int V);  // Constructor\n \n    // function to add an edge to graph\n    void addEdge(int v, int w); \n \n    // prints BFS traversal from a given source s\n    void BFS(int s);  \n};\n \nGraph::Graph(int V)\n{\n    this->V = V;\n    adj = new list<int>[V];\n}\n \nvoid Graph::addEdge(int v, int w)\n{\n    adj[v].push_back(w); // Add w to v’s list.\n}\n\n///// MAIN LOGIC ALGORITHMIC FUNCTION  /////\nvoid Graph::BFS(int s)\n{\n    // Mark all the vertices as not visited\n    bool *visited = new bool[V];\n    for(int i = 0; i < V; i++)\n        visited[i] = false;\n \n    // Create a queue for BFS\n    list<int> queue;\n \n    // Mark the current node as visited and enqueue it\n    visited[s] = true;\n    queue.push_back(s);\n \n    // 'i' will be used to get all adjacent vertices of the current vertex.\n    list<int>::iterator i;\n \n    while(!queue.empty())\n    {\n        // Dequeue a vertex from queue and print it\n        s = queue.front();\n        cout << s << \" \";\n        queue.pop_front();\n \n        // Get all adjacent vertices of the dequeued vertex s. \n        // If a adjacent has not been visited, then mark it visited and enqueue it\n        for (i = adj[s].begin(); i != adj[s].end(); ++i)\n        {\n            if (!visited[*i])\n            {\n                visited[*i] = true;\n                queue.push_back(*i);\n            }\n        }\n    }\n}\n \nint main()\n{\n    // Create a graph (given is an example)\n    Graph g(4);\n    g.addEdge(0, 1);\n    g.addEdge(0, 2);\n    g.addEdge(1, 2);\n    g.addEdge(2, 0);\n    g.addEdge(2, 3);\n    g.addEdge(3, 3);\n \n    cout << \"Following is Breadth First Traversal \"\n         << \"(starting from vertex 2) \\n\";\n    g.BFS(2);   //2 is the starting vertex.\n \n    return 0;\n}\n"
  },
  {
    "path": "graph/bfs_dfs/bfs/BFS.py",
    "content": "# Program to print BFS traversal from a given source vertex.\n# BFS(int s) traverses vertices reachable from s.\nfrom collections import defaultdict\n \n# This class represents a directed graph using adjacency list representation\nclass Graph:\n \n    # Constructor\n    def __init__(self):\n \n        # default dictionary to store graph\n        self.graph = defaultdict(list)\n \n    # function to add an edge to graph\n    def addEdge(self,u,v):\n        self.graph[u].append(v)\n \n    ### Main Algorithmic Function\n    # Function to print a BFS of graph\n    def BFS(self, s):\n \n        # Mark all the vertices as not visited\n        visited = [False]*(len(self.graph))\n \n        # Create a queue for BFS\n        queue = []\n \n        # Mark the source node as visited and enqueue it\n        queue.append(s)\n        visited[s] = True\n \n        while queue:\n \n            # Dequeue a vertex from queue and print it\n            s = queue.pop(0)\n            print s,\n \n            # Get all adjacent vertices of the dequeued vertex s.\n            # If a adjacent has not been visited, then mark it visited and enqueue it\n            for i in self.graph[s]:\n                if visited[i] == False:\n                    queue.append(i)\n                    visited[i] = True\n \n \n# Create a graph (given is an example)\ng = Graph()\ng.addEdge(0, 1)\ng.addEdge(0, 2)\ng.addEdge(1, 2)\ng.addEdge(2, 0)\ng.addEdge(2, 3)\ng.addEdge(3, 3)\n \nprint \"Following is Breadth First Traversal (starting from vertex 2)\"\ng.BFS(2)\n"
  },
  {
    "path": "graph/bfs_dfs/bfs/bfs.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n#define For(i,a,b) for(int i=(a);i<(b);i++)\n\nvoid bfs(int n, std::vector<int> v[], int s){\n\tint c[n+1]={0};//colour of vertices\n\t//0 white 1 gray \n\tc[s] = 1;\n\tqueue<int> q;\n\tq.push(s);\n\tint t;\n\twhile(!q.empty()){\n\t\tt = q.front();\n\t\tcout << t << \" \";\n\t\t//q.front();\n\t\tq.pop();\n\t\tFor(i,0,v[t].size()){\n\t\t\tif(c[v[t][i]] == 0){\n\t\t\t\tc[v[t][i]] = 1;\n\t\t\t\tq.push(v[t][i]);\n\t\t\t}\n\t\t}\n\t}\n\n}\n\nint main(){\n\t\n\tcout << \"Enter number of vertices : \";\n\tint n; cin >> n;\n\tstd::vector<int> v[n+1];\n\tcout << \"Enter number of edges (Undirected Graph) : \";\n\tint e,a,b; cin >> e;\n\tcout << \"Enter edges now : \";\n\tFor(i,0,e){\n\t\tcout << \"\\nEdge no.\" << i+1 << \" : \";\n\t\tcin >> a;\n\t\tcin >> b;\n\t\tv[a].push_back(b);\n\t\tv[b].push_back(a);\n\t}\n\tcout << \"Find BFS from which vertex ? \";\n\tint s;cin >> s;\n\tbfs(n,v,s); \n}"
  },
  {
    "path": "graph/bfs_dfs/dfs/DFS.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <iomanip>\n#include <map>\n\nusing namespace std;\n\n#define WHITE 0\n#define GRAY 1\n#define BLACK 2\n\n#define MAXV 15\n\ntypedef pair<int, int> ii;      // Vertex, Weight\ntypedef vector<ii> vii;\ntypedef map<int, int> mii;\n\nvii adjList[MAXV];              // Adjacency List\n\nmii dfs_num; \nmii dfs_parent;\n\nmii dfs_d;\nmii dfs_f;\n\nint time_c = 0;\n\nvoid dfs(int u) {\n    dfs_num[u] = GRAY;\n    dfs_d[u] = ++time_c;\n\n    for(vii::iterator it = adjList[u].begin(); it != adjList[u].end(); it++) {\n        \n        // Finding edges in the graph\n        if (dfs_num[it->first] == WHITE) {\n            dfs_parent[it->first] = u;\n            dfs(it->first);\n        } else if (dfs_num[it->first] == GRAY) {    \n            if (it->first != dfs_parent[u]) {\n                // Finding return edges\n            } else {\n                // Finding bidirectional edges\n            }\n        } else if (dfs_num[it->first] == BLACK) {\n            // Finding crossover edges\n        }\n    }\n\n    dfs_num[u] = BLACK;\n    dfs_f[u] = ++time_c;\n}\n\nvoid printTree(int V) {\n    for (int i = 1; i <= V; i++) {\n        cout << \"Vértices: \";\n        cout << setw(2) << i << \" Discovery time: \";\n        cout << setw(2) << dfs_d[i] << \" End time: \";\n        cout << setw(2) << dfs_f[i] << \" Predecessor: \";\n\n        if (dfs_parent[i] >= 0) {\n            cout << setw(3) << dfs_parent[i] << endl;\n        } else {\n            cout << setw(3) << \"NIL \" << endl;\n        }\n    }\n}\n\nint main() {\n    int V,E,X,Y;\n    int IN;\n\n    cin >> V >> E;\n\n    for (int i=0; i<E; i++) {\n        cin >> X >> Y;\n\n        adjList[X].push_back(make_pair(Y,0));\n    }\n\n    cin >> IN;\n\n    dfs(IN);\n\n    printTree(V);\n\n    return 0;\n}\n"
  },
  {
    "path": "graph/bfs_dfs/dfs/DFS.java",
    "content": "/**\n * Input file example:\n *\n * 8\n * INF 1 1 INF INF INF INF INF\n * 1 INF INF 1 1 INF INF INF\n * 1 INF INF INF INF 1 1 INF\n * INF 1 INF INF INF INF INF INF\n * INF 1 INF INF INF INF INF 1\n * INF INF 1 INF INF INF INF INF\n * INF INF 1 INF INF INF INF INF\n * INF INF INF INF 1 INF INF INF\n * 1\n *\n * First line is number of elements in graph\n * Next n-lines is graph\n * Last line is begin point\n *\n * Output file:\n * 1 -> 2 -> 4 -> 5 -> 8 -> 3 -> 6 -> 7\n *\n */\n\npackage dfs;\n\nimport java.io.BufferedWriter;\nimport java.io.FileInputStream;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.util.*;\n\npublic class DFS {\n\n    private static final String INPUT_FILE_PATH = \"input.txt\";\n\n    private static final String OUTPUT_FILE_PATH = \"output.txt\";\n\n    private static final int INF = Integer.MAX_VALUE / 2;\n\n    private static boolean used[];\n\n    private static int begin;\n\n    public static void main(String[] args) {\n        int[][] matrix = readMatrixFromFile();\n        used = new boolean[matrix.length];\n        String answer = dfs(matrix, begin);\n        printSolution(answer);\n    }\n\n    private static int[][] readMatrixFromFile() {\n        int[][] matrix = null;\n\n        try (Scanner scanner = new Scanner(new FileInputStream(INPUT_FILE_PATH))) {\n            int matrixSize = Integer.parseInt(scanner.nextLine());\n            matrix = new int[matrixSize][matrixSize];\n\n            for (int row = 0; row < matrixSize; row++) {\n                String[] numbers = scanner.nextLine().split(\" \");\n                for (int col = 0; col < matrixSize; col++) {\n                    if (numbers[col].equals(\"INF\")) {\n                        matrix[row][col] = INF;\n                    } else {\n                        matrix[row][col] = Integer.parseInt(numbers[col]);\n                    }\n                }\n            }\n\n            begin = scanner.nextInt() - 1;\n        } catch (IOException e) {\n            e.printStackTrace();\n        }\n\n        return matrix;\n    }\n\n    private static String dfs(int[][] matrix, int v) {\n        StringBuilder answer = new StringBuilder();\n\n        used[v] = true;\n        answer.append(v + 1).append(\" \");\n        for (int nv = 0; nv < matrix.length; nv++) {\n            if (!used[nv] && matrix[v][nv] != INF) {\n                answer.append(dfs(matrix, nv));\n            }\n        }\n\n        return answer.toString();\n    }\n\n    private static void printSolution(String answer) {\n        try (BufferedWriter writer = new BufferedWriter(new FileWriter(OUTPUT_FILE_PATH))) {\n            String[] points = answer.split(\" \");\n            writer.write(points[0]);\n\n            for (int i = 1; i < points.length; i++) {\n                writer.write(\" -> \" + points[i]);\n            }\n        } catch (IOException e) {\n            e.printStackTrace();\n        }\n    }\n\n}\n"
  },
  {
    "path": "heap/heap.hpp",
    "content": "#include <iostream>\r\nusing namespace std;\r\n\r\ntemplate<typename T>\r\nclass heap {\r\nprivate:\r\n\tT *arr;\r\n\tint size;\r\n\tint capacity;\r\n\tint type; // if 1, max heap else if -1 min heap\r\npublic:\r\n\theap() : arr(NULL), size(0), capacity(0), type(0) {}\r\n\theap(int capacity, int type) : arr(new T[capacity]), size(0), capacity(capacity), type(type) {}\r\n\r\n\t// get private values\r\n\tint get_size(){ return this->size; }\r\n\tint get_capacity(){ return this->capacity; }\r\n\tint get_type(){ return this->type; }\r\n\r\n\t// util functions\r\n\t// get index of parent from child index\r\n\tint get_parent(int child_index){\r\n\t\tif(child_index <=0 || child_index >= this->capacity) return -1;\r\n\t\treturn (child_index-1)/2;\r\n\t}\r\n\r\n\tbool has_left_child(int parent_index){\r\n\t\treturn (parent_index * 2 + 1 < this->size) && (parent_index >= 0);\r\n\t}\r\n\r\n\tbool has_right_child(int parent_index){\r\n\t\treturn (parent_index * 2 + 2 < this->size) && (parent_index >= 0);\r\n\t}\r\n\r\n\t// get index of left child from parent's index\r\n\tint get_left_child(int parent_index){\r\n\t\tint left_child_index = parent_index * 2 + 1;\r\n\t\tif(!has_left_child(parent_index)) return -1;\r\n\t\treturn left_child_index;\r\n\t}\r\n\r\n\t// get index of left child from parent's index\r\n\tint get_right_child(int parent_index){\r\n\t\tint right_child_index = parent_index * 2 + 2;\r\n\t\tif(!has_right_child(parent_index)) return -1;\r\n\t\treturn right_child_index;\r\n\t}\r\n\r\n\t// get max / min, depending on the type of heap\r\n\t// get minimum from min heap\r\n\tT get_min(){\r\n\t\t// returns null if array is empty or heap type is max\r\n\t\tif(this->size == 0 || this->type == 1) return '\\0';\r\n\t\treturn this->arr[0];\r\n\t}\r\n\t// get maximum from max heap\r\n\tT get_max(){\r\n\t\t// returns null if array is empty or heap type is min\r\n\t\tif(this->size == 0 || this->type == -1) return '\\0';\r\n\t\treturn this->arr[0];\r\n\t}\r\n\r\n\t// takes location of element as input and heapifies our array downwards\r\n\t// considering max heap\r\n\tvoid down(int parent_index){\r\n\t\tint left_child_index = get_left_child(parent_index), right_child_index = get_right_child(parent_index);\r\n\t\tif(left_child_index == -1 && right_child_index == -1) return;\r\n\r\n\t\t// everything is valid, so let's proceed to finding the next max element that can be swapped with the parent\r\n\t\tint max_element = parent_index;\r\n\t\tif(left_child_index != -1){\r\n\t\t\tif(arr[left_child_index] > arr[parent_index]) max_element = left_child_index;\r\n\t\t\telse max_element = parent_index;\r\n\t\t} \r\n\t\telse max_element = parent_index;\r\n\r\n\t\tif(right_child_index != -1){\r\n\t\t\tif(arr[right_child_index] > arr[max_element]) max_element = right_child_index;\r\n\t\t} \r\n\r\n\t\tif(max_element == -1) return;\r\n\r\n\t\t// swap max_element with parent\r\n\t\tif(max_element != parent_index){\r\n\t\t\tint temp = arr[max_element];\r\n\t\t\tarr[max_element] = arr[parent_index];\r\n\t\t\tarr[parent_index] = temp;\r\n\t\t}\r\n\r\n\t\tdown(max_element);\r\n\t}\r\n\r\n\tbool is_full(){\r\n\t\treturn this->size == this->capacity;\r\n\t}\r\n\r\n\tbool is_empty(){\r\n\t\treturn this->size == 0;\r\n\t}\r\n\r\n\tvoid resize(){\r\n\t\tT *old_array = this->arr;\r\n\t\tthis->arr = static_cast< T* > (malloc(sizeof(T) * this->capacity * 2));\r\n\t\tif(this->arr == NULL){\r\n\t\t\tcout << \"Memory error\" << endl;\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tfor(int i=0;i<this->capacity;i++) this->arr[i] = old_array[i];\r\n\t\tthis->capacity *= 2;\r\n\t\tdelete [] old_array;\r\n\t}\r\n\r\n\tvoid insert(T data){\r\n\t\tif(this->is_full()) this->resize();\r\n\t\tthis->size++;\r\n\t\tint i = this->size - 1;\r\n\t\twhile(i>0 && data > this->arr[get_parent(i)]){\r\n\t\t\tthis->arr[i] = this->arr[get_parent(i)];\r\n\t\t\ti = get_parent(i);\r\n\t\t}\r\n\t\tthis->arr[i] = data;\r\n\t}\r\n\r\n\t// another constructor to create a heap from an array\r\n\theap(T ar[], int capacity, int type) : arr(new T[capacity]), size(capacity), capacity(capacity), type(type) {\r\n\t\tfor(int i=0;i<capacity;i++) this->arr[i] = ar[i];\r\n\t\tfor(int i=(capacity-1)/2;i>=0;i--) down(i);\r\n\t}\r\n\r\n\tvoid print(){\r\n\t\tcout << \"Printing heap: \" << endl;\r\n\t\tfor(int i=0;i<this->size;i++) cout << this->arr[i] << \" \";\r\n\t\tcout << endl;\r\n\t}\r\n\r\n\tbool is_heap(){\r\n\t\tint i = 0;\r\n\t\t// assuming max heap\r\n\t\tfor(int j=0;j<this->size;j++){\r\n\t\t\tif(this->has_left_child(j) && this->arr[this->get_left_child(j)] > this->arr[j]) return false; \r\n\t\t\tif(this->has_right_child(j) && this->arr[this->get_right_child(j)] > this->arr[j]) return false; \r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n};\r\n"
  },
  {
    "path": "heap/min_heap.cpp",
    "content": "#include<iostream>\n#include<vector>\nusing namespace std;\n\nclass minHeap{\n    vector<int> v;\n    \n    void heapify(int i){\n        int l=2*i;\n        int r=2*i+1;\n        int minIndex = i;\n        if(l < v.size() && v[l]<v[minIndex]){\n            minIndex = l;\n        }\n        if(r< v.size() && v[r]<v[minIndex]){\n            minIndex = r;\n        }\n        if(minIndex!=i){\n            swap(v[i],v[minIndex]);\n            heapify(minIndex);\n        }\n    }\n\npublic:\n    minHeap(){\n        v.push_back(-1);   \n    }\n    void push(int data){\n        v.push_back(data);\n        int index = v.size()-1;\n        int parent = index/2;\n\n        while(v[index]<v[parent] && index>1){\n            swap(v[index],v[parent]);\n            index=parent;\n            parent=parent/2;\n        }\n    }\n\n    int getmin(){\n        return v[1];\n    }\n    void pop(){\n        int last=v.size()-1;\n        swap(v[1],v[last]);\n        v.pop_back();\n        heapify(1);\n    }\n\n    bool isEmpty(){\n        return v.size()==1;\n    }\n};\n\nint main(){\n\n    int a[] = {10,45,33,211,16,120,150,132};\n    int n = sizeof(a)/sizeof(int);\n\n    minHeap h;\n    for(int i=0;i<n;i++) h.push(a[i]);\n      \n    while(!h.isEmpty()){\n        cout<<h.getmin()<<\" \";\n        h.pop();\n    }\n    return 0;\n}\n\n/* Output : 10 16 33 45 120 132 150 211 */\n"
  },
  {
    "path": "os/scheduling/fcfs.cpp",
    "content": "// C++ program for implementation of FCFS \r\n// scheduling\r\n#include<iostream>\r\nusing namespace std;\r\n\r\n// Function to find the waiting time for all \r\n// processes\r\nvoid findWaitingTime(int processes[], int n, \r\n                          int bt[], int wt[])\r\n{\r\n    // waiting time for first process is 0\r\n    wt[0] = 0;\r\n\r\n    // calculating waiting time\r\n    for (int  i = 1; i < n ; i++ )\r\n        wt[i] =  bt[i-1] + wt[i-1] ;\r\n}\r\n\r\n// Function to calculate turn around time\r\nvoid findTurnAroundTime( int processes[], int n, \r\n                  int bt[], int wt[], int tat[])\r\n{\t \r\n    // calculating turnaround time by adding\r\n    // bt[i] + wt[i]\r\n    for (int  i = 0; i < n ; i++)\r\n        tat[i] = bt[i] + wt[i];\r\n}\r\n\r\n//Function to calculate average time\r\nvoid findavgTime( int processes[], int n, int bt[])\r\n{\r\n    int wt[n], tat[n], total_wt = 0, total_tat = 0;\r\n\r\n    //Function to find waiting time of all processes\r\n    findWaitingTime(processes, n, bt, wt);\r\n\r\n    //Function to find turn around time for all processes\r\n    findTurnAroundTime(processes, n, bt, wt, tat);\r\n\r\n    //Display processes along with all details\r\n    cout << \"Processes  \"<< \" Burst time  \"\r\n         << \" Waiting time  \" << \" Turn around time\\n\";\r\n\r\n    // Calculate total waiting time and total turn \r\n    // around time\r\n    for (int  i=0; i<n; i++)\r\n    {\r\n        total_wt = total_wt + wt[i];\r\n        total_tat = total_tat + tat[i];\r\n        cout << \"   \" << i+1 << \"\\t\\t\" << bt[i] <<\"\\t    \"\r\n            << wt[i] <<\"\\t\\t  \" << tat[i] <<endl;\r\n    }\r\n\r\n    cout << \"Average waiting time = \" \r\n         << (float)total_wt / (float)n;\r\n    cout << \"\\nAverage turn around time = \" \r\n         << (float)total_tat / (float)n;\r\n}\r\n\r\n// Driver code\r\nint main()\r\n{\r\n    //process id's\r\n    int processes[] = { 1, 2, 3, 4};\r\n    int n = sizeof processes / sizeof processes[0];\r\n\r\n    //Burst time of all processes\r\n    int  burst_time[] = {5, 15, 8,12};\r\n\r\n    findavgTime(processes, n,  burst_time);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "os/scheduling/os_priority.cpp",
    "content": "\t// C++ program for implementation of FCFS\r\n// scheduling\r\n#include<bits/stdc++.h>\r\nusing namespace std;\r\n \r\nstruct Process\r\n{\r\n    int pid;  // Process ID\r\n    int bt;   // CPU Burst time required\r\n    int priority; // Priority of this process\r\n};\r\n \r\n// Function to sort the Process acc. to priority\r\nbool comparison(Process a, Process b)\r\n{\r\n    return (a.priority > b.priority);\r\n}\r\n \r\n// Function to find the waiting time for all\r\n// processes\r\nvoid findWaitingTime(Process proc[], int n,\r\n                     int wt[])\r\n{\r\n    // waiting time for first process is 0\r\n    wt[0] = 0;\r\n \r\n    // calculating waiting time\r\n    for (int  i = 1; i < n ; i++ )\r\n        wt[i] =  proc[i-1].bt + wt[i-1] ;\r\n}\r\n \r\n// Function to calculate turn around time\r\nvoid findTurnAroundTime( Process proc[], int n,\r\n                         int wt[], int tat[])\r\n{\r\n    // calculating turnaround time by adding\r\n    // bt[i] + wt[i]\r\n    for (int  i = 0; i < n ; i++)\r\n        tat[i] = proc[i].bt + wt[i];\r\n}\r\n \r\n//Function to calculate average time\r\nvoid findavgTime(Process proc[], int n)\r\n{\r\n    int wt[n], tat[n], total_wt = 0, total_tat = 0;\r\n \r\n    //Function to find waiting time of all processes\r\n    findWaitingTime(proc, n, wt);\r\n \r\n    //Function to find turn around time for all processes\r\n    findTurnAroundTime(proc, n, wt, tat);\r\n \r\n    //Display processes along with all details\r\n    cout << \"\\nProcesses  \"<< \" Burst time  \"\r\n         << \" Waiting time  \" << \" Turn around time\\n\";\r\n \r\n    // Calculate total waiting time and total turn\r\n    // around time\r\n    for (int  i=0; i<n; i++)\r\n    {\r\n        total_wt = total_wt + wt[i];\r\n        total_tat = total_tat + tat[i];\r\n        cout << \"   \" << proc[i].pid << \"\\t\\t\"\r\n             << proc[i].bt << \"\\t    \" << wt[i]\r\n             << \"\\t\\t  \" << tat[i] <<endl;\r\n    }\r\n \r\n    cout << \"\\nAverage waiting time = \"\r\n         << (float)total_wt / (float)n;\r\n    cout << \"\\nAverage turn around time = \"\r\n         << (float)total_tat / (float)n;\r\n}\r\n \r\nvoid priorityScheduling(Process proc[], int n)\r\n{\r\n    // Sort processes by priority\r\n    sort(proc, proc + n, comparison);\r\n \r\n    cout<< \"Order in which processes gets executed \\n\";\r\n    for (int  i = 0 ; i <  n; i++)\r\n        cout << proc[i].pid <<\" \" ;\r\n \r\n    findavgTime(proc, n);\r\n}\r\n \r\n// Driver code\r\nint main()\r\n{\r\n    Process proc[] = {{1, 12, 2}, {2, 6, 0}, {3, 9, 1}};\r\n    int n = sizeof proc / sizeof proc[0];\r\n    priorityScheduling(proc, n);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "os/scheduling/os_roundrobin.cpp",
    "content": "#include<iostream>\r\nusing namespace std;\r\n \r\n// Function to find the waiting time for all\r\n// processes\r\nvoid findWaitingTime(int processes[], int n,\r\n             int bt[], int wt[], int quantum)\r\n{\r\n    // Make a copy of burst times bt[] to store remaining\r\n    // burst times.\r\n    int rem_bt[n];\r\n    for (int i = 0 ; i < n ; i++)\r\n        rem_bt[i] =  bt[i];\r\n \r\n    int t = 0; // Current time\r\n \r\n    // Keep traversing processes in round robin manner\r\n    // until all of them are not done.\r\n    while (1)\r\n    {\r\n        bool done = true;\r\n \r\n        // Traverse all processes one by one repeatedly\r\n        for (int i = 0 ; i < n; i++)\r\n        {\r\n            // If burst time of a process is greater than 0\r\n            // then only need to process further\r\n            if (rem_bt[i] > 0)\r\n            {\r\n                done = false; // There is a pending process\r\n \r\n                if (rem_bt[i] > quantum)\r\n                {\r\n                    // Increase the value of t i.e. shows\r\n                    // how much time a process has been processed\r\n                    t += quantum;\r\n \r\n                    // Decrease the burst_time of current process\r\n                    // by quantum\r\n                    rem_bt[i] -= quantum;\r\n                }\r\n \r\n                // If burst time is smaller than or equal to\r\n                // quantum. Last cycle for this process\r\n                else\r\n                {\r\n                    // Increase the value of t i.e. shows\r\n                    // how much time a process has been processed\r\n                    t = t + rem_bt[i];\r\n \r\n                    // Waiting time is current time minus time\r\n                    // used by this process\r\n                    wt[i] = t - bt[i];\r\n \r\n                    // As the process gets fully executed\r\n                    // make its remaining burst time = 0\r\n                    rem_bt[i] = 0;\r\n                }\r\n            }\r\n        }\r\n \r\n        // If all processes are done\r\n        if (done == true)\r\n          break;\r\n    }\r\n}\r\n \r\n// Function to calculate turn around time\r\nvoid findTurnAroundTime(int processes[], int n,\r\n                        int bt[], int wt[], int tat[])\r\n{\r\n    // calculating turnaround time by adding\r\n    // bt[i] + wt[i]\r\n    for (int i = 0; i < n ; i++)\r\n        tat[i] = bt[i] + wt[i];\r\n}\r\n \r\n// Function to calculate average time\r\nvoid findavgTime(int processes[], int n, int bt[],\r\n                                     int quantum)\r\n{\r\n    int wt[n], tat[n], total_wt = 0, total_tat = 0;\r\n \r\n    // Function to find waiting time of all processes\r\n    findWaitingTime(processes, n, bt, wt, quantum);\r\n \r\n    // Function to find turn around time for all processes\r\n    findTurnAroundTime(processes, n, bt, wt, tat);\r\n \r\n    // Display processes along with all details\r\n    cout << \"Processes \"<< \" Burst time \"\r\n         << \" Waiting time \" << \" Turn around time\\n\";\r\n \r\n    // Calculate total waiting time and total turn\r\n    // around time\r\n    for (int i=0; i<n; i++)\r\n    {\r\n        total_wt = total_wt + wt[i];\r\n        total_tat = total_tat + tat[i];\r\n        cout << \" \" << i+1 << \"\\t\\t\" << bt[i] <<\"\\t \"\r\n             << wt[i] <<\"\\t\\t \" << tat[i] <<endl;\r\n    }\r\n \r\n    cout << \"Average waiting time = \"\r\n         << (float)total_wt / (float)n;\r\n    cout << \"\\nAverage turn around time = \"\r\n         << (float)total_tat / (float)n;\r\n}\r\n \r\n// Driver code\r\nint main()\r\n{\r\n    // process id's\r\n    int processes[] = { 1, 2, 3};\r\n    int n = sizeof processes / sizeof processes[0];\r\n \r\n    // Burst time of all processes\r\n    int burst_time[] = {10, 5, 8};\r\n \r\n    // Time quantum\r\n    int quantum = 2;\r\n    findavgTime(processes, n, burst_time, quantum);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "os/scheduling/os_sjf.cpp",
    "content": "// C++ program to implement Shortest Job first\r\n#include<bits/stdc++.h>\r\nusing namespace std;\r\n \r\nstruct Process\r\n{\r\n   int pid; // Process ID\r\n   int bt;  // Burst Time\r\n};\r\n \r\n// This function is used for sorting all\r\n// processes in increasing order of burst\r\n// time\r\nbool comparison(Process a, Process b)\r\n{\r\n     return (a.bt < b.bt);\r\n}\r\n \r\n// Function to find the waiting time for all\r\n// processes\r\nvoid findWaitingTime(Process proc[], int n, int wt[])\r\n{\r\n    // waiting time for first process is 0\r\n    wt[0] = 0;\r\n \r\n    // calculating waiting time\r\n    for (int i = 1; i < n ; i++ )\r\n        wt[i] = proc[i-1].bt + wt[i-1] ;\r\n}\r\n \r\n// Function to calculate turn around time\r\nvoid findTurnAroundTime(Process proc[], int n,\r\n                        int wt[], int tat[])\r\n{\r\n    // calculating turnaround time by adding\r\n    // bt[i] + wt[i]\r\n    for (int i = 0; i < n ; i++)\r\n        tat[i] = proc[i].bt + wt[i];\r\n}\r\n \r\n//Function to calculate average time\r\nvoid findavgTime(Process proc[], int n)\r\n{\r\n    int wt[n], tat[n], total_wt = 0, total_tat = 0;\r\n \r\n    // Function to find waiting time of all processes\r\n    findWaitingTime(proc, n, wt);\r\n \r\n    // Function to find turn around time for all processes\r\n    findTurnAroundTime(proc, n, wt, tat);\r\n \r\n    // Display processes along with all details\r\n    cout << \"\\nProcesses \"<< \" Burst time \"\r\n         << \" Waiting time \" << \" Turn around time\\n\";\r\n \r\n    // Calculate total waiting time and total turn\r\n    // around time\r\n    for (int i = 0; i < n; i++)\r\n    {\r\n        total_wt = total_wt + wt[i];\r\n        total_tat = total_tat + tat[i];\r\n        cout << \" \" << proc[i].pid << \"\\t\\t\"\r\n             << proc[i].bt << \"\\t \" << wt[i]\r\n             << \"\\t\\t \" << tat[i] <<endl;\r\n    }\r\n \r\n    cout << \"Average waiting time = \"\r\n         << (float)total_wt / (float)n;\r\n    cout << \"\\nAverage turn around time = \"\r\n         << (float)total_tat / (float)n;\r\n}\r\n \r\n// Driver code\r\nint main()\r\n{\r\n    Process proc[] = {{1, 6}, {2, 8}, {3, 7}, {4, 3}};\r\n    int n = sizeof proc / sizeof proc[0];\r\n \r\n    // Sorting processes by burst time.\r\n    sort(proc, proc + n, comparison);\r\n \r\n    cout << \"Order in which process gets executed\\n\";\r\n    for (int i = 0 ; i < n; i++)\r\n        cout << proc[i].pid <<\" \";\r\n \r\n    findavgTime(proc, n);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "os/scheduling/os_srtf.cpp",
    "content": "// C++ program to implement Shortest Remaining\r\n// Time First\r\n#include <bits/stdc++.h>\r\nusing namespace std;\r\n \r\nstruct Process {\r\n    int pid; // Process ID\r\n    int bt; // Burst Time\r\n    int art; // Arrival Time\r\n};\r\n \r\n// Function to find the waiting time for all\r\n// processes\r\nvoid findWaitingTime(Process proc[], int n,\r\n                                int wt[])\r\n{\r\n    int rt[n];\r\n \r\n    // Copy the burst time into rt[]\r\n    for (int i = 0; i < n; i++)\r\n        rt[i] = proc[i].bt;\r\n \r\n    int complete = 0, t = 0, minm = INT_MAX;\r\n    int shortest = 0, finish_time;\r\n    bool check = false;\r\n \r\n    // Process until all processes gets\r\n    // completed\r\n    while (complete != n) {\r\n \r\n        // Find process with minimum\r\n        // remaining time among the\r\n        // processes that arrives till the\r\n        // current time`\r\n        for (int j = 0; j < n; j++) {\r\n            if ((proc[j].art <= t) &&\r\n            (rt[j] < minm) && rt[j] > 0) {\r\n                minm = rt[j];\r\n                shortest = j;\r\n                check = true;\r\n            }\r\n        }\r\n \r\n        if (check == false) {\r\n            t++;\r\n            continue;\r\n        }\r\n \r\n        // Reduce remaining time by one\r\n        rt[shortest]--;\r\n \r\n        // Update minimum\r\n        minm = rt[shortest];\r\n        if (minm == 0)\r\n            minm = INT_MAX;\r\n \r\n        // If a process gets completely\r\n        // executed\r\n        if (rt[shortest] == 0) {\r\n \r\n            // Increment complete\r\n            complete++;\r\n \r\n            // Find finish time of current\r\n            // process\r\n            finish_time = t + 1;\r\n \r\n            // Calculate waiting time\r\n            wt[shortest] = finish_time -\r\n                        proc[shortest].bt -\r\n                        proc[shortest].art;\r\n \r\n            if (wt[shortest] < 0)\r\n                wt[shortest] = 0;\r\n        }\r\n        // Increment time\r\n        t++;\r\n    }\r\n}\r\n \r\n// Function to calculate turn around time\r\nvoid findTurnAroundTime(Process proc[], int n,\r\n                        int wt[], int tat[])\r\n{\r\n    // calculating turnaround time by adding\r\n    // bt[i] + wt[i]\r\n    for (int i = 0; i < n; i++)\r\n        tat[i] = proc[i].bt + wt[i];\r\n}\r\n \r\n// Function to calculate average time\r\nvoid findavgTime(Process proc[], int n)\r\n{\r\n    int wt[n], tat[n], total_wt = 0,\r\n                    total_tat = 0;\r\n \r\n    // Function to find waiting time of all\r\n    // processes\r\n    findWaitingTime(proc, n, wt);\r\n \r\n    // Function to find turn around time for\r\n    // all processes\r\n    findTurnAroundTime(proc, n, wt, tat);\r\n \r\n    // Display processes along with all\r\n    // details\r\n    cout << \"Processes \"\r\n        << \" Burst time \"\r\n        << \" Waiting time \"\r\n        << \" Turn around time\\n\";\r\n \r\n    // Calculate total waiting time and\r\n    // total turnaround time\r\n    for (int i = 0; i < n; i++) {\r\n        total_wt = total_wt + wt[i];\r\n        total_tat = total_tat + tat[i];\r\n        cout << \" \" << proc[i].pid << \"\\t\\t\"\r\n            << proc[i].bt << \"\\t\\t \" << wt[i]\r\n            << \"\\t\\t \" << tat[i] << endl;\r\n    }\r\n \r\n    cout << \"\\nAverage waiting time = \"\r\n        << (float)total_wt / (float)n;\r\n    cout << \"\\nAverage turn around time = \"\r\n        << (float)total_tat / (float)n;\r\n}\r\n \r\n// Driver code\r\nint main()\r\n{\r\n    Process proc[] = { { 1, 6, 1 }, { 2, 8, 1 },\r\n                    { 3, 7, 2 }, { 4, 3, 3 } };\r\n    int n = sizeof(proc) / sizeof(proc[0]);\r\n \r\n    findavgTime(proc, n);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "os/scheduling/readme.txt",
    "content": "Various Scheduling algorithms used in Operating System\n\nFirst Come First Serve\nShortest Job first\nShortest Remaining Time First\nPriority Scheduling\nRound Robin Scheduling\n\n"
  },
  {
    "path": "shellsort.c",
    "content": "#include <stdio.h>\n\nvoid shellsort(int arr[], int num)\n\n{\n    int i, j, k, tmp;\n    for (i = num / 2; i > 0; i = i / 2)  \n    {\n\n       // Do a gapped insertion sort for this gap size.\n        // The first gap elements a[0..i-1] are already in \n        //gapped order keep adding one more element until the\n        //entire array is gap sorted.\n        for (j = i; j < num; j++)\n        {\n            for(k = j - i; k >= 0; k = k - i)\n            {\n                if (arr[k+i] >= arr[k])\n                    break;\n                else\n                {\n                    tmp = arr[k];\n                    arr[k] = arr[k+i];\n                    arr[k+i] = tmp;\n                }\n            }\n        }\n    }\n}\n\nint main()\n\n{\n    int arr[30];\n    int k,  num;\n    printf(\"Enter total no. of elements : \");\n    scanf(\"%d\", &num);\n    printf(\"\\nEnter %d numbers: \", num);\n    for (k =  0 ; k < num; k++)\n    {\n        scanf(\"%d\", &arr[k]);\n    }\n    shellsort(arr, num);\n    printf(\"\\n Sorted array is: \");\n    for (k = 0; k < num; k++)\n        printf(\"%d \", arr[k]);\n    return 0;\n\n}"
  },
  {
    "path": "sieve_of_eratoshthenes.cpp",
    "content": "//isPrime denotes the array which will be used to mark prime numbers.\n//N is the limit, upto which we need to find prime numbers.\n\nbool isPrime[N+1];\n\nvoid sieve() {\n    int i, j;\n\n    memset(isPrime, true, sizeof(isPrime))\n\n    for(i = 2; i*i <= N; i++) {\n        if(isPrime[i] == true) {\n            for(j = i*i; j <= N; j = j+i)\n                isPrime[j] = false;\n        }\n    }\n}\n\n"
  },
  {
    "path": "square_root_decomposition",
    "content": "// C++ program to demonstrate working of Square Root\n// Decomposition.\n//This is a programme that will help to reduce time complexity \n//for big arrays\n#include \"iostream\"\n#include \"math.h\"\nusing namespace std;\n \n#define MAXN 10000\n#define SQRSIZE  100\n \nint arr[MAXN];               // original array\nint block[SQRSIZE];          // decomposed array\nint blk_sz;                      // block size\n \n// Time Complexity : O(1)\nvoid update(int idx, int val)\n{\n    int blockNumber = idx / blk_sz;\n    block[blockNumber] += val - arr[idx];\n    arr[idx] = val;\n}\n \n// Time Complexity : O(sqrt(n))\nint query(int l, int r)\n{\n    int sum = 0;\n    while (l<r and l%blk_sz!=0 and l!=0)\n    {\n        // traversing first block in range\n        sum += arr[l];\n        l++;\n    }\n    while (l+blk_sz <= r)\n    {\n        // traversing completely overlapped blocks in range\n        sum += block[l/blk_sz];\n        l += blk_sz;\n    }\n    while (l<=r)\n    {\n        // traversing last block in range\n        sum += arr[l];\n        l++;\n    }\n    return sum;\n}\n \n// Fills values in input[]\nvoid preprocess(int input[], int n)\n{\n    // initiating block pointer\n    int blk_idx = -1;\n \n    // calculating size of block\n    blk_sz = sqrt(n);\n \n    // building the decomposed array\n    for (int i=0; i<n; i++)\n    {\n        arr[i] = input[i];\n        if (i%blk_sz == 0)\n        {\n            // entering next block\n            // incementing block pointer\n            blk_idx++;\n        }\n        block[blk_idx] += arr[i];\n    }\n}\n \n// Driver code\nint main()\n{\n    // We have used separate array for input because\n    // the purpose of this code is to explain SQRT\n    // decomposition in competitive programming where\n    // we have multiple inputs.\n    int input[] = {1, 5, 2, 4, 6, 1, 3, 5, 7, 10};\n    int n = sizeof(input)/sizeof(input[0]);\n \n    preprocess(input, n);\n \n    cout << \"query(3,8) : \" << query(3, 8) << endl;\n    cout << \"query(1,6) : \" << query(1, 6) << endl;\n    update(8, 0);\n    cout << \"query(8,8) : \" << query(8, 8) << endl;\n    return 0;\n}\n"
  },
  {
    "path": "travelling_salesman_problem",
    "content": "#include<stdio.h>\n \nint matrix[25][25], visited_cities[10], limit, cost = 0;\n \nint tsp(int c)\n{\n      int count, nearest_city = 999;\n      int minimum = 999, temp;\n      for(count = 0; count < limit; count++)\n      {\n            if((matrix[c][count] != 0) && (visited_cities[count] == 0))\n            {\n                  if(matrix[c][count] < minimum)\n                  {\n                        minimum = matrix[count][0] + matrix[c][count];\n                  }\n                  temp = matrix[c][count];\n                  nearest_city = count;\n            }\n      }\n      if(minimum != 999)\n      {\n            cost = cost + temp;\n      }\n      return nearest_city;\n}\n \nvoid minimum_cost(int city)\n{\n      int nearest_city;\n      visited_cities[city] = 1;\n      printf(\"%d \", city + 1);\n      nearest_city = tsp(city);\n      if(nearest_city == 999)\n      {\n            nearest_city = 0;\n            printf(\"%d\", nearest_city + 1);\n            cost = cost + matrix[city][nearest_city];\n            return;\n      }\n      minimum_cost(nearest_city);\n}\n \nint main()\n{ \n      int i, j;\n      printf(\"Enter Total Number of Cities:\\t\");\n      scanf(\"%d\", &limit);\n      printf(\"\\nEnter Cost Matrix\\n\");\n      for(i = 0; i < limit; i++)\n      {\n            printf(\"\\nEnter %d Elements in Row[%d]\\n\", limit, i + 1);\n            for(j = 0; j < limit; j++)\n            {\n                  scanf(\"%d\", &matrix[i][j]);\n            }\n            visited_cities[i] = 0;\n      }\n      printf(\"\\nEntered Cost Matrix\\n\");\n      for(i = 0; i < limit; i++)\n      {\n            printf(\"\\n\");\n            for(j = 0; j < limit; j++)\n            {\n                  printf(\"%d \", matrix[i][j]);\n            }\n      }\n      printf(\"\\n\\nPath:\\t\");\n      minimum_cost(0);\n      printf(\"\\n\\nMinimum Cost: \\t\");\n      printf(\"%d\\n\", cost);\n      return 0;\n}\n"
  }
]