[
  {
    "path": ".gitignore",
    "content": "*.out\njavascript/node_modules\n.idea"
  },
  {
    "path": ".vscode/settings.json",
    "content": "{\n  \"files.associations\": {\n    \"vector\": \"cpp\"\n  }\n}"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing to this repo\n**Implementing new File/Directory Structure**\n* Try to keep things as modular as possible, the new file/directory structure should be: \n```\n/data_structures/structure/language/file\nex: /data_structures/char_stack/cpp/cstack.cpp\n/algorithms/algorithm/language/file\nex: /algorithms/bubble_sort/cpp/bubble_sort.cpp\n```\n\n## How To:\n\n1. `git clone https://github.com/bareinhard/Hacktoberfest-Data-Structure-and-Algorithms`\n2. `git checkout -b <Your-Branch-Name-Here>`\n3. Code your files in the proper directory based on the instructions above\n4. add all your files `git add your/directory/path/to/file/` (see new directory structure above)\n5. commit your file changes `git commit -m \"Whatever you did here, e.g. created linkedlist class in C++\"`\n6. push your changes `git push origin <Your-Branch-Name-Here>`\n7. Create a Pull Request to master\n\n### Alternate via Web\n\n1. Fork Repo on Web Page\n2. Make your changes on your forked repo\n3. Make Pull Request to master\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    {one line to give the program's name and a brief idea of what it does.}\n    Copyright (C) {year}  {name of author}\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    {project}  Copyright (C) {year}  {fullname}\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "# Hacktoberfest-Data-Structure-and-Algorithms\nA repository containing data structures and algorithms, regardless of language.\n\nNo longer active\n\n***Not Affiliated with Digital Ocean or Hacktoberfest***\n\n![Hacktoberfest](https://pbs.twimg.com/media/Dn4njsBXkAEQWZs.jpg)\n\n# CONTRIBUTING!\n\n# Contributing to this repo\n**Implementing new File/Directory Structure**\n* Try to keep things as modular as possible, the new file/directory structure should be:\n```\n/data_structures/structure/language/file\nex: /data_structures/char_stack/cpp/cstack.cpp\n/algorithms/algorithm/language/file\nex: /algorithms/bubble_sort/cpp/bubble_sort.cpp\n```\n\n\n\n## How To:\n\n1. Fork Repo on Web Page\n2. `git clone https://github.com/{your-username}/Hacktoberfest-Data-Structure-and-Algorithms`\n3. Code your files in the proper directory based on the instructions above\n4. add all your files `git add your/directory/path/to/file/` (see new directory structure above)\n5. commit your file changes `git commit -m \"Whatever you did here, e.g. created linkedlist class in C++\"`\n6. push your changes `git push`\n7. Create a Pull Request to master on Web Page\n\n### Alternate via Web\n\n1. Fork Repo on Web Page\n2. Make your changes on your forked repo\n3. Make Pull Request to master\n\n#### Credits\nLogo created with: http://logomakr.com\n"
  },
  {
    "path": "algorithms/EuclideanAlgorithm/c/euclid.c",
    "content": "#include<stdio.h>\n\nint gcd(int x, int y){\n\tif(x == 0)\n\t\treturn y;\n\treturn gcd(y % x, x);\n}\n\nvoid main(){\n\tint hcf, a, b;\n\tprintf(\"Enter the 2 numbers: \");\n\tscanf(\"%d%d\",&a, &b);\n\thcf = gcd(a, b);\n\tprintf(\"The HCF is: %d\\n\",hcf);\n}\n"
  },
  {
    "path": "algorithms/EuclideanAlgorithm/python/euclideanAlgorithm.py",
    "content": "def euclidean(a,b):#for natural numbers a,b\n  \n  #sanitize the inputs\n  a=int(a)\n  b=int(b)\n  \n  if(not(a and b)):#if either are 0\n    return(0)\n  \n  if(b>a):#to have it so a>=b\n    temp=a\n    a=b\n    b=temp\n  \n  while(1):\n    remainder=a%b\n    a=b\n    b=remainder\n    if(b==0):\n      return(a)\n"
  },
  {
    "path": "algorithms/Graph/connected_components_in_undirected_graph/python/ConnectedComponents.py",
    "content": "'''\nQuestion source -- LeetCode\nGiven n nodes labeled from 0 to n - 1 and a list of undirected edges\n(where each edge is a pair of nodes), write a function to find the number\nof connected components in an undirected graph.\n\n'''\n\ndef countComponents( n, edges):\n    \"\"\"\n    :type n: int\n    :type edges: List[List[int]]\n    :rtype: int\n    \"\"\"\n    # finds the path recursively\n    def find(data, i):\n        if i != data[i]:\n            data[i] = find(data, data[i]) \n        return data[i]\n\n    # creates the union find data structure\n    def union(data, i, j):\n        root_i, root_j = find(data, i), find(data, j)\n        if root_i != root_j:\n            data[root_i] = root_j\n\n    data = [i for i in range(n)]\n    \n    for i,j in edges:\n        union(data, i, j)\n    # set data structure to eliminate the possibilities of duplicates. \n    res = set()\n\n    # union-find the roots of the each nodes in the components. \n    for i in range(n):\n        res.add(find(data,i))\n\n    # the total length of the root nodes determine the total number of components. \n    return len(res)\n\n\nprint(countComponents(5, [[0, 1], [1, 2], [3, 4]]))\n\n"
  },
  {
    "path": "algorithms/a_search/cpp/a_star.cpp",
    "content": "// A C++ Program to implement A* Search Algorithm\n#include <bits/stdc++.h>\nusing namespace std;\n \n#define ROW 9\n#define COL 10\n \n// Creating a shortcut for int, int pair type\ntypedef pair<int, int> Pair;\n \n// Creating a shortcut for pair<int, pair<int, int>> type\ntypedef pair<double, pair<int, int>> pPair;\n \n// A structure to hold the neccesary parameters\nstruct cell\n{\n    // Row and Column index of its parent\n    // Note that 0 <= i <= ROW-1 & 0 <= j <= COL-1\n    int parent_i, parent_j;\n    // f = g + h\n    double f, g, h;\n};\n \n// A Utility Function to check whether given cell (row, col)\n// is a valid cell or not.\nbool isValid(int row, int col)\n{\n    // Returns true if row number and column number\n    // is in range\n    return (row >= 0) && (row < ROW) &&\n           (col >= 0) && (col < COL);\n}\n \n// A Utility Function to check whether the given cell is\n// blocked or not\nbool isUnBlocked(int grid[][COL], int row, int col)\n{\n    // Returns true if the cell is not blocked else false\n    if (grid[row][col] == 1)\n        return (true);\n    else\n        return (false);\n}\n \n// A Utility Function to check whether destination cell has\n// been reached or not\nbool isDestination(int row, int col, Pair dest)\n{\n    if (row == dest.first && col == dest.second)\n        return (true);\n    else\n        return (false);\n}\n \n// A Utility Function to calculate the 'h' heuristics.\ndouble calculateHValue(int row, int col, Pair dest)\n{\n    // Return using the distance formula\n    return ((double)sqrt ((row-dest.first)*(row-dest.first)\n                          + (col-dest.second)*(col-dest.second)));\n}\n \n// A Utility Function to trace the path from the source\n// to destination\nvoid tracePath(cell cellDetails[][COL], Pair dest)\n{\n    printf (\"\\nThe Path is \");\n    int row = dest.first;\n    int col = dest.second;\n \n    stack<Pair> Path;\n \n    while (!(cellDetails[row][col].parent_i == row\n             && cellDetails[row][col].parent_j == col ))\n    {\n        Path.push (make_pair (row, col));\n        int temp_row = cellDetails[row][col].parent_i;\n        int temp_col = cellDetails[row][col].parent_j;\n        row = temp_row;\n        col = temp_col;\n    }\n \n    Path.push (make_pair (row, col));\n    while (!Path.empty())\n    {\n        pair<int,int> p = Path.top();\n        Path.pop();\n        printf(\"-> (%d,%d) \",p.first,p.second);\n    }\n \n    return;\n}\n \n// A Function to find the shortest path between\n// a given source cell to a destination cell according\n// to A* Search Algorithm\nvoid aStarSearch(int grid[][COL], Pair src, Pair dest)\n{\n    // If the source is out of range\n    if (isValid (src.first, src.second) == false)\n    {\n        printf (\"Source is invalid\\n\");\n        return;\n    }\n \n    // If the destination is out of range\n    if (isValid (dest.first, dest.second) == false)\n    {\n        printf (\"Destination is invalid\\n\");\n        return;\n    }\n \n    // Either the source or the destination is blocked\n    if (isUnBlocked(grid, src.first, src.second) == false ||\n            isUnBlocked(grid, dest.first, dest.second) == false)\n    {\n        printf (\"Source or the destination is blocked\\n\");\n        return;\n    }\n \n    // If the destination cell is the same as source cell\n    if (isDestination(src.first, src.second, dest) == true)\n    {\n        printf (\"We are already at the destination\\n\");\n        return;\n    }\n \n    // Create a closed list and initialise it to false which means\n    // that no cell has been included yet\n    // This closed list is implemented as a boolean 2D array\n    bool closedList[ROW][COL];\n    memset(closedList, false, sizeof (closedList));\n \n    // Declare a 2D array of structure to hold the details\n    //of that cell\n    cell cellDetails[ROW][COL];\n \n    int i, j;\n \n    for (i=0; i<ROW; i++)\n    {\n        for (j=0; j<COL; j++)\n        {\n            cellDetails[i][j].f = FLT_MAX;\n            cellDetails[i][j].g = FLT_MAX;\n            cellDetails[i][j].h = FLT_MAX;\n            cellDetails[i][j].parent_i = -1;\n            cellDetails[i][j].parent_j = -1;\n        }\n    }\n \n    // Initialising the parameters of the starting node\n    i = src.first, j = src.second;\n    cellDetails[i][j].f = 0.0;\n    cellDetails[i][j].g = 0.0;\n    cellDetails[i][j].h = 0.0;\n    cellDetails[i][j].parent_i = i;\n    cellDetails[i][j].parent_j = j;\n \n    /*\n     Create an open list having information as-\n     <f, <i, j>>\n     where f = g + h,\n     and i, j are the row and column index of that cell\n     Note that 0 <= i <= ROW-1 & 0 <= j <= COL-1\n     This open list is implenented as a set of pair of pair.*/\n    set<pPair> openList;\n \n    // Put the starting cell on the open list and set its\n    // 'f' as 0\n    openList.insert(make_pair (0.0, make_pair (i, j)));\n \n    // We set this boolean value as false as initially\n    // the destination is not reached.\n    bool foundDest = false;\n \n    while (!openList.empty())\n    {\n        pPair p = *openList.begin();\n \n        // Remove this vertex from the open list\n        openList.erase(openList.begin());\n \n        // Add this vertex to the open list\n        i = p.second.first;\n        j = p.second.second;\n        closedList[i][j] = true;\n      \n       /*\n        Generating all the 8 successor of this cell\n \n            N.W   N   N.E\n              \\   |   /\n               \\  |  /\n            W----Cell----E\n                 / | \\\n               /   |  \\\n            S.W    S   S.E\n \n        Cell-->Popped Cell (i, j)\n        N -->  North       (i-1, j)\n        S -->  South       (i+1, j)\n        E -->  East        (i, j+1)\n        W -->  West           (i, j-1)\n        N.E--> North-East  (i-1, j+1)\n        N.W--> North-West  (i-1, j-1)\n        S.E--> South-East  (i+1, j+1)\n        S.W--> South-West  (i+1, j-1)*/\n \n        // To store the 'g', 'h' and 'f' of the 8 successors\n        double gNew, hNew, fNew;\n \n        //----------- 1st Successor (North) ------------\n \n        // Only process this cell if this is a valid one\n        if (isValid(i-1, j) == true)\n        {\n            // If the destination cell is the same as the\n            // current successor\n            if (isDestination(i-1, j, dest) == true)\n            {\n                // Set the Parent of the destination cell\n                cellDetails[i-1][j].parent_i = i;\n                cellDetails[i-1][j].parent_j = j;\n                printf (\"The destination cell is found\\n\");\n                tracePath (cellDetails, dest);\n                foundDest = true;\n                return;\n            }\n            // If the successor is already on the closed\n            // list or if it is blocked, then ignore it.\n            // Else do the following\n            else if (closedList[i-1][j] == false &&\n                     isUnBlocked(grid, i-1, j) == true)\n            {\n                gNew = cellDetails[i][j].g + 1.0;\n                hNew = calculateHValue (i-1, j, dest);\n                fNew = gNew + hNew;\n \n                // If it isn’t on the open list, add it to\n                // the open list. Make the current square\n                // the parent of this square. Record the\n                // f, g, and h costs of the square cell\n                //                OR\n                // If it is on the open list already, check\n                // to see if this path to that square is better,\n                // using 'f' cost as the measure.\n                if (cellDetails[i-1][j].f == FLT_MAX ||\n                        cellDetails[i-1][j].f > fNew)\n                {\n                    openList.insert( make_pair(fNew,\n                                               make_pair(i-1, j)));\n \n                    // Update the details of this cell\n                    cellDetails[i-1][j].f = fNew;\n                    cellDetails[i-1][j].g = gNew;\n                    cellDetails[i-1][j].h = hNew;\n                    cellDetails[i-1][j].parent_i = i;\n                    cellDetails[i-1][j].parent_j = j;\n                }\n            }\n        }\n \n        //----------- 2nd Successor (South) ------------\n \n        // Only process this cell if this is a valid one\n        if (isValid(i+1, j) == true)\n        {\n            // If the destination cell is the same as the\n            // current successor\n            if (isDestination(i+1, j, dest) == true)\n            {\n                // Set the Parent of the destination cell\n                cellDetails[i+1][j].parent_i = i;\n                cellDetails[i+1][j].parent_j = j;\n                printf(\"The destination cell is found\\n\");\n                tracePath(cellDetails, dest);\n                foundDest = true;\n                return;\n            }\n            // If the successor is already on the closed\n            // list or if it is blocked, then ignore it.\n            // Else do the following\n            else if (closedList[i+1][j] == false &&\n                     isUnBlocked(grid, i+1, j) == true)\n            {\n                gNew = cellDetails[i][j].g + 1.0;\n                hNew = calculateHValue(i+1, j, dest);\n                fNew = gNew + hNew;\n \n                // If it isn’t on the open list, add it to\n                // the open list. Make the current square\n                // the parent of this square. Record the\n                // f, g, and h costs of the square cell\n                //                OR\n                // If it is on the open list already, check\n                // to see if this path to that square is better,\n                // using 'f' cost as the measure.\n                if (cellDetails[i+1][j].f == FLT_MAX ||\n                        cellDetails[i+1][j].f > fNew)\n                {\n                    openList.insert( make_pair (fNew, make_pair (i+1, j)));\n                    // Update the details of this cell\n                    cellDetails[i+1][j].f = fNew;\n                    cellDetails[i+1][j].g = gNew;\n                    cellDetails[i+1][j].h = hNew;\n                    cellDetails[i+1][j].parent_i = i;\n                    cellDetails[i+1][j].parent_j = j;\n                }\n            }\n        }\n \n        //----------- 3rd Successor (East) ------------\n \n        // Only process this cell if this is a valid one\n        if (isValid (i, j+1) == true)\n        {\n            // If the destination cell is the same as the\n            // current successor\n            if (isDestination(i, j+1, dest) == true)\n            {\n                // Set the Parent of the destination cell\n                cellDetails[i][j+1].parent_i = i;\n                cellDetails[i][j+1].parent_j = j;\n                printf(\"The destination cell is found\\n\");\n                tracePath(cellDetails, dest);\n                foundDest = true;\n                return;\n            }\n \n            // If the successor is already on the closed\n            // list or if it is blocked, then ignore it.\n            // Else do the following\n            else if (closedList[i][j+1] == false &&\n                     isUnBlocked (grid, i, j+1) == true)\n            {\n                gNew = cellDetails[i][j].g + 1.0;\n                hNew = calculateHValue (i, j+1, dest);\n                fNew = gNew + hNew;\n \n                // If it isn’t on the open list, add it to\n                // the open list. Make the current square\n                // the parent of this square. Record the\n                // f, g, and h costs of the square cell\n                //                OR\n                // If it is on the open list already, check\n                // to see if this path to that square is better,\n                // using 'f' cost as the measure.\n                if (cellDetails[i][j+1].f == FLT_MAX ||\n                        cellDetails[i][j+1].f > fNew)\n                {\n                    openList.insert( make_pair(fNew,\n                                        make_pair (i, j+1)));\n \n                    // Update the details of this cell\n                    cellDetails[i][j+1].f = fNew;\n                    cellDetails[i][j+1].g = gNew;\n                    cellDetails[i][j+1].h = hNew;\n                    cellDetails[i][j+1].parent_i = i;\n                    cellDetails[i][j+1].parent_j = j;\n                }\n            }\n        }\n \n        //----------- 4th Successor (West) ------------\n \n        // Only process this cell if this is a valid one\n        if (isValid(i, j-1) == true)\n        {\n            // If the destination cell is the same as the\n            // current successor\n            if (isDestination(i, j-1, dest) == true)\n            {\n                // Set the Parent of the destination cell\n                cellDetails[i][j-1].parent_i = i;\n                cellDetails[i][j-1].parent_j = j;\n                printf(\"The destination cell is found\\n\");\n                tracePath(cellDetails, dest);\n                foundDest = true;\n                return;\n            }\n \n            // If the successor is already on the closed\n            // list or if it is blocked, then ignore it.\n            // Else do the following\n            else if (closedList[i][j-1] == false &&\n                     isUnBlocked(grid, i, j-1) == true)\n            {\n                gNew = cellDetails[i][j].g + 1.0;\n                hNew = calculateHValue(i, j-1, dest);\n                fNew = gNew + hNew;\n \n                // If it isn’t on the open list, add it to\n                // the open list. Make the current square\n                // the parent of this square. Record the\n                // f, g, and h costs of the square cell\n                //                OR\n                // If it is on the open list already, check\n                // to see if this path to that square is better,\n                // using 'f' cost as the measure.\n                if (cellDetails[i][j-1].f == FLT_MAX ||\n                        cellDetails[i][j-1].f > fNew)\n                {\n                    openList.insert( make_pair (fNew,\n                                          make_pair (i, j-1)));\n \n                    // Update the details of this cell\n                    cellDetails[i][j-1].f = fNew;\n                    cellDetails[i][j-1].g = gNew;\n                    cellDetails[i][j-1].h = hNew;\n                    cellDetails[i][j-1].parent_i = i;\n                    cellDetails[i][j-1].parent_j = j;\n                }\n            }\n        }\n \n        //----------- 5th Successor (North-East) ------------\n \n        // Only process this cell if this is a valid one\n        if (isValid(i-1, j+1) == true)\n        {\n            // If the destination cell is the same as the\n            // current successor\n            if (isDestination(i-1, j+1, dest) == true)\n            {\n                // Set the Parent of the destination cell\n                cellDetails[i-1][j+1].parent_i = i;\n                cellDetails[i-1][j+1].parent_j = j;\n                printf (\"The destination cell is found\\n\");\n                tracePath (cellDetails, dest);\n                foundDest = true;\n                return;\n            }\n \n            // If the successor is already on the closed\n            // list or if it is blocked, then ignore it.\n            // Else do the following\n            else if (closedList[i-1][j+1] == false &&\n                     isUnBlocked(grid, i-1, j+1) == true)\n            {\n                gNew = cellDetails[i][j].g + 1.414;\n                hNew = calculateHValue(i-1, j+1, dest);\n                fNew = gNew + hNew;\n \n                // If it isn’t on the open list, add it to\n                // the open list. Make the current square\n                // the parent of this square. Record the\n                // f, g, and h costs of the square cell\n                //                OR\n                // If it is on the open list already, check\n                // to see if this path to that square is better,\n                // using 'f' cost as the measure.\n                if (cellDetails[i-1][j+1].f == FLT_MAX ||\n                        cellDetails[i-1][j+1].f > fNew)\n                {\n                    openList.insert( make_pair (fNew, \n                                    make_pair(i-1, j+1)));\n \n                    // Update the details of this cell\n                    cellDetails[i-1][j+1].f = fNew;\n                    cellDetails[i-1][j+1].g = gNew;\n                    cellDetails[i-1][j+1].h = hNew;\n                    cellDetails[i-1][j+1].parent_i = i;\n                    cellDetails[i-1][j+1].parent_j = j;\n                }\n            }\n        }\n \n        //----------- 6th Successor (North-West) ------------\n \n        // Only process this cell if this is a valid one\n        if (isValid (i-1, j-1) == true)\n        {\n            // If the destination cell is the same as the\n            // current successor\n            if (isDestination (i-1, j-1, dest) == true)\n            {\n                // Set the Parent of the destination cell\n                cellDetails[i-1][j-1].parent_i = i;\n                cellDetails[i-1][j-1].parent_j = j;\n                printf (\"The destination cell is found\\n\");\n                tracePath (cellDetails, dest);\n                foundDest = true;\n                return;\n            }\n \n            // If the successor is already on the closed\n            // list or if it is blocked, then ignore it.\n            // Else do the following\n            else if (closedList[i-1][j-1] == false &&\n                     isUnBlocked(grid, i-1, j-1) == true)\n            {\n                gNew = cellDetails[i][j].g + 1.414;\n                hNew = calculateHValue(i-1, j-1, dest);\n                fNew = gNew + hNew;\n \n                // If it isn’t on the open list, add it to\n                // the open list. Make the current square\n                // the parent of this square. Record the\n                // f, g, and h costs of the square cell\n                //                OR\n                // If it is on the open list already, check\n                // to see if this path to that square is better,\n                // using 'f' cost as the measure.\n                if (cellDetails[i-1][j-1].f == FLT_MAX ||\n                        cellDetails[i-1][j-1].f > fNew)\n                {\n                    openList.insert( make_pair (fNew, make_pair (i-1, j-1)));\n                    // Update the details of this cell\n                    cellDetails[i-1][j-1].f = fNew;\n                    cellDetails[i-1][j-1].g = gNew;\n                    cellDetails[i-1][j-1].h = hNew;\n                    cellDetails[i-1][j-1].parent_i = i;\n                    cellDetails[i-1][j-1].parent_j = j;\n                }\n            }\n        }\n \n        //----------- 7th Successor (South-East) ------------\n \n        // Only process this cell if this is a valid one\n        if (isValid(i+1, j+1) == true)\n        {\n            // If the destination cell is the same as the\n            // current successor\n            if (isDestination(i+1, j+1, dest) == true)\n            {\n                // Set the Parent of the destination cell\n                cellDetails[i+1][j+1].parent_i = i;\n                cellDetails[i+1][j+1].parent_j = j;\n                printf (\"The destination cell is found\\n\");\n                tracePath (cellDetails, dest);\n                foundDest = true;\n                return;\n            }\n \n            // If the successor is already on the closed\n            // list or if it is blocked, then ignore it.\n            // Else do the following\n            else if (closedList[i+1][j+1] == false &&\n                     isUnBlocked(grid, i+1, j+1) == true)\n            {\n                gNew = cellDetails[i][j].g + 1.414;\n                hNew = calculateHValue(i+1, j+1, dest);\n                fNew = gNew + hNew;\n \n                // If it isn’t on the open list, add it to\n                // the open list. Make the current square\n                // the parent of this square. Record the\n                // f, g, and h costs of the square cell\n                //                OR\n                // If it is on the open list already, check\n                // to see if this path to that square is better,\n                // using 'f' cost as the measure.\n                if (cellDetails[i+1][j+1].f == FLT_MAX ||\n                        cellDetails[i+1][j+1].f > fNew)\n                {\n                    openList.insert(make_pair(fNew, \n                                        make_pair (i+1, j+1)));\n \n                    // Update the details of this cell\n                    cellDetails[i+1][j+1].f = fNew;\n                    cellDetails[i+1][j+1].g = gNew;\n                    cellDetails[i+1][j+1].h = hNew;\n                    cellDetails[i+1][j+1].parent_i = i;\n                    cellDetails[i+1][j+1].parent_j = j;\n                }\n            }\n        }\n \n        //----------- 8th Successor (South-West) ------------\n \n        // Only process this cell if this is a valid one\n        if (isValid (i+1, j-1) == true)\n        {\n            // If the destination cell is the same as the\n            // current successor\n            if (isDestination(i+1, j-1, dest) == true)\n            {\n                // Set the Parent of the destination cell\n                cellDetails[i+1][j-1].parent_i = i;\n                cellDetails[i+1][j-1].parent_j = j;\n                printf(\"The destination cell is found\\n\");\n                tracePath(cellDetails, dest);\n                foundDest = true;\n                return;\n            }\n \n            // If the successor is already on the closed\n            // list or if it is blocked, then ignore it.\n            // Else do the following\n            else if (closedList[i+1][j-1] == false &&\n                     isUnBlocked(grid, i+1, j-1) == true)\n            {\n                gNew = cellDetails[i][j].g + 1.414;\n                hNew = calculateHValue(i+1, j-1, dest);\n                fNew = gNew + hNew;\n \n                // If it isn’t on the open list, add it to\n                // the open list. Make the current square\n                // the parent of this square. Record the\n                // f, g, and h costs of the square cell\n                //                OR\n                // If it is on the open list already, check\n                // to see if this path to that square is better,\n                // using 'f' cost as the measure.\n                if (cellDetails[i+1][j-1].f == FLT_MAX ||\n                        cellDetails[i+1][j-1].f > fNew)\n                {\n                    openList.insert(make_pair(fNew, \n                                        make_pair(i+1, j-1)));\n \n                    // Update the details of this cell\n                    cellDetails[i+1][j-1].f = fNew;\n                    cellDetails[i+1][j-1].g = gNew;\n                    cellDetails[i+1][j-1].h = hNew;\n                    cellDetails[i+1][j-1].parent_i = i;\n                    cellDetails[i+1][j-1].parent_j = j;\n                }\n            }\n        }\n    }\n \n    // When the destination cell is not found and the open\n    // list is empty, then we conclude that we failed to\n    // reach the destiantion cell. This may happen when the\n    // there is no way to destination cell (due to blockages)\n    if (foundDest == false)\n        printf(\"Failed to find the Destination Cell\\n\");\n \n    return;\n}\n \n \n// Driver program to test above function\nint main()\n{\n    /* Description of the Grid-\n     1--> The cell is not blocked\n     0--> The cell is blocked    */\n    int grid[ROW][COL] =\n    {\n        { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },\n        { 1, 1, 1, 0, 1, 1, 1, 0, 1, 1 },\n        { 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 },\n        { 0, 0, 1, 0, 1, 0, 0, 0, 0, 1 },\n        { 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 },\n        { 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 },\n        { 1, 0, 0, 0, 0, 1, 0, 0, 0, 1 },\n        { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },\n        { 1, 1, 1, 0, 0, 0, 1, 0, 0, 1 }\n    };\n \n    // Source is the left-most bottom-most corner\n    Pair src = make_pair(8, 0);\n \n    // Destination is the left-most top-most corner\n    Pair dest = make_pair(0, 0);\n \n    aStarSearch(grid, src, dest);\n \n    return(0);\n}\n"
  },
  {
    "path": "algorithms/backtracking/c/n_queens_problem.c",
    "content": "/* C/C++ program to solve N Queen Problem using\n   backtracking */\n#define N 4\n#include<stdio.h>\n\n/* A utility function to print solution */\nvoid printSolution(int board[N][N])\n{\n    for (int i = 0; i < N; i++)\n    {\n        for (int j = 0; j < N; j++)\n            printf(\" %d \", board[i][j]);\n        printf(\"n\");\n    }\n}\n\n/* A utility function to check if a queen can\n   be placed on board[row][col]. Note that this\n   function is called when \"col\" queens are\n   already placed in columns from 0 to col -1.\n   So we need to check only left side for\n   attacking queens */\nbool isSafe(int board[N][N], int row, int col)\n{\n    int i, j;\n\n    /* Check this row on left side */\n    for (i = 0; i < col; i++)\n        if (board[row][i])\n            return false;\n\n    /* Check upper diagonal on left side */\n    for (i=row, j=col; i>=0 && j>=0; i--, j--)\n        if (board[i][j])\n            return false;\n\n    /* Check lower diagonal on left side */\n    for (i=row, j=col; j>=0 && i<N; i++, j--)\n        if (board[i][j])\n            return false;\n\n    return true;\n}\n\n/* A recursive utility function to solve N\n   Queen problem */\nbool solveNQUtil(int board[N][N], int col)\n{\n    /* base case: If all queens are placed\n      then return true */\n    if (col >= N)\n        return true;\n\n    /* Consider this column and try placing\n       this queen in all rows one by one */\n    for (int i = 0; i < N; i++)\n    {\n        /* Check if queen can be placed on\n          board[i][col] */\n        if ( isSafe(board, i, col) )\n        {\n            /* Place this queen in board[i][col] */\n            board[i][col] = 1;\n\n            /* recur to place rest of the queens */\n            if ( solveNQUtil(board, col + 1) )\n                return true;\n\n            /* If placing queen in board[i][col]\n               doesn't lead to a solution, then\n               remove queen from board[i][col] */\n            board[i][col] = 0; // BACKTRACK\n        }\n    }\n\n     /* If queen can not be place in any row in\n        this colum col  then return false */\n    return false;\n}\n\n/* This function solves the N Queen problem using\n   Backtracking. It mainly uses solveNQUtil() to\n   solve the problem. It returns false if queens\n   cannot be placed, otherwise return true and\n   prints placement of queens in the form of 1s.\n   Please note that there may be more than one\n   solutions, this function prints one  of the\n   feasible solutions.*/\nbool solveNQ()\n{\n    int board[N][N] = { {0, 0, 0, 0},\n        {0, 0, 0, 0},\n        {0, 0, 0, 0},\n        {0, 0, 0, 0}\n    };\n\n    if ( solveNQUtil(board, 0) == false )\n    {\n      printf(\"Solution does not exist\");\n      return false;\n    }\n\n    printSolution(board);\n    return true;\n}\n\n// driver program to test above function\nint main()\n{\n    solveNQ();\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/backtracking/c/rat_in_a_maze_problem.c",
    "content": "/* C/C++ program to solve Rat in a Maze problem using\n   backtracking */\n#include<stdio.h>\n\n// Maze size\n#define N 4\n\nbool solveMazeUtil(int maze[N][N], int x, int y, int sol[N][N]);\n\n/* A utility function to print solution matrix sol[N][N] */\nvoid printSolution(int sol[N][N])\n{\n    for (int i = 0; i < N; i++)\n    {\n        for (int j = 0; j < N; j++)\n            printf(\" %d \", sol[i][j]);\n        printf(\"\\n\");\n    }\n}\n\n/* A utility function to check if x,y is valid index for N*N maze */\nbool isSafe(int maze[N][N], int x, int y)\n{\n    // if (x,y outside maze) return false\n    if(x >= 0 && x < N && y >= 0 && y < N && maze[x][y] == 1)\n        return true;\n\n    return false;\n}\n\n/* This function solves the Maze problem using Backtracking.  It mainly\n   uses solveMazeUtil() to solve the problem. It returns false if no\n   path is possible, otherwise return true and prints the path in the\n   form of 1s. Please note that there may be more than one solutions,\n   this function prints one of the feasible solutions.*/\nbool solveMaze(int maze[N][N])\n{\n    int sol[N][N] = { {0, 0, 0, 0},\n        {0, 0, 0, 0},\n        {0, 0, 0, 0},\n        {0, 0, 0, 0}\n    };\n\n    if(solveMazeUtil(maze, 0, 0, sol) == false)\n    {\n        printf(\"Solution doesn't exist\");\n        return false;\n    }\n\n    printSolution(sol);\n    return true;\n}\n\n/* A recursive utility function to solve Maze problem */\nbool solveMazeUtil(int maze[N][N], int x, int y, int sol[N][N])\n{\n    // if (x,y is goal) return true\n    if(x == N-1 && y == N-1)\n    {\n        sol[x][y] = 1;\n        return true;\n    }\n\n    // Check if maze[x][y] is valid\n    if(isSafe(maze, x, y) == true)\n    {\n        // mark x,y as part of solution path\n        sol[x][y] = 1;\n\n        /* Move forward in x direction */\n        if (solveMazeUtil(maze, x+1, y, sol) == true)\n            return true;\n\n        /* If moving in x direction doesn't give solution then\n           Move down in y direction  */\n        if (solveMazeUtil(maze, x, y+1, sol) == true)\n            return true;\n\n        /* If none of the above movements work then BACKTRACK:\n            unmark x,y as part of solution path */\n        sol[x][y] = 0;\n        return false;\n    }\n\n    return false;\n}\n\n// driver program to test above function\nint main()\n{\n    int maze[N][N]  =  { {1, 0, 0, 0},\n        {1, 1, 0, 1},\n        {0, 1, 0, 0},\n        {1, 1, 1, 1}\n    };\n\n    solveMaze(maze);\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/backtracking/c/sudoku_problem.c",
    "content": "// A Backtracking program  in C++ to solve Sudoku problem\n#include <stdio.h>\n\n// UNASSIGNED is used for empty cells in sudoku grid\n#define UNASSIGNED 0\n\n// N is used for size of Sudoku grid. Size will be NxN\n#define N 9\n\n// This function finds an entry in grid that is still unassigned\nbool FindUnassignedLocation(int grid[N][N], int &row, int &col);\n\n// Checks whether it will be legal to assign num to the given row,col\nbool isSafe(int grid[N][N], int row, int col, int num);\n\n/* Takes a partially filled-in grid and attempts to assign values to\n  all unassigned locations in such a way to meet the requirements\n  for Sudoku solution (non-duplication across rows, columns, and boxes) */\nbool SolveSudoku(int grid[N][N])\n{\n    int row, col;\n\n    // If there is no unassigned location, we are done\n    if (!FindUnassignedLocation(grid, row, col))\n       return true; // success!\n\n    // consider digits 1 to 9\n    for (int num = 1; num <= 9; num++)\n    {\n        // if looks promising\n        if (isSafe(grid, row, col, num))\n        {\n            // make tentative assignment\n            grid[row][col] = num;\n\n            // return, if success, yay!\n            if (SolveSudoku(grid))\n                return true;\n\n            // failure, unmake & try again\n            grid[row][col] = UNASSIGNED;\n        }\n    }\n    return false; // this triggers backtracking\n}\n\n/* Searches the grid to find an entry that is still unassigned. If\n   found, the reference parameters row, col will be set the location\n   that is unassigned, and true is returned. If no unassigned entries\n   remain, false is returned. */\nbool FindUnassignedLocation(int grid[N][N], int &row, int &col)\n{\n    for (row = 0; row < N; row++)\n        for (col = 0; col < N; col++)\n            if (grid[row][col] == UNASSIGNED)\n                return true;\n    return false;\n}\n\n/* Returns a boolean which indicates whether any assigned entry\n   in the specified row matches the given number. */\nbool UsedInRow(int grid[N][N], int row, int num)\n{\n    for (int col = 0; col < N; col++)\n        if (grid[row][col] == num)\n            return true;\n    return false;\n}\n\n/* Returns a boolean which indicates whether any assigned entry\n   in the specified column matches the given number. */\nbool UsedInCol(int grid[N][N], int col, int num)\n{\n    for (int row = 0; row < N; row++)\n        if (grid[row][col] == num)\n            return true;\n    return false;\n}\n\n/* Returns a boolean which indicates whether any assigned entry\n   within the specified 3x3 box matches the given number. */\nbool UsedInBox(int grid[N][N], int boxStartRow, int boxStartCol, int num)\n{\n    for (int row = 0; row < 3; row++)\n        for (int col = 0; col < 3; col++)\n            if (grid[row+boxStartRow][col+boxStartCol] == num)\n                return true;\n    return false;\n}\n\n/* Returns a boolean which indicates whether it will be legal to assign\n   num to the given row,col location. */\nbool isSafe(int grid[N][N], int row, int col, int num)\n{\n    /* Check if 'num' is not already placed in current row,\n       current column and current 3x3 box */\n    return !UsedInRow(grid, row, num) &&\n           !UsedInCol(grid, col, num) &&\n           !UsedInBox(grid, row - row%3 , col - col%3, num);\n}\n\n/* A utility function to print grid  */\nvoid printGrid(int grid[N][N])\n{\n    for (int row = 0; row < N; row++)\n    {\n       for (int col = 0; col < N; col++)\n             printf(\"%2d\", grid[row][col]);\n        printf(\"n\");\n    }\n}\n\n/* Driver Program to test above functions */\nint main()\n{\n    // 0 means unassigned cells\n    int grid[N][N] = {{3, 0, 6, 5, 0, 8, 4, 0, 0},\n                      {5, 2, 0, 0, 0, 0, 0, 0, 0},\n                      {0, 8, 7, 0, 0, 0, 0, 3, 1},\n                      {0, 0, 3, 0, 1, 0, 0, 8, 0},\n                      {9, 0, 0, 8, 6, 3, 0, 0, 5},\n                      {0, 5, 0, 0, 9, 0, 6, 0, 0},\n                      {1, 3, 0, 0, 0, 0, 2, 5, 0},\n                      {0, 0, 0, 0, 0, 0, 0, 7, 4},\n                      {0, 0, 5, 2, 0, 6, 3, 0, 0}};\n    if (SolveSudoku(grid) == true)\n          printGrid(grid);\n    else\n         printf(\"No solution exists\");\n\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/backtracking/c/the_knight_tour_problem.c",
    "content": "// C program for Knight Tour problem\n#include<stdio.h>\n#define N 8\n\nint solveKTUtil(int x, int y, int movei, int sol[N][N],\n                int xMove[],  int yMove[]);\n\n/* A utility function to check if i,j are valid indexes\n   for N*N chessboard */\nbool isSafe(int x, int y, int sol[N][N])\n{\n    return ( x >= 0 && x < N && y >= 0 &&\n             y < N && sol[x][y] == -1);\n}\n\n/* A utility function to print solution matrix sol[N][N] */\nvoid printSolution(int sol[N][N])\n{\n    for (int x = 0; x < N; x++)\n    {\n        for (int y = 0; y < N; y++)\n            printf(\" %2d \", sol[x][y]);\n        printf(\"\\n\");\n    }\n}\n\n/* This function solves the Knight Tour problem using\n   Backtracking.  This function mainly uses solveKTUtil()\n   to solve the problem. It returns false if no complete\n   tour is possible, otherwise return true and prints the\n   tour.\n   Please note that there may be more than one solutions,\n   this function prints one of the feasible solutions.  */\nbool solveKT()\n{\n    int sol[N][N];\n\n    /* Initialization of solution matrix */\n    for (int x = 0; x < N; x++)\n        for (int y = 0; y < N; y++)\n            sol[x][y] = -1;\n\n    /* xMove[] and yMove[] define next move of Knight.\n       xMove[] is for next value of x coordinate\n       yMove[] is for next value of y coordinate */\n    int xMove[8] = {  2, 1, -1, -2, -2, -1,  1,  2 };\n    int yMove[8] = {  1, 2,  2,  1, -1, -2, -2, -1 };\n\n    // Since the Knight is initially at the first block\n    sol[0][0]  = 0;\n\n    /* Start from 0,0 and explore all tours using\n       solveKTUtil() */\n    if (solveKTUtil(0, 0, 1, sol, xMove, yMove) == false)\n    {\n        printf(\"Solution does not exist\");\n        return false;\n    }\n    else\n        printSolution(sol);\n\n    return true;\n}\n\n/* A recursive utility function to solve Knight Tour\n   problem */\nint solveKTUtil(int x, int y, int movei, int sol[N][N],\n                int xMove[N], int yMove[N])\n{\n   int k, next_x, next_y;\n   if (movei == N*N)\n       return true;\n\n   /* Try all next moves from the current coordinate x, y */\n   for (k = 0; k < 8; k++)\n   {\n       next_x = x + xMove[k];\n       next_y = y + yMove[k];\n       if (isSafe(next_x, next_y, sol))\n       {\n         sol[next_x][next_y] = movei;\n         if (solveKTUtil(next_x, next_y, movei+1, sol,\n                         xMove, yMove) == true)\n             return true;\n         else\n             sol[next_x][next_y] = -1;// backtracking\n       }\n   }\n\n   return false;\n}\n\n/* Driver program to test above functions */\nint main()\n{\n    solveKT();\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/bellman_ford/cpp/bellman_ford.cpp",
    "content": "/* 1. shortest path from source to vertices\n   2. can be used for negetive weights\n   3.can be used to detect neg cycle.\n   */\n#include<bits/stdc++.h>\nusing namespace std;\n#define pii pair<int,int>\n#define mp make_pair\n#define INF (1<<20);\npair<int ,pii> G[1000];\nint dis[1000];\n\nint main()\n{\n\tint nodes,edges;\n\tcin>>nodes>>edges;\n\tfor(int i=0;i<edges;i++)\n\t{\n\t\tint u,v,w;\n\t\tcin>>u>>v>>w;\n\t\tG[i]=mp(u,mp(v,w));\n\t//\tv[v].push_back(mp(u,w)); for undirected;\n\t}\n\tfor(int i=1;i<=nodes;i++)\n\t\tdis[i]=INF;\n\tdis[1]=0;\n\tfor(int i=0;i<nodes-1;i++)\n\t{\n\tfor(int j=0;j<edges;j++)\n\t{\n\t\tint u,v,w;\n\t\tu=G[j].first;\n\t\tv=G[j].second.first;\n\t\tw=G[j].second.second;\n\t\tif(dis[v]>dis[u]+w)\n\t\t{\n\t\t\tdis[v]=dis[u]+w;\n\t\t}\n\t}\n\t}\n\tbool negc=false;\n\tfor(int j=0;j<edges;j++)\n\t{\n\t\tint u,v,w;\n\t\tu=G[j].first;\n\t\tv=G[j].second.first;\n\t\tw=G[j].second.second;\n\t\tif(dis[v]>dis[u]+w)\n\t\t{\n\t\t\tnegc=true;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif(negc)\n\tcout<<\"negetive cycle\";\n\telse\n\t{\n\t\tfor(int i=1;i<=nodes;i++)\n\t\t{\n\t\t\tcout<<\"1\"<<\" - \"<<i<<\"= \"<<dis[i]<<endl;\n\t\t}\n\t}\n\n\n}\n\n"
  },
  {
    "path": "algorithms/bellman_ford/java/BellmanFord.java",
    "content": "import java.util.*;\n\nclass Graph\n{\n\tprivate class Edge {\n\t\tint src, dest, weight;\n\t\tprivate Edge(int src, int dest, int weight) {\n\t\t\tthis.src = src;\n\t\t\tthis.dest = dest;\n\t\t\tthis.weight = weight;\n\t\t}\n\t};\n\n\tprivate int V;\n\tprivate LinkedList<Edge> edgeList;\n\tpublic Graph(int v)\n\t{\n\t\tthis.V = v;\n\t\tedgeList = new LinkedList<Edge>();\n\t}\n\n\tpublic void bellmanFord(int src) {\n\t\tif (src < 0 || src > (V - 1)) {\n\t\t\tSystem.out.println(\"Invalid starting vertex\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tint dist[] = new int[V];\n\n\t\tfor (int i=0; i<V; ++i)\n\t\t\tdist[i] = Integer.MAX_VALUE;\n\t\tdist[src] = 0;\n\n\t\tfor (int i=1; i < V; ++i) {\n\t\t\tfor (int j=0; j <  edgeList.size(); ++j) {\t\t\n\t\t\t\tint u = edgeList.get(j).src;\n\t\t\t\tint v = edgeList.get(j).dest;\n\t\t\t\tint weight = edgeList.get(j).weight;\n\t\t\t\t\n\t\t\t\tif (dist[u] != Integer.MAX_VALUE && dist[u] + weight<dist[v]) {\n\t\t\t\t\tdist[v]=dist[u]+weight;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (int j = 0; j < edgeList.size(); ++j) {\n\t\t\tint u = edgeList.get(j).src;\n\t\t\tint v = edgeList.get(j).dest;\n\t\t\tint weight = edgeList.get(j).weight;\n\t\t\t\n\t\t\tif (dist[u] != Integer.MAX_VALUE && dist[u] + weight < dist[v]) {\n\t\t\t\tSystem.out.println(\"Graph contains negative weight cycle\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\tprintArr(dist, V);\n\t}\n\n\tprivate void printArr(int dist[], int V)\n\t{\n\t\tSystem.out.println(\"Vertex Distance from Source\");\n\t\tfor (int i=0; i<V; ++i)\n\t\t\tSystem.out.println(i+\"tt\"+dist[i]);\n\t}\n\t\n\tpublic boolean addEdge(int src, int dest, int weight) {\n\t\tif (src < 0 || dest < 0 || src > (V - 1) || dest > (V - 1)) {\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tEdge edge = new Edge(src, dest, weight);\n\t\tedgeList.add(edge);\n\t\treturn true;\n\t}\n\n\tpublic static void main(String[] args)\n\t{\n\t\tint V = 5;\n\n\t\tGraph graph = new Graph(V);\n\t\t\n\t\tgraph.addEdge(0, 1, -1);\n\t\tgraph.addEdge(0, 2, 4);\n\t\tgraph.addEdge(1, 2, 3);\n\t\tgraph.addEdge(1, 3, 2);\n\t\tgraph.addEdge(1, 4, 2);\n\t\tgraph.addEdge(3, 2, 5);\n\t\tgraph.addEdge(3, 1, 1);\n\t\tgraph.addEdge(4, 3, -3);\n\n\t\tgraph.bellmanFord(1);\n\t}\n}\n"
  },
  {
    "path": "algorithms/bfs/cpp/bfs.cpp",
    "content": "\n#import <vector>\n#import <queue>\n#import <iostream>\n\nclass Vertex {\npublic:\n    Vertex(std::string n);\n\n    Vertex * prev; //predecessor\n    Vertex *next;   //for queue purposes\n    int dist;\n    std::string name;\n    std::vector <Vertex *> neighbours;\n};\n\nVertex::Vertex(std::string n) {\n    prev = nullptr;\n    next = nullptr;\n    dist = -1;\n    name = n;\n}\n\nclass Queue{\npublic:\n    Queue(Vertex *first){\n        head = first;\n        tail = first;\n        first->dist = 0;\n    }\n    void Enqueue(Vertex *pred_, Vertex * cur) {\n        if(head == nullptr) {\n            head = cur;\n        }\n        cur->dist = pred_->dist+1;\n        cur->prev = pred_;\n        tail->next = cur;\n        tail = cur;\n    }\n\n    Vertex * Dequeue(){\n        Vertex *tmp = head;\n        head = head->next;\n        return tmp;\n    }\n\n    bool isEmpty(){\n        return head== nullptr;\n    }\n\n    bool isInQueue(Vertex v){\n        Vertex *iter = head;\n        while(iter != nullptr) {\n            if (iter->name == v.name)\n                return true;\n            iter = iter->next;\n        }\n        return false;\n    }\n    Vertex *head;\n    Vertex *tail;\n\n};\n\n\nvoid BFS(Vertex *root) {\n\n    Queue q(root);\n    Vertex *cur;\n    int dist=0;\n    root->dist = 0;\n    while(!q.isEmpty()) {\n\n        cur = q.Dequeue();\n        for (Vertex *v : cur->neighbours) {\n            if (q.isInQueue(*v))\n                continue;\n            cur->dist = dist;\n            q.Enqueue(cur,v);\n        }\n        dist++;\n    }\n}\n\nint main() {\n    Vertex v1(\"v1\");\n    Vertex v2(\"v2\");\n    Vertex v3(\"v3\");\n    Vertex v4(\"v4\");\n    v1.neighbours.emplace_back(&v2);\n    v1.neighbours.emplace_back(&v3);\n    v2.neighbours.emplace_back(&v3);\n    v3.neighbours.emplace_back(&v4);\n    v1.neighbours.emplace_back(&v4);\n    BFS(&v1);\n    std::cout << v1.dist << \"   v2prevname\" << v2.prev->name << \"    \" << v3.dist << \"    \" << v4.dist;\n    return 0;\n}\n\n"
  },
  {
    "path": "algorithms/bfs/java/Graph.java",
    "content": "import java.util.*;\n\n/**\n * Represents a directed graph using adjacency list\n */\npublic class Graph {\n    private int vertexNumber;\n    private LinkedList[] adj;\n\n    /**\n     *\n     * @param v number of vertex\n     */\n    public Graph(int v) {\n        vertexNumber = v;\n        adj = new LinkedList[v];\n        for (int i = 0; i < v; ++i)\n            adj[i] = new LinkedList();\n    }\n\n    /**\n     * Add edge into graph\n     * @param v vertex\n     * @param w vertex\n     */\n    public void addEdge(int v, int w)  {\n        adj[v].add(w);\n    }\n\n    /**\n     * Prints BFS traversal from a given source vertex\n     * @param source source vertex\n     */\n    public void BFS(int source) {\n        boolean visited[] = new boolean[vertexNumber];\n\n        LinkedList<Integer> queue = new LinkedList<>();\n\n        visited[source] = true;\n        queue.add(source);\n\n        while (queue.size() != 0) {\n            source = queue.poll();\n            System.out.print(source + \" \");\n\n            for (Integer n : (Iterable<Integer>) adj[source]) {\n                if (!visited[n]) {\n                    visited[n] = true;\n                    queue.add(n);\n                }\n            }\n        }\n    }\n\n    /**\n     * Test\n     * @param args\n     */\n    public static void main(String args[]) {\n        Graph g = new Graph(4);\n\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        g.BFS(2);\n    }\n}"
  },
  {
    "path": "algorithms/binary_search/PHP/binarysearch.php",
    "content": "<?php\n/*\n * @Author: Sushma Kure\n * @ProblemStatement: Binary search in PHP\n */\n\nfunction binary_search( $sourceArr, $keyword )\n{\n  $start  = 0;\n  $end    = count( $sourceArr ) - 1;\n  while ( $start <= $end )\n  {\n    $middle = ( $start + $end ) / 2;\n    if( $keyword == $sourceArr[$middle] ) {\n\n      return $middle;\n\n    } elseif( $keyword < $sourceArr[$middle] ) {\n\n      $end = $middle - 1;\n\n    } else {\n\n      $start = $middle + 1;\n\n    }\n\n  }\n  return -1;\n}\n\n$sourceArr = range(1, 100, 7);\n$keyword   = $sourceArr[ array_rand( $sourceArr ) ];  \n$position  = binary_search( $sourceArr, $keyword );\necho '<pre>'; print_r( $sourceArr ); echo '</pre>';\necho ( $position >= 0 ) ? 'Keyword ' . $keyword . ' is found at position: ' . $position :  'Your keyword is not found.';\n\n?>"
  },
  {
    "path": "algorithms/binary_search/binary_search.md",
    "content": "## ELI5\n**Binary Serch** is a way of searching for a thing in a list of things. The list must be sorted, that is, it must be in order of some comparable value or the it won't work. First, we go to the middle of the list and see if the item value equals to the value we want to find. Then, if our value is less/greater than the item in the middle, we work on a new list (which starts from the middle and all the way to the bottom or top) and everything on the bottom or top side. We keep doing this until we find the value we were looking for or if were fluctuating between two elements.\n\n## Pros\n* It takes much less time than a reqular sequential search. \n* Average case of O(log n) vs O(n) for a linear search\n\n## Cons\n* The list must be sorted\n\n## Technical Explanation\n\nIf we have the list\n\n`a = [45,64,68,46,70,6,46,4,6,48]`\n\nAnd we want to find an element if it exists in the list or not\n\nThe naive solution is to go in the list element by element, ask if this is the element I'm looking for or not.\n\nThe worst case is that the element is not in the list, or at the end of it,\n\nthen the time Complexity it takes to end the search process is O(n);\n\nWe can to do better.\n\nHere comes the **Binary Search**,\n\nPseudocode for Binary Searching:\n\nGiven an array A of n elements with values or records A0, A1, ..., An−1, sorted such that A0 ≤ A1 ≤ ... ≤ An−1, and target value T, the following subroutine uses binary search to find the index of T in A.[7]\n1. Set L to 0 and R to n − 1.\n2. If L > R, the search terminates as unsuccessful.\n3. Set m (the position of the middle element) to the floor (the largest previous integer) of (L + R) / 2.\n4. If Am < T, set L to m + 1 and go to step 2.\n5. If Am > T, set R to m − 1 and go to step 2.\n6. Now Am = T, the search is done; return m.\n\n## Pros\n* The Time Complexity is O(log(n))\n* Binary search adds a small amount of complexity for large performance gains.\n* Simple to write.\n* One of the fastest way to find elements in a list.\n\n## Cons\n* The list must be sorted, which is,\n* The complexity can increase when the collection is not stored in a simple structure, such as a list.\n* The list has to be sorted.\n* Doesn't help in reducing the time much and adds complexity for small arrays.\n"
  },
  {
    "path": "algorithms/binary_search/c/binary_search.c",
    "content": "#include <stdio.h>\n\nint binarySearch(int arr[], int l, int r, int key) {\n  if (r >= l) {\n       int mid = l + (r - l)/2;\n\n       // If the element is present at the middle\n       if (arr[mid] == key)  return mid;\n\n       // If element is smaller than mid, then it can only be present in left subarray\n       else if (arr[mid] > key) return binarySearch(arr, l, mid-1, key);\n\n       // Else the element can only be present in right subarray\n       return binarySearch(arr, mid+1, r, key);\n  }\n  // When element is not present in array\n  return -1;\n}\n\nint main(void) {\n  int arr[] = {2, 3, 4, 10, 40};\n  int n = sizeof(arr)/ sizeof(arr[0]);\n  int key = 10;\n  int result = binarySearch(arr, 0, n-1, key);\n  (result == -1) ? printf(\"Element is not present in array\") : printf(\"Element is present at index %d\", result);\n  return 0;\n}"
  },
  {
    "path": "algorithms/binary_search/cpp/binary_search.cpp",
    "content": "//saru95, cruxiu :)\n#include <iostream> /* cout and cin */\n#include <chrono> /* steady_clock::now */\n\nbool binarySearchIterative(int list[], int first, int end, int item){\n\n\tint middle;\n\n\twhile(first <= end){\n\t\tmiddle = (first + end)/2;\n\t\tif(list[middle] == item) {\n\t\t\treturn true;\n\t\t}\n\t\tif(list[middle] < item) {\n\t\t\tfirst = middle + 1;\n\t\t} else {\n\t\t\tend = middle - 1;\n\t\t}\n\t}\n\treturn false;\n}\n\nbool binarySearchRecursive(int list[], int first, int end, int item){\n\n\tint middle = (first + end)/2;\n\n\tif(list[middle] == item){\n\t\treturn true;\n\t}\n\tif(first >= end){\n\t\treturn false;\n\t}\n\tif(list[middle] < item){\n\t\treturn binarySearchRecursive(list, middle+1, end, item);\n\t} else {\n\t\treturn binarySearchRecursive(list, first, middle-1, item);\n\t}\n\n}\n\nint main(int argc, char const *argv[]){\n  std::cout << \"Please, enter the size of the list.\" << std::endl;\n  int size, value, option;\n  bool find;\n  std::cin >> size;\n  int *list = new int[size];\n  for(int i = 0; i < size; i++){\n    std::cout << \"Enter the element \" << i << \" of the list.\" << std::endl;\n    std::cin >> list[i];\n  }\n  std::cout << \"Now, enter a value to be searched in the list.\" << std::endl;\n  std::cin >> value;\n  std::cout << \"Now, would you like to use a binary search iterative (0) or a binary search recursive(1).\" << std::endl;\n  std::cin >> option;\n  switch (option) {\n    case 0:\n      {\n        auto start = std::chrono::steady_clock::now();\n        find = binarySearchIterative(list, 0, size-1, value);\n        auto end = std::chrono::steady_clock::now();\n        auto diff = end - start;\n        if(find)\n        {\n          std::cout << \"You find the element using the binary search iterative.\" << std::endl;\n        }\n        else{\n          std::cout << \"You not find the element using the binary search iterative.\" << std::endl;\n        }\n        std::cout << \"And the time of search was\" << std::chrono::duration <double, std::milli> (diff).count() << \" ms.\" << std::endl;\n      }\n      break;\n    case 1:\n      {\n        auto start = std::chrono::steady_clock::now();\n        find = binarySearchRecursive(list, 0, size-1, value);\n        auto end = std::chrono::steady_clock::now();\n        auto diff = start - end;\n        if(find)\n        {\n          std::cout << \"You find the element using the binary search recursive.\" << std::endl;\n        }\n        else{\n          std::cout << \"You not find the element using the binary search recursive.\" << std::endl;\n        }\n        std::cout << \"And the time of search was\" << std::chrono::duration <double, std::milli> (diff).count() << \" ms.\" << std::endl;\n      }\n      break;\n    default:\n      std::cout << \"This isn't a valid option, please restart the program.\" << std::endl;\n      break;\n  }\n  delete[] list;\n\treturn 0;\n}\n"
  },
  {
    "path": "algorithms/binary_search/java/binarysearch.java",
    "content": "// Java implementation of Binary Search\nclass BinarySearch\n{\n    // Returns index of x if it is present in arr[l..r], else return -1\n    int binarySearch(int ar[], int l, int r, int x){\n\t\tif(ar.length == 0) {\n    \t\treturn -1;\n    \t}\n\t\t\n        if (r >= l){\n            int mid = l + (r - l) / 2;\n            // If the search is present at the mid postion\n            if (ar[mid] == x){\n               return mid;\n            }\n            // If element is smaller than mid, then it can only be in left subarray\n            if (ar[mid] > x){\n               return binarySearch(ar, l, mid - 1, x);\n            }\n            // Else the element can only be present in right subarray\n            return binarySearch(ar, mid + 1, r, x);\n        }\n        // We reach here when element is not present in array\n        return -1;\n    }\n    // Main method for testing\n    public static void main(String args[])\n    {\n        BinarySearch ob = new BinarySearch();\n        int arr[] = {1, 4, 5, 10, 11, 27, 36, 67, 90};\n        int n = arr.length;\n        int x = 10;\n        int result = ob.binarySearch(arr, 0, n - 1, x);\n        if (result == -1){\n            System.out.println(\"Element not present\");\n        }\n        else{\n            System.out.println(\"Element found at index \" + result);\n        }\n    }\n}\n"
  },
  {
    "path": "algorithms/binary_search/javascript/binary_search.js",
    "content": "function binarySearch(ar, el, compare_fn) {\n    var m = 0;\n    var n = ar.length - 1;\n    while (m <= n) {\n        var k = (n + m) >> 1;\n        var cmp = compare_fn(el, ar[k]);\n        if (cmp > 0) {\n            m = k + 1;\n        } else if(cmp < 0) {\n            n = k - 1;\n        } else {\n            return k;\n        }\n    }\n    return -m - 1;\n}\n"
  },
  {
    "path": "algorithms/binary_search/python/binary_search.py",
    "content": "#Simple implementation of the binary search\n\ndef b_search(a,s,start,end):\n    target = int((start+end)/2)\n    if start > end:\n        return -1\n    if s == a[target]:\n        return target\n    if s > a[target]:\n        return b_search(a,s, target+1, end)\n    if s < a[target]:\n        return b_search(a,s, start, target-1)\n\n#input: s = target, a = array \nprint('Insert array (list of ints separated by a space): ')\na = list(map(int, input().split()))\nprint('Insert target: ')\ns = int(input())\nprint('Pos: ')\nprint(b_search(a,s,0,len(a)-1))\n"
  },
  {
    "path": "algorithms/binary_search/ruby/binary_search.rb",
    "content": "def binary_search(an_array, item)\n  first = 0\n  last = an_array.length - 1\n\n  while first <= last\n    i = (first + last) / 2\n\n    if an_array[i] == item\n      return i\n    elsif an_array[i] > item\n      last = i - 1\n    elsif an_array[i] < item\n      first = i + 1\n    else\n      return -1\n    end\n  end\nend\n\narr = [0,1,2,3,4,27,5,6,7,8,9]\n\nbinary_search(arr, 27)\n# => 5\n"
  },
  {
    "path": "algorithms/bipartite_check/cpp/bipartite.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\nint col[100];\nint G[100][100];\nint nodes,edges;\nbool bipartite(int src)\n{\ncol[src]=1;\nqueue<int> q;\nq.push(src);\nwhile(!q.empty())\n{\n\tint u=q.front();\n\tq.pop();\n\tfor(int i=1;i<=nodes;i++)\n\t{\n\t\tif(G[u][i]==1 && col[i]==-1)\n\t\t{\n\t\t\tcol[i]=1-col[u];\n\t\t\tq.push(i);\n\t\t}\n\t\telse\n\t\t\tif(G[u][i]==1 && col[i]==col[u])\n\t\t\t\treturn false;\n\t}\n}\nreturn true;\n\n}\nint main()\n{\n\n\tcin>>nodes>>edges;\n\tfor(int i=0;i<100;i++)\n\t{\n\t\tcol[i]=-1;\n\tfor(int j=0;j<100;j++)\n\t{\n\t\tG[i][j]=0;\n\t}\n}\n\tfor(int i=0;i<edges;i++)\n\t{\n\t\tint u,v;\n\t\tcin>>u>>v;\n\t\tG[u][v]=1;\n\t\tG[v][u]=1;\n\n\t}\n\tcout<<bipartite(1);\n\n}\n"
  },
  {
    "path": "algorithms/bitwise/cpp/generating_subsets.cpp",
    "content": "#include <iostream>\n#include <vector>\n\n#define pb push_back\n\nusing namespace std;\n\nint main(void)\n{\n    vector<int> v = {1,2,3};\n    int numSubsets = 1 << v.size();\n    for(int i = 0; i < numSubsets; ++i)\n    {\n        int pos = v.size() - 1;\n        int subsetMask = i;\n        cout << \"{ \";\n        while(subsetMask > 0)\n        {\n            if(subsetMask & 1)\n                cout << v[pos] << \" \";\n            subsetMask >>= 1;\n            pos--;\n        }\n        cout << \"}\\n\";\n    }\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/bitwise/java/AddTwoNumbersWithoutPlusOperator.java",
    "content": "\npublic class AddTwoNumbersWithoutPlusOperator {\n    public static void main(String[] args) {\n        int a = 10;\n        int b = 90;\n        add(a, b);\n    }\n\n    private static void add(int a, int b) {\n        int carry;\n        while (b != 0) {\n            carry = a & b;\n            a = a ^ b;\n            b = carry << 1;\n        }\n        System.out.println(\"The sum  \" + a);\n    }\n}\n"
  },
  {
    "path": "algorithms/bitwise/java/BinaryPalidrome.java",
    "content": "public class BinaryPalidrome {\n    // check if binary representation of a number is palidrome\n    public static void main(String[] args) {\n        int n = 153;\n        if (new BinaryPalidrome().isPalidrome(n)) {\n            System.out.println(\"Yes, the binary representation of the number \" + n + \" is palidrome.\");\n        } else {\n            System.out.println(\"No, the binary representation of the number \" + n + \" is not a palidrome.\");\n        }\n    }\n\n    private boolean isPalidrome(int n) {\n        int m = getTotalBits(n) - 1;\n        int i = 0;\n        while (i <= m) {\n            if (kthBit(n, i) != kthBit(n, m)) {\n                return false;\n            }\n            i++;\n            m--;\n        }\n        return true;\n    }\n\n    private int kthBit(int n, int kthBit) {\n        return (n & 1 << kthBit) > 0 ? 1 : 0;\n    }\n\n    private int getTotalBits(int n) {\n        int totalBits = 0;\n        while (n != 0) {\n            totalBits++;\n            n = n >> 1;\n        }\n        return totalBits;\n    }\n}\n"
  },
  {
    "path": "algorithms/bitwise/java/NegateANumberWithoutPlusOperator.java",
    "content": "public class NegateANumberWithoutPlusOperator {\n    public static void main(String[] args) {\n        NegateANumberWithoutPlusOperator number = new NegateANumberWithoutPlusOperator();\n        int n = 54;\n        System.out.println(\"Negation of number \" + n + \" is \" + number.negate(n));\n    }\n\n    private int negate(int n) {\n        n = ~n;\n        return add(n, 1);\n    }\n    private int add(int a, int b) {\n        int carry;\n        while (b != 0) {\n            carry = a & b;\n            a = a ^ b;\n            b = carry << 1;\n        }\n        return a;\n    }\n}\n"
  },
  {
    "path": "algorithms/bitwise/java/Optimized_permutation",
    "content": "//Initial values\nint x = 0;\nint y = 1;\n//Optimzed permutation:\nx = x ^ y;\ny = x ^ y;\nx = x ^ y;\n//Yields: x = 1 and y = 0\n"
  },
  {
    "path": "algorithms/bitwise/java/Subsets.java",
    "content": "/**\n * Subsets of a set:\n * input: array of size of n elements\n * output: 2^n subsets\n */\n\npublic class Subsets {\n    public static void main(String[] args) {\n        char[] array = {'a', 'b', 'c'};\n        Subsets set = new Subsets();\n        set.printSubsets(array);\n    }\n\n    private void printSubsets(char[] set) {\n        int n = set.length;\n        int totalSubsets = 1 << n;\n        for (int i = 0; i < totalSubsets; i++) {\n            System.out.print(\"{ \");\n            for (int j = 0; j < n; j++) {\n                if ((i & (1 << j))  > 0) {\n                    System.out.print(set[j] + \" \");\n                }\n            }\n            System.out.println(\" }\");\n\n        }\n\n\n    }\n}"
  },
  {
    "path": "algorithms/bogo_sort/java/BogoSort.java",
    "content": "import java.util.Arrays;\nimport java.util.List;\nimport java.util.Collections;\n\npublic class BogoSort {\n\t\n\tpublic static List<Integer> bogoSort(List<Integer> nums) {\n\t\tif (isSorted(nums)) {\n\t\t\treturn nums;\n\t\t}\n\t\t\n\t\tfor (;;) {\n\t\t\tCollections.shuffle(nums);\n\t\t\t\n\t\t\tif (isSorted(nums)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn nums;\n\t}\n\t\n\tpublic static boolean isSorted(List<Integer> x) {\n\t\tfor (int i = 0; i < x.size() - 1; i++) {\n\t\t\tif (x.get(i) > x.get(i + 1)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn true;\n\t}\n}"
  },
  {
    "path": "algorithms/bogo_sort/python/bogo.py",
    "content": "from random import *\n\nseed()\nx = []\nfor i in range(0, 10):\n    x.append(randint(0, 100))\n\ndef inorder(x):\n    i = 0\n    j = len(x)\n    while i + 1 < j:\n        if x[i] > x[i + 1]:\n            return False\n        i += 1\n    return True\n\ndef bogo(x):\n    while not inorder(x):\n        shuffle(x)\n    return x\n\n"
  },
  {
    "path": "algorithms/bogo_sort/ruby/bogo_sort.rb",
    "content": "def bogosort(arr)\n  arr.shuffle! while !arr.each_cons(2).all? do |x, y|\n    x <= y\n  end\nend\narray = [ 0, 5, 4, 3, 2, 8, 7, 1, 9, 6]\nbogosort(array)\nputs array # => 0, 1, 2, 3, 4, 5, 6, 7, 8, 9\n"
  },
  {
    "path": "algorithms/breadth_first_search/cpp/bfs.cpp",
    "content": "#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    list<int> *adj;    // Pointer to an array containing adjacency lists\npublic:\n    Graph(int V);  // Constructor\n    void addEdge(int v, int w); // function to add an edge to graph\n    void BFS(int s);  // prints BFS traversal from a given source 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 \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 a 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\n        // 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}\nint main()\n{\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);\n \n    return 0;\n}\n"
  },
  {
    "path": "algorithms/bubble_sort/README.md",
    "content": "# Bubble Sort\n\nThis folder contains examples of the bubble sort algorithm in the following programming languages:\n\n* bash\n* C\n* C++\n* Crystal\n* C#\n* Elixir\n* Go\n* Haskell\n* Java\n* JavaScript\n* Kotlin\n* Objective-C\n* Power Shell\n* Python\n* Ruby\n* Swift\n* Visual Basic\n"
  },
  {
    "path": "algorithms/bubble_sort/assembly_mips/bubble_sort.asm",
    "content": "## Data declaration section \n.data\n# these are globals\n  # array of word long ints\n  myarray:    .word 23, 4, 34, 55, 87, 24, 99, 12, 233, 45, 43245, 23, 45, 68, 69\n  mysize:     .word 15\n\n.text ## Assembly language instructions go in text segment \nj main # very first, goto main.\n\nbubblesort:\n   # inputs:\n   # ra must be set before calling this and contain the location to where this will return after execution\n   # a0 must be the base address of the array of integers to print\n   # a1 must be the size of the array to print (or the number of elements in the array to print)\n   # outputs: only output is the system \"display\", no return values\n   # saved registers: no need as this internally only uses t registers\n   #\n   # internal register uses\n   # t0 = address of base of myarray from input $a0\n   # t1 = value of mysize from input $a1\n   # t2 is used to put address, once calculated of array[index]\n   # t3 is used to put address, once calculated of array[index + 1]\n   # t4 is used to put the value of array[index]\n   # t5 is used to put the value of array[index + 1]\n   # t6 bool hold comparison result between t2 and t3\n   # t7 bool hasChanged. Keep track of if changes have been made in array\n   # t8 is used to hold comparison result\n   # t9 = index into array \n  add $t0 $0 $a0  # move a0 to t0 via an add statement\n  move $t1 $a1    # move a1 to t1 via the move command\n  # either of the above commands work. Before you choose, look at the \n  #   assembled version of each command\n  \n  #################################################################################\n  #print array (unsorted)\n  add $t9 $0 $0   # initialize the counter before the loop\n  printunsorted:\n    #do stuff\n    sll $t2 $t9 2   # multiply index by 4\n    add $t2 $t0 $t2 # add base address of array to 4*index\n    lw $a0 0($t2) # put value of myarray[index] into a0\n    \n    li $v0, 1 # load instruction 1 (print an int whose value is in a0)\n    syscall\n    \n    li $v0, 11        #load instruction 11 (print single char whose value is in a0)\n    addi $a0, $0, 0x20  #load ascii char 32 = 0x20 = 'space'\n    syscall\n    \n    addi $t9 $t9 1  # increment counter \n    slt $t8 $t9 $t1  # compare counter t9 to size t1\n    bne $t8 $0 printunsorted # loop if $t9 < size\n  #end printsorted\n  li $v0, 11        #load instruction 11 (print single char whose value is in a0)\n    addi $a0, $0, 0x0A  #load ascii char 32 = 0x0A = 'new line'\n    syscall\n  #################################################################################\n  addi $t1 $t1 -1 #loop for (size - 1)\n  outer:\n    move $t7 $0   # set default value of register inside beginning of outer do-while loop     \n    \n    add $t9 $0 $0   # initialize the counter before the loop\n    inner:\n      #do stuff\n      sll $t2 $t9 2   # multiply index by 4\n    \n      add $t2 $t0 $t2 # add base address of array to 4*index\n      addi $t3 $t2 4 #place address of myarray[index + 1] in t3\n    \n      lw $t4 0($t2) # put value of myarray[index] into t2 ### change from    lw $a0 0($t2) # put value of myarray[index] into t2 #which is used to be able to call print syscall, which uses $a0\n      lw $t5 0($t3) #put value of myarray[index + 1] into t3\n    \n      slt $t6 $t5 $t4 #compare myarray[index + 1] < myarray[index]\n      beq $t6 $0 noswap # don't swap if in correct relative location \n      #swap\n      sw $t5 0($t2) # myarray[index] = myarray[index + 1]\n      sw $t4 0($t3) # myarray[index + 1] = myarray[index] (value before swap)\n      addi $t7 $t7 1   # set default value of register inside beginning of outer do-while loop\n      noswap:#skipped past swap operations\n    \n      addi $t9 $t9 1  # increment counter\n      slt $t8 $t9 $t1  # compare counter t9 to size t1\n      bne $t8 $0 inner # loop if $t9 < size\n    #end inner\n    bne $t7 $0 outer # loop if $t0 != 0 (hasChanged)\n  #end outer\n  #################################################################################\n  addi $t1 $t1 1 #reset size of loop counter\n  #print array (sorted)\n  add $t9 $0 $0   # initialize the counter before the loop\n  printsorted:\n   #do stuff\n    sll $t2 $t9 2   # multiply index by 4\n    add $t2 $t0 $t2 # add base address of array to 4*index\n    move $a3 $a0\n    lw $a0 0($t2) # put value of myarray[index] into a0\n    \n    li $v0, 1 # load instruction 1 (print an int whose value is in a0)\n    syscall\n    \n    li $v0, 11        #load instruction 11 (print single char whose value is in a0)\n    addi $a0, $0, 0x20  #load ascii char 32 = 0x20 = 'space'\n    syscall\n    \n    addi $t9 $t9 1  # increment counter  \n    slt $t8 $t9 $t1  # compare counter t9 to size t1\n    bne $t8 $0 printsorted # loop if $t9 < size\n  #################################################################################\n  jr $ra #leave function\n\n\nmain: ## Start of code section\n  la $a0 myarray\n  lw $a1 mysize\n  jal bubblesort # jump to bubblesort and put current address in $ra so that it can come \n    #  back (ie return to here after function call)\n\nleave:\n  li $v0, 10         # load system instruction 10 (terminate program) into v0 register\n  syscall\n"
  },
  {
    "path": "algorithms/bubble_sort/bash/bubblesort.sh",
    "content": "#!/bin/bash\necho \"enter maximum number\"\nread n\n\n\necho \"enter Numbers in array:\"\nfor (( i = 0; i < $n; i++ ))\ndo\nread nos[$i]\ndone\n\nfor (( i = 0; i < $n ; i++ ))\ndo\n\tfor (( j = $i; j < $n; j++ ))\n\tdo\n\t\tif [ ${nos[$i]} -gt ${nos[$j]}  ]; then\n\t\tt=${nos[$i]}\n\t\tnos[$i]=${nos[$j]}\n\t\tnos[$j]=$t\n\t\tfi\n\tdone\ndone\n\n# Printing the sorted number\necho -e \"\\nSorted Numbers \"\nfor (( i=0; i < $n; i++ ))\n\tdo\n\techo ${nos[$i]}\ndone\n"
  },
  {
    "path": "algorithms/bubble_sort/c/bubble_sort.c",
    "content": "//algorithm of bubble sort in c\n//start from the first elemnent \n/*1. start comparing it with the next element\n  2. swap the element with the first smaller element it encounters.\n  3. every traversal pushes the largest element towards the end.\n*/\n  \n\n\n\nvoid bubbleSort(int arr[], int n)\n{\n   int i, j;\n   for (i = 0; i < n-1; i++)      \n \n       // Last i elements are already in place   \n       for (j = 0; j < n-i-1; j++) \n           if (arr[j] > arr[j+1])\n              swap(&arr[j], &arr[j+1]);\n}\n\nint main()\n{\nint i,j,k;\nint a[5];\nfor(i=0;i<5;i++)\nscanf(\"%d\",&a[i]);\nbubblesort(a,5);\nfor(i=0;i<5;i++)\nprintf(\"%d\\n\",a[i]);\n\nreturn 0;\n}\n"
  },
  {
    "path": "algorithms/bubble_sort/cpp/bubble_sort_1.cpp",
    "content": "#include<iostream>\nusing namespace std;\n\n//global variables for ease of use\nlong long int array[1000],n,temp;\n\n//function for bubble sort\nvoid bubble_sort()\n{\n\n\tfor(register long long int i=0;i<n;i++)\n\t{\n\t\tfor(register long long int j=0;j<n-i-1;j++)\n\t\t{\n\t\t\tif(array[j]>array[j+1])\n\t\t\t{\n\t\t\t\ttemp=array[j];\n\t\t\t\tarray[j]=array[j+1];\n\t\t\t\tarray[j+1]=temp;\n\t\t\t}\n\t\t}\t\n\t}\n}\nint main()\n{\n\t// Enter the number of elements \n\tcin>>n;\n\n\t//Entering the elements\n\tfor(register long long int i=0;i<n;i++)\n\t{\n\t\tcin>>array[i];\n\t}\n\n\t//buuble sort\n\tbubble_sort();\n\n\t//Sorted order\n\tfor(register long long int i=0;i<n;i++)\n\t{\n\t\tcout<<array[i]<<\" \";\n\t}\n}\n"
  },
  {
    "path": "algorithms/bubble_sort/cpp/bubblesort.cpp",
    "content": "/* C++ Program - Bubble Sort */\n\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": "algorithms/bubble_sort/crystal/bubble_sort.cr",
    "content": "def bubbleSort(array)\n  count = 0\n  while true\n    swapped = false\n    i = 0\n\n    while true\n      if array[i] > array[i + 1]\n        array[i], array[i + 1] = array[i + 1], array[i]\n        swapped = true\n      end\n\n      i += 1\n      break if i == array.size - 1\n    end\n\n    break if !swapped\n\n    count += 1\n    break if count == array.size - 1\n  end\n\n  array\nend\n\nnumbers = [4, 2, 8, 1, 0, 10]\n\nputs \"Unsorted: #{numbers}\"\n\nputs \"Sorted: #{bubbleSort(numbers)}\"\n"
  },
  {
    "path": "algorithms/bubble_sort/csharp/BubbleSort.cs",
    "content": "using System;\nusing System.Collections.Generic;\n\n\npublic class BubbleSort {\n    private static void Main(string[] args) {\n         Console.WriteLine(\"Input the elements of the array\");\n            var isNumber = true;\n            var userInput = new List<int>();\n            while (isNumber) {\n                var input = Console.ReadLine();\n                if (int.TryParse(input, out var temp )) {\n                    userInput.Add(temp);\n                } else {\n                    isNumber = false;\n                }\n            }\n            Console.Write('\\n');\n            Console.WriteLine(\"Array before Sorting with Bubble Sort\");\n            foreach (var entry in userInput) {\n                Console.Write(entry + \"   \");\n            }\n            BubbleSort(userInput);\n            Console.Write('\\n');\n            Console.WriteLine(\"Array after Sorting with Bubble Sort\");\n            foreach (var entry in userInput) {\n                Console.Write(entry + \"   \");\n            }\n            Console.Read();\n        }\n        \n        private static void BubbleSort(IList<int> list) {\n            var n = list.Count;\n            do {\n                var newn = 1;\n                for (var i = 0; i < n - 1; i++) {\n                    if (list[i] <= list[i + 1]) {\n                        continue;\n                    }\n                    var temp = list[i];\n                    list[i] = list[i + 1];\n                    list[i + 1] = temp;\n                    newn = i + 1;\n                }\n                n = newn;\n            } while (n > 1);\n        }\n    }\n"
  },
  {
    "path": "algorithms/bubble_sort/elixir/README.md",
    "content": "# Elixir BubbleSort\n\nA simple implementation of the bubble sort algorithm in Elixir.\n\nExample of usage:\n\n```\niex(1)> c(\"bubblesort.ex\")\n[BubbleSort]\niex(2)> BubbleSort.sort(1..1_000 |> Enum.reverse)\n[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,\n 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,\n 43, 44, 45, 46, 47, 48, 49, 50, ...]\n```\n"
  },
  {
    "path": "algorithms/bubble_sort/elixir/bubblesort.ex",
    "content": "defmodule BubbleSort do\n  def sort([]),  do: []\n  def sort(list) do\n    round = swap(list)\n    cond do\n      round == list -> list\n      true -> sort(round)\n    end\n  end\n\n  defp swap([head | []]), do: [head]\n  defp swap([head | [second | tail]]) do\n    cond do\n      head < second -> [head | swap([second | tail])]\n      true  -> [second | swap([head | tail])]\n    end\n  end\nend\n"
  },
  {
    "path": "algorithms/bubble_sort/go/bubble-sort-algorithm.go",
    "content": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tvar numbers []int = []int{5, 4, 2, 3, 1, 0}\n\tfmt.Println(\"Unsorted:\", numbers)\n\n\tbubbleSort(numbers)\n\tfmt.Println(\"Sorted:\", numbers)\n}\n\nfunc bubbleSort(numbers []int) {\n\tvar N int = len(numbers)\n\tvar i int\n\tfor i = 0; i < N; i++ {\n\t\tsweep(numbers)\n\t}\n}\n\nfunc sweep(numbers []int) {\n\tvar N int = len(numbers)\n\tvar firstIndex int = 0\n\tvar secondIndex int = 1\n\n\tfor secondIndex < N {\n\t\tvar firstNumber int = numbers[firstIndex]\n\t\tvar secondNumber int = numbers[secondIndex]\n\n\t\tif firstNumber > secondNumber {\n\t\t\tnumbers[firstIndex] = secondNumber\n\t\t\tnumbers[secondIndex] = firstNumber\n\t\t}\n\n\t\tfirstIndex++\n\t\tsecondIndex++\n\t}\n}\n"
  },
  {
    "path": "algorithms/bubble_sort/haskell/bubble_sort.hs",
    "content": "import Debug.Trace\n\nmain :: IO()\nmain = do\n  let sorted = bubbleSort [6, 5, 3, 1, 8, 7, 2, 4] :: [Integer]\n  print sorted\n\nbubbleSort :: (Ord a, Show a) => [a] -> [a]\n--bubbleSort lst | trace (\"sorting: \" ++ show lst) False = undefined\nbubbleSort [] = []\nbubbleSort [x] = [x]\nbubbleSort (x:y:rest) =\n  bubbleSort (init bubbled) ++ [last bubbled]\n  where\n    (first, second) = if x > y then (y,x) else (x,y)\n    bubbled = first : bubbleSort (second:rest)\n"
  },
  {
    "path": "algorithms/bubble_sort/java/BubbleSortExample.java",
    "content": "import java.util.Scanner;\n\npublic class BubbleSortExample {\n\n    private static void bubbleSort(int[] arr) {\n        int n = arr.length;\n        int temp = 0;\n        for(int i=0; i < n; i++){\n            for(int j=1; j < (n-i); j++){\n                if(arr[j-1] > arr[j]){\n                    //swap elements\n                    temp = arr[j-1];\n                    arr[j-1] = arr[j];\n                    arr[j] = temp;\n                }\n\n            }\n        }\n\n    }\n    public static void main(String[] args) {\n\n        Scanner in = new Scanner(System.in);\n\n        System.out.println(\"Input the size of array\");\n        int n = in.nextInt();\n        int[] arr = new int[n];\n\n        System.out.println(\"Input the elements of array\");\n        for(int i=0; i<n; i++){\n            arr[i] = in.nextInt();\n        }\n\n        System.out.println(\"Array Before Bubble Sort\");\n        for (int anArr : arr) {\n            System.out.print(anArr + \" \");\n        }\n        System.out.println();\n\n        bubbleSort(arr);//sorting array elements using bubble sort\n\n        System.out.println(\"Array After Bubble Sort\");\n        for (int anArr : arr) {\n            System.out.print(anArr + \" \");\n        }\n\n    }\n}\n"
  },
  {
    "path": "algorithms/bubble_sort/java/GenericBubbleSort.java",
    "content": "\nclass GenericBubbleSort {\n\n    public static <T extends Comparable<T>> void bubble_sort(T array[]){\n        boolean swapped;\n        int indexOfLastUnsortedElement =  array.length;\n        do{\n            swapped = false;\n            for(int i=0; i < indexOfLastUnsortedElement - 1; i++){\n                if(array[i].compareTo(array[i+1]) > 0){\n                    swap(i, array);\n                    swapped = true;\n                }\n            }\n            indexOfLastUnsortedElement--;\n            printArray(array);\n        }while(swapped);\n    }\n\n    private static <T> void swap(int index, T[] array){\n        T temp = array[index];\n        array[index] = array[index + 1];\n        array[index + 1] = temp;\n    }\n\n    private static <T> void printArray(T[] input){\n        for(int i  = 0; i < input.length; i++){\n            System.out.print(input[i] + \" \");\n        }\n        System.out.print(\"\\n\");\n    }\n\n    public static void main(String[] args){\n        bubble_sort(new Integer[] {4, 2, 9, 6, 23, 12, 34, 0, 1});\n        bubble_sort(new String[] { \"c\", \"a\", \"e\", \"d\", \"b\" });\n    }\n}"
  },
  {
    "path": "algorithms/bubble_sort/javascript/bubble-sort.js",
    "content": "function bubbleSort(a)\n{\n    let swapped;\n    do {\n        swapped = false;\n        for (let i=0; i < a.length-1; i++) {\n            if (a[i] > a[i+1]) {\n                let temp = a[i];\n                a[i] = a[i+1];\n                a[i+1] = temp;\n                swapped = true;\n            }\n        }\n    } while (swapped);\n    return a;\n}\n"
  },
  {
    "path": "algorithms/bubble_sort/javascript/bubbleSort.js",
    "content": "function bubbleSort(array) {\n    let len = array.length;\n    let temp;\n\n    for (let i = 0; i < len; i++) {\n        for (let j = 0; j < len; j++) {\n            if (array[i] < array[j]) {\n                temp = array[i];\n                array[i] = array[j];\n                array[j] = temp;\n            }\n        }\n    }\n}\n// export default bubbleSort;\nmodule.exports = bubbleSort;\n"
  },
  {
    "path": "algorithms/bubble_sort/javascript/main_bs.js",
    "content": "let bubbleSort = require('./bubbleSort');\n// import bubbleSort from './bubbleSort';\nlet rl = require('readline');\n// import rl from 'readline';\n// allow input through console\nlet prompt = rl.createInterface(process.stdin,\n                                 process.stdout);\n\nlet array = [];\nlet flag = true;\nconsole.log('Enter all the values. Press q to stop input');\n\nfunction readInput() {\n    prompt.question('>>', function(inp) {\n        if (inp == 'q') {\n            console.log('initial array: ', array);\n            bubbleSort(array);\n            console.log('final array: ', array);            \n\n            return prompt.close();\n        }\n\n        array.push(Number(inp));\n        readInput();\n    });\n}\n\nreadInput();\n"
  },
  {
    "path": "algorithms/bubble_sort/kotlin/bubblesort.kt",
    "content": "public class bubbleSort : Algorithm{\n\n    public override fun sort(arr: Array<Long>): Array<Long> {\n        var swappedElements : Boolean;\n        do {\n            swappedElem = false;\n            for (i in 0..arr.size - 2){\n                if (arr[i] > arr[i + 1]){\n                    swap(arr, i, i + 1);\n                    swappedElem = true;\n                }\n            }\n        } while (swappedElem);\n        return arr;\n    }\n\n    public override fun getName(): String {\n        return \"BubbleSort Algorithm\";\n    }\n}\n"
  },
  {
    "path": "algorithms/bubble_sort/objetive-c/BubbleSort.m",
    "content": "- (NSArray *)bubbleSort:(NSArray *)unsortedArray {\n    //create mutable copy of the array\n    NSMutableArray *unsortedMutableArray = [unsortedArray mutableCopy];\n    \n    for (int i = 0; i < unsortedMutableArray.count; ++i) {\n        for (int j = 0; j < (unsortedMutableArray.count - i - 1); ++j) {\n            //reading integer values of the current and the next elements in the array\n            NSInteger currElement = [unsortedMutableArray[j] integerValue];\n            NSInteger nextElement = [unsortedMutableArray[j + 1] integerValue];\n            \n            //comparing the elements\n            if (currElement > nextElement) {\n                NSNumber *temp = unsortedMutableArray[j]; //keeping the current element in a temp\n                //swapping the elements\n                unsortedMutableArray[j] = unsortedMutableArray[j + 1];\n                unsortedMutableArray[j + 1] = temp;\n            }\n        }\n    }\n    //return the sorted array\n    return [NSArray arrayWithArray:unsortedMutableArray];\n}\n"
  },
  {
    "path": "algorithms/bubble_sort/perl/BubbleSort.pl",
    "content": "my @array = ( 5, 6, 3, 1, 7, 3, 2, 9, 10, 4 );\n\nfor my $x ( reverse 1 .. $#array ) {\n    for my $y ( 0 .. $x - 1 ) {\n        @array[ $y, $y + 1 ] = @array[ $y + 1, $y ]\n            if $array[$y] > $array[ $y + 1 ];\n    }\n}\n\nprint \"@array\\n\";"
  },
  {
    "path": "algorithms/bubble_sort/power_shell/bubble_sort.ps1",
    "content": "function bubblesort ($a) {\n    $l = $a.Length\n    $hasChanged = $true\n    while ($hasChanged) {\n        $hasChanged = $false\n        $l--\n        for ($i = 0; $i -lt $l; $i++) {\n            if ($a[$i] -gt $a[$i+1]) {\n                $a[$i], $a[$i+1] = $a[$i+1], $a[$i]\n                $hasChanged = $true\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "algorithms/bubble_sort/python/bubble_sort.py",
    "content": "def bubbleSort(a):\n    n = len(a)\n    sorted = False\n    while not sorted:\n        sorted = True\n        for i in range(0, n - 1):\n            if a[i] > a[i + 1]:\n                sorted = False\n                a[i], a[i + 1] = a[i + 1], a[i]\n\na = [12, 33, 1, 3, 54, 32, 78, 54, 99, 6]\nprint(a)\nbubbleSort(a)\nprint(a)\n"
  },
  {
    "path": "algorithms/bubble_sort/ruby/bubble_sort.rb",
    "content": "def bubble_sort(array)\n  n = array.length\n  loop do\n    swapped = false\n\n    (n-1).times do |i|\n      next unless array[i] > array[i+1]\n      array[i], array[i+1] = array[i+1], array[i]\n      swapped = true\n    end\n\n    break if not swapped\n  end\n\n  array\nend\n\narr = [1,4,5,2,6,7,8,3]\nbubble_sort(arr)\n# => [1, 2, 3, 4, 5, 6, 7, 8]\n"
  },
  {
    "path": "algorithms/bubble_sort/swift/bubble_sort.swift",
    "content": "func bubbleSort(unsortedArray: Array<NSNumber>) -> Array<NSNumber> {\n    //mutable copy of the initial array\n    var mutableArray = unsortedArray\n    //double looping through the array\n    for i in 0..<mutableArray.count {\n        for j in 0..<(mutableArray.count - i - 1) {\n            //checking the elements\n            if (mutableArray[j] as! Int > mutableArray[j + 1] as! Int) {\n                let temp = mutableArray[j] //storing into a temp value\n                //swapping the elements\n                mutableArray[j] = mutableArray[j + 1]\n                mutableArray[j + 1] = temp\n            }\n        }\n    }\n    //returning the sorted array\n    let sortedArray = mutableArray\n    return sortedArray\n}\n"
  },
  {
    "path": "algorithms/bubble_sort/vb/bubble_sort.bas",
    "content": "Option Explicit\n'VB6 Specific\nPrivate Sub bubble_sort()\nDim i As Integer\nDim j As Integer\nDim k As Integer\nDim array_unsorted(1001) As String\nDim array_sorted(1001) As String\nDim temp As String\nDim swapped As Boolean\n    i = 1000\n    j = 0\n    Do\n        swapped = False\n        For j = 1 To i - 1\n            If LCase(array_unsorted(j)) > LCase(array_unsorted(j + 1)) Then\n                temp = array_unsorted(j)\n                array_unsorted(j) = array_unsorted(j + 1)\n                array_unsorted(j + 1) = temp\n                swapped = True\n            End If\n        Next j\n        i = i - 1\n    Loop Until Not swapped\n    For k = 1 To 1000\n        array_sorted(k) = array_unsorted(k)\n    Next k\nEnd Sub\n\n\n"
  },
  {
    "path": "algorithms/bucket_sort/bucket_sort.cpp",
    "content": "// C++ program to sort an array using bucket sort\n#include <iostream>\n#include <algorithm>\n#include <vector>\nusing namespace std;\n \n// Function to sort arr[] of size n using bucket sort\nvoid bucketSort(float arr[], int n)\n{\n    // 1) Create n empty buckets\n    vector<float> b[n];\n    \n    // 2) Put array elements in different buckets\n    for (int i=0; i<n; i++)\n    {\n       int bi = n*arr[i]; // Index in bucket\n       b[bi].push_back(arr[i]);\n    }\n \n    // 3) Sort individual buckets\n    for (int i=0; i<n; i++)\n       sort(b[i].begin(), b[i].end());\n \n    // 4) Concatenate all buckets into arr[]\n    int index = 0;\n    for (int i = 0; i < n; i++)\n        for (int j = 0; j < b[i].size(); j++)\n          arr[index++] = b[i][j];\n}\n \n/* Driver program to test above funtion */\nint main()\n{\n    float arr[] = {0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434};\n    int n = sizeof(arr)/sizeof(arr[0]);\n    bucketSort(arr, n);\n \n    cout << \"Sorted array is \\n\";\n    for (int i=0; i<n; i++)\n       cout << arr[i] << \" \";\n    return 0;\n}"
  },
  {
    "path": "algorithms/bucket_sort/bucket_sort.java",
    "content": "//This is a java program to sort numbers using bucket sort\nimport java.util.Random;\n \npublic class Bucket_Sort \n{\n    static int[] sort(int[] sequence, int maxValue) \n    {\n        // Bucket Sort\n        int[] Bucket = new int[maxValue + 1];\n        int[] sorted_sequence = new int[sequence.length];\n \n        for (int i = 0; i < sequence.length; i++)\n            Bucket[sequence[i]]++;\n \n        int outPos = 0;\n        for (int i = 0; i < Bucket.length; i++)\n            for (int j = 0; j < Bucket[i]; j++)\n                sorted_sequence[outPos++] = i;\n \n        return sorted_sequence;\n    }\n \n    static void printSequence(int[] sorted_sequence) \n    {\n        for (int i = 0; i < sorted_sequence.length; i++)\n            System.out.print(sorted_sequence[i] + \" \");\n    }\n \n    static int maxValue(int[] sequence) \n    {\n        int maxValue = 0;\n        for (int i = 0; i < sequence.length; i++)\n            if (sequence[i] > maxValue)\n                maxValue = sequence[i];\n        return maxValue;\n    }\n \n    public static void main(String args[]) \n    {\n        System.out\n                .println(\"Sorting of randomly generated numbers using BUCKET SORT\");\n        Random random = new Random();\n        int N = 20;\n        int[] sequence = new int[N];\n \n        for (int i = 0; i < N; i++)\n            sequence[i] = Math.abs(random.nextInt(100));\n \n        int maxValue = maxValue(sequence);\n \n        System.out.println(\"\\nOriginal Sequence: \");\n        printSequence(sequence);\n \n        System.out.println(\"\\nSorted Sequence: \");\n        printSequence(sort(sequence, maxValue));\n    }\n}"
  },
  {
    "path": "algorithms/bucket_sort/bucket_sort.py",
    "content": "def bucketsort( A ):\n  # get hash codes\n  code = hashing( A )\n  buckets = [list() for _ in range( code[1] )]\n  # distribute data into buckets: O(n)\n  for i in A:\n    x = re_hashing( i, code )\n    buck = buckets[x]\n    buck.append( i )\n \n  # Sort each bucket: O(n).\n  # I mentioned above that the worst case for bucket sort is counting\n  # sort. That's because in the worst case, bucket sort may end up\n  # with one bucket per key. In such case, sorting each bucket would\n  # take 1^2 = O(1). Even after allowing for some probabilistic\n  # variance, to sort each bucket would still take 2-1/n, which is\n  # still a constant. Hence, sorting all the buckets takes O(n).\n \n  for bucket in buckets:\n    insertionsort( bucket )\n \n  ndx = 0\n  # merge the buckets: O(n)\n  for b in range( len( buckets ) ):\n    for v in buckets[b]:\n      A[ndx] = v\n      ndx += 1\n \nimport math\n \ndef hashing( A ):\n  m = A[0]\n  for i in range( 1, len( A ) ):\n    if ( m < A[i] ):\n      m = A[i]\n  result = [m, int( math.sqrt( len( A ) ) )]\n  return result\n \n \ndef re_hashing( i, code ):\n  return int( i / code[0] * ( code[1] - 1 ) )"
  },
  {
    "path": "algorithms/bucket_sort/c/bucket_sort.c",
    "content": "    /*\n\n     * C Program to Sort Array using Bucket Sort\n\n     */\n\n    #include <stdio.h>\n\n     \n\n    /* Function for bucket sort */\n\n    void Bucket_Sort(int array[], int n)\n\n    {  \n\n        int i, j;  \n\n        int count[n]; \n\n        for (i = 0; i < n; i++)\n\n            count[i] = 0;\n\n     \n\n        for (i = 0; i < n; i++)\n\n            (count[array[i]])++;\n\n     \n\n        for (i = 0, j = 0; i < n; i++)  \n\n            for(; count[i] > 0; (count[i])--)\n\n                array[j++] = i;\n\n    }   \n\n    /* End of Bucket_Sort() */\n\n     \n\n    /* The main() begins */\n\n    int main()\n\n    {\n\n        int array[100], i, num; \n\n     \n\n        printf(\"Enter the size of array : \");   \n\n        scanf(\"%d\", &num);   \n\n        printf(\"Enter the %d elements to be sorted:\\n\",num); \n\n        for (i = 0; i < num; i++)\n\n            scanf(\"%d\", &array[i]); \n\n        printf(\"\\nThe array of elements before sorting : \\n\");\n\n        for (i = 0; i < num; i++)\n\n            printf(\"%d \", array[i]);  \n\n        printf(\"\\nThe array of elements after sorting : \\n\"); \n\n        Bucket_Sort(array, num); \n\n        for (i = 0; i < num; i++)\n\n            printf(\"%d \", array[i]);   \n\n        printf(\"\\n\");     \n\n        return 0;\n\n    }\n"
  },
  {
    "path": "algorithms/caesar_cipher/java/caesar.java",
    "content": "/**\nAuthor : FAHRI YARDIMCI\nA Java implementation of Caesar Cipher.\n/It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. /\n**/\nimport java.util.Scanner;\npublic class Caesar {\npublic static String encode (String message,int shift)\n{\n\tString encoded = \"\";\n\tfor(int i = 0 ; i<message.length() ;i++)\n\t{\n\t\tint current = message.charAt(i); //using char to shift characters because ascii is in-order latin alphabet\n\t\tif(current==32)\n\t\t{\n\t\t\tencoded += \" \";\n\t\t\tcontinue;\n\n\t\t}\n\t\telse if (current>=65 && current<= 90)\n\t\t{\n\t\t\tint numAlphabet = message.charAt(i);\n\t\t\tif(shift + numAlphabet > 90)\n\t\t\t{\n\t\t\t\tint j = 90 - numAlphabet;\n\t\t\t\tchar nextKey = (char)(65 + (shift - j - 1));\n\t\t\t\tencoded += nextKey;\n\t\t\t\t\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tchar nextKey = (char)(current + shift);\n\t\t\t\tencoded += nextKey;\n\t\t\t}\n\t\t}\n\t\telse if (current>=97 && current <= 122)\n\t\t{\n\t\t\tint numAlphabet = message.charAt(i);\n\t\t\tif(shift + numAlphabet > 122)\n\t\t\t{\n\t\t\t\tint j = 122 - numAlphabet;\n\t\t\t\tchar nextKey = (char)(97 + (shift - j - 1));\n\t\t\t\tencoded += nextKey;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tchar nextKey = (char)(current + shift);\n\t\t\t\tencoded += nextKey;\n\t\t\t}\n\t\t}\n\t}\n\treturn encoded;\n}\npublic static String decode (String message,int shift)\n{\n\tString decoded = \"\";\n\tfor(int i = 0 ; i<message.length() ;i++)\n\t{\n\t\tint current = message.charAt(i);\n\t\tif(current==32)\n\t\t{\n\t\t\tdecoded += \" \";\n\t\t\tcontinue;\n\n\t\t}\n\t\telse if (current>=65 && current<= 90)\n\t\t{\n\t\t\tint numAlphabet = message.charAt(i);\n\t\t\tif(numAlphabet - shift < 65)\n\t\t\t{\n\t\t\t\tint j = numAlphabet - 65;\n\t\t\t\tchar nextKey = (char)(90 - (shift - j - 1));\n\t\t\t\tdecoded += nextKey;\n\t\t\t\t\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tchar nextKey = (char)(current - shift);\n\t\t\t\tdecoded += nextKey;\n\t\t\t}\n\t\t}\n\t\telse if (current>=97 && current <= 122)\n\t\t{\n\t\t\tint numAlphabet = message.charAt(i);\n\t\t\tif(numAlphabet - shift < 97)\n\t\t\t{\n\t\t\t\tint j = numAlphabet - 97;\n\t\t\t\tchar nextKey = (char)(122 - (shift - j - 1));\n\t\t\t\tdecoded += nextKey;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tchar nextKey = (char)(current - shift);\n\t\t\t\tdecoded += nextKey;\n\t\t\t}\n\t\t}\n\t}\n\treturn decoded;\n}\npublic static void main(String[] args)\n{\n\tScanner input = new Scanner(System.in);\n\tSystem.out.println(\"Please enter the message (Latin Alphabet)\");\n\tString message = input.nextLine();\n\tSystem.out.println(message);\n\tSystem.out.println(\"Please enter the shift number\");\n\tint shift = input.nextInt() % 26;\n\tSystem.out.println(\"(E)ncode or (D)ecode ?\");\n\tchar choice = input.next().charAt(0);\n\tif(choice == 'E' || choice=='e')\n\t\tSystem.out.println(\"ENCODED MESSAGE IS \\n\" + encode(message,shift)); //send our function to handle\n\tif(choice =='D' || choice =='d')\n\t\tSystem.out.println(\"DECODED MESSAGE IS \\n\" + decode(message,shift));\n}\n\n}\n"
  },
  {
    "path": "algorithms/caesar_cipher/javascript/caesarCipher.js",
    "content": "const LEGAL_VALUES = 'abcdefghijklmnopqrstuvwxyz';\nconst START_CODE = 'a'.charCodeAt(0);\nconst END_CODE = 'z'.charCodeAt(0);\n\nclass CaesarCipher {\n  constructor(key) {\n    if (key === undefined) {\n      this.generateKey();\n\n    } else {\n      this.key = key;\n      this.validateKey();\n    }\n  }\n\n  generateKey() {\n    this.key = '';\n\n    for (let i = 0; i < 100; i++) {\n      let randomIdx = Math.floor(Math.random() * 26);\n      this.key += LEGAL_VALUES.charAt(randomIdx);\n    }\n  }\n\n  validateKey() {\n    const emptyKey = this.key.length < 1;\n    const hasInvalidChars = this.key.split('').some(letter => {\n      return LEGAL_VALUES.indexOf(letter) === -1;\n    });\n\n    if (emptyKey || hasInvalidChars) {\n      throw new Error('Bad key');\n    }\n  }\n\n  encode(decodedMessage) {\n    let longKey = this.key;\n    let encodedMessage = \"\";\n\n    while (longKey.length < decodedMessage.length) {\n      longKey += longKey;\n    }\n\n    decodedMessage.split('').forEach((letter, idx) => {\n      const currentKeyCode = longKey.charCodeAt(idx);\n      const offset = (currentKeyCode - START_CODE);\n      let newCharCode = letter.charCodeAt(0) + offset;\n\n      if (newCharCode > END_CODE) {\n        newCharCode -= LEGAL_VALUES.length;\n      }\n\n      encodedMessage += String.fromCharCode(newCharCode);\n    });\n\n    return encodedMessage;\n  }\n\n  decode(encodedMessage) {\n    let longKey = this.key;\n    let decodedMessage = \"\";\n\n    while (longKey.length < encodedMessage.length) {\n      longKey += longKey;\n    }\n\n    encodedMessage.split('').forEach((letter, idx) => {\n      const currentKeyCode = longKey.charCodeAt(idx);\n      const offset = (currentKeyCode - START_CODE);\n      let newCharCode = letter.charCodeAt(0) - offset;\n\n      if (newCharCode < START_CODE) {\n        newCharCode += LEGAL_VALUES.length;\n      }\n\n      decodedMessage += String.fromCharCode(newCharCode);\n    });\n\n    return decodedMessage;\n  }\n}\n\nmodule.exports = CaesarCipher;\n"
  },
  {
    "path": "algorithms/check_pallindrome_number/c/checkPalindrome.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n\nint checkPall(char str[])\n{\n\tfor(int i = 0; i < strlen(str); i++)\n\t{\n\t\tif(str[i] != str[strlen(str)-i-1])\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\t}\n\treturn 1;\n}\nint main()\n{\n\tchar str[10000];\n\tgets(str);\n\tif(checkPall(str))\n\t{\n\t\tprintf(\"YES\");\n\t}\n\telse\n\t{\n\t\tprintf(\"NO\");\n\t}\n\treturn 0;\n}\n"
  },
  {
    "path": "algorithms/check_pallindrome_number/cpp/checkPall.cpp",
    "content": "#include <iostream>\n#include <cstring>\n#include <string>\nusing namespace std;\nint checkPall(char str[])\n{\n\tfor(int i = 0; i < strlen(str); i++)\n\t{\n\t\tif(str[i] != str[strlen(str)-i-1])\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\t}\n\treturn 1;\n}\nint main()\n{\n\tchar str[10000];\n\tcin >> str;\n\tif(checkPall(str))\n\t{\n\t\tcout << \"YES\" << endl;\n\t}\n\telse\n\t{\n\t\tcout << \"NO\" << endl;\n\t}\n\treturn 0;\n}\n"
  },
  {
    "path": "algorithms/closest/java/Closest.java",
    "content": "package algorithms.closest.java;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Scanner;\n\n/*\nThis algorithm searches through a list of integers and finds the distance between\nthe two closest element. It then prints this integer.\n */\npublic class Closest {\n    public static void main(String[] args) {\n        //get input\n        Scanner sc = new Scanner(System.in).useDelimiter(\" \");\n        ArrayList<Integer> input = new ArrayList<>();\n        //add input to ArrayList\n        while (sc.hasNextInt()) {\n            input.add(sc.nextInt());\n        }\n        //sort the list\n        Collections.sort(input);\n        //initialize closest values, with the first two elements in the list\n        int closest = input.get(1)-input.get(0);\n        //check all elements in the list\n        for(int i = 2; i < input.size(); i++) {\n            //change closest if we find two elements with a shorter distance.\n            closest = Math.min(closest, input.get(i)-input.get(i-1));\n        }\n        //print the shortest distance\n        System.out.println(closest);\n    }\n}\n"
  },
  {
    "path": "algorithms/count_sort/javascript/count_sort.js",
    "content": "\"use strict\";\nvar countSort = (arr, range)=>{\n    /**\n     * Consider the input is in range of 1 to 9\n      */\n    // this can vary depending on your input array\n    let countArr = [];\n    //Initialise count array to 0;\n    for(let i=0; i <= range; i++){\n        countArr[i] = 0;\n    }\n    for(let i=0; i < arr.length; i++){\n        ++countArr[arr[i]];\n    }\n    for(let i=1; i<= countArr.length-1; i++){\n        countArr[i] += countArr[i-1];\n    }\n    //Take the sorted array and insert the data of input array based on the count array and\n    // decrease the value by 1 every time the element is inserted in sorted array\n\n    let sortedArray = new Array(arr.length -1);\n    for(let i=0; i<arr.length; i++){\n        sortedArray[countArr[arr[i]]-1] = arr[i];\n        --countArr[arr[i]];\n    }\n return sortedArray;    \n}\nlet arr = [2,1,3,4,5,4,6,7,6];\nlet range = 9;\nlet sortedArray = countSort(arr, range);\nconsole.log(sortedArray);"
  },
  {
    "path": "algorithms/cycle_sort/java/cycleSort.java",
    "content": "// Java program to impleament cycle sort\n\nimport java.util.*;\nimport java.lang.*;\n\nclass GFG\n{\n// Function sort the array using Cycle sort\n\tpublic static void cycleSort (int arr[], int n)\n\t{\n\t\t// count number of memory writes\n\t\tint writes = 0;\n\n\t\t// traverse array elements and put it to on\n\t\t// the right place\n\t\tfor (int cycle_start=0; cycle_start<=n-2; cycle_start++)\n\t\t{\n\t\t\t// initialize item as starting point\n\t\t\tint item = arr[cycle_start];\n\n\t\t\t// Find position where we put the item. We basically\n\t\t\t// count all smaller elements on right side of item.\n\t\t\tint pos = cycle_start;\n\t\t\tfor (int i = cycle_start+1; i<n; i++)\n\t\t\t\tif (arr[i] < item)\n\t\t\t\t\tpos++;\n\n\t\t\t// If item is already in correct position\n\t\t\tif (pos == cycle_start)\n\t\t\t\tcontinue;\n\n\t\t\t// ignore all duplicate elements\n\t\t\twhile (item == arr[pos])\n\t\t\t\tpos += 1;\n\n\t\t\t// put the item to it's right position\n\t\t\tif (pos != cycle_start)\n\t\t\t{\n\t\t\t\tint temp = item;\n\t\t\t\titem = arr[pos];\n\t\t\t\tarr[pos] = temp;\n\t\t\t\twrites++;\n\t\t\t}\n\n\t\t\t// Rotate rest of the cycle\n\t\t\twhile (pos != cycle_start)\n\t\t\t{\n\t\t\t\tpos = cycle_start;\n\n\t\t\t\t// Find position where we put the element\n\t\t\t\tfor (int i = cycle_start+1; i<n; i++)\n\t\t\t\t\tif (arr[i] < item)\n\t\t\t\t\t\tpos += 1;\n\n\t\t\t\t// ignore all duplicate elements\n\t\t\t\twhile (item == arr[pos])\n\t\t\t\t\tpos += 1;\n\n\t\t\t\t// put the item to it's right position\n\t\t\t\tif (item != arr[pos])\n\t\t\t\t{\n\t\t\t\t\tint temp = item;\n\t\t\t\t\titem = arr[pos];\n\t\t\t\t\tarr[pos] = temp;\n\t\t\t\t\twrites++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n// Driver program to test above function\n\tpublic static void main(String[] args)\n\t{\n\t\tint arr[] = {1, 8, 3, 9, 10, 10, 2, 4 };\n\t\tint n = arr.length;\n\t\tcycleSort(arr, n) ;\n\n\t\tSystem.out.println(\"After sort : \");\n\t\tfor (int i =0; i<n; i++)\n\t\t\tSystem.out.print(arr[i] + \" \");\n\t}\n}\n"
  },
  {
    "path": "algorithms/decoding/c/base64_decoder.c",
    "content": "// C implementation of base64 decoder for converting radix-64 representation into ASCII string format\n#include<stdio.h>\n#include<math.h>\n#include<stdlib.h>\n#include<string.h>\n\n\nstatic char b64_arr[] = {\n    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',\n    'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',\n    'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',\n    'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',\n    'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',\n    'o', 'p', 'q', 'r', 's', 't', 'u', 'v',\n    'w', 'x', 'y', 'z', '0', '1', '2', '3',\n    '4', '5', '6', '7', '8', '9', '+', '/'};\n\nint val(char x){\n    for (int i = 0; i < 64; ++i){\n        if(x == b64_arr[i]) return i;\n    }\n    return -1;\n}\n\nint main() {\n    char *str = \"TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=\";\n    int in = -1;\n    int len = strlen(str);\n    int outlen = (int)ceil(len/4.0)*3;\n    char *result = (char *)malloc(sizeof(char)*outlen);\n    for (int i = 0; i < len; i += 4) {\n        int x = 0;\n        if(str[i+2] != '=' && str[i+3] != '='){\n            x |= (val(str[i]) << 18);\n            x |= (val(str[i+1]) << 12);\n            x |= (val(str[i+2]) << 6);\n            x |= (val(str[i+3]));\n            result[++in] = (x >> 16) & (0xFF);\n            result[++in] = (x >> 8) & (0xFF);\n            result[++in] = (x) & (0xFF);\n        }\n        else if(str[i+2] != '='){\n            x |= (val(str[i]) << 18);\n            x |= (val(str[i+1]) << 12);\n            x |= (val(str[i+2]) << 6);\n            result[++in] = (x >> 16) & (0xFF);\n            result[++in] = (x >> 8) & (0xFF);\n        }\n        else{\n            x |= (val(str[i]) << 18);\n            x |= (val(str[i+1]) << 12);\n            result[++in] = (x >> 16) & (0xFF);\n        }\n    }\n    if(in < outlen) result[++in] = '\\0';\n    printf(\"%s\\n\", result);\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/dfs/cpp/dfs.cpp",
    "content": "\n\n#import <vector>\n#import <queue>\n#import <iostream>\n\n\nclass Vertex {\npublic:\n    Vertex(std::string n);\n\n    bool visited;\n    Vertex * prev; //predecessor\n    int dist;\n    std::string name;\n    std::vector <Vertex *> neighbours;\n};\n\nVertex::Vertex(std::string n) {\n    prev = nullptr;\n    dist = -1;\n    name = n;\n}\n\nvoid VisitVertex(Vertex *v, Vertex * predecessor){\n    v->prev = predecessor;\n    v->visited = true;\n    for (Vertex * successor : v->neighbours) {\n        if (!successor->visited)\n            VisitVertex(successor,v);\n    }\n}\n\nvoid DFS(std::vector <Vertex *> graph){\n    Vertex * predecessor = nullptr;\n    for (Vertex * v: graph ) {\n        v->visited = false;\n    }\n    for (Vertex * v: graph ) {\n        if (!v->visited)\n            VisitVertex(v, predecessor);\n        predecessor = v;\n    }\n\n}\n\nint main() {\n\n    //testing\n\n    Vertex v1(\"v1\");\n    Vertex v2(\"v2\");\n    Vertex v3(\"v3\");\n    Vertex v4(\"v4\");\n    v1.neighbours.emplace_back(&v2);\n    v1.neighbours.emplace_back(&v3);\n    v4.neighbours.emplace_back(&v3);\n    v3.neighbours.emplace_back(&v4);\n    v1.neighbours.emplace_back(&v4);\n\n    std::vector <Vertex *> graph;\n    graph.emplace_back(&v1);\n    graph.emplace_back(&v2);\n    graph.emplace_back(&v3);\n    graph.emplace_back(&v4);\n\n    DFS(graph);\n    std::cout << \"v1 prev: \" << v1.prev <<std::endl;\n    std::cout << \"v2 prev: \" << v2.prev->name <<std::endl;\n    std::cout << \"v3 prev: \" << v3.prev->name <<std::endl;\n    std::cout << \"v4 prev: \" << v4.prev->name <<std::endl;\n    return 0;\n}"
  },
  {
    "path": "algorithms/dfs/java/Graph.java",
    "content": "import java.util.*;\n\n/**\n * Represents a directed graph using adjacency list\n */\nclass Graph {\n    private int vertexNumber;\n    private LinkedList<Integer> adj[];\n\n    /**\n     *\n     * @param v number of vertex\n     */\n    Graph(int v) {\n        vertexNumber = v;\n        adj = new LinkedList[v];\n        for (int i=0; i<v; ++i)\n            adj[i] = new LinkedList();\n    }\n\n    /**\n     * Add edge into graph\n     * @param v vertex\n     * @param w vertex\n     */\n    public void addEdge(int v, int w)  {\n        adj[v].add(w);\n    }\n\n    /**\n     *\n     * @param v\n     * @param visited\n     */\n    private void DFSUtil(int v, boolean visited[])  {\n        visited[v] = true;\n        System.out.print(v + \" \");\n\n        for (Integer n : adj[v]) {\n            if (!visited[n])\n                DFSUtil(n, visited);\n        }\n    }\n\n    /**\n     * To do DFS traversal. It uses recursive DFSUtil()\n     * @param source source vertex\n     */\n    void DFS(int source) {\n        boolean[] visited = new boolean[vertexNumber];\n\n        DFSUtil(source, visited);\n    }\n\n    /**\n     * Test\n     * @param args\n     */\n    public static void main(String args[]) {\n        Graph g = new Graph(4);\n\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        g.DFS(2);\n    }\n}"
  },
  {
    "path": "algorithms/dfs/python/Dfs.py",
    "content": "__author__ = 'mittr'\n   # Python program to print DFS traversal from a\n# given given graph\nfrom collections import defaultdict\n\n# This class represents a directed graph using\n# 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    # A function used by DFS\n    def DFSUtil(self,v,visited):\n\n        # Mark the current node as visited and print it\n        visited[v]= True\n        print (v),\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.DFSUtil(i, visited)\n\n\n    # The function to do DFS traversal. It uses\n    # recursive DFSUtil()\n    def DFS(self,v):\n\n        # Mark all the vertices as not visited\n        visited = [False]*(len(self.graph))\n\n        # Call the recursive helper function to print\n        # DFS traversal\n        self.DFSUtil(v,visited)\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 DFS from (starting from vertex 2)\")\ng.DFS(2)\n"
  },
  {
    "path": "algorithms/dijkstra/cpp/Dijkstras.cpp",
    "content": "// A C / C++ program for Dijkstra's single source shortest path algorithm.\n// The program is for adjacency matrix representation of the graph\n\n#include <stdio.h>\n#include <limits.h>\n\n// Number of vertices in the graph\n#define V 9\n\n// A utility function to find the vertex with minimum distance value, from\n// the set of vertices not yet included in shortest path tree\nint minDistance(int dist[], bool sptSet[])\n{\n// Initialize min value\nint min = INT_MAX, min_index;\n\nfor (int v = 0; v < V; v++)\n\tif (sptSet[v] == false && dist[v] <= min)\n\t\tmin = dist[v], min_index = v;\n\nreturn min_index;\n}\n\n// A utility function to print the constructed distance array\nint printSolution(int dist[], int n)\n{\nprintf(\"Vertex Distance from Sourcen\");\nfor (int i = 0; i < V; i++)\n\tprintf(\"%d tt %dn\", i, dist[i]);\n}\n\n// Funtion that implements Dijkstra's single source shortest path algorithm\n// for a graph represented using adjacency matrix representation\nvoid dijkstra(int graph[V][V], int src)\n{\n\tint dist[V];\t // The output array. dist[i] will hold the shortest\n\t\t\t\t\t// distance from src to i\n\n\tbool sptSet[V]; // sptSet[i] will true if vertex i is included in shortest\n\t\t\t\t\t// path tree or shortest distance from src to i is finalized\n\n\t// Initialize all distances as INFINITE and stpSet[] as false\n\tfor (int i = 0; i < V; i++)\n\t\tdist[i] = INT_MAX, sptSet[i] = false;\n\n\t// Distance of source vertex from itself is always 0\n\tdist[src] = 0;\n\n\t// Find shortest path for all vertices\n\tfor (int count = 0; count < V-1; count++)\n\t{\n\t// Pick the minimum distance vertex from the set of vertices not\n\t// yet processed. u is always equal to src in first iteration.\n\tint u = minDistance(dist, sptSet);\n\n\t// Mark the picked vertex as processed\n\tsptSet[u] = true;\n\n\t// Update dist value of the adjacent vertices of the picked vertex.\n\tfor (int v = 0; v < V; v++)\n\n\t\t// Update dist[v] only if is not in sptSet, there is an edge from\n\t\t// u to v, and total weight of path from src to v through u is\n\t\t// smaller than current value of dist[v]\n\t\tif (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX\n\t\t\t\t\t\t\t\t\t&& dist[u]+graph[u][v] < dist[v])\n\t\t\tdist[v] = dist[u] + graph[u][v];\n\t}\n\n\t// print the constructed distance array\n\tprintSolution(dist, V);\n}\n\n// driver program to test above function\nint main()\n{\n/* Let us create the example graph discussed above */\nint graph[V][V] = {{0, 4, 0, 0, 0, 0, 0, 8, 0},\n\t\t\t\t\t{4, 0, 8, 0, 0, 0, 0, 11, 0},\n\t\t\t\t\t{0, 8, 0, 7, 0, 4, 0, 0, 2},\n\t\t\t\t\t{0, 0, 7, 0, 9, 14, 0, 0, 0},\n\t\t\t\t\t{0, 0, 0, 9, 0, 10, 0, 0, 0},\n\t\t\t\t\t{0, 0, 4, 14, 10, 0, 2, 0, 0},\n\t\t\t\t\t{0, 0, 0, 0, 0, 2, 0, 1, 6},\n\t\t\t\t\t{8, 11, 0, 0, 0, 0, 1, 0, 7},\n\t\t\t\t\t{0, 0, 2, 0, 0, 0, 6, 7, 0}\n\t\t\t\t\t};\n\n\tdijkstra(graph, 0);\n\n\treturn 0;\n}\n"
  },
  {
    "path": "algorithms/dijkstra/java/ShortestPath.java",
    "content": "/**\n * A Java program for Dijkstra's single source shortest path algorithm.\n * The program is for adjacency matrix representation of the graph\n */\npublic class ShortestPath {\n    private static final int vertexNumber = 9;\n\n    private int minDistance(int dist[], Boolean sptSet[]) {\n        int min = Integer.MAX_VALUE;\n        int minIndex = -1;\n\n        for (int v = 0; v < vertexNumber; v++) {\n            if (!sptSet[v] && dist[v] <= min) {\n                min = dist[v];\n                minIndex = v;\n            }\n        }\n\n        return minIndex;\n    }\n\n    private void printSolution(int dist[]) {\n        System.out.println(\"Vertex   Distance from Source\");\n        for (int i = 0; i < vertexNumber; i++)\n            System.out.println(i + \" \\t\\t \" + dist[i]);\n    }\n\n    /**\n     * Dijkstra's single source shortest path\n     *\n     * @param graph The graph represented using adjacency matrix\n     * @param source Source vertex\n     */\n    public void dijkstra(int graph[][], int source) {\n        int dist[] = new int[vertexNumber];\n\n        Boolean sptSet[] = new Boolean[vertexNumber];\n\n        for (int i = 0; i < vertexNumber; i++) {\n            dist[i] = Integer.MAX_VALUE;\n            sptSet[i] = false;\n        }\n\n        dist[source] = 0;\n\n        for (int count = 0; count < vertexNumber-1; count++) {\n            int u = minDistance(dist, sptSet);\n\n            sptSet[u] = true;\n\n            for (int v = 0; v < vertexNumber; v++) {\n                if (!sptSet[v] && graph[u][v] != 0 &&\n                        dist[u] != Integer.MAX_VALUE &&\n                        dist[u] + graph[u][v] < dist[v]) {\n                    dist[v] = dist[u] + graph[u][v];\n                }\n            }\n        }\n\n        printSolution(dist);\n    }\n\n    /**\n     * Usage\n     * @param args\n     */\n    public static void main (String[] args) {\n        int graph[][] = new int[][]{{0, 4, 0, 0, 0, 0, 0, 8, 0},\n                {4, 0, 8, 0, 0, 0, 0, 11, 0},\n                {0, 8, 0, 7, 0, 4, 0, 0, 2},\n                {0, 0, 7, 0, 9, 14, 0, 0, 0},\n                {0, 0, 0, 9, 0, 10, 0, 0, 0},\n                {0, 0, 4, 14, 10, 0, 2, 0, 0},\n                {0, 0, 0, 0, 0, 2, 0, 1, 6},\n                {8, 11, 0, 0, 0, 0, 1, 0, 7},\n                {0, 0, 2, 0, 0, 0, 6, 7, 0}\n        };\n\n        ShortestPath t = new ShortestPath();\n        t.dijkstra(graph, 0);\n    }\n}"
  },
  {
    "path": "algorithms/dijkstra/python/djikstra.py",
    "content": "class Graph:\n  def __init__(self):\n    self.nodes = set()\n    self.edges = defaultdict(list)\n    self.distances = {}\n\n  def add_node(self, value):\n    self.nodes.add(value)\n\n  def add_edge(self, from_node, to_node, distance):\n    self.edges[from_node].append(to_node)\n    self.edges[to_node].append(from_node)\n    self.distances[(from_node, to_node)] = distance\n\n\ndef dijsktra(graph, initial):\n  visited = {initial: 0}\n  path = {}\n\n  nodes = set(graph.nodes)\n\n  while nodes: \n    min_node = None\n    for node in nodes:\n      if node in visited:\n        if min_node is None:\n          min_node = node\n        elif visited[node] < visited[min_node]:\n          min_node = node\n\n    if min_node is None:\n      break\n\n    nodes.remove(min_node)\n    current_weight = visited[min_node]\n\n    for edge in graph.edges[min_node]:\n      weight = current_weight + graph.distances[(min_node, edge)]\n      if edge not in visited or weight < visited[edge]:\n        visited[edge] = weight\n        path[edge] = min_node\n\n  return visited, path\n"
  },
  {
    "path": "algorithms/doomsday/java/doomsday.java",
    "content": "/**\n * Determines the day of the week.\n * \n * @author Atom\n *\n */\npublic class Doomsday {\n\t\n\t/**\n\t * Determines the day of the week using Tomohiko Sakamoto's Algorithm\n\t * to calculate Day of Week based on Gregorian calendar.\n\t * \n\t * @param y year\n\t * @param m month\n\t * @param d day\n\t * @return day of the week (0 = sunday, 6 = saturday)\n\t */\n\tpublic static int dow(int y, int m, int d) {\n\t\tfinal int[] t = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 };\n\t\ty -= (m < 3) ? 1 : 0;\n\t    return (y + y/4 - y/100 + y/400 + t[m-1] + d) % 7;\n\t}\n\t\n\t/**\n\t * Determines the day of the week using Tomohiko Sakamoto's Algorithm\n\t * to calculate Day of Week based on Gregorian calendar.\n\t * \n\t * @param y year\n\t * @param m month\n\t * @param d day\n\t * @return day of the week\n\t */\n\tpublic static String dowS(int y, int m, int d) {\n\t\tswitch (dow(y, m, d)) {\n\t\t\tcase 0: return \"Sunday\";\n\t\t\tcase 1: return \"Monday\";\n\t\t\tcase 2: return \"Tuesday\";\n\t\t\tcase 3: return \"Wednesday\";\n\t\t\tcase 4: return \"Thursday\";\n\t\t\tcase 5: return \"Friday\";\n\t\t\tcase 6: return \"Saturday\";\n\t\t\tdefault:\n\t\t\t\tSystem.out.println(\"Unknown dow\");\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(dow(1886, 5, 1) + \": \" + dowS(1886, 5, 1));\n\t\tSystem.out.println(dow(1948, 12, 10) + \": \" + dowS(1948, 12, 10));\n\t\tSystem.out.println(dow(2001, 1, 15) + \": \" + dowS(2001, 1, 15));\n\t\tSystem.out.println(dow(2017, 10, 10) + \": \" + dowS(2017, 10, 10));\n\t\tSystem.out.println(dow(2018, 1, 1) + \": \" + dowS(2018, 1, 1));\n\t\tSystem.out.println(dow(2018, 2, 16) + \": \" + dowS(2018, 2, 16));\n\t\tSystem.out.println(dow(2018, 5, 17) + \": \" + dowS(2018, 5, 17));\n\t}\n\n}\n"
  },
  {
    "path": "algorithms/doomsday/javascript/doomsday.js",
    "content": "function dayOfTheWeek(y, m, d) {\n    const t = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4]\n    y -= m < 3;\n    return (y + Math.floor(y/4) - Math.floor(y/100) + Math.floor(y/400) + t[m-1] + d) % 7;\n}\n\nconst dayMapping = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']\n\nconst tests = [\n    [1886, 5, 1],\n    [1948, 12, 10],\n    [2001, 1, 15],\n    [2017, 10, 10],\n    [2018, 1, 1],\n    [2018, 2, 16],\n    [2018, 5, 17],\n]\n\ntests.forEach(test => console.log(test.join('/') + ': ' + dayMapping[dayOfTheWeek(...test)]))\n"
  },
  {
    "path": "algorithms/dynamic_programming/c/0_1_knapsack_problem.c",
    "content": "// A Dynamic Programming based solution for 0-1 Knapsack problem\n#include<stdio.h>\n\n// A utility function that returns maximum of two integers\nint max(int a, int b) { return (a > b)? a : b; }\n\n// Returns the maximum value that can be put in a knapsack of capacity W\nint knapSack(int W, int wt[], int val[], int n)\n{\n   int i, w;\n   int K[n+1][W+1];\n\n   // Build table K[][] in bottom up manner\n   for (i = 0; i <= n; i++)\n   {\n       for (w = 0; w <= W; w++)\n       {\n           if (i==0 || w==0)\n               K[i][w] = 0;\n           else if (wt[i-1] <= w)\n                 K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]],  K[i-1][w]);\n           else\n                 K[i][w] = K[i-1][w];\n       }\n   }\n\n   return K[n][W];\n}\n\nint main()\n{\n    int val[] = {60, 100, 120};\n    int wt[] = {10, 20, 30};\n    int  W = 50;\n    int n = sizeof(val)/sizeof(val[0]);\n    printf(\"%d\", knapSack(W, wt, val, n));\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/dynamic_programming/c/Coin_change_DP.c",
    "content": "//Coin change problem : \n/*\nGiven a value N, if we want to make change for N cents, and we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins, how many ways can we make the change? \nThe order of coins doesn’t matter.\n\nFor example, for N = 4 and S = {1,2,3}, there are four solutions: \n{1,1,1,1},{1,1,2},{2,2},{1,3}. \nSo output should be 4. \n\nFor N = 10 and S = {2, 5, 3, 6}, there are five solutions: {2,2,2,2,2}, {2,2,3,3}, {2,2,6}, {2,3,5} and {5,5}. \nSo the output should be 5.\n*/\n\n\n#include<stdio.h>\n \nint count( int S[], int m, int n )\n{\n    int i, j, x, y;\n \n    // We need n+1 rows as the table is consturcted in bottom up manner using \n    // the base case 0 value case (n = 0)\n    int table[n+1][m];\n    \n    // Fill the enteries for 0 value case (n = 0)\n    for (i=0; i<m; i++)\n        table[0][i] = 1;\n \n    // Fill rest of the table enteries in bottom up manner  \n    for (i = 1; i < n+1; i++)\n    {\n        for (j = 0; j < m; j++)\n        {\n            // Count of solutions including S[j]\n            x = (i-S[j] >= 0)? table[i - S[j]][j]: 0;\n \n            // Count of solutions excluding S[j]\n            y = (j >= 1)? table[i][j-1]: 0;\n \n            // total count\n            table[i][j] = x + y;\n        }\n    }\n    return table[n][m-1];\n}\n \n// Driver program to test above function\nint main()\n{\n    int arr[] = {1, 2, 3};\n    int m = sizeof(arr)/sizeof(arr[0]);\n    int n = 4;\n    printf(\" %d \", count(arr, m, n));\n    return 0;\n}"
  },
  {
    "path": "algorithms/dynamic_programming/c/coinChange.c",
    "content": "#include<stdio.h>\nint count( int S[], int m, int n )\n{\n    // table[i] will be storing the number of solutions for\n    // value i. We need n+1 rows as the table is consturcted\n    // in bottom up manner using the base case (n = 0)\n    int table[n+1];\n \n    // Initialize all table values as 0\n    memset(table, 0, sizeof(table));\n \n    // Base case (If given value is 0)\n    table[0] = 1;\n \n    // Pick all coins one by one and update the table[] values\n    // after the index greater than or equal to the value of the\n    // picked coin\n    for(int i=0; i<m; i++)\n        for(int j=S[i]; j<=n; j++)\n            table[j] += table[j-S[i]];\n \n    return table[n];\n}\nint main()\n{\n    int arr[] = {1, 2, 3};\n    int m = sizeof(arr)/sizeof(arr[0]);\n    int n = 4;\n    printf(\" %d \", count(arr, m, n));\n    return 0;\n}"
  },
  {
    "path": "algorithms/dynamic_programming/c/count_no_of_ways_to_reach_nth_stair.c",
    "content": "// A C program to count number of ways to reach n't stair when\n// a person can climb 1, 2, ..m stairs at a time\n#include<stdio.h>\n\n// A recursive function used by countWays\nint countWaysUtil(int n, int m)\n{\n    int res[n];\n    res[0] = 1; res[1] = 1;\n    for (int i=2; i<n; i++)\n    {\n       res[i] = 0;\n       for (int j=1; j<=m && j<=i; j++)\n         res[i] += res[i-j];\n    }\n    return res[n-1];\n}\n\n// Returns number of ways to reach s'th stair\nint countWays(int s, int m)\n{\n    return countWaysUtil(s+1, m);\n}\n\n// Driver program to test above functions\nint main ()\n{\n    int s = 4, m = 2;\n    printf(\"Nuber of ways = %d\", countWays(s, m));\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/dynamic_programming/c/longestIncreasingSubsequence.c",
    "content": "/* Dynamic Programming C/C++ implementation of LIS problem */\n#include<stdio.h>\n#include<stdlib.h>\n \n/* lis() returns the length of the longest increasing\n  subsequence in arr[] of size n */\nint lis( int arr[], int n )\n{\n    int *lis, i, j, max = 0;\n    lis = (int*) malloc ( sizeof( int ) * n );\n \n    /* Initialize LIS values for all indexes */\n    for (i = 0; i < n; i++ )\n        lis[i] = 1;\n \n    /* Compute optimized LIS values in bottom up manner */\n    for (i = 1; i < n; i++ )\n        for (j = 0; j < i; j++ ) \n            if ( arr[i] > arr[j] && lis[i] < lis[j] + 1)\n                lis[i] = lis[j] + 1;\n \n    /* Pick maximum of all LIS values */\n    for (i = 0; i < n; i++ )\n        if (max < lis[i])\n            max = lis[i];\n \n    /* Free memory to avoid memory leak */\n    free(lis);\n \n    return max;\n}\n \n/* Driver program to test above function */\nint main()\n{\n    int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 };\n    int n = sizeof(arr)/sizeof(arr[0]);\n    printf(\"Length of lis is %dn\", lis( arr, n ) );\n    return 0;\n}"
  },
  {
    "path": "algorithms/dynamic_programming/c/longestRepeatedSequence.c",
    "content": "// C++ program to find the longest repeated\n// subsequence\n#include <bits/stdc++.h>\nusing namespace std;\n \n// This function mainly returns LCS(str, str)\n// with a condition that same characters at\n// same index are not considered.\nstring longestRepeatedSubSeq(string str)\n{\n    // THIS PART OF CODE IS SAME AS BELOW POST. \n    // IT FILLS dp[][]\n    // http://www.geeksforgeeks.org/longest-repeating-subsequence/\n    // OR the code mentioned above.\n    int n = str.length();\n    int dp[n+1][n+1];\n    for (int i=0; i<=n; i++)\n        for (int j=0; j<=n; j++)\n            dp[i][j] = 0;\n    for (int i=1; i<=n; i++)\n        for (int j=1; j<=n; j++)\n            if (str[i-1] == str[j-1] && i != j)\n                dp[i][j] =  1 + dp[i-1][j-1];\n            else\n                dp[i][j] = max(dp[i][j-1], dp[i-1][j]);\n \n \n    // THIS PART OF CODE FINDS THE RESULT STRING USING DP[][]\n    // Initialize result\n    string res = \"\";\n \n    // Traverse dp[][] from bottom right\n    int i = n, j = n;\n    while (i > 0 && j > 0)\n    {\n        // If this cell is same as diagonally\n        // adjacent cell just above it, then \n        // same characters are present at \n        // str[i-1] and str[j-1]. Append any \n        // of them to result.\n        if (dp[i][j] == dp[i-1][j-1] + 1)\n        {\n           res = res + str[i-1];\n           i--;\n           j--;\n        }\n \n        // Otherwise we move to the side\n        // that that gave us maximum result\n        else if (dp[i][j] == dp[i-1][j])\n            i--;\n        else\n            j--;\n    }\n \n    // Since we traverse dp[][] from bottom,\n    // we get result in reverse order.\n    reverse(res.begin(), res.end());\n \n    return res;\n}\n \n// Driver Program\nint main()\n{\n    string str = \"AABEBCDD\";\n    cout << longestRepeatedSubSeq(str);\n    return 0;\n}"
  },
  {
    "path": "algorithms/dynamic_programming/c/longest_pallindrome_sequence.c",
    "content": "# A Dynamic Programming based Python program for LPS problem\n# Returns the length of the longest palindromic subsequence in seq\n#include<stdio.h>\n#include<string.h>\n\n// A utility function to get max of two integers\nint max (int x, int y) { return (x > y)? x : y; }\n\n// Returns the length of the longest palindromic subsequence in seq\nint lps(char *str)\n{\n   int n = strlen(str);\n   int i, j, cl;\n   int L[n][n];  // Create a table to store results of subproblems\n\n\n   // Strings of length 1 are palindrome of lentgh 1\n   for (i = 0; i < n; i++)\n      L[i][i] = 1;\n\n    // Build the table. Note that the lower diagonal values of table are\n    // useless and not filled in the process. The values are filled in a\n    // manner similar to Matrix Chain Multiplication DP solution (See\n    // http://www.geeksforgeeks.org/archives/15553). cl is length of\n    // substring\n    for (cl=2; cl<=n; cl++)\n    {\n        for (i=0; i<n-cl+1; i++)\n        {\n            j = i+cl-1;\n            if (str[i] == str[j] && cl == 2)\n               L[i][j] = 2;\n            else if (str[i] == str[j])\n               L[i][j] = L[i+1][j-1] + 2;\n            else\n               L[i][j] = max(L[i][j-1], L[i+1][j]);\n        }\n    }\n\n    return L[0][n-1];\n}\n\n/* Driver program to test above functions */\nint main()\n{\n    char seq[] = \"GEEKS FOR GEEKS\";\n    int n = strlen(seq);\n    printf (\"The lnegth of the LPS is %d\", lps(seq));\n    getchar();\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/dynamic_programming/c/maxSumIncSequence.c",
    "content": "/* Dynamic Programming implementation of Maximum Sum Increasing\nSubsequence (MSIS) problem */\n#include<stdio.h>\n \n/* maxSumIS() returns the maximum sum of increasing subsequence\n    in arr[] of size n */\nint maxSumIS( int arr[], int n )\n{\n    int i, j, max = 0;\n    int msis[n];\n \n    /* Initialize msis values for all indexes */\n    for ( i = 0; i < n; i++ )\n        msis[i] = arr[i];\n \n    /* Compute maximum sum values in bottom up manner */\n    for ( i = 1; i < n; i++ )\n        for ( j = 0; j < i; j++ )\n            if ( arr[i] > arr[j] && msis[i] < msis[j] + arr[i])\n                msis[i] = msis[j] + arr[i];\n \n    /* Pick maximum of all msis values */\n    for ( i = 0; i < n; i++ )\n        if ( max < msis[i] )\n            max = msis[i];\n \n    return max;\n}\n \n/* Driver program to test above function */\nint main()\n{\n    int arr[] = {1, 101, 2, 3, 100, 4, 5};\n    int n = sizeof(arr)/sizeof(arr[0]);\n    printf(\"Sum of maximum sum increasing subsequence is %dn\",\n           maxSumIS( arr, n ) );\n    return 0;\n}"
  },
  {
    "path": "algorithms/dynamic_programming/c/subsetSum.c",
    "content": "// A recursive solution for subset sum problem\n#include <stdio.h>\n \n// Returns true if there is a subset of set[] with sun equal to given sum\nbool isSubsetSum(int set[], int n, int sum)\n{\n   // Base Cases\n   if (sum == 0)\n     return true;\n   if (n == 0 && sum != 0)\n     return false;\n \n   // If last element is greater than sum, then ignore it\n   if (set[n-1] > sum)\n     return isSubsetSum(set, n-1, sum);\n \n   /* else, check if sum can be obtained by any of the following\n      (a) including the last element\n      (b) excluding the last element   */\n   return isSubsetSum(set, n-1, sum) || \n                        isSubsetSum(set, n-1, sum-set[n-1]);\n}\n \n// Driver program to test above function\nint main()\n{\n  int set[] = {3, 34, 4, 12, 5, 2};\n  int sum = 9;\n  int n = sizeof(set)/sizeof(set[0]);\n  if (isSubsetSum(set, n, sum) == true)\n     printf(\"Found a subset with given sum\");\n  else\n     printf(\"No subset with given sum\");\n  return 0;\n}"
  },
  {
    "path": "algorithms/dynamic_programming/cpp/kadens.cpp",
    "content": "// C++ program to print largest contiguous array sum\n#include<iostream>\n#include<climits>\nusing namespace std;\n \nint maxSubArraySum(int a[], int size)\n{\n    int max_so_far = INT_MIN, max_ending_here = 0;\n \n    for (int i = 0; i < size; i++)\n    {\n        max_ending_here = max_ending_here + a[i];\n        if (max_so_far < max_ending_here)\n            max_so_far = max_ending_here;\n \n        if (max_ending_here < 0)\n            max_ending_here = 0;\n    }\n    return max_so_far;\n}\n \n/*Driver program to test maxSubArraySum*/\nint main()\n{\n    int a[] = {-2, -3, 4, -1, -2, 1, 5, -3};\n    int n = sizeof(a)/sizeof(a[0]);\n    int max_sum = maxSubArraySum(a, n);\n    cout << \"Maximum contiguous sum is \" << max_sum;\n    return 0;\n}"
  },
  {
    "path": "algorithms/dynamic_programming/cpp/nCr.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\n \n// Returns nCr % p\nint nCrModp(int n, int r, int p)\n{\n    // The array C is going to store last row of\n    // pascal triangle at the end. And last entry\n    // of last row is nCr\n    int C[r+1];\n    memset(C, 0, sizeof(C));\n \n    C[0] = 1; // Top row of Pascal Triangle\n \n    // One by constructs remaining rows of Pascal\n    // Triangle from top to bottom\n    for (int i = 1; i <= n; i++)\n    {\n        // Fill entries of current row using previous\n        // row values\n        for (int j = min(i, r); j > 0; j--)\n \n            // nCj = (n-1)Cj + (n-1)C(j-1);\n            C[j] = (C[j] + C[j-1])%p;\n    }\n    return C[r];\n}\n \n// Driver program\nint main()\n{\n    int n = 10, r = 2, p = 13;\n    cout << \"Value of nCr % p is \" << nCrModp(n, r, p);\n    return 0;\n}"
  },
  {
    "path": "algorithms/dynamic_programming/cpp/subset_sum.cpp",
    "content": "#include<bits/stdc++.h>\nusing namespace std;\nint arr[1000];\nint sum=0;\nint cache[100][100];\nint m_diff(int idx,int sub_sum)\n{\n\tif(cache[idx][sub_sum])\n\t\treturn cache[idx][sub_sum];\n\n\tif(idx==0)\n\t{\n\t\tcache[0][sub_sum]=abs((sum-sub_sum)-sub_sum);\n\t\treturn cache[0][sub_sum];\n\t}\n\tcache[idx][sub_sum]=min(m_diff(idx-1,sub_sum-arr[idx]),m_diff(idx-1,sub_sum));\n\treturn cache[idx][sub_sum];\n}\nint main()\n{\n\tmemset(cache,0,sizeof cache);\n\tint n;\n\tcin>>n;\n\tfor(int i=0;i<n;i++)\n\t\t{\n\t\t\tcin>>arr[i];\n\t\t\tsum+=arr[i];\n\t\t}\n\t\tcout<<m_diff(n,sum)<<endl;\n}"
  },
  {
    "path": "algorithms/dynamic_programming/java/MinCostPath.java",
    "content": "import java.util.Scanner;\n\npublic class MinCostPath {\n\n\tpublic static int minCostPathDP(int arr[][],int row, int column) {\n\t\tint m = row;\n\t\tint n = column;\n\t\tint storage[][] = new int[m][n];\n\n\t\tstorage[m - 1][n - 1] = arr[m - 1][n - 1];\n\t\t// Last Row\n\t\tfor (int j = n - 2; j >= 0; j--) {\n\t\t\tstorage[m - 1][j] = storage[m - 1][j + 1] + arr[m - 1][j];\n\t\t}\n\t\t// Last Column\n\t\tfor (int i = m - 2; i >= 0; i--) {\n\t\t\tstorage[i][n - 1] = storage[i + 1][n - 1] + arr[i][n - 1];\n\t\t}\n\n\t\tfor (int i = m - 2; i >= 0; i--) {\n\t\t\tfor (int j = n - 2; j >= 0; j--) {\n\t\t\t\tstorage[i][j] = arr[i][j]\n\t\t\t\t\t\t+ Math.min(storage[i][j + 1], Math.min(\n\t\t\t\t\t\t\t\tstorage[i + 1][j + 1], storage[i + 1][j]));\n\t\t\t}\n\t\t}\n\t\treturn storage[0][0]+arr[row][column];\n\t}\n\n\tpublic static void main(String args[]) {\n\t\tScanner s = new Scanner(System.in);\n\t\tint rows = s.nextInt();\n\t\tint columns = s.nextInt();\n\t\tint arr[][] = new int[rows][columns];\n\t\tfor (int i = 0; i < rows; i++) {\n\t\t\tfor (int j = 0; j < columns; j++) {\n\t\t\t\tarr[i][j] = s.nextInt();\n\t\t\t}\n\t\t}\n\t\tint row = s.nextInt();\n\t\tint column = s.nextInt();\n\t\tSystem.out.println(minCostPathDP(arr,row,column));\n\t\ts.close();\n\t}\n}\n\n"
  },
  {
    "path": "algorithms/encoding/base64_encoder.c",
    "content": "// C implementation of base64 encoder for converting ASCII string format into radix-64 representation.\n#include<stdio.h>\n#include<math.h>\n#include<stdlib.h>\n#include<string.h>\n\n\nstatic char b64_arr[] = {\n    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',\n    'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',\n    'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',\n    'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',\n    'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',\n    'o', 'p', 'q', 'r', 's', 't', 'u', 'v',\n    'w', 'x', 'y', 'z', '0', '1', '2', '3',\n    '4', '5', '6', '7', '8', '9', '+', '/'};\n\nint main() {\n    char *str = \"Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.\";\n    int in = -1;\n    int len = strlen(str);\n    int outlen = (int)ceil(len/3.0)*4;\n    char *result = (char *)malloc(sizeof(char)*outlen);\n    for (int i = 0; i < len; i += 3) {\n        int x = 0;\n        if(str[i+1] != '\\0' && str[i+2] != '\\0'){\n            x |= (str[i] << 16);\n            x |= (str[i+1] << 8);\n            x |= (str[i+2]);\n            result[++in] = b64_arr[(x >> 18) & (0x3F)];\n            result[++in] = b64_arr[(x >> 12) & (0x3F)];\n            result[++in] = b64_arr[(x >> 6) & (0x3F)];\n            result[++in] = b64_arr[(x) & (0x3F)];\n        }\n        else if(str[i+1] != '\\0'){\n            x |= (str[i] << 16);\n            x |= (str[i+1] << 8);\n            result[++in] = b64_arr[(x >> 18) & (0x3F)];\n            result[++in] = b64_arr[(x >> 12) & (0x3F)];\n            result[++in] = b64_arr[(x >> 6) & (0x3F)];\n            result[++in] = '=';\n        }\n        else{\n            x |= (str[i] << 16);\n            result[++in] = b64_arr[(x >> 18) & (0x3F)];\n            result[++in] = b64_arr[(x >> 12) & (0x3F)];\n            result[++in] = '=';\n            result[++in] = '=';\n        }\n    }\n    if(in < outlen) result[++in] = '\\0';\n    printf(\"%s\\n\", result);\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/fibonacci/cpp/constexpr-fibonacci.cpp",
    "content": "// Computes a specific index of the Fibonacci sequence\n// Can be computed at compile-time under certain conditions\n\nconstexpr unsigned int fibonacci(unsigned int index) {\n\n    constexpr auto gr = (1 + std::sqrt(5)) / 2;\n\n    if(index == 0) {\n        return 0;\n    } else if(index == 1) {\n        return 1;\n    }\n\n    return static_cast<unsigned int>(\n            (std::pow(gr, index) - std::pow(1 - gr, index)) / sqrt(5)\n    );\n}\n"
  },
  {
    "path": "algorithms/floyd_warshall/java/ShortestPath.java",
    "content": "/**\n * A Java program for Floyd Warshall All Pairs Shortest\n * Path algorithm.\n */\npublic class ShortestPath {\n    private final static int VERTEX_NUMBER = 4;\n    private final static int MAX_VALUE = 999999;\n\n    public void floydWarshall(int graph[][]) {\n        int dist[][] = new int[VERTEX_NUMBER][VERTEX_NUMBER];\n        int i, j, k;\n\n        for (i = 0; i < VERTEX_NUMBER; i++)\n            for (j = 0; j < VERTEX_NUMBER; j++)\n                dist[i][j] = graph[i][j];\n\n        for (k = 0; k < VERTEX_NUMBER; k++) {\n            for (i = 0; i < VERTEX_NUMBER; i++) {\n                for (j = 0; j < VERTEX_NUMBER; j++) {\n                    if (dist[i][k] + dist[k][j] < dist[i][j]) {\n                        dist[i][j] = dist[i][k] + dist[k][j];\n                    }\n                }\n            }\n        }\n\n        printSolution(dist);\n    }\n\n    private void printSolution(int dist[][]) {\n        for (int i = 0; i < VERTEX_NUMBER; ++i) {\n            for (int j = 0; j < VERTEX_NUMBER; ++j) {\n                if (dist[i][j] == MAX_VALUE) {\n                    System.out.print(\"INF \");\n                } else {\n                    System.out.print(dist[i][j] + \"   \");\n                }\n            }\n            System.out.println();\n        }\n    }\n\n    /**\n     * Test\n     * @param args\n     */\n    public static void main (String[] args) {\n        int graph[][] = {\n                {0,         5,          MAX_VALUE,  10},\n                {MAX_VALUE, 0,          3,          MAX_VALUE},\n                {MAX_VALUE, MAX_VALUE,  0,          1},\n                {MAX_VALUE, MAX_VALUE,  MAX_VALUE,  0}\n        };\n\n        ShortestPath a = new ShortestPath();\n\n        a.floydWarshall(graph);\n    }\n}\n"
  },
  {
    "path": "algorithms/greedy_search/cpp/prims_algorithm.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n\nint minkey(int key[], bool mstset[],int n)\n{\n\tint min_index;\n\tint Min = INT_MAX;\n\tfor(int i=0;i<n;i++)\n\t{\n\t\tif(mstset[i]==false and key[i]<Min)\n\t\t{\t\n\t\t\tMin= key[i];\n\t\t\tmin_index = i;\n\t\t}\n\t}\n\treturn min_index;\n}\nint main()\n{\n\tint n;\n\tcout<<\"enter the number of vertices in the graph\\n\";\n\tcin>>n;\n\tint cost[n][n];\n\tmemset(cost,0,sizeof(cost));\n\tint m;\n\tcout<<\"enter the number of edges in the graph\\n\";\n\tcin>>m;\n\tvector<pair<int,int> > edgelist(m);\n\tfor(int i=0;i<m;i++)\n\t{\n\t\tint a,b,c;\n\t\tcout<<\"enter the \"<<i+1<<\" edge and the weight\\n\";\n\t\tcin>>a>>b>>c;\n\t\tedgelist[i] = make_pair(a,b);\n\t\tcost[a][b] =c;\n\t\tcost[b][a] =c;\n\t}\n\tbool mstset[n];\n\tpair<int,int> edge[n];\n\tint key[n];\n\tfor(int i=0;i<n;i++)\n\t{\n\t\tkey[i]= INT_MAX;\n\t\tmstset[i] = false;\n\t}\n\tkey[0] =0;\n\tfor(int i=0;i<n-1;i++)\n\t{\n\t\tint u = minkey(key,mstset,n);\n\t\tmstset[u] = true;\n\t\tfor(int v=0;v<n;v++)\n\t\t{\n\t\t\tif(cost[u][v] and mstset[v]==false and cost[u][v] < key[v])\n\t\t\t{\n\t\t\t\tkey[v] = cost[u][v];\n\t\t\t\tedge[v] = make_pair(u,v);\n\t\t\t}\n\t\t}\n\t}\n\tcout<<\"the edges of the  minimum spanning tree are\\n\";\n\tfor(int i=1;i<n;i++)\n\t\tcout<<edge[i].first<<\"--\"<<edge[i].second<<endl;\n\tfor(int i=0;i<m;)\n\t{\n\t\tint j;\n\t\tfor(j=0;j<n;j++)\n\t\t{\n\t\t\tif((edgelist[i].first== edge[j].first and edgelist[i].second == edge[j].second) or (edgelist[i].first== edge[j].second and edgelist[i].second == edge[j].first))\n\t\t\t{\n\t\t\t\tedgelist.erase(edgelist.begin()+i);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif(j==n)\n\t\t\t++i;\n\t}\n\t cout<<\"the edges not in minimum spanning tree are \\n\";\n\tcout<<\"edge\"<<\"  \"<<endl;\n\tfor(int i=0;i<edgelist.size();i++)\n\t\tcout<<edgelist[i].first<<\"--\"<<edgelist[i].second<<\"\\n\";\n\treturn 0;\n}\n"
  },
  {
    "path": "algorithms/heap_sort/crystal/heap_sort.cr",
    "content": "def heap_sort(array)\n  to_heap(array)\n  bottom = array.size - 1\n\n  while bottom > 0\n    array[0], array[bottom] = array[bottom], array[0]\n    sift_down(array, 0, bottom)\n    bottom -= 1\n  end\n\n  array\nend\n\ndef to_heap(array)\n  i = (array.size/2) - 1\n\n  while i >= 0\n    sift_down(array, i, array.size)\n    i -= 1\n  end\n\n  array\nend\n\ndef sift_down(array, i, max)\n  i_big, c1, c2 = 0, 0, 0\n\n  while i < max\n    i_big = i\n    c1 = (2*i) + 1\n    c2 = c1 + 1\n\n    if c1 < max && array[c1] > array[i_big]\n      i_big = c1\n    end\n\n    if c2 < max && array[c2] > array[i_big]\n      i_big = c2\n    end\n\n    break if i_big == i\n\n    array[i], array[i_big] = array[i_big], array[i]\n\n    i = i_big\n  end\n\n  array\nend\n\nnumbers = [4, 2, 8, 1, 30, 0, 10, 16]\n\nputs \"Unsorted: #{numbers}\"\n\nputs \"Sorted: #{heap_sort(numbers)}\"\n"
  },
  {
    "path": "algorithms/heap_sort/java/heap_sort.java",
    "content": "/*\n * Java Program to Implement Heap Sort\n */\n \nimport java.util.Scanner;\n \n/* Class HeapSort */\npublic class HeapSort \n{    \n    private static int N;\n    /* Sort Function */\n    public static void sort(int arr[])\n    {       \n        heapify(arr);        \n        for (int i = N; i > 0; i--)\n        {\n            swap(arr,0, i);\n            N = N-1;\n            maxheap(arr, 0);\n        }\n    }     \n    /* Function to build a heap */   \n    public static void heapify(int arr[])\n    {\n        N = arr.length-1;\n        for (int i = N/2; i >= 0; i--)\n            maxheap(arr, i);        \n    }\n    /* Function to swap largest element in heap */        \n    public static void maxheap(int arr[], int i)\n    { \n        int left = 2*i ;\n        int right = 2*i + 1;\n        int max = i;\n        if (left <= N && arr[left] > arr[i])\n            max = left;\n        if (right <= N && arr[right] > arr[max])        \n            max = right;\n \n        if (max != i)\n        {\n            swap(arr, i, max);\n            maxheap(arr, max);\n        }\n    }    \n    /* Function to swap two numbers in an array */\n    public static void swap(int arr[], int i, int j)\n    {\n        int tmp = arr[i];\n        arr[i] = arr[j];\n        arr[j] = tmp; \n    }    \n    /* Main method */\n    public static void main(String[] args) \n    {\n        Scanner scan = new Scanner( System.in );        \n        System.out.println(\"Heap Sort Test\\n\");\n        int n, i;    \n        /* Accept number of elements */\n        System.out.println(\"Enter number of integer elements\");\n        n = scan.nextInt();    \n        /* Make array of n elements */\n        int arr[] = new int[ n ];\n        /* Accept elements */\n        System.out.println(\"\\nEnter \"+ n +\" integer elements\");\n        for (i = 0; i < n; i++)\n            arr[i] = scan.nextInt();\n        /* Call method sort */\n        sort(arr);\n        /* Print sorted Array */\n        System.out.println(\"\\nElements after sorting \");        \n        for (i = 0; i < n; i++)\n            System.out.print(arr[i]+\" \");            \n        System.out.println();            \n    }    \n}\n"
  },
  {
    "path": "algorithms/heap_sort/java/heapsort.java",
    "content": "//Java program for Heap Sort\n\nclass heapsort\n{\n    public void sort(int arr[])\n    {\n        int n = arr.length;\n \n        // Build heap (rearrange array)\n        for (int i = n / 2 - 1; i >= 0; i--)\n            heapify(arr, n, i);\n \n        // One by one extract an element from heap\n        for (int i=n-1; i>=0; i--)\n        {\n            // Move current root to end\n            int temp = arr[0];\n            arr[0] = arr[i];\n            arr[i] = temp;\n \n            // call max heapify on the reduced heap\n            heapify(arr, i, 0);\n        }\n    }\n \n    // To heapify a subtree rooted with node i which is\n    // an index in arr[]. n is size of heap\n    void heapify(int arr[], int n, int i)\n    {\n        int largest = i;  // Initialize largest as root\n        int l = 2*i + 1;  // left = 2*i + 1\n        int r = 2*i + 2;  // right = 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    /* A utility function to print array of size n */\n    static void printArray(int arr[])\n    {\n        int n = arr.length;\n        for (int i=0; i<n; ++i)\n            System.out.print(arr[i]+\" \");\n        System.out.println();\n    }\n \n    // Driver program\n    public static void main(String args[])\n    {\n        int arr[] = {12, 11, 13, 5, 6, 7};\n        int n = arr.length;\n \n        HeapSort ob = new HeapSort();\n        ob.sort(arr);\n \n        System.out.println(\"Sorted array is\");\n        printArray(arr);\n    }\n}\n"
  },
  {
    "path": "algorithms/heap_sort/javascript/heap_sort.js",
    "content": "  var array_length;\n/* to create MAX  array */  \nfunction heap_root(input, i) {\n    var left = 2 * i + 1;\n    var right = 2 * i + 2;\n    var max = i;\n\n    if (left < array_length && input[left] > input[max]) {\n        max = left;\n    }\n\n    if (right < array_length && input[right] > input[max])     {\n        max = right;\n    }\n\n    if (max != i) {\n        swap(input, i, max);\n        heap_root(input, max);\n    }\n}\n\nfunction swap(input, index_A, index_B) {\n    var temp = input[index_A];\n\n    input[index_A] = input[index_B];\n    input[index_B] = temp;\n}\n\nfunction heapSort(input) {\n    \n    array_length = input.length;\n\n    for (var i = Math.floor(array_length / 2); i >= 0; i -= 1)      {\n        heap_root(input, i);\n      }\n\n    for (i = input.length - 1; i > 0; i--) {\n        swap(input, 0, i);\n        array_length--;\n      \n      \n        heap_root(input, 0);\n    }\n}\n\nvar arr = [3, 0, 2, 5, -1, 4, 1];\nheapSort(arr);\nconsole.log(arr);\n"
  },
  {
    "path": "algorithms/heap_sort/python/heap_sort.py",
    "content": "from heapq import heappush, heappop\n\ndef heap_sort(heap_iterable):\n    '''\n    Heap sort implementation\n    '''\n    heap = []\n    for val in heap_iterable:\n        heappush(heap, val)\n    return [heappop(heap) for _ in range(len(heap))]\n\n# Test\nif __name__ == '__main__':\n    test_cases = (\n        [1, 3, 5, 7, 9, 2, 4, 6, 8, 0],\n        [3, 15, 68, 34, 39, 85, 85, 71, 47, 84], \n        [3, 10, 68, 34, 15, 85, 85, 71, 47, 84, 39], \n        [2, 10, 3, 34, 15, 68, 85, 71, 47, 84, 39, 85],\n        [1, 10, 2, 34, 15, 3, 85, 71, 47, 84, 39, 85, 68],\n        range(50)\n    )\n    for iterable in test_cases:\n        assert heap_sort(iterable) == sorted(iterable)\n"
  },
  {
    "path": "algorithms/histogram_equalization/java/HistogramEqualization.java",
    "content": "/*\n* This file has been created by github user vn17.\n* Feel free to use it for any purpose.\n*\n* This file makes extensive use of Java 8 lambdas.\n*\n* For more details on the algorithm,\n* refer to @see <a href=https://en.wikipedia.org/wiki/Histogram_equalization>https://en.wikipedia.org/wiki/Histogram_equalization</a>\n*/\npackage Java;\n\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.stream.IntStream;\n\nimport static java.util.stream.Collectors.joining;\n\n\npublic class HistogramEqualization {\n\n    public static void main(String[] args) {\n        ImageMatrix imageMatrix = new ImageMatrix(new int[][]{{2, 3, 1}, {3, 4, 6}, {7, 3, 6}});\n        System.out.println(\"Input Matrix: \\n\" + imageMatrix);\n        System.out.println(\"Frequency: \\t\" + imageMatrix.frequency() + \"\\nCDF: \\t\\t\" + imageMatrix.cdf() + \"\\n\");\n        ImageMatrix equalizedImageMatrix = imageMatrix.equalize();\n        System.out.println(\"Histogram Equalized Matrix: \\n\" + equalizedImageMatrix);\n    }\n}\n\nclass ImageMatrix {\n    private static final int NUMBER_OF_LEVELS = 8;//This is the intensity range.\n    // Eg. For a 3 bit per pixel image, the intensity value is 8.\n\n    private int cdfMin = -1;//This is the cdf of the minimum intensity value\n\n    private int size;//Size of the image. 3 x 3 = 9 in this case\n\n    private int[][] imageArray;//3 x 3 Array to store intensity values at each pixel\n\n    private HashMap<Integer, Integer> frequency;//HashMap to store the frequency of each intensity value i.e.\n    // the number of times each value has appeared in the 3 x 3 array.\n\n    private HashMap<Integer, Integer> cdf;//HashMap to store the CDF of each intensity value i.e.\n    // the sum of the frequency values of all intensities lesser than the current intensity level.\n\n    public ImageMatrix(int[][] arr) {\n        this.imageArray = arr;\n        this.size = (int) Arrays.stream(arr).flatMapToInt(IntStream::of).count();\n    }\n\n    public int getFrequency(int key) {\n        if (frequency == null) calculateFrequency();\n        return frequency().get(key);\n    }\n\n    public int getCdf(int key) {\n        if (cdf == null) calculateCdf();\n        return cdf().get(key);\n    }\n\n    public HashMap<Integer, Integer> frequency() {\n        if (frequency == null) calculateFrequency();\n        return frequency;\n    }\n\n    public HashMap<Integer, Integer> cdf() {\n        if (cdf == null) calculateCdf();\n        return cdf;\n    }\n\n    /**\n     * This method calculates the frequency of each intensity value in the given intensity range.\n     */\n    private void calculateFrequency() {\n        this.frequency = new HashMap<>();\n        Arrays.stream(imageArray)//Get the 2D array\n                .flatMapToInt(IntStream::of)//Convert it to a 1D array\n                .forEach(intensity -> {//Increment the frequency value for intensity by 1\n                    if (frequency.containsKey(intensity)) frequency.put(intensity, frequency.get(intensity) + 1);\n                    else frequency.put(intensity, 1);\n                });\n    }\n\n    /**\n     * This method calculates the CDF by adding all the intensity values lesser than the current value.\n     */\n    private void calculateCdf() {\n        if (frequency == null) calculateFrequency();\n        cdf = (HashMap) frequency().clone();\n        cdf.keySet().stream()\n                .sorted().mapToInt(Integer::intValue)\n                .reduce(0, (previousSum, currentKey) -> {\n                    int sum = previousSum + cdf.get(currentKey);\n                    cdf.put(currentKey, sum);\n                    if (cdfMin == -1)//To store the cdf of the minimum intensity value\n                        cdfMin = sum;\n                    return sum;\n                });\n    }\n\n    /**\n     * This method applies the equalization formula to each element in the matrix.\n     * @return\n     */\n    public ImageMatrix equalize() {\n        int[][] equalizedArray = Arrays.stream(imageArray)\n                .map(p -> Arrays.stream(p).map(q -> (getCdf(q) - cdfMin) * (NUMBER_OF_LEVELS - 2) / (size - 1) + 1).toArray())\n                .toArray(int[][]::new);\n        return new ImageMatrix(equalizedArray);\n    }\n\n    /**\n     * Prints a 2D array line by line for each array.\n     * @return\n     */\n    @Override\n    public String toString() {\n        return Arrays.stream(imageArray).map(s -> String.format(\"%s\\n\", Arrays.toString(s))).collect(joining());\n    }\n}\n\n"
  },
  {
    "path": "algorithms/huffmann_algorithm/java/Huffman.java",
    "content": "package Lecture25;\r\n\r\nimport java.util.HashMap;\r\nimport java.util.Set;\r\n\r\nimport Lecture19.BinaryTree;\r\nimport Lecture21.Heap;\r\n\r\npublic class Huffman {\r\n\tprivate HashMap<Character, String> encoder;\r\n\tprivate HashMap<String, Character> decoder;\r\n\t\r\n\r\n\tpublic Huffman(String sourceString){\r\n\t\t// 1. prepare freq map\r\n\t\tHashMap<Character, Integer> freqMap = new HashMap<>();\r\n\t\tfor(int i = 0; i < sourceString.length(); i++){\r\n\t\t\tchar ch = sourceString.charAt(i);\r\n\t\t\t\r\n\t\t\tif(freqMap.containsKey(ch)){\r\n\t\t\t\tfreqMap.put(ch, freqMap.get(ch) + 1);\r\n\t\t\t} else {\r\n\t\t\t\tfreqMap.put(ch, 1);\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\t\r\n\t\t// 2. Prepare bt's for each key freqmap and add to a min heap\r\n\t\tHeap<Integer, Pair> minHeap = new Heap<>(true);\r\n\t\t\r\n\t\tSet<Character> allChars = freqMap.keySet();\r\n\t\tfor(Character ch: allChars){\r\n\t\t\tBinaryTree bt = new BinaryTree(ch, null, null);\r\n\t\t\tPair pair = new Pair(freqMap.get(ch), bt);\r\n\t\t\t\r\n\t\t\tminHeap.add(pair.cost, pair);\r\n\t\t}\r\n\t\t\r\n\t\t// 3. till the heap is empty, we pull out two, create a new and enter it back\r\n\t\twhile(minHeap.size() != 1){\r\n\t\t\tPair p1 = minHeap.removeHP();\r\n\t\t\tPair p2 = minHeap.removeHP();\r\n\t\t\t\r\n\t\t\tBinaryTree bt = new BinaryTree(0, p1.bt, p2.bt);\r\n\t\t\tPair p = new Pair(p1.cost + p2.cost, bt);\r\n\t\t\t\r\n\t\t\tminHeap.add(p.cost, p);\r\n\t\t}\r\n\t\t\r\n\t\t// 4. Get final tree out of heap\r\n\t\tPair fp = minHeap.removeHP();\r\n\t\tBinaryTree ft = fp.bt;\r\n\t\t\r\n\t\t// 5. Get enc, dec filled\r\n\t\tthis.encoder = new HashMap<>();\r\n\t\tthis.decoder = new HashMap<>();\r\n\t\t\r\n\t\tft.traversalForHC(encoder, decoder);\r\n\t}\r\n\t\r\n\t// input - aaaaaaaaaaaaaaaaafadsfaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbccccccccc\r\n\t// output - 11110101010101111100001101010101010101\r\n\tpublic String encode(String str){\r\n\t\tString rv = \"\";\r\n\t\t\r\n\t\tfor(int i = 0; i < str.length(); i++){\r\n\t\t\trv += encoder.get(str.charAt(i));\r\n\t\t}\r\n\t\t\r\n\t\treturn rv;\r\n\t}\r\n\t\r\n\t// input - 11110101010101111100001101010101010101\r\n\t// output - aaaaaaaaaaaaaaaaafadsfaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbccccccccc\r\n\tpublic String decode(String str){\r\n\t\tString rv = \"\";\r\n\t\t\r\n\t\tString key = \"\";\r\n\t\tfor(int i = 0; i < str.length(); i++){\r\n\t\t\tkey += str.charAt(i);\r\n\t\t\t\r\n\t\t\tif(decoder.containsKey(key)){\r\n\t\t\t\trv += decoder.get(key);\r\n\t\t\t\tkey = \"\";\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\treturn rv;\r\n\t}\r\n\t\r\n\tprivate class Pair {\r\n\t\tint cost;\r\n\t\tBinaryTree bt;\r\n\t\t\r\n\t\tPair(int cost, BinaryTree bt){\r\n\t\t\tthis.cost = cost;\r\n\t\t\tthis.bt = bt;\r\n\t\t}\r\n\t}\r\n}\r\n"
  },
  {
    "path": "algorithms/insertion_sort/ada/insertion_sort.adb",
    "content": "with Ada.Containers.Vectors;\nwith Ada.Numerics.Discrete_Random;\nwith Ada.Text_IO;\nwith Ada.Integer_Text_IO;\n\nuse Ada.Text_IO;\nuse Ada.Integer_Text_IO;\n\nprocedure Insertion_Sort is\n\n   ------------------------------\n   -- Constant, types, package --\n   ------------------------------\n\n   ARRAY_SIZE : constant Natural := 10;\n   RANGE_MIN  : constant Integer := 1;\n   RANGE_MAX  : constant Integer := 100;\n\n   package P_Vectors is new Ada.Containers.Vectors (Positive, Integer);\n   use P_Vectors;\n\n   -----------------------\n   --  Method prototype --\n   -----------------------\n\n   --  Initializing an array with default values\n   function Init_Vector return Vector;\n\n   procedure Put (Tab : Vector);\n\n   procedure Swap (a : in out Integer; b : in out Integer);\n\n   function Sort (T : Vector) return Vector;\n\n   -----------------------------\n   --  Declaration of methods --\n   -----------------------------\n\n   function Init_Vector return Vector\n   is\n      subtype T_Interval is Integer range RANGE_MIN .. RANGE_MAX;\n      package P_Random is new Ada.numerics.discrete_random (T_Interval);\n      use P_Random;\n\n      seed : Generator;\n      T    : Vector;\n   begin\n      Reset (seed);\n\n      for i in 1 .. ARRAY_SIZE loop\n         Append (T, Random (seed));\n      end loop;\n\n      return T;\n   end Init_Vector;\n\n   procedure Put (Tab : Vector)\n   is\n   begin\n      for e of Tab loop\n         Put (e, Width => 0);\n         Put (\";\");\n      end loop;\n   end Put;\n\n   procedure Swap (a : in out Integer; b : in out Integer)\n   is\n      c : constant Integer := a;\n   begin\n      a := b;\n      b := c;\n   end Swap;\n\n   function Sort (T : Vector) return Vector is\n      Tab : Vector := T;\n   begin\n      for i in First_Index (T) + 1 .. Last_Index (T) loop\n         for j in reverse First_Index (T) + 1 .. i loop\n            exit when Tab (j - 1) <= Tab (j);\n            Swap (Tab (j - 1), Tab (j));\n         end loop;\n      end loop;\n      return Tab;\n   end Sort;\n\n   ---------------\n   -- Variables --\n   ---------------\n\n   T : Vector := Init_Vector;\nbegin\n   Put (\"Array        : \");\n   Put (T);\n   New_Line;\n\n   T := Sort (T);\n\n   Put (\"Sorted array : \");\n   Put (T);\nend Insertion_Sort;\n"
  },
  {
    "path": "algorithms/insertion_sort/c/InsertionSort.c",
    "content": "// C program for insertion sort\n#include <stdio.h> \n/* Function to sort an array using insertion sort */\nvoid insertionSort(int ar[], int n)\n{\n   int i, key, j;\n   for (i = 1; i < n; i++)\n   {\n       key = ar[i];\n       j = i-1;\n       /* Move elements with indices from 0 to i-1 that are greater \n       than key, to one position ahead of their current position */\n       while (j >= 0 && ar[j] > key)\n       {\n           ar[j+1] = ar[j];\n           j = j-1;\n       }\n       ar[j+1] = key;\n   }\n}\n// method to print array\nvoid print(int ar[], int n)\n{\n   for (int  i=0; i < n; i++){\n       printf(\"%d \", ar[i]);\n   }\n}\n/* To test insertion sort function */\nint main()\n{\n    int arr[] = {10, 29, 1, 9, 37, 24, 6, 3, 11};\n    // Calculates array size\n    int n = sizeof(arr) / sizeof(arr[0]);\n    insertionSort(arr, n);\n    print(arr, n);\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/insertion_sort/cpp/insertion_sort.cpp",
    "content": "//\n// Created by radligna on 05.10.17.\n//\n\n\n// C++ program for insertion sort\n\n//needed to print the sorted array\n#include <iostream>\n\n/* Function to sort an array using insertion sort */\nvoid insertionSort( int tab[], int arraySize ) {\n    int temp, iter2;\n    for( int iter1 = 1; iter1 < arraySize; iter1++ ) {\n        temp = tab[iter1];\n        for( iter2 = iter1 - 1; iter2 >= 0 and tab[iter2] > temp; iter2-- )\n            tab[ iter2 + 1 ] = tab[ iter2 ];\n        tab[ iter2 + 1 ] = temp;\n    }\n}\n// method to print array\nvoid printArray(int arr[], int arraySize) {\n    for (int  i=0; i < arraySize; i++)\n        std::cout<<arr[i]<<\" \";\n}\n/* To test insertion sort function */\nint main() {\n    int arr[] = {10, 29, 1, 9, 37, 24, 6, 3, 11};\n    int arraySize = (sizeof(arr)/sizeof(*arr));\n    insertionSort(arr, arraySize);\n    printArray(arr, arraySize);\n    return 0;\n}"
  },
  {
    "path": "algorithms/insertion_sort/crystal/insertion_sort.cr",
    "content": "def insertion_sort(array)\n  x = 1\n  loop do\n    i = x\n\n    while i > 0 && array[i-1] > array[i]\n      array[i], array[i - 1] = array[i - 1], array[i]\n      i -= 1\n    end\n\n    x += 1\n    break if x == array.size\n  end\n\n  array\nend\n\nnumbers = [4, 2, 8, 1, 30, 0, 10, 16]\n\nputs \"Unsorted: #{numbers}\"\n\nputs \"Sorted: #{insertion_sort(numbers)}\"\n"
  },
  {
    "path": "algorithms/insertion_sort/java/InsertionSort.java",
    "content": "class InsertionSort {\r\n\r\n    /*\r\n    This class sorts an array using insertion sort\r\n     */\r\n\r\n    public static int[] insertionSort(int[] array) {\r\n        int key,\r\n                previousIndex;\r\n\r\n        for (int index = 1; index < array.length; index++) {\r\n            key = array[index];\r\n            previousIndex = index - 1;\r\n\r\n            while(previousIndex >= 0 && array[previousIndex] > key){\r\n                array[previousIndex + 1] = array[previousIndex];\r\n                previousIndex -= 1;\r\n                array[previousIndex + 1] = key;\r\n            }\r\n        }\r\n        return array;\r\n    }\r\n\r\n    public static void main(String[] args) {\r\n        int[] array = new int[10];\r\n\r\n\r\n        for (int i = 10; i > 0 ; i--) {\r\n            array[10 - i] = i;\r\n        }\r\n\r\n        int[] sortedArray = insertionSort(array);\r\n\r\n        for (int i: sortedArray) {\r\n            System.out.print(i + \" \");\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "algorithms/insertion_sort/javascript/insertionSort.js",
    "content": "function insertionSort(array) {\n  for (let i = 0; i < array.length; i++) {\n    let temp = array[i];\n    let j = i - 1;\n\n    while (j >= 0 && array[j] > temp) {\n      array[j + 1] = array[j];\n      j--;\n    }\n\n    array[j + 1] = temp;\n  }\n\n  return array;\n}\n"
  },
  {
    "path": "algorithms/insertion_sort/javascript/insertion_sort.js",
    "content": "function insertionSort(unsortedList) {\n\tlet len = unsortedList.length;\n\n\tfor (let i = 1; i < len; i++) {\n\t\tlet ele = unsortedList[i];\n\n\t\tfor (var j = i - 1; j >= 0 && (unsortedList[j] > ele); j--) {\n\t\t\tunsortedList[j+1] = unsortedList[j];\n\t\t}\n\n\t\tunsortedList[j+1] = ele;\n\t}\n}"
  },
  {
    "path": "algorithms/insertion_sort/python/insertionsort.py3",
    "content": "# Python program for implementation of Insertion Sort\n \n# Function to do insertion sort\ndef insertionSort(arr):\n \n    # Traverse through 1 to len(arr)\n    for i in range(1, len(arr)):\n \n        key = arr[i]\n \n        # Move elements of arr[0..i-1], that are\n        # greater than key, to one position ahead\n        # of their current position\n        j = i-1\n        while j >=0 and key < arr[j] :\n                arr[j+1] = arr[j]\n                j -= 1\n        arr[j+1] = key\n \n \n#Test case\narr = [12, 11, 13, 5, 6]\ninsertionSort(arr)\nfor i in range(len(arr)):\n    print (\"%d\" %arr[i])\n"
  },
  {
    "path": "algorithms/insertion_sort/ruby/insertion_sort.rb",
    "content": "def insertion_sort(numbers)\n  for i in 1...numbers.length\n    key = numbers[i]\n    j = i - 1\n    while j >= 0 and numbers[j] > key\n      numbers[j+1] = numbers[j]\n      j = j - 1\n    end\n    numbers[j+1] = key\n  end\n  numbers\nend\n\nunsorted = [5, 2, 6, 7, 20, 9, 1, 3]\n\nputs \"Unsorted \" + unsorted.inspect\n\nsorted = insertion_sort(unsorted)\nputs \"Sorted \" + sorted.inspect\n"
  },
  {
    "path": "algorithms/inversion_count/cpp/inversion_count.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n\nlong merge(vector<int> &arr, vector<int> &tmp, int left, int mid, int right) {\n\tint i = left;\n\tint k = left;\n\tint j = mid;\n\tlong count = 0;\n\twhile(i <= (mid-1) && j <= right) {\n\t\tif(arr[i] <= arr[j] ) tmp[k++] = arr[i++];\n\t\telse {\n\t\t\ttmp[k++] = arr[j++];\n\t\t\tcount += mid - i;\n\t\t}\n\t}\n\twhile(i <= mid - 1)\n\t\ttmp[k++] = arr[i++];\n\twhile(j <= right)\n\t\ttmp[k++] = arr[j++];\n\tfor (int i = left; i <= right; ++i) {\n\t\tarr[i] = tmp[i];\n\t}\n\treturn count;\n}\n\nlong mergeSort(vector<int> &arr, vector<int> &tmp, int left, int right) {\n\tlong count = 0;\n\tint mid;\n\tif(left < right) {\n\t\tmid = (right + left)/2;\n\t\tcount += mergeSort(arr, tmp, left, mid);\n\t\tcount += mergeSort(arr, tmp , mid+1 , right);\n\t\tcount += merge(arr, tmp, left, mid+1, right);\n\t}\n\treturn count;\n}\n\nlong countInversions(vector<int> arr) {\n   vector<int> tmp(arr.size());\n   return mergeSort(arr, tmp, 0, arr.size()-1);\n}\n\nint main() {\n    int n;\n    cin >> n;\n    vector <int> arr(n);\n    for(int arr_i = 0; arr_i < n; arr_i++) {\n       cin >> arr[arr_i];\n    }\n    long result = countInversions(arr);\n    cout << result << endl;\n    return 0;\n}"
  },
  {
    "path": "algorithms/jarvis/cpp/jarvis.cpp",
    "content": "/*Given a set of points in the plane. the convex hull of the set is the smallest convex polygon that contains all the points of it.*/\n#include <bits/stdc++.h>\nusing namespace std;\n \nstruct Point\n{\n    int x, y;\n};\n \n// To find orientation of ordered triplet (p, q, r).\n// The function returns following values\n// 0 --> p, q and r are colinear\n// 1 --> Clockwise\n// 2 --> Counterclockwise\nint orientation(Point p, Point q, Point r)\n{\n    int val = (q.y - p.y) * (r.x - q.x) -\n              (q.x - p.x) * (r.y - q.y);\n \n    if (val == 0) return 0;  // colinear\n    return (val > 0)? 1: 2; // clock or counterclock wise\n}\n \n// Prints convex hull of a set of n points.\nvoid convexHull(Point points[], int n)\n{\n    // There must be at least 3 points\n    if (n < 3) return;\n \n    // Initialize Result\n    vector<Point> hull;\n \n    // Find the leftmost point\n    int l = 0;\n    for (int i = 1; i < n; i++)\n        if (points[i].x < points[l].x)\n            l = i;\n \n    // Start from leftmost point, keep moving counterclockwise\n    // until reach the start point again.  This loop runs O(h)\n    // times where h is number of points in result or output.\n    int p = l, q;\n    do\n    {\n        // Add current point to result\n        hull.push_back(points[p]);\n \n        // Search for a point 'q' such that orientation(p, x,\n        // q) is counterclockwise for all points 'x'. The idea\n        // is to keep track of last visited most counterclock-\n        // wise point in q. If any point 'i' is more counterclock-\n        // wise than q, then update q.\n        q = (p+1)%n;\n        for (int i = 0; i < n; i++)\n        {\n           // If i is more counterclockwise than current q, then\n           // update q\n           if (orientation(points[p], points[i], points[q]) == 2)\n               q = i;\n        }\n \n        // Now q is the most counterclockwise with respect to p\n        // Set p as q for next iteration, so that q is added to\n        // result 'hull'\n        p = q;\n \n    } while (p != l);  // While we don't come to first point\n \n    // Print Result\n    for (int i = 0; i < hull.size(); i++)\n        cout << \"(\" << hull[i].x << \", \"\n              << hull[i].y << \")\\n\";\n}\n"
  },
  {
    "path": "algorithms/johnson_algorithm/cpp/johnson_algorithm.cpp",
    "content": "    #include<iostream>\n\n    #include<conio.h>\n\n     \n\n    using namespace std;\n\n     \n\n    int min(int a, int b);\n\n    int cost[10][10], a[10][10], i, j, k, c;\n\n     \n\n    int min(int a, int b)\n\n    {\n\n        if (a < b)\n\n            return a;\n\n        else\n\n            return b;\n\n    }\n\n     \n\n    int main(int argc, char **argv)\n\n    {\n\n        int n, m;\n\n        cout << \"Enter no of vertices\";\n\n        cin >> n;\n\n        cout << \"Enter no of edges\";\n\n        cin >> m;\n\n        cout << \"Enter the\\nEDGE Cost\\n\";\n\n        for (k = 1; k <= m; k++)\n\n        {\n\n            cin >> i >> j >> c;\n\n            a[i][j] = cost[i][j] = c;\n\n        }\n\n        for (i = 1; i <= n; i++)\n\n            for (j = 1; j <= n; j++)\n\n            {\n\n                if (a[i][j] == 0 && i != j)\n\n                    a[i][j] = 31999;\n\n            }\n\n        for (k = 1; k <= n; k++)\n\n            for (i = 1; i <= n; i++)\n\n                for (j = 1; j <= n; j++)\n\n                    a[i][j] = min(a[i][j], a[i][k] + a[k][j]);\n\n        cout << \"Resultant adj matrix\\n\";\n\n        for (i = 1; i <= n; i++)\n\n        {\n\n            for (j = 1; j <= n; j++)\n\n            {\n\n                if (a[i][j] != 31999)\n\n                    cout << a[i][j] << \" \";\n\n            }\n\n            cout << \"\\n\";\n\n        }\n\n        return 0;\n\n    }\n"
  },
  {
    "path": "algorithms/kmp_search/cpp/KMPSearch.cpp",
    "content": "//CPP Implementation of Knuth-Morris-Pratt(KMP) algorithm for pattern matching in a given text string.\n\n#include<bits/stdc++.h>\n#define MAX 10000\nusing namespace std;\n\nchar text[MAX],pattern[MAX];\nint prefix_array[MAX],m,n;\n\nvoid Compute_Prefix_Array();\nint Kmp_Search();\n\nint main(void)\n{\n    int find_pattern;\n\tcout<<\"Specify Input Text: \";\n\tcin>>text;\n\tcout<<\"Specify Input Pattern: \";\n\tcin>>pattern;\n\tm=strlen(text);\n\tn=strlen(pattern);\n\tfind_pattern=Kmp_Search();\n\tif(find_pattern>=0)\n\t{\n\t\tcout<<\"\\nMatching Pattern FOUND at position \"<<find_pattern<<\" in the input Text.\"<<endl;\n\t}\n\telse\n\t{\n\t    cout<<\"\\nMatching Pattern NOT found in the input Text!\"<<endl;\n\t}\n\treturn 0;\n}\n\nint Kmp_Search()\n{\n\tint i;\n\tCompute_Prefix_Array();\n\tint k=-1;\n\tfor(i=0;i<m;i++)\n\t{\n\t\twhile(k>-1 && pattern[k+1]!=text[i])\n\t\t{\n\t\t    k=prefix_array[k];\n\t\t}\n\t\tif(text[i] == pattern[k+1])\n\t\t{\n\t\t    k++;\n\t\t}\n\t\tif(k==n-1)\n\t\t{\n\t\t\treturn i-k+1;\n\t\t}\n\t}\n\treturn -1;\n}\n\nvoid Compute_Prefix_Array()\n{\n\tint k=-1;\n\tint i=1;\n\tprefix_array[0]=k;\n\tfor(i=1;i<n;i++)\n\t{\n\t\twhile(k>-1&&pattern[k+1]!=pattern[i])\n\t\t{\n\t\t    k=prefix_array[k];\n\t\t}\n\t\tif(pattern[i]==pattern[k+1])\n\t\t{\n            k++;\n\t\t}\n\t\tprefix_array[i]=k;\n\t}\n}\n\n/*\nSAMPLE OUTPUT:\nSpecify Input Text: ababdabacdababcabab\nSpecify Input Pattern: ababcabab\n\nMatching Pattern FOUND at position 11 in the input Text.\n*/\n"
  },
  {
    "path": "algorithms/kmp_search/java/KMPSearch.java",
    "content": "\npublic class KMPSearch {\n    public static void main(String[] args) {\n        new KMPSearch().demo();\n    }\n\n    private void demo() {\n        String s1 = \"abcxabcdabxabcdabcdabcypo\";\n        String s2 = \"abcdabcy\";\n        int[] prefixArray = new int[s2.length()];\n        calculatePrefixArray(s2, prefixArray);\n        for (int i = 0, j = 0; i < s1.length(); i++) {\n            if (s1.charAt(i) == s2.charAt(j)) {\n                j++;\n            } else {\n                if (j != 0) {\n                    j = prefixArray[j - 1];\n                    i--;\n                }\n            }\n\n            if (j == s2.length()) {\n                int index = i - j + 1;\n                System.out.println(\"Pattern found at index \" + index);\n                System.out.println(s1.substring(index, index+s2.length()));\n                return;\n            }\n\n        }\n        System.out.println(\"Pattern not found\");\n    }\n\n\n    private void calculatePrefixArray(String s, int[] prefixArray) {\n        int j = 0;\n        prefixArray[j] = 0;\n        for (int i = 1; i < s.length(); i++) {\n            if (s.charAt(i) == s.charAt(j)) {\n                prefixArray[i] = j + 1;\n                j++;\n            } else {\n                if (j == 0) {\n                    prefixArray[i] = 0;\n                } else {\n                    j = prefixArray[j - 1];\n                    while (j != 0) {\n                        if (s.charAt(j) == s.charAt(i)) {\n                            prefixArray[i] = j + 1;\n                            break;\n                        } else {\n                            j--;\n                        }\n                    }\n                    if (j == 0) {\n                        prefixArray[i] = 0;\n\n                    }\n                }\n\n            }\n\n        }\n\n    }\n}\n"
  },
  {
    "path": "algorithms/kmp_search/python/KMPSearch.py",
    "content": "class KMP:\n    def partial(self, pattern):\n        \"\"\" Calculate partial match table: String -> [Int]\"\"\"\n        ret = [0]\n        \n        for i in range(1, len(pattern)):\n            j = ret[i - 1]\n            while j > 0 and pattern[j] != pattern[i]:\n                j = ret[j - 1]\n            ret.append(j + 1 if pattern[j] == pattern[i] else j)\n        return ret\n        \n    def search(self, T, P):\n        \"\"\" \n        KMP search main algorithm: String -> String -> [Int] \n        Return all the matching position of pattern string P in S\n        \"\"\"\n        partial, ret, j = self.partial(P), [], 0\n        \n        for i in range(len(T)):\n            while j > 0 and T[i] != P[j]:\n                j = partial[j - 1]\n            if T[i] == P[j]: j += 1\n            if j == len(P): \n                ret.append(i - (j - 1))\n                j = 0\n            \n        return ret"
  },
  {
    "path": "algorithms/linear_search/c/linearsearch.C",
    "content": "#include <stdio.h>\n// linear search function\nint linear(int a[], int n, int x){\n  for(int i = 0; i < n; i++){\n    // if element found return its position\n    if(a[i] == x){\n      return i + 1;\n    }\n  }\n  // If element not in array\n  return -1;\n}\nint main(){\n  // Sample array\n  int a[] = {1, 2, 5, 10, 7, 11, 8, 9, 22, 3};\n  //Size of array\n  int n = sizeof(a) / sizeof(a[0]);\n  // Element to be searched\n  int x = 7;\n  // Return value after search\n  int c = linear(a, n, x);\n  if(c == -1)\n    printf(\"Element not present in list\");\n  else\n    printf(\"Element is at position %d\", c);\n  return 0;\n}\n"
  },
  {
    "path": "algorithms/linear_search/cpp/linearSearch.cpp",
    "content": "#include <iostream>\nusing namespace std;\n\nint linearSearch(int* arr, int size, int num){\n  for(int i = 0; i < size; i++){\n    if(arr[i] == num){\n      return i;\n    }\n  }\n  return -1;\n}\nint main(){\n  int arr[] = {1, 2, 5, 10, 7, 11, 8, 9, 22, 3};\n  int size = sizeof(arr) / sizeof(arr[0]);\n  int num = 7;\n  int result = linearSearch(arr, size, num);\n  if(result == -1)\n    cout << \"Element not present in list\" << endl;\n  else\n    cout << \"Element is at position \" << result << endl;\n  return 0;\n}\n"
  },
  {
    "path": "algorithms/linear_search/java/LinearSearch.java",
    "content": "import java.util.Scanner;\n\npublic class LinearSearch {\n\n    public static void main(String args[])\n    {\n        int i;\n        int desiredNumber;\n        int numList[];\n\n        Scanner in = new Scanner(System.in);\n        numList = new int[] {1,2,3,4,5,6,7,8,9,10};\n\n        System.out.println(\"Desired Number: \");\n        desiredNumber = in.nextInt();\n\n        for (i = 0; i < numList.length; i++)\n        {\n            if (numList[i] == desiredNumber)\n            {\n                System.out.println(\"Number found in the array\");\n                break;\n            }\n        }\n        if (i == numList.length)\n            System.out.println(\"Number not in the array\");\n    }\n}\n\n\n"
  },
  {
    "path": "algorithms/linear_search/javascript/linear_search.js",
    "content": "var linearSearch = function(list, target){\n  var result = null,\n      i = 0, value;\n  for(; i < list.length; i++){\n    value = list[i];\n    if(value === target){\n      result = i;\n      break;\n    }\n  }\n  return result;\n};\n"
  },
  {
    "path": "algorithms/linear_search/python/linear_search.py",
    "content": "def linear_search(a,target):\n\ti = 0\n \twhile i < len(a) and a[i] != target:\n \t\ti = i+1\n \treturn i < len(a);\n\n#input: target = target, a = array \nprint('Insert array (list of ints separated by a space): ') #For example: \"1 2 3 4\"\na = list(map(int, input().split())) \nprint('Insert target: ')\ntarget = int(input())\nprint('Pos: ')\nprint(linear_search(a,target))"
  },
  {
    "path": "algorithms/longest_common_subsequence/cpp/LongestCommonSubsequence.cpp",
    "content": "/* Dynamic Programming C/C++ implementation of LCS problem */\n#include<bits/stdc++.h>\n  \nint max(int a, int b);\n  \n/* Returns length of LCS for X[0..m-1], Y[0..n-1] */\nint lcs( char *X, char *Y, int m, int n )\n{\n   int L[m+1][n+1];\n   int i, j;\n  \n   /* Following steps build L[m+1][n+1] in bottom up fashion. Note \n      that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */\n   for (i=0; i<=m; i++)\n   {\n     for (j=0; j<=n; j++)\n     {\n       if (i == 0 || j == 0)\n         L[i][j] = 0;\n  \n       else if (X[i-1] == Y[j-1])\n         L[i][j] = L[i-1][j-1] + 1;\n  \n       else\n         L[i][j] = max(L[i-1][j], L[i][j-1]);\n     }\n   }\n    \n   /* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */\n   return L[m][n];\n}\n  \n/* Utility function to get max of 2 integers */\nint max(int a, int b)\n{\n    return (a > b)? a : b;\n}\n  \n/* Driver program to test above function */\nint main()\n{\n  char X[] = \"AGGTAB\";\n  char Y[] = \"GXTXAYB\";\n  \n  int m = strlen(X);\n  int n = strlen(Y);\n  \n  printf(\"Length of LCS is %dn\", lcs( X, Y, m, n ) );\n \n  return 0;\n}\n"
  },
  {
    "path": "algorithms/longest_common_subsequence/javaj/LCS.java",
    "content": "/* Returns length of LCS for X[0..m-1], Y[0..n-1] */\n  int lcs( char[] X, char[] Y, int m, int n )\n  {\n    int L[][] = new int[m+1][n+1];\n \n    /* Following steps build L[m+1][n+1] in bottom up fashion. Note\n         that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */\n    for (int i=0; i<=m; i++)\n    {\n      for (int j=0; j<=n; j++)\n      {\n        if (i == 0 || j == 0)\n            L[i][j] = 0;\n        else if (X[i-1] == Y[j-1])\n            L[i][j] = L[i-1][j-1] + 1;\n        else\n            L[i][j] = max(L[i-1][j], L[i][j-1]);\n      }\n    }\n  return L[m][n];\n  }\n \n  /* Utility function to get max of 2 integers */\n  int max(int a, int b)\n  {\n    return (a > b)? a : b;\n  }\n \n  public static void main(String[] args)\n  {\n    LongestCommonSubsequence lcs = new LongestCommonSubsequence();\n    String s1 = \"AGGTAB\";\n    String s2 = \"GXTXAYB\";\n \n    char[] X=s1.toCharArray();\n    char[] Y=s2.toCharArray();\n    int m = X.length;\n    int n = Y.length;\n \n    System.out.println(\"Length of LCS is\" + \" \" +\n                                  lcs.lcs( X, Y, m, n ) );\n  }\n \n}\n"
  },
  {
    "path": "algorithms/longest_common_subsequence/javascript/longest_common_subsequence.js",
    "content": "function lcs(a, b) {\n  var aSub = a.substr(0, a.length - 1);\n  var bSub = b.substr(0, b.length - 1);\n \n  if (a.length === 0 || b.length === 0) {\n    return '';\n  } else if (a.charAt(a.length - 1) === b.charAt(b.length - 1)) {\n    return lcs(aSub, bSub) + a.charAt(a.length - 1);\n  } else {\n    var x = lcs(a, bSub);\n    var y = lcs(aSub, b);\n    return (x.length > y.length) ? x : y;\n  }\n}\n"
  },
  {
    "path": "algorithms/longest_common_subsequence/python/LCS.py",
    "content": "# Dynamic Programming implementation of LCS problem\n \ndef lcs(X , Y):\n    # find the length of the strings\n    m = len(X)\n    n = len(Y)\n \n    # declaring the array for storing the dp values\n    L = [[None]*(n+1) for i in xrange(m+1)]\n \n    \"\"\"Following steps build L[m+1][n+1] in bottom up fashion\n    Note: L[i][j] contains length of LCS of X[0..i-1]\n    and Y[0..j-1]\"\"\"\n    for i in range(m+1):\n        for j in range(n+1):\n            if i == 0 or j == 0 :\n                L[i][j] = 0\n            elif X[i-1] == Y[j-1]:\n                L[i][j] = L[i-1][j-1]+1\n            else:\n                L[i][j] = max(L[i-1][j] , L[i][j-1])\n \n    # L[m][n] contains the length of LCS of X[0..n-1] & Y[0..m-1]\n    return L[m][n]\n#end of function lcs\n \n \n# Driver program to test the above function\nX = \"AGGTAB\"\nY = \"GXTXAYB\"\nprint \"Length of LCS is \", lcs(X, Y)\n"
  },
  {
    "path": "algorithms/longest_common_substring/java/LongestCommonSubString.java",
    "content": "import java.util.Arrays;\n\nclass StringManager {\n\n    public static String findLongestCommonSubString(String str1, String str2) throws NullPointerException {\n    \t\n    \tchar[] x = str1.toCharArray();\n    \tchar[] y = str2.toCharArray();\n    \t\n        int LCSMatrix[][] = new int[x.length+1][y.length+1];\n        int length = 0;\n        int indexOfLastCharX = 0;\n\n        for(int i = 0; i < x.length; i++){\n            for(int j = 0; j < y.length; j++){\n                if(x[i] == y[j]){\n                    if(i == 0 || j == 0){\n                        LCSMatrix[i][j] = 1;\n                        if(LCSMatrix[i][j] > length){\n                        \tlength = LCSMatrix[i][j];\n                            indexOfLastCharX = i;\n                        }\n                    } else {\n                        LCSMatrix[i][j] = LCSMatrix[i-1][j-1] + 1;\n                        if(LCSMatrix[i][j] > length){\n                        \tlength = LCSMatrix[i][j];\n                            indexOfLastCharX = i;\n                        }\n                    }\n                } else {\n                    LCSMatrix[i][j] = 0;\n                }\n            }\n        }\n        \n        if(indexOfLastCharX == 0) return \"\";\n        \n        int indexOfFirstCharX = indexOfLastCharX - length + 1;\n        return new String(Arrays.copyOfRange(x, indexOfFirstCharX, indexOfLastCharX + 1));\n    }\n\n    public static void main(String[] args){\n    \tString test1 = \"immeasurable\";\n    \tString test2 = \"measure\";\n    \t\n    \tString result = findLongestCommonSubString(test1, test2);\n        System.out.println(result);\n    }\n\n}\n"
  },
  {
    "path": "algorithms/matrix_chain_multiplication/cpp/MCM.cpp",
    "content": "// See the Cormen book for details of the following algorithm\n#include<stdio.h>\n#include<limits.h>\n \n// Matrix Ai has dimension p[i-1] x p[i] for i = 1..n\nint MatrixChainOrder(int p[], int n)\n{\n \n    /* For simplicity of the program, one extra row and one\n       extra column are allocated in m[][].  0th row and 0th\n       column of m[][] are not used */\n    int m[n][n];\n \n    int i, j, k, L, q;\n \n    /* m[i,j] = Minimum number of scalar multiplications needed\n       to compute the matrix A[i]A[i+1]...A[j] = A[i..j] where\n       dimension of A[i] is p[i-1] x p[i] */\n \n    // cost is zero when multiplying one matrix.\n    for (i=1; i<n; i++)\n        m[i][i] = 0;\n \n    // L is chain length.\n    for (L=2; L<n; L++)\n    {\n        for (i=1; i<n-L+1; i++)\n        {\n            j = i+L-1;\n            m[i][j] = INT_MAX;\n            for (k=i; k<=j-1; k++)\n            {\n                // q = cost/scalar multiplications\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 \n    return m[1][n-1];\n}\n \nint main()\n{\n    int arr[] = {1, 2, 3, 4};\n    int size = sizeof(arr)/sizeof(arr[0]);\n \n    printf(\"Minimum number of multiplications is %d \",\n                       MatrixChainOrder(arr, size));\n \n    getchar();\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/matrix_chain_multiplication/java/MCM.java",
    "content": "{\n    // Matrix Ai has dimension p[i-1] x p[i] for i = 1..n\n    static int MatrixChainOrder(int p[], int n)\n    {\n        /* For simplicity of the program, one extra row and one\n        extra column are allocated in m[][].  0th row and 0th\n        column of m[][] are not used */\n        int m[][] = new int[n][n];\n \n        int i, j, k, L, q;\n \n        /* m[i,j] = Minimum number of scalar multiplications needed\n        to compute the matrix A[i]A[i+1]...A[j] = A[i..j] where\n        dimension of A[i] is p[i-1] x p[i] */\n \n        // cost is zero when multiplying one matrix.\n        for (i = 1; i < n; i++)\n            m[i][i] = 0;\n \n        // L is chain length.\n        for (L=2; L<n; L++)\n        {\n            for (i=1; i<n-L+1; i++)\n            {\n                j = i+L-1;\n                if(j == n) continue;\n                m[i][j] = Integer.MAX_VALUE;\n                for (k=i; k<=j-1; k++)\n                {\n                    // q = cost/scalar multiplications\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 \n        return m[1][n-1];\n    }\n \n    // Driver program to test above function\n    public static void main(String args[])\n    {\n        int arr[] = new int[] {1, 2, 3, 4};\n        int size = arr.length;\n \n        System.out.println(\"Minimum number of multiplications is \"+\n                           MatrixChainOrder(arr, size));\n    }\n}\n"
  },
  {
    "path": "algorithms/matrix_chain_multiplication/python/MCM.py",
    "content": "def matrix_chain_multiplication(dimensions):\n    \"\"\"\n    Implementation of matrix chain multiplication\n    \"\"\"\n\n    matrix = [[0 for _ in dimensions] for _ in dimensions]\n\n    for j in range(2, len(dimensions)):\n        for i in range(j - 1, 0, -1):\n            if j == i + 1:\n                matrix[i][j] = dimensions[i - 1] * dimensions[i] * dimensions[i + 1]\n            else:\n                matrix[i][j] = \\\n                        min((matrix[i][k] + matrix[k + 1][j] + \n                             dimensions[i - 1] * dimensions[k] * dimensions[j]) \n                            for k in range(i, j))\n        \n    return matrix[1][len(dimensions) - 1]\n\n# Test\nif __name__ == '__main__':\n    test_cases = (\n        ([13, 5, 89], 13 * 5 * 89), # (M_1*M_2)*(M_3*M_4)\n        ([13, 5, 89, 3, 34], 2856), # (M_1*(M_2*M_3))*M_4\n        ([2, 3, 5, 2, 4, 3], 78), # (M_1*(M_2*M_3))*(M_4*M_5)\n        ([66, 87, 71, 43, 18, 19, 33, 98, 54], 498402) # (M_1*(M_2*(M_3*M_4)))*(((M_5*M_6)*M_7)*M_8)\n    )\n    for dimensions, result in test_cases:\n        assert matrix_chain_multiplication(dimensions) == result\n"
  },
  {
    "path": "algorithms/merge_sort/c#/MergeSort.cs",
    "content": "﻿using System;\n\nnamespace MergeSort\n{\n    class MergeSort\n    {\n        static void Main(string[] args)\n        {\n            int[] array = { -2, 5, 3, 8, 9, 9, -8, 5, -4 };\n            array = Sort(array);\n            foreach (var item in array)\n            {\n                Console.Write(\"{0} \", item);\n            }\n        }\n\n        static int[] Sort(int[] w)\n        {\n            if(w.Length <= 1)\n            {\n                return w;\n            }\n            else\n            {\n                int n = w.Length;\n                int k = n / 2;\n                int[] u = new int[k];\n                int[] v = new int[n - k];\n                for (int i = 0; i < k; i++)\n                {\n                    u[i] = w[i];\n                }                    \n                for (int i = k; i < n; i++)\n                {\n                    v[i - k] = w[i];\n                }                   \n                u = Sort(u);\n                v = Sort(v);\n                w = Merge(u, v);\n                return w;\n            }\n        }\n\n        static int[] Merge(int[] u, int[] v)\n        {\n            int n = u.Length + v.Length;\n            int[] t = new int[n];\n            int i = 0, j = 0;\n            for (int k = 0; k < n; k++)\n            {\n                if(i < u.Length && (j >= v.Length || u[i] < v[j]))\n                {\n                    t[k] = u[i];\n                    i++;\n                }\n                else\n                {\n                    t[k] = v[j];\n                    j++;\n                }\n            }\n            return t;\n        }\n    }\n}\n"
  },
  {
    "path": "algorithms/merge_sort/cpp/merge_sort.cpp",
    "content": "#include <iostream.h>\nint a[50];\nvoid merge(int,int,int);\nvoid merge_sort(int low,int high)\n{\n int mid;\n if(low<high)\n {\n  mid=(low+high)/2;\n  merge_sort(low,mid);\n  merge_sort(mid+1,high);\n  merge(low,mid,high);\n }\n}\nvoid merge(int low,int mid,int high)\n{\n int h,i,j,b[50],k;\n h=low;\n i=low;\n j=mid+1;\n\n while((h<=mid)&&(j<=high))\n {\n  if(a[h]<=a[j])\n  {\n   b[i]=a[h];\n   h++;\n  }\n  else\n  {\n   b[i]=a[j];\n   j++;\n  }\n  i++;\n }\n if(h>mid)\n {\n  for(k=j;k<=high;k++)\n  {\n   b[i]=a[k];\n   i++;\n  }\n }\n else\n {\n  for(k=h;k<=mid;k++)\n  {\n   b[i]=a[k];\n   i++;\n  }\n }\n for(k=low;k<=high;k++) a[k]=b[k];\n}\nvoid main()\n{\n int num,i;\n\ncout<<\"*******************************************************************\n*************\"<<endl;\n cout<<\"                             MERGE SORT PROGRAM\n\"<<endl;\n\ncout<<\"*******************************************************************\n*************\"<<endl;\n cout<<endl<<endl;\n cout<<\"Please Enter THE NUMBER OF ELEMENTS you want to sort [THEN \nPRESS\nENTER]:\"<<endl;\n cin>>num;\n cout<<endl;\n cout<<\"Now, Please Enter the ( \"<< num <<\" ) numbers (ELEMENTS) [THEN\nPRESS ENTER]:\"<<endl;\n for(i=1;i<=num;i++)\n {\n  cin>>a[i] ;\n }\n merge_sort(1,num);\n cout<<endl;\n cout<<\"So, the sorted list (using MERGE SORT) will be :\"<<endl;\n cout<<endl<<endl;\n\n for(i=1;i<=num;i++)\n cout<<a[i]<<\"\t\";\n\n cout<<endl<<endl<<endl<<endl;\n\n}\n\n"
  },
  {
    "path": "algorithms/merge_sort/haskell/merge_sort.hs",
    "content": "module MergeSort where\n\n{-\nMerge Sort in Haskell.\n-}\n\nmerge :: Ord a =>[a] -> [a] -> [a]\nmerge [] ys = ys\nmerge xs [] = xs\nmerge (x:xs) (y:ys)\n  | x > y = y:x:(merge xs ys)\n  | y >= x = x:y:(merge xs ys)\n\nmergeSort' :: Ord a => Int -> [a] -> [a]\nmergeSort' 1 [x]  = [x]\nmergeSort' len xs = merge (mergeSort' middle left) (mergeSort' (len-middle) right)\n  where\n    middle = len `div` 2\n    (left, right) = splitAt middle xs\n    \nmergeSort :: Ord a => [a] -> [a]\nmergeSort [] = []\nmergeSort [x] = [x]\nmergeSort xs  = mergeSort' (length xs) xs\n"
  },
  {
    "path": "algorithms/merge_sort/java/merge_sort.java",
    "content": "/* Java program for Merge Sort */\nclass MergeSort\n{\n    // Merges two subarrays of arr[].\n    // First subarray is arr[l..m]\n    // Second subarray is arr[m+1..r]\n    private static void merge(int arr[], int l, int m, int r)\n    {\n        // Find sizes of two subarrays to be merged\n        int n1 = m - l + 1;\n        int n2 = r - m;\n \n        /* Create temp arrays */\n        int L[] = new int [n1];\n        int R[] = new int [n2];\n \n        /*Copy data to temp arrays*/\n        for (int i=0; i<n1; ++i)\n            L[i] = arr[l + i];\n        for (int j=0; j<n2; ++j)\n            R[j] = arr[m + 1+ j];\n \n \n        /* Merge the temp arrays */\n \n        // Initial indexes of first and second subarrays\n        int i = 0, j = 0;\n \n        // Initial index of merged subarry array\n        int k = l;\n        while (i < n1 && j < n2)\n        {\n            if (L[i] <= R[j])\n            {\n                arr[k] = L[i];\n                i++;\n            }\n            else\n            {\n                arr[k] = R[j];\n                j++;\n            }\n            k++;\n        }\n \n        /* Copy remaining elements of L[] if any */\n        while (i < n1)\n        {\n            arr[k] = L[i];\n            i++;\n            k++;\n        }\n \n        /* Copy remaining elements of R[] if any */\n        while (j < n2)\n        {\n            arr[k] = R[j];\n            j++;\n            k++;\n        }\n    }\n \n    // Main function that sorts arr[l..r] using\n    // merge()\n    private static void sort(int arr[], int l, int r)\n    {\n        if (l < r)\n        {\n            // Find the middle point\n            int m = (l+r)/2;\n \n            // Sort first and second halves\n            sort(arr, l, m);\n            sort(arr , m+1, r);\n \n            // Merge the sorted halves\n            merge(arr, l, m, r);\n        }\n    }\n    \n    //The method exposed externally, deals with input validation\n    //and hides the implementation details\n    public static boolean sort(int[] arr) {\n    \tif(arr == null) {\n    \t\treturn false;\n    \t}\n    \t\n    \tif(arr.length != 0) {\n    \t\tsort(arr, 0, arr.length - 1);\n    \t}\n    \t\n    \treturn true;\n    }\n \n    /* A utility function to print array of size n */\n    public static void printArray(int arr[])\n    {\n        int n = arr.length;\n        for (int i=0; i<n; ++i)\n            System.out.print(arr[i] + \" \");\n        System.out.println();\n    }\n \n    // Driver method\n    public static void main(String args[])\n    {\n        int arr[] = {12, 11, 13, 5, 6, 7};\n \n        System.out.println(\"Given Array\");\n        printArray(arr);\n \n        MergeSort.sort(arr);\n \n        System.out.println(\"\\nSorted array\");\n        printArray(arr);\n    }\n}\n"
  },
  {
    "path": "algorithms/merge_sort/javascript/MergeSort.js",
    "content": "var a = [34, 203, 3, 746, 200, 984, 198, 764, 9];\n \nfunction mergeSort(arr)\n{\n    if (arr.length < 2)\n        return arr;\n \n    var middle = parseInt(arr.length / 2);\n    var left   = arr.slice(0, middle);\n    var right  = arr.slice(middle, arr.length);\n \n    return merge(mergeSort(left), mergeSort(right));\n}\n \nfunction merge(left, right)\n{\n    var result = [];\n \n    while (left.length && right.length) {\n        if (left[0] <= right[0]) {\n            result.push(left.shift());\n        } else {\n            result.push(right.shift());\n        }\n    }\n \n    while (left.length)\n        result.push(left.shift());\n \n    while (right.length)\n        result.push(right.shift());\n \n    return result;\n}\n \nconsole.log(mergeSort(a));\n"
  },
  {
    "path": "algorithms/merge_sort/python/merge_sort.py",
    "content": "def merge_sort(li):\n    # recursively split the lists\n    if len(li) <= 1:\n        return li\n    middle = len(li) / 2\n    left = li[:middle]\n    right = li[middle:]\n    return merge(merge_sort(left), merge_sort(right))\n\n\ndef merge(left, right):\n    # Merge the two lists back together\n    result = []\n    while left or right:\n        if left and right:\n            if left[0] < right[0]:\n                result.append(left.pop(0))\n            else:\n                result.append(right.pop(0))\n        elif left:\n            result.append(left.pop(0))\n        else:\n            result.append(right.pop(0))\n    return result\n"
  },
  {
    "path": "algorithms/merge_sort/ruby/merge_sort.rb",
    "content": "def sort(numbers)\n  return numbers if numbers.size <= 1\n\n  arr_len = numbers.size\n  half_size = (arr_len / 2).round\n\n  left_array  = numbers.take(half_size)\n  right_array = numbers.drop(half_size)\n\n  sorted_left = sort(left_array)\n  sorted_right = sort(right_array)\n\n  merge(sorted_left, sorted_right)\nend\n\ndef merge(left, right)\n  return left if right.empty?\n  return right if left.empty?\n\n  smallest_number = if left.first <= right.first\n    left.shift\n  else\n    right.shift\n  end\n  recursive = merge(left, right)\n  [smallest_number].concat(recursive)\nend\n\narr = [1,8,4,5,7,3,9,2,6]\nsort(arr)\n# => [1, 2, 3, 4, 5, 6, 7, 8, 9]\n"
  },
  {
    "path": "algorithms/minimum_spanning_tree/cpp/MST.cpp",
    "content": "#include<bits/stdc++.h>\n#include<algorithm>\nusing namespace std;\nint parent[1000];\nint size[1000];\n\n//// union find\nvoid init()\n{\n\tfor(int i=0;i<1000;i++)\n\t{\n\t\tparent[i]=i;\n\t}\n\n}\nint root(int i)\n{\n\twhile(parent[i]!=i)\n\t{\n\t\tparent[i]=parent[parent[i]];\n\t\ti=parent[i];\n\t}\n\treturn i;\n}\nvoid unio(int a,int b)\n{\n\tint root_a=root(a);\n\tint root_b=root(b);\n\tparent[root_a]=parent[root_b];\n}\n\n////// krushkal()\n#define ll long long\n#define mp make_pair\nvector<pair <int, pair<int,int> > > v;\nll nodes,edges;\n\nll kruskal(){\n\n int x,y;\n ll cost=0,mincost=0;\n // step 2. loop through sorted array until all nodes are in same set\n for(ll i=0;i<edges;i++)\n {\n \tx=v[i].second.first;\n \ty=v[i].second.second;\n \tcost=v[i].first;\n \tif(root(x)!=root(y))\n \t{\n \t\tmincost+=cost;\n \t\tunio(x,y);\n \t}\n }\n return mincost;\n }\n\n\nint main()\n{\ninit();\ncin>>nodes>>edges;\nfor(int i=0;i<edges;++i)\n{\n\tint a,b;\n\tint w;\n\tcin>>a>>b>>w;\n\tv.push_back(make_pair(w, make_pair(a, b)));\n}\n// 1. step is to sort all the edges by its weights\nsort(v.begin(),v.end());\ncout<<\"ans =\"<<kruskal();\n}\n"
  },
  {
    "path": "algorithms/optimal_binary_search_tree/java/OptimalBst.java",
    "content": "import javax.lang.model.element.Element;\n\npublic class OptimalBst {\n\t\n\tstatic int[] elements = {5,6,8,20};\n\t\n\tstatic int[] access = {4,2,6,3} ;\n\t\n\tpublic static void main(String[] args) {\n\t\t\n\t\tint len = elements.length ;\n\t\t\n\t\tint[][] solution = new int[len][len] ;\n\t\t\n\t\tfor (int i = 0; i < solution.length; i++) {\n\t\t\tfor (int j = 0; j < solution.length; j++) {\n\t\t\t\tsolution[i][j] = 0 ;\n\t\t\t}\n\t\t}\n\t\t\n\t\tfor (int i = 0; i < solution.length; i++) {\n\t\t\tfor (int j = 0; j < solution.length; j++) {\n\t\t\t\tif(i == j) {\n\t\t\t\t\tsolution[i][j] = access[i] ;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tfor (int i = 0 ; i < solution.length-1 ; i++) {\n\t\t\t\n\t\t\tfor (int j = 0; j < solution.length - 1; j++) {\n\t\t\t\t\n\t\t\t\tfor (int k = i+j+1 ; k < solution.length ; k++) {\n\t\t\t\t\t\n\t\t\t\t\tif(k == i+j+1) {\n\t\t\t\t\t\tsolution[j][k] = findMinimum(solution , j , k);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t for (int i = 0; i < solution.length; i++) {\n\t\t\tfor (int j = 0; j < solution.length; j++) {\n\t\t\t\tSystem.out.print(solution[i][j] + \" \");\n\t\t\t}\n\t\t\tSystem.out.println();\n\t\t} \n\t\t\n\t\tSystem.out.println(\"\\nCost of Optimal Binary Search Tree : \" + solution[0][solution.length - 1]);\n\t\t\n\t}\n\t\n\tpublic static int findMinimum(int[][] array , int i , int j){\n\t\t\n\t\tint min = Integer.MAX_VALUE ;\n\t\tint baseSum = 0 ;\n\t\t\n\t\tfor (int k = i ; k <= j ; k++) {\n\t\t\tbaseSum += access[k] ;\t\t\t\n\t\t}\n\t\t\n\t\tfor (int k = i ; k <= j ; k++) {\n\t\t\t\n\t\t\tint temp = 0 ;\n\t\t\t\n\t\t\tif(k == i) {\n\t\t\t\ttemp = baseSum +  array[k+1][j] ;\n\t\t\t}else if(k == j) {\n\t\t\t\ttemp = baseSum +  array[i][j-1] ;\n\t\t\t}else{\n\t\t\t\ttemp = baseSum +  array[i][k-1] + +  array[k+1][j] ;\n\t\t\t}\n\t\t\t\n\t\t\tif(temp <= min) {\n\t\t\t\tmin = temp ;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn min ;\n\t\t\n\t}\n\t\n\n}\n"
  },
  {
    "path": "algorithms/parse_tree/python/parse_tree.py",
    "content": "class Stack:\n     def __init__(self):\n         self.items = []\n\n     def isEmpty(self):\n         return self.items == []\n\n     def push(self, item):\n         self.items.append(item)\n\n     def pop(self):\n         return self.items.pop()\n\n     def peek(self):\n         return self.items[len(self.items)-1]\n\n     def size(self):\n         return len(self.items)\n\nclass BinaryTree:\n    def __init__(self,rootObj):\n        self.key = rootObj\n        self.leftChild = None\n        self.rightChild = None\n\n    def insertLeft(self,newNode):\n        if self.leftChild == None:\n            self.leftChild = BinaryTree(newNode)\n        else:\n            t = BinaryTree(newNode)\n            t.leftChild = self.leftChild\n            self.leftChild = t\n\n    def insertRight(self,newNode):\n        if self.rightChild == None:\n            self.rightChild = BinaryTree(newNode)\n        else:\n            t = BinaryTree(newNode)\n            t.rightChild = self.rightChild\n            self.rightChild = t\n\n\n    def getRightChild(self):\n        return self.rightChild\n\n    def getLeftChild(self):\n        return self.leftChild\n\n    def setRootVal(self,obj):\n        self.key = obj\n\n    def getRootVal(self):\n        return self.key\n\n\ndef buildParseTree(fpexp):\n    fplist = fpexp.split()\n    pStack = Stack()\n    eTree = BinaryTree('')\n    pStack.push(eTree)\n    currentTree = eTree\n    for i in fplist:\n        if i == '(':\n            currentTree.insertLeft('')\n            pStack.push(currentTree)\n            currentTree = currentTree.getLeftChild()\n        elif i not in ['+', '-', '*', '/', ')']:\n            currentTree.setRootVal(int(i))\n            parent = pStack.pop()\n            currentTree = parent\n        elif i in ['+', '-', '*', '/']:\n            currentTree.setRootVal(i)\n            currentTree.insertRight('')\n            pStack.push(currentTree)\n            currentTree = currentTree.getRightChild()\n        elif i == ')':\n            currentTree = pStack.pop()\n        else:\n            raise ValueError\n    return eTree\n\ndef evaluate(parseTree):\n    opers = {'+':operator.add, '-':operator.sub, '*':operator.mul, '/':operator.truediv}\n\n    leftC = parseTree.getLeftChild()\n    rightC = parseTree.getRightChild()\n\n    if leftC and rightC:\n        fn = opers[parseTree.getRootVal()]\n        return fn(evaluate(leftC),evaluate(rightC))\n    else:\n        return parseTree.getRootVal()\n"
  },
  {
    "path": "algorithms/permutations/java/Permutation.java",
    "content": "//Backtracking solution\npublic class Permutation\n{\n    public void permute(String str, int l, int r)\n    {\n        if (l == r)\n            System.out.println(str);\n        else\n        {\n            for (int i = l; i <= r; i++)\n            {\n                str = swap(str,l,i);\n\n                permute(str, l+1, r);\n                str = swap(str,l,i);\n\n            }\n        }\n    }\n \n   \n    public String swap(String a, int i, int j)\n    {\n        char temp;\n        char[] charArray = a.toCharArray();\n        temp = charArray[i] ;\n        charArray[i] = charArray[j];\n        charArray[j] = temp;\n        return String.valueOf(charArray); \n    }\n    \n    public static void main(String[] args)\n    {\n        String str = \"ABCD\";\n        int n = str.length();\n        Permutation permutation = new Permutation();\n        permutation.permute(str, 0, n-1);\n    }\n \n}"
  },
  {
    "path": "algorithms/permutations/javascript/permutations.js",
    "content": "// Takes an Array, arr, and returns an Array of all permutations of arr\n\nconst permutations = function(arr) {\n  let result = [];\n\n  permute(arr, [], result);\n\n  return result;\n};\n\nconst permute = (arr, m = [], result) => {\n  if (arr.length === 0) {\n    result.push(m);\n\n  } else {\n    for (let i = 0; i < arr.length; i++) {\n      let current = arr.slice();\n      let next = current.splice(i, 1);\n\n      permute(current.slice(), m.concat(next), result);\n    };\n  };\n};\n"
  },
  {
    "path": "algorithms/quick_sort/ada/quick_sort.adb",
    "content": "with Ada.Containers.Vectors;\nwith Ada.Numerics.Discrete_Random;\nwith Ada.Text_IO;\nwith Ada.Integer_Text_IO;\n\nuse Ada.Text_IO;\nuse Ada.Integer_Text_IO;\n\nprocedure Quick_Sort is\n\n   ------------------------------\n   -- Constant, types, package --\n   ------------------------------\n\n   ARRAY_SIZE : constant Natural := 10;\n   RANGE_MIN  : constant Integer := 1;\n   RANGE_MAX  : constant Integer := 100;\n\n   package P_Vectors is new Ada.Containers.Vectors (Positive, Integer);\n   use P_Vectors;\n\n   -----------------------\n   --  Method prototype --\n   -----------------------\n\n   --  Initializing an array with default values\n   function Init_Vector return Vector;\n\n   procedure Put (Tab : Vector);\n\n   procedure Swap (a : in out Integer; b : in out Integer);\n\n   function Sort (T : Vector) return Vector;\n\n   -----------------------------\n   --  Declaration of methods --\n   -----------------------------\n\n   function Init_Vector return Vector\n   is\n      subtype T_Interval is Integer range RANGE_MIN .. RANGE_MAX;\n      package P_Random is new Ada.numerics.discrete_random (T_Interval);\n      use P_Random;\n\n      seed : Generator;\n      T    : Vector;\n   begin\n      Reset (seed);\n\n      for i in 1 .. ARRAY_SIZE loop\n         Append (T, Random (seed));\n      end loop;\n\n      return T;\n   end Init_Vector;\n\n   procedure Put (Tab : Vector)\n   is\n   begin\n      for e of Tab loop\n         Put (e, Width => 0);\n         Put (\";\");\n      end loop;\n   end Put;\n\n   procedure Swap (a : in out Integer; b : in out Integer)\n   is\n      c : constant Integer := a;\n   begin\n      a := b;\n      b := c;\n   end Swap;\n\n   function Sort (T : Vector) return Vector\n   is\n\n      -----------------------\n      --  Method prototype --\n      -----------------------\n\n      procedure Sort (T           : in out Vector;\n                      First, Last :        Integer);\n\n      -----------------------------\n      --  Declaration of methods --\n      -----------------------------\n\n      procedure Sort (T           : in out Vector;\n                      First, Last :        Integer)\n      is\n         Pivot : Integer := (First + Last) / 2;\n         j     : Integer := First + 1;\n      begin\n         if First < Last then\n            Swap (T (First), T (Pivot));\n            Pivot := First;\n            for i in First + 1 .. Last loop\n               if T (i) < T (Pivot) then\n                  Swap (T (i), T (j));\n                  j := j + 1;\n               end if;\n            end loop;\n\n            Swap (T (Pivot), T (j - 1));\n            Pivot := j - 1;\n\n            Sort (T, First, Pivot - 1);\n            Sort (T, Pivot + 1, Last);\n         end if;\n      end Sort;\n\n      ---------------\n      -- Variables --\n      ---------------\n\n      Tab : Vector := T;\n   begin\n      Sort (Tab, First_Index (Tab), Last_Index (Tab));\n      return Tab;\n   end Sort;\n\n   ---------------\n   -- Variables --\n   ---------------\n\n   T : Vector := Init_Vector;\nbegin\n   Put (\"Array        : \");\n   Put (T);\n   New_Line;\n\n   T := Sort (T);\n\n   Put (\"Sorted array : \");\n   Put (T);\nend Quick_Sort;\n"
  },
  {
    "path": "algorithms/quick_sort/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": "algorithms/quick_sort/cpp/quickSort.cpp",
    "content": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nvoid quickSort(vector<int>&,int,int);\n\nint partition(vector<int>&, int,int);\n\nint main()\n{\n    vector<int> A = {6,10,13,5,8,3,2,25,4,11};\n    int start = 0;\n    int end = 10;\n\n    cout << \"Before:\" << endl;\n    for(auto value : A)\n        cout << value <<\" \";\n    cout << endl;    \n\n    quickSort(A, start, end);\n\n    cout << \"After: \" << endl;\n    for(auto value : A)\n        cout << value <<\" \";\n    cout << endl;   \n}\n\n\nvoid quickSort(vector<int>& A, int start,int end)\n{\n    int pivot;\n    if(start < end)\n    {\n        pivot=partition(A, start, end);\n        quickSort(A, start, pivot);  \n        quickSort(A, pivot+1, end);\n    }\n}\n\n\nint partition(vector<int>& A, int start,int end)\n{\n    int x = A[start];\n    int i = start;\n    int j;\n\n    for(j = start+1; j < end; j++)\n    {\n        if(A[j]<=x)\n        {\n            i=i+1;\n\t\t\tswap(A[i],A[j]);\n        }\n\n    }\n\n    swap(A[i],A[start]);\n    return i;\n}\n"
  },
  {
    "path": "algorithms/quick_sort/csharp/QuickSort.cs",
    "content": "using System;\n\nnamespace QuickSort\n{\n    class QuickSort\n    {\n        static void Main(string[] args)\n        {\n            int[] array = { 3, 10, 7, 9, 1, 5, 8 };\n\n            QuickSort qs = new QuickSort();\n            qs.Sort(array, 0, array.Length - 1);\n\n            foreach (var item in array)\n            {\n                Console.Write(item.ToString() + \",\");\n            }\n        }\n\n        void Sort(int[] arr, int low, int high)\n        {\n            if (low < high)\n            {\n                int index = Partition(arr, low, high);\n                Sort(arr, low, index - 1);\n                Sort(arr, index + 1, high);\n            }\n        }\n\n        int Partition(int[] arr, int low, int high)\n        {\n            int pivot = arr[high];\n            int i = (low - 1);\n            for (int j = low; j < high; j++)\n            {\n                if (arr[j] <= pivot)\n                {\n                    i++;\n                    int aux = arr[i];\n                    arr[i] = arr[j];\n                    arr[j] = aux;\n                }\n            }\n\n            int temp = arr[i + 1];\n            arr[i + 1] = arr[high];\n            arr[high] = temp;\n\n            return i + 1;\n        }\n    }\n}\n"
  },
  {
    "path": "algorithms/quick_sort/csharp/quicksort.cs",
    "content": "using System;\nusing System.Collections.Generic;\n\n/// <summary>\n/// Class for QuickSort\n/// </summary>\npublic class QuickSort\n{\n    /// <summary>\n    /// Main Function\n    /// </summary>\n    /// <param name=\"args\"></param>\n    private static void Main(string[] args)\n    {\n        // array declaration\n        var arr = new[] { 9, 7, 5, 11, 12, 2, 14, 3, 10, 4, 6 };\n\n        // printing original array\n        Console.Write('\\n');\n        Console.WriteLine(\"Array before Sorting with Bubble Sort\");\n        foreach (var entry in arr)\n        {\n            Console.Write(entry + \"   \");\n        }\n\n        // Sorting Array and printing the sorted array\n        Qsort(arr, 0, arr.Length - 1);\n        Console.Write('\\n');\n        Console.WriteLine(\"Array after Sorting with Bubble Sort\");\n        foreach (var entry in arr)\n        {\n            Console.Write(entry + \"   \");\n        }\n        Console.Read();\n    }\n\n    /// <summary>\n    /// Method for sorting an array\n    /// </summary>\n    /// <param name=\"list\">Takes the array</param>\n    /// <param name=\"left\">Left key</param>\n    /// <param name=\"right\">Right Key</param>\n    private static void Qsort(IList<int> list, int left, int right)\n    {\n        if (left >= right)\n        {\n            return;  // no sorting for array having either one or zero elements\n        }\n\n        var teiler = Partition(list, left, right);\n        Qsort(list, left, teiler - 1);\n        Qsort(list, teiler + 1, right);\n    }\n\n    private static int Partition(IList<int> list, int left, int right)\n    {\n        var i = left;\n        var j = right - 1;\n        var pivot = list[right];\n        do\n        {\n            while (list[i] <= pivot && i < right)\n            {\n                i++;\n            }\n            while (list[j] >= pivot && j > left)\n            {\n                j--;\n            }\n            if (i < j)\n            {\n                Swap(list, i, j);\n            }\n        } while (i < j);\n        if (list[i] > pivot)\n        {\n            Swap(list, i, right);\n        }\n        return i;\n    }\n\n    /// <summary>\n    /// Swapping of two elements\n    /// </summary>\n    /// <param name=\"arr\">Array to be swapped</param>\n    /// <param name=\"i\">i th index</param>\n    /// <param name=\"j\">j th index</param>\n    private static void Swap(IList<int> arr, int i, int j)\n    {\n        var tmp = arr[i];\n        arr[i] = arr[j];\n        arr[j] = tmp;\n    }\n}\n"
  },
  {
    "path": "algorithms/quick_sort/haskell/quicksort.hs",
    "content": "quicksort [] = []\nquicksort (p:xs) = (quicksort lesser) ++ [p] ++ (quicksort greater)\n    where (lesser, greater) = partition (< p) xs"
  },
  {
    "path": "algorithms/quick_sort/java/QuickSort.java",
    "content": "public class QuickSort{\n\tstatic void quickSort(int[] arr,int start, int end){\n\t\tif (start < end){\n\t\t\tint pivot_pos = partition(arr,start,end);\n\t\t\tquickSort (arr,start, pivot_pos-1);\n\t\t\tquickSort (arr,pivot_pos+1, end);\n\t\t}\n\t}\n\t\n\tstatic int partition(int [] arr, int start, int end){\n\t\tint pivot = arr[end];\n\t\tint i = start, j = end - 1;\n\t\twhile (i <= j) {\n\t\t\tif (arr[j] <= pivot && arr[i] > pivot){\n\t\t\t\tswap(arr,i,j);\n\t\t\t}\n\t\t\tif (arr[i] <= pivot) {\n\t\t\t\ti++;\n\t\t\t}\n\t\t\tif (arr [j] > pivot){\n\t\t\t\tj--;\n\t\t\t}\n\t\t}\n\t\tswap(arr,i,end);\n\t\treturn i;\n\t}\n\t\n\tstatic void swap(int[] arr,int i, int j){\n\t\tint tmp = arr[i] ;\n\t\tarr[i] = arr[j];\n\t\tarr[j] = tmp;\n\t}\n\t\n\tstatic void print(int [] arr){\n\t\tfor (int i = 0; i < arr.length; i++)\n\t\t\tSystem.out.print(arr[i] + \" \");\n\t\tSystem.out.println();\n\t}\n\t\n\tpublic static void main(String [] args){\n\t\tint [] arr = {9, 7, 5, 11, 12, 2, 14, 3, 10, 4, 6};\n\t\tSystem.out.print(\"Before: \");\n\t\tprint(arr);\n\t\tquickSort(arr,0, arr.length-1);\n\t\tSystem.out.print(\"After: \");\n\t\tprint(arr);\n\t}\n}\n"
  },
  {
    "path": "algorithms/quick_sort/javascript/quick_sort.js",
    "content": "/* Quicksort implementation in JavaScript */\n\nfunction quicksort(arr, p, r) {\n\tif ( p < r ) {\n\t\tq = partition(arr, p, r);\n\t\tquicksort(arr, p, q-1);\n\t\tquicksort(arr, q+1, r);\n\t}\n\treturn arr;\n}\n\n\nfunction partition(arr, p, r) {\n\tx = arr[r];\n\ti = p-1;\n\tvar temp;\n\tfor(var j = p; j < r; j++) {\n\t\tif (arr[j] < x) {\n\t\t\ti++;\n\t\t\ttemp = arr[i];\n\t\t\tarr[i] = arr[j];\n\t\t\tarr[j] = temp;\n\t\t}\n\t}\n\ti++;\n\ttemp = arr[i];\n\tarr[i] = arr[r];\n\tarr[r] = temp;\n\n\treturn i;\n}\n\t\n\nvar arr = [9, 8, 7, 6, 5, 4, 3, 2, 1];\nconsole.log(quicksort(arr, 0, arr.length-1));\n"
  },
  {
    "path": "algorithms/quick_sort/kotlin/quicksort.kt",
    "content": "class QuickSort {\n    private fun quickSort(arr: IntArray, start: Int, end: Int) {\n        if (start < end) {\n            val pivot_pos = partition(arr, start, end)\n            quickSort(arr, start, pivot_pos - 1)\n            quickSort(arr, pivot_pos + 1, end)\n        }\n    }\n\n    private fun partition(arr: IntArray, start: Int, end: Int): Int {\n        val pivot = arr[end]\n        var i = start\n        var j = end - 1\n        while (i <= j) {\n            if (arr[j] <= pivot && arr[i] > pivot) {\n                swap(arr, i, j)\n            }\n            if (arr[i] <= pivot) {\n                i++\n            }\n            if (arr[j] > pivot) {\n                j--\n            }\n        }\n        swap(arr, i, end)\n        return i\n    }\n\n    private fun swap(arr: IntArray, i: Int, j: Int) {\n        val tmp = arr[i]\n        arr[i] = arr[j]\n        arr[j] = tmp\n    }\n\n    private fun print(arr: IntArray) {\n        for (i in arr.indices) {\n            print(arr[i].toString() + \" \")\n        }\n        print('\\n')\n    }\n\n    fun main() {\n        val arr = intArrayOf(9, 7, 5, 11, 12, 2, 14, 3, 10, 4, 6)\n        print(\"Before: \")\n        print(arr)\n        quickSort(arr, 0, arr.size - 1)\n        print(\"After: \")\n        print(arr)\n    }\n}\n"
  },
  {
    "path": "algorithms/quick_sort/python/quicksort.py",
    "content": "def partition(li, start, end):\n    pivot = li[start]\n    left = start + 1\n    right = end\n    done = False\n\n    while not done:\n        while left <= right and li[left] <= pivot:\n            left += 1\n        while right >= left and li[right] >= pivot:\n            right -= 1\n        if right < left:\n            done = True\n        else:\n            li[left], li[right] = li[right], li[left]\n    li[start], li[right] = li[right], li[start]\n    return right\n\n\ndef quicksort(li, start=0, end=None):\n    if not end:\n        end = len(li) - 1\n    if start < end:\n        pivot = partition(li, start, end)\n        # Recursively perform same operation on first and last halves of list\n        quicksort(li, start, pivot - 1)\n        quicksort(li, pivot + 1, end)\n    return li\n"
  },
  {
    "path": "algorithms/quick_sort/ruby/quick_sort.rb",
    "content": "def quicksort(array)\n  return array if array.length <= 1\n\n  pivot_index = (array.length / 2).to_i\n  pivot_value = array[pivot_index]\n  array.delete_at(pivot_index)\n\n  lesser = Array.new\n  greater = Array.new\n\n  array.each do |x|\n    if x <= pivot_value\n      lesser << x\n    else\n      greater << x\n    end\n  end\n\n  quicksort(lesser) + [pivot_value] + quicksort(greater)\nend\n\narr = [1,8,4,5,7,3,9,2,6]\nquicksort(arr)\n# => [1, 2, 3, 4, 5, 6, 7, 8, 9]\n"
  },
  {
    "path": "algorithms/rabin_karp/java/RabinKarp.java",
    "content": "import java.math.BigInteger;\nimport java.util.Random;\npublic class RabinKarp {\nprivate long patHash;\n    private int M;\n    private long Q;\n    private int R;\n    private long RM;\n    public RabinKarp(String pat)\n    {\n        M=pat.length();\n        R=256;\n        Q=longPrimeNumber();\n        RM=1;\n        for (int i=1;i<=M-1;i++)\n        {\n            RM=(R*RM)%Q;\n        }\n    }\n    private long hash(String key,int M)\n    {\n        long h=0;\n        for (int i=0;i<M;i++)\n        {\n            h=(R*h+key.charAt(i))%Q;\n        }\n        return h;\n    }\n    public int search(String txt)\n    {\n        int N=txt.length();\n        long txtHash=hash(txt,M);\n        for (int i=M;i<N;i++)\n        {\n            txtHash=(txtHash+Q-RM*txt.charAt(i-M)%Q)%Q;\n            txtHash=(R*txtHash+txt.charAt(i))%Q;\n            if (patHash==txtHash)\n                return i+M-1;\n        }\n        return N;\n    }\n    private static long longPrimeNumber()\n    {\n        BigInteger prime=BigInteger.probablePrime(31,new Random());\n        return prime.longValue();\n    }\n\n}\n"
  },
  {
    "path": "algorithms/radixsort/c++/radixsort.cpp",
    "content": "# include <iostream>\n\nusing namespace std; \n  \nint getMax(int arr[], int n) \n{ \n    int mx = arr[0]; \n    for (int i = 1; i < n; i++) \n        if (arr[i] > mx) \n            mx = arr[i]; \n    return mx; \n} \n  \nvoid countSort(int arr[], int n, int exp) \n{ \n\tint output[n]; \n\tint i, count[10] = {0}; \n\tfor (i = 0; i < n; i++) \n\t\tcount[ (arr[i]/exp)%10 ]++; \n\n\tfor (i = 1; i < 10; i++) \n\t\tcount[i] += count[i - 1]; \n\n\tfor (i = n - 1; i >= 0; i--) \n\t{ \n\t\toutput[count[ (arr[i]/exp)%10 ] - 1] = arr[i]; \n\t\tcount[ (arr[i]/exp)%10 ]--; \n\t} \n\n\tfor (i = 0; i < n; i++) \n\t\tarr[i] = output[i]; \n} \n  \nvoid radixsort(int arr[], int n) \n{ \n    int m = getMax(arr, n); \n    for (int exp = 1; m/exp > 0; exp *= 10) \n        countSort(arr, n, exp); \n} \n  \nvoid print(int arr[], int n) \n{ \n    for (int i = 0; i < n; i++) \n        cout << arr[i] << \" \"; \n} \n\nint main() \n{ \n    int arr[] = {170, 45, 75, 90, 802, 24, 2, 66}; \n    int n = sizeof(arr)/sizeof(arr[0]); \n    radixsort(arr, n); \n    print(arr, n); \n    return 0; \n}\n"
  },
  {
    "path": "algorithms/radixsort/python/lsd_radixsort.py",
    "content": "import functools\n\n\ndef get_digit(number, digit):\n    return int((number % (10 ** digit)) / (10 ** (digit - 1)))\n\n\ndef lsd_radix_sort(array):\n    MAX_DIGITS = 10\n    for digit in range(1, MAX_DIGITS + 1):\n        buckets = [[] for _ in range(10)]\n        for number in array:\n            buckets[get_digit(number, digit)].append(number)\n        array = functools.reduce(lambda x, y: x + y, buckets, [])\n    return array\n\n\nif __name__ == '__main__':\n    print (lsd_radix_sort([43, 1243, 354, 0, 1, 22]))\n    print (lsd_radix_sort([2, 10]))\n    print (lsd_radix_sort([1]))\n    print (lsd_radix_sort([]))\n"
  },
  {
    "path": "algorithms/selection_sort/c/SelectionSort.c",
    "content": "#include<stdio.h>\n\nconst int SIZE=100;\n\nvoid SelectionSort(int arr[SIZE]){\n  int i,j,temp,min=999999,index;\n  for (i = 0; i < SIZE; i++) {\n    for (j = i; j < SIZE; j++) {\n      if(arr[j]<min){\n        min=arr[j];\n        index=j;\n      }\n    }\n    temp=arr[i];\n    arr[i]=arr[index];\n    arr[index]=temp;\n    index=0;\n    min=999999;\n  }\n\n}\n\nvoid main(){\n\tint i;\n\tint arr[SIZE];\n\tprintf(\"Enter the unsorted array\\n\");\n\tfor(i=0;i<SIZE;i++)\n\t\tscanf(\"%d\",&arr[i]);\n\tSelectionSort(arr);\t\n\tprintf(\"Sorted array is\\n\");\n\tfor(i=0;i<SIZE;i++)\n\t\tprintf(\"%d \",arr[i]);\n}\n"
  },
  {
    "path": "algorithms/selection_sort/crystal/selection_sort.cr",
    "content": "def selection_sort(array)\n  i = 0\n\n  loop do\n    j = i\n    min_index = i\n\n    loop do\n      if array[min_index] > array[j]\n        min_index = j\n      end\n      j += 1\n      break if j == array.size\n    end\n\n    array[i], array[min_index] = array[min_index], array[i]\n\n    i += 1\n    break if i == array.size\n  end\n\n  array\nend\n\nnumbers = [4, 2, 8, 1, 30, 0, 10, 16]\n\nputs \"Unsorted: #{numbers}\"\n\nputs \"Sorted: #{selection_sort(numbers)}\"\n"
  },
  {
    "path": "algorithms/selection_sort/java/SelectionSort.java",
    "content": "// Java program for implementation of Selection Sort\nclass SelectionSort\n{\n    // Implementation of Selection Sort\n    void sort(int ar[])\n    {\n        int n = ar.length;\n        for (int i = 0; i < n-1; i++)\n        {\n            int min = i, temp;\n            for (int j = i+1; j < n; j++)\n                if (ar[j] < ar[min]){\n                    min = j;\n            }\n            temp = ar[min];\n            ar[min] = ar[i];\n            ar[i] = temp;\n        }\n    }\n    // Prints the array\n    void printArray(int arr[])\n    {\n        int n = arr.length;\n        for (int i = 0; i < n; i++)\n            System.out.print(arr[i] + \" \");\n    }\n    // Main function to test\n    public static void main(String args[])\n    {\n        SelectionSort ob = new SelectionSort();\n        int arr[] = {79, 34, 7, 23, 11, 10, 99, 1, 15, 11};\n        ob.sort(arr);\n        System.out.println(\"Sorted array:\");\n        ob.printArray(arr);\n    }\n}\n"
  },
  {
    "path": "algorithms/selection_sort/javascript/selection_sort.js",
    "content": "var selectionSort = function(array){\n  for(var i = 0; i < array.length; i++){\n    //set min to the current iteration of i\n    var min = i;\n    for(var j = i+1; j < array.length; j++){\n      if(array[j] < array[min]){\n       min = j;\n      }\n    }\n    var temp = array[i];\n    array[i] = array[min];\n    array[min] = temp;\n  }\n  return array;\n};\n"
  },
  {
    "path": "algorithms/selection_sort/python/selection_sort.py",
    "content": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Oct 1 21:17 2017\n@author: john2ksonn\n\nJust a simple implementation of the selectionsort algo\n\"\"\"\n\ndef selectionsort(a):\n    n = len(a)\n    left = 0\n    while left < n:\n        minVal = left\n        for i in range(left + 1, n):\n            if(a[i] < a[minVal]):\n                minVal = i\n        temp = a[left]\n        a[left] = a[minVal]\n        a[minVal] = temp\n        left += 1\n\n\na = [12, 33, 1, 3, 54, 32, 78, 54, 99, 6]\nprint(a)\nselectionsort(a)\nprint(a)\n"
  },
  {
    "path": "algorithms/selection_sort/ruby/selection_sort.rb",
    "content": "def selection_sort(input_arr)\n  arr = input_arr.dup\n  n = arr.size - 1\n\n  n.times do |i|\n    index_min = i\n    (i + 1).upto(n) do |j|\n      index_min = j if arr[j] < arr[index_min]\n    end\n    arr[i], arr[index_min] = arr[index_min], arr[i] if index_min != i\n  end\n  arr\nend\n\narr = [1,8,4,5,7,3,9,2,6]\nselection_sort(arr)\n# => [1, 2, 3, 4, 5, 6, 7, 8, 9]\n"
  },
  {
    "path": "algorithms/shell_sort/C/ShellSort.c",
    "content": "#include <stdio.h>\n\nvoid shellsort(int arr[], int num)\n{\n    int i, j, k, tmp;\n    for (i = num / 2; i > 0; i = i / 2)\n    {\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\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    int arr[] = {12, 34, 54, 2, 3}, i;\n    int n = sizeof(arr)/sizeof(arr[0]);\n    shellsort(arr, n);\n    printf(\"\\n Sorted array is: \");\n    for (i = 0; i < n; i++)\n        printf(\"%d \", arr[i]);\n    return 0;\n\n}\n"
  },
  {
    "path": "algorithms/shell_sort/C++/ShellSort.cpp",
    "content": "// C++ implementation of Shell Sort\n#include  <iostream>\nusing namespace std;\n \n/* function to sort arr using shellSort */\nint shellSort(int arr[], int n)\n{\n    // Start with a big gap, then reduce the gap\n    for (int gap = n/2; gap > 0; gap /= 2)\n    {\n        // Do a gapped insertion sort for this gap size.\n        // The first gap elements a[0..gap-1] are already in gapped order\n        // keep adding one more element until the entire array is\n        // gap sorted \n        for (int i = gap; i < n; i += 1)\n        {\n            // add a[i] to the elements that have been gap sorted\n            // save a[i] in temp and make a hole at position i\n            int temp = arr[i];\n \n            // shift earlier gap-sorted elements up until the correct \n            // location for a[i] is found\n            int j;            \n            for (j = i; j >= gap && arr[j - gap] > temp; j -= gap)\n                arr[j] = arr[j - gap];\n             \n            //  put temp (the original a[i]) in its correct location\n            arr[j] = temp;\n        }\n    }\n    return 0;\n}\n \nvoid printArray(int arr[], int n)\n{\n    for (int i=0; i<n; i++)\n        cout << arr[i] << \" \";\n}\n \nint main()\n{\n    int arr[] = {12, 34, 54, 2, 3}, i;\n    int n = sizeof(arr)/sizeof(arr[0]);\n \n    cout << \"Array before sorting: \\n\";\n    printArray(arr, n);\n \n    shellSort(arr, n);\n \n    cout << \"\\nArray after sorting: \\n\";\n    printArray(arr, n);\n \n    return 0;\n}"
  },
  {
    "path": "algorithms/shell_sort/Java/ShellSort.java",
    "content": "// Java implementation of ShellSort\nclass ShellSort\n{\n\t/* An utility function to print array of size n*/\n\tstatic void printArray(int arr[])\n\t{\n\t\tint n = arr.length;\n\t\tfor (int i=0; i<n; ++i)\n\t\t\tSystem.out.print(arr[i] + \" \");\n\t\tSystem.out.println();\n\t}\n\n\t/* function to sort arr using shellSort */\n\tint sort(int arr[])\n\t{\n\t\tint n = arr.length;\n\n\t\t// Start with a big gap, then reduce the gap\n\t\tfor (int gap = n/2; gap > 0; gap /= 2)\n\t\t{\n\t\t\t// Do a gapped insertion sort for this gap size.\n\t\t\t// The first gap elements a[0..gap-1] are already\n\t\t\t// in gapped order keep adding one more element\n\t\t\t// until the entire array is gap sorted\n\t\t\tfor (int i = gap; i < n; i += 1)\n\t\t\t{\n\t\t\t\t// add a[i] to the elements that have been gap\n\t\t\t\t// sorted save a[i] in temp and make a hole at\n\t\t\t\t// position i\n\t\t\t\tint temp = arr[i];\n\n\t\t\t\t// shift earlier gap-sorted elements up until\n\t\t\t\t// the correct location for a[i] is found\n\t\t\t\tint j;\n\t\t\t\tfor (j = i; j >= gap && arr[j - gap] > temp; j -= gap)\n\t\t\t\t\tarr[j] = arr[j - gap];\n\n\t\t\t\t// put temp (the original a[i]) in its correct\n\t\t\t\t// location\n\t\t\t\tarr[j] = temp;\n\t\t\t}\n\t\t}\n\t\treturn 0;\n\t}\n\n\t// Driver method\n\tpublic static void main(String args[])\n\t{\n\t\tint arr[] = {12, 34, 54, 2, 3};\n\t\tSystem.out.println(\"Array before sorting\");\n\t\tprintArray(arr);\n\n\t\tShellSort ob = new ShellSort();\n\t\tob.sort(arr);\n\n\t\tSystem.out.println(\"Array after sorting\");\n\t\tprintArray(arr);\n\t}\n}\n"
  },
  {
    "path": "algorithms/shell_sort/python/shellsort.py",
    "content": "def shellSort(arr):\n \n    # Start with a big gap, then reduce the gap\n    n = len(arr)\n    gap = n/2\n \n    # Do a gapped insertion sort for this gap size.\n    # The first gap elements a[0..gap-1] are already in gapped \n    # order keep adding one more element until the entire array\n    # is gap sorted\n    while gap > 0:\n \n        for i in range(gap,n):\n \n            # add a[i] to the elements that have been gap sorted\n            # save a[i] in temp and make a hole at position i\n            temp = arr[i]\n \n            # shift earlier gap-sorted elements up until the correct\n            # location for a[i] is found\n            j = i\n            while  j >= gap and arr[j-gap] >temp:\n                arr[j] = arr[j-gap]\n                j -= gap\n \n            # put temp (the original a[i]) in its correct location\n            arr[j] = temp\n        gap /= 2\n"
  },
  {
    "path": "algorithms/sieve_of_eratosthenes/cpp/sieve_of_eratosthenes.cpp",
    "content": "// C++ program to print all primes smaller than or equal to\n// n using Sieve of Eratosthenes\n#include <bits/stdc++.h>\nusing namespace std;\n\nvoid SieveOfEratosthenes(int n)\n{\n    // Create a boolean array \"prime[0..n]\" and initialize\n    // all entries it as true. A value in prime[i] will\n    // finally be false if i is Not a prime, else true.\n    bool prime[n+1];\n    memset(prime, true, sizeof(prime));\n\n    for (int p=2; p*p<=n; p++)\n    {\n        // If prime[p] is not changed, then it is a prime\n        if (prime[p] == true)\n        {\n            // Update all multiples of p\n            for (int i=p*2; i<=n; i += p)\n                prime[i] = false;\n        }\n    }\n\n    // Print all prime numbers\n    for (int p=2; p<=n; p++)\n       if (prime[p])\n          cout << p << \" \";\n}\n\n// Driver Program to test above function\nint main()\n{\n    int n = 100;\n    cout << \"Following are the prime numbers smaller \"\n         << \" than or equal to \" << n << endl;\n    SieveOfEratosthenes(n);\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/sieve_of_eratosthenes/java/sieve.java",
    "content": "import java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\n \npublic class sieve\n{\n\t/*\n\t * Function which finds all the prime numbers less than or equal to n\n\t */\n    private void sievefunction(int n, boolean primearr[])\n    {    \n    \tint i;\n    \tint j;\n    \t\n    \t// Begin from the first prime (2)\n        for(i = 2 ; i*i<=n ; i++)\n        {\n        \t// remove the multipes of the number i if it is prime\n            if(primearr[i] == true)\n            {\n            \t// loops into all the multiples of i sby incrementing with i at every step\n                for(j = i*2 ; j<=n ; j = j+i)\n                {\n                \t// marking them as false since they are not prime\n                    primearr[j] = false;\n                }\n            }\n        }\n    }\n    \n    /*\n     * Function for printing all the primes obtained in the end\n     */\n    private void print(int n, boolean primearr[])\n    {\n    \tint k;\n    \tfor(k = 2 ; k<=n; k++)\n        {\n            if(primearr[k] == true)\n            {\n                System.out.print(k + \" \");\n            }\n        }\n    }\n    \n    public static void main(String args[]) throws IOException\n    {\n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n        String a = br.readLine(); // Take user input\n    \tint n = Integer.parseInt(a); // n denotes the number upto which primes have to be displayed\n    \t\n    \t// initialise the boolean array primearr with all true values\n    \t// at the end of the algorithm only those values will be true that are prime\n    \tboolean[] primearr = new boolean[n+1];\n    \tfor(int i = 0 ; i<=n ; i++)\n    \t{\n    \t\tprimearr[i] = true;\n    \t}\n    \t\n        sieve g = new sieve();\n        \n        // calling the sievefunction given n and boolean primearr\n        g.sievefunction(n, primearr);\n        \n        // printing the primes obtained in the end\n        g.print(n, primearr);\n    }\n}\n \n"
  },
  {
    "path": "algorithms/sieve_of_eratosthenes/javascript/sieve.js",
    "content": "let sieveOfEratosthenes = function(n) {\n  let array = [];\n  let upperLimit = Math.sqrt(n);\n  let output = [];\n\n  for (let i = 0; i < n; i++) {\n    array.push(true);\n  }\n\n  for (let i = 2; i <= upperLimit; i++) {\n    if (array[i]) {\n      for (let j = i * i; j < n; j += i) {\n        array[j] = false;\n      }\n    }\n  }\n\n  for (let i = 2; i < n; i++) {\n    if (array[i]) {\n      output.push(i);\n    }\n  }\n\n  return output;\n};\n"
  },
  {
    "path": "algorithms/sieve_of_eratosthenes/python/sieve.py",
    "content": "def run_sieve(N, isPrime):\n    for i in range(N+1):\n        if isPrime[i]:\n            for j in range(i+1, N+1):\n                if j % i == 0:\n                    isPrime[j] = False\n\n\ndef print_sieve(N, isPrime):\n    for i in range(N+1):\n        if isPrime[i]:\n            print i,\n\n\ndef sieve(N):\n    isPrime = [True] * (N+1)\n    isPrime[0], isPrime[1] = False, False\n    run_sieve(N, isPrime)\n    print_sieve(N, isPrime)\n\n\nsieve(int(input(\"Input size of sieve: \")))\n"
  },
  {
    "path": "algorithms/sort/heap_sort/java/heap_sort.java",
    "content": "// Java program for implementation of Heap Sort\npublic class HeapSort\n{\n    public void sort(int arr[])\n    {\n        int n = arr.length;\n \n        // Build heap (rearrange array)\n        for (int i = n / 2 - 1; i >= 0; i--)\n            heapify(arr, n, i);\n \n        // One by one extract an element from heap\n        for (int i=n-1; i>=0; i--)\n        {\n            // Move current root to end\n            int temp = arr[0];\n            arr[0] = arr[i];\n            arr[i] = temp;\n \n            // call max heapify on the reduced heap\n            heapify(arr, i, 0);\n        }\n    }\n \n    // To heapify a subtree rooted with node i which is\n    // an index in arr[]. n is size of heap\n    void heapify(int arr[], int n, int i)\n    {\n        int largest = i;  // Initialize largest as root\n        int l = 2*i + 1;  // left = 2*i + 1\n        int r = 2*i + 2;  // right = 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    /* A utility function to print array of size n */\n    static void printArray(int arr[])\n    {\n        int n = arr.length;\n        for (int i=0; i<n; ++i)\n            System.out.print(arr[i]+\" \");\n        System.out.println();\n    }\n \n    // Driver program\n    public static void main(String args[])\n    {\n        int arr[] = {12, 11, 13, 5, 6, 7};\n        int n = arr.length;\n \n        HeapSort ob = new HeapSort();\n        ob.sort(arr);\n \n        System.out.println(\"Sorted array is\");\n        printArray(arr);\n    }\n}\n"
  },
  {
    "path": "algorithms/strings/cpp/anagrams.cpp",
    "content": "#include <bits/stdc++.h>\nusing namespace std;\n\nbool isAnagram(string a, string b)\n{\n    sort(a.begin(),a.end());\n    sort(b.begin(),b.end());\n    if(a.compare(b)==0)\n        return true;\n    return false;\n}\n\nvector<int> findAnagrams(string arr[], int n)\n{\n    vector<int> v;\n    for(int i=0;i<n-1;i++)\n    {\n        for(int j=i+1;j<n;j++)\n        {\n            if(isAnagram(arr[i], arr[j]))\n            {\n                v.push_back(i+1);\n                v.push_back(j+1);\n                cout<<arr[i]<<\"-->\"<<arr[j]<<endl;\n            }\n        }\n    }\n    for(int i=0;i<v.size();i++)\n        cout<<v[i]<<endl;\n    return v;\n}\n\nint main(int argc, char const *argv[])\n{\n    string arr[] = {\"cat\",\"dog\",\"god\",\"tca\"};\n    int n = sizeof(arr)/sizeof(arr[0]);\n    vector<int> ress = findAnagrams(arr, n);\n    for(int i=0;i<ress.size()-1;i+=2)\n    {\n        cout<<\"[\"<<ress[i]<<\" \"<<ress[i+1]<<\"] \";\n    }\n    cout<<endl;\n    return 0;\n}\n"
  },
  {
    "path": "algorithms/tower_of_hanoi/cpp/tower_of_hanoi.cpp",
    "content": "#include <iostream>\nusing namespace std;\nint moves(0);\nvoid Hanoi(int m, char a, char b, char c);\nint main(){\n\n  int discs;\n  cout << \"Enter the number of discs: \" << endl;\n  cin >> discs;\n  Hanoi(discs, 'A', 'B', 'C');\n  cout << \"It took \" << moves << \" moves. \" << endl;\n  return 0;\n}\n\nvoid Hanoi(int m, char a, char b, char c)\n{\n    moves++;\n    if(m == 1){\n        cout << \"Move disc \" << m << \" from \" << a << \" to \" << c << endl;\n    }\n    else{\n        Hanoi(m-1, a,c,b);\n        cout << \"Move disc \" << m << \" from \" << a << \" to \" << c << endl;\n        Hanoi(m-1,b,a,c);\n    }\n}\n"
  },
  {
    "path": "algorithms/tower_of_hanoi/java/towers_of_hanoi.java",
    "content": "public class TowersOfHanoi {\n\n   public void solve(int n, String start, String auxiliary, String end) {\n       if (n == 1) {\n           System.out.println(start + \" -> \" + end);\n       } else {\n           solve(n - 1, start, end, auxiliary);\n           System.out.println(start + \" -> \" + end);\n           solve(n - 1, auxiliary, start, end);\n       }\n   }\n\n   public static void main(String[] args) {\n       TowersOfHanoi towersOfHanoi = new TowersOfHanoi();\n       System.out.print(\"Enter number of discs: \");\n       Scanner scanner = new Scanner(System.in);\n       int discs = scanner.nextInt();\n       towersOfHanoi.solve(discs, \"A\", \"B\", \"C\");\n   }\n}\n"
  },
  {
    "path": "algorithms/tower_of_hanoi/javascript/tower_of_hanoi.js",
    "content": "\n// Prints the movement\nfunction moveDisk(from_pole, to_pole) {\n    console.log(\"Moving disk from \" + \n        from_pole + \" to \" + to_pole);\n}\n\n// Tower of Hanoi implementation\nfunction towerOfHanoi(height, from_pole=1, to_pole=2, aux=3) {\n    if (height > 0) {\n        towerOfHanoi(height - 1, from_pole, to_pole, aux);\n        moveDisk(from_pole, to_pole);\n        towerOfHanoi(height - 1, aux, from_pole, to_pole);\n    }\n}\n\ntowerOfHanoi(3);\n"
  },
  {
    "path": "algorithms/tower_of_hanoi/php/towers_of_hanoi.php",
    "content": "<?php \n\nfunction move($n, $src, $dest, $temp ){\n\tif($n >= 1){\n\t\tmove($n-1, $src,$temp, $dest);\n\t\tprintf(\"Moving %d -> %d \",$src, $dest);\n\t\techo \"<br/>\";\n\t\tmove($n-1, $temp , $dest , $src);\n\t}\n}\n\nmove(3,1,3,2);\n\n?>"
  },
  {
    "path": "algorithms/tower_of_hanoi/python/tower_of_hanoi.py",
    "content": "\ndef move_disk(from_pole, to_pole):\n    '''\n    Prints the movement\n    '''\n    print('Moving disk from', from_pole, ' to ', to_pole)\n\ndef tower_of_hanoi(height, from_pole=1, to_pole=2, aux=3):\n    '''\n    Tower of Hanoi implementation\n    '''\n    if height > 0:\n        tower_of_hanoi(height - 1, from_pole, to_pole, aux)\n        move_disk(from_pole, to_pole)\n        tower_of_hanoi(height - 1, aux, from_pole, to_pole)\n\nif __name__ == '__main__':\n    tower_of_hanoi(3)\n"
  },
  {
    "path": "data_structures/arraylist/java/arraylist.java",
    "content": "import java.util.*;\npublic class arraylist {\n\n   public static void main(String args[]) {\n      // create an array list\n      ArrayList al = new ArrayList();\n      System.out.println(\"Initial size of al: \" + al.size());\n\n      // add elements to the array list\n      al.add(\"C\");\n      al.add(\"A\");\n      al.add(\"E\");\n      al.add(\"B\");\n      al.add(\"D\");\n      al.add(\"F\");\n      al.add(1, \"A2\");\n      System.out.println(\"Size of al after additions: \" + al.size());\n\n      // display the array list\n      System.out.println(\"Contents of al: \" + al);\n\n      // Remove elements from the array list\n      al.remove(\"F\");\n      al.remove(2);\n      System.out.println(\"Size of al after deletions: \" + al.size());\n      System.out.println(\"Contents of al: \" + al);\n   }\n}"
  },
  {
    "path": "data_structures/avl_tree/java/AVL.java",
    "content": "public class AVL {\n    class Node {\n        private int data, height;\n        private Node left, right;\n        public Node(int data, int height) {\n            this.data = data;\n            this.height = height;\n        }\n    }\n\n    Node root = null;\n\n    private int getHeight(Node root) {\n        if(root == null) return 0;\n        return root.height;\n    }\n\n    private int getBalance(Node root) {\n        if(root == null) return 0;\n        return (getHeight(root.left) - getHeight(root.right));\n    }\n\n    private Node rightRotate(Node root) {\n        Node temp1 = root.left;\n        Node temp2 = temp1.right;\n        temp1.right = root;\n        root.left = temp2;\n        \n        root.height = Math.max(getHeight(root.left), getHeight(root.right)) + 1;\n        temp1.height = Math.max(getHeight(temp1.left), getHeight(temp1.right)) + 1;\n        \n        return temp1;\n    }\n\n    private Node leftRotate(Node root) {\n        Node temp1 = root.right;\n        Node temp2 = temp1.left;\n        temp1.left = root;\n        root.right = temp2;\n \n        root.height = Math.max(getHeight(root.left), getHeight(root.right)) + 1;\n        temp1.height = Math.max(getHeight(temp1.left), getHeight(temp1.right)) + 1;\n        \n        return temp1;\n    }\n\n    public void insert(int data) {\n        root = insert(root, data, 0);\n    }\n\n    private Node insert(Node root, int data, int height) {\n        if(root == null) return new Node(data, height);\n        else if(root.data > data) root.left = insert(root.left, data, height+1);\n        else if(root.data < data) root.right = insert(root.right, data, height+1);\n        else return root;\n\n        int balance = getBalance(root);\n\n        if(balance > 1 && data < root.left.data) {\n            return rightRotate(root);\n        }\n        else if(balance > 1 && data > root.left.data) {\n            root.left = leftRotate(root.left);\n            return rightRotate(root);\n        }\n        else if(balance < -1 && data > root.right.data) {\n            return leftRotate(root);\n        }\n        else if(balance < -1 && data < root.right.data) {\n            root.right = rightRotate(root.right);\n            return leftRotate(root);\n        }\n\n        return root;\n    }\n\n    public void preorder() {\n        preorder(root);\n    }\n\n    private void preorder(Node root) {\n        if(root == null) return;\n        System.out.println(root.data);\n        preorder(root.left);\n        preorder(root.right);\n    }\n\n    public static void main(String[] args) {\n        AVL a1 = new AVL();\n        a1.insert(10);\n        a1.insert(20);\n        a1.insert(30);\n        a1.insert(40);\n        a1.insert(50);\n        a1.insert(25);\n        a1.preorder();\n    }\n}\n"
  },
  {
    "path": "data_structures/avl_tree/javascript/avl.js",
    "content": "var Node = function (value)\n{\n    this.left = null;\n    this.right = null;\n    this.value = value;\n\tthis.balance = 0;\n};\n\nvar AVL = function ()\n{\n    this._root = null;\n    this._size = 0;\n    this.get = function (value){\n        if (this._root === null) return null;\n        return this._get(value, this._root).value;\n    };\n    this._get = function (value, root){\n\t\tif(root === null) \t\t return null;\n        if (value == root.value) return root;\n        if (value < root.value)  return this._get(value, root.left);\n        else\t\t\t\t\t return this._get(value, root.right);\n    };\n    this.insert = function (value){\n        this._root = this._insert(value, this._root);\n        this._size++;\n        this._root = this.rebalance(this._root, value);\n    };\n    this._insert = function (value, root){\n        if (root === null)\t\t\t\treturn new Node(value);\n        if (value < root.value)     \troot.left = this._insert(value, root.left);\n        else if (value > root.value)\troot.right = this._insert(value, root.right);\n        else\t\t\t\t\t\t\tthis._size--;\n        return root;\n    }\n    this.Height = function (node){\n        if (node !== null) return 1 + Math.max( this.Height(node.left), this.Height(node.right) );\n        return 0;\n    };\n    this.rotateLeft = function (n){\n        temp = n;\n        n = n.right;\n        temp.right = n.left;\n        n.left = temp;\n        return n;\n    };\n    this.rotateRight = function (n){\n        temp = n;\n        n = n.left;\n        temp.left = n.right;\n        n.right = temp;\n        return n;\n    };\n    this.rebalance = function(node, value){\n        if(node === null) \t\t\t\treturn null;\n        if(node.value > value) \t\t\tnode.left = this.rebalance(node.left, value);\n        else if(node.value < value) \tnode.right = this.rebalance(node.right, value);\n        this.setBalance(node);\n        if (node.balance == -2){\n            if (this.Height(node.left.left) >= this.Height(node.left.right))\n                node = this.rotateRight(node);\n            else\n                node = this.rotateLeftThenRight(node);\n        }\n        else if (node.balance == 2){\n            if (this.Height(node.right.right) >= this.Height(node.right.left))\n                node = this.rotateLeft(node);\n            else\n                node = this.rotateRightThenLeft(node);\n        }\n        return node;\n    }\n    this.rotateLeftThenRight = function(node){\n        node.left = this.rotateLeft(node.left);\n        node = this.rotateRight(node);\n        return node;\n    }\n    this.rotateRightThenLeft = function(node){\n        node.right = this.rotateRight(node.right);\n        node = this.rotateLeft(node);\n        return node;\n    }\n    this.setBalance = function(node){\n        if(node === null) return null;\n        node.balance = this.Height(node.right) - this.Height(node.left);\n        return node;\n    }\n    this.delete = function(value){\n        this._root = this._delete(this._root, value);\n        this._root = this.rebalance(this._root, value);\n        if(this._root === null)return;\n    }\n    this._delete = function(node, value){\n\t\tif (node === null) return null;\n    \tvar cmp;\n        if(node.value < value) cmp = -1;\n        else if(node.value > value) cmp = 1;\n        else cmp = 0;\n\n\t\tif (cmp > 0)\t\tnode.left = this._delete (node.left, value);\n\t\telse if (cmp < 0)\tnode.right = this._delete (node.right, value);\n\t\telse{\n\t\t\tif (node.right === null) \t\t\t\t\t\treturn node.left;\n\t\t\tif (node.left === null)  \t\t\t\t\t\treturn node.right;\n\t\t\tif(node.right === null && node.left === null)   return null;\n\t\t\tvar temp = this._Min(node.right);\n\t\t\tnode.value = temp.value;\n\t\t\tnode.right = this._DeleteMin(node.right);\n\t\t}\n\t\treturn node;\n\t}\n    this.Min = function(){\n        return this._Min(this._root);\n    }\n    this._Min = function(r){\n        var temp = r;\n        while(temp.left !== null)\n            temp = temp.left;\n        return temp;\n    }\n    this.DeleteMin = function(){\n        this._DeleteMin(this._root);\n    }\n    this._DeleteMin = function(n){\n        if(n.left !== null)\n            n.left = this._DeleteMin(n.left);\n        else{\n            if(n.right !== null) return n.right;\n            else\t\t\t\t return null;\n        }\n        return n;\n    }\n};\n"
  },
  {
    "path": "data_structures/bag/java/Bag.java",
    "content": "package bag.java;\n\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\n\n/**\n * Collection which does not allow removing elements (only collect and iterate)\n *\n * @param <Element> - the generic type of an element in this bag\n */\npublic class Bag<Element> implements Iterable<Element> {\n\n\tprivate Node<Element> firstElement; // first element of the bag\n\tprivate int size; // size of bag\n\n\tprivate static class Node<Element> {\n\t\tprivate Element content;\n\t\tprivate Node<Element> nextElement;\n\t}\n\n\t/**\n\t * Create an empty bag\n\t */\n\tpublic Bag() {\n\t\tfirstElement = null;\n\t\tsize = 0;\n\t}\n\n\t/**\n\t * @return true if this bag is empty, false otherwise\n\t */\n\tpublic boolean isEmpty() {\n\t\treturn firstElement == null;\n\t}\n\n\t/**\n\t * @return the number of elements\n\t */\n\tpublic int size() {\n\t\treturn size;\n\t}\n\n\t/**\n\t * @param element - the element to add\n\t */\n\tpublic void add(Element element) {\n\t\tNode<Element> oldfirst = firstElement;\n\t\tfirstElement = new Node<>();\n\t\tfirstElement.content = element;\n\t\tfirstElement.nextElement = oldfirst;\n\t\tsize++;\n\t}\n\n\t/**\n\t * Checks if the bag contains a specific element\n\t *\n\t * @param element which you want to look for\n\t * @return true if bag contains element, otherwise false\n\t */\n\tpublic boolean contains(Element element) {\n\t\tIterator<Element> iterator = this.iterator();\n\t\twhile(iterator.hasNext()) {\n\t\t\tif (iterator.next().equals(element)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * @return an iterator that iterates over the elements in this bag in arbitrary order\n\t */\n\tpublic Iterator<Element> iterator() {\n\t\treturn new ListIterator<>(firstElement);\n\t}\n\n\t@SuppressWarnings(\"hiding\")\n\tprivate class ListIterator<Element> implements Iterator<Element> {\n\t\tprivate Node<Element> currentElement;\n\n\t\tpublic ListIterator(Node<Element> firstElement) {\n\t\t\tcurrentElement = firstElement;\n\t\t}\n\n\t\tpublic boolean hasNext() {\n\t\t\treturn currentElement != null;\n\t\t}\n\n\t\t/**\n\t\t * remove is not allowed in a bag\n\t\t */\n\t\t@Override\n\t\tpublic void remove() {\n\t\t\tthrow new UnsupportedOperationException();\n\t\t}\n\n\t\tpublic Element next() {\n\t\t\tif (!hasNext())\n\t\t\t\tthrow new NoSuchElementException();\n\t\t\tElement element = currentElement.content;\n\t\t\tcurrentElement = currentElement.nextElement;\n\t\t\treturn element;\n\t\t}\n\t}\n\n\t/**\n\t * main-method for testing\n\t */\n\tpublic static void main(String[] args) {\n\t\tBag<String> bag = new Bag<>();\n\n\t\tbag.add(\"1\");\n\t\tbag.add(\"1\");\n\t\tbag.add(\"2\");\n\n\t\tSystem.out.println(\"size of bag = \" + bag.size());\n\t\tfor (String s : bag) {\n\t\t\tSystem.out.println(s);\n\t\t}\n\n\t\tSystem.out.println(bag.contains(null));\n\t\tSystem.out.println(bag.contains(\"1\"));\n\t\tSystem.out.println(bag.contains(\"3\"));\n\t}\n}\n"
  },
  {
    "path": "data_structures/binary_search_tree/binary_search_tree.md",
    "content": "\n## ELI5\nA tree is a container that stores items in sorted order in memory.It's like the inversed version of an actual tree.\n\n### Pros\n* BSTs allow fast lookup, addition and removal of items.\n### Cons\n* Tree gets skewed to one side when we save sorted items.The advantage of fast operations is lost.\n\n## Technical Explaination\nBinary Search Tree is a node-based binary tree data structure.\n*NODE: All items are stored in nodes.\n*ROOT: The top node in a tree.\n*CHILD: A node directly connected to another node when moving away from the Root.Each node can have 0 to 2 child nodes.Left child's value is smaller than its parent and right child's value is greater than its parent.\n*LEAVES: Nodes with no child nodes.\n*HEIGHT: Number of edges on the longest path between the root and a leaf.\n*DEPTH: The depth of a node is the number of edges from the tree's root node to the node.\n\nStoring 2,4,1,10,3 in a BST:\n\t2\n   / \\\n  1   4\n\t / \\\n\t3  10\n\t  \n\t\n### Pros\n* Time Complexity of insertion,deletion and search is O(h). h=height of tree\ni.e. O(log n) which is less than linked list and array.   n=number of nodes\n### Cons\n* For a skewed binary tree time complexity of insertion,deletion and search is O(n).\nAs for a skewed binary tree height h is O(n).\ne.g 2,3,4,5\n 2\n  \\\n   3\n    \\\n\t 4\n\t  \\\n\t   5\n\t\n"
  },
  {
    "path": "data_structures/binary_search_tree/c/BSTtraversal.c",
    "content": "// C program for different tree traversals\n#include <stdio.h>\n#include <stdlib.h>\n \n/* A binary tree node has data, pointer to left child\n   and a pointer to right child */\nstruct node\n{\n     int data;\n     struct node* left;\n     struct node* right;\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 = (struct node*)\n                                  malloc(sizeof(struct node));\n     node->data = data;\n     node->left = NULL;\n     node->right = NULL;\n \n     return(node);\n}\n \n/* Given a binary tree, print its nodes according to the\n  \"bottom-up\" postorder traversal. */\nvoid printPostorder(struct node* node)\n{\n     if (node == NULL)\n        return;\n \n     // first recur on left subtree\n     printPostorder(node->left);\n \n     // then recur on right subtree\n     printPostorder(node->right);\n \n     // now deal with the node\n     printf(\"%d \", node->data);\n}\n \n/* Given a binary tree, print its nodes in inorder*/\nvoid printInorder(struct node* node)\n{\n     if (node == NULL)\n          return;\n \n     /* first recur on left child */\n     printInorder(node->left);\n \n     /* then print the data of node */\n     printf(\"%d \", node->data);  \n \n     /* now recur on right child */\n     printInorder(node->right);\n}\n \n/* Given a binary tree, print its nodes in preorder*/\nvoid printPreorder(struct node* node)\n{\n     if (node == NULL)\n          return;\n \n     /* first print data of node */\n     printf(\"%d \", node->data);  \n \n     /* then recur on left sutree */\n     printPreorder(node->left);  \n \n     /* now recur on right subtree */\n     printPreorder(node->right);\n}    \n \n/* Driver program to test above functions*/\nint main()\n{\n     struct node *root  = newNode(1);\n     root->left             = newNode(2);\n     root->right           = newNode(3);\n     root->left->left     = newNode(4);\n     root->left->right   = newNode(5); \n \n     printf(\"\\nPreorder traversal of binary tree is \\n\");\n     printPreorder(root);\n \n     printf(\"\\nInorder traversal of binary tree is \\n\");\n     printInorder(root);  \n \n     printf(\"\\nPostorder traversal of binary tree is \\n\");\n     printPostorder(root);\n \n     getchar();\n     return 0;\n}"
  },
  {
    "path": "data_structures/binary_search_tree/cpp/BST.h",
    "content": "/**\n  A simple BST in C++\n  Author: PryDt\n*/\n\n#ifndef BST_H\n#define BST_H\n\n#include <iostream>\n\ntemplate <class T>\nclass BinarySearchTree {\n public:\n  // constructor\n  BinarySearchTree() { root = nullptr; }\n  ~BinarySearchTree()\n  {\n    destroy(root);\n  }\n\n  // insert\n  void insert(T data) { insert(data, root); }\n\n  // find min\n  int findMin() { return findMin(root); }\n\n  // remove node\n  void remove(T data) { remove(data, root); }\n\n\n  // check if a number is in tree\n  bool find(T data)\n  {\n    return find(data, root);\n  }\n\n  // print tree in order out to stdout\n  void printTree()\n  {\n    std::cout << \"[ \";\n    print(root);\n    std::cout << \" ]\\n\";\n  }\n\n private:\n  // basic building block of tree\n  struct Node {\n    T key;  // value of node\n\n    Node *left;   // smaller\n    Node *right;  // greater\n  };\n\n  void destroy(Node *n)\n  {\n    if(n == nullptr)\n      return;\n\n    destroy(n->left);\n    destroy(n->right);\n\n    delete n;\n  }\n\n  // helper function print\n  void print(Node *ptr)\n  {\n    if (root != nullptr) {\n      if (ptr->left != nullptr) {\n        print(ptr->left);\n      }\n      std::cout << ptr->key << \" \";\n\n      if (ptr->right != nullptr) {\n        print(ptr->right);\n      }\n    }\n    else {\n      std::cout << \"Binary Search Tree is empty\\n\";\n    }\n  }\n\n  // internals for find function\n  bool find(T data, Node *n)\n  {\n    if(data == n->key)\n      return true;\n\n    if(data > n->key && n->right != nullptr)\n      return find(data, n->right);\n\n    if(data < n->key && n->left != nullptr)\n      return find(data, n->left);\n\n    return false;\n  }\n\n  // find min\n  int findMin(Node *ptr)\n  {\n    if (root == nullptr) {\n      std::cout << \"findMin(): BST is empty\\n\";\n      return -324243;\n    }\n    else {\n      if (ptr->left != nullptr) {\n        return findMin(ptr->left);\n      }\n      else {\n        return ptr->key;\n      }\n    }\n  }\n\n  // make a new node\n  Node *createLeaf(T data)\n  {\n    Node *n = new Node();\n    n->key = data;\n\n    n->left = nullptr;\n    n->right = nullptr;\n\n    return n;\n  }\n\n  void insert(T data, Node *ptr)\n  {\n    if (root == nullptr) {\n      root = createLeaf(data);\n      return;\n    }\n    else if (data < ptr->key) {\n      if (ptr->left != nullptr)\n        insert(data, ptr->left);\n      else {\n        ptr->left = createLeaf(data);\n        return;\n      }\n    }\n    else if (data > ptr->key) {\n      if (ptr->right != nullptr)\n        insert(data, ptr->right);\n      else {\n        ptr->right = createLeaf(data);\n        return;\n      }\n    }\n    else {\n      std::cout << \"Attempted to add duplicate key in BST\\n\";\n    }\n  }\n\n  // remove match\n  void removeMatch(Node *parent, Node *match, bool left)\n  {\n    if (root != nullptr) {\n      Node *delptr;\n      int small;\n\n      // case A: 0 children\n      if (match->left == nullptr && match->right == nullptr) {\n        delptr = match;\n\n        left ? parent->left = nullptr : parent->right = nullptr;\n\n        delete delptr;\n      }\n\n      // case B: 1 child\n      else if ((match->left == nullptr) != (match->right == nullptr)) {\n        (left) ? ((match->right != nullptr) ? parent->left = parent->right : parent->left = parent->left)\n          : (match->right != nullptr ? parent->right = match->right : parent->right = match->left);\n\n        (match->right != nullptr) ? match->right = nullptr : match->left = nullptr;\n\n        delptr = match;\n\n        delete delptr;\n      }\n\n      // case C: 2 children\n      else\n      {\n        small = findMin(match->right);\n        remove(small, match);\n        match->key = small;\n      }\n\n    }\n    else {\n      std::cout << \"removeMatch(): cannot remove match, BST empty\\n\";\n    }\n  }\n\n  // removes root of tree (used in special cases)\n  void removeRootMatch()\n  {\n    if (root == nullptr) {\n      std::cout << \"removeRootMatch(): BST is empty\\n\";\n      return;\n    }\n\n    Node *delptr = root;\n    int small;\n\n    // case A: 0 children\n    if (root->left == nullptr && root->right == nullptr) {\n      root = nullptr;\n      delete delptr;\n    }\n\n    // case B: 1 child\n    else if ((root->left == nullptr) != (root->right == nullptr)) {\n      root = (root->left != nullptr) ? root->left : root->right;\n\n      (root->right != nullptr) ? delptr->right = nullptr : delptr->left = nullptr;\n      delete delptr;\n    }\n\n    // case C: 2 children\n\n    else {\n      small = findMin(root->right);\n      remove(small, root);\n\n      root->key = small;\n    }\n  }\n\n  void remove(T data, Node *parent)\n  {\n    if (root == nullptr) {\n      std::cout << \"remove(): FAILED, BST is empty\\n\";\n    }\n    else {\n      if (root->key == data) {\n        removeRootMatch();\n      }\n      else {\n        if (data < parent->key && parent->left != nullptr) {\n          parent->left->key == data ? removeMatch(parent, parent->left, true)\n                                    : remove(data, parent->left);\n        }\n        else if (data > parent->key && parent->right != nullptr) {\n          parent->right->key == data ? removeMatch(parent, parent->right, false)\n                                     : remove(data, parent->right);\n        }\n        else {\n          std::cout << \"remove(): The key(\" << data\n                    << \") was not found in BST\\n\";\n        }\n      }\n    }\n  }\n\n  // root of the tree\n  Node *root;\n};\n\n// typedef for convenience\ntypedef BinarySearchTree<int> intBST;\n\n#endif // BST_H\n"
  },
  {
    "path": "data_structures/binary_search_tree/java/binary_search_tree.java",
    "content": "\n/*\n** Binary tree & Binary tree search implementation in java\n*/\n\n\n/*\n**Input patterns \n**create 25 15 9 18 2 90 25 42 60 35 1 19 10 100 3 - create the binary tree\n**print - print the binary tree in sorted order\n**search 15 \n**delete 15\n**search 15\n**search 13\n**add 13\n**search 13\n**pre-order\n**in-order\n**post-order\n**\n**\n*/\n\n\nimport java.util.Scanner;\nimport java.util.LinkedList;\n\nclass Node {                                                                    //create a Node class\n\n    private int value;\n    private Node left;\n    private Node right;\n\n    public Node getLeft() {\n        return this.left;\n    }\n\n    public void setLeft(Node e) {\n        this.left = e;\n    }\n\n    public Node getRight() {\n        return this.right;\n    }\n\n    public void setRight(Node e) {\n        this.right = e;\n    }\n\n    public void setValue(int value) {\n        this.value = value;\n    }\n\n    public int getValue() {\n        return this.value;\n    }\n}\n\n/**\n *\n * @author Thuvarakan\n */\n\n\npublic class BinarySearchTree {\n\n    public static void main(String[] args){\n\n    \tScanner scanner = new Scanner(System.in);\n        BinSearchTree th = new BinSearchTree();\n        Node root = null;\n        String line;\n        while ((line = scanner.nextLine() )!= null) {\n            String[] tokens = line.split(\" \");\n            //check the instructions\n            switch (tokens[0]) {\n                //if instruction is create\n                case \"create\": {\n\n                    int[] a = new int[tokens.length - 1];\n                    for (int i = 0; i < a.length; i++) {\n                        a[i] = Integer.parseInt(tokens[i + 1]);\n                    }\n                    root = th.createTree(a);\n                    if (root != null) {\n                        System.out.println(\"S\");\n                    } else {\n                        System.out.println(\"F\");\n                    }\n                    break;\n                }\n                //if instruction is print\n                case \"print\":\n                    th.print_tree(root);\n                    break;\n                //if instruction is search\n                case \"search\":\n                    if (th.searchValue(root, Integer.parseInt(tokens[1])) != null) {\n                        System.out.println(\"T\");\n                    } else {\n                        System.out.println(\"F\");\n                    }\n                    break;\n                //if instruction is delete\n                case \"delete\":\n                    if (th.deleteValue(root, Integer.parseInt(tokens[1]))) {\n                        System.out.println(\"S\");\n                    } else {\n                        System.out.println(\"F\");\n                    }\n                    break;\n                //if instruction is add\n                case \"add\":\n                    if (th.addValue(root, Integer.parseInt(tokens[1]))) {\n                        System.out.println(\"S\");\n                    } else {\n                        System.out.println(\"F\");\n                    }\n                    break;\n                //if instruction is pre-order\n                case \"pre-order\":\n                    th.traverse_preorder(root);\n                    System.out.println();\n                    break;\n                //if instruction is in-order\n                case \"in-order\":\n                    th.traverse_inorder(root);\n                    System.out.println();\n                    break;\n                //if instruction is post-order\n                case \"post-order\":\n                    th.traverse_postorder(root);\n                    System.out.println();\n                    break;\n            }\n        }\n    }\n}\n\nclass Bintree {\n\n    public boolean addLeftChild(Node parent, int newvalue) {                   //add left child for binary tree\n        if (parent.getLeft() == null) {\n            parent.setLeft(new Node());\n            parent.getLeft().setValue(newvalue);\n            return true;\n        }\n        return false;\n    }\n\n    public boolean addRightChild(Node parent, int newvalue) {                  //add right child for binary tree\n        if (parent.getRight() == null) {\n            parent.setRight(new Node());\n            parent.getRight().setValue(newvalue);\n            return true;\n        }\n        return false;\n    }\n\n    public Node createTree(int[] elements) {                               //create a new tree\n        LinkedList<Node> lisa = new LinkedList<>();\n        Node root = new Node();\n        Node root1 = root;\n        root.setValue(elements[0]);\n        lisa.addLast(root);\n        int i = 1;\n        while (!lisa.isEmpty()) {\n            root = lisa.removeFirst();\n            if (i < elements.length) {\n                this.addLeftChild(root, elements[i]);\n                lisa.addLast(root.getLeft());\n                i++;\n                if (i < elements.length) {\n                    this.addRightChild(root, elements[i]);\n                    lisa.addLast(root.getRight());\n                    i++;\n                }\n            } else {\n                return root1;\n            }\n        }\n        return root1;\n    }\n\n    public boolean expandTree(Node root, int[] elements) {             //expand tree\n        LinkedList<Node> nodeList = new LinkedList<>();                 //create a linkedlist\n        nodeList.addLast(root);\n        int i = 0;\n        while (!nodeList.isEmpty()) {                                   //run until finish all array elements \n            root = nodeList.removeFirst();\n            if (i < elements.length) {\n                if (root.getLeft() == null) {\n                    this.addLeftChild(root, elements[i]);\n                    nodeList.addLast(root.getLeft());\n                    i++;\n                } else {\n                    nodeList.addLast(root.getLeft());\n                }\n                if (i < elements.length) {\n                    if (root.getRight() == null) {\n                        this.addRightChild(root, elements[i]);\n                        nodeList.addLast(root.getRight());\n                        i++;\n                    } else {\n                        nodeList.addLast(root.getRight());\n                    }\n                }\n            } else {\n                return true;\n            }\n        }\n        return false;\n    }\n\n    public void traverse_inorder(Node root) {                      //inorder traversal\n        if (root != null) {\n            traverse_inorder(root.getLeft());\n            System.out.print(root.getValue() + \" \");\n            traverse_inorder(root.getRight());\n        }\n    }\n\n    public void traverse_preorder(Node root) {                     //inorder traversal\n        if (root != null) {\n            System.out.print(root.getValue() + \" \");\n            traverse_preorder(root.getLeft());\n            traverse_preorder(root.getRight());\n        }\n    }\n\n    public void traverse_postorder(Node root) {                    //postorder traversal\n        if (root != null) {\n            traverse_postorder(root.getLeft());\n            traverse_postorder(root.getRight());\n            System.out.print(root.getValue() + \" \");\n        }\n    }\n}\n\nclass BinSearchTree extends Bintree {                                  //create binary search tree\n\n    public Node insert(Node root, int key) {                    //define a insert method\n        //recursivly check and add the value in the correct place\n        if (root == null) {\n            root = new Node();\n            root.setValue(key);\n        } else if (key < root.getValue()) {\n            root.setLeft(insert(root.getLeft(), key));\n        } else {\n            root.setRight(insert(root.getRight(), key));\n        }\n        return root;\n    }\n\n    @Override\n    public Node createTree(int[] p) {                   //create Binary search tree\n        Node thua = null;\n        Node roots = null;\n        for (int i = 0; i < p.length; i++) {\n            thua = this.insert(thua, p[i]);\n            if (i == 0) {\n                roots = thua;\n            }\n        }\n        return roots;\n    }\n\n    public boolean addValue(Node root, int newvalue) { //add value to the binary search tree\n        if (this.searchValue(root, newvalue) == null) {\n            if (root == null) {\n                root = new Node();\n                root.setValue(newvalue);\n            } else if (newvalue < root.getValue()) {\n                root.setLeft(insert(root.getLeft(), newvalue));\n            } else {\n                root.setRight(insert(root.getRight(), newvalue));\n            }\n            return true;\n        }\n        return false;\n    }\n\n    public boolean deleteValue(Node root, int value) {                 //delete a given value from tree\n        Node parentNode = root;\n        Node deleteNode;\n        Node replaceNode;\n        if (root == null) {\n            return false;\n        }\n        if (this.searchValue(root, value) == null) {                        //Checks whether a given value exists\n            return false;\n        }\n        deleteNode = root;\n        //get the node being deleted & its parent Node\n        while (deleteNode != null && deleteNode.getValue() != value) {\n            parentNode = deleteNode;\n            if (value < deleteNode.getValue()) {\n                deleteNode = deleteNode.getLeft();\n            } else if (value > deleteNode.getValue()) {\n                deleteNode = deleteNode.getRight();\n            }\n        }\n\n        if (deleteNode.getLeft() == null && deleteNode.getRight() == null) {          //when delete node don't has any child node\n            if (parentNode.getLeft() == deleteNode) {\n                parentNode.setLeft(null);\n                return true;\n            } else {\n                parentNode.setRight(null);\n                return true;\n            }\n        }\n        if (deleteNode.getLeft() != null && deleteNode.getRight() == null) {          // when it has only a left child\n            if (parentNode.getLeft() == deleteNode) {\n                parentNode.setLeft(deleteNode.getLeft());\n                return true;\n            } else {\n                parentNode.setRight(deleteNode.getLeft());\n                return true;\n            }\n        }\n        if (deleteNode.getLeft() == null && deleteNode.getRight() != null) {           // when it has only a right child\n            if (parentNode.getLeft() == deleteNode) {\n                parentNode.setLeft(deleteNode.getRight());\n                return true;\n            } else {\n                parentNode.setRight(deleteNode.getRight());\n                return true;\n            }\n        }\n        if (deleteNode.getLeft() != null && deleteNode.getRight() != null) {          //when it has two child nodes\n            parentNode = deleteNode;\n            replaceNode = deleteNode.getRight();\n            if (replaceNode.getLeft() == null) {\n                deleteNode.setValue(replaceNode.getValue());\n                deleteNode.setRight(replaceNode.getRight());\n                return true;\n            }\n            //find the replace node and its parent\n            while (replaceNode.getLeft() != null) {\n                parentNode = replaceNode;\n                replaceNode = replaceNode.getLeft();\n            }\n            deleteNode.setValue(replaceNode.getValue());\n            parentNode.setLeft(replaceNode.getRight());\n            return true;\n        }\n        return false;\n    }\n\n    public Node searchValue(Node root, int key) {          //find the node of the given value \n        Node refNode = root;\n        while (refNode != null) {                 //get the node of the key value\n            if (key == refNode.getValue()) {\n                return refNode;\n            } else if (key < refNode.getValue()) {\n                refNode = refNode.getLeft();\n            } else {\n                refNode = refNode.getRight();\n            }\n        }\n        return null;\n    }\n\n    public void print_tree(Node root) {\n        this.traverse_inorder(root); //print binary search tree in sorted order\n        System.out.println();\n    }\n}\n"
  },
  {
    "path": "data_structures/binary_search_tree/java/bst_operations/CheckBST.java",
    "content": "package bst_operations;\n\npublic class CheckBST {\n    public static void main(String[] args) {\n        new CheckBST().demo();\n    }\n\n    private void demo() {\n        Node n = new Node(4);\n        // left\n        n.left = new Node(2);\n        n.left.left = new Node(1);\n        n.left.right = new Node(3);\n\n        //right\n        n.right = new Node(5);\n        System.out.println(isBST(n, Integer.MIN_VALUE, Integer.MAX_VALUE));\n    }\n\n    private boolean isBST(Node n, int min, int max) {\n        if (n == null) {\n            return true;\n        }\n        if (n.data < min || n.data > max) {\n            return false;\n        }\n        if(n.data == max || n.data == min) {\n            System.out.println(\"duplication of data\");\n            return false;\n        }\n        return isBST(n.left, min, n.data) && isBST(n.right, n.data, max);\n    }\n}\n\n"
  },
  {
    "path": "data_structures/binary_search_tree/java/bst_operations/CorrectBST.java",
    "content": "package bst_operations;\n\nimport java.util.ArrayList;\n\n/**\n * Two nodes of a BST are swapped, correct the BST\n */\npublic class CorrectBST {\n    public static void main(String[] args) {\n        new CorrectBST().demo();\n    }\n\n    private void demo() {\n        Node n = new Node(10);\n        n.left = new Node(5);\n        n.left.left = new Node(2);\n        n.left.right = new Node(20);\n        n.right = new Node(8);\n        /*\n         10\n        /  \\\n       5    8\n      / \\\n     2   20\n*/\n        ArrayList<Node> list = new ArrayList<Node>();\n        display(n);\n        balanceBST(n, list, Integer.MIN_VALUE, Integer.MAX_VALUE);\n        System.out.println();\n        list.get(0).data = list.get(0).data + list.get(1).data;\n        list.get(1).data = list.get(0).data - list.get(1).data;\n        list.get(0).data = list.get(0).data - list.get(1).data;\n        System.out.println(\"After\");\n        display(n);\n    }\n\n    private void display(Node n) {\n        if (n != null) {\n            display(n.left);\n            System.out.print(n.data + \"\\t\");\n            display(n.right);\n        }\n    }\n\n    private void balanceBST(Node n, ArrayList<Node> list, int min, int max) {\n        if (n == null) {\n            return;\n        }\n        if (n.data > max || n.data < min) {\n            list.add(n);\n        }\n        balanceBST(n.left, list, min, n.data);\n        balanceBST(n.right, list, n.data, max);\n\n    }\n}\n"
  },
  {
    "path": "data_structures/binary_search_tree/java/bst_operations/FindAncestor.java",
    "content": "package bst_operations;\n\n/**\n * Created by kalsi on 30/08/17.\n * find lowest ancestor of two items\n * I assumed both the elements are present in the tree\n */\npublic class FindAncestor {\n    public static void main(String[] args) {\n        new FindAncestor().demo();\n    }\n\n    private void demo() {\n\n        Node n = new Node(8);\n        // left\n        n.left = new Node(3);\n        n.left.left = new Node(1);\n        n.left.right = new Node(6);\n        n.left.right.left = new Node(4);\n        n.left.right.right = new Node(7);\n\n        //right\n        n.right = new Node(10);\n        n.right.right = new Node(14);\n        n.right.right.left = new Node(13);\n\n        /*\n                            8\n                        3      10\n                     1    6        14\n                        4   7   13\n        *\n        * */\n        int m1 = 4;\n        int m2 = 7;\n        Node ancestor = lowestAncestor(n, m1, m2);\n        System.out.println(\"Lowest ancestor is : \" + ancestor.data);\n        System.out.println(\"Distance from root to ancestor is: \" + findDistance(n, ancestor));\n    }\n\n    private int findDistance(Node n, Node ancestor) {\n        return findDistanceUtil(n,ancestor, 0);\n    }\n\n    private int findDistanceUtil(Node n, Node ancestor, int level) {\n        if(n == null || ancestor == null) {\n            return 0;\n        }\n        if(n.data == ancestor.data) {\n            return level;\n        }\n        level++;\n        return findDistanceUtil(n.left, ancestor, level) + findDistanceUtil(n.right, ancestor, level);\n\n    }\n\n    private Node lowestAncestor(Node n, int m1, int m2) {\n        if (n == null) {\n            return null;\n        }\n        if (n.data == m2 || n.data == m1) {\n            return n;\n        }\n        Node left = lowestAncestor(n.left, m1, m2);\n        Node right = lowestAncestor(n.right, m1, m2);\n        if (left != null && right != null) {\n            return n;\n        }\n        return left == null ? right : left;\n    }\n\n\n}\n"
  },
  {
    "path": "data_structures/binary_search_tree/java/bst_operations/InorderSuccessor.java",
    "content": "package bst_operations;\n\npublic class InorderSuccessor {\n    public static void main(String[] args) {\n        new InorderSuccessor().demo();\n    }\n\n    private void demo() {\n        Node n = new Node(8);\n        // left\n        n.left = new Node(3);\n        n.left.left = new Node(1);\n        n.left.right = new Node(6);\n        n.left.right.left = new Node(4);\n        n.left.right.right = new Node(7);\n\n        //right\n        n.right = new Node(10);\n        n.right.right = new Node(14);\n        n.right.right.left = new Node(13);\n\n        /*\n                            8\n                        3      10\n                     1    6        14\n                        4   7   13\n        *\n        * */\n        System.out.println(getNextSuccessor(n, new Node(8)));\n    }\n\n    private Integer getNextSuccessor(Node root, Node target) {\n        if (root == null || target == null) {\n            return null;\n        }\n        Boolean found = false;\n        Node candidate = null;\n        Node current = root;\n        while (current != null) {\n            if (current.data == target.data) {\n                found = true;\n                current = current.right;\n            } else if (current.data > target.data) {\n                candidate = current;\n                current = current.left;\n            } else {\n                current = current.right;\n            }\n        }\n        return found && candidate != null ? candidate.data : null;\n    }\n}\n"
  },
  {
    "path": "data_structures/binary_search_tree/java/bst_operations/LargestBST.java",
    "content": "package bst_operations;\n\n\n/**\n * Created by kalsi on 06/09/17.\n */\npublic class LargestBST {\n    class BSTCount {\n        Boolean isBST;\n        int count;\n    }\n\n    class BST {\n        int max;\n        Node n;\n\n        public BST() {\n            max = -1;\n            n = null;\n        }\n    }\n\n    public static void main(String[] args) {\n        new LargestBST().demo();\n    }\n\n    private void demo() {\n        Node n = new Node(50);\n        // left\n        n.left = new Node(30);\n        n.left.left = new Node(5);\n        n.left.right = new Node(20);\n\n        //right\n        n.right = new Node(60);\n        n.right.left = new Node(45);\n        n.right.right = new Node(70);\n        n.right.right.left = new Node(65);\n        n.right.right.right = new Node(80);\n      /*    50\n         /    \\\n        30       60\n      /  \\     /  \\\n     5   20   45    70\n                  /  \\\n                65    80\n                */\n        largestBST(n);\n    }\n\n    private void largestBST(Node n) {\n        BST bst = new BST();\n        BSTCount bstCount = new BSTCount();\n        largestBSTUtil(n, bst, bstCount);\n        System.out.println(\"Largest BST: \" + bst.n.data);\n        System.out.println(\"Count: \" + bst.max);\n    }\n\n    private void largestBSTUtil(Node n, BST bst, BSTCount bstCount) {\n        if (n == null) {\n            return;\n        }\n        isBST(n, bstCount);\n        if (bstCount.isBST && bstCount.count > bst.max) {\n            bst.max = bstCount.count;\n            bst.n = n;\n        }\n        largestBSTUtil(n.left, bst, bstCount);\n        largestBSTUtil(n.right, bst, bstCount);\n    }\n\n    private void isBST(Node n, BSTCount bstCount) {\n        bstCount.count = 0;\n        bstCount.isBST = false;\n        bstCount.isBST = isBSTUtil(n, Integer.MIN_VALUE, Integer.MAX_VALUE, bstCount);\n    }\n\n    private Boolean isBSTUtil(Node n, int minValue, int maxValue, BSTCount c) {\n        if (n == null) {\n            return true;\n        }\n        if (minValue < n.data && n.data < maxValue) {\n            c.count++;\n            return isBSTUtil(n.left, minValue, n.data, c) && isBSTUtil(n.right, n.data, maxValue, c);\n        }\n\n        return false;\n    }\n}"
  },
  {
    "path": "data_structures/binary_search_tree/java/bst_operations/LevelOrder.java",
    "content": "package bst_operations;\n\n\nimport java.util.*;\n\n/**\n * Created by kalsi on 01/09/17.\n */\npublic class LevelOrder {\n    public static void main(String[] args) {\n        new LevelOrder().demo();\n    }\n\n    private void demo() {\n\n        Node n = new Node(8);\n        // left\n        n.left = new Node(3);\n        n.left.left = new Node(1);\n        n.left.right = new Node(6);\n        n.left.right.left = new Node(4);\n        n.left.right.right = new Node(7);\n\n        //right\n        n.right = new Node(10);\n        n.right.right = new Node(14);\n        n.right.right.left = new Node(13);\n\n        /*\n                                    8\n                        3                    10\n                  1             6                       14\n                           4        7              13\n        *\n        * */\n        System.out.println(\"Without zigzag\");\n        displayLevelOrder(n, false); //without zigzag\n        System.out.println(\"With zigzag\");\n        displayLevelOrder(n, true); //with zigzag\n    }\n\n    private void displayLevelOrder(Node n, Boolean zigzag) {\n        if (n == null) {\n            return;\n        }\n        Boolean flag = true;\n        Deque<Node> parents = new LinkedList<Node>();\n        parents.add(n);\n        while (!parents.isEmpty()) {\n            print(parents, flag, zigzag);\n            flag = !flag;\n            int count = parents.size();\n            while (count-- > 0) {\n                Node removedParent = parents.removeFirst();\n                if (removedParent.left != null) {\n                    parents.addLast(removedParent.left);\n                }\n                if (removedParent.right != null) {\n                    parents.addLast(removedParent.right);\n                }\n            }\n            System.out.println();\n        }\n    }\n\n    private void print(Deque<Node> parents, Boolean flag, Boolean zigzag) {\n        Iterator<Node> iterator = parents.descendingIterator();\n        if (!zigzag || flag) {\n            iterator = parents.iterator();\n        }\n        while (iterator.hasNext()) {\n            System.out.print(iterator.next().data + \"\\t\");\n        }\n\n    }\n}\n"
  },
  {
    "path": "data_structures/binary_search_tree/java/bst_operations/MorrisTraversal.java",
    "content": "package bst_operations;\n\n\n/**\n * Created by kalsi on 30/08/17.\n * Inorder traversal without recursion or stacks\n */\npublic class MorrisTraversal {\n    public static void main(String[] args) {\n        new MorrisTraversal().demo();\n    }\n\n    private void demo() {\n        Node n = new Node(8);\n        // left\n        n.left = new Node(3);\n        n.left.left = new Node(1);\n        n.left.right = new Node(6);\n        n.left.right.left = new Node(4);\n        n.left.right.right = new Node(7);\n\n        //right\n        n.right = new Node(10);\n        n.right.right = new Node(14);\n        n.right.right.left = new Node(13);\n\n        /*\n                            8\n                        3      10\n                     1    6        14\n                        4   7   13\n        *\n        * */\n        inorderIterative(n);\n    }\n\n\n    private void inorderIterative(Node n) {\n        while (n != null) {\n            if (n.left == null) {\n                System.out.print(n.data + \"\\t\");\n                n = n.right;\n            }\n            Node predecessor = getPredecessor(n);\n            if (predecessor.right == null) {\n                predecessor.right = n;\n                n = n.left;\n            } else {\n                predecessor.right = null;\n                System.out.print(n.data + \"\\t\");\n                n = n.right;\n            }\n\n        }\n    }\n\n    private Node getPredecessor(Node n) {\n        Node temp = n.left;\n        while( temp.right != null && temp.right != n) {\n            temp = temp.right;\n        }\n        return temp;\n    }\n}\n"
  },
  {
    "path": "data_structures/binary_search_tree/java/bst_operations/Node.java",
    "content": "package bst_operations;\n\npublic class Node {\n    int data;\n    Node left;\n    Node right;\n\n    public Node(int d) {\n        data = d;\n    }\n}\n\n"
  },
  {
    "path": "data_structures/binary_search_tree/java/bst_operations/PathFromRootToNode.java",
    "content": "package bst_operations;\n\nimport java.util.ArrayList;\n\n/**\n * Created by kalsi on 30/08/17.\n * Path from root to node\n */\npublic class PathFromRootToNode {\n    Boolean found = false;\n    public static void main(String[] args) {\n        new PathFromRootToNode().demo();\n    }\n\n    private void demo() {\n        Node n = new Node(8);\n        // left\n        n.left = new Node(3);\n        n.left.left = new Node(1);\n        n.left.right = new Node(6);\n        n.left.right.left = new Node(4);\n        n.left.right.right = new Node(7);\n\n        //right\n        n.right = new Node(10);\n        n.right.right = new Node(14);\n        n.right.right.left = new Node(13);\n\n        /*\n                            8\n                        3      10\n                     1    6        14\n                        4   7   13\n        *\n        * */\n        ArrayList<Node> al = new ArrayList<Node>();\n        findPath(n, 13, al);\n        display(al);\n\n    }\n\n    private void display(ArrayList<Node> al) {\n        System.out.println(\"--\");\n        for (Node n : al) {\n            System.out.print(n.data + \" --> \");\n        }\n        System.out.println(\"NULL\");\n    }\n\n    private void findPath(Node n, int data, ArrayList<Node> al) {\n        if (n != null && !found) {\n            al.add(n);\n            findPath(n.left, data, al);\n            if (n.data == data) {\n                found = true;\n            }\n            findPath(n.right, data, al);\n            if (!found) {\n                al.remove(al.size() - 1);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "data_structures/binary_search_tree/javascript/binary_tree.js",
    "content": "// Cleaner Logging\nexport const _ = (...vals) => console.log(...vals);\n\n// Create BST Node\nexport function BST(val) {\n    let self = Object.create(BST.prototype);\n\n    // Create Based Properties of BST Node\n    self.value = val;\n    self.right = undefined;\n    self.left = undefined;\n\n    // Insert Function, to properly place value in tree structure\n\n    return self;\n}\nBST.prototype.insert = function(value) {\n    let node = BST(value);\n    function recurse(bst) {\n        if (bst.value > value && bst.left === undefined) {\n            bst.left = node;\n        } else if (bst.value > value) {\n            recurse(bst.left);\n        } else if (bst.value < value && bst.right === undefined) {\n            bst.right = node;\n        } else if (bst.value < value) {\n            recurse(bst.right);\n        }\n    }\n\n    recurse(this);\n};\n"
  },
  {
    "path": "data_structures/binary_search_tree/javascript/binary_tree_search.js",
    "content": "import { _, BST } from './binary_tree';\n\n// Recursive binary search\nBST.prototype.contains = function(value) {\n    var doesContain = false;\n    function recurse(bst) {\n        if (bst.value === value) {\n            doesContain = true;\n        } else if (bst.left !== undefined && value < bst.value) {\n            recurse(bst.left);\n        } else if (bst.right !== undefined && value > bst.value) {\n            recurse(bst.right);\n        }\n    }\n\n    recurse(this);\n    return doesContain;\n};\nBST.prototype.binarySearch = function(value) {\n    let bst = this;\n    let returnVal = null;\n    let it = 0;\n    function recurse(bst) {\n        it++;\n        if (bst.value === value) {\n            returnVal = { bst, it };\n        } else if (bst.left !== undefined && value < bst.value) {\n            recurse(bst.left);\n        } else if (bst.right !== undefined && value > bst.value) {\n            recurse(bst.right);\n        }\n    }\n\n    recurse(this);\n    return returnVal;\n};\nBST.prototype.binarySearchIterative = function(value) {\n    let bst = this;\n    let it = 0;\n    let found = false;\n    while (!found) {\n        it++;\n        if (bst.value === value) {\n            return { bst, it };\n        } else if (bst.left !== undefined && value < bst.value) {\n            bst = bst.left;\n        } else if (bst.right !== undefined && value > bst.value) {\n            bst = bst.right;\n        } else {\n            found = true;\n        }\n    }\n\n    return { bst: null, it };\n};\nlet _bst = BST(5);\n_bst.insert(3);\n_bst.insert(4);\n_bst.insert(1);\n_bst.insert(2);\n_bst.insert(0);\n_bst.insert(8);\n_bst.insert(7);\n_bst.insert(9);\n_bst.insert(6);\nlet num = 3;\n\n_(`Binary Search for ${num}: `, _bst.binarySearchIterative(num));\n"
  },
  {
    "path": "data_structures/binary_search_tree/javascript/breadth_first_search.js",
    "content": "import { _, BST } from './binary_tree';\n// Create Queue Class\nlet Queue = () => {\n    let _data = [];\n\n    return {\n        enqueue(val) {\n            _data.push(val);\n        },\n        dequeue() {\n            return _data.splice(0, 1)[0];\n        },\n        isEmpty() {\n            return _data.length === 0;\n        },\n        Top() {\n            return _data[0];\n        },\n    };\n};\n// Test Queue\n// let que = Queue();\n// que.enqueue(1);\n// que.enqueue(2);\n// que.enqueue(3);\n\n// _(que.dequeue());\n// _(que.dequeue());\n\n// _(que.dequeue());\n\nBST.prototype.breadthFirstLog = function(callback) {\n    let bst = this;\n    let queue = Queue();\n    let firstRun = true;\n    function recurse(bst) {\n        callback.call(bst, bst.value);\n        if (!queue.isEmpty() || (bst.left !== undefined || bst.right !== undefined) || firstRun) {\n            if (firstRun) {\n                firstRun = false;\n            }\n            if (bst.left !== undefined) {\n                queue.enqueue(bst.left);\n            }\n\n            if (bst.right !== undefined) {\n                queue.enqueue(bst.right);\n            }\n            recurse(queue.dequeue());\n        }\n    }\n    recurse(this);\n};\nBST.prototype.breadthFirstSearch = function(searchVal) {\n    let queue = Queue();\n    let firstRun = true;\n    let it = 0;\n    let returnVal = null;\n    function recurse(bst) {\n        it++;\n        _(bst.value, searchVal);\n        if (bst.value === searchVal) {\n            // Set Return for BST Node and how many recursive iterations there were\n            returnVal = { bst, it };\n        } else {\n            if (!queue.isEmpty() || (bst.left !== undefined || bst.right !== undefined) || firstRun) {\n                if (firstRun) {\n                    firstRun = false;\n                }\n                if (bst.left !== undefined) {\n                    queue.enqueue(bst.left);\n                }\n\n                if (bst.right !== undefined) {\n                    queue.enqueue(bst.right);\n                }\n                if (!queue.isEmpty()) {\n                    recurse(queue.dequeue());\n                }\n            }\n        }\n    }\n    recurse(this);\n    if (returnVal === null) {\n        returnVal = { bst: null, it };\n    }\n    return returnVal;\n};\nBST.prototype.breadthFirstSearchIterative = function(searchVal) {\n    let bst = this;\n    let queue = Queue();\n    let firstRun = true;\n    let it = 0;\n    do {\n        it++;\n        _(bst.value, searchVal);\n        if (bst.value === searchVal) {\n            // Set Return for BST Node and how many recursive iterations there were\n            return { bst, it };\n        } else {\n            if (!queue.isEmpty() || (bst.left !== undefined || bst.right !== undefined) || firstRun) {\n                if (firstRun) {\n                    firstRun = false;\n                }\n                if (bst.left !== undefined) {\n                    queue.enqueue(bst.left);\n                }\n\n                if (bst.right !== undefined) {\n                    queue.enqueue(bst.right);\n                }\n                bst = queue.dequeue();\n            }\n        }\n    } while (!queue.isEmpty() || bst !== undefined);\n    return { BST: null, it };\n};\n\nlet _bst = BST(5);\n_bst.insert(3);\n_bst.insert(4);\n_bst.insert(1);\n_bst.insert(2);\n_bst.insert(0);\n_bst.insert(8);\n_bst.insert(7);\n_bst.insert(9);\n_bst.insert(6);\n\nlet num = 3;\n_(`Breadth First Search for ${num}: `, _bst.breadthFirstSearch(num));\n"
  },
  {
    "path": "data_structures/binary_search_tree/javascript/depth_first_search.js",
    "content": "import { _, BST } from './binary_tree';\n\n// Create Stack Class\nlet Stack = () => {\n    let _data = [];\n    return {\n        Top() {\n            return _data[_data.length - 1];\n        },\n        Pop() {\n            return _data.splice(_data.length - 1, 1)[0];\n        },\n        Push(val) {\n            _data.push(val);\n        },\n        isEmpty() {\n            return _data.length === 0;\n        },\n    };\n};\n// Test Stack Class\n// let stack = Stack();\n// stack.Push(1);\n// stack.Push(2);\n// stack.Push(3);\n// stack.Push(4);\n// _(stack.Pop());\n// _(stack.Pop());\n// _(stack.Pop());\n// _(stack.Pop());\n\nBST.prototype.depthFirstLog = function(callback) {\n    function recurse(bst) {\n        callback.call(bst, bst.value);\n        if (bst.left !== undefined) {\n            recurse(bst.left);\n        }\n        if (bst.right !== undefined) {\n            recurse(bst.right);\n        }\n    }\n\n    recurse(this);\n};\nBST.prototype.depthFirstSearch = function(searchVal) {\n    let stack = Stack();\n    let it = 0;\n    let returnVal = null;\n    function recurse(bst) {\n        it++;\n        if (bst.value === searchVal) {\n            returnVal = { bst, it };\n        } else {\n            if (bst.left !== undefined) {\n                stack.Push(bst.left);\n            }\n            if (bst.right !== undefined) {\n                stack.Push(bst.right);\n            }\n            if (!stack.isEmpty()) {\n                recurse(stack.Pop());\n            }\n        }\n    }\n\n    recurse(this);\n    if (returnVal === null) {\n        returnVal = { bst: null, it };\n    }\n    return returnVal;\n};\nBST.prototype.depthFirstSearchIterative = function(searchVal) {\n    let bst = this;\n    let stack = Stack();\n    let it = 0;\n    do {\n        it++;\n        if (bst.value === searchVal) {\n            return { bst, it };\n        } else {\n            if (bst.left !== undefined) {\n                stack.Push(bst.left);\n            }\n            if (bst.right !== undefined) {\n                stack.Push(bst.right);\n            }\n            bst = stack.Pop();\n        }\n    } while (!stack.isEmpty() || bst !== undefined);\n\n    return { bst: null, it };\n};\nlet _bst = BST(5);\n_bst.insert(3);\n_bst.insert(4);\n_bst.insert(1);\n_bst.insert(2);\n_bst.insert(0);\n_bst.insert(8);\n_bst.insert(7);\n_bst.insert(9);\n_bst.insert(6);\n\nlet num = 3;\n_(`Depth First Search for ${num}: `, _bst.depthFirstSearch(num));\n"
  },
  {
    "path": "data_structures/binary_search_tree/python/bst.py",
    "content": "\"\"\"\nDefining a TreeNode class\n\"\"\"\n\nclass TreeNode:\n    def __init__(self,k=None):\n        self.parent=None\n        self.key=k\n        self.left=None\n        self.right=None\n\n    def isleft(self):\n    \tif self.parent is None:\n    \t\tprint(\"Root\")\n    \tif self.parent.left==self:\n    \t\treturn True\n    \treturn False\n    \n    def isright(self):\n    \tif self.parent is None:\n    \t\tprint(\"Root\")\n    \tif self.parent.right==self:\n    \t\treturn True\n    \treturn False\n    def isleaf(self):\n    \tif self.right is None and self.left is None:\n    \t\treturn True\n    \telse:\n    \t\treturn False\t\t\n\"\"\"\nBinary Search Tree Implementation.\nMethods : \nisEmpty()\ninsert()\ndelete()\nprecdecessor()\nmaximum()\nminimum()\nsuccessor()\nsearch()\n\n\"\"\"\n\nclass BST:\n    \n    def __init__(self):\n        self.root=None\n    \n    def isEmpty(self):\n    \tif self.root is None:\n    \t\treturn True\n    \treturn False\n    \n    def insert(self,key1):\n    \ttemp=TreeNode(key1)\n    \tif self.isEmpty():\n    \t\tself.root=temp\n    \telse:\n    \t\tcurrent=self.root\n    \t\twhile current is not None:\n    \t\t\tif key1 > current.key:\n    \t\t\t\tif current.right is None:\n    \t\t\t\t\tcurrent.right=temp\n    \t\t\t\t\ttemp.parent=current\n    \t\t\t\t\tbreak\n    \t\t\t\telse:\n    \t\t\t\t\tcurrent=current.right\n    \t\t\telse:\n    \t\t\t\tif current.left is None:\n    \t\t\t\t\tcurrent.left=temp\n    \t\t\t\t\ttemp.parent=current\n    \t\t\t\t\tbreak\n    \t\t\t\telse:\n    \t\t\t\t\tcurrent=current.left\n    \t\t\t\t\t\t\t\n    def maximum(self):\n    \tif self.isEmpty():\n    \t\treturn \"Empty Tree\"\n    \telse:\n    \t\tcurrent=self.root\n    \t\twhile current is not None:\n    \t\t\tif current.right is None:\n    \t\t\t\treturn current.key\n    \t\t\telse:\n    \t\t\t\tcurrent=current.right\t\t\n\n    def minimum(self):\n    \tif self.isEmpty():\n    \t\treturn \"Empty Tree\"\n    \telse:\n    \t\tcurrent=self.root\n    \t\twhile current is not None:\n    \t\t\tif current.left is None:\n    \t\t\t\treturn current.key\n    \t\t\telse:\n    \t\t\t\tcurrent=current.left\n\n    def successor(self,node):\n    \tif node.key ==self.maximum():\n    \t\treturn node.key\n    \telse:\n    \t\tif node.right is not None:\n    \t\t\ttempt=BST()\n    \t\t\ttempt.root=node.right\n    \t\t\treturn tempt.minimum()\n    \t\telse:\n    \t\t\tch=node\n    \t\t\tp=node.parent\n    \t\t\twhile ch is not None:\n    \t\t\t\tif ch.isleft():\n    \t\t\t\t\treturn p.key\n    \t\t\t\telse:\n    \t\t\t\t\tch=p\n    \t\t\t\t\tp=p.parent\n    def predecessor(self,node):\n    \tif node.key ==self.minimum():\n    \t\treturn node.key\n    \telse:\n    \t\tif node.left is not None:\n    \t\t\ttempt=BST()\n    \t\t\ttempt.root=node.left\n    \t\t\treturn tempt.maximum()\n    \t\telse:\n    \t\t\tch=node\n    \t\t\tp=node.parent\n    \t\t\twhile ch is not None:\n    \t\t\t\tif ch.isright():\n    \t\t\t\t\treturn p.key\n    \t\t\t\telse:\n    \t\t\t\t\tch=p\n    \t\t\t\t\tp=p.parent\n\t\t\t\t\t\n\n    def search(self,key):\t\t\t\t\t\n    \tcurrent=self.root\n    \twhile current is not None:\n    \t\tif current.key==key:\n    \t\t\treturn current\n    \t\telif current.key<key:\n    \t\t\tcurrent=current.right\n    \t\telse:\n    \t\t\tcurrent=current.left\t\t\n    \treturn None\n\n    def delete(self,node):\n        if self.isEmpty():\n            return \"Empty tree\"\n        elif node is None:\n        \treturn \"Node not in tree\"\n        elif node==self.root:\n        \tpred=self.search(self.predecessor(node))\n        \tnode.key=pred.key\n        \tself.delete(pred)\t\t\t\t\n        else:\n        \tif node.isleaf():\n        \t\tif node.isleft():\n        \t\t\tnode.parent.left=None\n        \t\telse:\n        \t\t\tnode.parent.right=None\n        \telif node.left is None or node.right is None:\n        \t\tif node.left is None:\n        \t\t\tchild=node.right\n        \t\telse:\n        \t\t\tchild=node.left\n        \t\tif node.isleft():\n        \t\t\tnode.parent.left=child\n        \t\t\tchild.parent=node.parent\n        \t\telse:\n        \t\t\tnode.parent.right=child\n        \t\t\tchild.parent=node.parent\n        \telse:\n        \t\tpred=self.search(self.predecessor(node))\n        \t\tnode.key=pred.key\n        \t\tself.delete(pred)\n\"\"\"\nFunction to print preorder traversal of tree\n\"\"\"\n\n\ndef printree(r):\n\tif r.isleaf():\n\t\tprint(r.key,end=' ')\n\telse:\n\t\tif r.left is not None:\n\t\t\tprintree(r.left)\n\t\tif r.right is not None:\n\t\t\tprintree(r.right)\n\t\tprint(r.key,end=' ')\n\tprint(\" \")    \t\n"
  },
  {
    "path": "data_structures/binary_search_tree/python/bst1.py",
    "content": "# 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))\n \n# Print inoder traversal of the BST\ninorder(r)\n"
  },
  {
    "path": "data_structures/binary_search_tree/python/bst2.py",
    "content": "\nclass Node:\n    def __init__(self,data,left=None,right=None):\n        self.data = data\n        self.left = left\n        self.right = right\n\n\nclass BST:\n    def __init__(self,data=None):\n        self.root = Node(data)\n    \n    def printSideway(root,level):\n        if root != None:\n            BST.printSideway(root.right,level+1)\n            print(' '*(3*level),root.data)\n            BST.printSideway(root.left,level+1)\n\n    def addI(self,data):\n        q = []\n        q.append(self.root)\n        while len(q) != 0:\n            n = q.pop(0)\n            if not n.left < data:\n                q.append(n.left)\n            if not n.right >= data:\n                q.append(n.right)\n                \n            \n            if n.left == None:\n                pass\n            else:q.append(n.left)\n\n            if n.right == None:\n                passs\n            else:q.append(n.right)\n\n    \n    def insertR(root,data):\n\n        if root.data == None:\n            root.data = data\n            return\n        if data < root.data:\n            if root.left != None:\n                BST.insertR(root.left,data)\n            else:\n                root.left = Node(data)\n        else:\n            if root.right != None:\n                BST.insertR(root.right,data)\n            else:\n                root.right = Node(data)\n\n    def inOrder(root,lamb=None):\n        if root.left != None:\n            BST.inOrder(root.left,lamb)\n        if root.data != None:\n            if lamb == None:\n                print(root.data,end=' ')\n            else:\n                lamb(root.data)\n        if root.right != None:\n            BST.inOrder(root.right,lamb)\n    def _search(root,data):\n        if root.left != None:\n            return BST._search(root.left,data)\n        if root.data != None:\n            if root.data == data:\n                return root.data\n        if root.right != None:\n            return BST._search(root.right,data)\n\n    def search(self,data):\n        return BST._search(self.root,data)\n        \n    def _path(root,data):\n        if root.left != None:\n            res = BST._path(root.left,data) \n            if res!=None:\n                print(root.data)\n            return res\n        if root.data != None:\n            if root.data == data:\n                print(root.data)\n                return root.data\n        if root.right != None:\n            res = BST._path(root.right,data) \n            if res!=None:\n                print(root.data)\n            return res\n\n    def path(self,data):\n        BST._path(self.root,data)\n\n\n    def _del(root,data):\n        if root.left != None:\n            BST._del(root.left,data)\n        if root.data != None:\n            if root.data == data:\n                pass\n                # root.\n        if root.right != None:\n            BST._del(root.right,data)\n    def dele(self,data):\n        BST._del(self.root,data)\n"
  },
  {
    "path": "data_structures/binary_tree/c/diameterBT.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n \nstruct node\n{\n    int data;\n    struct node* left, *right;\n};\n \n/* function to create a new node of tree and returns pointer */\nstruct node* newNode(int data);\n \n/* returns max of two integers */\nint max(int a, int b);\n \n/* function to Compute height of a tree. */\nint height(struct node* node);\n \n/* Function to get diameter of a binary tree */\nint diameter(struct node * tree)\n{\n   /* base case where tree is empty */\n   if (tree == NULL)\n     return 0;\n \n  /* get the height of left and right sub-trees */\n  int lheight = height(tree->left);\n  int rheight = height(tree->right);\n \n  /* get the diameter of left and right sub-trees */\n  int ldiameter = diameter(tree->left);\n  int rdiameter = diameter(tree->right);\n \n  /* Return max of following three\n   1) Diameter of left subtree\n   2) Diameter of right subtree\n   3) Height of left subtree + height of right subtree + 1 */\n  return max(lheight + rheight + 1, max(ldiameter, rdiameter));\n} \n \n/* UTILITY FUNCTIONS TO TEST diameter() FUNCTION */\n \n/*  The function Compute the \"height\" of a tree. Height is the \n    number f nodes along the longest path from the root node \n    down to the farthest leaf node.*/\nint height(struct node* node)\n{\n   /* base case tree is empty */\n   if(node == NULL)\n       return 0;\n \n   /* If tree is not empty then height = 1 + max of left \n      height and right heights */   \n   return 1 + max(height(node->left), height(node->right));\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 = (struct node*)\n                       malloc(sizeof(struct node));\n  node->data = data;\n  node->left = NULL;\n  node->right = NULL;\n \n  return(node);\n}\n \n/* returns maximum of two integers */\nint max(int a, int b)\n{\n  return (a >= b)? a: b;\n}    \n \n/* Driver function*/\nint main()\n{\n \n  /* Constructed binary tree is \n            1\n          /   \\\n        2      3\n      /  \\\n    4     5\n  */\n  struct node *root = newNode(1);\n  root->left        = newNode(2);\n  root->right       = newNode(3);\n  root->left->left  = newNode(4);\n  root->left->right = newNode(5);\n \n  printf(\"Diameter of the given binary tree is %d\\n\", diameter(root));\n \n  getchar();\n  return 0;\n}"
  },
  {
    "path": "data_structures/binary_tree/cpp/binary_tree.cpp",
    "content": "#include <iostream>\n\nstruct Node {\n    int key;\n    Node *leftnode;\n    Node *rightnode;\n    std::string value;\n    Node(int tkey, const std::string& tvalue) : leftnode(nullptr), rightnode(nullptr), key(tkey), value(tvalue) {}\n};\n\nNode root_node(1, \"Node #1\"); \nstd::string query_bst(const int key) {\n    Node *cur_node = &root_node;\n    while (cur_node != nullptr) {\n        if (key == cur_node->key) {\n            return cur_node->value;\n        }\n        if (key < cur_node->key) { \n            cur_node = cur_node->leftnode;\n        } else {\n            cur_node = cur_node->rightnode;\n        }\n    }\n    return \"\"; \n}\n\nvoid insert_bst(int key, const std::string& value) {\n    Node *cur_node;\n    Node *next_node = &root_node;\n    while (next_node != nullptr) {\n        cur_node = next_node;\n        if (key < cur_node->key) {\n            next_node = cur_node->leftnode;\n        } else {\n            next_node = cur_node->rightnode;\n        }\n    }\n    if (key < cur_node->key) {\n        cur_node->leftnode = new Node(key, value);\n    }\n    else {\n        cur_node->rightnode = new Node(key, value);\n    }\n}\n\nint main() {\n    insert_bst(2, \"Node #2\");\n    insert_bst(3, \"Node #3\");\n    std::cout << query_bst(3) << '\\n';\n}\n"
  },
  {
    "path": "data_structures/binary_tree/cpp/boundaryTraversal.cpp",
    "content": "/* program for boundary traversal of a binary tree */\n#include <stdio.h>\n#include <stdlib.h>\n\nstruct node\n{\n    int data;\n    struct node *left, *right;\n};\n \n// A simple function to print leaf nodes of a binary tree\nvoid printLeaves(struct node* root)\n{\n    if ( root )\n    {\n        printLeaves(root->left);\n \n        // Print it if it is a leaf node\n        if ( !(root->left)  &&  !(root->right) )\n            printf(\"%d \", root->data);\n \n        printLeaves(root->right);\n    }\n}\n \n// A function to print all left boundry nodes, except a leaf node.\n// Print the nodes in TOP DOWN manner\nvoid printBoundaryLeft(struct node* root)\n{\n    if (root)\n    {\n        if (root->left)\n        {\n            // to ensure top down order, print the node\n            // before calling itself for left subtree\n            printf(\"%d \", root->data);\n            printBoundaryLeft(root->left);\n        }\n        else if( root->right )\n        {\n            printf(\"%d \", root->data);\n            printBoundaryLeft(root->right);\n        }\n        // do nothing if it is a leaf node, this way we avoid\n        // duplicates in output\n    }\n}\n \n// A function to print all right boundry nodes, except a leaf node\n// Print the nodes in BOTTOM UP manner\nvoid printBoundaryRight(struct node* root)\n{\n    if (root)\n    {\n        if ( root->right )\n        {\n            // to ensure bottom up order, first call for right\n            //  subtree, then print this node\n            printBoundaryRight(root->right);\n            printf(\"%d \", root->data);\n        }\n        else if ( root->left )\n        {\n            printBoundaryRight(root->left);\n            printf(\"%d \", root->data);\n        }\n       // do nothing if it is a leaf node, this way we avoid\n       // duplicates in output\n    }\n}\n \n \n// A function to do boundary traversal of a given binary tree\nvoid printBoundary (struct node* root)\n{\n    if (root)\n    {\n        printf(\"%d \",root->data);\n \n        // Print the left boundary in top-down manner.\n        printBoundaryLeft(root->left);\n \n        // Print all leaf nodes\n        printLeaves(root->left);\n        printLeaves(root->right);\n \n        // Print the right boundary in bottom-up manner\n        printBoundaryRight(root->right);\n    }\n}\n \n// Create a node\nstruct node* newNode( int data )\n{\n    struct node* temp = (struct node *) malloc( sizeof(struct node) );\n \n    temp->data = data;\n    temp->left = temp->right = NULL;\n \n    return temp;\n}\n \n// Driver program\nint main()\n{\n    struct node *root         = newNode(20);\n    root->left                = newNode(8);\n    root->left->left          = newNode(4);\n    root->left->right         = newNode(12);\n    root->left->right->left   = newNode(10);\n    root->left->right->right  = newNode(14);\n    root->right               = newNode(22);\n    root->right->right        = newNode(25);\n \n    printBoundary( root );\n \n    return 0;\n}"
  },
  {
    "path": "data_structures/binary_tree/csharp/BinaryTree.cs",
    "content": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace DataStructures\n{\n    class BinaryTree\n    {\n\n        public class TreeObject\n        {\n            TreeObject key;\n            TreeObject leftchild = null;\n            TreeObject rightchild = null;\n\n            public TreeObject(TreeObject newitem)\n            {\n                key = newitem;\n            }\n\n            public TreeObject getRoot()\n            {\n                return key;\n            }\n\n            public TreeObject getLeftChild()\n            {\n                return leftchild;\n            }\n\n            public TreeObject getRightChild()\n            {\n                return rightchild;\n            }\n\n            public void setRoot(TreeObject newItem)\n            {\n                key = newItem;\n            }\n\n            public void setLeftChild(TreeObject newItem)\n            {\n                leftchild = newItem;\n            }\n\n            public void setRightChild(TreeObject newItem)\n            {\n                rightchild = newItem;\n            }\n\n        }\n\n        public TreeObject init(TreeObject newitem)\n        {\n            return new TreeObject(newitem);\n        }\n\n\n        public void insertRight(TreeObject self, TreeObject newNode)\n        {\n            if (self.getRightChild() == null)\n            {\n                self.setRightChild(newNode);\n            }\n            else\n            {\n                TreeObject obj = new TreeObject(newNode);\n                obj.setRightChild(self.getRightChild());\n                self.setRightChild(obj);\n            }\n        }\n\n\n        public void insertLeft(TreeObject self, TreeObject newNode)\n        {\n            if (self.getLeftChild() == null)\n            {\n                self.setLeftChild(newNode);\n            }\n            else\n            {\n                TreeObject obj = new TreeObject(newNode);\n                obj.setLeftChild(self.getLeftChild());\n                self.setLeftChild(obj);\n            }\n        }\n\n    }\n}\n"
  },
  {
    "path": "data_structures/binary_tree/java/binary_tree_bfs.java",
    "content": "package shubham;  //Breadth first search to search the element and print the path.\n\nimport java.util.LinkedList;\nimport java.util.Queue;\n\npublic class bfs {\n\n\tpublic void levelOrderQueue(Node root) {\n\tQueue<Node> q = new LinkedList<Node>();\n\tif (root == null)\n\treturn;\n\tq.add(root);\n\twhile (!q.isEmpty()) {\n\tNode n = (Node) q.remove();\n\t\t\t\t\n\t\t\t\t\n\tint goal=11;\n\tint c=0;\n\t\t\t\t\n\t\t\t\tif (n.left != null)\n\t\t\t\t\tq.add(n.left);\n\t\t\t\tc+=1;\n\t\t\t\tif (n.right != null)\n\t\t\t\t\tq.add(n.right);\n\t\t\t\tc+=1;\n\t\t\t\t  System.out.print(\" \" + n.data);\n\t\t\t\t\tif(n.data==goal)\n\t\t\t\t\tbreak;\n\t\t\t\n\t\t\t    \n\t\t\t      \n\t\t\t    \n\t\t\t}\n\t\t\t\n\t\t}\n\n\t\tpublic static void main(String[] args) throws java.lang.Exception {\n\t\t\tNode root = new Node(1);\n\t\t\troot.left = new Node(2);\n\t\t\troot.right = new Node(3);\n\t\t\troot.left.left = new Node(4);\n\t\t\troot.left.right = new Node(5);\n\t\t\troot.right.left = new Node(6);\n\t\t\troot.right.right = new Node(7);\n            root.left.left.left= new Node(8);\n            root.left.left.right= new Node(9);\n            root.left.right.left=new Node(10);\n\t\t\troot.left.right.right=new Node(11);\n            root.right.left.left=new Node(12);\n            root.right.left.right=new Node(13);\n\t\t\troot.right.left.right= new Node(14);\n\t\t\troot.right.right.right= new Node(15);\n\t\t\t\n            bfs i = new bfs();\n\t\t\tSystem.out.println(\"Breadth First Search : \");\n\t\t\ti.levelOrderQueue(root);\n\t\t}\n\t}\n\n\tclass Node {\n\t\tint data;\n\t\tNode left;\n\t\tNode right;\n\n\t\tpublic Node(int data) {\n\t\t\tthis.data = data;\n\t\t\tthis.left = null;\n\t\t\tthis.right = null;\n\t\t}\n\t}\n\n"
  },
  {
    "path": "data_structures/binary_tree/java/binary_tree_dfs.java",
    "content": "import java.util.*;\n\nclass Node{\n\tint data;\n\tNode left,right;\n\n\t\tpublic Node(int item){\n\t\tdata = item;\n\t\tleft = right = null;\n\t\t}\n\n}\n\nclass BinaryTree{\n\n\tNode root;\n\tBinaryTree(){\n\troot = null;\n}\n\n\npublic void preorder_rec(Node node){\n\n\tif(node == null) return;\n\tSystem.out.println(node.data);\n\n\tpreorder_rec(node.left);\n\n\tpreorder_rec(node.right);\n\n}\n\n\n\npublic void inorder_rec(Node node){\n\n\tif(node == null) return;\n\n\tinorder_rec(node.left);\n\n\tSystem.out.println(node.data);\n\n\tinorder_rec(node.right);\n\n}\n\n\n\npublic void postorder(Node node){\n\n\tif(node == null) return;\n\tpostorder(node.left);\n\n\tpostorder(node.right);\n\n\tSystem.out.println(node.data);\n\n}\n\n\n\npublic static void main(String[] args){\n\nBinaryTree bt = new BinaryTree();\n\n bt.root = new Node(1);\n bt.root.left = new Node(2);\n bt.root.right = new Node(3);\n bt.root.left.left = new Node(4);\n bt.root.left.right = new Node(5);  \n bt.root.right.right = new Node(7);\n bt.root.right.left = new Node(6);\n bt.queue.add(bt.root);\n\n\nSystem.out.println(\"Preorder Recursive\");\nbt.preorder_rec(bt.root);\n\nSystem.out.println(\"Inorder Recursive\");\nbt.inorder_rec(bt.root);\n\nSystem.out.println(\"Postorder\");\nbt.postorder(bt.root);\n\n\n\n}\n\n}"
  },
  {
    "path": "data_structures/binary_tree/python/binary_tree.py",
    "content": "class BinaryTree:\n\tdef __init__(self,rootObj):\n\t\tself.key = rootObj\n\t\tself.leftChild = None\n\t\tself.rightChild = None\n\n\tdef insertLeft(self,newNode):\n\t\tif self.leftChild == None:\n\t\t\tself.leftChild = BinaryTree(newNode)\n\t\telse:\n\t\t\tt = BinaryTree(newNode)\n\t\t\tt.leftChild = self.leftChild\n\t\t\tself.leftChild = t\n\n\tdef insertRight(self,newNode):\n\t\tif self.rightChild == None:\n\t\t\tself.rightChild = BinaryTree(newNode)\n\t\telse:\n\t\t\tt = BinaryTree(newNode)\n\t\t\tt.rightChild = self.rightChild\n\t\t\tself.rightChild = t\n\n\n\tdef getRightChild(self):\n\t\treturn self.rightChild\n\n\tdef getLeftChild(self):\n\t\treturn self.leftChild\n\n\tdef setRootVal(self,obj):\n\t\tself.key = obj\n\n\tdef getRootVal(self):\n\t\treturn self.key\n\n"
  },
  {
    "path": "data_structures/bloom_filter/python/bloom_filter.py",
    "content": "# A simple bloom filter in Python 3\n# Author: Flora Rosenkreuz (reindeer-cafe)\nimport math\n\nclass BloomFilter:\n\n\t# very simple string encode\n\tdef SimpleStringEncode(self, data):\n\t\thash = 0\n\t\tfor x in data: hash += (ord(x))\n\t\treturn hash % 20\n\n\t# implementation of the fnv hash\n\tdef FNV(self, data):\n\t\thash = 2166136261\n\t\tb = bytes(data, 'utf-8')\n\t\tfor byte in b:\n\t\t\thash = hash ^ byte\n\t\t\thash = hash * 16777619\n\t\treturn hash % 20\n\n\t# add a string to the filter\n\tdef Add(self, data):\n\t\th1 = self.SimpleStringEncode(data)\n\t\th2 = self.FNV(data)\n\t\tself.Vector[h1] = 1\n\t\tself.Vector[h2] = 1\n\n\t# false positives are possible in a bloom filter hence is \"possibly\" in\n\tdef IsPossiblyIn(self, data):\n\t\t#m num b\n\t\th1 = self.SimpleStringEncode(data)\n\t\th2 = self.FNV(data)\n\t\treturn True if (self.Vector[h1] and self.Vector[h2]) else False\n\n\t# computes the approximate false positive rate\n\tdef ComputeCollisionRate(self):\n\t\tn = 0\n\t\tfor b in self.Vector:\n\t\t\tn += 1 if b else 0\n\t\treturn math.pow((1 - (math.pow(math.e, (((-1 * 2) * n) / 20)))), 2)\n\n\tdef __init__(self):\n\t\tself.Vector = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\n"
  },
  {
    "path": "data_structures/circular_queue/circular_queue.md",
    "content": "## ELI5\nCIRCULAR QUEUE is a queue in which last position is connected back to first position,i.e. after last location of the list we visit the first location.Forms a circle.\n\n### Pros:\n* Fast operations of adding and removing elements.\n* Utilizes memory efficiently.\n\n### Cons:\n* May become a never-ending loop.\n\n## TECHNICAL EXPLAINATION\nA FIFO data structure ,also called ‘Ring Buffer’,where last element points back to the first element to make a circle.\n* Operations on Circular Queue:.\n\t*enqueue(element): This function is used to insert an element into the circular queue. The new element is always inserted at Rear position.\n\tSteps:\n\tCheck whether queue is Full – Check ((REAR == SIZE && FRONT == 1) || (REAR == FRONT-1)) If TRUE,queue is full. If queue is not full then insert element.\n\t*dequeue(): This function is used to delete an element from the circular queue.The element is always deleted from FRONT position.\neg. CQueue = 1,2,3,4,_\nenqueue(5) gives CQueue=1,2,3,4,5\ndequeue() gives CQueue= _,2,3,4,5\nenqueue(6) gives CQueue=6,2,3,4,5\n\n### Pros:\n* Time complexity of enqueue(), dequeue() operation is O(1).\n* Prevents wastage of space of Simple Queue.\n\n### Cons:\n* A circular queue might cause an an infinite loop, impairing processing - if not implemented properly or in a multi-threaded environment. \n* Complex to code.\n"
  },
  {
    "path": "data_structures/circular_queue/cpp/circular queue.cpp",
    "content": "#include<iostream>\r\n#include<conio.h>\r\nusing namespace std;\r\n\r\nclass queue1\r\n{\r\n\r\n    int n=8,front1=-1,rear=-1,a=0;\r\npublic:\r\n\r\n    int arr[8];\r\n\r\n    void element()\r\n    {\r\n\r\n        cout<<\"enter element\";\r\n        cin>>a;\r\n    }\r\n    void inqueue()\r\n    {\r\n    if((front1>=0&&rear==n-1)||(front1==rear+1))\r\n            {\r\n             //overflow\r\n             cout<<\"queue overflow\"<<endl;\r\n            }\r\n   if (front1==-1&&rear==-1)\r\n        {\r\n            //queue empty\r\n            front1=0;\r\n            rear=0;\r\n            arr[rear]=a;\r\n\r\n        }\r\n        else if(rear==n-1)\r\n            {\r\n                rear=0;\r\n                arr[rear]=a;\r\n\r\n            }\r\n\r\n        else {\r\n                rear++;\r\n               arr[rear]=a;\r\n            }\r\n    }\r\n    int b;\r\n    void dequeue()\r\n    {\r\n        if(rear==-1&&front1==-1)\r\n        {\r\n            cout<<\"underflow\"<<endl;\r\n        }\r\n    if (front1==rear)\r\n        {\r\n            //one element\r\n            b=arr[front1];\r\n            cout<<\"deleted single element is :\"<<b<<endl;\r\n            front1=-1;\r\n            rear=-1;\r\n\r\n        }\r\n        else if (front1==n-1)\r\n        {\r\n            b=arr[front1];\r\n            cout<<\"deleted element last is :\"<<b<<endl;\r\n            front1=0;\r\n        }\r\n        else\r\n        {\r\n           b=arr[front1];\r\n            cout<<\"deleted any element is :\"<<b<<endl;\r\n            front1++;\r\n        }\r\n\r\n    }\r\n    void display()\r\n    {\r\n        cout<<\"the no. in queue are\"<<endl;\r\n        for(int i=front1;i<=rear;i++)\r\n        {\r\n            cout<<arr[i]<<endl;\r\n        }\r\n    }\r\n};\r\n    int main()\r\n    {\r\n        queue1 q;\r\n        int ch,c=1;\r\n\r\nwhile(c==1)\r\n{\r\n        cout<<\"enter choice 1.insertion 2.deletion 3.display 4.exit\"<<endl;\r\n        cin>>ch;\r\n   switch(ch)\r\n{\r\n    case 1:\r\n        {\r\n            q.element();\r\n            q.inqueue();\r\n            break;\r\n        }\r\n    case 2:\r\n        {\r\n            q.dequeue();\r\n            break;\r\n        }\r\n    case 3:\r\n        {\r\n            q.display();\r\n            break;\r\n        }\r\n    case 4:\r\n        {\r\n            c=0;\r\n            break;\r\n        }\r\n}\r\n}\r\n}\r\n\r\n\r\n//seraching n traversing in lkd list\r\n"
  },
  {
    "path": "data_structures/circular_queue/java/circular_queue.java",
    "content": "//circular queue\nimport java.util.*;\ninterface queue1\n{\n\tvoid insert();\n\tvoid delete();\n\tvoid display();\n\t\n}\nclass myqueue1 implements queue1\n{\n\tint arr[]=new int[3];\n\tint front=0,rear=0;\n\tScanner s1 = new Scanner(System.in);\n\tpublic void insert()\n\t{\n\t\t\tint a;\n\t\t\tSystem.out.println(\"enter element:\");\n\t\t\ta=s1.nextInt();\n\t\t\tarr[rear]=a;\n\t\t\trear++;\n\t\tif(rear==3)\n\t\t\trear=0;\n\t}\npublic void delete()\n\t{\n\t\tif (rear==front)\n\t\t\tSystem.out.println(\"queue is empty\");\n\t\telse\n\t\t{\n\t\t\tint a;\n\t\t\ta=arr[front];\n\t\t\tfront++;\n\t\t\tSystem.out.println(\"element deleted : \"+a );\n\t\t\tif(front==3)\n\t\t\tfront=0;\n\t\t}\n\t}\n\tpublic void display()\n\t{\n\t\tSystem.out.println(\"elements are\");\n\t\tfor(int i=front;i<rear;i++)\n\t\t{\n\t\t\tSystem.out.println(arr[i]);\n\t\t}\n\t}\n}\nclass tut7\n{\npublic static void main(String args[])\n{\n\tScanner s = new Scanner(System.in);\n\t\tmyqueue1 m = new myqueue1();\n\t\tboolean b= true;\n\t\twhile(b)\n\t\t{\n\t\tSystem.out.println(\"enter ur choices \\n 1. insert \\n 2. delete \\n 3. display \\n 4. exit\");\n\t\tint n;\n\t\tn=s.nextInt();\n\t\t\n\t\t\n\t\tswitch(n)\n\t\t{\n\t\tcase 1:\n\t\tm.insert();\n\t\tbreak;\n\t\tcase 2:\n\t\tm.delete();\n\t\tbreak;\n\t\tcase 3:\n\t\tm.display();\n\t\tbreak;\n\t\tcase 4:\n\t\tSystem.exit(0);\n\t\t}\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "data_structures/circular_queue/python/circular_queue.py",
    "content": "class CircularQueue:\n\n    def __init__(self):\n        self.queue = list()\n        self.head = 0\n        self.tail = 0\n        self.maxSize = 8\n\n    def enqueue(self, element):\n        if self.size() == self.maxSize-1:\n            return (\"Queue is full.\")\n        self.queue.append(element)\n        self.tail = (self.tail + 1) % self.maxSize\n        return True\n\n    def dequeue(self):\n        if self.size()==0:\n            return (\"Empty queue. Cannot dequeue.\") \n        element = self.queue[self.head]\n        self.head = (self.head + 1) % self.maxSize\n        return element\n\n    def size(self):\n        if self.tail>=self.head:\n            return (self.tail-self.head)\n        return (self.maxSize - (self.head-self.tail))"
  },
  {
    "path": "data_structures/d_heap/c/d_heap.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <heap.h>\n\nHEAP *init(int d){\n\tHEAP *heap = (HEAP *) malloc(sizeof(HEAP));\n\theap->d = d;\n\theap->size = 0;\n\theap->items = NULL;\n\n\treturn heap;\n}\n\nint parent_index(int n, int d){\n\treturn (n-1)/d;\n}\n\nint child_index(int n, int d, int i){\n\treturn n*d+i+1;\n}\n\nvoid push(HEAP *heap, int value){\n\tint i;\n\n\theap->size++;\n\theap->items = (int *) realloc(heap->items, sizeof(int)*heap->size);\n\ti = heap->size - 1;\n\theap->items[i] = 0;\n\n\twhile(i >= 1 && heap->items[parent_index(i, heap->d)] > value){\n\t\theap->items[i] = heap->items[parent_index(i, heap->d)];\n\t\ti = parent_index(i, heap->d);\n\t}\n\theap->items[i] = value;\n}\n\nvoid min_heapify(int n, HEAP *heap){\n\tint i, current, aux, smallest;\n\n\tsmallest = n;\n\tfor(i = 0; i < heap->d; i++){\n\t\tcurrent = child_index(n, heap->d, i);\n\t\tif(current <= heap->size  && heap->items[current] < heap->items[smallest]){\n\t\t\tsmallest = current;\n\t\t}\n\t}\n\tif(smallest != n){\n\t\taux = heap->items[n];\n\t\theap->items[n] = heap->items[smallest];\n\t\theap->items[smallest] = aux;\n\t\tmin_heapify(smallest, heap);\n\t}\n}\n\nint pop(HEAP *heap){\n\tint removed;\n\n\tif(heap->size == 0)\n\t\treturn -1;\n\telse{\n\t\tremoved = heap->items[0];\n\t\theap->items[0] = heap->items[heap->size -1];\n\t\theap->size--;\n\t\tmin_heapify(0, heap);\n\t\treturn removed;\n\t}\n}\n\nvoid short_print(HEAP *heap){\n\tint i;\n\n\tfor(i = 0; i < heap->size; i++){\n\t\tprintf(\"%d \", heap->items[i]);\n\t}\n}\n\nvoid print(HEAP *heap){\n\tint i, j;\n\n\tprintf(\"size = %d\\n\", heap->size);\n\tfor(i = 0; i < heap->size; i++){\n\t\tprintf(\"Index = %d Elemento = %d\\n\", i, heap->items[i]);\n\t\tprintf(\"Pai = %d\\n\", parent_index(i, heap->d));\n\t\tfor(j = 0; j < heap->d; j++){\n\t\t\tprintf(\"Filho %d = %d\\n\", j+1, child_index(i, heap->d, j));\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\tprintf(\"\\n\\n\");\n}\n\nvoid destroy(HEAP *heap){\n\tif(heap->items != NULL){\n\t\tfree(heap->items);\n\t}\n\tfree(heap);\n}\n"
  },
  {
    "path": "data_structures/dimaeter_of_a_tree/cpp/Diameter.cpp",
    "content": "//WAP to find diameter of a BST.\n#include<iostream>\n#include<malloc.h>\nusing namespace std;\nstruct tree{\n\tint data;\n\tstruct tree *left,*right;\n};\ntypedef struct tree node;\nnode *current=NULL,*root=NULL,*parent=NULL,*temp=NULL;\nvoid newnode(int n)\n{\n\tcurrent = (node*)malloc(sizeof(node));\n\tcurrent->data = n;\n\tcurrent->left = NULL;\n\tcurrent->right = NULL;\n\tif(root==NULL)\n\t{\n\t\troot=current;\n\t}\n\telse\n\t{\n\t\ttemp=root;\n\t\tparent=NULL;\n\t\twhile(1)\n\t\t{\tparent = temp;\n\t\t\tif(n<temp->data)\n\t\t\t{\n\t\t\t\ttemp = temp->left;\n\t\t\t\tif(temp==NULL)\n\t\t\t\t{\tparent->left= current;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\ttemp = temp->right;\n\t\t\t\tif(temp==NULL)\n\t\t\t\t{\tparent->right= current;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\t\n\t\t}\n\t}\n}\nint max(int a,int b)\n{\n\tif(a>b)\n\treturn a;\n\telse\n\treturn b;\n}\nint height(node* temp)\n{\n\tif(temp==NULL)\n\treturn 0;\n\treturn 1+max(height(temp->left),height(temp->right));}\nint diameter(node* temp)\n{\n\tint dia=0,maxDia;\n\tif(temp ==NULL)\n\treturn 0;\n\tint lheight,rheight,ldiameter,rdiameter;\n\tlheight = height(temp->left);\n\trheight = height(temp->right);\n\tdia = 1 + lheight + rheight;\n\tldiameter = diameter(temp->left);\n\trdiameter = diameter(temp->right);\n\tmaxDia = max(dia,max(ldiameter,rdiameter));\n\treturn maxDia;\n}\nint main()\n{\n\tint i,an;\n\tint x[]={41,27,83,45,65,80,40,55};\n\t/*\n\t\t   \t 41\n\t\t    / \\\n\t\t   27  83\n\t\t   \\  /\n\t\t   40 45\n\t\t      \\\n\t\t       65\n\t\t       / \\\n\t\t     55  80\n\t*/\n\tfor(i=0;i<=7;i++)\n\tnewnode(x[i]);\n\tan=diameter(root);\n\tcout<<\"\\nDiameter of tree:\"<<an;\n\treturn 0;\n}\n"
  },
  {
    "path": "data_structures/dimaeter_of_a_tree/diameter_of_a_tree.md",
    "content": "//Diameter of a tree\n## ELI5\nThe diameter of a tree is its width.The maximum possible number of items between any two end-most items in a tree.\n\n## Explaination\nThe diameter of a tree (sometimes called the width) is the number of nodes on the longest path between two leaves in the tree.\n\nThe diameter of a tree T is the largest of the following quantities:\n\n* the diameter of T’s left subtree\n* the diameter of T’s right subtree\n* the longest path between leaves that goes through the root of T (this can be computed from the heights of the subtrees of T)\n"
  },
  {
    "path": "data_structures/dimaeter_of_a_tree/java/Diameter.java",
    "content": "import java.lang.Math;\n\n\nclass Diameter{\n\tNode root;\n\n\tpublic Diameter(Node root){\n\t\tthis.root = root;\n\t}\n\n   public static int c_diameter(Node node){\n\n   \tif(node == null)return 0;\n\n\n    //heights of left & right subtrees\n   \tint c_left_height = c_height(node.left);\n   \tint c_right_height = c_height(node.right);\n\n   \t//diameters of left an right subtrees\n   \tint c_left_diameter = c_diameter(node.left);\n   \tint c_right_diameter = c_diameter(node.right);\n\n    //return \n    return  Math.max(c_left_height+c_right_height+1,Math.max(c_left_diameter,c_right_diameter));\n\n   }\n\n\n   public static int c_height(Node node){\n   \tif(node == null) return 0;\n\n\n   \treturn 1 + Math.max(c_height(node.left),c_height(node.right));\n   }\n\n\n\n\n\n\tpublic static void main(String[] args){\n\t\tNode root = new Node(1);\n\t\troot.left = new Node(2);\n\t\troot.right = new Node(3);\n\t\troot.left.left = new Node(4);\n\t\troot.left.right = new Node(5);\n\t\troot.left.left.left = new Node(6);\n\n\t\tDiameter diameter = new Diameter(root);\n\n\t\tSystem.out.println(c_diameter(root));\n\n\t}\n}"
  },
  {
    "path": "data_structures/double_linked_list/cpp/doublelinkedlist.cpp",
    "content": "#include<iostream>\nusing namespace std;\n\nvoid FindLocation(int);\nstruct student{\n  int data;\n  student* next;\n  student* prev;\n} *loc,*head,*tail,*ptr;\n\nvoid insertion_begin(int y){\n  student* temp=new student();\n  \n if(head==NULL){\n  temp->next=NULL;\n temp->prev=NULL;\n  head=temp;\n  tail=temp;\n  temp->data=y;\n}\n else{\n  temp->next=head;\n  temp->prev=NULL; \n  head->prev=temp;\n  head=temp;\n  temp->data=y;\n  }\n\n}\nvoid insertion_end(int y){\n student* temp=new student();\n\n if(head==NULL){\n  temp->next=head;\n  temp->prev=head;\n   head=temp;\n   tail=temp;\n  temp->data=y;\n}\n else{\n  temp->next=NULL;\n  temp->prev=tail;\n  tail->next=temp;\n  tail=temp;\n temp->data=y;\n}\n}\nvoid insertion_after(int y1){\n\n        student* temp=new student();\n         int k3;\n    cout<<\"enter the element after which data to be inserted \";\n    cin>>k3;\n        FindLocation(k3);\n\t  if(loc==NULL)\n               insertion_end(y1);\n           else{\n\t\ttemp->next=loc->next;\n\t\ttemp->prev=loc;\n\t\tloc->next->prev=temp;\n\t\tloc->next=temp;\n                temp->data=y1;\n   }\n}\nvoid insertion_before(int y2){\n         student* temp=new student();\n        int k1;\n    cout<<\"enter the element before which data to be inserted \";\n    cin>>k1;\n        FindLocation(k1);\n          if(loc==NULL)\n               insertion_begin(y2);\n\t  else{\n\t\ttemp->next=loc;\n\t\ttemp->prev=loc->prev;\n\t\tloc->prev->next=temp;\n\t\tloc->prev=temp;\n                 temp->data=y2;\n      }\n}\nvoid FindLocation(int k2){\n       student* p=head;\n\twhile(p!=NULL){\n\t\tif(p->data==k2){\n\t\t  loc=p;\n\t\t  return;\n       }\n\t\telse\n\t\t   p=p->next;\n           \n  }\n\n  loc=NULL;\n}\n       \n\nvoid display()\n{\n  student* q=head;\n  while(q!=NULL){\n  cout<<q->data<<\" \";\n  q=q->next;\n}\ncout<<endl<<endl;\n}\nint main()\n{\n        head=NULL;\n\ttail=NULL;\n        int i,n,x,k,m,a;\n         cout<<endl<<\"Enter the number of elements: \";\n        cin>>n;\n         while(1){\n        cout<<\"select from the following: \"<<endl;\n        cout<<\"1.insertion at the beginning \"<<endl;\n        cout<<\"2.insertion at the end\"<<endl;\n        cout<<\"3. insertion after a given element\"<<endl;\n        cout<<\"4.insertion before a given location\"<<endl;\n        cout<<\"5.display the given list\"<<endl;\n        cout<<\"6.exit\"<<endl;\n\t cin>>k;\n        switch(k)\n        {\n          case 1: cout<<\"enter the number:\";\n           for(i=0;i<n;i++){\n            cin>>x;\n            insertion_begin(x);\n      }\n           break;\n          case 2: cout<<\"enter the number:\";\n           for(i=0;i<n;i++){\n            cin>>x;\n            insertion_end(x);\n        }\n           break;\n          case 3: cout<<\"enter the element to be inserted: \";\n                  cin>>m;\n                   insertion_after(m);\n          break;\n          case 4: cout<<\"enter the element to be inserted: \";\n                  cin>>a;\n\t\t  insertion_before(a);\n          break;\n          case 5: display();\n          break;\n        case 6: return(0);\n           default: cout<<\"incorrect choice\"<<endl;\n\n        }\n        }\n    return(0);\n}                   \n                                                            \n\n"
  },
  {
    "path": "data_structures/doubly_linked_list/java/DoublyLinkedList.java",
    "content": "import java.util.Scanner;\n\n//Create a node class for creating new nodes in linked list\nclass Node{\n\t\n\tprivate int data ; // data of that node\n\tprivate Node next ; // node data of next linked node\n\tprivate Node prev ; // node data of previous linked node\n\t \n\tpublic Node() {  // initialize new node\n\t\tdata = 0 ;\n\t\tnext = null ;\n\t\tprev = null ;\n\t}\n\t\n\t// Input data in new node\n\tpublic Node(int d) {\n\t\tdata = d ;\n\t\tnext = null;\n\t\tprev = null;\n\t}\n\t\n\t// set link to the next node\n\tpublic void setNextLink(Node link) {\n\t\tnext = link ;\n\t}\n\t\n\t// set link to the previous node\n\tpublic void setPrevLink(Node link) {\n\t\tprev = link ;\n\t}\n\t\n\t// Get link of the next node\n\tpublic Node getNextLink() {\n\t\treturn next ;\n\t}\n\t\n\t// Get link of the previous node\n\tpublic Node getPrevLink() {\n\t\treturn prev ;\n\t}\n\t\n\t// Get data of the current node\n\tpublic int getData() {\n\t\treturn data ;\n\t}\n\t\n}\n\n\t//class for creating linked list\n\tclass LinkList{\n\t\n\t\tprivate Node start ;\n\t\tprivate Node end ;\n\t\tpublic int size ;\n\t\t\n\t\t// Initialize all the variables\n\t\tpublic LinkList() {\n\t\t\tstart = null ;\n\t\t\tend = null ;\n\t\t\tsize = 0 ;\n\t\t}\n\t\t\n\t\t// Adding nodes at starting of the linked list\n\t\tpublic void addAtStart(int data) {\n\t\t\t\n\t\t\tNode node = new Node(data); // Create object of Node class\n\t\t\tsize++ ; // Increment size of linked list\n\t\t\t\n\t\t\tif(start == null) {\n\t\t\t\tstart = node ; // make start the current node\n\t\t\t\tstart.setNextLink(null);\n\t\t\t\tstart.setPrevLink(null);\n\t\t\t\tend = start ; // make node the ending node\n\t\t\t}else {\n\t\t\t\t\n\t\t\t\tstart.setPrevLink(node); // Attach new node before start\n\t\t\t\tnode.setNextLink(start); // Set start to the next of the node\n\t\t\t\tnode.setPrevLink(null);\n\t\t\t\tstart = node ; // make the new node as start\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\tpublic void addAtEnd(int data) {\n\t\t\t\n\t\t\tNode node = new Node(data);\n\t\t\tsize++ ;\n\t\t\t\n\t\t\tif(start == null) {\n\t\t\t\tstart = node ;\n\t\t\t\tstart.setNextLink(null);\n\t\t\t\tstart.setPrevLink(null);\n\t\t\t\tend = start ;\n\t\t\t}else {\n\t\t\t\t\n\t\t\t\tend.setNextLink(node); // Attach new node after end\n\t\t\t\tnode.setPrevLink(null);\n\t\t\t\tnode.setPrevLink(end); // Set end to the previous of the node\n\t\t\t\tend = node ; // make the new node as end\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\t// Adding node at the middle of the linked list\n\t\tpublic void addAtMiddle(int data , int pos) {\n\t\t\tNode node = new Node(data);\n\t\t\tsize++ ;\n\t\t\t\n\t\t\tNode preptr = start ;\n\t\t\tNode ptr = start ;\n\t\t\tptr = ptr.getNextLink();\n\t\t\tint count = 1 ;\n\t\t\twhile(count != pos) {\n\t\t\t\tpreptr = preptr.getNextLink();\n\t\t\t\tptr = ptr.getNextLink();\n\t\t\t\tcount++ ;\n\t\t\t}\n\t\t\tpreptr.setNextLink(node);\n\t\t\tnode.setPrevLink(preptr);\n\t\t\tnode.setNextLink(ptr);\n\t\t\tptr.setPrevLink(node);\n\t\t\t\n\t\t}\n\t\t\n\t\t// Adding node after a certain data of the linked list\n\t\tpublic void addAfterData(int data , int refData) {\n\t\t\tNode node = new Node(data);\n\t\t\tsize++ ;\n\t\t\t\n\t\t\t\n\t\t\tNode preptr = start ;\n\t\t\tNode ptr = start ;\n\t\t\tptr = ptr.getNextLink();\n\t\t\t\n\t\t\twhile(preptr.getData() != refData) {\n\t\t\t\tpreptr = preptr.getNextLink();\n\t\t\t\tptr = ptr.getNextLink();\n\t\t\t}\n\t\t\tpreptr.setNextLink(node);\n\t\t\tnode.setPrevLink(preptr);\n\t\t\tnode.setNextLink(ptr);\n\t\t\tptr.setPrevLink(node);\n\t\t\t\n\t\t}\n\t\t\n\t\t// Deleting node in linked list\n\t\tpublic void deleteNode(int refData) {\n\t\t\t\n\t\t\tNode preptr = start ;\n\t\t\tNode ptr = start ;\n\t\t\tptr = ptr.getNextLink();\n\t\t\t\n\t\t\twhile(ptr.getData() != refData) {\n\t\t\t\tpreptr = preptr.getNextLink();\n\t\t\t\tptr = ptr.getNextLink();\n\t\t\t}\n\t\t\t\n\t\t\tpreptr.setNextLink(ptr.getNextLink());\n\t\t\tptr.getNextLink().setPrevLink(preptr);\n\t\t\tptr = null ;\n\t\t\t\n\t\t\tsize-- ; // Reduce size of linked list\n\t\t\t\n\t\t}\n\t\t\n\t\t// Traversing data from left to right \n\t\tpublic void showDataFromLeft() {\n\t\t\t\n\t\t\tNode ptr = start ;\n\t\t\t\n\t\t\twhile(ptr.getNextLink()!=null) {\n\t\t\t\tSystem.out.print(ptr.getData() + \"-->\");\n\t\t\t\tptr = ptr.getNextLink();\n\t\t\t}\n\t\t\tSystem.out.print(ptr.getData());\n\t\t\t\n\t\t}\n\t\t\n\t\t// Traversing data from right to lest \n\t\tpublic void showDataFromRight() {\n\t\t\t\n\t\t\tNode ptr = end ;\n\t\t\t\n\t\t\twhile(ptr.getPrevLink()!=null) {\n\t\t\t\tSystem.out.print(ptr.getData() + \"-->\");\n\t\t\t\tptr = ptr.getPrevLink();\n\t\t\t}\n\t\t\tSystem.out.print(ptr.getData());\n\t\t\t\n\t\t}\n\t\n\t}\n\n\npublic class DoublyLinkedList {\n\t\n\tpublic static void main(String[] args) {\n\t\t\n\t\tScanner sc = new Scanner(System.in);\n\t\tint data = 0 ;\n\t\t\n\t\tLinkList ll = new LinkList();\n\t\t\n\t\tSystem.out.println(\"Choose : \\n1. Insert at Start \\n2. Insert At End \");\n\t\t\n\t\tswitch (sc.nextInt()) {\n\t\tcase 1:\n\t\t\t// Get data from user again and again and add them to linked list\n\t\t\tdo {\n\t\t\t\tSystem.out.print(\"Enter the data : \");\n\t\t\t\tdata = sc.nextInt();\n\t\t\t\t\n\t\t\t\tll.addAtStart(data);\n\t\t\t\t\n\t\t\t\tSystem.out.print(\"Do you want to add more (y/n) : \");\n\t\t\t\t\n\t\t\t}while(sc.next().equals(\"y\"));\n\t\t\t\n\t\t\tSystem.out.println(\"From left to right : \");\n\t\t\tll.showDataFromLeft(); // show data from left to right of linked list\n\t\t\tSystem.out.println(\"\\nFrom right to left : \");\n\t\t\tll.showDataFromRight(); // show data from right to left of linked list\n\t\t\t\n\t\t\tbreak;\n\t\t\t\n\t\tcase 2:\n\t\t\t\n\t\t\tdo {\n\t\t\t\tSystem.out.print(\"Enter the data : \");\n\t\t\t\tdata = sc.nextInt();\n\t\t\t\t\n\t\t\t\tll.addAtEnd(data);\n\t\t\t\t\n\t\t\t\tSystem.out.print(\"Do you want to add more (y/n) : \");\n\t\t\t\t\n\t\t\t}while(sc.next().equals(\"y\"));\n\t\t\t\n\t\t\tSystem.out.println(\"From left to right : \");\n\t\t\tll.showDataFromLeft();\n\t\t\tSystem.out.println(\"\\nFrom right to left : \");\n\t\t\tll.showDataFromRight();\n\t\t\t\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\tSystem.out.println(\"\\nChoose : \\n1. Insert At Middle \\n2. Insert After A Data \\n3. Delete A Node\");\n\t\t\n\t\tswitch (sc.nextInt()) {\n\t\tcase 1:\n\t\t\tSystem.out.print(\"Enter the data : \");\n\t\t\tdata = sc.nextInt();\n\t\t\tint pos = 0 ;\n\t\t\tif(ll.size%2 == 0) {\n\t\t\t\tpos = ll.size/2 ;\n\t\t\t}else {\n\t\t\t\tpos = (ll.size - 1)/2 ;\n\t\t\t}\n\t\t\t\n\t\t\tll.addAtMiddle(data , pos);\n\t\t\t// Calculating middle position\n\t\t\tSystem.out.println(\"From left to right : \");\n\t\t\tll.showDataFromLeft();\n\t\t\tSystem.out.println(\"\\nFrom right to left : \");\n\t\t\tll.showDataFromRight();\n\t\t\t\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tSystem.out.print(\"Enter the data : \");\n\t\t\tdata = sc.nextInt();\n\t\t\t\n\t\t\tSystem.out.print(\"Enter the data after which you want to add new data : \");\n\t\t\t\n\t\t\tll.addAfterData(data , sc.nextInt());\n\t\t\t\n\t\t\tSystem.out.println(\"From left to right : \");\n\t\t\tll.showDataFromLeft();\n\t\t\tSystem.out.println(\"\\nFrom right to left : \");\n\t\t\tll.showDataFromRight();\n\t\t\t\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tSystem.out.print(\"Enter the data to be deleted : \");\n\t\t\tdata = sc.nextInt();\n\t\t\t\n\t\t\tll.deleteNode(data); // Delete node\n\t\t\t\n\t\t\tSystem.out.println(\"From left to right : \");\n\t\t\tll.showDataFromLeft();\n\t\t\tSystem.out.println(\"\\nFrom right to left : \");\n\t\t\tll.showDataFromRight();\n\t\t\t\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\n\t\t\n\t}\n\n}\n"
  },
  {
    "path": "data_structures/doubly_linked_list/python/DoublyLinkedList.py",
    "content": "\nclass Li2st:\n\n    def __init__(self,data = None):\n        self.head = self.tail = node(data)\n        self.size = 0 if data == None else 1\n    def __str__(self):\n        p = self.head\n        while p.nexts != None:\n            print(p.data,end=' ')\n            p = p.nexts\n        print(p.data)\n        return ''\n    \n    def isEmpty(self):\n        return self.size == 0\n\n    def append(self,data):\n        p = node(data)\n        if self.head.data == None:\n            self.head = p\n            self.tail = self.head\n        self.tail.nexts = p\n        self.tail = p\n        self.size += 1\n    \n    def addHead(self,data):\n        p = node(data,self.head)\n        self.head = p\n        self.size +=1\n\n    def isIn(self,data):\n        t = self.head\n        while t.nexts != None:\n            if t.data == data:\n                return True\n            t = t.nexts\n        if t.data == data:\n            return True\n        return False\n\n    def before(self,data):\n        before = None\n        i = self.head\n        while i.nexts != None:\n            if i.data == data:\n                return before\n            before = i\n            i = i.nexts\n        if i.data == data:\n            return before\n        return None\n\n    # def remove(self,data):\n    #     if not self.isIn(data) or self.before(data) == None:\n    #         print('Failed to remove')\n    #         return\n    #     self.before(data).nexts = self.before(data).nexts.nexts\n    \n    def remove(self,index):\n        currentNode = self.get(index-1)\n        currentNode.nexts= self.get(index+1)\n    def removeTail(self):\n        t = self.before(self.tail.data)\n        t.nexts = None\n        self.tail = t\n\n    def removeHead(self):\n        self.head = self.head.nexts\n\n    def get(self,index):\n        if index > self.size:\n            raise IndexError\n        t = self.head\n        for i in range(index):\n            t = t.nexts\n        if t != None:\n            return t\n\n    def insert(self,node,index):\n        currentNode = self.get(index)\n        nextNode = currentNode.nexts\n        \n        currentNode.nexts = node\n        node.nexts = nextNode\n\n     "
  },
  {
    "path": "data_structures/generic_tree/java/gt.java",
    "content": "package practiceds;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.LinkedList;\r\nimport java.util.Queue;\r\nimport java.util.Scanner;\r\nimport java.util.Stack;\r\n\r\npublic class generictree {\r\n\tprivate class node {\r\n\t\tprivate int data;\r\n\t\tprivate ArrayList<node> children;\r\n\r\n\t\tpublic node(int data) {\r\n\t\t\tthis.data = data;\r\n\t\t\tthis.children = new ArrayList<>();\r\n\t\t}\r\n\t}\r\n\r\n\tprivate node root;\r\n\tprivate int size;\r\n\r\n\tpublic generictree() {\r\n\t\tScanner scn = new Scanner(System.in);\r\n\t\tthis.root = this.takeinput(scn, null, 0);\r\n\t}\r\n\r\n\tprivate node takeinput(Scanner scn, node parent, int ithchild) {\r\n\t\tif (parent == null) {\r\n\t\t\tSystem.out.println(\"Enter data for parent node \");\r\n\t\t} else {\r\n\t\t\tSystem.out.println(\"enter data for \" + ithchild + \"th child of \"+parent.data);\r\n\t\t}\r\n\t\tint childdata = scn.nextInt();\r\n\t\tnode child = new node(childdata);\r\n\t\tthis.size++;\r\n\t\tSystem.out.println(\"Enter the number of children for \" + childdata);\r\n\t\tint numgranchild = scn.nextInt();\r\n\t\tfor (int i = 0; i < numgranchild; i++) {\r\n\t\t\tnode grandchild = takeinput(scn, child, i + 1);\r\n\t\t\tchild.children.add(grandchild);\r\n\t\t}\r\n\t\treturn child;\r\n\t}\r\n\r\n\tpublic int size() {\r\n\t\treturn this.size;\r\n\t}\r\n\r\n\tpublic boolean isempty() {\r\n\t\treturn this.size == 0;\r\n\t}\r\n\r\n\tpublic void display() {\r\n\t\tSystem.out.println(this);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String toString() {\r\n\t\treturn this.toString(this.root);\r\n\t}\r\n\r\n\tprivate String toString(node node) {\r\n\t\tString retval = \"\";\r\n\t\tretval = retval + node.data + \" => \";\r\n\t\tfor (int i = 0; i < node.children.size(); i++) {\r\n\t\t\tretval = retval + node.children.get(i).data + \" , \";\r\n\t\t}\r\n\t\tretval = retval + \" end\\n\";\r\n\t\tfor (int i = 0; i < node.children.size(); i++) {\r\n\t\t\tretval = retval + this.toString(node.children.get(i));\r\n\r\n\t\t}\r\n\t\treturn retval;\r\n\t}\r\n\tpublic int max (){\r\n\t\treturn this.max (this.root);\r\n\t}\r\n\tprivate int max (node Node){\r\n\t\tint max=Node.data;\r\n\t\tfor (int i=0;i<Node.children.size();i++){\r\n\t\t\tint maxofchild=max(Node.children.get(i));\r\n\t\t\tif (maxofchild>max){\r\n\t\t\t\tmax = maxofchild;\r\n\t\t\t}\r\n\t\t}\r\n\treturn max;\r\n\t}\r\n\tpublic boolean find(int data){\r\n\t\treturn this.find(data,this.root);\r\n\t}\r\n\tprivate boolean find(int data,node Node){\r\n\t\tif (Node.data==data){\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\tfor (int i=0;i<Node.children.size();i++){\r\n\t\t\tboolean reschild = this.find (data,Node.children.get(i));\r\n\t\t\tif (reschild){\r\n\t\t\t\treturn reschild;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\tpublic int height(){\r\n\t\treturn this.height(this.root);\r\n\t}\r\n\tprivate int height(node node){\r\n\t\tint height=-1;\r\n\t\tfor (int i=0;i<node.children.size();i++){\r\n\t\t\tint childheight = this.height(node.children.get(i));\r\n\t\t\tif (childheight>height){\r\n\t\t\t\theight = childheight;\r\n\t\t\t}\r\n\t\t}\r\n\t\theight = height +1;\r\n\t\treturn height;\r\n\t}\r\n\t\r\n}\r\n"
  },
  {
    "path": "data_structures/graph/cpp/graph.cpp",
    "content": "//Graph C++\n#include<iostream>\n#include<vector>\nusing namespace std;\n\n//class for graph , easily customisable \nclass graph\n{\n\tint vertices;\n\tint edges;\n\tvector<int> *v;\n\n\tpublic:\n\t\t//constructors\n\t\tgraph()\n\t\t{\n\t\t\tvertices=0;\n\t\t\tedges=0;\n\t\t\tv=NULL;\n\t\t}\n\t\tgraph(int ver,int e)\n\t\t{\n\t\t\tvertices=ver;\n\t\t\tedges=e;\n\t\t\tv=new vector<int>[ver+2];\n\t\t}\n\n\t\t//0 for undirected\n\t\t//1 for directed\n\t\tvoid addedge(int a,int b,int dir)\n\t\t{\n\t\t\tif(a>vertices || a<0 || b>vertices || b<0)\n\t\t\t\treturn;\n\t\t\tv[a].push_back(b);\n\t\t\tif(dir==0)\n\t\t\t\tv[b].push_back(a);\n\t\t}\n\t\tvoid printedges()\n\t\t{\n\t\t\tvector<int>::iterator it;\n\t\t\tfor(int i=0;i<=vertices;i++)\n\t\t\t{\n\t\t\t\tfor(it=v[i].begin();it!=v[i].end();it++)\n\t\t\t\t{\n\t\t\t\t\tcout<<i<<\"----\"<<(*it)<<\"\\n\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n};\n\nint main()\n{\n\tgraph g(5,5);\n\tg.addedge(1,2,1);\n\tg.addedge(2,3,0);\n\tg.addedge(4,2,1);\n\tg.addedge(3,1,1);\n\tg.addedge(3,5,0);\n\tg.printedges();\n}\n"
  },
  {
    "path": "data_structures/graph/python/graph.py",
    "content": "class vertex:\n    def __init__(self,key):\n        self.id = key\n        self.connected_to = {}\n\n    def addNeighbor(self,neighbour,weight=0):\n        self.connected_to[neighbour] = weight\n\n    def __str__(self):\n        return str(self.id) + ' connected_to: ' + str([x.id for x in self.connected_to])\n\n    def getConnections(self):\n        return self.connected_to.keys()\n\n    def getId(self):\n        return self.id\n\n    def getWeight(self,nbr):\n        return self.connected_to[neighbour]\n\n\n\nclass Graph:\n    def __init__(self):\n        self.vert_list = {}\n        self.num_vertices = 0\n\n    def add_vertex(self,key):\n        self.num_vertices = self.num_vertices + 1\n        new_vertex = vertex(key)\n        self.vert_list[key] = new_vertex\n        return new_vertex\n\n    def get_vertex(self,n):\n        if n in self.vert_list:\n            return self.vert_list[n]\n        else:\n            return None\n\n    def __contains__(self,n):\n        return n in self.vert_list\n\n    def add_edge(self,f,t,cost=0):\n        if f not in self.vert_list:\n            nv = self.add_vertex(f)\n        if t not in self.vert_list:\n            nv = self.add_vertex(t)\n        self.vert_list[f].add_neighbor(self.vert_list[t], cost)\n\n    def get_vertices(self):\n        return self.vert_list.keys()\n\n    def __iter__(self):\n        return iter(self.vert_list.values())\n\n    def __del__(self):\n    \tpass\n"
  },
  {
    "path": "data_structures/hash_table/cpp/hashtable.h",
    "content": "/**\n  A simple hashtable in C++\n  Author: PryDt\n*/\n\n#ifndef HASHTABLE_H\n#define HASHTABLE_H\n\n#include <iostream>\n#include <list>\n#include <functional>\n#include <utility>\n\ntemplate <class Key, class T>\nclass HashTable  // AKA Symbol Table or HashMap or Dictionary\n{\n public:\n  // constructor\n  HashTable(size_t size = 13)\n  {\n    length = size;\n\n    table = new std::list<std::pair<Key, T>>[length];\n  }\n\n  // destructor\n  ~HashTable() { delete[] table; }\n\n  // insert val w/ specified key\n  void insert(Key key, T val)\n  {\n    size_t i = hash(key);\n\n    for (auto it = table[i].begin(); it != table[i].end(); ++it)\n    {\n      if (std::get<0>(*it) == key)\n      {\n        (*it) = std::make_pair(key, val);\n        return;\n      }\n    }\n    table[i].push_front(std::make_pair(key, val));\n    used++;\n  }\n\n  // delete key and value\n  void remove(Key key)\n  {\n    size_t i = hash(key);\n\n    if (!table[i].empty())\n      for (auto it = table[i].begin(); it != table[i].end(); ++it)\n      {\n        if (std::get<0>(*it) == key)\n        {\n          it = table[i].erase(it);\n          used--;\n        }\n      }\n  }\n\n  // search for a val w/ given key\n  T get(Key key)\n  {\n    size_t i = hash(key);\n\n    for (auto it = table[i].begin(); it != table[i].end(); ++it)\n    {\n      if (std::get<0>(*it) == key)\n      {\n        return std::get<1>(*it);\n      }\n    }\n    return nullptr;\n  }\n\n  void printTable()\n  {\n    std::cout << \"[\\n\";\n    for (size_t i = 0; i < length; i++)\n    {\n      if (!table[i].empty())\n      {\n        for (auto it = table[i].begin();\n            it != table[i].end(); ++it)\n        {\n          std::cout << '\\t' << std::get<0>(*it)\n            << \"\\t:\\t\" << std::get<1>(*it) << '\\n';\n        }\n      }\n    }\n    std::cout << \"]\\n\";\n  }\n\n  // returns true if hashtable is empty\n  inline bool isEmpty() { return used == 0; }\n\n  // returns true if hashtable\n  // contains specific key\n  bool contains(Key key) { return !(get(key) == nullptr); }\n\n  // returns size of hashtable\n  inline int size() { return used; }\n\n private:\n  std::hash<Key> prehash;\n\n  size_t length;\n  size_t used;\n\n  std::list<std::pair<Key, T>>* table;\n\n  size_t hash(Key key) { return (prehash(key) & 0x7fffffff) % length; }\n};\n\n#endif  // HASHTABLE_H\n"
  },
  {
    "path": "data_structures/hash_table/csharp/hash_table.cs",
    "content": "using System;\nusing System.Collections;  // namespace for hashtable\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n/*\n * The Hashtable class represents a collection of key-and-value pairs that are organized\n * based on the hash code of the key. It uses the key to access the elements in the collection.\n * */\nnamespace hashtables\n{\n    sealed class hTable // a class\n    {\n        static int key; // key of the hastable\n        public bool uniqueness { get; set; } // setting to check if allow uniqueness or not\n        Hashtable hashtable = new Hashtable();\n        internal void add(string value)\n        {\n            if(uniqueness)\n            {\n                if(hashtable.ContainsValue(value))\n                {\n                    Console.WriteLine(\"Entry exists\");\n                }\n                else\n                {\n                    hashtable.Add(++key,value);\n                }\n            }\n            else\n            {\n                hashtable.Add(++key, value);\n            }\n\n        }\n        internal void delete(int key)\n        {\n            if (hashtable.ContainsKey(key))\n            {\n                Console.WriteLine(\"Deleted value : \" + hashtable[key].ToString());\n                hashtable.Remove(key);\n            }\n            else\n            {\n                Console.WriteLine(\"Key not found\");\n            }\n        }\n        internal void show()\n        {\n            foreach(var key in hashtable.Keys)\n            {\n                Console.WriteLine(key.ToString() + \" : \" + hashtable[key]);\n            }\n        }\n\n    }\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            hTable obj = new hTable();\n\n            // i want uniqueness therefore making property true\n            obj.uniqueness = true;\n\n            // adding 3 values\n            Console.WriteLine(\"ADDING EXAMPLE\");\n            obj.add(\"terabyte\");\n            obj.add(\"sandysingh\");\n            obj.add(\"hacktoberfest\");\n\n            // adding terabyte again to see the exists message\n            Console.WriteLine(\"ADDING 'terabyte' AGAIN\");\n            obj.add(\"terabyte\");\n\n            // showing all original\n            Console.WriteLine(\"Original Table\");\n            obj.show();\n\n            // removing value at key = 2\n            Console.WriteLine(\"Deleting value\");\n            obj.delete(2);\n\n            // showing all new\n            Console.WriteLine(\"New Table\");\n            obj.show();\n\n\n            Console.ReadKey(); // in ordr to pause the program\n        }\n    }\n}\n"
  },
  {
    "path": "data_structures/hash_table/java/Hash_table.java",
    "content": "package lecture18;\n\npublic class HashTable<K, V> {\n\tprivate class HTPair {\n\t\tK key;\n\t\tV value;\n\n\t\tpublic HTPair(K key, V value) {\n\t\t\tthis.key = key;\n\t\t\tthis.value = value;\n\t\t}\n\n\t\tpublic boolean equals(Object other) {\n\t\t\tHTPair op = (HTPair) other;\n\t\t\treturn this.key.equals(op.key);\n\t\t}\n\n\t\tpublic String toString() {\n\t\t\treturn \"{\" + this.key + \"->\" + this.value + \"}\";\n\t\t}\n\t}\n\n\tprivate LinkedList<HTPair>[] bucketArray;\n\tprivate int size;\n\n\tpublic static final int DEFAULT_CAPACITY = 5;\n\n\tpublic HashTable() {\n\t\tthis(DEFAULT_CAPACITY);\n\t}\n\n\tpublic HashTable(int capacity) {\n\t\tthis.bucketArray = (LinkedList<HTPair>[]) new LinkedList[capacity];\n\t\tthis.size = 0;\n\t}\n\n\tpublic int size() {\n\t\treturn this.size;\n\t}\n\n\tprivate int HashFunction(K key) {\n\t\tint hc = key.hashCode();\n\t\thc = Math.abs(hc);\n\t\tint bi = hc % this.bucketArray.length;\n\t\treturn bi;\n\t}\n\n\tpublic void put(K key, V value) throws Exception {\n\t\tint bi = HashFunction(key);\n\t\tHTPair data = new HTPair(key, value);\n\t\tif (this.bucketArray[bi] == null) {\n\t\t\tLinkedList<HTPair> bucket = new LinkedList<>();\n\t\t\tbucket.addLast(data);\n\t\t\tthis.size++;\n\t\t\tthis.bucketArray[bi] = bucket;\n\t\t} else {\n\t\t\tint foundAt = this.bucketArray[bi].find(data);\n\t\t\tif (foundAt == -1) {\n\t\t\t\tthis.bucketArray[bi].addLast(data);\n\t\t\t\tthis.size++;\n\t\t\t} else {\n\t\t\t\tHTPair obj = this.bucketArray[bi].getAt(foundAt);\n\t\t\t\tobj.value = value;\n\t\t\t\tthis.size++;\n\t\t\t}\n\t\t}\n\t\tdouble lambda = (this.size) * 1.0;\n\t\tlambda = this.size / this.bucketArray.length;\n\t\tif (lambda > 0.75) {\n\t\t\trehash();\n\t\t}\n\t}\n\n\tpublic void display() {\n\t\tfor (LinkedList<HTPair> list : this.bucketArray) {\n\t\t\tif (list != null && !list.isEmpty()) {\n\t\t\t\tlist.display();\n\t\t\t} else {\n\t\t\t\tSystem.out.println(\"NULL\");\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic V get(K key) throws Exception {\n\t\tint index = this.HashFunction(key);\n\t\tLinkedList<HTPair> list = this.bucketArray[index];\n\t\tHTPair ptf = new HTPair(key, null);\n\t\tif (list == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\tint findAt = list.find(ptf);\n\t\t\tif (findAt == -1) {\n\t\t\t\treturn null;\n\t\t\t} else {\n\t\t\t\tHTPair pair = list.getAt(findAt);\n\t\t\t\treturn pair.value;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic V remove(K key) throws Exception {\n\t\tint index = this.HashFunction(key);\n\t\tLinkedList<HTPair> list = this.bucketArray[index];\n\t\tHTPair ptf = new HTPair(key, null);\n\t\tif (list == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\tint findAt = list.find(ptf);\n\t\t\tif (findAt == -1) {\n\t\t\t\treturn null;\n\t\t\t} else {\n\t\t\t\tHTPair pair = list.getAt(findAt);\n\t\t\t\tlist.removeAt(findAt);\n\t\t\t\tthis.size--;\n\t\t\t\treturn pair.value;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void rehash() throws Exception {\n\t\tLinkedList<HTPair>[] oba = this.bucketArray;\n\t\tthis.bucketArray = (LinkedList<HTPair>[]) new LinkedList[2 * oba.length];\n\t\tthis.size = 0;\n\t\tfor (LinkedList<HTPair> ob : oba) {\n\t\t\twhile (ob != null && !ob.isEmpty()) {\n\t\t\t\tHTPair pair = ob.removeFirst();\n\t\t\t\tthis.put(pair.key, pair.value);\n\t\t\t}\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "data_structures/hash_table/python/hashTable.py",
    "content": "class hashTable:\n    def __init__(self):\n        self.size = 13  # hash table with size of 13 to be consistent with cpp code\n        self.slots = [None] * self.size\n        self.data = [None] * self.size\n\n    def hashfunction(self, key, size): # remainder used to define slots\n        return key % size\n\n    def rehash(self, oldhash, size): # just a simple linear probing function for rehashing\n        return ( oldhash + 1 ) % size\n\n    def insert(self, key, data):\n        hash_val = self.hashfunction(key, len(self.slots))\n\n        if self.slots[hash_val] == None:\n            self.slots[hash_val] = key\n            self.data[hash_val] = data\n        else:\n            new_slot = self.rehash(hash_val,len(self.slots))\n            while self.slots[new_slot] != None and self.slots[new_slot] != key:\n                new_slot = self.rehash(new_slot,len(self.slots))\n\n            if self.slots[new_slot] == None:\n                self.slots[new_slot] = key\n                self.data[new_slot] = data\n\n    def get(self, key):\n        first_slot = self.hashfunction(key, len(self.slots))\n\n        data = None\n        stop = False\n        found = False\n        position = first_slot\n        while self.slots[position] != None and not found and not stop:\n            if self.slots[position] == key:\n                found = True\n                data = self.data[position]\n            else:\n                position=self.rehash(position,len(self.slots))\n                if position == first_slot:\n                    stop = True\n        return data\n\n    def __getitem__(self,key):\n        return self.get(key)\n\n    def __setitem__(self,key,data):\n        self.insert(key,data)\n\n        \n"
  },
  {
    "path": "data_structures/hashmap/java/hashmap.java",
    "content": "import java.util.*;\nclass hashmap {\n\n   public static void main(String args[]) {\n      // Create a hash map\n      HashMap hm = new HashMap();\n      \n      // Put elements to the map\n      hm.put(1, \"one\");\n      hm.put(2, \"two\");\n      hm.put(3,\"three\");\n      hm.put(1,\"ONE\");\n      hm.put(4,\"four\");\n      //storing values in key-value pairs with unorder of keys, by eliminating duplicate keys\n      System.out.println(hm);//1-ONE,2-two,3-three,4-four\n   }\n}"
  },
  {
    "path": "data_structures/hashset/java/hashset.java",
    "content": "import java.util.*;\nclass hashset {\n\n   public static void main(String args[]) {\n      // Create a tree set\n      HashSet hs = new HashSet();\n     \n      // Add elements to the tree set\n      hs.add(3);\n      hs.add(2);\n      hs.add(3);\n      hs.add(2);\n      hs.add(1);\n      hs.add(4);\n      //HashSet is very helpful datastructure for avoid duplicatses and access elements in o(1) time completexity. In this datastructure order is not preserved.\n      System.out.println(hs);// output will be {2,3,1,4}\n   }\n}"
  },
  {
    "path": "data_structures/heap/cpp/MinHeap.h",
    "content": "#include <iostream>\n#include <vector>\nusing std::vector;\n\nclass MinHeap\n{\npublic:\n  MinHeap();\n  MinHeap(vector<int>);\n  void push(int);\n  int pop();\n  int size() { return heap.size(); }\n\nprivate:\n  int left(int);\n  int right(int);\n  int parent(int);\n  void siftUp(int);\n  void siftDown(int);\n  vector<int> heap;\n\n};\n\nMinHeap::MinHeap()\n{\n}\n\nMinHeap::MinHeap(vector<int> nums) {\n  heap = nums;\n  for (int i = nums.size() / 2 - 1; i >= 0; i--)\n    siftDown(i);\n}\n\n\nvoid MinHeap::push(int element)\n{\n  heap.push_back(element);\n  siftUp(heap.size() - 1);\n}\n\nint MinHeap::pop()\n{\n  int top = heap.front();\n  heap[0] = heap.at(heap.size() - 1);\n  heap.pop_back();\n  siftDown(0);\n  return top;\n}\n\n\nvoid MinHeap::siftUp(int index)\n{\n\n  while ((index > 0) && (parent(index) >= 0) &&\n         (heap[parent(index)] > heap[index]))\n  {\n    int tmp = heap[parent(index)];\n    heap[parent(index)] = heap[index];\n    heap[index] = tmp;\n    index = parent(index);\n  }\n}\n\nvoid MinHeap::siftDown(int index)\n{\n\n  int child = left(index);\n  if ((child > 0) && (right(index) > 0) &&\n      (heap[child] > heap[right(index)]))\n  {\n    child = right(index);\n  }\n  if (child > 0)\n  {\n    int tmp = heap[index];\n    heap[index] = heap[child];\n    heap[child] = tmp;\n    siftDown(child);\n  }\n}\n\nint MinHeap::left(int parent)\n{\n  int i = (parent * 2) + 1;\n  return (i < heap.size()) ? i : -1;\n}\n\nint MinHeap::right(int parent)\n{\n  int i = (parent * 2) + 2;\n  return (i < heap.size()) ? i : -1;\n}\n\nint MinHeap::parent(int child)\n{\n  if (child != 0)\n  {\n    int i = (child - 1) / 2;\n    return i;\n  }\n  return -1;\n}"
  },
  {
    "path": "data_structures/heap/java/Heap.java",
    "content": "package lecture19;\n\nimport java.util.ArrayList;\n\npublic class Heap<T extends Comparable<T>> {\n\tboolean isMin;\n\tArrayList<T> data;\n\t\n\tpublic Heap(){\n\t\tthis(false);\n\t}\n\t\n\tpublic Heap(boolean isMin){\n\t\tthis.isMin=isMin;\n\t\tthis.data=new ArrayList<>();\n\t}\n\t\n\tpublic Heap(T[] arr,boolean isMin){\n\t\tthis(isMin);\n\t\tfor(T value:arr){\n\t\t\tthis.data.add(value);\n\t\t}\n\t\t\n\t\tfor(int i=this.data.size()/2-1;i>=0;i--){\n\t\t\tthis.downheapify(i);\n\t\t}\n\t}\n\t\n\tpublic int size(){\n\t\treturn this.data.size();\n\t}\n\t\n\tpublic T getHP(){\n\t\treturn this.data.get(0);\n\t}\n\t\n\tpublic void add(T item){\n\t\tthis.data.add(item);\n\t\tthis.upheapify(this.size()-1);\n\t}\n\t\n\tprivate void upheapify(int ci){\n\t\tif(ci==0){\n\t\t\treturn;\n\t\t}\n\t\tint pi=(ci-1)/2;\n\t\tif(this.isLarger(pi,ci)==true){\n\t\t\treturn;\n\t\t}else{\n\t\t\tthis.swap(pi,ci);\n\t\t\tthis.upheapify(pi);\n\t\t}\n\t}\n\t\n\tprivate void swap(int i,int j){\n\t\tT temp=this.data.get(i);\n\t\tthis.data.set(i,this.data.get(j));\n\t\tthis.data.set(j, temp);\n\t}\n\t\n\tprivate boolean isLarger(int i,int j){\n\t\tT ithitem=this.data.get(i);\n\t\tT jthitem=this.data.get(j);\n\t\tif(isMin==true){\n\t\t\treturn ithitem.compareTo(jthitem)<0;\n\t\t}else{\n\t\t\treturn ithitem.compareTo(jthitem)>0;\n\t\t}\n\t}\n\t\n\tpublic T remove(){\n\t\tT rv=this.data.get(0);\n\t\tthis.swap(0, this.data.size()-1);\n\t\tthis.data.remove(this.size()-1);\n\t\tthis.downheapify(0);\n\t\treturn rv;\n\t}\n\t\n\tprivate void downheapify(int pi){\n\t\tint lci=(2*pi)+1;\n\t\tint rci=(2*pi)+2;\n\t\tint mi=pi;\n\t\tif(lci<this.data.size()&&isLarger(lci,mi)){\n\t\t\tmi=lci;\n\t\t}\n\t\tif(rci<this.data.size()&&isLarger(rci,mi)){\n\t\t\tmi=rci;\n\t\t}\n\t\tif(!(pi==mi)){\n\t\t\tthis.swap(mi, pi);\n\t\t\tthis.downheapify(mi);\n\t\t}\n\t}\n\t\n\tpublic void display(){\n\t\tthis.display(0);\n\t}\n\t\n\tprivate void display(int index){\n\t\tint lci=2*index+1;\n\t\tint rci=2*index+2;\n\t\t\n\t\tString str=\"\";\n\t\tT node=this.data.get(index);\n\t\tif(lci<this.data.size()){\n\t\t\tT lc=this.data.get(lci);\n\t\t\tstr=str+lc+\"=>\";\n\t\t}else{\n\t\t\tstr=str+\"END=>\";\n\t\t}\n\t\tstr=str+node;\n\t\tif(rci<this.data.size()){\n\t\t\tT rc=this.data.get(rci);\n\t\t\tstr=str+\"<=\"+rc;\n\t\t}else{\n\t\t\tstr=str+\"<=END\";\n\t\t}\n\t\tSystem.out.println(str);\n\t\tif(lci<this.data.size()){\n\t\t\tthis.display(lci);\n\t\t}\n\t\tif(rci<this.data.size()){\n\t\t\tthis.display(rci);\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "data_structures/heap/java/heaps.java",
    "content": "package lecture22;\r\n\r\nimport java.util.ArrayList;\r\n\r\npublic class heaps<k extends Comparable<k>, v> {\r\n\tprivate class node implements Comparable<node> {\r\n\t\tk score;\r\n\t\tv value;\r\n\r\n\t\tnode(k score, v value) {\r\n\t\t\tthis.score = score;\r\n\t\t\tthis.value = value;\r\n\t\t}\r\n\r\n\t\tpublic String toString() {\r\n\t\t\treturn \"{\" + this.score + \":\" + this.value + \"}\";\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic int compareTo(heaps<k, v>.node o) {\r\n\t\t\tif (ismin) {\r\n\t\t\t\treturn -1 * this.score.compareTo(o.score);\r\n\t\t\t} else {\r\n\t\t\t\treturn this.score.compareTo(o.score);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tprivate ArrayList<node> nodes;\r\n\tprivate boolean ismin;\r\n\r\n\tpublic heaps() {\r\n\t\tthis(false);\r\n\t}\r\n\r\n\tpublic heaps(boolean ismin) {\r\n\t\tthis.ismin = ismin;\r\n\t\tthis.nodes = new ArrayList<>();\r\n\t}\r\n\r\n\tpublic int size() {\r\n\t\treturn this.nodes.size();\r\n\t}\r\n\r\n\tpublic boolean isempty() {\r\n\t\treturn this.nodes.size() == 0;\r\n\t}\r\n\r\n\tpublic void add(k score, v value) {\r\n\t\tnode ntba = new node(score, value);\r\n\t\tthis.nodes.add(ntba);\r\n\t\tthis.upheapify(this.nodes.size() - 1);\r\n\t}\r\n\r\n\tprivate void upheapify(int ci) {\r\n\t\tif (ci == 0)\r\n\t\t\treturn;\r\n\t\tint pi = (ci - 1) / 2;\r\n\t\tnode parent = this.nodes.get(pi);\r\n\t\tnode child = this.nodes.get(ci);\r\n\t\tif (parent.compareTo(child) < 0) {\r\n\t\t\tswap(pi, ci);\r\n\t\t\tupheapify(pi);\r\n\t\t}\r\n\r\n\t}\r\n\r\n\tpublic v removehp() {\r\n\t\tv rv = this.nodes.get(0).value;\r\n\t\tthis.swap(0, this.nodes.size() - 1);\r\n\t\tthis.nodes.remove(this.nodes.size() - 1);\r\n\t\tthis.downheapify(0);\r\n\t\treturn rv;\r\n\t}\r\n\r\n\tprivate void downheapify(int pi) {\r\n\t\tint lci = 2 * pi + 1;\r\n\t\tint rci = 2 * pi + 2;\r\n\t\tint maxi = pi;\r\n\r\n\t\tif (lci < this.nodes.size() && this.nodes.get(lci).compareTo(this.nodes.get(maxi)) > 0)\r\n\t\t\tmaxi = lci;\r\n\t\tif (rci < this.nodes.size() && this.nodes.get(rci).compareTo(this.nodes.get(maxi)) > 0)\r\n\t\t\tmaxi = rci;\r\n\t\tif (maxi != pi) {\r\n\t\t\tthis.swap(maxi, pi);\r\n\t\t\tthis.downheapify(maxi);\r\n\t\t}\r\n\t}\r\n\r\n\tpublic v gethp() {\r\n\t\treturn this.nodes.get(0).value;\r\n\t}\r\n\r\n\tpublic void display() {\r\n\t\tSystem.out.println(this);\r\n\t}\r\n\r\n\tpublic String toString() {\r\n\t\treturn this.nodes.toString();\r\n\t}\r\n\r\n\tpublic void displaytree() {\r\n\t\tString ts = this.treestring(0);\r\n\t\tSystem.out.println(ts);\r\n\t}\r\n\r\n\tprivate String treestring(int pi) {\r\n\t\tString rv = \"\";\r\n\t\tint lci = 2 * pi + 1;\r\n\t\tint rci = 2 * pi + 2;\r\n\t\tif (lci < this.nodes.size()) {\r\n\t\t\trv += this.nodes.get(lci) + \"=>\";\r\n\t\t} else {\r\n\t\t\trv += \"end =>\";\r\n\t\t}\r\n\t\trv += this.nodes.get(pi);\r\n\t\tif (rci < this.nodes.size()) {\r\n\t\t\trv += \"<=\" + this.nodes.get(rci);\r\n\t\t} else {\r\n\t\t\trv += \"<= end\";\r\n\t\t}\r\n\t\trv += \"\\n\";\r\n\t\tif (lci < this.nodes.size())\r\n\t\t\trv += treestring(lci);\r\n\t\tif (rci < this.nodes.size())\r\n\t\t\trv += treestring(rci);\r\n\t\treturn rv;\r\n\t}\r\n\r\n\tprivate void swap(int i, int j) {\r\n\t\tnode temp = this.nodes.get(i);\r\n\t\tthis.nodes.set(i, this.nodes.get(j));\r\n\t\tthis.nodes.set(j, temp);\r\n\t}\r\n\r\n}\r\n"
  },
  {
    "path": "data_structures/heap/python/minheap.py",
    "content": "import heapq\n\nclass Heap(object): \n    def __init__(self):\n        self._heap = []\n\n    def push(self, priority, item):\n        assert priority >= 0\n        heapq.heappush(self._heap, (priority, item))\n\n    def pop(self):\n        item = heapq.heappop(self._heap)[1] \n        return item\n\n    def __len__(self):\n        return len(self._heap)\n\n    def __iter__(self):\n        return self\n\n    def next(self):\n        try:\n            return self.pop()\n        except IndexError:\n            raise StopIteration"
  },
  {
    "path": "data_structures/heap/ruby/heap.rb",
    "content": "class Heap\n  def initialize\n      @store = Array.new\n  end\n\n  def push(data)\n    @store.push(data)\n    tear_up(size - 1)\n  end\n\n  def top\n    @store.first\n  end\n\n  def pop\n    data = top\n    if size > 1\n      @store[0] = @store.pop\n      tear_down(0)\n    else\n      @store.pop\n    end\n    return data\n  end\n\n  def size\n    @store.size\n  end\n\n  private\n\n  def tear_up(pos)\n    return if pos == 0\n    parent = (pos - 1) / 2\n\n    if @store[parent] < @store[pos]\n      @store[parent], @store[pos] = @store[pos], @store[parent]\n      tear_up(parent)\n    end\n  end\n\n  def tear_down(pos)\n    return if pos >= size\n    left = pos * 2 + 1\n    right = pos * 2 + 2\n\n    max_leaf = -1\n\n    if left >= size\n      max_leaf = -1\n    elsif right >= size\n      max_leaf = left\n    else\n      if @store[right] > @store[left]\n        max_leaf = right\n      else\n        max_leaf = left\n      end\n    end\n\n    if max_leaf != -1\n      @store[max_leaf], @store[pos] = @store[pos], @store[max_leaf]\n      tear_down(max_leaf)\n    end\n  end\nend\n\n# Usage\nH = Heap.new\nH.push(5)\nH.push(3)\nH.push(9)\nH.push(10)\nH.push(1)\nH.push(4)\n\n# 10\nputs H.top()\n\n# 10 9 5 4 3 1\nwhile H.size() > 0 do\n  puts H.pop()\nend"
  },
  {
    "path": "data_structures/heapify_insert_extract_min/cpp/max-heap_functions.cpp",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n    void heapify(int k,int arr[]);\n    void insert(int t,int arr[]);\n    int extract_max(int arr[]);\n\n    int n;\n    int size;\n    int flag;\n    int max;\n    int temp;\n    int temp1;\n    int xx;\n    int h;\n\n    int main()\n    {\n        int N;\n        int i,T;\n        int query;\n        int j;\n\n        scanf(\"%d\",&N);\n\n        int array[N];\n        int array1[N];\n\n        size=N;\n        int element;\n\n        for(i=0;i<N;i++)\n        {\n            scanf(\"%d\",&array[i]);\n        }\n\n        scanf(\"%d\",&T);\n \t\n\t// create a sorted heap\n\n        for(j=0;j<N;j++)\n        {\n            heapify(j,array);\n        }\n// for using various functions\n        for(i=0;i<T;i++)\n        {\n            scanf(\"%d\",&query);\n            switch(query)\n            {\n                // pirnt the max-heap \n                case 0:\n                    for(j=0;j<size;j++)\n                    {\n                        heapify(j,array);\n                    }\n                    for(j=0;j<size;j++)\n                    {\n                        printf(\"%d \",array[j]);\n                    }\n                    printf(\"\\n\");\n                    break;\n                // heapsort and then print the sorted array\n                case 1:\n                    xx=size;\n                    for(j=0;j<xx;j++)\n                    {\n                        array1[j]=array[j];\n                    }\n                    for(j=0;j<xx;j++)\n                    {\n                        extract_max(array1);\n                    }\n                    for(h=0;h<xx;h++)\n                    {\n                        printf(\"%d \",array1[h]);\n                    }\n                    printf(\"\\n\");\n                    size=xx;\n                    break;\n                // insert element into max-heap, then print the heap\n                case 2:\n                    scanf(\"%d\",&element);\n                    insert(element,array);\n                    for(h=0;h<size;h++)\n                    {\n                        printf(\"%d \",array[h]);\n                    }\n                    printf(\"\\n\");\n\n                    break;\n                // extract maximum element in the max heap and then print the max-heap\n                case 3:\n                    extract_max(array);\n                    for(j=0;j<size;j++)\n                    {\n                        printf(\"%d \",array[j]);\n                    }\n                    printf(\"\\n\");\n                    break;\n                // print maximum element of the max-heap\n                case 4:\n                    printf(\"%d\\n\",array[0]);\n                    break;\n\n            }\n        }\n\n\n\n        return 0;\n    }\n\n    void heapify(int k,int arr[])\n    {\n        n=size-1;\n        flag=1;\n        //printf(\"n: %d \\n\",n);\n        //printf(\"parent: %d\\n\",(int)floor((double)(n-1)/2.0));\n        while(k<=(int)floor((double)(n-1)/2.0) && flag==1)\n        {\n            max=k;\n            if(arr[k]<arr[2*k+1])\n            {\n                max=2*k+1;\n            }\n            if(2*k+2<=n && arr[max]<arr[2*k+2])\n            {\n                max=2*k+2;\n            }\n            if(max!=k)\n            {\n                temp1=arr[k];\n                arr[k]=arr[max];\n                arr[max]=temp1;\n                k=max;\n            }\n            else\n            {\n                flag=0;\n            }\n        }\n    }\n\n    void insert(int t,int arr[])\n    {\n        n=size;\n        //printf(\"t %d\",t);\n        arr[size]=t;\n        size+=1;\n        while(n>0 && arr[n]>arr[(int)floor((double)(n-1)/2.0)])\n        {\n            temp=arr[n];\n            arr[n]=arr[(int)floor((double)(n-1)/2.0)];\n            arr[(int)floor((double)(n-1)/2.0)]=temp;\n            n=(int)floor((double)(n-1)/2.0);\n        }\n    }\n\n    int extract_max(int arr[])\n    {\n        n=size-1;\n        temp=arr[0];\n        arr[0]=arr[n];\n        arr[n]=temp;\n        //printf(\"arr[0],arr[n]:- %d %d\\n\",arr[0],arr[n]);\n        size-=1;\n        //printf(\"%d\",size);\n        heapify(0,arr);\n        return temp;\n    }\n"
  },
  {
    "path": "data_structures/left_learning_red_black_tree/c/llrb_tree.c",
    "content": "#include <stdio.h>\n#include <stdbool.h>\n#include <stdlib.h>\n\n// Data structures\nstruct treenode\n{\n  int data;\n  bool is_red;\n  struct treenode *left;\n  struct treenode *right;\n};\n\n// Type definitions\ntypedef struct treenode TREENODE;\ntypedef TREENODE *TREE;\n\n// Function prototypes\nTREE make_tree(int data, TREE left, TREE right);\nint is_empty(TREE t);\nTREE left_subtree(TREE t);\nTREE right_subtree(TREE t);\nsize_t size(TREE t);\nsize_t height(TREE t);\nvoid preorder(TREE t);\nvoid inorder(TREE t);\nvoid postorder(TREE t);\nvoid print_leaf(TREE t);\nvoid insert_RB(TREE *t, int data);\nint search_RB(TREE t, int key);\n\nint main()\n{\n  TREE t;\n  int i;\n\n  t = NULL; // let's start with an empty tree\n\n  for (i = 1; i < 10; i++)\n    insert_RB(&t, i);\n\n  printf(\"Tree Size: %u / %u\\n\", size(t), height(t));\n\n  printf(\"Pre-order traversal: \");\n  preorder(t);\n  printf(\"\\n\");\n\n  printf(\"In-order traversal: \");\n  inorder(t);\n  printf(\"\\n\");\n\n  printf(\"Post-order traversal: \");\n  postorder(t);\n  printf(\"\\n\");\n\n  printf(\"Leaf Node: \");\n  print_leaf(t);\n  printf(\"\\n\");\n  // ***** END OF EXAMPLE ***** //\n\n  exit(EXIT_SUCCESS);\n}\n\nTREE make_tree(int data, TREE left, TREE right)\n{\n  TREE t;\n\n  t = (TREE) malloc(sizeof(TREENODE));\n  t->data = data;\n  t->left = left;\n  t->right = right;\n  t->is_red = true;\n\n  return t;\n}\n\nbool is_red(TREE t)\n{\n  if (t == NULL)\n    return false;\n  else\n    return t->is_red;\n}\n\nint is_empty(TREE t)\n{\n  return (t == NULL);\n}\n\nTREE left_subtree(TREE t)\n{\n  return t->left;\n}\n\nTREE right_subtree(TREE t)\n{\n  return t->right;\n}\n\nsize_t size(TREE t)\n{\n  // Basis: return 0 if tree is empty\n  if (is_empty(t))\n    return 0;\n\n  // Recursive: Count the root and accumulate size of left and right subtrees\n  else\n    return 1 + size(left_subtree(t)) + size(right_subtree(t));\n}\n\nsize_t max(size_t x, size_t y)\n{\n  if (x > y)  return x;\n  else return y;\n}\n\nsize_t height(TREE t)\n{\n  // Basis: return 0 if tree is empty\n  if (is_empty(t))\n    return 0;\n\n  // Recursive: +1 Current layer and find maximum height of both left and right\n  return 1 + max(height(left_subtree(t)), height(right_subtree(t)));\n}\n\nvoid preorder(TREE t)\n{\n  if (!is_empty(t))\n  {\n    printf(\"%d \", t->data);\n    preorder(left_subtree(t));\n    preorder(right_subtree(t));\n  }\n}\n\nvoid inorder(TREE t)\n{\n  if (!is_empty(t))\n  {\n    inorder(left_subtree(t));\n    printf(\"%d \", t->data);\n    inorder(right_subtree(t));\n  }\n}\n\nvoid postorder(TREE t)\n{\n  if (!is_empty(t))\n  {\n    postorder(left_subtree(t));\n    postorder(right_subtree(t));\n    printf(\"%d \", t->data);\n  }\n}\n\nvoid print_leaf(TREE t)\n{\n  if (!is_empty(t))\n  {\n    print_leaf(left_subtree(t));\n\n    // The leaf has no children\n    if ((left_subtree(t) == NULL) && (right_subtree(t) == NULL))\n      printf(\"%d \", t->data);\n\n    print_leaf(right_subtree(t));\n  }\n}\n\nvoid rotate_left(TREE *t)\n{\n  TREE old_root, new_root;\n\n  old_root = *t;\n  new_root = (*t)->right;\n\n  old_root->right = new_root->left;\n  new_root->left = old_root;\n  new_root->is_red = old_root->is_red;\n  old_root->is_red = true;\n\n  *t = new_root;\n}\n\nvoid rotate_right(TREE *t)\n{\n  TREE old_root, new_root;\n\n  old_root = *t;\n  new_root = (*t)->left;\n\n  old_root->left = new_root->right;\n  new_root->right = old_root;\n  new_root->is_red = old_root->is_red;\n  old_root->is_red = true;\n\n  *t = new_root;\n}\n\nvoid flip_color(TREE *t)\n{\n  (*t)->is_red = !(*t)->is_red;\n  (*t)->left->is_red = !(*t)->left->is_red;\n  (*t)->right->is_red = !(*t)->right->is_red;\n}\n\nvoid insert_RB(TREE *t, int data)\n{\n  if (is_empty(*t))\n    *t = make_tree(data, NULL, NULL);\n  else if ((*t)->data > data)\n    insert_RB(&((*t)->left), data);\n  else if ((*t)->data < data)\n    insert_RB(&((*t)->right), data);\n  else\n    ; // No duplicates !!\n\n  // Red node should be on left\n  if (is_red((*t)->right) && !is_red((*t)->left)) rotate_left(t);\n\n  // Consecutive red nodes must be rotated to be double red children and flipped\n  if (is_red((*t)->left) && is_red((*t)->left->left)) rotate_right(t);\n\n  // No double red children, flip color !!\n  if (is_red((*t)->left) && is_red((*t)->right)) flip_color(t);\n}\n\nint search_RB(TREE t, int key)\n{\n  // Basis 1: there is no data if tree is empty\n  if (is_empty(t))\n    return 0;\n\n  // Basis 2: if the root node is the key, we found it\n  else if (t->data == key)\n    return 1;\n\n  // Recursive 1: if the root is greather, the key should be on the left of BST\n  else if (t->data > key)\n    return search_RB(left_subtree(t), key);\n\n  // Recursive 2: the key should be on the right subtree otherwise\n  else\n    return search_RB(right_subtree(t), key);\n}\n"
  },
  {
    "path": "data_structures/left_learning_red_black_tree/java/left_leaning_red_black_tree.java",
    "content": "// Simplest Java Implementation of Left leaning Red Black Trees.\npublic class left_leaning_red_black_tree<Key extends Comparable<Key>, Value> {\n\tprivate static final boolean RED = true;\n\tprivate static final boolean BLACK = false;\n\tprivate Node root;\n\n\tprivate class Node {\n\t\tprivate Key key;\n\t\tprivate Value val;\n\t\tprivate Node left, right;\n\t\tprivate boolean color;\n\t\tNode(Key key, Value val) {\n\t\t    this.key = key;\n\t\t    this.val = val;\n\t\t    this.color = RED;\n\t\t}\n\t}\n\n\tpublic Value search(Key key) {\n\t\tNode x = root;\n\t\twhile (x != null) {\n\t\t\tint cmp = key.compareTo(x.key);\n\t\t\tif (cmp == 0) return x.val;\n\t\t\telse if (cmp < 0) x = x.left;\n\t\t\telse if (cmp > 0) x = x.right;\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic void insert(Key key, Value value) {\n\t    root = insert(root, key, value);\n\t    root.color = BLACK;\n\t}\n\n\tprivate Node insert(Node h, Key key, Value value) {\n\t\tif (h == null) return new Node(key, value);\n\t\tif (isRed(h.left) && isRed(h.right)) colorFlip(h);\n\t\tint cmp = key.compareTo(h.key);\n\t\tif (cmp == 0) h.val = value;\n\t\telse if (cmp < 0) h.left = insert(h.left, key, value);\n\t\telse h.right = insert(h.right, key, value);\n\t\tif (isRed(h.right) && !isRed(h.left)) h = rotateLeft(h);\n\t\tif (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h);\n\t\treturn h;\n\t}\n\n\tprivate boolean isRed(Node h) {\n\t\tif(h == null) return false;\n        return h.color;\n\t}\n\n\tvoid colorFlip(Node h) {\n\t\th.color = !h.color;\n\t\th.left.color = !h.left.color;\n\t\th.right.color = !h.right.color;\n\t}\n\n\tprivate Node rotateLeft(Node h) {\n\t\tNode x = h.right;\n\t\th.right = x.left;\n\t\tx.left = h;\n\t\tx.color = h.color;\n\t\th.color = RED;\n\t\treturn x;\n\t}\n\n\tprivate Node rotateRight(Node h) {\n\t\tNode x = h.left;\n\t\th.left= x.right;\n\t\tx.right= h;\n\t\tx.color = h.color;\n\t\th.color = RED;\n\t\treturn x;\n\t}\n\n    public void preorder() {\n        preorder(root);\n    }\n\n    private void preorder(Node root) {\n        if(root == null) return;\n        System.out.println(root.key);\n        preorder(root.left);\n        preorder(root.right);\n    }\n\n    public void inorder() {\n        inorder(root);\n    }\n\n    private void inorder(Node root) {\n        if(root == null) return;\n        inorder(root.left);\n        System.out.println(root.key);\n        inorder(root.right);\n    }\n\n    public void postorder() {\n        postorder(root);\n    }\n\n    private void postorder(Node root) {\n        if(root == null) return;\n        postorder(root.left);\n        postorder(root.right);\n        System.out.println(root.key);\n    }\n\n\tpublic static void main(String[] args) {\n\t\tleft_leaning_red_black_tree <Integer, Integer> l1 = new left_leaning_red_black_tree<>();\n\t\tl1.insert(1, 10);\n\t\tl1.insert(2, 20);\n\t\tl1.insert(4, 30);\n\t\tl1.insert(6, 75);\n\t\tl1.insert(12, 89);\n\t\tl1.insert(19, 134);\n\t\tl1.insert(38, 12);\n        l1.preorder();\n\t}\n}\n"
  },
  {
    "path": "data_structures/linked_list/c/linked_list.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n#include <malloc.h>\n\nstruct node\n{\n\tint info;\n\tstruct node *next;\n}*start=NULL;\n\nint main()\n{\n\tint n;\n\tchar ch;\n\tdo\n\t{\n\t\tprintf(\"enter choice\\n\");\n\t\tprintf(\"1.creation\\n2.insertion\\n3.deletion\\n4.search\\n5.display\\n\");\n\t    scanf(\"%d\",&n);\n\t\tswitch(n)\n\t\t{\n\t\t\tcase '1' : create();\n\t\t\t\tbreak;\n\t\t\tcase '2' : insert();\n\t\t\t\tbreak;\n\t\t\tcase '3' : delete();\n\t\t\t\tbreak;\n\t\t\tcase '4' : search();\n\t\t\t\tbreak;\n\t\t\tcase '5' : display();\n\t\t\t\tbreak;\n\t\t\tdefault:printf(\"wrong choice\\n\");\n\t\t\t\tbreak;\n\t\t}\n\t    printf(\"\\nwant to continue\\n\");\n        scanf(\"%s\",&ch);\n    }while(ch!='n');\n    return 0;\n}\n\nvoid create()\n{\n\tstruct node *temp,*new;\n\tchar ch;\n\tdo\n\t{\n\t\ttemp=(struct node *)malloc(sizeof(struct node));\n\t\tprintf(\"\\nenter data\\n\");\n\t\tscanf(\"%d\",&temp->info);\n\t\tif(start==NULL)\n\t\t{\n\t\t\tstart=temp;\n\t\t\ttemp->next=NULL;\n\t\t\tnew=temp;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tnew->next=temp;\n\t\t\ttemp->next=NULL;\n\t\t\tnew=temp;\n\t\t}\n\t\tprintf(\"want to enter more\\n\");\n\t\tch=getche();\n\t\tprintf(\"\\n\");\n\t}while(ch!='n');\n}\n\nvoid insert()\n{\n\tint n;\n\tstruct node *ptr,*temp;\n\tprintf(\"enter choice\\n\");\n\tprintf(\"1.insertion at beginning\\n2.insertion in the middle\\n3.insertion at end\\n\");\n\tscanf(\"%d\",&n);\n\tif(n==1)\n\t{\n\t\tprintf(\"enter the data to be inserted at the beginning\\n\");\n\t\ttemp=(struct node*)malloc(sizeof(struct node));\n\t\tscanf(\"%d\",&temp->info);\n\t\ttemp->next=start;\n\t\tstart=temp;\n\t}\n\telse if(n==2)\n\t{\n\t\tint i,pos;\n\t\tptr=start;\n\t\tprintf(\"insert data after the position\\n\");\n\t\tscanf(\"%d\",&pos);\n\t\tfor(i=0;i<pos-1;i++)\n\t\t\tptr=ptr->next;\n\t\ttemp=(struct node*)malloc(sizeof(struct node));\n\t\tprintf(\"enter data to be entered\\n\");\n\t\tscanf(\"%d\",&temp->info);\n\t\ttemp->next=ptr->next;\n\t\tptr->next=temp;\n\t}\n\telse if(n==3)\n\t{\n\t\tprintf(\"enter data to be inserted at the end\\n\");\n\t\tptr=start;\n\t\twhile(ptr->next!=NULL)\n\t\t\tptr=ptr->next;\n\t\ttemp=(struct node*)malloc(sizeof(struct node));\n\t\tscanf(\"%d\",&temp->info);\n\t\ttemp->next=NULL;\n\t\tptr->next=temp;\n\t}\n}\n\nvoid delete()\n{\n\tint n;\n\tstruct node *ptr,*temp;\n\tptr=start;\n\tprintf(\"enter choice\\n\");\n\tprintf(\"1.deletion at the beginning\\n2.deletion in the middle\\n3.deletion at the end\\n\");\n\tscanf(\"%d\",&n);\n\tif(n==1)\n\t{\n\t\tstart=ptr->next;\n\t\tfree(ptr);\n\t}\n\telse if(n==2)\n\t{\n\t\tint pos,i;\n\t\tprintf(\"enter the node number to be deleted\\n\");\n\t\tscanf(\"%d\",&pos);\n\t\tfor(i=0;i<pos-2;i++)\n\t\t\tptr=ptr->next;\n\t\ttemp=ptr->next;\n\t\tptr->next=temp->next;\n\t\tfree(temp);\n\t}\n\telse if(n==3)\n\t{\n\t\tint count=0,i;\n\t\twhile(ptr->next!=NULL)\n\t\t{\n\t\t\tptr=ptr->next;\n\t\t\tcount++;\n\t\t}\n\t\tptr=start;\n\t\tfor(i=0;i<count-1;i++)\n\t\t\tptr=ptr->next;\n\t\tptr->next=NULL;\n\t}\n}\n\nvoid search()\n{\n\tstruct node *ptr;\n\tptr=start;\n\tint data,f=0,count=0;\n\tprintf(\"enter data to be searched\\n\");\n\tscanf(\"%d\",&data);\n    while(ptr!=NULL)\n    {\n    \tif(ptr->info==data)\n    \t{\n    \t\tf=1;\n    \t\tbreak;\n    \t}\n    \telse\n    \t{\n    \t\tptr=ptr->next;\n    \t\tcount++;\n    \t}\n    }\n    if(f==1)\n    \tprintf(\"element %d found at node %d\",data,count+1);\n    else\n    \tprintf(\"element %d not found\",data);\n}\n\nvoid display()\n{\n\tint count=0,i;\n\tstruct node *ptr;\n\tprintf(\"List is\\n\");\n\tptr=start;\n\tif(ptr==NULL)\n\t\tprintf(\"List empty\\n\");\n\tdo\n\t{\n\t\tprintf(\"%d->\",ptr->info);\n\t\tptr=ptr->next;\n\t}while(ptr!=NULL);\n\tprintf(\"NULL\\n\");\n}\n"
  },
  {
    "path": "data_structures/linked_list/cpp/LinkedList.cpp",
    "content": "/*\n * C++ Program to Implement Singly 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}*start;\n\n/*\n * Class Declaration\n */\nclass single_llist\n{\n    public:\n        node* create_node(int);\n        void insert_begin();\n        void insert_pos();\n        void insert_last();\n        void delete_pos();\n        void sort();\n        void search();\n        void update();\n        void reverse();\n        void display();\n        single_llist()\n        {\n            start = NULL;\n        }\n};\n\n/*\n * Main :contains menu\n */\nmain()\n{\n    int choice, nodes, element, position, i;\n    single_llist sl;\n    start = NULL;\n    while (1)\n    {\n        cout<<endl<<\"---------------------------------\"<<endl;\n        cout<<endl<<\"Operations on singly linked list\"<<endl;\n        cout<<endl<<\"---------------------------------\"<<endl;\n        cout<<\"1.Insert Node at beginning\"<<endl;\n        cout<<\"2.Insert node at last\"<<endl;\n        cout<<\"3.Insert node at position\"<<endl;\n        cout<<\"4.Sort Link List\"<<endl;\n        cout<<\"5.Delete a Particular Node\"<<endl;\n        cout<<\"6.Update Node Value\"<<endl;\n        cout<<\"7.Search Element\"<<endl;\n        cout<<\"8.Display Linked List\"<<endl;\n        cout<<\"9.Reverse Linked List \"<<endl;\n        cout<<\"10.Exit \"<<endl;\n        cout<<\"Enter your choice : \";\n        cin>>choice;\n        switch(choice)\n        {\n        case 1:\n            cout<<\"Inserting Node at Beginning: \"<<endl;\n            sl.insert_begin();\n            cout<<endl;\n            break;\n        case 2:\n            cout<<\"Inserting Node at Last: \"<<endl;\n            sl.insert_last();\n            cout<<endl;\n            break;\n        case 3:\n            cout<<\"Inserting Node at a given position:\"<<endl;\n            sl.insert_pos();\n            cout<<endl;\n            break;\n        case 4:\n            cout<<\"Sort Link List: \"<<endl;\n            sl.sort();\n            cout<<endl;\n            break;\n        case 5:\n            cout<<\"Delete a particular node: \"<<endl;\n            sl.delete_pos();\n            break;\n        case 6:\n            cout<<\"Update Node Value:\"<<endl;\n            sl.update();\n            cout<<endl;\n            break;\n        case 7:\n            cout<<\"Search element in Link List: \"<<endl;\n            sl.search();\n            cout<<endl;\n            break;\n        case 8:\n            cout<<\"Display elements of link list\"<<endl;\n            sl.display();\n            cout<<endl;\n            break;\n        case 9:\n            cout<<\"Reverse elements of Link List\"<<endl;\n            sl.reverse();\n            cout<<endl;\n            break;\n        case 10:\n            cout<<\"Exiting...\"<<endl;\n            exit(1);\n            break;\n        default:\n            cout<<\"Wrong choice\"<<endl;\n        }\n    }\n}\n\n/*\n * Creating Node\n */\nnode *single_llist::create_node(int value)\n{\n    struct node *temp, *s;\n    temp = new(struct node);\n    if (temp == NULL)\n    {\n        cout<<\"Memory not allocated \"<<endl;\n        return 0;\n    }\n    else\n    {\n        temp->info = value;\n        temp->next = NULL;\n        return temp;\n    }\n}\n\n/*\n * Inserting element in beginning\n */\nvoid single_llist::insert_begin()\n{\n    int value;\n    cout<<\"Enter the value to be inserted: \";\n    cin>>value;\n    struct node *temp, *p;\n    temp = create_node(value);\n    if (start == NULL)\n    {\n        start = temp;\n        start->next = NULL;\n    }\n    else\n    {\n        p = start;\n        start = temp;\n        start->next = p;\n    }\n    cout<<\"Element Inserted at beginning\"<<endl;\n}\n\n/*\n * Inserting Node at last\n */\nvoid single_llist::insert_last()\n{\n    int value;\n    cout<<\"Enter the value to be inserted: \";\n    cin>>value;\n    struct node *temp, *s;\n    temp = create_node(value);\n    s = start;\n    while (s->next != NULL)\n    {\n        s = s->next;\n    }\n    temp->next = NULL;\n    s->next = temp;\n    cout<<\"Element Inserted at last\"<<endl;\n}\n\n/*\n * Insertion of node at a given position\n */\nvoid single_llist::insert_pos()\n{\n    int value, pos, counter = 0;\n    cout<<\"Enter the value to be inserted: \";\n    cin>>value;\n    struct node *temp, *s, *ptr;\n    temp = create_node(value);\n    cout<<\"Enter the postion at which node to be inserted: \";\n    cin>>pos;\n    int i;\n    s = start;\n    while (s != NULL)\n    {\n        s = s->next;\n        counter++;\n    }\n    if (pos == 1)\n    {\n        if (start == NULL)\n        {\n            start = temp;\n            start->next = NULL;\n        }\n        else\n        {\n            ptr = start;\n            start = temp;\n            start->next = ptr;\n        }\n    }\n    else if (pos > 1  && pos <= counter)\n    {\n        s = start;\n        for (i = 1; i < pos; i++)\n        {\n            ptr = s;\n            s = s->next;\n        }\n        ptr->next = temp;\n        temp->next = s;\n    }\n    else\n    {\n        cout<<\"Positon out of range\"<<endl;\n    }\n}\n\n/*\n * Sorting Link List\n */\nvoid single_llist::sort()\n{\n    struct node *ptr, *s;\n    int value;\n    if (start == NULL)\n    {\n        cout<<\"The List is empty\"<<endl;\n        return;\n    }\n    ptr = start;\n    while (ptr != NULL)\n    {\n        for (s = ptr->next;s !=NULL;s = s->next)\n        {\n            if (ptr->info > s->info)\n            {\n                value = ptr->info;\n                ptr->info = s->info;\n                s->info = value;\n            }\n        }\n        ptr = ptr->next;\n    }\n}\n\n/*\n * Delete element at a given position\n */\nvoid single_llist::delete_pos()\n{\n    int pos, i, counter = 0;\n    if (start == NULL)\n    {\n        cout<<\"List is empty\"<<endl;\n        return;\n    }\n    cout<<\"Enter the position of value to be deleted: \";\n    cin>>pos;\n    struct node *s, *ptr;\n    s = start;\n    if (pos == 1)\n    {\n        start = s->next;\n    }\n    else\n    {\n        while (s != NULL)\n        {\n            s = s->next;\n            counter++;\n        }\n        if (pos > 0 && pos <= counter)\n        {\n            s = start;\n            for (i = 1;i < pos;i++)\n            {\n                ptr = s;\n                s = s->next;\n            }\n            ptr->next = s->next;\n        }\n        else\n        {\n            cout<<\"Position out of range\"<<endl;\n        }\n        free(s);\n        cout<<\"Element Deleted\"<<endl;\n    }\n}\n\n/*\n * Update a given Node\n */\nvoid single_llist::update()\n{\n    int value, pos, i;\n    if (start == NULL)\n    {\n        cout<<\"List is empty\"<<endl;\n        return;\n    }\n    cout<<\"Enter the node postion to be updated: \";\n    cin>>pos;\n    cout<<\"Enter the new value: \";\n    cin>>value;\n    struct node *s, *ptr;\n    s = start;\n    if (pos == 1)\n    {\n        start->info = value;\n    }\n    else\n    {\n        for (i = 0;i < pos - 1;i++)\n        {\n            if (s == NULL)\n            {\n                cout<<\"There are less than \"<<pos<<\" elements\";\n                return;\n            }\n            s = s->next;\n        }\n        s->info = value;\n    }\n    cout<<\"Node Updated\"<<endl;\n}\n\n/*\n * Searching an element\n */\nvoid single_llist::search()\n{\n    int value, pos = 0;\n    bool flag = false;\n    if (start == NULL)\n    {\n        cout<<\"List is empty\"<<endl;\n        return;\n    }\n    cout<<\"Enter the value to be searched: \";\n    cin>>value;\n    struct node *s;\n    s = start;\n    while (s != NULL)\n    {\n        pos++;\n        if (s->info == value)\n        {\n            flag = true;\n            cout<<\"Element \"<<value<<\" is found at position \"<<pos<<endl;\n        }\n        s = s->next;\n    }\n    if (!flag)\n        cout<<\"Element \"<<value<<\" not found in the list\"<<endl;\n}\n\n/*\n * Reverse Link List\n */\nvoid single_llist::reverse()\n{\n    struct node *ptr1, *ptr2, *ptr3;\n    if (start == NULL)\n    {\n        cout<<\"List is empty\"<<endl;\n        return;\n    }\n    if (start->next == NULL)\n    {\n        return;\n    }\n    ptr1 = start;\n    ptr2 = ptr1->next;\n    ptr3 = ptr2->next;\n    ptr1->next = NULL;\n    ptr2->next = ptr1;\n    while (ptr3 != NULL)\n    {\n        ptr1 = ptr2;\n        ptr2 = ptr3;\n        ptr3 = ptr3->next;\n        ptr2->next = ptr1;\n    }\n    start = ptr2;\n}\n\n/*\n * Display Elements of a link list\n */\nvoid single_llist::display()\n{\n    struct node *temp;\n    if (start == NULL)\n    {\n        cout<<\"The List is Empty\"<<endl;\n        return;\n    }\n    temp = start;\n    cout<<\"Elements of list are: \"<<endl;\n    while (temp != NULL)\n    {\n        cout<<temp->info<<\"->\";\n        temp = temp->next;\n    }\n    cout<<\"NULL\"<<endl;\n}\n"
  },
  {
    "path": "data_structures/linked_list/cpp/singly_linked_list.cpp",
    "content": "#include <iostream>\nnamespace std{\n\n\tclass Node{\n\tprivate:\n\t\tint _data;\n\t\tNode *_next;\n\n\tpublic:\n\t\tNode(){}\n\t\t// setters\n\t\tvoid setData(int Data){ _data = Data;}\n\t\tvoid setNext(Node *Next){ \n\t\t\tif(Next == NULL){\n\t\t\t\t_next = NULL;\n\t\t\t}else{\n\t\t\t_next = Next;\n\t\t\t}\n\t\t}\n\t\tint Data(){return _data;}\n\t\tNode *Next(){return _next;}\n\t};\n\n\tclass LinkedList{\n\tprivate:\n\t\tNode *head;\n\tpublic:\n\t\tLinkedList(){ head = NULL;}\n\t\tvoid insert_Back(int data);\n\t\tvoid insert_front(int data);\n\t\tbool isEmpty();\n\t\tvoid init_list(int data);\n\t\tvoid print_List();\n\t\tint size();\n\t};\n\n\tvoid LinkedList::print_List(){\n\t\tNode *tmp = head;\n\n\t\t//Checking the list if there is a node or not.\n\t\tif(tmp == NULL){\n\t\t\tcout << \"List is empty\\n\";\n\t\t\treturn;\n\t\t}\n\n\t\t//Checking only one node situation.\n\t\tif(tmp->Next() == NULL){\n\t\t\tcout << \"Starting: \" <<tmp->Data()\n\t\t\t\t <<\"Next Value > NULL\\n\";\n\t\t}else{\n\t\t\twhile(tmp!=NULL){\n\t\t\t\tcout << tmp->Data() << \" > \";\n\t\t\t\t//incrementing the pointer;\n\t\t\t\ttmp = tmp->Next();\n\t\t\t}\n\t\t}\n\t}\n\n\t/*inserting a value infront of the */\n\tvoid LinkedList::insert_Back(int data){\n\t\t//Creating a node\n\t\tNode *newNode = new Node();\n\t\tnewNode->setData(data);\n\t\tnewNode->setNext(NULL);\n\n\t\t//Creating a temporary pointer.\n\t\tNode *tmp = head;\n\n\t\tif (tmp != NULL){\n\t\t\twhile(tmp->Next() != NULL){\n\t\t\t\ttmp = tmp->Next();\n\t\t\t}\n\t\t\ttmp->setNext(newNode);\n\t\t}else{\n\t\t\thead = newNode;\n\t\t}\n\t}\n\t/*Inserting a value in front of the head node.*/\n\tvoid LinkedList::insert_front(int data){\n\t\t// creating a new node.\n\t\t Node *newNode = new Node();\n\t\t newNode->setData(data);\n\t\t newNode->setNext(NULL);\n\n\t\t newNode->setNext(head);\n\t\t head = newNode;\n\t}\n\t/*Initializing the list with a value.*/\n\tvoid LinkedList::init_list(int data){\n\t\t//creating a node\n\t\tNode *newNode = new Node();\n\t\tnewNode->setData(data);\n\t\tnewNode->setNext(NULL);\n\t\tif(head != NULL){\n\t\t\thead = NULL;\n\t\t}\n\t\thead = newNode;\n\t}\n\t/*It returns to Linked Lists size.*/\n\tint LinkedList::size(){\n\t\t//counter variable\n\t\tint ctr = 0;\n\t\tNode *tmp = head;\n\t\t\n\t\twhile(tmp!=NULL){\n\t\t\tctr++;\n\t\t\ttmp = tmp->Next();\n\t\t}\n\t\treturn ctr;\n\t}\n\n\tbool LinkedList::isEmpty(){ return (head == NULL) ? true:false;\t}\n}\n\nint main(){\n\t//Creating a list\n\tstd::LinkedList list;\n\n\t//Initilizing it with 5\n\tlist.init_list(5);\n\tlist.insert_Back(6);\n\tlist.insert_front(4);\n\tlist.print_List();\n}\n"
  },
  {
    "path": "data_structures/linked_list/csharp/LinkedList.cs",
    "content": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace DataStructures\n{\n    /*\n     * Implementing methods from https://www.cs.cmu.edu/~adamchik/15-121/lectures/Linked%20Lists/linked%20lists.html\n     */\n\n    class LinkedList\n    {\n\n        LinkedListNode head = null;\n\n\n        public class LinkedListNode\n        {\n            object data;\n            LinkedListNode next = null;\n\n            public LinkedListNode(object newitem)\n            {\n                data = newitem;\n            }\n\n            public LinkedListNode(object newitem, LinkedListNode next)\n            {\n                data = newitem;\n                this.next = next;\n            }\n\n            public object getData()\n            {\n                return data;\n            }\n\n            public LinkedListNode getNextNode()\n            {\n                return next;\n            }\n\n            public void setNextNode(LinkedListNode next)\n            {\n                this.next = next;\n            }\n\n        }\n\n\n        public LinkedList(object data)\n        {\n            head = new LinkedListNode(data);\n        }\n\n\n        public void addFirst(object data)\n        {\n            head = new LinkedListNode(data, head);\n        }\n\n\n        public void addLast(object data)\n        {\n            if (head == null)\n            {\n                addFirst(data);\n            }\n            else\n            {\n                LinkedListNode temp = head;\n                while (temp.getNextNode() != null)\n                {\n                    temp = temp.getNextNode();\n                }\n                temp.setNextNode(new LinkedListNode(data));\n            }\n        }\n\n\n        public void insertAfter(object data, object newData)\n        {\n            LinkedListNode temp = head;\n            while ((temp != null) && (temp.getData() != data))\n            {\n                temp = temp.getNextNode();\n            }\n\n            if (temp != null)\n            { \n                temp.setNextNode(new LinkedListNode(newData, temp));\n            }\n        }\n\n\n        public void insertBefore(object data, object newData)\n        {\n            if (head == null)\n            {\n                return;\n            }\n            if (head.getData() == data)\n            {\n                addFirst(newData);\n                return;\n            }\n\n            LinkedListNode prev = null;\n            LinkedListNode curr = head;\n\n            while ((curr != null) && (curr.getData() != data))\n            {\n                prev = curr;\n                curr = curr.getNextNode();\n            }\n\n            if (curr != null)\n            {\n                prev.setNextNode(new LinkedListNode(newData, curr));\n            }\n        }\n\n\n        public void remove(object data)\n        {\n            if (head == null)\n            {\n                throw new Exception(\"List is empty, cannot delete.\");\n            }\n\n            if (head.getData() == data)\n            {\n                head = head.getNextNode();\n                return;\n            }\n\n            LinkedListNode prev = null;\n            LinkedListNode curr = head;\n\n            while ((curr != null) && (curr.getData() != data))\n            {\n                prev = curr;\n                curr = curr.getNextNode();\n            }\n\n            if (curr == null)\n            {\n                throw new Exception(\"Cannot delete.\");\n            }\n\n            prev.setNextNode(curr.getNextNode());\n        }\n\n\n    }\n}\n"
  },
  {
    "path": "data_structures/linked_list/go/linked_list.go",
    "content": "package main\n\nimport \"fmt\"\n\ntype Node struct {\n\tValue interface{}\n\tnext  *Node\n}\n\nfunc (n *Node) Next() *Node {\n\treturn n.next\n}\n\ntype LinkedList struct {\n\tfirst *Node\n\tlast  *Node\n}\n\nfunc (l *LinkedList) Add(v interface{}) {\n\tn := new(Node)\n\tn.Value = v\n\tif l.first == nil {\n\t\tl.first = n\n\t\tl.last = n\n\t} else {\n\t\tl.last.next = n\n\t\tl.last = n\n\t}\n}\n\nfunc (l *LinkedList) First() *Node {\n\treturn l.first\n}\n\nfunc (l *LinkedList) ToString() string {\n\tstr := \"\"\n\tif l.first != nil {\n\t\tn := l.first\n\t\tstr += n.Value.(string)\n\t\tfor n.next != nil {\n\t\t\tstr += \",\" + n.next.Value.(string)\n\t\t\tn = n.next\n\t\t}\n\t}\n\treturn str\n}\n\nfunc main() {\n\tlist := new(LinkedList)\n\tlist.Add(\"a\")\n\tlist.Add(\"b\")\n\tlist.Add(\"c\")\n\n\tfmt.Printf(list.ToString() + \"\\n\")\n}\n"
  },
  {
    "path": "data_structures/linked_list/java/LinkedList.java",
    "content": "*\n *  Java Program to Implement Singly Linked List\n */\n \nimport java.util.Scanner;\n \n/*  Class Node  */\nclass Node\n{\n    protected int data;\n    protected Node link;\n \n    /*  Constructor  */\n    public Node()\n    {\n        link = null;\n        data = 0;\n    }    \n    /*  Constructor  */\n    public Node(int d,Node n)\n    {\n        data = d;\n        link = n;\n    }    \n    /*  Function to set link to next Node  */\n    public void setLink(Node n)\n    {\n        link = n;\n    }    \n    /*  Function to set data to current Node  */\n    public void setData(int d)\n    {\n        data = d;\n    }    \n    /*  Function to get link to next node  */\n    public Node getLink()\n    {\n        return link;\n    }    \n    /*  Function to get data from current Node  */\n    public int getData()\n    {\n        return data;\n    }\n}\n \n/* Class linkedList */\nclass linkedList\n{\n    protected Node start;\n    protected Node end ;\n    public int size ;\n \n    /*  Constructor  */\n    public linkedList()\n    {\n        start = null;\n        end = null;\n        size = 0;\n    }\n    /*  Function to check if list is empty  */\n    public boolean isEmpty()\n    {\n        return start == null;\n    }\n    /*  Function to get size of list  */\n    public int getSize()\n    {\n        return size;\n    }    \n    /*  Function to insert an element at begining  */\n    public void insertAtStart(int val)\n    {\n        Node nptr = new Node(val, null);    \n        size++ ;    \n        if(start == null) \n        {\n            start = nptr;\n            end = start;\n        }\n        else \n        {\n            nptr.setLink(start);\n            start = nptr;\n        }\n    }\n    /*  Function to insert an element at end  */\n    public void insertAtEnd(int val)\n    {\n        Node nptr = new Node(val,null);    \n        size++ ;    \n        if(start == null) \n        {\n            start = nptr;\n            end = start;\n        }\n        else \n        {\n            end.setLink(nptr);\n            end = nptr;\n        }\n    }\n    /*  Function to insert an element at position  */\n    public void insertAtPos(int val , int pos)\n    {\n        Node nptr = new Node(val, null);                \n        Node ptr = start;\n        pos = pos - 1 ;\n        for (int i = 1; i < size; i++) \n        {\n            if (i == pos) \n            {\n                Node tmp = ptr.getLink() ;\n                ptr.setLink(nptr);\n                nptr.setLink(tmp);\n                break;\n            }\n            ptr = ptr.getLink();\n        }\n        size++ ;\n    }\n    /*  Function to delete an element at position  */\n    public void deleteAtPos(int pos)\n    {        \n        if (pos == 1) \n        {\n            start = start.getLink();\n            size--; \n            return ;\n        }\n        if (pos == size) \n        {\n            Node s = start;\n            Node t = start;\n            while (s != end)\n            {\n                t = s;\n                s = s.getLink();\n            }\n            end = t;\n            end.setLink(null);\n            size --;\n            return;\n        }\n        Node ptr = start;\n        pos = pos - 1 ;\n        for (int i = 1; i < size - 1; i++) \n        {\n            if (i == pos) \n            {\n                Node tmp = ptr.getLink();\n                tmp = tmp.getLink();\n                ptr.setLink(tmp);\n                break;\n            }\n            ptr = ptr.getLink();\n        }\n        size-- ;\n    }    \n    /*  Function to display elements  */\n    public void display()\n    {\n        System.out.print(\"\\nSingly Linked List = \");\n        if (size == 0) \n        {\n            System.out.print(\"empty\\n\");\n            return;\n        }    \n        if (start.getLink() == null) \n        {\n            System.out.println(start.getData() );\n            return;\n        }\n        Node ptr = start;\n        System.out.print(start.getData()+ \"->\");\n        ptr = start.getLink();\n        while (ptr.getLink() != null)\n        {\n            System.out.print(ptr.getData()+ \"->\");\n            ptr = ptr.getLink();\n        }\n        System.out.print(ptr.getData()+ \"\\n\");\n    }\n}\n \n/*  Class SinglyLinkedList  */\npublic class SinglyLinkedList\n{    \n    public static void main(String[] args)\n    {             \n        Scanner scan = new Scanner(System.in);\n        /* Creating object of class linkedList */\n        linkedList list = new linkedList(); \n        System.out.println(\"Singly Linked List Test\\n\");          \n        \n        char ch;\n        /*  Perform list operations  */\n        do\n        {\n            System.out.println(\"\\nSingly Linked List Operations\\n\");\n            System.out.println(\"1. insert at begining\");\n            System.out.println(\"2. insert at end\");\n            System.out.println(\"3. insert at position\");\n            System.out.println(\"4. delete at position\");\n            System.out.println(\"5. check empty\");\n            System.out.println(\"6. get size\");            \n            \n            int choice = scan.nextInt();            \n            switch (choice)\n            {\n            case 1 : \n                System.out.println(\"Enter integer element to insert\");\n                list.insertAtStart( scan.nextInt());                     \n                break;                          \n            case 2 : \n                System.out.println(\"Enter integer element to insert\");\n                list.insertAtEnd( scan.nextInt());                     \n                break;                         \n            case 3 : \n                System.out.println(\"Enter integer element to insert\");\n                int num = scan.nextInt() ;\n                \n                System.out.println(\"Enter position\");\n                int pos = scan.nextInt() ;\n                \n                if (pos <= 1 || pos > list.getSize())\n                    System.out.println(\"Invalid position\\n\");\n                else\n                    list.insertAtPos(num, pos);\n                break;                                          \n            case 4 : \n                System.out.println(\"Enter position\");\n\n                int p = scan.nextInt() ;\n                if (p < 1 || p > list.getSize() )\n                    System.out.println(\"Invalid position\\n\");\n                else\n                    list.deleteAtPos(p);\n                break;\n            case 5 : \n                System.out.println(\"Empty status = \"+ list.isEmpty());\n                break;                   \n            case 6 : \n                System.out.println(\"Size = \"+ list.getSize() +\" \\n\");\n                break;                         \n             default : \n                System.out.println(\"Wrong Entry \\n \");\n                break;   \n            }\n\n            /*  Display List  */ \n            list.display();\n            \n            System.out.println(\"\\nDo you want to continue (Type y or n) \\n\");\n            ch = scan.next().charAt(0);                        \n        \n        } while (ch == 'Y'|| ch == 'y');               \n    }\n}\n"
  },
  {
    "path": "data_structures/linked_list/java/LinkedListLinkedList.java",
    "content": "/**\r\n * Java LinkedList implementation for Hacktoberfest\r\n * @author Prohunt\r\n *\r\n * @param <E> type of LinkedList\r\n */\r\npublic class LinkedList<E> {\r\n\tprivate Node head;\r\n\tprivate Node tail;\r\n\t\r\n\tprivate int size;\r\n\t/**\r\n\t * Constructor\r\n\t */\r\n\tpublic LinkedList(){\r\n\t\thead = null;\r\n\t\ttail = null;\r\n\t\tsize = 0;\r\n\t}\r\n\t/**\r\n\t * Adds an element to the tail end of the list\r\n\t * @param element\r\n\t * @return success or failure\r\n\t */\r\n\tpublic boolean add(E element){\r\n\t\tif(null == head){\r\n\t\t\thead = new Node(element);\r\n\t\t\tsize++;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\tif(null == tail){\r\n\t\t\ttail = new Node(element);\r\n\t\t\thead.next = tail;\r\n\t\t\tsize++;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\tif(null != element){\r\n\t\t\ttail.next = new Node(element);\r\n\t\t\ttail = new Node(element);\r\n\t\t\tsize++;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\t/**\r\n\t * Removes the given element from the list\r\n\t * @param element to remove\r\n\t * @return success or failure\r\n\t */\r\n\tpublic boolean remove(E element){\r\n\t\tNode current = head;\r\n\t\twhile(null != current.next){\r\n\t\t\tif(current.next.data.equals(element)){\r\n\t\t\t\tcurrent.next = current.next.next;\r\n\t\t\t\tsize--;\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t\tcurrent = current.next;\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Checks if the list contains the element\r\n\t * @param element to check\r\n\t * @return true if it contains it, false otherwise\r\n\t */\r\n\tpublic boolean contains(E element) {\r\n\t\tNode current = head;\r\n\t\twhile (null != current){\r\n\t\t\tif(current.data.equals(element)){\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t\tcurrent = current.next;\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Get the Head of the list\r\n\t * @return\r\n\t */\r\n\tpublic E head(){\r\n\t\treturn head.data;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Gets the tail of the list\r\n\t * @return tail element\r\n\t */\r\n\tpublic E tail(){\r\n\t\treturn tail.data;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Gets the size of the list\r\n\t * @return size\r\n\t */\r\n\tpublic int size(){\r\n\t\treturn size;\r\n\t}\r\n\t/**\r\n\t * Inner Class for storing elements as nodes\r\n\t * Provides a next Node for linking the elements together\r\n\t * @author Prohunt\r\n\t *\r\n\t */\r\n\tprivate class Node{\r\n\t\tE data;\r\n\t\tNode next;\r\n\t\t\r\n\t\t\r\n\t\tpublic Node(E element){\r\n\t\t\tdata = element;\r\n\t\t\tnext = null;\r\n\t\t}\r\n\r\n\t\t\r\n\r\n\t\r\n\t}\r\n\r\n}\r\n"
  },
  {
    "path": "data_structures/linked_list/java/LinkedListTest.java",
    "content": "import static org.junit.Assert.*;\r\n\r\nimport org.junit.Test;\r\n\r\n/**\r\n * Testing LinkedList\r\n * @author Prohunt\r\n *\r\n */\r\npublic class LinkedListTest {\r\n\t@Test\r\n\tpublic void testLinkedList(){\r\n\t\tLinkedList<Integer> intList = new LinkedList<Integer>();\r\n\t\tassertTrue(intList.add(1));\r\n\t\tassertTrue(intList.add(2));\r\n\t\tassertEquals(new Integer(1), intList.head());\r\n\t\tassertEquals(new Integer(2), intList.tail());\r\n\t\tassertTrue(intList.add(3));\r\n\t\tassertEquals(new Integer(3), intList.tail());\r\n\t\tassertEquals(3, intList.size());\r\n\t\t\r\n\t\tassertFalse(intList.add(null));\r\n\t\t\r\n\t\tassertTrue(intList.remove(new Integer(3)));\r\n\t\tassertFalse(intList.contains(new Integer(3)));\r\n\t\tassertEquals(2, intList.size());\r\n\t\t\r\n\t\tassertTrue(intList.contains(new Integer(2)));\r\n\t\t\r\n\t\tassertFalse(intList.remove(new Integer(3)));\r\n\t}\r\n}\r\n"
  },
  {
    "path": "data_structures/linked_list/kotlin/LinkedList.kt",
    "content": "import java.util.*\n\n/*\n *  Kotlin Program to Implement Singly Linked List\n */\n\n/*  Class Node  */\ninternal class Node {\n    /*  Function to get data from current Node  */\n    /*  Function to set data to current Node  */\n    var data: Int = 0\n    /*  Function to get link to next node  */\n    /*  Function to set link to next Node  */\n    var link: Node? = null\n\n    /*  Constructor  */\n    constructor() {\n        link = null\n        data = 0\n    }\n\n    /*  Constructor  */\n    constructor(d: Int, n: Node?) {\n        data = d\n        link = n\n    }\n}\n\n/* Class linkedList */\ninternal class linkedList {\n    private var start: Node? = null\n    private var end: Node? = null\n    /*  Function to get size of list  */\n    var size: Int = 0\n    /*  Function to check if list is empty  */\n    val isEmpty: Boolean\n        get() = start == null\n\n    /*  Constructor  */\n    init {\n        start = null\n        end = null\n        size = 0\n    }\n\n    /*  Function to insert an element at begining  */\n    fun insertAtStart(value: Int) {\n        val nptr = Node(value, null)\n        size++\n        if (start == null) {\n            start = nptr\n            end = start\n        } else {\n            nptr.link = start\n            start = nptr\n        }\n    }\n\n    /*  Function to insert an element at end  */\n    fun insertAtEnd(value: Int) {\n        val nptr = Node(value, null)\n        size++\n        if (start == null) {\n            start = nptr\n            end = start\n        } else {\n            end!!.link = nptr\n            end = nptr\n        }\n    }\n\n    /*  Function to insert an element at position  */\n    fun insertAtPos(value: Int, pos: Int) {\n        var pos = pos\n        val nptr = Node(value, null)\n        var ptr = start\n        pos =- 1\n        for (i in 1 until size) {\n            if (i == pos) {\n                val tmp = ptr!!.link\n                ptr.link = nptr\n                nptr.link = tmp\n                break\n            }\n            ptr = ptr!!.link\n        }\n        size++\n    }\n\n    /*  Function to delete an element at position  */\n    fun deleteAtPos(pos: Int) {\n        var pos = pos\n        if (pos == 1) {\n            start = start!!.link\n            size--\n            return\n        }\n        if (pos == size) {\n            var s = start\n            var t = start\n            while (s !== end) {\n                t = s\n                s = s!!.link\n            }\n            end = t\n            end!!.link = null\n            size--\n            return\n        }\n        var ptr = start\n        pos =- 1\n        for (i in 1 until size - 1) {\n            if (i == pos) {\n                var tmp = ptr!!.link\n                tmp = tmp!!.link\n                ptr.link = tmp\n                break\n            }\n            ptr = ptr!!.link\n        }\n        size--\n    }\n\n    /*  Function to display elements  */\n    fun display() {\n        print(\"\\nSingly Linked List = \")\n        if (size == 0) {\n            print(\"empty\\n\")\n            return\n        }\n        if (start!!.link == null) {\n            println(start!!.data)\n            return\n        }\n        var ptr = start\n        print(start!!.data.toString() + \"->\")\n        ptr = start!!.link\n        while (ptr!!.link != null) {\n            print(ptr.data.toString() + \"->\")\n            ptr = ptr.link\n        }\n        print(ptr.data.toString() + \"\\n\")\n    }\n}\n\n/*  Class SinglyLinkedList  */\nobject SinglyLinkedList {\n    fun main(args: Array<String>) {\n        val scan = Scanner(System.`in`)\n        /* Creating object of class linkedList */\n        val list = linkedList()\n        println(\"Singly Linked List Test\\n\")\n\n        var ch: Char\n        /*  Perform list operations  */\n        do {\n            println(\"\\nSingly Linked List Operations\\n\")\n            println(\"1. insert at begining\")\n            println(\"2. insert at end\")\n            println(\"3. insert at position\")\n            println(\"4. delete at position\")\n            println(\"5. check empty\")\n            println(\"6. get size\")\n\n            val choice = scan.nextInt()\n            when (choice) {\n                1 -> {\n                    println(\"Enter integer element to insert\")\n                    list.insertAtStart(scan.nextInt())\n                }\n                2 -> {\n                    println(\"Enter integer element to insert\")\n                    list.insertAtEnd(scan.nextInt())\n                }\n                3 -> {\n                    println(\"Enter integer element to insert\")\n                    val num = scan.nextInt()\n\n                    println(\"Enter position\")\n                    val pos = scan.nextInt()\n\n                    if (pos <= 1 || pos > list.size)\n                        println(\"Invalid position\\n\")\n                    else\n                        list.insertAtPos(num, pos)\n                }\n                4 -> {\n                    println(\"Enter position\")\n\n                    val p = scan.nextInt()\n                    if (p < 1 || p > list.size)\n                        println(\"Invalid position\\n\")\n                    else\n                        list.deleteAtPos(p)\n                }\n                5 -> println(\"Empty status = \" + list.isEmpty)\n                6 -> println(\"Size = \" + list.size + \" \\n\")\n                else -> println(\"Wrong Entry \\n \")\n            }\n\n            /*  Display List  */\n            list.display()\n\n            println(\"\\nDo you want to continue (Type y or n) \\n\")\n            ch = scan.next()[0]\n\n        } while (ch == 'Y' || ch == 'y')\n    }\n}\n"
  },
  {
    "path": "data_structures/linked_list/linked_list.md",
    "content": "## ELI5\nA linked list is a data structure made up of a bunch of little boxes that each hold a piece of information and directions to the next box. This makes it easy to make changes, because you don't have to move anything to a different box, you just have to give each box new directions. However, if you want the values in a certain box, you have to ask every box before it for directions to get there.\n### Pros\n* It's cheap to add and remove elements from a linked list.\n### Cons\n* It's expensive to get values in a given box.\n\n## Technical Explanation\nA linked list is defined recursively as being either empty, or containing a node which stores a value and a pointer to a linked list. A linked list commonly starts with a pointer (often named \"start\" or \"head\") to the first node, and each subsequent node contains its value and a pointer to the next node. The pointer of the last node points to null, and therefore there are no more nodes and the list ends.\nBecause of the pointer connections between nodes, inserting and removing values from a linked list is efficient, in O(1) time. Whereas contiguous data structures require shifting every piece of data after the edit point to preserve the contiguous structure, one can simply redirect the pointers in a linked list to accomplish the same.\nInserting an item requires creating a node with that item, assigning that node's pointer to the address of the item after it (which can be retrieved from the item before it) and then assigning the pointer of the item before it to the newly created node. \nDeleting/erasing an item simply requires redirecting the pointer of the previous node to the next node. Care must be taken in languages where memory is manually deallocated/freed so as to delete the node before redirecting the pointer that points to it, and without losing the pointer to the next node. \nThe pointer-based nature of list also makes it easier to make greater changes such as reversing the list, as once again no values must be copied to different spots in memory, instead only pointers are reassigned.\nAccessing the value at a given index in the list is expensive, in O(n) time. One must start at a known pointer and increment through the list one node at a time until the desired location is reached. Because lists are not based on arrays, subscripting in the standard O(1) sense cannot be used to access list values.\n### Pros\n* Adding and removing nodes from the list is cheap O(1)\n### Cons\n* Accessing values in the list is expensive O(n)\n"
  },
  {
    "path": "data_structures/linked_list/python/linked_list.py",
    "content": "class Node:\n    def __init__(self, data=None, next_node=None):\n        self.data = data\n        self.next = next_node\n        self.prev = None\n\n    def __repr__(self):\n        return self.data or ''\n\n\nclass LinkedList:\n    '''\n    Implementation of Linked list data structure\n    '''\n\n    def __init__(self, data_iterable):\n        self.head = None\n        for data in data_iterable:\n            self.add(data)\n\n    def add(self, data):\n        node = Node(data)\n        node.next = self.head\n        self.head = node\n        if node.next:\n            node.next.prev = node\n\n    def search(self, data):\n        node = self.head\n        while node:\n            if node.data == data:\n                return node\n            node = node.next\n        return None\n\n    def remove(self, node):\n        if node is self.head:\n            self.head = node.next\n        else:\n            node.prev.next = node.next\n        if node.next:\n            node.next.prev = node.prev\n    \n    def __repr__(self):\n        node = self.head\n        data = []\n        while node:\n            data.append(node.data)\n            node = node.next\n        return ' '.join(data)\n\n\nif __name__ == '__main__':\n    l = LinkedList(['d', 'c', 'b'])\n    assert str(l) == 'b c d'\n    l.add('a')\n    assert str(l) == 'a b c d'\n    l.remove(l.search('a'))\n    l.remove(l.search('c'))\n    assert str(l) == 'b d'\n\n"
  },
  {
    "path": "data_structures/linked_list/ruby/linked_list.rb",
    "content": "class Node\n    attr_writer :next\n    attr_reader :next, :data\n\n    def initialize(data, next_node = nil)\n        @data = data\n        @next = next_node\n    end\nend\n\nclass LinkedList\n    def initialize\n        @head = nil\n        @tail = @head\n    end\n\n    def insertFront(data)\n        node = Node.new(data, @head)\n        @tail = node if @tail == nil\n        @head = node\n    end\n\n    def insertBack(data)\n        node = Node.new(data)\n        @head = node if @head == nil\n        @tail.next = node if @tail != nil\n        @tail = node\n    end\n\n    def find(data)\n        current = @head\n        while current != nil do\n            return current if data == current.data\n            current = current.next\n        end\n        return nil\n    end\n\n    def remove(node)\n        prev = nil\n        current = @head\n\n        while current != nil do\n            if node.equal? current\n                if current == @head\n                    @head = @head.next\n                elsif current == @tail\n                    @tail = prev\n                    prev.next = nil\n                else\n                    prev.next = current.next\n                end\n                break\n            end\n            prev = current\n            current = current.next\n        end\n    end\n\n    def iterate\n        current = @head\n        while current != nil do\n            yield current.data\n            current = current.next\n        end\n    end\nend\n\n# Usage\nL = LinkedList.new\nL.insertBack(3)\nL.insertBack(4)\nL.insertFront(2)\nL.insertFront(1)\n\n# 1 2 3 4\nL.iterate { |data| puts(data) }\n\nnode_2 = L.find(4)\nL.remove(node_2)\n\n# 1 3 4\nL.iterate { |data| puts(data) }"
  },
  {
    "path": "data_structures/linked_list_queue/cpp/queue_linked_list.cpp",
    "content": "// Simple queue data structure using singly linked list\n#include <iostream>\n\n// List node\ntemplate <typename T>\nstruct QueueNode {\n\t// Constructor. Set node value and initialize next node pointer to NULL\n\tQueueNode<T>(T _value) {\n\t\tvalue = _value;\n\t\tpNext = NULL;\n\t}\n\t\n\tT value; // Value stored in node\n\tQueueNode<T> *pNext; // Next node in linked list\n};\n\n// Queue structure\ntemplate <typename T>\nclass CQueue {\npublic:\n\t// Constructor. Initialize head & tail pointer to NULL.\n\tCQueue<T>() {\n\t\tm_pHead = m_pTail = NULL;\n\t}\n\n\t// Push a new element into the queue\n\tvoid enqueue(T value) {\n\t\tQueueNode<T> *pNewTail = new QueueNode<T>(value);\n\t\t\n\t\tif (m_pHead == NULL)\n\t\t\tm_pHead = m_pTail = pNewTail;\n\t\telse {\n\t\t\tm_pTail->pNext = pNewTail;\n\t\t\tm_pTail = pNewTail;\n\t\t}\n\t}\n\t\n\t// Pop the head element from the queue\n\tT dequeue() {\n\t\tif (m_pHead == NULL)\n\t\t\treturn NULL;\n\t\t\n\t\tT value = m_pHead->value;\n\t\tQueueNode<T> *pNewHead = m_pHead->pNext;\n\t\tdelete m_pHead;\n\t\tm_pHead = pNewHead;\n\t\t\n\t\treturn value;\n\t}\n\t\n\t// Check if the queue is empty\n\tbool isEmpty() {\n\t\treturn m_pHead == NULL;\n\t}\n\t\nprivate:\n\tQueueNode<T> *m_pHead; // Head node of linked list\n\tQueueNode<T> *m_pTail; // Tail node of linked list\n};\n\nusing namespace std;\n\nint main() {\n\tCQueue<int> queue;\n\t\n\tqueue.enqueue(1);\n\tqueue.enqueue(2);\n\tqueue.enqueue(3);\n\tqueue.enqueue(4);\n\tqueue.enqueue(5);\n\t\n\twhile (!queue.isEmpty())\n\t\tcout << queue.dequeue() << ' ';\n\t\n\treturn 0;\n}\n"
  },
  {
    "path": "data_structures/min_heap/cpp/impl_minHeap.cpp",
    "content": "// Insert the following numbers into the heap, printing the heap after each insert:\n//  2  3  7 22  5 21  1 28  4 16  0 17 12 18 20 25\n\n// deleteMin() the numbers in the heap, into a new list (array or vector is fine), printing the heap after each deleteMin() (I want to see how your heap structure changes after each deleteMin).\n// Print the new sorted list of numbers.\n#include \"minHeap.cpp\"\n#include <iostream>\n#include <cstdlib>\n#include <string>\n#include <cmath>\n\nusing std::cout;\nusing std::endl;\nusing std::string;\n\nint main(){\n    int unsortedNums[] = {2, 3, 7, 22, 5, 21, 1, 28, 4, 16, 0, 17, 12, 18, 20, 25};\n    int sortedNums[16];\n    MinHeap heap;\n    \n    cout << \"Printing unsorted List: \\n\";\n    for(int k = 0;k<16;k++){\n        cout << unsortedNums[k] << \", \";\n    }\n    cout << \"\\n\\n========================================================\\nInserting to min heap: \\n\";\n    for(int i = 0;i<16;i++){\n        heap.insert(unsortedNums[i]);\n        heap.printSelf();\n        cout << endl;\n    }\n    cout << \"========================================================\\nSorting List: \\n\";\n    for(int j = 0;j<16;j++){\n        int min = heap.deleteMin();\n        sortedNums[j] = min;\n        heap.printSelf();\n        cout << endl;\n    }\n    cout << \"========================================================\\nPrinting Sorted List: \\n\";\n    for(int k = 0;k<16;k++){\n        cout << sortedNums[k] << \", \";\n    }\n    cout << endl;\n}\n"
  },
  {
    "path": "data_structures/min_heap/cpp/minHeap.cpp",
    "content": "#include \"minHeap.hpp\"\n#include <iostream>\n#include <cstdlib>\n#include <vector>\n\nusing std::cout;\nusing std::endl;\nusing std::vector;\n\n// Some helpers first\n// The left child of node in index i is: 2*i+1\n// The right child of node in index i is: 2*i+2\n// The parent of the node in index i is: (int)((i-1)/2)\n\nint getLeftIndex(int x){\n    return 2*x+1;\n}\n\nint getRightIndex(int x){\n    return 2*x+2;\n}\n\nint getParentIndex(int x){\n    return (int)((x-1)/2);\n}\n\n\nMinHeap::MinHeap(){}\n\nMinHeap::~MinHeap(){}\n\nvoid MinHeap::insert(int item){\n    int length = _heap.size();\n    _heap.push_back(item);\n    bubbleUp(length);\n}\n\nint MinHeap::deleteMin(){\n    int length = _heap.size();\n\n    if(length == 0){\n        return -1;\n    }\n    int min = _heap[0];\n    \n    _heap[0] = _heap[length-1];\n    _heap.pop_back();\n\n    bubbleDown(0);\n    return min;\n}\n\nvoid MinHeap::printSelf(){\n    cout << \"Heap printing...\\n\";\n    if(_heap.size() == 0){\n        cout << \"There is nothing in the heap\\n\";\n        return;\n    }\n    for(int i = 0;i < _heap.size();i++){\n        cout << _heap.at(i) << \", \";\n    }\n    cout << endl;\n}\n\nvoid MinHeap::bubbleDown(int index){\n    int length = _heap.size();\n    int leftChildIndex = getLeftIndex(index);\n    int rightChildIndex = getRightIndex(index);\n\n    if(leftChildIndex >= length)\n        return; //index is a leaf\n\n    int minIndex = index;\n\n    if(_heap[index] > _heap[leftChildIndex]){\n        minIndex = leftChildIndex;\n    }\n    \n    if((rightChildIndex < length) && (_heap[minIndex] > _heap[rightChildIndex])){\n        minIndex = rightChildIndex;\n    }\n\n    if(minIndex != index){\n        //need to swap\n        int temp = _heap[index];\n        _heap[index] = _heap[minIndex];\n        _heap[minIndex] = temp;\n        bubbleDown(minIndex);\n    }\n}\n\nvoid MinHeap::bubbleUp(int index){\n    if(index == 0)\n        return;\n\n    int parentIndex = getParentIndex(index);\n\n    if(_heap[parentIndex] > _heap[index]){\n        int temp = _heap[parentIndex];\n        _heap[parentIndex] = _heap[index];\n        _heap[index] = temp;\n        bubbleUp(parentIndex);\n    }\n}\n"
  },
  {
    "path": "data_structures/min_heap/cpp/minHeap.hpp",
    "content": "#ifndef MINHEAP_H\n#define MINHEAP_H\n\n#include <iostream>\n#include <vector>\n#include <cstdlib>\n\nusing std::vector;\n\nclass MinHeap{\npublic:\n    MinHeap();\n    ~MinHeap();\n    void insert(int item);\n    int deleteMin();\n    void printSelf();\nprivate:\n    void bubbleUp(int index);\n    void bubbleDown(int index);\n    vector<int> _heap;\n};\n\n#endif //MINHEAP_H\n"
  },
  {
    "path": "data_structures/mirror_of_a_tree.java/java/Mirror.java",
    "content": "class Mirror{\n\n\tNode root = null;\n\tNode mRoot = null;\n\tpublic void mirror(Node node){\n\n\tif(node == null) return ;\n\n\tmirror(node.left);\n\n\tmirror(node.right);\n\n\tNode temp = node.left;\n\tnode.left = node.right;\n\tnode.right = temp;\n\n\t}\n\n\tpublic void printTree(Node node){\n\n\tif(node == null) return;\n\n\tprintTree(node.left);\n\n\tSystem.out.print(node.data+\" \");\n\n\tprintTree(node.right);\n\n\t}\n\tpublic static void main(String[] args){\n\n\tMirror bt = new Mirror();\n\n\t        bt.root = new Node(1);\n\t        bt.root.left = new Node(2);\n\t        bt.root.right = new Node(3);\n\t        bt.root.left.left = new Node(4);\n\t        bt.root.left.right = new Node(5);  \n\t        bt.root.right.right = new Node(7);\n\t        bt.root.right.left = new Node(6);\n\n\t\n\n \tSystem.out.println(\"Original Tree\\n\");\n\tbt.printTree(bt.root);\n\n\tbt.mirror(bt.root);\n\tSystem.out.println();\n\n\tSystem.out.println(\"Mirror Tree\\n\");\n\tbt.printTree(bt.root);\n\n\t}\n\n}"
  },
  {
    "path": "data_structures/mirrot_of_a_tree.cpp/mirror.cpp",
    "content": "#include <iostream>\n#include <queue>\n#include <cstdlib>\n\nusing namespace std;\n\ntypedef struct btree {\n\tint data;\n\tstruct btree *left;\n\tstruct btree *right;\n}btree;\n\nbtree *makeTree(btree *root , int d) {\n\tbtree *nn = (btree*)malloc(sizeof(btree));\n\tnn->data = d;\n\tnn->left = NULL;\n\tnn->right = NULL;\n\tif(root==NULL) {\n\t\treturn nn;\n\t}\n\telse {\n\t\tqueue<btree*> q;\n\t\tq.push(root);\n\t\twhile(!q.empty()) {\n\t\t\tbtree *node = q.front();\n\t\t\tq.pop();\n\t\t\tif(node->left) q.push(node->left);\n\t\t\telse {\n\t\t\t\tnode->left = nn;\n\t\t\t\treturn root;\n\t\t\t}\n\n\t\t\tif(node->right) q.push(node->right);\n\t\t\telse {\n\t\t\t\tnode->right = nn;\n\t\t\t\treturn root;\n\t\t\t}\n\t\t}\n\t}\n}\n\nbtree *mirror(btree *root) {\n\tif(root==NULL) return NULL;\n\tbtree *nn = (btree*)malloc(sizeof(btree));\n\n\tnn->data = root->data;\n\tnn->right = mirror(root->left);\n\tnn->left = mirror(root->right);\n\n\treturn nn;\n}\n\nvoid printTreeLevelOrder(btree *root) {\n\tqueue<btree*> q;\n\tq.push(root);\n\twhile(!q.empty()) {\n\t\tbtree *node = q.front();\n\t\tq.pop();\n\t\tcout<<node->data<<\" \";\n\t\tif(node->left) q.push(node->left);\n\n\t\tif(node->right) q.push(node->right);\n\t}\n}\n\nint main()\n{\n\tbtree *a = NULL;\n\ta = makeTree(a,1);\n\ta = makeTree(a,2);\n\ta = makeTree(a,3);\n\ta = makeTree(a,4);\n\ta = makeTree(a,5);\n\ta = makeTree(a,6);\n\ta = makeTree(a,7);\n\n\tbtree *b = mirror(a);\n\tprintTreeLevelOrder(b);\n\tcout<<endl;\n\treturn 0;\n}\n"
  },
  {
    "path": "data_structures/mst/cpp/mst.cpp",
    "content": "// A C / C++ program for Prim's Minimum Spanning Tree (MST) algorithm. \n// The program is for adjacency matrix representation of the graph\n \n#include <stdio.h>\n#include <limits.h>\n \n// Number of vertices in the graph\n#define V 5\n \n// A utility function to find the vertex with minimum key value, from\n// the set of vertices not yet included in MST\nint minKey(int key[], bool mstSet[])\n{\n   // Initialize min value\n   int min = INT_MAX, min_index;\n \n   for (int v = 0; v < V; v++)\n     if (mstSet[v] == false && key[v] < min)\n         min = key[v], min_index = v;\n \n   return min_index;\n}\n \n// A utility function to print the constructed MST stored in parent[]\nint printMST(int parent[], int n, int graph[V][V])\n{\n   printf(\"Edge   Weight\\n\");\n   for (int i = 1; i < V; i++)\n      printf(\"%d - %d    %d \\n\", parent[i], i, graph[i][parent[i]]);\n}\n \n// Function to construct and print MST for a graph represented using adjacency\n// matrix representation\nvoid primMST(int graph[V][V])\n{\n     int parent[V]; // Array to store constructed MST\n     int key[V];   // Key values used to pick minimum weight edge in cut\n     bool mstSet[V];  // To represent set of vertices not yet included in MST\n \n     // Initialize all keys as INFINITE\n     for (int i = 0; i < V; i++)\n        key[i] = INT_MAX, mstSet[i] = false;\n \n     // Always include first 1st vertex in MST.\n     key[0] = 0;     // Make key 0 so that this vertex is picked as first vertex\n     parent[0] = -1; // First node is always root of MST \n \n     // The MST will have V vertices\n     for (int count = 0; count < V-1; count++)\n     {\n        // Pick the minimum key vertex from the set of vertices\n        // not yet included in MST\n        int u = minKey(key, mstSet);\n \n        // Add the picked vertex to the MST Set\n        mstSet[u] = true;\n \n        // Update key value and parent index of the adjacent vertices of\n        // the picked vertex. Consider only those vertices which are not yet\n        // included in MST\n        for (int v = 0; v < V; v++)\n \n           // graph[u][v] is non zero only for adjacent vertices of m\n           // mstSet[v] is false for vertices not yet included in MST\n           // Update the key only if graph[u][v] is smaller than key[v]\n          if (graph[u][v] && mstSet[v] == false && graph[u][v] <  key[v])\n             parent[v]  = u, key[v] = graph[u][v];\n     }\n \n     // print the constructed MST\n     printMST(parent, V, graph);\n}\n \n \n// driver program to test above function\nint main()\n{\n   /* Let us create the following graph\n          2    3\n      (0)--(1)--(2)\n       |   / \\   |\n      6| 8/   \\5 |7\n       | /     \\ |\n      (3)-------(4)\n            9          */\n   int graph[V][V] = {{0, 2, 0, 6, 0},\n                      {2, 0, 3, 8, 5},\n                      {0, 3, 0, 0, 7},\n                      {6, 8, 0, 0, 9},\n                      {0, 5, 7, 9, 0},\n                     };\n \n    // Print the solution\n    primMST(graph);\n \n    return 0;\n}"
  },
  {
    "path": "data_structures/mst/java/prims.java",
    "content": "public class PrimMST {\n    private static final double FLOATING_POINT_EPSILON = 1E-12;\n\n    private Edge[] edgeTo;        // edgeTo[v] = shortest edge from tree vertex to non-tree vertex\n    private double[] distTo;      // distTo[v] = weight of shortest such edge\n    private boolean[] marked;     // marked[v] = true if v on tree, false otherwise\n    private IndexMinPQ<Double> pq;\n\n    /**\n     * Compute a minimum spanning tree (or forest) of an edge-weighted graph.\n     * @param G the edge-weighted graph\n     */\n    public PrimMST(EdgeWeightedGraph G) {\n        edgeTo = new Edge[G.V()];\n        distTo = new double[G.V()];\n        marked = new boolean[G.V()];\n        pq = new IndexMinPQ<Double>(G.V());\n        for (int v = 0; v < G.V(); v++)\n            distTo[v] = Double.POSITIVE_INFINITY;\n\n        for (int v = 0; v < G.V(); v++)      // run from each vertex to find\n            if (!marked[v]) prim(G, v);      // minimum spanning forest\n\n        // check optimality conditions\n        assert check(G);\n    }\n\n    // run Prim's algorithm in graph G, starting from vertex s\n    private void prim(EdgeWeightedGraph G, int s) {\n        distTo[s] = 0.0;\n        pq.insert(s, distTo[s]);\n        while (!pq.isEmpty()) {\n            int v = pq.delMin();\n            scan(G, v);\n        }\n    }\n\n    // scan vertex v\n    private void scan(EdgeWeightedGraph G, int v) {\n        marked[v] = true;\n        for (Edge e : G.adj(v)) {\n            int w = e.other(v);\n            if (marked[w]) continue;         // v-w is obsolete edge\n            if (e.weight() < distTo[w]) {\n                distTo[w] = e.weight();\n                edgeTo[w] = e;\n                if (pq.contains(w)) pq.decreaseKey(w, distTo[w]);\n                else                pq.insert(w, distTo[w]);\n            }\n        }\n    }\n\n    /**\n     * Returns the edges in a minimum spanning tree (or forest).\n     * @return the edges in a minimum spanning tree (or forest) as\n     *    an iterable of edges\n     */\n    public Iterable<Edge> edges() {\n        Queue<Edge> mst = new Queue<Edge>();\n        for (int v = 0; v < edgeTo.length; v++) {\n            Edge e = edgeTo[v];\n            if (e != null) {\n                mst.enqueue(e);\n            }\n        }\n        return mst;\n    }\n\n    /**\n     * Returns the sum of the edge weights in a minimum spanning tree (or forest).\n     * @return the sum of the edge weights in a minimum spanning tree (or forest)\n     */\n    public double weight() {\n        double weight = 0.0;\n        for (Edge e : edges())\n            weight += e.weight();\n        return weight;\n    }\n\n\n    // check optimality conditions (takes time proportional to E V lg* V)\n    private boolean check(EdgeWeightedGraph G) {\n\n        // check weight\n        double totalWeight = 0.0;\n        for (Edge e : edges()) {\n            totalWeight += e.weight();\n        }\n        if (Math.abs(totalWeight - weight()) > FLOATING_POINT_EPSILON) {\n            System.err.printf(\"Weight of edges does not equal weight(): %f vs. %f\\n\", totalWeight, weight());\n            return false;\n        }\n\n        // check that it is acyclic\n        UF uf = new UF(G.V());\n        for (Edge e : edges()) {\n            int v = e.either(), w = e.other(v);\n            if (uf.connected(v, w)) {\n                System.err.println(\"Not a forest\");\n                return false;\n            }\n            uf.union(v, w);\n        }\n\n        // check that it is a spanning forest\n        for (Edge e : G.edges()) {\n            int v = e.either(), w = e.other(v);\n            if (!uf.connected(v, w)) {\n                System.err.println(\"Not a spanning forest\");\n                return false;\n            }\n        }\n\n        // check that it is a minimal spanning forest (cut optimality conditions)\n        for (Edge e : edges()) {\n\n            // all edges in MST except e\n            uf = new UF(G.V());\n            for (Edge f : edges()) {\n                int x = f.either(), y = f.other(x);\n                if (f != e) uf.union(x, y);\n            }\n\n            // check that e is min weight edge in crossing cut\n            for (Edge f : G.edges()) {\n                int x = f.either(), y = f.other(x);\n                if (!uf.connected(x, y)) {\n                    if (f.weight() < e.weight()) {\n                        System.err.println(\"Edge \" + f + \" violates cut optimality conditions\");\n                        return false;\n                    }\n                }\n            }\n\n        }\n\n        return true;\n    }\n\n    /**\n     * Unit tests the {@code PrimMST} data type.\n     *\n     * @param args the command-line arguments\n     */\n    public static void main(String[] args) {\n        In in = new In(args[0]);\n        EdgeWeightedGraph G = new EdgeWeightedGraph(in);\n        PrimMST mst = new PrimMST(G);\n        for (Edge e : mst.edges()) {\n            StdOut.println(e);\n        }\n        StdOut.printf(\"%.5f\\n\", mst.weight());\n    }\n\n\n}\n"
  },
  {
    "path": "data_structures/priority_queue/c/priority_queue.cpp",
    "content": "#include<stdio.h>\n#include<malloc.h>\nstruct node{\n\tint data,priority;\n\tstruct node* next;\n};\nstruct node *header=NULL;\n\nvoid enque(int data,int priority)\n{\n\tstruct node* ptr2;\n\tptr2=(struct node*)malloc(sizeof(struct node));\n\tptr2->data=data;\n\tptr2->priority=priority;\n\tptr2->next=header;\n\theader=ptr2;\n}\n\nvoid deque()\n{\n\tstruct node *ptr,*min,*prev;\n\tprev=NULL;\n\tptr=header;\n\tmin=ptr;\n\tptr=ptr->next;\n\tif(ptr==NULL)\n\t{\n\t\tprintf(\"empty\\n\");\n\t\treturn;\n\t}\n\twhile(ptr!=NULL)\n\t{\n\t\tif(min->priority>ptr->priority)\n\t\t{\n\t\t\tprev=min;\n\t\t\tmin=ptr;\n\t\t}\n\t\tptr=ptr->next;\n\t}\n\tprintf(\"dequeued element: %d\\tpriority: %d\\n\",min->data,min->priority);\n\tprev->next=min->next;\n\tfree(min);\n}\n\nvoid display()\n{\n\tstruct node *ptr;\n\tptr=header;\n\tif(ptr==NULL)\n\t{\n\t\tprintf(\"empty\\n\");\n\t\treturn;\n\t}\n\twhile(ptr!=NULL)\n\t{\n\t\tprintf(\"%d,%d\\t\",ptr->data,ptr->priority);\n\tptr=ptr->next;\n\t}\n\tprintf(\"\\n\");\n}\nint main()\n{\n\tint c,x,p;\n\twhile(1)\n{\n\tprintf(\"1.enque\\n2.deque\\n3.display\\n4.exit\\n\");\n\tscanf(\"%d\",&c);\n\tswitch(c)\n\t{\n\t\tcase 1:\tprintf(\"enter element and priority: \");\n\t\t\t\tscanf(\"%d%d\",&x,&p);\n\t\t\t\tenque(x,p);\n\t\t\t\tbreak;\n\t\tcase 2: deque();\n\t\t\t\tbreak;\n\t\tcase 3: display();\n\t\t\t\tbreak;\n\t\tcase 4: goto end;\n\t}\n}\nend:;\n}\n\n"
  },
  {
    "path": "data_structures/queue/c/queue.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n# define max 5\nint queue[max];\nint f=0,r=-1;\nint count=0;\nint main()\n{\n    int n;\n    do\n    {\n        printf(\"\\nEnter choice:\\n1.Push\\n2.POP\\n3.Display\\n4.Exit\\n\");\n        scanf(\"%d\",&n);\n        switch(n)\n        {\n            case 1:\n            push();\n            break;\n            case 2:\n            pop();\n            break;\n            case 3:\n            display();\n            break;\n            case 4:\n            exit(0);\n            break;\n        }\n    }while(n!=4);\n    return 0;\n}\n\nvoid push()\n{\n    int data;\n    printf(\"\\n\");\n    if((f==0 && r==max-1) || (f>0 && r==f-1))\n        printf(\"queue overflow\\n\");\n    else if((r==-1 && f==0) || (f==0 && r<max-1) || (f>0 && r!=f))\n    {\n        r=(r+1)%max;\n        printf(\"Enter element\\n\");\n        scanf(\"%d\",&queue[r]);\n        count++;\n    }\n    printf(\"\\n\\n\");\n}\n\nvoid pop()\n{\n    if(r==-1 || (f>0 && f==(r+1)%max))\n        printf(\"\\nUnderflow\\n\");\n    else\n    {\n        printf(\"\\nElement %d is popped out\\n\",queue[f]);\n        f=(f+1)%max;\n        count--;\n    } printf(\"\\n\\n\");\n}\n\nvoid display()\n{\n    printf(\"\\n\");\n    int i;\n    printf(\"\\nElements present are\\n\");\n    for(i=0;i<count;i++)\n    {\n        printf(\"%d\\t\",queue[f]);\n        f=(f+1)%max;\n    }\n    printf(\"\\n\\n\");\n}"
  },
  {
    "path": "data_structures/queue/cpp/Queue.cpp",
    "content": "#include \"Queue.h\"\n\ntemplate<class T>\nQueue<T>::Queue()\n{\n    tail = head = nullptr;\n    sz = 0;\n}\n\ntemplate<class T>\nQueue<T>::Queue(T value, int intial_size)\n{\n    sz = intial_size;\n    if(intial_size > 0)\n    {\n        Node* temp = new Node(value, nullptr);\n        tail = head = temp;\n        intial_size--;\n    }else{\n        tail = head = nullptr;\n    }\n    while(intial_size > 0)\n    {\n        Node* temp = new Node(value, nullptr);\n        tail->prev = temp;\n        tail = temp;\n        intial_size--;\n    }\n}\n\ntemplate<class T>\nT* Queue<T>::Front()\n{\n    try{\n        if(head != nullptr)\n            return &(head->value);\n        throw(0);\n    catch(...){\n        cout << \"EmptyQueue\" << endl;\n    }\n}\n\ntemplate<class T>\nvoid Queue<T>::Pop()\n{\n    if(head == nullptr)\n        return;\n    sz--;\n    Node* temp = head;\n    head = head->prev;\n    delete temp;\n}\ntemplate<class T>\nvoid Queue<T>::Push(T value)\n{\n    Node* temp = new Node(value, NULL);\n    if(tail == nullptr)\n    {\n        tail = head = temp;\n        sz++;\n        return;\n    }\n    tail->prev = temp;\n    tail = temp;\n    sz++;\n}\ntemplate<class T>\nint Queue<T>::Size()\n{\n    return sz;\n}\n\ntemplate<class T>\nvoid Queue<T>::Print()\n{\n    Node* temp = head;\n    while(temp != nullptr)\n    {\n        cout << temp->value << \" \";\n        temp = temp->prev;\n    }\n}\n\n\ntemplate<class T>\nQueue<T>::~Queue()\n{\n    Node* temp = head;\n    while(temp != nullptr)\n    {\n        temp = head;\n        head = head->prev;\n        delete temp;\n    }\n}\n"
  },
  {
    "path": "data_structures/queue/cpp/Queue.h",
    "content": "#ifndef QUEUE_H\n#define QUEUE_H\n#include <iostream>\nusing namespace std;\n\ntemplate<class T>\nclass Queue\n{\n    struct Node\n    {\n        Node(T v, Node* pre){value = v; prev = pre;}\n        T value;\n        Node* prev;\n    };\n    public:\n        Queue();\n        Queue(T value, int intial_size);\n        T* Front();\n        void Pop();\n        void Push(T value);\n        int Size();\n        void Print();\n        virtual ~Queue();\n\n    protected:\n\n    private:\n        Node* tail;\n        Node* head;\n        int sz;\n};\n\n#endif // QUEUE_H\n"
  },
  {
    "path": "data_structures/queue/csharp/Queue.cs",
    "content": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace DataStructures\n{\n    class Queue\n    {\n\n        private List<Object> queue = new List<Object>();\n\n        public Object dequeue()\n        {\n            if (queue.Count > 0)\n            {\n                Object temp = queue[0];\n                queue.RemoveAt(0);\n                return temp;\n            }\n            else\n            {\n                return null;\n            }\n        }\n\n\n        public Object peek()\n        {\n            if (queue.Count > 0)\n            {\n                return queue[0];\n            }\n            else\n            {\n                return null;\n            }\n        }\n\n\n        public void enqueue(Object newItem)\n        {\n            queue.Add(newItem);\n        }\n\n        \n        public bool isEmpty()\n        {\n            return (queue.Count == 0);\n        }\n\n\n    }\n}\n"
  },
  {
    "path": "data_structures/queue/go/queue.go",
    "content": "package main\n\nimport \"fmt\"\n\ntype queue struct {\n    data []interface{}\n}\n\nfunc NewQueue() queue {\n    return queue{nil}\n}\n\nfunc (q *queue) Enqueue(value interface{}) {\n    q.data = append(q.data, value)\n}\n\nfunc (q *queue) Dequeue() (interface{}) {\n    value := q.data[0]\n    q.data = q.data[1: len(q.data)]\n    return value\n}\n\nfunc main() {\n    q := NewQueue()\n    q.Enqueue(10)\n    q.Enqueue(\"Hello\")\n    q.Enqueue(20)\n    q.Enqueue(10)\n    q.Enqueue(\"Hello\")\n    q.Enqueue(20)\n    q.Enqueue(10)\n    q.Enqueue(\"Hello\")\n    q.Enqueue(20)\n    q.Enqueue(10)\n    q.Enqueue(\"Hello\")\n    q.Enqueue(20)\n    q.Enqueue(10)\n    q.Enqueue(\"Hello\")\n    q.Enqueue(20)\n    q.Enqueue(10)\n    q.Enqueue(\"Hello\")\n    q.Enqueue(20)\n    fmt.Println(q)\n    fmt.Println(q.Dequeue())\n    fmt.Println(q.Dequeue())\n    fmt.Println(q)\n}\n"
  },
  {
    "path": "data_structures/queue/java/IterableQueue.java",
    "content": "import java.util.Iterator;\nimport java.util.NoSuchElementException;\n\npublic class IterableQueue<E> implements Iterable<E> {\n    private Node<E> first;    // beginning of queue\n    private Node<E> last;     // end of queue\n    private int n;            // number of elements on queue\n\n    // helper linked list class\n    private static class Node<E> {\n        private E element;\n        private Node<E> next;\n    }\n\n    /**\n     * Initializes an empty queue.\n     */\n    public IterableQueue() {\n        first = null;\n        last  = null;\n        n = 0;\n    }\n\n    /**\n     * Returns true if this queue is empty.\n     *\n     * @return {@code true} if this queue is empty; {@code false} otherwise\n     */\n    public boolean isEmpty() {\n        return first == null;\n    }\n\n    /**\n     * Returns the number of items in this queue.\n     *\n     * @return the number of items in this queue\n     */\n    public int size() {\n        return n;\n    }\n\n    /**\n     * Returns the element least recently added to this queue.\n     *\n     * @return the element least recently added to this queue\n     * @throws NoSuchElementException if this queue is empty\n     */\n    public E peek() {\n        if (isEmpty()) throw new NoSuchElementException(\"Queue underflow\");\n        return first.element;\n    }\n\n    /**\n     * Adds the element to this queue.\n     *\n     * @param  element the element to add\n     */\n    public void enqueue(E element) {\n        Node<E> oldLast = last;\n        last = new Node<E>();\n        last.element = element;\n        last.next = null;\n        if (isEmpty()) first = last;\n        else           oldLast.next = last;\n        n++;\n    }\n\n    /**\n     * Removes and returns the element on this queue that was least recently added.\n     *\n     * @return the element on this queue that was least recently added\n     * @throws NoSuchElementException if this queue is empty\n     */\n    public E dequeue() {\n        if (isEmpty()) throw new NoSuchElementException(\"Queue underflow\");\n        E element = first.element;\n        first = first.next;\n        n--;\n        if (isEmpty()) last = null;   // to avoid loitering\n        return element;\n    }\n\n    /**\n     * Returns a string representation of this queue.\n     *\n     * @return the sequence of items in FIFO order, separated by spaces\n     */\n    public String toString() {\n        StringBuilder s = new StringBuilder();\n        for (E element : this) {\n            s.append(element);\n            s.append(' ');\n        }\n        return s.toString();\n    }\n\n    /**\n     * Returns an iterator that iterates over the items in this queue in FIFO order.\n     *\n     * @return an iterator that iterates over the items in this queue in FIFO order\n     */\n    public Iterator<E> iterator()  {\n        return new ListIterator<E>(first);\n    }\n\n    // an iterator, doesn't implement remove() since it's optional\n    private class ListIterator<Item> implements Iterator<Item> {\n        private Node<Item> current;\n\n        public ListIterator(Node<Item> first) {\n            current = first;\n        }\n\n        public boolean hasNext()  { return current != null;                     }\n        public void remove()      { throw new UnsupportedOperationException();  }\n\n        public Item next() {\n            if (!hasNext()) throw new NoSuchElementException();\n            Item item = current.element;\n            current = current.next;\n            return item;\n        }\n    }\n}\n"
  },
  {
    "path": "data_structures/queue/javascript/queue_ES5.js",
    "content": "function Queue() {\n    this._oldestIndex = 1;\n    this._newestIndex = 1;\n    this._storage = {};\n}\n \nQueue.prototype.size = function() {\n    return this._newestIndex - this._oldestIndex;\n};\n \nQueue.prototype.enqueue = function(data) {\n    this._storage[this._newestIndex] = data;\n    this._newestIndex++;\n};\n \nQueue.prototype.dequeue = function() {\n    var oldestIndex = this._oldestIndex,\n        newestIndex = this._newestIndex,\n        deletedData;\n \n    if (oldestIndex !== newestIndex) {\n        deletedData = this._storage[oldestIndex];\n        delete this._storage[oldestIndex];\n        this._oldestIndex++;\n \n        return deletedData;\n    }\n};\n"
  },
  {
    "path": "data_structures/queue/javascript/queue_ES6.js",
    "content": "class Queue {\n    constructor() {\n        this._oldestIndex = 1;\n        this._newestIndex = 1;\n        this._storage = {};\n    }\n\n    size() {\n        return this._newestIndex - this._oldestIndex;\n    }\n\n    enqueue(data) {\n        this._storage[this._newestIndex] = data;\n        this._newestIndex++;\n    }\n\n    dequeue() {\n        let oldestIndex = this._oldestIndex;\n        let newestIndex = this._newestIndex;\n        let deletedData;\n\n        if (oldestIndex !== newestIndex) {\n            deletedData = this._storage.oldestIndex;\n            delete this._storage.oldestIndex;\n            this._oldestIndex++;\n\n            return deletedData;\n        }\n    }\n}\n"
  },
  {
    "path": "data_structures/queue/kotlin/IterableQueue.kt",
    "content": "import java.util.NoSuchElementException\n\nclass IterableQueue<E> : Iterable<E> {\n    private var first: Node<E>? = null    // beginning of queue\n    private var last: Node<E>? = null     // end of queue\n    private var n: Int = 0            // number of elements on queue\n\n    // helper linked list class\n    private class Node<E> {\n        internal var element: E? = null\n        internal var next: Node<E>? = null\n    }\n\n    /**\n     * Initializes an empty queue.\n     */\n    init {\n        first = null\n        last = null\n        n = 0\n    }\n\n    /**\n     * Returns true if this queue is empty.\n\n     * @return `true` if this queue is empty; `false` otherwise\n     */\n    val isEmpty: Boolean\n        get() = first == null\n\n    /**\n     * Returns the number of items in this queue.\n\n     * @return the number of items in this queue\n     */\n    fun size(): Int {\n        return n\n    }\n\n    /**\n     * Returns the element least recently added to this queue.\n\n     * @return the element least recently added to this queue\n     * *\n     * @throws NoSuchElementException if this queue is empty\n     */\n    fun peek(): E {\n        if (isEmpty) throw NoSuchElementException(\"Queue underflow\")\n        return first!!.element!!\n    }\n\n    /**\n     * Adds the element to this queue.\n\n     * @param  element the element to add\n     */\n    fun enqueue(element: E) {\n        val oldLast = last\n        last = Node<E>()\n        last!!.element = element\n        last!!.next = null\n        if (isEmpty)\n            first = last\n        else\n            oldLast!!.next = last\n        n++\n    }\n\n    /**\n     * Removes and returns the element on this queue that was least recently added.\n\n     * @return the element on this queue that was least recently added\n     * *\n     * @throws NoSuchElementException if this queue is empty\n     */\n    fun dequeue(): E {\n        if (isEmpty) throw NoSuchElementException(\"Queue underflow\")\n        val element = first!!.element\n        first = first!!.next\n        n--\n        if (isEmpty) last = null   // to avoid loitering\n        return element!!\n    }\n\n    /**\n     * Returns a string representation of this queue.\n\n     * @return the sequence of items in FIFO order, separated by spaces\n     */\n    override fun toString(): String {\n        val s = StringBuilder()\n        for (element in this) {\n            s.append(element)\n            s.append(' ')\n        }\n        return s.toString()\n    }\n\n    /**\n     * Returns an iterator that iterates over the items in this queue in FIFO order.\n\n     * @return an iterator that iterates over the items in this queue in FIFO order\n     */\n    override fun iterator(): Iterator<E> {\n        return ListIterator(first)\n    }\n\n    // an iterator, doesn't implement remove() since it's optional\n    private inner class ListIterator<Item>(private var current: Node<Item>?) : Iterator<Item> {\n\n        override fun hasNext(): Boolean {\n            return current != null\n        }\n\n        override fun next(): Item {\n            if (!hasNext()) throw NoSuchElementException()\n            val item = current!!.element\n            current = current!!.next\n            return item!!\n        }\n    }\n}\n"
  },
  {
    "path": "data_structures/queue/php/queue.php",
    "content": "<?php\n\n/**\n * Class Queue by Bennett Treptow\n * Pretty trivial implementation\n * PHP arrays and array_shift do the hard work\n */\nclass Queue {\n    /**\n     * @var array\n     */\n    protected $_data = [];\n\n    /**\n     * Queue constructor.\n     * @param null $data\n     */\n    public function __construct($data = null){\n        if(!is_null($data)){\n            foreach($data as $item){\n                $this->enqueue($item);\n            }\n        }\n    }\n\n    /**\n     * @return int\n     */\n    public function size(){\n        return count($this->_data);\n    }\n\n    /**\n     * @param $item\n     */\n    public function enqueue($item){\n        $this->_data[] = $item;\n    }\n\n    /**\n     * @return mixed\n     * @throws Exception\n     */\n    public function dequeue(){\n        if($this->size() > 0){\n            return array_shift($this->_data);\n        } else {\n            throw new Exception('Can\\'t dequeue an empty queue!');\n        }\n    }\n}\n\n$queue = new Queue(['1','2','3','4']);\n$queue->dequeue(); //1\n$queue->enqueue('5'); //2,3,4,5\n?>"
  },
  {
    "path": "data_structures/queue/python/queue_two_stacks.py",
    "content": "def get_command():\n    parts = input().strip().split(' ')\n    command = int(parts[0])\n\n    if len(parts) == 1:\n        return (command, None)\n    try:\n        arg = int(parts[1])\n    except ValueError:\n        arg = parts[1]\n\n    return command, arg\n\n\nclass Stack:\n    def __init__(self):\n        self._l = []\n\n    def __len__(self):\n        return len(self._l)\n\n    def push(self, data):\n        self._l.append(data)\n\n    def pop(self):\n        return self._l.pop()\n\n    def top(self):\n        if self._l:\n            return self._l[-1]\n        return None\n\n\nclass Queue:\n    def __init__(self):\n        self._head = Stack()\n        self._tail = Stack()\n\n    def enqueue(self, data):\n        self._tail.push(data)\n\n    def dequeue(self):\n        if self._head:\n            return self._head.pop()\n\n        return self._tail_to_head().pop()\n\n    def peek(self):\n        if self._head:\n            return self._head.top()\n\n        return self._tail_to_head().top()\n\n    def _tail_to_head(self):\n        while self._tail:\n            self._head.push(self._tail.pop())\n\n        return self._head\n\n\ndef main():\n\n    queue = Queue()\n\n    command_no = int(input().strip())\n    for _ in range(command_no):\n        command, arg = get_command()\n        if command == ENQUEUE:\n            queue.enqueue(arg)\n        elif command == DEQUEUE:\n            queue.dequeue()\n        elif command == PRINT:\n            print(queue.peek())\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "data_structures/queue/ruby/queue.rb",
    "content": "class Queue\n    def initialize\n        @store = Array.new\n    end\n\n    def enqueue(data)\n        @store.push(data)\n    end\n\n    def dequeue()\n        raise Exception if size == 0\n        @store.shift\n    end\n\n    def front()\n        raise Exception if size == 0\n        @store.first\n    end\n\n    def back()\n        @store.last\n    end\n\n    def size()\n        @store.size\n    end\nend\n\n# Usage\nQ = Queue.new\nQ.enqueue(1)\nQ.enqueue(2)\nQ.enqueue(3)\n\nputs Q.front()\nputs Q.back()\n\nputs Q.dequeue()\nputs Q.dequeue()"
  },
  {
    "path": "data_structures/simple_queue/java/QueueImplementation.java",
    "content": "import java.util.Scanner;\n\n/* Class QueueImplement  */\npublic class QueueImplementation\n{\n    public static void main(String[] args)\n    {\n        Scanner scan = new Scanner(System.in);\n\n        System.out.println(\"Array Queue Test\\n\");\n        System.out.println(\"Enter Size of Integer Queue \");\n        int n = scan.nextInt();\n        /* creating object of class arrayQueue */\n        arrayQueue q = new arrayQueue(n);        \n        /* Perform Queue Operations */\n        char ch;\n        do{\n            System.out.println(\"\\nQueue Operations\");\n            System.out.println(\"1. insert\");\n            System.out.println(\"2. remove\");\n            System.out.println(\"3. peek\");\n            System.out.println(\"4. check empty\");\n            System.out.println(\"5. check full\");\n            System.out.println(\"6. size\");\n            int choice = scan.nextInt();\n            switch (choice)\n            {\n                case 1 :\n                    System.out.println(\"Enter integer element to insert\");\n                    try\n                    {\n                        q.insert( scan.nextInt() );\n                    }\n                    catch(Exception e)\n                    {\n                        System.out.println(\"Error : \" +e.getMessage());\n                    }\n                    break;\n                case 2 :\n                    try\n                    {\n                        System.out.println(\"Removed Element = \"+q.remove());\n                    }\n                    catch(Exception e)\n                    {\n                        System.out.println(\"Error : \" +e.getMessage());\n                    }\n                    break;\n                case 3 :\n                    try\n                    {\n                        System.out.println(\"Peek Element = \"+q.peek());\n                    }\n                    catch(Exception e)\n                    {\n                        System.out.println(\"Error : \"+e.getMessage());\n                    }\n                    break;\n                case 4 :\n                    System.out.println(\"Empty status = \"+q.isEmpty());\n                    break;\n                case 5 :\n                    System.out.println(\"Full status = \"+q.isFull());\n                    break;\n                case 6 :\n                    System.out.println(\"Size = \"+ q.getSize());\n                    break;\n                default : System.out.println(\"Wrong Entry \\n \");\n                    break;\n            }\n            /* display Queue */\n            q.display();\n            System.out.println(\"\\nDo you want to continue (Type y or n) \\n\");\n            ch = scan.next().charAt(0);\n\n        } while (ch == 'Y'|| ch == 'y');\n    }\n}"
  },
  {
    "path": "data_structures/simple_queue/java/arrayQueue.java",
    "content": "/*\n * Java Program to Implement Queue\n */\n\nimport java.util.*;\n\n/*  Class arrayQueue  */\nclass arrayQueue {\n    protected int Queue[] ;\n    protected int front, rear, size, len;\n\n    /* Constructor */\n    public arrayQueue(int n)\n    {\n        size = n;\n        len = 0;\n        Queue = new int[size];\n        front = -1;\n        rear = -1;\n    }\n    /*  Function to check if queue is empty */\n    public boolean isEmpty()\n    {\n        return front == -1;\n    }\n    /*  Function to check if queue is full */\n    public boolean isFull()\n    {\n        return front==0 && rear == size -1 ;\n    }\n    /*  Function to get the size of the queue */\n    public int getSize()\n    {\n        return len ;\n    }\n    /*  Function to check the front element of the queue */\n    public int peek()\n    {\n        if (isEmpty())\n            throw new NoSuchElementException(\"Underflow Exception\");\n        return Queue[front];\n    }\n    /*  Function to insert an element to the queue */\n    public void insert(int i)\n    {\n        if (rear == -1)\n        {\n            front = 0;\n            rear = 0;\n            Queue[rear] = i;\n        }\n        else if (rear + 1 >= size)\n            throw new IndexOutOfBoundsException(\"Overflow Exception\");\n        else if ( rear + 1 < size)\n            Queue[++rear] = i;\n        len++ ;\n    }\n    /*  Function to remove front element from the queue */\n    public int remove()\n    {\n        if (isEmpty())\n            throw new NoSuchElementException(\"Underflow Exception\");\n        else\n        {\n            len-- ;\n            int ele = Queue[front];\n            if ( front == rear)\n            {\n                front = -1;\n                rear = -1;\n            }\n            else\n                front++;\n            return ele;\n        }\n    }\n    /*  Function to display the status of the queue */\n    public void display()\n    {\n        System.out.print(\"\\nQueue = \");\n        if (len == 0)\n        {\n            System.out.print(\"Empty\\n\");\n            return ;\n        }\n        for (int i = front; i <= rear; i++)\n            System.out.print(Queue[i]+\" \");\n        System.out.println();\n    }\n}"
  },
  {
    "path": "data_structures/simple_queue/java/queue.java",
    "content": "import java.util.*;\ninterface queue\n{\n\tvoid insert();\n\tvoid delete();\n\tvoid display();\n\t\n}\nclass myqueue implements queue\n{\n\tint arr[]=new int[10];\n\tint front=0,rear=0;\n\tScanner s1 = new Scanner(System.in);\n\tpublic void insert()\n\t{\n\t\tif (rear>10)\n\t\t\tSystem.out.println(\"queue overflow\");\n\t\telse\n\t\t{\n\t\t\tint a;\n\t\t\tSystem.out.println(\"enter element:\");\n\t\t\ta=s1.nextInt();\n\t\t\tarr[rear]=a;\n\t\t\trear++;\n\t\t}\n\t}\npublic void delete()\n\t{\n\t\tif (rear==front)\n\t\t\tSystem.out.println(\"queue is empty\");\n\t\telse\n\t\t{\n\t\t\tint a;\n\t\t\ta=arr[front];\n\t\t\tfront++;\n\t\t\tSystem.out.println(\"element deleted : \"+a );\n\t\t}\n\t}\n\tpublic void display()\n\t{\n\t\tSystem.out.println(\"elements are\");\n\t\tfor(int i=front;i<rear;i++)\n\t\t{\n\t\t\tSystem.out.println(arr[i]);\n\t\t}\n\t}\n}\nclass tut6\n{\npublic static void main(String args[])\n{\n\tScanner s = new Scanner(System.in);\n\t\tmyqueue m = new myqueue();\n\t\tboolean b= true;\n\t\twhile(b)\n\t\t{\n\t\tSystem.out.println(\"enter ur choices \\n 1. push \\n 2. pop \\n 3. display \\n 4. exit\");\n\t\tint n;\n\t\tn=s.nextInt();\n\t\t\n\t\t\n\t\tswitch(n)\n\t\t{\n\t\tcase 1:\n\t\tm.insert();\n\t\tbreak;\n\t\tcase 2:\n\t\tm.delete();\n\t\tbreak;\n\t\tcase 3:\n\t\tm.display();\n\t\tbreak;\n\t\tcase 4:\n\t\tSystem.exit(0);\n\t\t}\n\t\t}\n\t}\n}\n\n"
  },
  {
    "path": "data_structures/simple_queue/python/queue.py",
    "content": "class Queue:\n    def __init__(self):\n        self.data = []\n\n    def enqueue(self, item):\n        self.data.insert(0, item)\n\n    def dequeue(self):\n        return self.data.pop()\n\n    def peek(self):\n        return self.data[-1]\n"
  },
  {
    "path": "data_structures/simple_queue/simple_queue.md",
    "content": "## ELI5\nQUEUE: Queue is a list of elements where elements are removed in the order they were added. First come, first serve basis like in actual queues at ticket counters.\nUSE: Used when we want to process items in a first in,first out order.\n\n### Pros\n* Fast to add and remove items from the list.\n### Cons\n* Searching a queue is difficult.\n* Wastage of space/memory when front items have been removed.\n\n## Technical Explaination\nA queue or FIFO (first in, first out) is an abstract data type(ADT) that serves as a collection of elements on which we perform these main operations:\n* enqueue: Adding element to queue\n* deque: Extracting element from queue\nTwo pointer variables : FRONT and REAR\nFRONT of a queue points to the first element that will be dequed and REAR is pointer the last element of the queue.\nFor a queue = 8,4,5,6,7,_. (FRONT=1,REAR=5)\nenqueue(0) gives queue = 8,4,5,6,7,0.    (REAR = REAR+1)(FRONT =1,REAR=6)\ndequeue() gives queue  = _,4,5,6,7,0.    (FRONT = FRONT +1)(FRONT=2,REAR=6)\nFirst element of queue is removed from queue and returned via dequeue.\nUSE: Used when multiple processes are waiting for a resourse.e.g. Disk scheduliing.\n### Pros\n*Time complexity of all operations like enqueue(), dequeue(), isFull(), isEmpty(), front() and rear() is O(1)\n* It can be implemented by using both array and linked list.\n\n\n### Cons\n* Not readily searchable.\n* Wastage of memory space.Once queue becomes full, we can not insert the next element even if there is a space in front of queue.\ni.e. For N size queue.After N insertions REAR points to N. When queue is dequed(<=N) times then FRONT = i. Now, enqueue will add items at REAR+1 only and since size is N, no new insertions take place even though queue has few elements.\nWE USE CIRCULAR QUEUE TO SAVE MEMORY SPACE.\n"
  },
  {
    "path": "data_structures/stack/c/stack1.c",
    "content": "#include<stdio.h>\n#include<stdlib.h>\n\n\nstruct node{\n int data;\nstruct node* next;\n};\n\nstruct node* head;\nvoid insertatthebegin(int x)\n{\n struct node* temp=(struct node*)malloc(sizeof(struct node));\n temp->data=x;\n temp->next=head;\n head=temp;\n \n}\n\n\nvoid print()\n{\n struct node* temp=head;\n \nif(temp== NULL)\n printf(\"empty list\\n\");\nelse{\n while(temp!=NULL)\n   {\n    printf(\"%d \",temp->data);\n    temp=temp->next;\n   }\n}\nprintf(\"\\n\"); \n \n}\n\n\nvoid reverse()\n{\n struct node* prev, *current , *next;\n prev=NULL;\n\ncurrent=head;\n\nwhile(current !=NULL)\n{\n next=current->next;\n current->next=prev;\n prev=current;\ncurrent=next;\n}\nhead=prev;\n\n}\n\nint main()\n{\nint i,j,n,k,l,x;\n head=NULL;\nprintf(\"enter the number of elements\\n\");\nscanf(\"%d\",&n);\n\nprintf(\"enter the elements and the position\\n\");\nfor(i=0;i<n;i++)\n{\n scanf(\"%d\",&x);\n insertatthebegin(x);\n//print();\n}\nprint();\n\nreverse();\n printf(\"the reversed linked list is \\n\");\nprint();\n\n\nreturn 0;\n}\n\n\n"
  },
  {
    "path": "data_structures/stack/c#/main.cs",
    "content": "using System; \nusing System.Collections.Generic;\nnamespace Stack{\n        public class main{\n            static void Main(){\n                Stack<int> stack = new Stack<int>();\n                stack.Push(1);\n                stack.Push(3);\n                Console.WriteLine(stack.Top());\n                stack.Pop();\n                Console.WriteLine(stack.Top());\n                \n            }\n        }\n}"
  },
  {
    "path": "data_structures/stack/c#/stack.cs",
    "content": "using System; \nusing System.Collections.Generic;\n \nnamespace Stack{\n   public class Stack<t>  {\n        private List<t> _array;     // Storage for stack elements \n        private int _size;       \n        private int _top;    // Number of items in the stack.\n        static List<t> _emptyArray = new List<t>(); \n        public Stack(){\n            \n            _array = _emptyArray;\n            _size = 0; \n            _top = -1;\n            \n        }\n        public void Push(t data){\n            _array.Add(data);\n            _size++;\n            _top++;\n        }\n        public void Pop(){\n            _array.RemoveAt(_top--);\n        }\n        public t Top(){\n            return _array[_top];\n        }\n    }\n}\n\n      \n"
  },
  {
    "path": "data_structures/stack/cpp/celement.h",
    "content": "#ifndef CELEMENT_H\n#define CELEMENT_H\n\n/**\n * An element of a CStack : contains a char value and a pointer to the element just below in the stack\n */\nstruct CElement {\n\tCElement *_element_below;\t\t//Next element in the stack\n\tchar _val;\n};\n\n#endif // CELEMENT_H included\n"
  },
  {
    "path": "data_structures/stack/cpp/cstack.cpp",
    "content": "// Implementation File\n\n#include \"cstack.h\"\nusing namespace std;\n\n// Default Constructor to allow for no params being passed\nCStack::CStack()\n{\n    // Init top to be nullptr, stack is empty\n    _top = nullptr;\n};\n// Destructor to free memory\nCStack::~CStack()\n{\n    while (!IsEmpty())\n    {\n        Pop ();\n    }\n}\n// Removes value from the top of the stack\nvoid CStack::Pop()\n{\n    // Check if the array isnt empty, then pop off top stack value\n    if (!IsEmpty())\n    {\n        CElement *new_top = _top->_element_below;\n        delete _top;        //Do not forget to free memory\n        _top = new_top;\n    }\n}\n// Pushes new value to the top of the stack\nvoid CStack::Push(char val)\n{\n    CElement *new_top = new CElement();     //Allocate memory for the new top element\n    new_top->_element_below = _top;\n    new_top->_val = val;\n    _top = new_top;\n}\n// Returns value at top of the stack\nchar CStack::Top()\n{\n    // If array is empty, return null character\n    if (IsEmpty())\n    {\n        return '\\0';\n        // Else return top Stack value\n    }\n    else\n    {\n        return _top->_val;\n    }\n}\n// Checks whether the stack is empty, returns bool\nbool CStack::IsEmpty()\n{\n    return _top == nullptr;\n}\n"
  },
  {
    "path": "data_structures/stack/cpp/cstack.h",
    "content": "\n#ifndef CSTACK_H\n#define CSTACK_H\n\n#include \"celement.h\"\n\n// Header File\nclass CStack\n{\n  public:\n    CStack(const CStack&) = delete;             //Forbid usage of Copy Constructor because we use raw pointers\n    CStack& operator=(const CStack&) = delete;  //Forbid usage of copy assignment for the same reason\n    CStack();\n    ~CStack();\n    char Top();\n    void Pop();\n    void Push(char);\n    bool IsEmpty();\n\n  private:\n    CElement *_top;\n};\n#endif\n"
  },
  {
    "path": "data_structures/stack/cpp/cstack.test.cpp",
    "content": "#include <iostream>\n#include \"cstack.h\"\n\nusing namespace std;\n\nint main()\n{\n    char input; \n    CStack stack;\n\n    // Prompt user for expression\n    cout << \"Please Enter an expression (must end with the EOF character) : \";      //EOF is CTRL^D (Linux) or CTRL^Z (Windows)\n    \n    // Fill stack with char values\n    while(cin >> input) {\n        stack.Push(input);\n    }\n\n    // Show LIFO\n    cout << endl;\n    while(!stack.IsEmpty()){\n        cout << stack.Top();\n        stack.Pop();\n    }\n    cout << endl;\n    return 0;\n}\n"
  },
  {
    "path": "data_structures/stack/cpp/stack_balanced_paranthesis.cpp",
    "content": "\n#include<iostream>\n#include<stack>\nusing namespace std;\n\nint main()\n{\n    int t;\n    cout<<\"Enter no of test cases\";\n    cin>>t;\n    string s=\" \";\n\n    while(t--)\n    {\n         stack<char> st;\n         cout<<\"\\nEnter the string\\n\";\n         cin>>s;\n         int flag=0;\n         for(int i=0;i<s.size();i++)\n         {\n            // cout<<s.size();\n             if(s[i]=='(' || s[i]=='{'|| s[i]=='[')\n                    st.push(s[i]);\n             else if(s[i]==']' || s[i]=='}' || s[i]==')')\n             {  if((!st.empty()) && ((s[i]==')' && st.top()=='(') || (s[i]=='}' && st.top()=='{') || (s[i]==']' && st.top()=='[')))\n                st.pop();\n                else\n                {\n                    //cout<<\"NO\"<<endl;\n                    flag=1;\n                    break;\n                }\n             }\n         }\n         if(st.empty() && flag==0) cout<<\"YES\"<<endl;\n         else if(!st.empty() || flag==1) cout<<\"NO\"<<endl;\n    }\n    return 0;\n}\n"
  },
  {
    "path": "data_structures/stack/cpp/templated_stack.cpp",
    "content": "#include <exception>\n#include <iostream>\n\n#include \"Stack.hpp\"\n\n/*\n * Main is only used to test different\n * methods on my stack\n *\n */\n\nint main(void) {\n\tStack<int> s;\n\n\tstd::cout << \"Initializing stack\" << std::endl;\n\n\tfor (int i = 0; i < 10; ++i)\n\t\ts.push(i);\n\n\tstd::cout << \"Done!\" << std::endl;\n\n\twhile ( !s.empty() )\n\t{\n\t\tstd::cout << s.top() << std::endl;\n\t\ts.pop();\n\t}\n\n\tstd::cout << \"Popping off another (inexistant) element\" << std::endl;\n\n\ttry \n\t{\n\t\ts.pop();\n\t} \n\tcatch (std::exception& e)\n\t{\n\t\tstd::cerr << \"[ERR] \" << e.what() << std::endl;\n\t}\n\n\treturn 0;\n}\n"
  },
  {
    "path": "data_structures/stack/cpp/templated_stack.hpp",
    "content": "#ifndef STACK_H\n#define STACK_H\n\n#include <stdexcept>\n\n/*\n * Templated class declaration and definition\n * in a single file for portability\n *\n */\ntemplate <typename Object>\nclass Stack {\nprivate:\n\tclass Node {\n\tfriend Stack;\n\tprivate:\n\t\tNode * next;\n\t\tObject data;\n\tpublic:\n\t\tNode(const Object & d, Node * n): \n\t\t\tdata(d), next(n) {  }\n\t};\n\n\tint length {0};\n\tNode * head {nullptr};\n\npublic:\n\t// Default ctor but clear on destruction\n\tStack() {  };\n\t~Stack() { clear(); };\n\n\t// Returns the number of elements in the stack\n\tint size() { \n\t\treturn length; \n\t}\n\n\t// Adds an element on top of the stack\n\tvoid push(const Object & value) {\n\t\thead = new Node(value, head);\n\t\t++length;\n\t}\n\n\t// Returns top element form the stack\n\tObject top() {\n\t\tif ( head != nullptr )\n\t\t\treturn head->data;\n\t\tthrow std::logic_error(\"Cannot return top from an empty stack\");\n\t}\n\n\t// Removes top element from the stack\n\tvoid pop() {\n\t\tif ( head != nullptr )\n\t\t{\n\t\t\tNode * tmp {head};\n\t\t\thead = head->next;\n\t\t\t--length;\n\t\t\tdelete tmp;\n\t\t} else\n\t\t\tthrow std::logic_error(\"Cannot remove top from an empty stack\");\n\t}\n\n\t// Tests wether or not the stack is empty\n\tbool empty() { \n\t\treturn length == 0; \n\t}\n\n\t// Removes all element from the stack\n\tvoid clear() {\n\t\twhile ( !empty() )\n\t\t\tpop();\n\t}\n};\n#endif\n"
  },
  {
    "path": "data_structures/stack/crystal/stack.cr",
    "content": "class Stack(T)\n  @size : Int32\n\n  def initialize(@stack : Array(T))\n    @size = @stack.size\n  end\n\n  # Returns size (Implicit return)\n  def push(item : T)\n    @stack << item\n    @size += 1\n  end\n\n  # Returns size (Implicit return)\n  def pop()\n    @stack.pop\n    @size -= 1\n  end\n\n  def peek()\n    @stack.last\n  end\n\n  def size()\n    @size\n  end\nend\n\n# Union together Types you might need since crystal is type-checked at compile time\n# You'll get an error if you try and push a type that isn't in the union\nstack = Stack.new([] of Int32|String)\n\nputs stack.size()         # ==> 0\nstack.push(30)            # ==> [30]\nstack.push(\"Hello\")       # ==> [30, \"hello\"]\nstack.pop()               # ==> 1\nputs stack.peek()         # ==> 30\n\n"
  },
  {
    "path": "data_structures/stack/csharp/Stack.cs",
    "content": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace DataStructures\n{\n    class Stack\n    {\n        private List<Object> items = new List<Object>();\n\n        public Object pop()\n        {\n            if (items.Count > 0)\n            {\n                int lastPos = items.Count - 1;\n                Object temp = items[lastPos];\n                items.RemoveAt(lastPos);\n                return temp;\n            }\n            else\n            {\n                throw new Exception(\"Underflow: Stack is empty\");\n            }\n        }\n\n        public void push(Object newItem)\n        {\n            items.Add(newItem);\n        }\n\n\n        public bool isEmpty()\n        {\n            return (items.Count == 0);\n        }\n\n    }\n}\n"
  },
  {
    "path": "data_structures/stack/go/stack.go",
    "content": "package main\n\ntype stack struct {\n\tdata []interface{}\n}\n\nfunc (s *stack) Push(value interface{}) {\n\ts.data = append(s.data, value)\n}\n\nfunc (s *stack) Pop() interface{} {\n\t//get last item\n\tvalue := s.data[len(s.data)-1]\n\t//shrink array\n\ts.data = s.data[0 : len(s.data)-1]\n\n\treturn value\n}\n"
  },
  {
    "path": "data_structures/stack/java/Node.java",
    "content": "import java.util.*;\n\npublic class Node<T>{\n  private T data;\n  private Node nextNode;\n  private Node previewNode;\n  private int index;\n\n  public Node(T data){\n    this.data = data;\n    this.nextNode = null;\n    this.previewNode = null;\n    this.index = 0;\n  }\n\n  public Node(){\n    this.data = null;\n    this.nextNode = null;\n    this.previewNode = null;\n    this.index = 0;\n  }\n\n  public T getData(){\n    return this.data;\n  }\n\n  public void setData(T data){\n    this.data = data;\n  }\n\n  public int getIndex(){\n    return this.index;\n  }\n\n  public void setNext(Node node){\n    this.nextNode = node;\n  }\n\n  public Node getNext(){\n      return this.nextNode;\n  }\n\n  public void setPreview(Node node){\n    this.previewNode = node;\n  }\n\n  public Node getPreview(){\n      return this.previewNode;\n  }\n}\n"
  },
  {
    "path": "data_structures/stack/java/Stack.java",
    "content": "import java.util.*;\n\npublic class Stack<T>{\n  private Node topNode;\n  private int size;\n\n  public Stack(){\n    this.topNode = null;\n    this.size = 0;\n  }\n\n  public boolean isEmpty(){\n    return this.size == 0;\n  }\n\n  public void push(T data){\n    Node node = new Node<T>();\n    node.setData(data);\n    if(!isEmpty()){\n      node.setPreview(this.topNode);\n      this.topNode.setNext(node);\n      this.topNode = node;\n    }else{\n      this.topNode = node;\n    }\n    this.size++;\n  }\n\n  public T top(){\n    if(!isEmpty()){\n      return (T) this.topNode;\n    }\n    return null;\n  }\n\n  public void pop(){\n    if(!isEmpty()){\n      if(this.size == 1){\n        this.topNode = null;\n      }else{\n        Node a = this.topNode.getPreview();\n        a.setNext(null);\n        this.topNode = a;\n      }\n      this.size--;\n    }else{\n      System.out.println(\"There is no object on the stack!\");\n    }\n  }\n\n  public void viewStack(){\n    if(!isEmpty()){\n      Node node = this.topNode;\n      while(node != null){\n        System.out.println(node.getData());\n        node = node.getPreview();\n      }\n    }else{\n      System.out.println(\"Stack is Empty!\");\n    }\n  }\n\n    public static void main(String[] args) {\n      Stack s = new Stack<>();\n      s.push(\"a\");\n      s.push(\"aa\");\n      s.push(\"aaa\");\n      s.push(\"aaaa\");\n\n      s.viewStack();\n      System.out.println(\"-------------------------\");\n      s.pop();\n      s.viewStack();\n      System.out.println(\"-------------------------\");\n      s.pop();\n      s.viewStack();\n      System.out.println(\"-------------------------\");\n      s.pop();\n      s.viewStack();\n      System.out.println(\"-------------------------\");\n      s.pop();\n      s.viewStack();\n      System.out.println(\"-------------------------\");\n    }\n\n}\n"
  },
  {
    "path": "data_structures/stack/java/integer_stack.java",
    "content": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class Stack {\n    private List<Integer> _data = new ArrayList<Integer>();\n    private int _top = -1;\n    public Stack(){\n\n    }\n    public void Push(int val){\n        _top++;\n        _data.add(val);\n    }\n\n    public void Pop(){\n        if(!isEmpty())\n            _data.remove(_top--);\n        else\n            System.out.println(\"Queue Is Empty\");\n    }\n\n    public int Top(){\n        return _data.get(_top);\n    }\n    private boolean isEmpty(){\n        return _top == -1;\n    }\n}\n\n"
  },
  {
    "path": "data_structures/stack/javascript/stack.js",
    "content": "'use strict';\nexport default function Stack(maxSize = null) {\n    // Private variables\n    let _data = [];\n    let _top = -1;\n    // Helper function to check if the stack is empty\n    function _checkEmpty() {\n        return _top === -1;\n    }\n    // Helper function to check if the stack is full\n    function _checkFull() {\n        return maxSize === null ? false : _top >= maxSize - 1;\n    }\n    // Error Helper Function to help display\n    // when Stack is empty or full\n    function throwError(message) {\n        throw new Error(message);\n        return true;\n    }\n    // Return Object\n    let _Stack = {\n        // Returns Top Data\n        Top: () => {\n            return _data[_top] !== undefined ? _data[_top] : null;\n        },\n        // Void, adds new Data\n        Push: data => {\n            !_checkFull() ? (_data[++_top] = data) : throwError('Stack is full');\n        },\n        // Void, removes Data\n        Pop: () => {\n            !_checkEmpty() ? _data.splice(_top--, 1) : throwError('Stack is empty');\n        },\n        // Void, logs Top Data\n        Log: () => {\n            console.log(this.Top());\n        },\n        // Void , logs all Data\n        LogAll: () => {\n            for (let i = 0; i < _top; i++) {\n                console.log(_data[i]);\n            }\n        },\n    };\n    return _Stack;\n}\n// Test the Code\n\n// let _ = data => {\n//     console.log(data);\n// };\n// let stack = new Stack();\n\n// try {\n//     stack.Push(1);\n//     _(stack.Top());\n//     stack.Push(0b11);\n//     _(stack.Top());\n//     stack.Pop();\n//     _(stack.Top());\n// } catch (e) {\n//     _(e.message);\n// }\n\n"
  },
  {
    "path": "data_structures/stack/javascript/usingstack.js",
    "content": "import Stack from './stack';\nimport readline from 'readline';\n(async function  RunMe(){\n    let stack =  Stack();\n    let input;\n    const cin = readline.createInterface({\n        input: process.stdin,\n        output: process.stdout\n      });\n      \n       cin.question('Test the stack class, type something it will output it backwards. Aka LIFO: ', (answer) => {\n        input = answer;\n        cin.close();\n        for(let char of input){\n            stack.Push(char);\n        }\n        while(stack.Top()!==null){\n            console.log(stack.Top());\n            stack.Pop();\n        }\n      });\n      \n      \n})();\n\n"
  },
  {
    "path": "data_structures/stack/lisp/Stack.bak",
    "content": "(define (make-stack)\n\n  (define arr '())\n  (define length 0)\n  (define temp '())\n\n  (define (size)\n    length)\n\n  (define (pop)\n    (set! temp (car arr))\n    (set! arr (cons arr))\n    temp)\n\n  (define (dispatch method)\n    (cond ((eq? method 'size) size)\n          ((eq? method 'pop) pop)\n          (else (lambda() (display \"Unknown Stack Request\")(display method)(newline)))))\n\n  dispatch)"
  },
  {
    "path": "data_structures/stack/lisp/Stack.rkt",
    "content": "(define (make-stack)\n\n  ;backing structure\n  (define arr '())\n  (define length 0)\n  (define temp '())\n\n  ;size method\n  (define (size)\n    length)\n\n  ;print method\n  (define (print)\n    (display arr))\n\n  ;receiving mpair violation instead of exiting procedure call\n  ;pop method: removes the head and returns it\n  (define (pop)\n    (if (eqv? length 0) (display \"Can't Pop\"))\n    (set! length (- length 1))\n    (set! temp (cdr arr))\n    (set! arr (cdr arr))\n    temp)\n\n  ;push method: puts x at the head\n  (define (push x)\n    (set! length (+ length 1))\n    (set! arr (cons x arr)))\n\n  ;method to get method from user\n  (define (dispatch method)\n    (cond ((eq? method 'size) size)\n          ((eq? method 'pop) pop)\n          ((eq? method 'print) print)\n          ((eq? method 'push) push)\n          (else (lambda() (display \"Unknown Stack Request\")(display method)(newline)))))\n\n  dispatch)\n\n;how to use\n(define (testing)\n  (define stack (make-stack))\n  ((stack 'push) 0)\n  ((stack 'push) 1)\n  ((stack 'push) 2)\n  ((stack 'print))(newline)\n  ((stack 'pop))\n  ((stack 'print))(newline)\n  ((stack 'pop))\n  ((stack 'print))(newline)\n  ((stack 'pop))\n  ;((stack 'pop))\n  )\n\n(testing)\n  \n  "
  },
  {
    "path": "data_structures/stack/php/stack.php",
    "content": "<?php \nclass Stack { \n    private $_data = array();\n    private $_top = -1; \n    public function Pop(){\n        if($this->_top == -1){\n            throw new Exception(\"Stack is empty\");\n        }else{\n            $this->_top--;\n        }\n    }\n    public function Push($data) { \n\n        $this->_top++;\n        array_push($this->_data,$data);\n    } \n    public function Top(){\n        return $this->_data[$this->_top];\n    }\n    \n} \n\n$stack = new Stack(); \n$stack->Push(\"First Input\");\n$stack->Push(\"Second Input\");\n\necho $stack->Top();\n$stack->Pop();\necho $stack->Top();\n?> \n"
  },
  {
    "path": "data_structures/stack/python/stack.py",
    "content": "class Stack:\n    def __init__(self):\n        self.data = []\n\n    def push(self, item):\n        self.data.append(item)\n\n    def pop(self):\n        return self.data.pop()\n\n    def peek(self):\n        return self.data[-1]\n"
  },
  {
    "path": "data_structures/stack/ruby/stack.rb",
    "content": "class Stack\n    def initialize\n        @store = Array.new\n    end\n\n    def push(data)\n        @store.push(data)\n    end\n\n    def pop()\n        raise Exception if size == 0\n        @store.pop\n    end\n\n    def top()\n        raise Exception if size == 0\n        @store.last\n    end\n\n    def size()\n        @store.size\n    end\nend\n\n# Usage\nS = Stack.new\nS.push(1)\nS.push(2)\nS.push(3)\n\nputs S.top()\nputs S.size()\n\nputs S.pop()\nputs S.pop()"
  },
  {
    "path": "data_structures/treemap/java/treemap.java",
    "content": "import java.util.*;\nclass treemap {\n\n   public static void main(String args[]) {\n      // Create a hash map\n      TreeMap tm = new TreeMap();\n      \n      // Put elements to the map\n      tm.put(1, \"one\");\n      tm.put(2, \"two\");\n      tm.put(3,\"three\");\n      tm.put(1,\"ONE\");\n      tm.put(4,\"four\");\n      //storing values in key-value pairs with sorted order of keys, by eliminating duplicate keys\n      System.out.println(tm);//1-ONE,2-two,3-three,4-four\n   }\n}"
  },
  {
    "path": "data_structures/treeset/java/treeset.java",
    "content": "import java.util.*;\nclass treeset {\n\n   public static void main(String args[]) {\n      // Create a tree set\n      TreeSet ts = new TreeSet();\n     \n      // Add elements to the tree set\n      ts.add(3);\n      ts.add(2);\n      ts.add(3);\n      ts.add(2);\n      ts.add(1);\n      ts.add(4);\n      //Treeset is very helpful datastructure for avoid duplicatses and maintain the values in sorted order \n      System.out.println(ts);// output will be {1,2,3,4}\n   }\n}"
  },
  {
    "path": "data_structures/trie/Trie.md",
    "content": "## ELI5\nTrie is an information re'trie'val data container.It's a tree useful in searching strings.\nUSES:Autocomplete in text messages etc.\n### Pros\n* Searching is easier and faster.\n### Cons\n* Storage takes more space.\n\n## Technical Explaination\nA Trie, also called a digital tree or prefix tree, is a search tree that is used to store a dynamic set or associative array.The keys of a Trie are mostly strings.The postition of node in tree defines its key. All the descendants of a node have a common prefix of the string associated with that node, and the root is associated with the empty string.\nEach brach of tree represents a character.\n* isEndOfWord : It is the last node of a word.\n\n### Pros\n* Search in trie is O(M) where M is length of the key. Faster than BST.\n### Cons\n* Tries can be slower in some cases than hash tables for looking up data\n* Require more space.\n"
  },
  {
    "path": "data_structures/trie/java/Trie.java",
    "content": "import java.util.ArrayList;\n\npublic class Trie {\n    public class TrieNode {\n        TrieNode[] characters;\n        Boolean isEnd = false;\n\n        public TrieNode() {\n            characters = new TrieNode[26];\n        }\n    }\n\n    public static void main(String[] args) {\n        new Trie().demo();\n    }\n\n    private void demo() {\n        TrieNode trie = new TrieNode();\n        ArrayList<String> values = new ArrayList<String>() {{\n            add(\"MY\");\n            add(\"MANY\");\n            add(\"LIE\");\n            add(\"A\");\n            add(\"AS\");\n        }};\n        for (String s : values) {\n            add(trie, s);\n        }\n        displayTree(trie);\n    }\n\n    private void displayTree(TrieNode trie) {\n        for (int i = 0; i < trie.characters.length; i++) {\n            if (trie.characters[i] != null) {\n                DFS(trie.characters[i], new StringBuilder(), i);\n            }\n\n        }\n    }\n\n    private void DFS(TrieNode n, StringBuilder sb, int index) {\n        if (n == null) {\n            return;\n        }\n        sb.append(getCharacter(index));\n        for (int i = 0; i < n.characters.length; i++) {\n            if (n.characters[i] != null ) {\n                DFS(n.characters[i], new StringBuilder(sb), i);\n            }\n        }\n        if (sb.length() != 0 && n.isEnd) {\n            System.out.println(sb.toString());\n        }\n    }\n\n    private void add(TrieNode trie, String s) {\n        char[] chars = s.toCharArray();\n        TrieNode currentTrie = trie;\n        for (Character c : chars) {\n            if (currentTrie.characters[getIndex(c)] == null) {\n                currentTrie.characters[getIndex(c)] = new TrieNode();\n            }\n            currentTrie = currentTrie.characters[getIndex(c)];\n        }\n        currentTrie.isEnd = true;\n    }\n\n    public Character getCharacter(int index) {\n        return (char) (index + 65);\n    }\n\n    public Integer getIndex(Character c) {\n        return c - 65;\n    }\n}\n"
  },
  {
    "path": "data_structures/trie/javascript/Trie.js",
    "content": "class Node {\n    constructor(){\n        this.end   = false;\n        this.children = {};\n    }\n\n    setEnd(isEnd) {\n        this.end = isEnd;\n    }\n\n    addChild(value) {\n        if (this.children && this.children.hasOwnProperty(value)) {\n            return this.children[value];\n        } else {\n            let a = new Node();\n            this.children[value] = a;\n            return a;\n        }\n    }\n}\n\nclass Trie {\n    constructor() {\n        this.root = new Node();\n    }\n\n    findPrefix(prefix, parent) {\n        if (!parent) { parent = this.root; }\n        if (prefix !== null) {\n            let letter = prefix.substring(0, 1);\n            let remaining = prefix.substring(1);\n            if (parent.children.hasOwnProperty(letter)) {\n                if (prefix.length === 1) { return true;}\n                let result = this.findPrefix(remaining, parent.children[letter]);\n                return result;\n            } else {\n                return false;\n            }\n        }\n    }\n\n    addWord(word, parent = this.root) {\n        if (word !== null) {\n            let letter = word.substring(0, 1);\n            let child = parent.addChild(letter);\n            if (word.length > 1) {\n                this.addWord(word.substring(1), child);\n            } else {\n                child.setEnd(true);\n            }\n        }\n    }\n\n    list(root = this.root, word = [], words = []) {\n        if (root.end) {\n            words.push(word.join(\"\"));\n        }\n\n        for (let child in root.children) {\n            word.push(child);\n            this.list(root.children[child], word, words);\n            word.pop();\n        }\n        return words;\n    }\n}\n\n// How to use:\n// let t = new Trie();\n// t.addWord(\"testing\");\n// t.addWord(\"test\");\n// t.addWord(\"tesla\");\n// t.addWord(\"word\");\n// t.addWord(\"work\");\n// let allwords = t.list();\n// console.info(JSON.stringify(t.root));\n// console.info(allwords);\n// console.info(\"Prefix test :\", t.findPrefix(\"tes\"));\n// console.info(\"Prefix testi :\", t.findPrefix(\"testi\"));\n// console.info(\"Prefix word :\", t.findPrefix(\"word\"));\n// console.info(\"Prefix war :\", t.findPrefix(\"war\"));\n// console.info(\"Prefix c :\", t.findPrefix(\"c\"));\n// console.info(\"Prefix testingg :\", t.findPrefix(\"testingg\"));\n// console.info(\"Prefix testing2 :\", t.findPrefix(\"testing2\"));"
  },
  {
    "path": "data_structures/union_find/cpp/UnionFind.cpp",
    "content": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nclass UnionFind{\r\n\tvector<int> parent;\r\n\tvector<int> size;\r\n\tint components;\r\n\t\r\n\t// Finds the root of p, which is the identifier of its component\t\r\n\tint root(int p){\r\n\t\twhile(p != parent[p]){\r\n\t\t\tparent[p] = parent[parent[p]];\r\n\t\t\tp = parent[p];\r\n\t\t}\r\n\t\treturn p;\r\n\t}\r\n\r\n\t// Creates the Union-Find data structure\r\n\t// N = number of components\t \r\n\tpublic:\r\n\tUnionFind(int N){\r\n\t\tcomponents = N;\r\n\t\tfor(int i=0; i<N; i++){\r\n\t\t\tparent.push_back(i);\r\n\t\t\tsize.push_back(1);\r\n\t\t}\r\n\t}\r\n\r\n\t// Merges the component containing p and the component containing q\t\r\n\tvoid unionElem(int p, int q){\r\n\t\tint rootP = root(p);\r\n\t\tint rootQ = root(q);\r\n\t\tif(rootP != rootQ){\r\n\t\t\tif(size[rootP] < size[rootQ]){\r\n\t\t\t\tparent[rootP] = rootQ;\r\n\t\t\t\tsize[rootQ] = size[rootQ] + size[rootP];\r\n\t\t\t}else{\r\n\t\t\t\tparent[rootQ] = rootP;\r\n\t\t\t\tsize[rootP] = size[rootP] + size[rootQ];\r\n\t\t\t}\r\n\t\t\tcomponents--;\r\n\t\t}\r\n\t}\r\n\t\r\n\t// Returns true if p and q are connected (that is, if they are on the same component)\t\r\n\tbool connected(int p, int q){\r\n\t\treturn root(p) == root(q);\r\n\t}\r\n\r\n\t// Returns the number of components\t\r\n\tint getComponents(){\r\n\t\treturn components;\r\n\t}\r\n};\r\n\r\nint main(){\r\n\t\t// Create an Union-Find\twith 5 nodes\r\n\t\tUnionFind uf(5);\r\n\t\t\r\n\t\t// Make some unions\r\n\t\tuf.unionElem(0, 2);\r\n\t\tuf.unionElem(1, 0);\r\n\t\tuf.unionElem(3, 4);\r\n\t\t\r\n\t\t// The number of components after these unions is:\t\t\r\n\t\tint comp = uf.getComponents();\r\n\t\tcout<<\"Components: \"<<comp<<endl;\r\n\t\t// Are 1 and 2 on the same component?:\t\t\r\n\t\tbool connected = uf.connected(1, 2);\r\n\t\tcout<<\"Are 1 and 2 connected: \"<<connected<<endl;\r\n}\r\n"
  },
  {
    "path": "data_structures/union_find/java/UnionFind.java",
    "content": "\nclass UnionFind{\n\tprivate int[] parent, size;\n\tprivate int components;\n\t\n\t// Creates the Union-Find data structure\n\t// n = number of nodes\t \n\tpublic UnionFind(int n){\n\t\tcomponents = n;\n\t\tparent = new int[n];\n\t\tsize = new int[n];\n\t\tfor(int i=0; i<n; i++){\n\t\t\tparent[i] = i;\n\t\t\tsize[i] = 1;\n\t\t}\n\t}\n\n\t// Finds the root of p, which is the identifier of its component\t\n\tprivate int root(int p){\n\t\twhile(p != parent[p]){\n\t\t\tparent[p] = parent[parent[p]];\n\t\t\tp = parent[p];\n\t\t}\n\t\treturn p;\n\t}\n\n\t// Merges the component containing p and the component containing q\t\n\tpublic void union(int p, int q){\n\t\tint rootP = root(p);\n\t\tint rootQ = root(q);\n\t\tif(rootP != rootQ){\n\t\t\tif(size[rootP] < size[rootQ]){\n\t\t\t\tparent[rootP] = rootQ;\n\t\t\t\tsize[rootQ] = size[rootQ] + size[rootP];\n\t\t\t}else{\n\t\t\t\tparent[rootQ] = rootP;\n\t\t\t\tsize[rootP] = size[rootP] + size[rootQ];\n\t\t\t}\n\t\t\tcomponents--;\n\t\t}\n\t}\n\t\n\t// Returns true if p and q are connected (that is, if they are on the same component)\t\n\tpublic boolean connected(int p, int q){\n\t\treturn root(p) == root(q);\n\t}\n\n\t// Returns the number of components\t\n\tpublic int getComponents(){\n\t\treturn components;\n\t}\n}\n\nclass Main {\n\tpublic static void main(String[] args){\t\t\n\t\t// Create an Union-Find\twith 5 nodes\n\t\tUnionFind uf = new UnionFind(5);\n\t\t\n\t\t// Make some unions\n\t\tuf.union(0, 2);\n\t\tuf.union(1, 0);\n\t\tuf.union(3, 4);\n\t\t\n\t\t// The number of components after these unions is:\t\t\n\t\tint comp = uf.getComponents();\n\n\t\t// Are 1 and 2 on the same component?:\t\t\n\t\tboolean connected = uf.connected(1, 2);\n\t}\n}\n"
  },
  {
    "path": "data_structures/union_find/python/UnionFind.py",
    "content": "# finds the path recursively\ndef find(data, i):\n    if i != data[i]:\n        data[i] = find(data, data[i]) \n    return data[i]\n\n# creates the union find data structure\ndef union(data, i, j):\n    root_i, root_j = find(data, i), find(data, j)\n    if root_i != root_j:\n        data[root_i] = root_j\n        \n# recursive conncetions to find the connected components. \ndef connected(data, i, j):\n    return find(data, i) == find(data, j)\n\nn = 10\ndata = [i for i in range(n)]\nconnections = [(0, 1), (1, 2), (0, 9), (5, 6), (6, 4), (5, 9)]\n\n# union\nfor i, j in connections:\n    union(data, i, j)\n\nprint(data)"
  },
  {
    "path": "data_structures/union_find/union_find.md",
    "content": "## ELI5\nUnion Find Data structure quickly figures out if there is a line joining two points or not! Imagine a maze full of different coloured lines and lots of points on each of these. Now, you want to figure out if point A and point B are on the same line or not, quickly, such that, you can also add more lines of the same colour at any time, quickly.\n\n(Here, the lines are graph edges and points are graph nodes)\n\n### Pros\n* Fast query time \n* Best of both worlds - find points and add new lines\n### Cons\n* If you don't have to draw more lines, find time can be improved\n* If you don't have to find points, line drawing time can be improved\n\n## Technical Explaination\nA Union Find Datastructure aims to achieve a balance between query and add operations, more specifically, querying if 2 nodes belong to the same set and creating union of 2 or more sets. The way this works is, you initially have n disjoint sets representing the n initial points in the datastructure. Representation is via a pointer array, with the pointer for each indexed element pointing to itself. So, the pointer for the k'th element points to itself, k.\n\n1  2  3  4\n^  ^  ^  ^\n|  |  |  |\n1  2  3  4\n\nOnce we do a union operation, we make the parent pointer of A set point to B set.\n\nSo, union(4,3) means\n\n1  2  3  4\n^  ^  ^  \n|  |  | \\\n1  2  3  4\n\nFor find, we find the parent pointers and check if they are the same. If yes, they are in the same set, if no, they aren't.\n\nThis is used majorly to find if there exists a cycle in a graph. ( As a part of Prims and Krustkals Algorithm to find the M.S.T)\n\n### Pros\n* Find is O(log*N) where N is number of elements. This is almost O(1) for all practical purposes. Achieved by using path compression and union by size as added enhancements to the base algorithm.\n### Cons\n* Only applies to a very specific set of problems.\n"
  },
  {
    "path": "design_patterns/behavioral/javascript/mediator-example.js",
    "content": "'use strict';\n\n// 1\nmediator.weather = 'rainy';\nmediator.subscribe('weather:change', function (arg) {\n  console.log(this.weather);\n  this.weather = arg;\n  console.log(this.weather);\n});\n\nmediator.publish('weather:change', 'sunny');\n\n// 2\nvar person = {\n  firstName: 'John',\n  lastName: 'Doe'\n};\n\nmediator.bindTo(person);\n\nperson.subscribe('name:change', function (arg) {\n  console.log(this.firstName);\n  this.firstName = arg;\n  console.log(this.firstName);\n});\n\nmediator.publish('name:change', 'Alex');\n"
  },
  {
    "path": "design_patterns/behavioral/javascript/mediator.js",
    "content": "'use strict';\n\nlet mediator = (function () {\n\n  return {\n    channels: {},\n    publish: publish,\n    subscribe: suscribe,\n    bindTo: function (receiver) {\n      receiver.publish = publish;\n      receiver.subscribe = subscribe;\n    }\n  };\n\n  let publish = function (channel) {\n    if (!mediator.channels[channel]) {\n      return false;\n    }\n\n    let args = Array.prototype.slice.call(arguments, 1);\n\n    for (let i = 0, l = mediator.channels[channel].length; i < l; i++) {\n      let subscription = mediator.channels[channel][i];\n      subscription.callback.apply(subscription.context.args);\n    }\n\n    return this;\n  };\n\n  let subscribe = function (channel, fn) {\n    if (!mediator.channels[channel]) {\n      mediator.channels[channel] = [];\n    }\n\n    mediator.channels[channel].push({\n      context: this,\n      callback: fn\n    });\n\n    return this;\n  };\n})();\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"hacktoberfest-data-structure-and-algorithms\",\n  \"version\": \"1.0.0\",\n  \"description\": \"A Repository Containing Algorithms and Data Structures in all languages\",\n  \"main\": \"README.md\",\n  \"scripts\": {\n    \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/bareinhard/Hacktoberfest-Data-Structure-and-Algorithms.git\"\n  },\n  \"author\": \"Brett Reinhard <brett@reinhards.us> (http://brettreinhard.com)\",\n  \"license\": \"GPL-3.0\",\n  \"bugs\": {\n    \"url\": \"https://github.com/bareinhard/Hacktoberfest-Data-Structure-and-Algorithms/issues\"\n  },\n  \"homepage\": \"https://github.com/bareinhard/Hacktoberfest-Data-Structure-and-Algorithms#readme\",\n  \"devDependencies\": {\n    \"babel-cli\": \"^6.26.0\",\n    \"babel-preset-env\": \"^1.6.0\"\n  }\n}\n"
  }
]