From 347dcde2d8400a5a730282cd96c276f7eb67ea56 Mon Sep 17 00:00:00 2001 From: bakurits Date: Wed, 2 Oct 2019 16:57:18 +0400 Subject: [PATCH 001/209] implemented word dictionary using trie --- .gitignore | 2 + dictionary/dictionary.go | 118 ++++++++++++++++++++++++++++ dictionary/dictionary_test.go | 141 ++++++++++++++++++++++++++++++++++ 3 files changed, 261 insertions(+) create mode 100644 dictionary/dictionary.go create mode 100644 dictionary/dictionary_test.go diff --git a/.gitignore b/.gitignore index c6127b3..9d6bf16 100644 --- a/.gitignore +++ b/.gitignore @@ -50,3 +50,5 @@ modules.order Module.symvers Mkfile.old dkms.conf + +.idea \ No newline at end of file diff --git a/dictionary/dictionary.go b/dictionary/dictionary.go new file mode 100644 index 0000000..855c015 --- /dev/null +++ b/dictionary/dictionary.go @@ -0,0 +1,118 @@ +// Package dictionary is word dictionary implementation using trie in go +package dictionary + +// trieNode saves trie structure +type trieNode struct { + childMap map[rune]*trieNode + isEnd bool +} + +// Dictionary struct contains data and methods +type Dictionary struct { + root *trieNode + wordCount int +} + +// NewDictionary creates new instance of dictionary +func NewDictionary() *Dictionary { + return &Dictionary{ + root: &trieNode{ + childMap: map[rune]*trieNode{}, + isEnd: false, + }, + wordCount: 0, + } +} + +// Size returns word count in dictionary +func (pr *Dictionary) Size() int { + return pr.wordCount +} + +// Insert inserts new word in dictionary +// returns false if this word already present +func (pr *Dictionary) Insert(word string) bool { + node := pr.root + for _, ch := range word { + if newNode, ok := node.childMap[ch]; ok { + node = newNode + } else { + node.childMap[ch] = &trieNode{ + childMap: map[rune]*trieNode{}, + isEnd: false, + } + node = node.childMap[ch] + } + } + if node.isEnd { + return false + } + node.isEnd = true + pr.wordCount++ + return true +} + +// InsertAll inserts all words in dictionary +// returns number of words actually inserted +func (pr *Dictionary) InsertAll(words []string) int { + var res = 0 + for _, word := range words { + if pr.Insert(word) { + res++ + } + } + return res +} + +// Retrieve retrieves all words in dictionary starting with prefix +func (pr *Dictionary) Retrieve(prefix string) []string { + node, depth := longestMatch(prefix, pr.root) + if depth != len(prefix) { + return []string{} + } + return allChild(prefix, node) +} + +// Contains checks if given word is in dictionary +func (pr *Dictionary) Contains(word string) bool { + node, depth := longestMatch(word, pr.root) + return depth == len(word) && node.isEnd +} + +// Delete deletes given word from dictionary +// returns false if word is'n in dictionary +func (pr *Dictionary) Delete(word string) bool { + node, depth := longestMatch(word, pr.root) + if depth == len(word) && node.isEnd { + node.isEnd = false + return true + } + return false +} + +func longestMatch(prefix string, root *trieNode) (*trieNode, int) { + node := root + var depth = 0 + for _, ch := range prefix { + if newNode, ok := node.childMap[ch]; ok { + node = newNode + depth++ + } else { + return node, depth + } + } + return node, depth +} + +func allChild(prefix string, node *trieNode) []string { + var res []string + if node.isEnd { + res = append(res, prefix) + } + + for ch, childNode := range node.childMap { + newStr := prefix + string(ch) + res = append(res, allChild(newStr, childNode)...) + } + return res +} diff --git a/dictionary/dictionary_test.go b/dictionary/dictionary_test.go new file mode 100644 index 0000000..59d0838 --- /dev/null +++ b/dictionary/dictionary_test.go @@ -0,0 +1,141 @@ +package dictionary_test + +import ( + "algorithms-1/dictionary" + "testing" +) + +func TestEmptyDictionary(t *testing.T) { + var dict = dictionary.NewDictionary() + if dict.Size() != 0 { + t.Errorf("dictionary should be empty") + } + +} +func TestInsertingSame(t *testing.T) { + var dict = dictionary.NewDictionary() + + if dict.Insert("abc") == false { + t.Errorf("dictionary should be empty") + } + if dict.Insert("abc") == true { + t.Errorf("abc should already be in dictionary") + } + +} + +func TestRetrieve(t *testing.T) { + var dict = dictionary.NewDictionary() + + if dict.Insert("abc") == false { + t.Errorf("dictionary should be empty") + } + if dict.Insert("abb") == false { + t.Errorf("abb should't be in directory") + } + if dict.Insert("abcc") == false { + t.Errorf("abcc should't be in directory") + } + + if len(dict.Retrieve("a")) != 3 { + t.Errorf("there sould be 3 words starting with a") + } + if len(dict.Retrieve("ab")) != 3 { + t.Errorf("there sould be 3 words starting with ab") + } + if len(dict.Retrieve("abb")) != 1 { + t.Errorf("there sould be 1 words starting with abb") + } + if len(dict.Retrieve("gg")) != 0 { + t.Errorf("there sould be 0 words starting with gg") + } + +} + +func TestContains(t *testing.T) { + var dict = dictionary.NewDictionary() + if dict.Insert("abc") == false { + t.Errorf("dictionary should be empty") + } + if dict.Contains("abc") == false { + t.Errorf("abc should be in dictionary") + } + + var words = []string{ + "aaa", + "b", + "bbc", + "ccccdddd", + "d", + "ddaaaa", + "dddddddeeeeeeaaaa", + "eabbbb", + "eaccbbbbb", + } + + var containsTests = []struct { + word string // input + expected bool // expected result + }{ + {"aaa", true}, + {"ccccdddd", true}, + {"sdfdsf", false}, + {"eaccbbbba", false}, + {"", false}, + {"eabbbb", true}, + {"bb", false}, + } + dict.InsertAll(words) + + for _, tt := range containsTests { + actual := dict.Contains(tt.word) + if actual != tt.expected { + t.Errorf("contains(%s): expected %t, actual %t", tt.word, tt.expected, actual) + } + } + +} +func TestDelete(t *testing.T) { + var dict = dictionary.NewDictionary() + if dict.Insert("abc") == false { + t.Errorf("dictionary should be empty") + } + if dict.Delete("abc") == false { + t.Errorf("abc should be in dictionary") + } + + var words = []string{ + "aaa", + "b", + "bbc", + "ccccdddd", + "d", + "ddaaaa", + "dddddddeeeeeeaaaa", + "eabbbb", + "eaccbbbbb", + } + + var containsTests = []struct { + word string // input + expected bool // expected result + }{ + {"aaa", true}, + {"aaa", false}, + {"sdfdsf", false}, + {"eaccbbbba", false}, + {"", false}, + {"eabbbb", true}, + {"eabbbb", false}, + {"bb", false}, + } + dict.InsertAll(words) + + for _, tt := range containsTests { + actual := dict.Delete(tt.word) + if actual != tt.expected { + t.Errorf("delete(%s): expected %t, actual %t", tt.word, tt.expected, actual) + } + } + +} From 1df70b8dd9ed7daae1ade76d2f615e5a129483f0 Mon Sep 17 00:00:00 2001 From: bakurits Date: Wed, 2 Oct 2019 16:59:08 +0400 Subject: [PATCH 002/209] minor import change --- dictionary/dictionary_test.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/dictionary/dictionary_test.go b/dictionary/dictionary_test.go index 59d0838..7186795 100644 --- a/dictionary/dictionary_test.go +++ b/dictionary/dictionary_test.go @@ -1,8 +1,9 @@ package dictionary_test import ( - "algorithms-1/dictionary" "testing" + + "github.com/x899/algorithms/dictionary" ) func TestEmptyDictionary(t *testing.T) { From 9e5e0081bac6b97a4e8e369baa5bf6f302547868 Mon Sep 17 00:00:00 2001 From: Priyank Chheda Date: Wed, 23 Oct 2019 13:38:12 +0530 Subject: [PATCH 003/209] Update LICENSE --- LICENSE | 695 ++------------------------------------------------------ 1 file changed, 21 insertions(+), 674 deletions(-) diff --git a/LICENSE b/LICENSE index 94a9ed0..305f16c 100644 --- a/LICENSE +++ b/LICENSE @@ -1,674 +1,21 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. +MIT License + +Copyright (c) 2019 Priyank Chheda + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. From fc629719c80b4b0d5264d2058e63bbed08605b9c Mon Sep 17 00:00:00 2001 From: DirtyAxe Date: Fri, 25 Oct 2019 19:38:16 +0300 Subject: [PATCH 004/209] Added gnome sort --- sort/gnome.go | 17 +++++++++++++++++ sort/sort_test.go | 5 +++++ 2 files changed, 22 insertions(+) create mode 100644 sort/gnome.go diff --git a/sort/gnome.go b/sort/gnome.go new file mode 100644 index 0000000..d5ecde2 --- /dev/null +++ b/sort/gnome.go @@ -0,0 +1,17 @@ +package sort + +func GnomeSort(data []int) { + index := 0 + for index < len(data) { + if (index == 0 || data[index] >= data[index - 1]) { + index = index + 1 + } else { + // Swap value at index and (index - 1) + tempVal := data[index - 1] + data[index - 1] = data[index] + data[index] = tempVal + + index = index - 1 + } + } +} \ No newline at end of file diff --git a/sort/sort_test.go b/sort/sort_test.go index ac37453..6708dd7 100644 --- a/sort/sort_test.go +++ b/sort/sort_test.go @@ -87,6 +87,11 @@ func TestHeapSort(t *testing.T) { testSortRandom(t, mysort.HeapSort) } +func TestGnomeSort(t *testing.T) { + testSort(t, mysort.GnomeSort) + testSortRandom(t, mysort.GnomeSort) +} + func TestMergeSort(t *testing.T) { tests := []struct { original []int From 701e39a551c0574886c3d9c441084c5b50b58b62 Mon Sep 17 00:00:00 2001 From: DirtyAxe Date: Sat, 26 Oct 2019 13:39:54 +0300 Subject: [PATCH 005/209] Added documentations for gnome sort function --- sort/gnome.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/sort/gnome.go b/sort/gnome.go index d5ecde2..b8b5e39 100644 --- a/sort/gnome.go +++ b/sort/gnome.go @@ -1,5 +1,9 @@ package sort + +// The gnome sort is a sorting algorithm which is similar +// to insertion sort in that it works with one item at a time +// but gets the item to the proper place by a series of swaps. func GnomeSort(data []int) { index := 0 for index < len(data) { From 253e8f226790e3d7b642f7edc8ee80fcd2f861f2 Mon Sep 17 00:00:00 2001 From: DirtyAxe Date: Sat, 26 Oct 2019 18:25:32 +0300 Subject: [PATCH 006/209] Fixed GnomeSort description --- sort/gnome.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sort/gnome.go b/sort/gnome.go index b8b5e39..fc6f49a 100644 --- a/sort/gnome.go +++ b/sort/gnome.go @@ -1,7 +1,7 @@ package sort -// The gnome sort is a sorting algorithm which is similar +// GnomeSort is a sorting algorithm which is similar // to insertion sort in that it works with one item at a time // but gets the item to the proper place by a series of swaps. func GnomeSort(data []int) { From f1ea432ec8ceececf561d4d54061c99c02c24417 Mon Sep 17 00:00:00 2001 From: suvidsahay Date: Thu, 31 Oct 2019 12:36:09 +0530 Subject: [PATCH 007/209] Implementation of Odd Even Sort --- sort/oddeven.go | 30 ++++++++++++++++++++++++++++++ sort/sort_test.go | 5 +++++ 2 files changed, 35 insertions(+) create mode 100644 sort/oddeven.go diff --git a/sort/oddeven.go b/sort/oddeven.go new file mode 100644 index 0000000..eae48d4 --- /dev/null +++ b/sort/oddeven.go @@ -0,0 +1,30 @@ +package sort + +//Odd-Even Sort is a variation of bubble sort where the sorting is divided into +//two phases, Odd and Even Phase and it runs until all the elements are sorted +//In the odd phase we perform bubble sort on odd indexed elements and in the +//even phase we perform bubble sort on even indexed elements. + +func OddEvenSort(data []int) { + sorted := false + dataLen := len(data) + + for { + sorted = true + for i := 1; i < dataLen-1; i += 2 { + if data[i] > data[i+1] { + data[i], data[i+1] = data[i+1], data[i] + sorted = false + } + } + for i := 0; i < dataLen-1; i += 2 { + if data[i] > data[i+1] { + data[i], data[i+1] = data[i+1], data[i] + sorted = false + } + } + if sorted { + break + } + } +} diff --git a/sort/sort_test.go b/sort/sort_test.go index 6708dd7..8a6dd81 100644 --- a/sort/sort_test.go +++ b/sort/sort_test.go @@ -276,3 +276,8 @@ func TestQuickSelect(t *testing.T) { } } } + +func TestOddEvenSort(t *testing.T) { + testSort(t, mysort.OddEvenSort) + testSortRandom(t, mysort.OddEvenSort) +} From e3d87b450e580c4ba81b3c49ca242ad03aa153ef Mon Sep 17 00:00:00 2001 From: Suvid Sahay <42059321+suvidsahay@users.noreply.github.com> Date: Thu, 31 Oct 2019 13:52:40 +0530 Subject: [PATCH 008/209] Changed the decription and removed extra lines Changed the Description in comment to start with function name and removed an extra line after the description. --- sort/oddeven.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/sort/oddeven.go b/sort/oddeven.go index eae48d4..230ea61 100644 --- a/sort/oddeven.go +++ b/sort/oddeven.go @@ -1,10 +1,9 @@ package sort -//Odd-Even Sort is a variation of bubble sort where the sorting is divided into +//OddEvenSort is a variation of bubble sort where the sorting is divided into //two phases, Odd and Even Phase and it runs until all the elements are sorted //In the odd phase we perform bubble sort on odd indexed elements and in the //even phase we perform bubble sort on even indexed elements. - func OddEvenSort(data []int) { sorted := false dataLen := len(data) From 6490720f7d84e12ae7fe13be88c38e9f31a6a06c Mon Sep 17 00:00:00 2001 From: x899 Date: Tue, 5 Nov 2019 20:16:13 +0530 Subject: [PATCH 009/209] binary heap documentation update --- heap/doc.go | 29 +++++++++++++++++++++++++++++ heap/maxheap/maxheap.go | 8 ++++---- heap/minheap/minheap.go | 4 ++-- 3 files changed, 35 insertions(+), 6 deletions(-) create mode 100644 heap/doc.go diff --git a/heap/doc.go b/heap/doc.go new file mode 100644 index 0000000..171bb0f --- /dev/null +++ b/heap/doc.go @@ -0,0 +1,29 @@ +/* +Package heap is the implementation of Binary Heap which is going to help us +implement all the priority queue quickly. + +So the idea of a binary heap is based on the idea of a complete binary tree. +Now the way we're going to use a complete binary trees to implement priority +queues is to first of all associate information with each node. We'll put our +keys in the nodes. And also we're going to represent it with an array. + +So when we start putting the keys in the nodes, we're going to impose one more +condition that's called heap ordering. And the idea is that the parent's key +is going to be no smaller than its children's key, and that's true for every +node in the tree. The array representation, all we do is we put, we start with +indices at 1. It's a little less calculation. That way, we leave a of zero +empty. The way that we move around the tree is by doing arithmetic on the +indices. + +Properties: +1. Largest key is a[1], which is root of binary tree. +2. Can use array indices to move through tree + - Parent of node at k is at k/2 + - Children of node at k is at 2k and 2k+1 + +Time Complexity: +Both insertion and deletion priority key happens in log N time. + +Best Pratice: use immutable keys +*/ +package heap diff --git a/heap/maxheap/maxheap.go b/heap/maxheap/maxheap.go index 74bead4..efb868f 100644 --- a/heap/maxheap/maxheap.go +++ b/heap/maxheap/maxheap.go @@ -24,7 +24,7 @@ func BuildHeap(data []int) *Heap { return &heap } -// NewMinHeap creates new empty 1-indexed heap +// NewHeap creates new empty 1-indexed heap func NewHeap() *Heap { heap := Heap{arr: make([]int, 0)} heap.arr = append(heap.arr, -99) @@ -42,7 +42,7 @@ func (h *Heap) Insert(d int) { h.swim(len(h.arr) - 1) } -// ExtractMin returns the minimum value (i.e. root) in the heap and removes it +// ExtractMax returns the maximum value (i.e. root) in the heap and removes it // from the heap. Returns error, if heap is empty func (h *Heap) ExtractMax() (int, error) { if h.Length() <= 0 { @@ -55,7 +55,7 @@ func (h *Heap) ExtractMax() (int, error) { return maxvalue, nil } -// Min returns the minimum value (i.e. root) in the heap, without removing it. +// Max returns the maximum value (i.e. root) in the heap, without removing it. // Returns error, if heap is empty func (h *Heap) Max() (int, error) { if h.Length() <= 0 { @@ -77,7 +77,7 @@ func (h *Heap) swim(k int) { } } -// swim moves element at index k downward to maintain heap invariant +// sink moves element at index k downward to maintain heap invariant func (h *Heap) sink(k int) { min := k c := k * 2 diff --git a/heap/minheap/minheap.go b/heap/minheap/minheap.go index 9015e18..2152585 100644 --- a/heap/minheap/minheap.go +++ b/heap/minheap/minheap.go @@ -1,4 +1,4 @@ -// Package minheap is an implementation of minheap data structure in go +// Package minheap is an implementation of minheap data structure in go. package minheap import "errors" @@ -24,7 +24,7 @@ func BuildHeap(data []int) *Heap { return &heap } -// NewMinHeap creates new empty 1-indexed heap +// NewHeap creates new empty 1-indexed heap func NewHeap() *Heap { heap := Heap{arr: make([]int, 0)} heap.arr = append(heap.arr, -99) From 9be45300269a6753881eef335af77ff2b8d27b8c Mon Sep 17 00:00:00 2001 From: x899 Date: Thu, 7 Nov 2019 12:10:22 +0530 Subject: [PATCH 010/209] update heap and heapsort documentation --- heap/doc.go | 20 +++++++------------- sort/heap.go | 5 +++-- 2 files changed, 10 insertions(+), 15 deletions(-) diff --git a/heap/doc.go b/heap/doc.go index 171bb0f..7b91188 100644 --- a/heap/doc.go +++ b/heap/doc.go @@ -10,20 +10,14 @@ keys in the nodes. And also we're going to represent it with an array. So when we start putting the keys in the nodes, we're going to impose one more condition that's called heap ordering. And the idea is that the parent's key is going to be no smaller than its children's key, and that's true for every -node in the tree. The array representation, all we do is we put, we start with -indices at 1. It's a little less calculation. That way, we leave a of zero -empty. The way that we move around the tree is by doing arithmetic on the +node in the tree. For easy calculation , we start with indices at 1. +The way that we move around the tree is by doing arithmetic on the indices. + - Parent of node at k is at k/2. + - Children of node at k is at 2k and 2k+1. -Properties: -1. Largest key is a[1], which is root of binary tree. -2. Can use array indices to move through tree - - Parent of node at k is at k/2 - - Children of node at k is at 2k and 2k+1 - -Time Complexity: -Both insertion and deletion priority key happens in log N time. - -Best Pratice: use immutable keys +The largest key is a[1], which is root of binary tree. The time complexity of +both insertion and deletion priority key happens in log N time. It is +recommanded to use immutable keys. */ package heap diff --git a/sort/heap.go b/sort/heap.go index f3ffc28..ded4aa7 100644 --- a/sort/heap.go +++ b/sort/heap.go @@ -28,10 +28,11 @@ func heapify(arr []int, root int, length int) { } } -// Heap sort is a comparison based sorting technique based on Binary Heap +// HeapSort is a comparison based sorting technique based on Binary Heap // data structure. It is similar to selection sort where we first find the // maximum element and place the maximum element at the end. We repeat the -// same process for remaining element. +// same process for remaining element. Heap Sort is not stable, In-place +// sorting algorithm with guarantee NlogN time complexity in worst-case. func HeapSort(data []int) { buildHeap(data) for i := len(data) - 1; i > 0; i-- { From 13291fe0ba8429033a89f1c7c07d0e46041f462b Mon Sep 17 00:00:00 2001 From: x899 Date: Thu, 7 Nov 2019 12:10:50 +0530 Subject: [PATCH 011/209] update redblacktree documentation --- redblacktree/doc.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/redblacktree/doc.go b/redblacktree/doc.go index fc662f7..af5e244 100644 --- a/redblacktree/doc.go +++ b/redblacktree/doc.go @@ -8,7 +8,7 @@ two adjacent red nodes (A red node cannot have a red parent or red child). Every path from a node (including root) to any of its descendant NULL node has the same number of black nodes. -Why Red-Black Trees? +Why Red-Black Trees Most of the BST operations (e.g., search, max, min, insert, delete.. etc) take O(h) time where h is the height of the BST. The cost of these From 2fab12fe49054c4ec7377874de90e8c4924424e0 Mon Sep 17 00:00:00 2001 From: x899 Date: Wed, 13 Nov 2019 18:45:23 +0530 Subject: [PATCH 012/209] bst delete node comment --- bst/delete.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/bst/delete.go b/bst/delete.go index c22fb00..37b2c2f 100644 --- a/bst/delete.go +++ b/bst/delete.go @@ -4,6 +4,12 @@ import "errors" // Delete deletes a node with said data such that the binary search tree // property is still maintained. +// +// The main problem with BST deletion (Hibbard Deletion) is that it is not +// symmetric. After many insertion and deletion BST become less balance. +// Researchers proved that after sufficiently long number of random insert and +// delete height of the tree becomes sqrt(n) . so now every operation (search, +// insert, delete) will take sqrt(n) time which is not good compare to O(logn). func (t *Tree) Delete(data int) error { if t.Root == nil { return errors.New("can not delete from an empty tree") From c6126940f4314cf6c778e13c99d50ef387af3571 Mon Sep 17 00:00:00 2001 From: x899 Date: Mon, 25 Nov 2019 19:30:44 +0530 Subject: [PATCH 013/209] set data structure add, has, size functions --- set/set.go | 49 +++++++++++++++++++++++++++++++++++++++++++ set/set_test.go | 56 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 105 insertions(+) create mode 100644 set/set.go create mode 100644 set/set_test.go diff --git a/set/set.go b/set/set.go new file mode 100644 index 0000000..a3acea6 --- /dev/null +++ b/set/set.go @@ -0,0 +1,49 @@ +package set + +// Set defines a non-thread safe set data structure +type Set struct { + m map[int]struct{} // struct{} doesn't take up space +} + +// helpful to not write everywhere struct{}{} +var keyExists = struct{}{} + +// NewSet creates and initializes a new non-threatsafe Set. +func NewSet() *Set { + s := &Set{} + s.m = make(map[int]struct{}) + return s +} + +// Add includes the specified items (one or more) to the set. The underlying +// Set s is modified. If passed nothing it silently returns. +func (s *Set) Add(items ...int) { + if len(items) == 0 { + return + } + for _, item := range items { + s.m[item] = keyExists + } +} + +// Size returns the number of items in a set. +func (s *Set) Size() int { + return len(s.m) +} + +// Has looks for the existance of items passed. It returns false if nothing is +// passed. For multiple items, it returns true if all of the items exist. +func (s *Set) Has(items ...int) bool { + // assume checked for empty item, which not exist + if len(items) == 0 { + return false + } + + has := true + for _, item := range items { + if _, has = s.m[item]; !has { + break + } + } + return has +} diff --git a/set/set_test.go b/set/set_test.go new file mode 100644 index 0000000..b497b05 --- /dev/null +++ b/set/set_test.go @@ -0,0 +1,56 @@ +package set_test + +import ( + "testing" + + "github.com/x899/algorithms/set" +) + +func TestHas(t *testing.T) { + s := set.NewSet() + s.Add(34, 546, 234, 78) + + if s.Has() { + t.Error("empty parameters expected false, but returning true") + } + if !s.Has(34) { + t.Error("the item 34 exist, but 'Has' is returning false") + } + if !s.Has(34, 546, 234, 78) { + t.Error("the items all exist, but 'Has' is returning false") + } + if s.Has(34, 546, 234, 77) { + t.Error("77 doesn't exist in set, but 'Has' is returning true") + } +} + +func TestAddSingle(t *testing.T) { + s := set.NewSet() + s.Add() + s.Add(1) + s.Add(1) // duplicate entry + s.Add(2) + s.Add(3) + s.Add(2) // duplicate entry + + if actualSize := s.Size(); actualSize != 3 { + t.Errorf("wrong answer expected: 5, got:%v", actualSize) + } + + if !s.Has(1, 2, 3) { + t.Error("added items are not availabile in the set.") + } +} + +func TestAddMultiple(t *testing.T) { + s := set.NewSet() + s.Add(12, 23, 35, 47) + + if actualSize := s.Size(); actualSize != 4 { + t.Errorf("wrong answer expected: 5, got:%v", actualSize) + } + + if !s.Has(12, 23, 35, 47) { + t.Error("added items are not availabile in the set.") + } +} From 82222fdef5768860bf0cff6ca20810caa2c9f3a5 Mon Sep 17 00:00:00 2001 From: x899 Date: Wed, 27 Nov 2019 23:35:11 +0530 Subject: [PATCH 014/209] set ds remove pop clear isempty func --- set/set.go | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/set/set.go b/set/set.go index a3acea6..d7a7b52 100644 --- a/set/set.go +++ b/set/set.go @@ -1,5 +1,7 @@ package set +import "fmt" + // Set defines a non-thread safe set data structure type Set struct { m map[int]struct{} // struct{} doesn't take up space @@ -47,3 +49,34 @@ func (s *Set) Has(items ...int) bool { } return has } + +// Remove deletes the specified items from the set. The underlying Set s is +// modified. If passed nothing it silently returns. +func (s *Set) Remove(items ...int) { + if len(items) == 0 { + return + } + for _, item := range items { + delete(s.m, item) + } +} + +// Pop deletes and return an item from the set. The underlying Set s is +// modified. If set is empty, nil is returned. +func (s *Set) Pop() (int, error) { + for item := range s.m { + delete(s.m, item) + return item, nil + } + return 0, fmt.Errorf("set is empty") +} + +// Clear removes all items from the set. +func (s *Set) Clear() { + s.m = make(map[int]struct{}) +} + +// IsEmpty reports whether the set is empty. +func (s *Set) IsEmpty() bool { + return s.Size() == 0 +} From 8e5f4459ba4d791a6d0ad4820e4f3d67541d981b Mon Sep 17 00:00:00 2001 From: x899 Date: Fri, 29 Nov 2019 11:30:20 +0530 Subject: [PATCH 015/209] redblacktree documentation --- redblacktree/doc.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/redblacktree/doc.go b/redblacktree/doc.go index af5e244..168816d 100644 --- a/redblacktree/doc.go +++ b/redblacktree/doc.go @@ -28,5 +28,12 @@ to O(logn) . This is very long standing(around 50 years) open problem to efficient symmetric delete for BST. for guaranteed balanced tree, we have to use RedBlack Tree etc. + +Properties + + - No Node has two red links connected to it. + - Every path from root to null link has the same number of black links. + - Red links lean left. + */ package redblacktree From d336e716e43bf7a82721121eacbcb16731b742f8 Mon Sep 17 00:00:00 2001 From: x899 Date: Thu, 5 Dec 2019 11:37:01 +0530 Subject: [PATCH 016/209] added set test cases for remove, pop, clear, isempty --- set/set_test.go | 95 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) diff --git a/set/set_test.go b/set/set_test.go index b497b05..e092a99 100644 --- a/set/set_test.go +++ b/set/set_test.go @@ -54,3 +54,98 @@ func TestAddMultiple(t *testing.T) { t.Error("added items are not availabile in the set.") } } + +func TestRemoveSingle(t *testing.T) { + s := set.NewSet() + s.Add(1) + s.Add(2) + s.Add(3) + + s.Remove(2) + if s.Size() != 2 { + t.Error("Remove: set size should be two after removing") + } + + s.Remove(2) + if s.Size() != 2 { + t.Error("Remove: set size should not change after removing 2 again") + } + + s.Remove(1) + s.Remove(3) + if s.Size() != 0 { + t.Error("Remove: set size should be zero") + } + + // try to remove something from a zero length set + s.Remove(34) +} + +func TestRemoveMultiple(t *testing.T) { + s := set.NewSet() + s.Add(1, 3, 4, 5) + s.Remove() + if s.Size() != 4 { + t.Error("Remove: items are not unique. The set size should be four") + } + + s.Remove(3, 4, 5) + if s.Size() != 1 { + t.Error("Remove: items are not unique. The set size should be one") + } + + if !s.Has(1) { + t.Error("added items are not available in the set.") + } +} + +func TestPop(t *testing.T) { + s := set.NewSet() + s.Add(1, 3, 4, 5) + a, _ := s.Pop() + if s.Size() != 3 { + t.Error("Pop: set size should be two after popping out") + } + + if s.Has(a) { + t.Error("Pop: returned item should not exist") + } + + s.Pop() + s.Pop() + s.Pop() + b, err := s.Pop() + if b != 0 { + t.Error("Pop: should return 0 because set is empty") + } + if err.Error() != "set is empty" { + t.Error("error message should be 'set is empty'") + } + + //try to remove something from a zero length set + s.Pop() +} + +func TestClear(t *testing.T) { + s := set.NewSet() + s.Add(1) + s.Add(2) + s.Add(3, 4, 5) + + s.Clear() + if s.Size() != 0 { + t.Error("Clear: set size should be zero") + } +} + +func TestIsEmpty(t *testing.T) { + s := set.NewSet() + if !s.IsEmpty() { + t.Error("IsEmpty: set is empty, it should be true") + } + + s.Add(1, 2, 3) + if s.IsEmpty() { + t.Error("IsEmpty: set is filled, it should be false") + } +} From 72c3db5ac03c2c4d6b46511743fc5a4fd98a3ccf Mon Sep 17 00:00:00 2001 From: x899 Date: Sat, 7 Dec 2019 09:58:13 +0530 Subject: [PATCH 017/209] set IsEqual func and test cases --- set/set.go | 21 ++++++++++++++++++++- set/set_test.go | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) diff --git a/set/set.go b/set/set.go index d7a7b52..6ba0a5e 100644 --- a/set/set.go +++ b/set/set.go @@ -1,6 +1,8 @@ package set -import "fmt" +import ( + "fmt" +) // Set defines a non-thread safe set data structure type Set struct { @@ -80,3 +82,20 @@ func (s *Set) Clear() { func (s *Set) IsEmpty() bool { return s.Size() == 0 } + +// IsEqual tests whether s and t are same in size and have exactly same +// content. +func (s *Set) IsEqual(t *Set) bool { + if s.Size() != t.Size() { + return false + } + + equal := true + for item := range t.m { + _, equal = s.m[item] + if !equal { + break + } + } + return equal +} diff --git a/set/set_test.go b/set/set_test.go index e092a99..43d7a96 100644 --- a/set/set_test.go +++ b/set/set_test.go @@ -149,3 +149,37 @@ func TestIsEmpty(t *testing.T) { t.Error("IsEmpty: set is filled, it should be false") } } + +func TestIsEqual(t *testing.T) { + a := set.NewSet() + a.Add(1, 2, 3) + b := set.NewSet() + b.Add(1, 2, 3) + + ok := a.IsEqual(b) + if !ok { + t.Error("IsEqual: set a and b are equal. However it returns false") + } + + // same size, different content + a = set.NewSet() + a.Add(1, 2, 3) + b = set.NewSet() + b.Add(4, 5, 6) + + ok = a.IsEqual(b) + if ok { + t.Error("IsEqual: set a and b are not equal. However it returns true") + } + + // different size, similar content + a = set.NewSet() + a.Add(1, 2, 3) + b = set.NewSet() + b.Add(1, 2, 3, 4) + + ok = a.IsEqual(b) + if ok { + t.Error("IsEqual: set a and b are not equal. However it returns true") + } +} From 36559e52bb34fc6aea07eb020999550ebe6b229a Mon Sep 17 00:00:00 2001 From: x899 Date: Sat, 7 Dec 2019 10:00:45 +0530 Subject: [PATCH 018/209] set subset superset --- set/set.go | 17 +++++++++++++++++ set/set_test.go | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/set/set.go b/set/set.go index 6ba0a5e..62877fe 100644 --- a/set/set.go +++ b/set/set.go @@ -99,3 +99,20 @@ func (s *Set) IsEqual(t *Set) bool { } return equal } + +//IsSubset tests whether t is a subset of s. +func (s *Set) IsSubset(t *Set) bool { + subset := true + for item := range t.m { + _, subset = s.m[item] + if !subset { + break + } + } + return subset +} + +// IsSuperset tests whether t is a superset of s. +func (s *Set) IsSuperset(t *Set) bool { + return t.IsSubset(s) +} diff --git a/set/set_test.go b/set/set_test.go index 43d7a96..ba4e858 100644 --- a/set/set_test.go +++ b/set/set_test.go @@ -183,3 +183,37 @@ func TestIsEqual(t *testing.T) { t.Error("IsEqual: set a and b are not equal. However it returns true") } } + +func TestIsSubset(t *testing.T) { + s := set.NewSet() + s.Add(1, 2, 3, 4) + u := set.NewSet() + u.Add(1, 2, 3) + + ok := s.IsSubset(u) + if !ok { + t.Error("IsSubset: u is a subset of s. However it returns false") + } + + ok = u.IsSubset(s) + if ok { + t.Error("IsSubset: s is not a subset of u. However it returns true") + } +} + +func TestIsSuperset(t *testing.T) { + s := set.NewSet() + s.Add(1, 2, 3, 4) + u := set.NewSet() + u.Add(1, 2, 3) + + ok := u.IsSuperset(s) + if !ok { + t.Error("IsSuperset: u is a superset of s. However it returns false") + } + + ok = s.IsSuperset(u) + if ok { + t.Error("IsSuperset: s is not a superset of u. However it returns true") + } +} From fbfeb02b02640f2d082405486c749d4136fad714 Mon Sep 17 00:00:00 2001 From: x899 Date: Sun, 8 Dec 2019 11:21:53 +0530 Subject: [PATCH 019/209] set copy string list func --- set/set.go | 30 ++++++++++++++++++++++++++++++ set/set_test.go | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+) diff --git a/set/set.go b/set/set.go index 62877fe..e191809 100644 --- a/set/set.go +++ b/set/set.go @@ -2,6 +2,7 @@ package set import ( "fmt" + "strings" ) // Set defines a non-thread safe set data structure @@ -116,3 +117,32 @@ func (s *Set) IsSubset(t *Set) bool { func (s *Set) IsSuperset(t *Set) bool { return t.IsSubset(s) } + +// Copy returns a new Set with a copy of s. +func (s *Set) Copy() *Set { + u := NewSet() + for item := range s.m { + u.Add(item) + } + return u +} + +// String returns a string representation of s +func (s *Set) String() string { + t := make([]string, 0, s.Size()) + for item := range s.m { + t = append(t, fmt.Sprintf("%v", item)) + } + + return fmt.Sprintf("[%s]", strings.Join(t, ", ")) +} + +// List returns a slice of all items. +func (s *Set) List() []int { + list := make([]int, 0, s.Size()) + + for item := range s.m { + list = append(list, item) + } + return list +} diff --git a/set/set_test.go b/set/set_test.go index ba4e858..cf43840 100644 --- a/set/set_test.go +++ b/set/set_test.go @@ -1,6 +1,7 @@ package set_test import ( + "strings" "testing" "github.com/x899/algorithms/set" @@ -217,3 +218,41 @@ func TestIsSuperset(t *testing.T) { t.Error("IsSuperset: s is not a superset of u. However it returns true") } } + +func TestString(t *testing.T) { + s := set.NewSet() + if s.String() != "[]" { + t.Errorf("String: output is not what is excepted '%s'", s.String()) + } + + s.Add(1, 2, 3, 4) + if !strings.HasPrefix(s.String(), "[") { + t.Error("String: output should begin with a square bracket") + } + + if !strings.HasSuffix(s.String(), "]") { + t.Error("String: output should end with a square bracket") + } +} + +func TestList(t *testing.T) { + s := set.NewSet() + if len(s.List()) != 0 { + t.Errorf("len of list excepted - 0, got - '%v'", s.List()) + } + + s.Add(1, 2, 3, 4) + if len(s.List()) != 4 { + t.Errorf("len of list excepted - 4, got - '%v'", s.List()) + } +} + +func TestCopy(t *testing.T) { + s := set.NewSet() + s.Add(1, 2, 3, 4, 5) + u := s.Copy() + + if !s.IsEqual(u) { + t.Error("Copy: set s and u are not equal") + } +} From 491672b7e9a3f80e35784baed3a8b12696788581 Mon Sep 17 00:00:00 2001 From: x899 Date: Mon, 9 Dec 2019 09:06:39 +0530 Subject: [PATCH 020/209] renaming dictionary to trie --- dictionary/dictionary.go => trie/trie.go | 41 +++++++++---------- .../dictionary_test.go => trie/trie_test.go | 32 +++++++-------- 2 files changed, 36 insertions(+), 37 deletions(-) rename dictionary/dictionary.go => trie/trie.go (63%) rename dictionary/dictionary_test.go => trie/trie_test.go (77%) diff --git a/dictionary/dictionary.go b/trie/trie.go similarity index 63% rename from dictionary/dictionary.go rename to trie/trie.go index 855c015..ada105d 100644 --- a/dictionary/dictionary.go +++ b/trie/trie.go @@ -1,5 +1,5 @@ -// Package dictionary is word dictionary implementation using trie in go -package dictionary +// Package trie is word dictionary implementation using trie in go +package trie // trieNode saves trie structure type trieNode struct { @@ -7,15 +7,15 @@ type trieNode struct { isEnd bool } -// Dictionary struct contains data and methods -type Dictionary struct { +// Trie struct contains data and methods +type Trie struct { root *trieNode wordCount int } -// NewDictionary creates new instance of dictionary -func NewDictionary() *Dictionary { - return &Dictionary{ +// NewTrie creates new instance of trie +func NewTrie() *Trie { + return &Trie{ root: &trieNode{ childMap: map[rune]*trieNode{}, isEnd: false, @@ -24,14 +24,14 @@ func NewDictionary() *Dictionary { } } -// Size returns word count in dictionary -func (pr *Dictionary) Size() int { +// Size returns word count in trie +func (pr *Trie) Size() int { return pr.wordCount } -// Insert inserts new word in dictionary +// Insert inserts new word in trie // returns false if this word already present -func (pr *Dictionary) Insert(word string) bool { +func (pr *Trie) Insert(word string) bool { node := pr.root for _, ch := range word { if newNode, ok := node.childMap[ch]; ok { @@ -52,9 +52,9 @@ func (pr *Dictionary) Insert(word string) bool { return true } -// InsertAll inserts all words in dictionary -// returns number of words actually inserted -func (pr *Dictionary) InsertAll(words []string) int { +// InsertAll inserts all words in trie returns number of words actually +// inserted. +func (pr *Trie) InsertAll(words []string) int { var res = 0 for _, word := range words { if pr.Insert(word) { @@ -64,8 +64,8 @@ func (pr *Dictionary) InsertAll(words []string) int { return res } -// Retrieve retrieves all words in dictionary starting with prefix -func (pr *Dictionary) Retrieve(prefix string) []string { +// Retrieve retrieves all words in trie starting with prefix. +func (pr *Trie) Retrieve(prefix string) []string { node, depth := longestMatch(prefix, pr.root) if depth != len(prefix) { return []string{} @@ -73,15 +73,14 @@ func (pr *Dictionary) Retrieve(prefix string) []string { return allChild(prefix, node) } -// Contains checks if given word is in dictionary -func (pr *Dictionary) Contains(word string) bool { +// Contains checks if given word is in trie. +func (pr *Trie) Contains(word string) bool { node, depth := longestMatch(word, pr.root) return depth == len(word) && node.isEnd } -// Delete deletes given word from dictionary -// returns false if word is'n in dictionary -func (pr *Dictionary) Delete(word string) bool { +// Delete deletes given word from trie. Returns false if word is not in trie. +func (pr *Trie) Delete(word string) bool { node, depth := longestMatch(word, pr.root) if depth == len(word) && node.isEnd { node.isEnd = false diff --git a/dictionary/dictionary_test.go b/trie/trie_test.go similarity index 77% rename from dictionary/dictionary_test.go rename to trie/trie_test.go index 7186795..e7c4973 100644 --- a/dictionary/dictionary_test.go +++ b/trie/trie_test.go @@ -1,35 +1,35 @@ -package dictionary_test +package trie_test import ( "testing" - "github.com/x899/algorithms/dictionary" + "github.com/x899/algorithms/trie" ) -func TestEmptyDictionary(t *testing.T) { - var dict = dictionary.NewDictionary() +func TestEmptyTrie(t *testing.T) { + var dict = trie.NewTrie() if dict.Size() != 0 { - t.Errorf("dictionary should be empty") + t.Errorf("trie should be empty") } } func TestInsertingSame(t *testing.T) { - var dict = dictionary.NewDictionary() + var dict = trie.NewTrie() if dict.Insert("abc") == false { - t.Errorf("dictionary should be empty") + t.Errorf("trie should be empty") } if dict.Insert("abc") == true { - t.Errorf("abc should already be in dictionary") + t.Errorf("abc should already be in trie") } } func TestRetrieve(t *testing.T) { - var dict = dictionary.NewDictionary() + var dict = trie.NewTrie() if dict.Insert("abc") == false { - t.Errorf("dictionary should be empty") + t.Errorf("trie should be empty") } if dict.Insert("abb") == false { t.Errorf("abb should't be in directory") @@ -54,12 +54,12 @@ func TestRetrieve(t *testing.T) { } func TestContains(t *testing.T) { - var dict = dictionary.NewDictionary() + var dict = trie.NewTrie() if dict.Insert("abc") == false { - t.Errorf("dictionary should be empty") + t.Errorf("trie should be empty") } if dict.Contains("abc") == false { - t.Errorf("abc should be in dictionary") + t.Errorf("abc should be in trie") } var words = []string{ @@ -97,12 +97,12 @@ func TestContains(t *testing.T) { } func TestDelete(t *testing.T) { - var dict = dictionary.NewDictionary() + var dict = trie.NewTrie() if dict.Insert("abc") == false { - t.Errorf("dictionary should be empty") + t.Errorf("trie should be empty") } if dict.Delete("abc") == false { - t.Errorf("abc should be in dictionary") + t.Errorf("abc should be in trie") } var words = []string{ From cafc12e5848993cff518b8e52db308777cba903b Mon Sep 17 00:00:00 2001 From: x899 Date: Tue, 10 Dec 2019 15:38:14 +0530 Subject: [PATCH 021/209] set merge seperate union func --- set/set.go | 30 +++++++++++++++++++++++++++++ set/set_test.go | 50 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 80 insertions(+) diff --git a/set/set.go b/set/set.go index e191809..7f3b817 100644 --- a/set/set.go +++ b/set/set.go @@ -146,3 +146,33 @@ func (s *Set) List() []int { } return list } + +// Merge is like Union, however it modifies the current set it's applied on +// with the given t set. +func (s *Set) Merge(t *Set) { + for item := range t.m { + s.m[item] = keyExists + } +} + +// Separate removes the set items containing in t from set s. Please aware that +// it's not the opposite of Merge. +func (s *Set) Separate(t *Set) { + s.Remove(t.List()...) +} + +// Union is the merger of multiple sets. It returns a new set with all the +// elements present in all the sets that are passed. +func Union(set1, set2 *Set, setItems ...*Set) *Set { + u := set1.Copy() + for item := range set2.m { + u.Add(item) + } + + for _, setItem := range setItems { + for item := range setItem.m { + u.Add(item) + } + } + return u +} diff --git a/set/set_test.go b/set/set_test.go index cf43840..fd2be97 100644 --- a/set/set_test.go +++ b/set/set_test.go @@ -256,3 +256,53 @@ func TestCopy(t *testing.T) { t.Error("Copy: set s and u are not equal") } } + +func TestMerge(t *testing.T) { + s := set.NewSet() + s.Add(1, 2, 3) + r := set.NewSet() + r.Add(3, 4, 5) + s.Merge(r) + + if s.Size() != 5 { + t.Error("Merge: the set doesn't have all items in it.") + } + + if !s.Has(1, 2, 3, 4, 5) { + t.Error("Merge: merged items are not availabile in the set.") + } +} + +func TestSeparate(t *testing.T) { + s := set.NewSet() + s.Add(1, 2, 3) + r := set.NewSet() + r.Add(3, 5) + s.Separate(r) + + if s.Size() != 2 { + t.Error("Separate: the set doesn't have all items in it.") + } + + if !s.Has(1, 2) { + t.Error("Separate: items after separation are not availabile in the set.") + } +} + +func TestUnion(t *testing.T) { + s1 := set.NewSet() + s1.Add(1, 2, 3) + s2 := set.NewSet() + s2.Add(4, 5, 6) + s3 := set.NewSet() + s3.Add(1, 5, 7) + + u := set.Union(s1, s2, s3) + if u.Size() != 7 { + t.Errorf("expected size 7 got %v", u.Size()) + } + + if !u.Has(1, 2, 3, 4, 5, 6, 7) { + t.Error("merged items are not availabile in union set") + } +} From 6a1490931b86a7b4a5b69597b8012c54260d9d6e Mon Sep 17 00:00:00 2001 From: x899 Date: Wed, 11 Dec 2019 11:20:59 +0530 Subject: [PATCH 022/209] set intersection func --- set/set.go | 19 +++++++++++++++++++ set/set_test.go | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/set/set.go b/set/set.go index 7f3b817..dda3442 100644 --- a/set/set.go +++ b/set/set.go @@ -176,3 +176,22 @@ func Union(set1, set2 *Set, setItems ...*Set) *Set { } return u } + +// Intersection returns a new set which contains items that only exist in all +// given sets. +func Intersection(set1, set2 *Set, setItems ...*Set) *Set { + all := Union(set1, set2, setItems...) + result := Union(set1, set2, setItems...) + + for item := range all.m { + if !set1.Has(item) || !set2.Has(item) { + result.Remove(item) + } + for _, setItem := range setItems { + if !setItem.Has(item) { + result.Remove(item) + } + } + } + return result +} diff --git a/set/set_test.go b/set/set_test.go index fd2be97..27bd011 100644 --- a/set/set_test.go +++ b/set/set_test.go @@ -306,3 +306,37 @@ func TestUnion(t *testing.T) { t.Error("merged items are not availabile in union set") } } + +func TestIntersection(t *testing.T) { + s1 := set.NewSet() + s1.Add(1, 2, 3, 4, 5) + s2 := set.NewSet() + s2.Add(4, 2, 6, 5) + s3 := set.NewSet() + s3.Add(1, 4, 5, 7) + + u := set.Intersection(s1, s2, s3) + if u.Size() != 2 { + t.Errorf("expected size 2 got %v", u.Size()) + } + + if !u.Has(4, 5) { + t.Error("merged items are not availabile in union set") + } +} + +func TestIntersection2(t *testing.T) { + s1 := set.NewSet() + s1.Add(1, 2, 3, 4, 5) + s2 := set.NewSet() + s2.Add(6, 7) + + u := set.Intersection(s1, s2) + if u.Size() != 0 { + t.Errorf("expected size 0 got %v", u.Size()) + } + + if !u.IsEmpty() { + t.Error("union set should be empty") + } +} From 19548b56685963f6bf8f54e175a1788eb83299ae Mon Sep 17 00:00:00 2001 From: x899 Date: Thu, 12 Dec 2019 09:43:38 +0530 Subject: [PATCH 023/209] set difference symmetric difference functions --- set/set.go | 20 ++++++++++++++++++++ set/set_test.go | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/set/set.go b/set/set.go index dda3442..d29ee59 100644 --- a/set/set.go +++ b/set/set.go @@ -177,6 +177,18 @@ func Union(set1, set2 *Set, setItems ...*Set) *Set { return u } +// Difference returns a new set which contains items which are in in the first +// set but not in the others. Unlike the Separate() method you can use this +// function separately with multiple sets. +func Difference(set1, set2 *Set, sets ...*Set) *Set { + s := set1.Copy() + s.Separate(set2) + for _, set := range sets { + s.Separate(set) + } + return s +} + // Intersection returns a new set which contains items that only exist in all // given sets. func Intersection(set1, set2 *Set, setItems ...*Set) *Set { @@ -195,3 +207,11 @@ func Intersection(set1, set2 *Set, setItems ...*Set) *Set { } return result } + +// SymmetricDifference returns a new set which s is the difference of items +// which are in one of either, but not in both. +func SymmetricDifference(s *Set, t *Set) *Set { + u := Difference(s, t) + v := Difference(t, s) + return Union(u, v) +} diff --git a/set/set_test.go b/set/set_test.go index 27bd011..5304296 100644 --- a/set/set_test.go +++ b/set/set_test.go @@ -307,6 +307,24 @@ func TestUnion(t *testing.T) { } } +func TestDifference(t *testing.T) { + s1 := set.NewSet() + s1.Add(1, 2, 3) + s2 := set.NewSet() + s2.Add(4, 2, 6) + s3 := set.NewSet() + s3.Add(1, 5, 7) + + u := set.Difference(s1, s2, s3) + if u.Size() != 1 { + t.Errorf("expected size 1 got %v", u.Size()) + } + + if !u.Has(3) { + t.Error("merged items are not availabile in union set") + } +} + func TestIntersection(t *testing.T) { s1 := set.NewSet() s1.Add(1, 2, 3, 4, 5) @@ -340,3 +358,19 @@ func TestIntersection2(t *testing.T) { t.Error("union set should be empty") } } + +func TestSymmetricDifference(t *testing.T) { + s1 := set.NewSet() + s1.Add(1, 2, 3) + s2 := set.NewSet() + s2.Add(3, 4, 5) + + u := set.SymmetricDifference(s1, s2) + if u.Size() != 4 { + t.Errorf("expected size 2 got %v", u.Size()) + } + + if !u.Has(1, 2, 4, 5) { + t.Error("merged items are not availabile in union set") + } +} From 9a041d4cdd8406097e14a4ed156c5d3e75321993 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Mon, 27 Jan 2020 14:33:24 +0530 Subject: [PATCH 024/209] set test fix error msg expected value --- set/set_test.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/set/set_test.go b/set/set_test.go index 5304296..4a93388 100644 --- a/set/set_test.go +++ b/set/set_test.go @@ -35,7 +35,7 @@ func TestAddSingle(t *testing.T) { s.Add(2) // duplicate entry if actualSize := s.Size(); actualSize != 3 { - t.Errorf("wrong answer expected: 5, got:%v", actualSize) + t.Errorf("wrong answer expected: 3, got:%v", actualSize) } if !s.Has(1, 2, 3) { @@ -48,7 +48,7 @@ func TestAddMultiple(t *testing.T) { s.Add(12, 23, 35, 47) if actualSize := s.Size(); actualSize != 4 { - t.Errorf("wrong answer expected: 5, got:%v", actualSize) + t.Errorf("wrong answer expected: 4, got:%v", actualSize) } if !s.Has(12, 23, 35, 47) { @@ -367,7 +367,7 @@ func TestSymmetricDifference(t *testing.T) { u := set.SymmetricDifference(s1, s2) if u.Size() != 4 { - t.Errorf("expected size 2 got %v", u.Size()) + t.Errorf("expected size 4 got %v", u.Size()) } if !u.Has(1, 2, 4, 5) { From 562a830acd0d46237e534c5cb2d025dce9b412cf Mon Sep 17 00:00:00 2001 From: TheOneWhoDoes Date: Tue, 28 Jan 2020 16:04:59 +0330 Subject: [PATCH 025/209] add counting sort --- sort/countingSort.go | 68 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 sort/countingSort.go diff --git a/sort/countingSort.go b/sort/countingSort.go new file mode 100644 index 0000000..8d8c69a --- /dev/null +++ b/sort/countingSort.go @@ -0,0 +1,68 @@ +package main + +import "fmt" + +//use this for strings +func countingSortString(data []rune, size int) string { + length := 256 + count := make([]int, length) + output := make([]rune, size) + for i := 0; i < size; i++ { + count[data[i]]++ + } + + for i := 1; i < length; i++ { + count[i] += count[i-1] + } + + for i := 0; i < size; i++ { + output[count[data[i]]-1] = data[i] + count[data[i]]-- + } + + return string(output) +} + +func countingSortNumber(data []int, size int) []int { + min := data[0] + for _, val := range data { + if val < min { + min = val + } + } + max := data[0] + for _, val := range data { + if val > max { + max = val + } + } + + length := max - min + 1 + count := make([]int, length) + output := make([]int, size) + for i := 0; i < size; i++ { + count[data[i]-min]++ + } + + for i := 1; i < length; i++ { + count[i] += count[i-1] + } + + for i := 0; i < size; i++ { + output[count[data[i]-min]-1] = data[i] + count[data[i]-min]-- + } + + return output + +} + +func main() { + data := "golang" + g := []rune(data) + str := countingSortString(g, len(data)) + fmt.Println(str) + + arr := []int{0, -2, -9, 20, 7} + fmt.Println(countingSortNumber(arr, len(arr))) +} From 6417bbe9969340de960de3749ecbeda63f2f38bc Mon Sep 17 00:00:00 2001 From: TheOneWhoDoes Date: Wed, 29 Jan 2020 15:25:24 +0330 Subject: [PATCH 026/209] edit countingsort --- sort/countingSort.go | 53 ++++++++++---------------------------------- sort/sort_test.go | 5 +++++ 2 files changed, 17 insertions(+), 41 deletions(-) diff --git a/sort/countingSort.go b/sort/countingSort.go index 8d8c69a..8d2fb13 100644 --- a/sort/countingSort.go +++ b/sort/countingSort.go @@ -1,37 +1,19 @@ -package main - -import "fmt" - -//use this for strings -func countingSortString(data []rune, size int) string { - length := 256 - count := make([]int, length) - output := make([]rune, size) - for i := 0; i < size; i++ { - count[data[i]]++ - } - - for i := 1; i < length; i++ { - count[i] += count[i-1] - } - - for i := 0; i < size; i++ { - output[count[data[i]]-1] = data[i] - count[data[i]]-- - } - - return string(output) -} - -func countingSortNumber(data []int, size int) []int { +package sort + +/* +Counting sort is a sorting algorithm that sorts the elements of an array +by counting the number of occurrences of each unique element in the array. +The count is stored in an auxiliary array +and the sorting is done by mapping the count as an index of the auxiliary array. +*/ +func CountingSort(data []int) { + size := len(data) min := data[0] + max := data[0] for _, val := range data { if val < min { min = val } - } - max := data[0] - for _, val := range data { if val > max { max = val } @@ -53,16 +35,5 @@ func countingSortNumber(data []int, size int) []int { count[data[i]-min]-- } - return output - -} - -func main() { - data := "golang" - g := []rune(data) - str := countingSortString(g, len(data)) - fmt.Println(str) - - arr := []int{0, -2, -9, 20, 7} - fmt.Println(countingSortNumber(arr, len(arr))) + data = output } diff --git a/sort/sort_test.go b/sort/sort_test.go index 8a6dd81..5bc0891 100644 --- a/sort/sort_test.go +++ b/sort/sort_test.go @@ -62,6 +62,11 @@ func TestInsertionSort(t *testing.T) { testSortRandom(t, mysort.InsertionSort) } +func TestCountingSort(t *testing.T) { + testSort(t, mysort.CountingSort) + testSortRandom(t, mysort.CountingSort) +} + func TestBubbleSort(t *testing.T) { testSort(t, mysort.BubbleSort) testSortRandom(t, mysort.BubbleSort) From ba734ead1a610975e7cd74b3c8b93bec4aa5160c Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sun, 8 Mar 2020 20:01:39 +0530 Subject: [PATCH 027/209] folder restructuring --- Go_Implementation/README.md | 57 +++++++++++++++++++ {bst => Go_Implementation/bst}/bst.go | 0 {bst => Go_Implementation/bst}/bst_test.go | 0 {bst => Go_Implementation/bst}/checkbst.go | 0 {bst => Go_Implementation/bst}/delete.go | 0 {bst => Go_Implementation/bst}/find.go | 0 {bst => Go_Implementation/bst}/height.go | 0 {bst => Go_Implementation/bst}/insert.go | 0 {bst => Go_Implementation/bst}/traversal.go | 0 .../doublylinkedlist}/doublylinkedlist.go | 0 .../doublylinkedlist_test.go | 0 .../hashtable}/hashtable.go | 0 .../hashtable}/hashtable_test.go | 0 {heap => Go_Implementation/heap}/doc.go | 0 .../heap}/maxheap/maxheap.go | 0 .../heap}/maxheap/maxheap_test.go | 0 .../heap}/minheap/minheap.go | 0 .../heap}/minheap/minheap_test.go | 0 .../linkedlist}/linkedlist.go | 0 .../linkedlist}/linkedlist_test.go | 0 {queue => Go_Implementation/queue}/queue.go | 0 .../queue}/queue_test.go | 0 .../redblacktree}/doc.go | 0 .../redblacktree}/find.go | 0 .../redblacktree}/insert.go | 0 .../redblacktree}/redblacktree.go | 0 .../redblacktree}/redblacktree_test.go | 0 .../redblacktree}/utils.go | 0 .../search}/binarysearch.go | 0 .../search}/binarysearch_test.go | 0 {set => Go_Implementation/set}/set.go | 0 {set => Go_Implementation/set}/set_test.go | 0 .../shuffle}/shuffle.go | 0 {sort => Go_Implementation/sort}/bubble.go | 0 .../sort}/countingSort.go | 0 {sort => Go_Implementation/sort}/gnome.go | 0 {sort => Go_Implementation/sort}/heap.go | 0 {sort => Go_Implementation/sort}/insertion.go | 0 {sort => Go_Implementation/sort}/merge.go | 0 {sort => Go_Implementation/sort}/oddeven.go | 0 {sort => Go_Implementation/sort}/quick.go | 0 .../sort}/quickselect.go | 0 {sort => Go_Implementation/sort}/selection.go | 0 {sort => Go_Implementation/sort}/shell.go | 0 {sort => Go_Implementation/sort}/sort.go | 0 {sort => Go_Implementation/sort}/sort_test.go | 0 .../stack}/applications/applications.go | 0 .../stack}/applications/applications_test.go | 0 .../stack}/applications/infixevaluation.go | 0 .../stack}/applications/infixtopostfix.go | 0 .../stack}/applications/infixtoprefix.go | 0 .../stack}/applications/utils.go | 0 {stack => Go_Implementation/stack}/stack.go | 0 .../stack}/stack_test.go | 0 {trie => Go_Implementation/trie}/trie.go | 0 {trie => Go_Implementation/trie}/trie_test.go | 0 56 files changed, 57 insertions(+) create mode 100644 Go_Implementation/README.md rename {bst => Go_Implementation/bst}/bst.go (100%) rename {bst => Go_Implementation/bst}/bst_test.go (100%) rename {bst => Go_Implementation/bst}/checkbst.go (100%) rename {bst => Go_Implementation/bst}/delete.go (100%) rename {bst => Go_Implementation/bst}/find.go (100%) rename {bst => Go_Implementation/bst}/height.go (100%) rename {bst => Go_Implementation/bst}/insert.go (100%) rename {bst => Go_Implementation/bst}/traversal.go (100%) rename {doublylinkedlist => Go_Implementation/doublylinkedlist}/doublylinkedlist.go (100%) rename {doublylinkedlist => Go_Implementation/doublylinkedlist}/doublylinkedlist_test.go (100%) rename {hashtable => Go_Implementation/hashtable}/hashtable.go (100%) rename {hashtable => Go_Implementation/hashtable}/hashtable_test.go (100%) rename {heap => Go_Implementation/heap}/doc.go (100%) rename {heap => Go_Implementation/heap}/maxheap/maxheap.go (100%) rename {heap => Go_Implementation/heap}/maxheap/maxheap_test.go (100%) rename {heap => Go_Implementation/heap}/minheap/minheap.go (100%) rename {heap => Go_Implementation/heap}/minheap/minheap_test.go (100%) rename {linkedlist => Go_Implementation/linkedlist}/linkedlist.go (100%) rename {linkedlist => Go_Implementation/linkedlist}/linkedlist_test.go (100%) rename {queue => Go_Implementation/queue}/queue.go (100%) rename {queue => Go_Implementation/queue}/queue_test.go (100%) rename {redblacktree => Go_Implementation/redblacktree}/doc.go (100%) rename {redblacktree => Go_Implementation/redblacktree}/find.go (100%) rename {redblacktree => Go_Implementation/redblacktree}/insert.go (100%) rename {redblacktree => Go_Implementation/redblacktree}/redblacktree.go (100%) rename {redblacktree => Go_Implementation/redblacktree}/redblacktree_test.go (100%) rename {redblacktree => Go_Implementation/redblacktree}/utils.go (100%) rename {search => Go_Implementation/search}/binarysearch.go (100%) rename {search => Go_Implementation/search}/binarysearch_test.go (100%) rename {set => Go_Implementation/set}/set.go (100%) rename {set => Go_Implementation/set}/set_test.go (100%) rename {shuffle => Go_Implementation/shuffle}/shuffle.go (100%) rename {sort => Go_Implementation/sort}/bubble.go (100%) rename {sort => Go_Implementation/sort}/countingSort.go (100%) rename {sort => Go_Implementation/sort}/gnome.go (100%) rename {sort => Go_Implementation/sort}/heap.go (100%) rename {sort => Go_Implementation/sort}/insertion.go (100%) rename {sort => Go_Implementation/sort}/merge.go (100%) rename {sort => Go_Implementation/sort}/oddeven.go (100%) rename {sort => Go_Implementation/sort}/quick.go (100%) rename {sort => Go_Implementation/sort}/quickselect.go (100%) rename {sort => Go_Implementation/sort}/selection.go (100%) rename {sort => Go_Implementation/sort}/shell.go (100%) rename {sort => Go_Implementation/sort}/sort.go (100%) rename {sort => Go_Implementation/sort}/sort_test.go (100%) rename {stack => Go_Implementation/stack}/applications/applications.go (100%) rename {stack => Go_Implementation/stack}/applications/applications_test.go (100%) rename {stack => Go_Implementation/stack}/applications/infixevaluation.go (100%) rename {stack => Go_Implementation/stack}/applications/infixtopostfix.go (100%) rename {stack => Go_Implementation/stack}/applications/infixtoprefix.go (100%) rename {stack => Go_Implementation/stack}/applications/utils.go (100%) rename {stack => Go_Implementation/stack}/stack.go (100%) rename {stack => Go_Implementation/stack}/stack_test.go (100%) rename {trie => Go_Implementation/trie}/trie.go (100%) rename {trie => Go_Implementation/trie}/trie_test.go (100%) diff --git a/Go_Implementation/README.md b/Go_Implementation/README.md new file mode 100644 index 0000000..c4d4d18 --- /dev/null +++ b/Go_Implementation/README.md @@ -0,0 +1,57 @@ +# Algorithms +Data Structure Libraries and Algorithms implementation in Go + +[![GoDoc](https://godoc.org/github.com/x899/algorithms?status.svg)](https://godoc.org/github.com/x899/algorithms) [![Go Report Card](https://goreportcard.com/badge/github.com/x899/algorithms)](https://goreportcard.com/report/github.com/x899/algorithms) + +**Disclaimer**
+This repository is meant to be used as a reference to learn data structure and +algorithm in Go programming language.
To reduce unnecessary language +complexity, all the programs only uses integer or string dataset. + +**Documentation**
+[Click to view goDoc Documentation](https://godoc.org/github.com/x899/algorithms) + +## Data structure +* Sorting Algorithms + * [Bubble Sort](https://en.wikipedia.org/wiki/Bubble_sort) + * [Selection Sort](https://en.wikipedia.org/wiki/Selection_sort) + * [Insertion Sort](https://en.wikipedia.org/wiki/Insertion_sort) + * [Merge Sort](https://en.wikipedia.org/wiki/Merge_sort) + * [Quick Sort](https://en.wikipedia.org/wiki/Quicksort) + * [Quick Select](https://en.wikipedia.org/wiki/Quickselect) + * [Shell Sort](https://en.wikipedia.org/wiki/Shellsort) + * [Heap Sort](https://en.wikipedia.org/wiki/Heapsort) +* [Stack (Array Implementation)](https://en.wikipedia.org/wiki/Stack_(abstract_data_type)) + * Infix to Postfix + * Infix to Prefix + * Infix Evaluation +* [Queue (Array Implementation)](https://en.wikipedia.org/wiki/Queue_(abstract_data_type)) +* LinkedList + * [Singly Linked List](https://en.wikipedia.org/wiki/Linked_list) + * [Doubly Linked List](https://en.wikipedia.org/wiki/Doubly_linked_list) +* [Shuffle (Using Fisher-Yates (Knuth) shuffling algorithm)](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) +* [Binary Search Tree](https://en.wikipedia.org/wiki/Binary_search_tree) +* [Binary Heap](https://en.wikipedia.org/wiki/Binary_heap) + * Min Heap + * Max Heap +* [Red Black Tree](https://en.wikipedia.org/wiki/Red%E2%80%93black_tree) +* Search + * [Binary Search](https://en.wikipedia.org/wiki/Binary_search_algorithm) + +## TO DO +* Vertical Order Traversal of Tree +* Order Statistics of Tree +* Red Black Tree Deletion +* B-Tree +* Deque using circular array +* Tree Varient +* Graph Varient +* [cocktail sort](https://en.wikipedia.org/wiki/Cocktail_shaker_sort) +* [gnome sort](https://en.wikipedia.org/wiki/Gnome_sort) +* [comb sort](https://en.wikipedia.org/wiki/Comb_sort) +* [odd-even sort](https://en.wikipedia.org/wiki/Odd%E2%80%93even_sort) +* [counting sort](https://en.wikipedia.org/wiki/Counting_sort) + +## Contribution +Feel Free to contribute.
+Please follow standard GoLang Guidelines. diff --git a/bst/bst.go b/Go_Implementation/bst/bst.go similarity index 100% rename from bst/bst.go rename to Go_Implementation/bst/bst.go diff --git a/bst/bst_test.go b/Go_Implementation/bst/bst_test.go similarity index 100% rename from bst/bst_test.go rename to Go_Implementation/bst/bst_test.go diff --git a/bst/checkbst.go b/Go_Implementation/bst/checkbst.go similarity index 100% rename from bst/checkbst.go rename to Go_Implementation/bst/checkbst.go diff --git a/bst/delete.go b/Go_Implementation/bst/delete.go similarity index 100% rename from bst/delete.go rename to Go_Implementation/bst/delete.go diff --git a/bst/find.go b/Go_Implementation/bst/find.go similarity index 100% rename from bst/find.go rename to Go_Implementation/bst/find.go diff --git a/bst/height.go b/Go_Implementation/bst/height.go similarity index 100% rename from bst/height.go rename to Go_Implementation/bst/height.go diff --git a/bst/insert.go b/Go_Implementation/bst/insert.go similarity index 100% rename from bst/insert.go rename to Go_Implementation/bst/insert.go diff --git a/bst/traversal.go b/Go_Implementation/bst/traversal.go similarity index 100% rename from bst/traversal.go rename to Go_Implementation/bst/traversal.go diff --git a/doublylinkedlist/doublylinkedlist.go b/Go_Implementation/doublylinkedlist/doublylinkedlist.go similarity index 100% rename from doublylinkedlist/doublylinkedlist.go rename to Go_Implementation/doublylinkedlist/doublylinkedlist.go diff --git a/doublylinkedlist/doublylinkedlist_test.go b/Go_Implementation/doublylinkedlist/doublylinkedlist_test.go similarity index 100% rename from doublylinkedlist/doublylinkedlist_test.go rename to Go_Implementation/doublylinkedlist/doublylinkedlist_test.go diff --git a/hashtable/hashtable.go b/Go_Implementation/hashtable/hashtable.go similarity index 100% rename from hashtable/hashtable.go rename to Go_Implementation/hashtable/hashtable.go diff --git a/hashtable/hashtable_test.go b/Go_Implementation/hashtable/hashtable_test.go similarity index 100% rename from hashtable/hashtable_test.go rename to Go_Implementation/hashtable/hashtable_test.go diff --git a/heap/doc.go b/Go_Implementation/heap/doc.go similarity index 100% rename from heap/doc.go rename to Go_Implementation/heap/doc.go diff --git a/heap/maxheap/maxheap.go b/Go_Implementation/heap/maxheap/maxheap.go similarity index 100% rename from heap/maxheap/maxheap.go rename to Go_Implementation/heap/maxheap/maxheap.go diff --git a/heap/maxheap/maxheap_test.go b/Go_Implementation/heap/maxheap/maxheap_test.go similarity index 100% rename from heap/maxheap/maxheap_test.go rename to Go_Implementation/heap/maxheap/maxheap_test.go diff --git a/heap/minheap/minheap.go b/Go_Implementation/heap/minheap/minheap.go similarity index 100% rename from heap/minheap/minheap.go rename to Go_Implementation/heap/minheap/minheap.go diff --git a/heap/minheap/minheap_test.go b/Go_Implementation/heap/minheap/minheap_test.go similarity index 100% rename from heap/minheap/minheap_test.go rename to Go_Implementation/heap/minheap/minheap_test.go diff --git a/linkedlist/linkedlist.go b/Go_Implementation/linkedlist/linkedlist.go similarity index 100% rename from linkedlist/linkedlist.go rename to Go_Implementation/linkedlist/linkedlist.go diff --git a/linkedlist/linkedlist_test.go b/Go_Implementation/linkedlist/linkedlist_test.go similarity index 100% rename from linkedlist/linkedlist_test.go rename to Go_Implementation/linkedlist/linkedlist_test.go diff --git a/queue/queue.go b/Go_Implementation/queue/queue.go similarity index 100% rename from queue/queue.go rename to Go_Implementation/queue/queue.go diff --git a/queue/queue_test.go b/Go_Implementation/queue/queue_test.go similarity index 100% rename from queue/queue_test.go rename to Go_Implementation/queue/queue_test.go diff --git a/redblacktree/doc.go b/Go_Implementation/redblacktree/doc.go similarity index 100% rename from redblacktree/doc.go rename to Go_Implementation/redblacktree/doc.go diff --git a/redblacktree/find.go b/Go_Implementation/redblacktree/find.go similarity index 100% rename from redblacktree/find.go rename to Go_Implementation/redblacktree/find.go diff --git a/redblacktree/insert.go b/Go_Implementation/redblacktree/insert.go similarity index 100% rename from redblacktree/insert.go rename to Go_Implementation/redblacktree/insert.go diff --git a/redblacktree/redblacktree.go b/Go_Implementation/redblacktree/redblacktree.go similarity index 100% rename from redblacktree/redblacktree.go rename to Go_Implementation/redblacktree/redblacktree.go diff --git a/redblacktree/redblacktree_test.go b/Go_Implementation/redblacktree/redblacktree_test.go similarity index 100% rename from redblacktree/redblacktree_test.go rename to Go_Implementation/redblacktree/redblacktree_test.go diff --git a/redblacktree/utils.go b/Go_Implementation/redblacktree/utils.go similarity index 100% rename from redblacktree/utils.go rename to Go_Implementation/redblacktree/utils.go diff --git a/search/binarysearch.go b/Go_Implementation/search/binarysearch.go similarity index 100% rename from search/binarysearch.go rename to Go_Implementation/search/binarysearch.go diff --git a/search/binarysearch_test.go b/Go_Implementation/search/binarysearch_test.go similarity index 100% rename from search/binarysearch_test.go rename to Go_Implementation/search/binarysearch_test.go diff --git a/set/set.go b/Go_Implementation/set/set.go similarity index 100% rename from set/set.go rename to Go_Implementation/set/set.go diff --git a/set/set_test.go b/Go_Implementation/set/set_test.go similarity index 100% rename from set/set_test.go rename to Go_Implementation/set/set_test.go diff --git a/shuffle/shuffle.go b/Go_Implementation/shuffle/shuffle.go similarity index 100% rename from shuffle/shuffle.go rename to Go_Implementation/shuffle/shuffle.go diff --git a/sort/bubble.go b/Go_Implementation/sort/bubble.go similarity index 100% rename from sort/bubble.go rename to Go_Implementation/sort/bubble.go diff --git a/sort/countingSort.go b/Go_Implementation/sort/countingSort.go similarity index 100% rename from sort/countingSort.go rename to Go_Implementation/sort/countingSort.go diff --git a/sort/gnome.go b/Go_Implementation/sort/gnome.go similarity index 100% rename from sort/gnome.go rename to Go_Implementation/sort/gnome.go diff --git a/sort/heap.go b/Go_Implementation/sort/heap.go similarity index 100% rename from sort/heap.go rename to Go_Implementation/sort/heap.go diff --git a/sort/insertion.go b/Go_Implementation/sort/insertion.go similarity index 100% rename from sort/insertion.go rename to Go_Implementation/sort/insertion.go diff --git a/sort/merge.go b/Go_Implementation/sort/merge.go similarity index 100% rename from sort/merge.go rename to Go_Implementation/sort/merge.go diff --git a/sort/oddeven.go b/Go_Implementation/sort/oddeven.go similarity index 100% rename from sort/oddeven.go rename to Go_Implementation/sort/oddeven.go diff --git a/sort/quick.go b/Go_Implementation/sort/quick.go similarity index 100% rename from sort/quick.go rename to Go_Implementation/sort/quick.go diff --git a/sort/quickselect.go b/Go_Implementation/sort/quickselect.go similarity index 100% rename from sort/quickselect.go rename to Go_Implementation/sort/quickselect.go diff --git a/sort/selection.go b/Go_Implementation/sort/selection.go similarity index 100% rename from sort/selection.go rename to Go_Implementation/sort/selection.go diff --git a/sort/shell.go b/Go_Implementation/sort/shell.go similarity index 100% rename from sort/shell.go rename to Go_Implementation/sort/shell.go diff --git a/sort/sort.go b/Go_Implementation/sort/sort.go similarity index 100% rename from sort/sort.go rename to Go_Implementation/sort/sort.go diff --git a/sort/sort_test.go b/Go_Implementation/sort/sort_test.go similarity index 100% rename from sort/sort_test.go rename to Go_Implementation/sort/sort_test.go diff --git a/stack/applications/applications.go b/Go_Implementation/stack/applications/applications.go similarity index 100% rename from stack/applications/applications.go rename to Go_Implementation/stack/applications/applications.go diff --git a/stack/applications/applications_test.go b/Go_Implementation/stack/applications/applications_test.go similarity index 100% rename from stack/applications/applications_test.go rename to Go_Implementation/stack/applications/applications_test.go diff --git a/stack/applications/infixevaluation.go b/Go_Implementation/stack/applications/infixevaluation.go similarity index 100% rename from stack/applications/infixevaluation.go rename to Go_Implementation/stack/applications/infixevaluation.go diff --git a/stack/applications/infixtopostfix.go b/Go_Implementation/stack/applications/infixtopostfix.go similarity index 100% rename from stack/applications/infixtopostfix.go rename to Go_Implementation/stack/applications/infixtopostfix.go diff --git a/stack/applications/infixtoprefix.go b/Go_Implementation/stack/applications/infixtoprefix.go similarity index 100% rename from stack/applications/infixtoprefix.go rename to Go_Implementation/stack/applications/infixtoprefix.go diff --git a/stack/applications/utils.go b/Go_Implementation/stack/applications/utils.go similarity index 100% rename from stack/applications/utils.go rename to Go_Implementation/stack/applications/utils.go diff --git a/stack/stack.go b/Go_Implementation/stack/stack.go similarity index 100% rename from stack/stack.go rename to Go_Implementation/stack/stack.go diff --git a/stack/stack_test.go b/Go_Implementation/stack/stack_test.go similarity index 100% rename from stack/stack_test.go rename to Go_Implementation/stack/stack_test.go diff --git a/trie/trie.go b/Go_Implementation/trie/trie.go similarity index 100% rename from trie/trie.go rename to Go_Implementation/trie/trie.go diff --git a/trie/trie_test.go b/Go_Implementation/trie/trie_test.go similarity index 100% rename from trie/trie_test.go rename to Go_Implementation/trie/trie_test.go From ae69003ba380a28b1b66e10273ec537cb626e87a Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sun, 8 Mar 2020 20:04:13 +0530 Subject: [PATCH 028/209] folder restructuring 2 --- .../dynamic_connectivity/quick_find/Makefile | 0 .../dynamic_connectivity/quick_find/main.c | 0 .../dynamic_connectivity/quick_find/quick_find.c | 0 .../dynamic_connectivity/quick_find/quick_find.h | 0 .../dynamic_connectivity/quick_union/Makefile | 0 .../dynamic_connectivity/quick_union/main.c | 0 .../dynamic_connectivity/quick_union/quick_union.c | 0 .../dynamic_connectivity/quick_union/quick_union.h | 0 {c(deprecated) => C_Deprecated}/queue/Makefile | 0 {c(deprecated) => C_Deprecated}/queue/main.c | 0 {c(deprecated) => C_Deprecated}/queue/queue.c | 0 {c(deprecated) => C_Deprecated}/queue/queue.h | 0 {c(deprecated) => C_Deprecated}/shuffling/Makefile | 0 {c(deprecated) => C_Deprecated}/shuffling/shuffle_array.c | 0 {c(deprecated) => C_Deprecated}/sorts/bubble_sort/Makefile | 0 {c(deprecated) => C_Deprecated}/sorts/bubble_sort/bubble_sort.c | 0 {c(deprecated) => C_Deprecated}/sorts/generic/Makefile | 0 {c(deprecated) => C_Deprecated}/sorts/generic/README.md | 0 {c(deprecated) => C_Deprecated}/sorts/generic/main.c | 0 {c(deprecated) => C_Deprecated}/sorts/generic/sort.c | 0 {c(deprecated) => C_Deprecated}/sorts/generic/sort.h | 0 {c(deprecated) => C_Deprecated}/sorts/insertion_sort/Makefile | 0 .../sorts/insertion_sort/insertion_sort.c | 0 {c(deprecated) => C_Deprecated}/sorts/merge_sort/Makefile | 0 {c(deprecated) => C_Deprecated}/sorts/merge_sort/merge_sort.c | 0 {c(deprecated) => C_Deprecated}/sorts/quick_sort/Makefile | 0 {c(deprecated) => C_Deprecated}/sorts/quick_sort/quick_sort.c | 0 {c(deprecated) => C_Deprecated}/sorts/selection_sort/Makefile | 0 .../sorts/selection_sort/selection_sort.c | 0 {c(deprecated) => C_Deprecated}/sorts/shell_sort/Makefile | 0 {c(deprecated) => C_Deprecated}/sorts/shell_sort/shell_sort.c | 0 .../stack/array_implementation/Makefile | 0 {c(deprecated) => C_Deprecated}/stack/array_implementation/main.c | 0 .../stack/array_implementation/stack.c | 0 .../stack/array_implementation/stack.h | 0 .../stack/generic_array_implementation/Makefile | 0 .../stack/generic_array_implementation/main.c | 0 .../stack/generic_array_implementation/stack.c | 0 .../stack/generic_array_implementation/stack.h | 0 39 files changed, 0 insertions(+), 0 deletions(-) rename {c(deprecated) => C_Deprecated}/dynamic_connectivity/quick_find/Makefile (100%) rename {c(deprecated) => C_Deprecated}/dynamic_connectivity/quick_find/main.c (100%) rename {c(deprecated) => C_Deprecated}/dynamic_connectivity/quick_find/quick_find.c (100%) rename {c(deprecated) => C_Deprecated}/dynamic_connectivity/quick_find/quick_find.h (100%) rename {c(deprecated) => C_Deprecated}/dynamic_connectivity/quick_union/Makefile (100%) rename {c(deprecated) => C_Deprecated}/dynamic_connectivity/quick_union/main.c (100%) rename {c(deprecated) => C_Deprecated}/dynamic_connectivity/quick_union/quick_union.c (100%) rename {c(deprecated) => C_Deprecated}/dynamic_connectivity/quick_union/quick_union.h (100%) rename {c(deprecated) => C_Deprecated}/queue/Makefile (100%) rename {c(deprecated) => C_Deprecated}/queue/main.c (100%) rename {c(deprecated) => C_Deprecated}/queue/queue.c (100%) rename {c(deprecated) => C_Deprecated}/queue/queue.h (100%) rename {c(deprecated) => C_Deprecated}/shuffling/Makefile (100%) rename {c(deprecated) => C_Deprecated}/shuffling/shuffle_array.c (100%) rename {c(deprecated) => C_Deprecated}/sorts/bubble_sort/Makefile (100%) rename {c(deprecated) => C_Deprecated}/sorts/bubble_sort/bubble_sort.c (100%) rename {c(deprecated) => C_Deprecated}/sorts/generic/Makefile (100%) rename {c(deprecated) => C_Deprecated}/sorts/generic/README.md (100%) rename {c(deprecated) => C_Deprecated}/sorts/generic/main.c (100%) rename {c(deprecated) => C_Deprecated}/sorts/generic/sort.c (100%) rename {c(deprecated) => C_Deprecated}/sorts/generic/sort.h (100%) rename {c(deprecated) => C_Deprecated}/sorts/insertion_sort/Makefile (100%) rename {c(deprecated) => C_Deprecated}/sorts/insertion_sort/insertion_sort.c (100%) rename {c(deprecated) => C_Deprecated}/sorts/merge_sort/Makefile (100%) rename {c(deprecated) => C_Deprecated}/sorts/merge_sort/merge_sort.c (100%) rename {c(deprecated) => C_Deprecated}/sorts/quick_sort/Makefile (100%) rename {c(deprecated) => C_Deprecated}/sorts/quick_sort/quick_sort.c (100%) rename {c(deprecated) => C_Deprecated}/sorts/selection_sort/Makefile (100%) rename {c(deprecated) => C_Deprecated}/sorts/selection_sort/selection_sort.c (100%) rename {c(deprecated) => C_Deprecated}/sorts/shell_sort/Makefile (100%) rename {c(deprecated) => C_Deprecated}/sorts/shell_sort/shell_sort.c (100%) rename {c(deprecated) => C_Deprecated}/stack/array_implementation/Makefile (100%) rename {c(deprecated) => C_Deprecated}/stack/array_implementation/main.c (100%) rename {c(deprecated) => C_Deprecated}/stack/array_implementation/stack.c (100%) rename {c(deprecated) => C_Deprecated}/stack/array_implementation/stack.h (100%) rename {c(deprecated) => C_Deprecated}/stack/generic_array_implementation/Makefile (100%) rename {c(deprecated) => C_Deprecated}/stack/generic_array_implementation/main.c (100%) rename {c(deprecated) => C_Deprecated}/stack/generic_array_implementation/stack.c (100%) rename {c(deprecated) => C_Deprecated}/stack/generic_array_implementation/stack.h (100%) diff --git a/c(deprecated)/dynamic_connectivity/quick_find/Makefile b/C_Deprecated/dynamic_connectivity/quick_find/Makefile similarity index 100% rename from c(deprecated)/dynamic_connectivity/quick_find/Makefile rename to C_Deprecated/dynamic_connectivity/quick_find/Makefile diff --git a/c(deprecated)/dynamic_connectivity/quick_find/main.c b/C_Deprecated/dynamic_connectivity/quick_find/main.c similarity index 100% rename from c(deprecated)/dynamic_connectivity/quick_find/main.c rename to C_Deprecated/dynamic_connectivity/quick_find/main.c diff --git a/c(deprecated)/dynamic_connectivity/quick_find/quick_find.c b/C_Deprecated/dynamic_connectivity/quick_find/quick_find.c similarity index 100% rename from c(deprecated)/dynamic_connectivity/quick_find/quick_find.c rename to C_Deprecated/dynamic_connectivity/quick_find/quick_find.c diff --git a/c(deprecated)/dynamic_connectivity/quick_find/quick_find.h b/C_Deprecated/dynamic_connectivity/quick_find/quick_find.h similarity index 100% rename from c(deprecated)/dynamic_connectivity/quick_find/quick_find.h rename to C_Deprecated/dynamic_connectivity/quick_find/quick_find.h diff --git a/c(deprecated)/dynamic_connectivity/quick_union/Makefile b/C_Deprecated/dynamic_connectivity/quick_union/Makefile similarity index 100% rename from c(deprecated)/dynamic_connectivity/quick_union/Makefile rename to C_Deprecated/dynamic_connectivity/quick_union/Makefile diff --git a/c(deprecated)/dynamic_connectivity/quick_union/main.c b/C_Deprecated/dynamic_connectivity/quick_union/main.c similarity index 100% rename from c(deprecated)/dynamic_connectivity/quick_union/main.c rename to C_Deprecated/dynamic_connectivity/quick_union/main.c diff --git a/c(deprecated)/dynamic_connectivity/quick_union/quick_union.c b/C_Deprecated/dynamic_connectivity/quick_union/quick_union.c similarity index 100% rename from c(deprecated)/dynamic_connectivity/quick_union/quick_union.c rename to C_Deprecated/dynamic_connectivity/quick_union/quick_union.c diff --git a/c(deprecated)/dynamic_connectivity/quick_union/quick_union.h b/C_Deprecated/dynamic_connectivity/quick_union/quick_union.h similarity index 100% rename from c(deprecated)/dynamic_connectivity/quick_union/quick_union.h rename to C_Deprecated/dynamic_connectivity/quick_union/quick_union.h diff --git a/c(deprecated)/queue/Makefile b/C_Deprecated/queue/Makefile similarity index 100% rename from c(deprecated)/queue/Makefile rename to C_Deprecated/queue/Makefile diff --git a/c(deprecated)/queue/main.c b/C_Deprecated/queue/main.c similarity index 100% rename from c(deprecated)/queue/main.c rename to C_Deprecated/queue/main.c diff --git a/c(deprecated)/queue/queue.c b/C_Deprecated/queue/queue.c similarity index 100% rename from c(deprecated)/queue/queue.c rename to C_Deprecated/queue/queue.c diff --git a/c(deprecated)/queue/queue.h b/C_Deprecated/queue/queue.h similarity index 100% rename from c(deprecated)/queue/queue.h rename to C_Deprecated/queue/queue.h diff --git a/c(deprecated)/shuffling/Makefile b/C_Deprecated/shuffling/Makefile similarity index 100% rename from c(deprecated)/shuffling/Makefile rename to C_Deprecated/shuffling/Makefile diff --git a/c(deprecated)/shuffling/shuffle_array.c b/C_Deprecated/shuffling/shuffle_array.c similarity index 100% rename from c(deprecated)/shuffling/shuffle_array.c rename to C_Deprecated/shuffling/shuffle_array.c diff --git a/c(deprecated)/sorts/bubble_sort/Makefile b/C_Deprecated/sorts/bubble_sort/Makefile similarity index 100% rename from c(deprecated)/sorts/bubble_sort/Makefile rename to C_Deprecated/sorts/bubble_sort/Makefile diff --git a/c(deprecated)/sorts/bubble_sort/bubble_sort.c b/C_Deprecated/sorts/bubble_sort/bubble_sort.c similarity index 100% rename from c(deprecated)/sorts/bubble_sort/bubble_sort.c rename to C_Deprecated/sorts/bubble_sort/bubble_sort.c diff --git a/c(deprecated)/sorts/generic/Makefile b/C_Deprecated/sorts/generic/Makefile similarity index 100% rename from c(deprecated)/sorts/generic/Makefile rename to C_Deprecated/sorts/generic/Makefile diff --git a/c(deprecated)/sorts/generic/README.md b/C_Deprecated/sorts/generic/README.md similarity index 100% rename from c(deprecated)/sorts/generic/README.md rename to C_Deprecated/sorts/generic/README.md diff --git a/c(deprecated)/sorts/generic/main.c b/C_Deprecated/sorts/generic/main.c similarity index 100% rename from c(deprecated)/sorts/generic/main.c rename to C_Deprecated/sorts/generic/main.c diff --git a/c(deprecated)/sorts/generic/sort.c b/C_Deprecated/sorts/generic/sort.c similarity index 100% rename from c(deprecated)/sorts/generic/sort.c rename to C_Deprecated/sorts/generic/sort.c diff --git a/c(deprecated)/sorts/generic/sort.h b/C_Deprecated/sorts/generic/sort.h similarity index 100% rename from c(deprecated)/sorts/generic/sort.h rename to C_Deprecated/sorts/generic/sort.h diff --git a/c(deprecated)/sorts/insertion_sort/Makefile b/C_Deprecated/sorts/insertion_sort/Makefile similarity index 100% rename from c(deprecated)/sorts/insertion_sort/Makefile rename to C_Deprecated/sorts/insertion_sort/Makefile diff --git a/c(deprecated)/sorts/insertion_sort/insertion_sort.c b/C_Deprecated/sorts/insertion_sort/insertion_sort.c similarity index 100% rename from c(deprecated)/sorts/insertion_sort/insertion_sort.c rename to C_Deprecated/sorts/insertion_sort/insertion_sort.c diff --git a/c(deprecated)/sorts/merge_sort/Makefile b/C_Deprecated/sorts/merge_sort/Makefile similarity index 100% rename from c(deprecated)/sorts/merge_sort/Makefile rename to C_Deprecated/sorts/merge_sort/Makefile diff --git a/c(deprecated)/sorts/merge_sort/merge_sort.c b/C_Deprecated/sorts/merge_sort/merge_sort.c similarity index 100% rename from c(deprecated)/sorts/merge_sort/merge_sort.c rename to C_Deprecated/sorts/merge_sort/merge_sort.c diff --git a/c(deprecated)/sorts/quick_sort/Makefile b/C_Deprecated/sorts/quick_sort/Makefile similarity index 100% rename from c(deprecated)/sorts/quick_sort/Makefile rename to C_Deprecated/sorts/quick_sort/Makefile diff --git a/c(deprecated)/sorts/quick_sort/quick_sort.c b/C_Deprecated/sorts/quick_sort/quick_sort.c similarity index 100% rename from c(deprecated)/sorts/quick_sort/quick_sort.c rename to C_Deprecated/sorts/quick_sort/quick_sort.c diff --git a/c(deprecated)/sorts/selection_sort/Makefile b/C_Deprecated/sorts/selection_sort/Makefile similarity index 100% rename from c(deprecated)/sorts/selection_sort/Makefile rename to C_Deprecated/sorts/selection_sort/Makefile diff --git a/c(deprecated)/sorts/selection_sort/selection_sort.c b/C_Deprecated/sorts/selection_sort/selection_sort.c similarity index 100% rename from c(deprecated)/sorts/selection_sort/selection_sort.c rename to C_Deprecated/sorts/selection_sort/selection_sort.c diff --git a/c(deprecated)/sorts/shell_sort/Makefile b/C_Deprecated/sorts/shell_sort/Makefile similarity index 100% rename from c(deprecated)/sorts/shell_sort/Makefile rename to C_Deprecated/sorts/shell_sort/Makefile diff --git a/c(deprecated)/sorts/shell_sort/shell_sort.c b/C_Deprecated/sorts/shell_sort/shell_sort.c similarity index 100% rename from c(deprecated)/sorts/shell_sort/shell_sort.c rename to C_Deprecated/sorts/shell_sort/shell_sort.c diff --git a/c(deprecated)/stack/array_implementation/Makefile b/C_Deprecated/stack/array_implementation/Makefile similarity index 100% rename from c(deprecated)/stack/array_implementation/Makefile rename to C_Deprecated/stack/array_implementation/Makefile diff --git a/c(deprecated)/stack/array_implementation/main.c b/C_Deprecated/stack/array_implementation/main.c similarity index 100% rename from c(deprecated)/stack/array_implementation/main.c rename to C_Deprecated/stack/array_implementation/main.c diff --git a/c(deprecated)/stack/array_implementation/stack.c b/C_Deprecated/stack/array_implementation/stack.c similarity index 100% rename from c(deprecated)/stack/array_implementation/stack.c rename to C_Deprecated/stack/array_implementation/stack.c diff --git a/c(deprecated)/stack/array_implementation/stack.h b/C_Deprecated/stack/array_implementation/stack.h similarity index 100% rename from c(deprecated)/stack/array_implementation/stack.h rename to C_Deprecated/stack/array_implementation/stack.h diff --git a/c(deprecated)/stack/generic_array_implementation/Makefile b/C_Deprecated/stack/generic_array_implementation/Makefile similarity index 100% rename from c(deprecated)/stack/generic_array_implementation/Makefile rename to C_Deprecated/stack/generic_array_implementation/Makefile diff --git a/c(deprecated)/stack/generic_array_implementation/main.c b/C_Deprecated/stack/generic_array_implementation/main.c similarity index 100% rename from c(deprecated)/stack/generic_array_implementation/main.c rename to C_Deprecated/stack/generic_array_implementation/main.c diff --git a/c(deprecated)/stack/generic_array_implementation/stack.c b/C_Deprecated/stack/generic_array_implementation/stack.c similarity index 100% rename from c(deprecated)/stack/generic_array_implementation/stack.c rename to C_Deprecated/stack/generic_array_implementation/stack.c diff --git a/c(deprecated)/stack/generic_array_implementation/stack.h b/C_Deprecated/stack/generic_array_implementation/stack.h similarity index 100% rename from c(deprecated)/stack/generic_array_implementation/stack.h rename to C_Deprecated/stack/generic_array_implementation/stack.h From d46191f588c9689181a6259ce7032c4c3fa174f3 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Mon, 9 Mar 2020 07:57:43 +0530 Subject: [PATCH 029/209] add linkedlist insertion algorithms --- .gitignore | 5 +- LinkedList/LinkedList.cpp | 61 ++++++++++++++++ LinkedList/LinkedList.hpp | 24 +++++++ LinkedList/Makefile | 13 ++++ LinkedList/test_LinkedList.cpp | 128 +++++++++++++++++++++++++++++++++ 5 files changed, 230 insertions(+), 1 deletion(-) create mode 100644 LinkedList/LinkedList.cpp create mode 100644 LinkedList/LinkedList.hpp create mode 100644 LinkedList/Makefile create mode 100755 LinkedList/test_LinkedList.cpp diff --git a/.gitignore b/.gitignore index 9d6bf16..53df7dd 100644 --- a/.gitignore +++ b/.gitignore @@ -51,4 +51,7 @@ Module.symvers Mkfile.old dkms.conf -.idea \ No newline at end of file +.idea + +# google test source code +googletest diff --git a/LinkedList/LinkedList.cpp b/LinkedList/LinkedList.cpp new file mode 100644 index 0000000..ebcff99 --- /dev/null +++ b/LinkedList/LinkedList.cpp @@ -0,0 +1,61 @@ +#include +#include "LinkedList.hpp" + +int LinkedList::getLength() { + Node* temp = head; + int count = 0; + while (temp) { + count++; + temp = temp->next; + } + return count; +} + +void LinkedList::insertHead(int data) { + Node* temp = new Node(data); + temp->next = head; + head = temp; +} + +void LinkedList::insertEnd(int data) { + Node* newNode = new Node(data); + Node* temp = head; + if (temp == nullptr) { + head = newNode; + return; + } + while(temp->next != nullptr) { + temp = temp->next; + } + temp->next = newNode; +} + +void LinkedList::insertAt(int data, int position) { + int linkedlist_len = getLength(); + if (position <= 1) { + insertHead(data); + return; + } else if (position >= linkedlist_len) { + insertEnd(data); + return; + } else { + Node* newNode = new Node(data); + Node* previous = head; + Node* current = head; + for (int i = 1; i < position; i++) { + previous = current; + current = current->next; + } + previous->next = newNode; + newNode->next = current; + } +} + +void LinkedList::printLinkedList() { + Node* temp = head; + while (temp) { + std::cout << " -> " << temp->data; + temp = temp->next; + } + std::cout << std::endl; +} \ No newline at end of file diff --git a/LinkedList/LinkedList.hpp b/LinkedList/LinkedList.hpp new file mode 100644 index 0000000..996f071 --- /dev/null +++ b/LinkedList/LinkedList.hpp @@ -0,0 +1,24 @@ +#ifndef LINKEDLIST_H +#define LINKEDLIST_H + +struct Node { + int data; + Node* next; + + Node(int _data) { data = _data; next = nullptr; } +}; + +class LinkedList { +private: + Node* head; +public: + LinkedList() { head = nullptr; } + Node* getHead() { return head; } + void insertHead(int data); + void insertEnd(int data); + void insertAt(int data, int position); + int getLength(); + void printLinkedList(); +}; + +#endif diff --git a/LinkedList/Makefile b/LinkedList/Makefile new file mode 100644 index 0000000..db6d622 --- /dev/null +++ b/LinkedList/Makefile @@ -0,0 +1,13 @@ +CC=g++ +GTEST_INCLUDE_PATH=../googletest/googletest/include/ +GTEST_LIBRARY_PATH=../googletest/build/lib/ -lgtest -lgtest_main +CCFLAGS=-Wall -std=c++14 -I$(GTEST_INCLUDE_PATH) -L$(GTEST_LIBRARY_PATH) + +all: LinkedList.o + $(CC) test_LinkedList.cpp LinkedList.o $(CCFLAGS) + +LinkedList.o: + $(CC) -c LinkedList.cpp + +clean: + rm ./a.out *.o diff --git a/LinkedList/test_LinkedList.cpp b/LinkedList/test_LinkedList.cpp new file mode 100755 index 0000000..f9c615e --- /dev/null +++ b/LinkedList/test_LinkedList.cpp @@ -0,0 +1,128 @@ +#include +#include +#include +#include "LinkedList.hpp" + +int getTailData(Node* node) { + while (node->next != nullptr) { + node = node->next; + } + return node->data; +} + +std::vector convertLinkedListToVector(Node* head) { + std::vector result; + Node* temp = head; + while(temp) { + result.push_back(temp->data); + temp = temp->next; + } + return result; +} + +// test insertHead method on empty linked list +TEST(LinkedListEmptyInit, InsertHeadTest) { + LinkedList ll; + ll.insertHead(1); + ASSERT_EQ(1, ll.getHead()->data); + ll.insertHead(2); + ASSERT_EQ(2, ll.getHead()->data); + ll.insertHead(3); + ASSERT_EQ(3, ll.getHead()->data); +} + +// test insertEnd method on empty linked list +TEST(LinkedListEmptyInit, InsertEndTest) { + LinkedList ll; + ll.insertEnd(1); + ASSERT_EQ(1, ll.getHead()->data); + ll.insertEnd(2); + ASSERT_EQ(1, ll.getHead()->data); + ll.insertEnd(3); + ASSERT_EQ(3, getTailData(ll.getHead())); + ll.insertEnd(4); + ASSERT_EQ(4, getTailData(ll.getHead())); +} + +// test insertAt method on empty linked list +TEST(LinkedListEmptyInit, InsertAtTest) { + LinkedList ll; + ll.insertAt(4, 3); + ll.insertAt(2, 1); + ll.insertAt(5, 3); + ll.insertAt(1, 5); + ll.insertAt(3, 2); + + int expectedOutput[] = {2, 3, 4, 5, 1}; + std::vector ll_vector = convertLinkedListToVector(ll.getHead()); + + for (int i = 0; i < 5; i++) + ASSERT_EQ(expectedOutput[i], ll_vector[i]); +} + +// test getLength method on empty linked list +TEST(LinkedListEmptyInit, GetLengthTest) { + LinkedList ll; + ASSERT_EQ(0, ll.getLength()); + ll.insertAt(4, 3); + ASSERT_EQ(1, ll.getLength()); + ll.insertAt(2, 1); + ASSERT_EQ(2, ll.getLength()); + ll.insertAt(5, 3); + ASSERT_EQ(3, ll.getLength()); + ll.insertAt(1, 5); + ASSERT_EQ(4, ll.getLength()); + ll.insertAt(3, 2); + ASSERT_EQ(5, ll.getLength()); +} + +class LinkedListDataInit : public testing::Test { +protected: + LinkedList ll; + void SetUp() override { + ll.insertEnd(1); + ll.insertEnd(2); + ll.insertEnd(3); + ll.insertEnd(4); + ll.insertEnd(5); + } +}; + +TEST_F(LinkedListDataInit, InsertHeadTest) { + ll.insertHead(6); + ll.insertHead(7); + + int expectedOutput[] = {7, 6, 1, 2, 3, 4, 5}; + std::vector ll_vector = convertLinkedListToVector(ll.getHead()); + + for (int i = 0; i < 7; i++) + ASSERT_EQ(expectedOutput[i], ll_vector[i]); +} + +TEST_F(LinkedListDataInit, InsertEndTest) { + ll.insertEnd(6); + ll.insertEnd(7); + + int expectedOutput[] = {1, 2, 3, 4, 5, 6, 7}; + std::vector ll_vector = convertLinkedListToVector(ll.getHead()); + + for (int i = 0; i < 7; i++) + ASSERT_EQ(expectedOutput[i], ll_vector[i]); +} + +TEST_F(LinkedListDataInit, GetLengthTest) { + ASSERT_EQ(5, ll.getLength()); + ll.insertAt(5, 3); + ASSERT_EQ(6, ll.getLength()); +} + +TEST_F(LinkedListDataInit, InsertAtTest) { + ll.insertAt(6, 3); + ll.insertAt(7, 0); + ll.insertAt(8, 10); + int expectedOutput[] = {7, 1, 2, 6, 3, 4, 5, 8}; + std::vector ll_vector = convertLinkedListToVector(ll.getHead()); + + for (int i = 0; i < 8; i++) + ASSERT_EQ(expectedOutput[i], ll_vector[i]); +} From c8c5e4be794441528d320e4bbf7a78b7f3ca591b Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Mon, 9 Mar 2020 11:05:51 +0530 Subject: [PATCH 030/209] add linked list deleteHead and deleteEnd method --- LinkedList/LinkedList.cpp | 28 +++++++- LinkedList/LinkedList.hpp | 11 ++- LinkedList/Makefile | 6 +- LinkedList/test_LinkedList.cpp | 127 +++++++++++++++++++++++---------- 4 files changed, 129 insertions(+), 43 deletions(-) diff --git a/LinkedList/LinkedList.cpp b/LinkedList/LinkedList.cpp index ebcff99..19b7482 100644 --- a/LinkedList/LinkedList.cpp +++ b/LinkedList/LinkedList.cpp @@ -58,4 +58,30 @@ void LinkedList::printLinkedList() { temp = temp->next; } std::cout << std::endl; -} \ No newline at end of file +} + +int LinkedList::deleteHead() { + if (head == nullptr) return -1; + Node* temp = head; + int removedData = temp->data; + head = head->next; + delete temp; + return removedData; +} + +int LinkedList::deleteEnd() { + if (head == nullptr) return -1; + Node* current = head; + if (head->next == nullptr) head = nullptr; + else { + Node* previous = head; + while (current->next != nullptr) { + previous = current; + current = current->next; + } + previous->next = nullptr; + } + int removedData = current->data; + delete current; + return removedData; +} diff --git a/LinkedList/LinkedList.hpp b/LinkedList/LinkedList.hpp index 996f071..44167b8 100644 --- a/LinkedList/LinkedList.hpp +++ b/LinkedList/LinkedList.hpp @@ -11,13 +11,22 @@ struct Node { class LinkedList { private: Node* head; + public: LinkedList() { head = nullptr; } Node* getHead() { return head; } + int getLength(); + + /* Insertion Method */ void insertHead(int data); void insertEnd(int data); void insertAt(int data, int position); - int getLength(); + + /* Deletion Method */ + int deleteHead(); + int deleteEnd(); + + /* Misc Method */ void printLinkedList(); }; diff --git a/LinkedList/Makefile b/LinkedList/Makefile index db6d622..2dfc9f3 100644 --- a/LinkedList/Makefile +++ b/LinkedList/Makefile @@ -1,13 +1,13 @@ CC=g++ GTEST_INCLUDE_PATH=../googletest/googletest/include/ GTEST_LIBRARY_PATH=../googletest/build/lib/ -lgtest -lgtest_main -CCFLAGS=-Wall -std=c++14 -I$(GTEST_INCLUDE_PATH) -L$(GTEST_LIBRARY_PATH) +CCFLAGS=-Wall -std=c++14 all: LinkedList.o - $(CC) test_LinkedList.cpp LinkedList.o $(CCFLAGS) + $(CC) test_LinkedList.cpp LinkedList.o $(CCFLAGS) -I$(GTEST_INCLUDE_PATH) -L$(GTEST_LIBRARY_PATH) LinkedList.o: - $(CC) -c LinkedList.cpp + $(CC) -c LinkedList.cpp $(CCFLAGS) clean: rm ./a.out *.o diff --git a/LinkedList/test_LinkedList.cpp b/LinkedList/test_LinkedList.cpp index f9c615e..80b81f0 100755 --- a/LinkedList/test_LinkedList.cpp +++ b/LinkedList/test_LinkedList.cpp @@ -3,6 +3,21 @@ #include #include "LinkedList.hpp" +/* Fixtures */ +class LinkedListDataInit : public testing::Test { +protected: + LinkedList ll; + void SetUp() override { + ll.insertEnd(1); + ll.insertEnd(2); + ll.insertEnd(3); + ll.insertEnd(4); + ll.insertEnd(5); + } +}; + +/* Helper Functions */ +// get tail node data int getTailData(Node* node) { while (node->next != nullptr) { node = node->next; @@ -10,6 +25,7 @@ int getTailData(Node* node) { return node->data; } +// convert linked list data to vector representation std::vector convertLinkedListToVector(Node* head) { std::vector result; Node* temp = head; @@ -31,6 +47,18 @@ TEST(LinkedListEmptyInit, InsertHeadTest) { ASSERT_EQ(3, ll.getHead()->data); } +// test insertHead method on filled linked list +TEST_F(LinkedListDataInit, InsertHeadTest) { + ll.insertHead(6); + ll.insertHead(7); + + int expectedOutput[] = {7, 6, 1, 2, 3, 4, 5}; + std::vector ll_vector = convertLinkedListToVector(ll.getHead()); + + for (int i = 0; i < 7; i++) + ASSERT_EQ(expectedOutput[i], ll_vector[i]); +} + // test insertEnd method on empty linked list TEST(LinkedListEmptyInit, InsertEndTest) { LinkedList ll; @@ -44,6 +72,18 @@ TEST(LinkedListEmptyInit, InsertEndTest) { ASSERT_EQ(4, getTailData(ll.getHead())); } +// test insertEnd method on filled linked list +TEST_F(LinkedListDataInit, InsertEndTest) { + ll.insertEnd(6); + ll.insertEnd(7); + + int expectedOutput[] = {1, 2, 3, 4, 5, 6, 7}; + std::vector ll_vector = convertLinkedListToVector(ll.getHead()); + + for (int i = 0; i < 7; i++) + ASSERT_EQ(expectedOutput[i], ll_vector[i]); +} + // test insertAt method on empty linked list TEST(LinkedListEmptyInit, InsertAtTest) { LinkedList ll; @@ -60,6 +100,18 @@ TEST(LinkedListEmptyInit, InsertAtTest) { ASSERT_EQ(expectedOutput[i], ll_vector[i]); } +// test insertAt method on filled linked list +TEST_F(LinkedListDataInit, InsertAtTest) { + ll.insertAt(6, 3); + ll.insertAt(7, 0); + ll.insertAt(8, 10); + int expectedOutput[] = {7, 1, 2, 6, 3, 4, 5, 8}; + std::vector ll_vector = convertLinkedListToVector(ll.getHead()); + + for (int i = 0; i < 8; i++) + ASSERT_EQ(expectedOutput[i], ll_vector[i]); +} + // test getLength method on empty linked list TEST(LinkedListEmptyInit, GetLengthTest) { LinkedList ll; @@ -76,53 +128,52 @@ TEST(LinkedListEmptyInit, GetLengthTest) { ASSERT_EQ(5, ll.getLength()); } -class LinkedListDataInit : public testing::Test { -protected: +// test getLength method on filled linked list +TEST_F(LinkedListDataInit, GetLengthTest) { + ASSERT_EQ(5, ll.getLength()); + ll.insertAt(5, 3); + ASSERT_EQ(6, ll.getLength()); +} + +// test deleteHead method on empty linked list +TEST(LinkedListEmptyInit, DeleteHeadTest) { LinkedList ll; - void SetUp() override { - ll.insertEnd(1); - ll.insertEnd(2); - ll.insertEnd(3); - ll.insertEnd(4); - ll.insertEnd(5); - } -}; + ASSERT_EQ(-1, ll.deleteHead()); -TEST_F(LinkedListDataInit, InsertHeadTest) { - ll.insertHead(6); - ll.insertHead(7); + // after removing every node from linked list, head should point to nullptr + ASSERT_EQ(nullptr, ll.getHead()); +} - int expectedOutput[] = {7, 6, 1, 2, 3, 4, 5}; - std::vector ll_vector = convertLinkedListToVector(ll.getHead()); +// test deleteHead method on filled linked list +TEST_F(LinkedListDataInit, DeleteHeadTest) { + ll.insertHead(8); + ASSERT_EQ(8, ll.deleteHead()); - for (int i = 0; i < 7; i++) - ASSERT_EQ(expectedOutput[i], ll_vector[i]); + for (int i = 1; i < 6; i++) + ASSERT_EQ(i, ll.deleteHead()); + + // after removing every node from linked list, head should point to nullptr + ASSERT_EQ(nullptr, ll.getHead()); } -TEST_F(LinkedListDataInit, InsertEndTest) { - ll.insertEnd(6); - ll.insertEnd(7); - - int expectedOutput[] = {1, 2, 3, 4, 5, 6, 7}; - std::vector ll_vector = convertLinkedListToVector(ll.getHead()); +// test deleteEnd method on empty linked list +TEST(LinkedListEmptyInit, DeleteEndTest) { + LinkedList ll; + for (int i = 0; i < 5; i++) + ASSERT_EQ(-1, ll.deleteEnd()); - for (int i = 0; i < 7; i++) - ASSERT_EQ(expectedOutput[i], ll_vector[i]); + // after removing every node from linked list, head should point to nullptr + ASSERT_EQ(nullptr, ll.getHead()); } -TEST_F(LinkedListDataInit, GetLengthTest) { - ASSERT_EQ(5, ll.getLength()); - ll.insertAt(5, 3); - ASSERT_EQ(6, ll.getLength()); -} +// test deleteEnd method on filled linked list +TEST_F(LinkedListDataInit, DeleteEndTest) { + ll.insertEnd(8); + ASSERT_EQ(8, ll.deleteEnd()); -TEST_F(LinkedListDataInit, InsertAtTest) { - ll.insertAt(6, 3); - ll.insertAt(7, 0); - ll.insertAt(8, 10); - int expectedOutput[] = {7, 1, 2, 6, 3, 4, 5, 8}; - std::vector ll_vector = convertLinkedListToVector(ll.getHead()); + for (int i = 5; i > 0; i--) + ASSERT_EQ(i, ll.deleteEnd()); - for (int i = 0; i < 8; i++) - ASSERT_EQ(expectedOutput[i], ll_vector[i]); + // after removing every node from linked list, head should point to nullptr + ASSERT_EQ(nullptr, ll.getHead()); } From 945ef762f25908e0b7f777b0951997aa70851aa8 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Mon, 9 Mar 2020 18:32:27 +0530 Subject: [PATCH 031/209] add linked list deleteAt method --- LinkedList/LinkedList.cpp | 24 ++++++++++++++++++++++++ LinkedList/LinkedList.hpp | 1 + LinkedList/test_LinkedList.cpp | 28 +++++++++++++++++++++++++++- 3 files changed, 52 insertions(+), 1 deletion(-) diff --git a/LinkedList/LinkedList.cpp b/LinkedList/LinkedList.cpp index 19b7482..0892c64 100644 --- a/LinkedList/LinkedList.cpp +++ b/LinkedList/LinkedList.cpp @@ -82,6 +82,30 @@ int LinkedList::deleteEnd() { previous->next = nullptr; } int removedData = current->data; + delete current; + return removedData; +} + +int LinkedList::deleteAt(int position) { + int ll_length = getLength(); + if (position < 1 || position > ll_length) + return -1; + + if (position == 1) + return deleteHead(); + else if (position == ll_length) + return deleteEnd(); + else { + Node* previous = head; + Node* current = head; + for (int i = 1; i < position; i++) { + previous = current; + current = current->next; + } + int removedData = current->data; + previous->next = current->next; + current->next = nullptr; delete current; return removedData; + } } diff --git a/LinkedList/LinkedList.hpp b/LinkedList/LinkedList.hpp index 44167b8..ebddabd 100644 --- a/LinkedList/LinkedList.hpp +++ b/LinkedList/LinkedList.hpp @@ -25,6 +25,7 @@ class LinkedList { /* Deletion Method */ int deleteHead(); int deleteEnd(); + int deleteAt(int position); /* Misc Method */ void printLinkedList(); diff --git a/LinkedList/test_LinkedList.cpp b/LinkedList/test_LinkedList.cpp index 80b81f0..46593b2 100755 --- a/LinkedList/test_LinkedList.cpp +++ b/LinkedList/test_LinkedList.cpp @@ -151,7 +151,7 @@ TEST_F(LinkedListDataInit, DeleteHeadTest) { for (int i = 1; i < 6; i++) ASSERT_EQ(i, ll.deleteHead()); - + // after removing every node from linked list, head should point to nullptr ASSERT_EQ(nullptr, ll.getHead()); } @@ -159,6 +159,13 @@ TEST_F(LinkedListDataInit, DeleteHeadTest) { // test deleteEnd method on empty linked list TEST(LinkedListEmptyInit, DeleteEndTest) { LinkedList ll; + + ll.insertHead(5); + ASSERT_EQ(5, ll.deleteEnd()); + + ll.insertHead(9); + ASSERT_EQ(9, ll.deleteEnd()); + for (int i = 0; i < 5; i++) ASSERT_EQ(-1, ll.deleteEnd()); @@ -177,3 +184,22 @@ TEST_F(LinkedListDataInit, DeleteEndTest) { // after removing every node from linked list, head should point to nullptr ASSERT_EQ(nullptr, ll.getHead()); } + +TEST(LinkedListEmptyInit, DeleteAtTest) { + LinkedList ll; + ASSERT_EQ(-1, ll.deleteAt(3)); + ASSERT_EQ(-1, ll.deleteAt(0)); + ASSERT_EQ(-1, ll.deleteAt(-5)); +} + +TEST_F(LinkedListDataInit, DeleteAtTest) { + ASSERT_EQ(3, ll.deleteAt(3)); + ASSERT_EQ(4, ll.deleteAt(3)); + ASSERT_EQ(-1, ll.deleteAt(0)); + ASSERT_EQ(-1, ll.deleteAt(5)); + ASSERT_EQ(-1, ll.deleteAt(4)); + ASSERT_EQ(5, ll.deleteAt(3)); + ASSERT_EQ(1, ll.deleteAt(1)); + ASSERT_EQ(2, ll.deleteAt(1)); + ASSERT_EQ(nullptr, ll.getHead()); +} From ba48f9d8de872c076074069947a5d0d247d5fbed Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Tue, 10 Mar 2020 08:49:42 +0530 Subject: [PATCH 032/209] add LinkedList reverse and other printing methods --- .gitignore | 1 + LinkedList/LinkedList.cpp | 69 +++++++++++++--- LinkedList/LinkedList.hpp | 13 ++- LinkedList/test_LinkedList.cpp | 141 +++++++++++++++++++++++++++++++++ 4 files changed, 213 insertions(+), 11 deletions(-) diff --git a/.gitignore b/.gitignore index 53df7dd..b1a87fb 100644 --- a/.gitignore +++ b/.gitignore @@ -55,3 +55,4 @@ dkms.conf # google test source code googletest +.vscode diff --git a/LinkedList/LinkedList.cpp b/LinkedList/LinkedList.cpp index 0892c64..aa3ba8d 100644 --- a/LinkedList/LinkedList.cpp +++ b/LinkedList/LinkedList.cpp @@ -51,15 +51,6 @@ void LinkedList::insertAt(int data, int position) { } } -void LinkedList::printLinkedList() { - Node* temp = head; - while (temp) { - std::cout << " -> " << temp->data; - temp = temp->next; - } - std::cout << std::endl; -} - int LinkedList::deleteHead() { if (head == nullptr) return -1; Node* temp = head; @@ -109,3 +100,63 @@ int LinkedList::deleteAt(int position) { return removedData; } } + +int LinkedList::dataAt(int position) { + int ll_length = getLength(); + if (position < 1 || position > ll_length) + return -1; + + Node* current = head; + for (int i = 1; i < position; i++) + current = current->next; + + return current->data; +} + +void LinkedList::Reverse() { + Node* previous = nullptr; + Node* following = nullptr; + Node* current = head; + + while (current != nullptr) { + following = current->next; + current->next = previous; + previous = current; + current = following; + } + head = previous; +} + +void LinkedList::ReverseRecursive(Node* node) { + if (node == nullptr) + return; + if (node->next == nullptr) { + head = node; + return; + } + ReverseRecursive(node->next); + Node* prev = node->next; + prev->next = node; + node->next = nullptr; +} + +void LinkedList::printList() { + Node* temp = head; + while (temp) { + std::cout << " -> " << temp->data; + temp = temp->next; + } + std::cout << std::endl; +} + +void LinkedList::printListRecursive(Node* node) { + if (node == nullptr) return; + std::cout << " -> " << node->data; + printListRecursive(node->next); +} + +void LinkedList::printReverseListRecursive(Node* node) { + if (node == nullptr) return; + printReverseListRecursive(node->next); + std::cout << " -> " << node->data; +} diff --git a/LinkedList/LinkedList.hpp b/LinkedList/LinkedList.hpp index ebddabd..dff6f89 100644 --- a/LinkedList/LinkedList.hpp +++ b/LinkedList/LinkedList.hpp @@ -27,8 +27,17 @@ class LinkedList { int deleteEnd(); int deleteAt(int position); - /* Misc Method */ - void printLinkedList(); + /* Data */ + int dataAt(int position); + + /* Recursive Method */ + void Reverse(); + void ReverseRecursive(Node* node); + + /* Print Method */ + void printList(); + void printListRecursive(Node* node); + void printReverseListRecursive(Node* node); }; #endif diff --git a/LinkedList/test_LinkedList.cpp b/LinkedList/test_LinkedList.cpp index 46593b2..8068599 100755 --- a/LinkedList/test_LinkedList.cpp +++ b/LinkedList/test_LinkedList.cpp @@ -4,6 +4,7 @@ #include "LinkedList.hpp" /* Fixtures */ +// LinkedList containing only multiple node class LinkedListDataInit : public testing::Test { protected: LinkedList ll; @@ -16,6 +17,15 @@ class LinkedListDataInit : public testing::Test { } }; +// LinkedList containing only one node +class LinkedListSingleInit : public testing::Test { +protected: + LinkedList ll; + void SetUp() override { + ll.insertHead(5); + } +}; + /* Helper Functions */ // get tail node data int getTailData(Node* node) { @@ -36,6 +46,8 @@ std::vector convertLinkedListToVector(Node* head) { return result; } +/* Linked List Insertion */ + // test insertHead method on empty linked list TEST(LinkedListEmptyInit, InsertHeadTest) { LinkedList ll; @@ -66,6 +78,7 @@ TEST(LinkedListEmptyInit, InsertEndTest) { ASSERT_EQ(1, ll.getHead()->data); ll.insertEnd(2); ASSERT_EQ(1, ll.getHead()->data); + ASSERT_EQ(2, getTailData(ll.getHead())); ll.insertEnd(3); ASSERT_EQ(3, getTailData(ll.getHead())); ll.insertEnd(4); @@ -112,6 +125,8 @@ TEST_F(LinkedListDataInit, InsertAtTest) { ASSERT_EQ(expectedOutput[i], ll_vector[i]); } +/* Linked List GetLength */ + // test getLength method on empty linked list TEST(LinkedListEmptyInit, GetLengthTest) { LinkedList ll; @@ -135,6 +150,8 @@ TEST_F(LinkedListDataInit, GetLengthTest) { ASSERT_EQ(6, ll.getLength()); } +/* Linked List Deletion */ + // test deleteHead method on empty linked list TEST(LinkedListEmptyInit, DeleteHeadTest) { LinkedList ll; @@ -142,6 +159,16 @@ TEST(LinkedListEmptyInit, DeleteHeadTest) { // after removing every node from linked list, head should point to nullptr ASSERT_EQ(nullptr, ll.getHead()); + ASSERT_EQ(0, ll.getLength()); +} + +// test deleteHead method on single linked list +TEST_F(LinkedListSingleInit, DeleteHeadTest) { + ASSERT_EQ(5, ll.deleteHead()); + ASSERT_EQ(-1, ll.deleteHead()); + // after removing every node from linked list, head should point to nullptr + ASSERT_EQ(nullptr, ll.getHead()); + ASSERT_EQ(0, ll.getLength()); } // test deleteHead method on filled linked list @@ -154,6 +181,7 @@ TEST_F(LinkedListDataInit, DeleteHeadTest) { // after removing every node from linked list, head should point to nullptr ASSERT_EQ(nullptr, ll.getHead()); + ASSERT_EQ(0, ll.getLength()); } // test deleteEnd method on empty linked list @@ -171,6 +199,16 @@ TEST(LinkedListEmptyInit, DeleteEndTest) { // after removing every node from linked list, head should point to nullptr ASSERT_EQ(nullptr, ll.getHead()); + ASSERT_EQ(0, ll.getLength()); +} + +// test deleteEnd method on single linked list +TEST_F(LinkedListSingleInit, DeleteEndTest) { + ASSERT_EQ(5, ll.deleteEnd()); + ASSERT_EQ(-1, ll.deleteEnd()); + // after removing every node from linked list, head should point to nullptr + ASSERT_EQ(nullptr, ll.getHead()); + ASSERT_EQ(0, ll.getLength()); } // test deleteEnd method on filled linked list @@ -183,15 +221,34 @@ TEST_F(LinkedListDataInit, DeleteEndTest) { // after removing every node from linked list, head should point to nullptr ASSERT_EQ(nullptr, ll.getHead()); + ASSERT_EQ(0, ll.getLength()); } +// test deleteAt method on empty linked list TEST(LinkedListEmptyInit, DeleteAtTest) { LinkedList ll; ASSERT_EQ(-1, ll.deleteAt(3)); ASSERT_EQ(-1, ll.deleteAt(0)); ASSERT_EQ(-1, ll.deleteAt(-5)); + + // after removing every node from linked list, head should point to nullptr + ASSERT_EQ(nullptr, ll.getHead()); + ASSERT_EQ(0, ll.getLength()); } +// test deleteAt method on single linked list +TEST_F(LinkedListSingleInit, DeleteAtTest) { + ASSERT_EQ(-1, ll.deleteAt(2)); + ASSERT_EQ(-1, ll.deleteAt(-1)); + ASSERT_EQ(-1, ll.deleteAt(0)); + ASSERT_EQ(5, ll.deleteAt(1)); + ASSERT_EQ(-1, ll.deleteAt(1)); + // after removing every node from linked list, head should point to nullptr + ASSERT_EQ(nullptr, ll.getHead()); + ASSERT_EQ(0, ll.getLength()); +} + +// test deleteAt method on filled linked list TEST_F(LinkedListDataInit, DeleteAtTest) { ASSERT_EQ(3, ll.deleteAt(3)); ASSERT_EQ(4, ll.deleteAt(3)); @@ -201,5 +258,89 @@ TEST_F(LinkedListDataInit, DeleteAtTest) { ASSERT_EQ(5, ll.deleteAt(3)); ASSERT_EQ(1, ll.deleteAt(1)); ASSERT_EQ(2, ll.deleteAt(1)); + + // after removing every node from linked list, head should point to nullptr + ASSERT_EQ(nullptr, ll.getHead()); + ASSERT_EQ(0, ll.getLength()); +} + +// test dataAt method on empty linked list +TEST(LinkedListEmptyInit, DataAtTest) { + LinkedList ll; + ASSERT_EQ(-1, ll.dataAt(0)); + ASSERT_EQ(-1, ll.dataAt(-1)); + ASSERT_EQ(-1, ll.dataAt(1)); +} + +// test dataAt method on empty linked list +TEST_F(LinkedListSingleInit, DataAtTest) { + ASSERT_EQ(-1, ll.dataAt(-2)); + ASSERT_EQ(-1, ll.dataAt(0)); + ASSERT_EQ(5, ll.dataAt(1)); + ASSERT_EQ(-1, ll.dataAt(2)); + ASSERT_EQ(1, ll.getLength()); +} + +// test dataAt method on empty linked list +TEST_F(LinkedListDataInit, DataAtTest) { + for (int i = 1; i < 6; i++) + ASSERT_EQ(i, ll.dataAt(i)); + ASSERT_EQ(-1, ll.dataAt(0)); + ASSERT_EQ(-1, ll.dataAt(-1)); +} + +/* Reverse Test */ + +// test reverse method on empty linked list +TEST(LinkedListEmptyInit, ReverseTest) { + LinkedList ll; + ll.Reverse(); + + // after removing every node from linked list, + // head should point to nullptr + ASSERT_EQ(nullptr, ll.getHead()); + ASSERT_EQ(0, ll.getLength()); +} + +// test reverse method on single node linked list +TEST_F(LinkedListSingleInit, ReverseTest) { + ll.Reverse(); + ASSERT_EQ(1, ll.getLength()); + ASSERT_EQ(5, ll.dataAt(1)); +} + +// test reverse method on multiple node linked list +TEST_F(LinkedListDataInit, ReverseTest) { + ll.Reverse(); + std::vector ll_vector = convertLinkedListToVector(ll.getHead()); + for (int i = 0; i < 5; i++) + ASSERT_EQ(ll_vector[i], 5-i); +} + + + +// test reverse method (recursive) on empty linked list +TEST(LinkedListEmptyInit, ReverseRecursiveTest) { + LinkedList ll; + ll.ReverseRecursive(ll.getHead()); + + // after removing every node from linked list, + // head should point to nullptr ASSERT_EQ(nullptr, ll.getHead()); + ASSERT_EQ(0, ll.getLength()); +} + +// test reverse method (recursive) on single node linked list +TEST_F(LinkedListSingleInit, ReverseRecursiveTest) { + ll.ReverseRecursive(ll.getHead()); + ASSERT_EQ(1, ll.getLength()); + ASSERT_EQ(5, ll.dataAt(1)); +} + +// test reverse method (recursive) on multiple node linked list +TEST_F(LinkedListDataInit, ReverseRecursiveTest) { + ll.ReverseRecursive(ll.getHead()); + std::vector ll_vector = convertLinkedListToVector(ll.getHead()); + for (int i = 0; i < 5; i++) + ASSERT_EQ(ll_vector[i], 5-i); } From 3b526fad4ecc29a29231eec52c76f7170bbfc85b Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Tue, 10 Mar 2020 12:06:44 +0530 Subject: [PATCH 033/209] add linked list get length recursive deleteKey deleteList indexOf methods --- LinkedList/LinkedList.cpp | 32 +++++++ LinkedList/LinkedList.hpp | 4 + LinkedList/test_LinkedList.cpp | 154 ++++++++++++++++++++++++++++++--- 3 files changed, 179 insertions(+), 11 deletions(-) diff --git a/LinkedList/LinkedList.cpp b/LinkedList/LinkedList.cpp index aa3ba8d..cc0cd3c 100644 --- a/LinkedList/LinkedList.cpp +++ b/LinkedList/LinkedList.cpp @@ -11,6 +11,11 @@ int LinkedList::getLength() { return count; } +int LinkedList::getLengthRecursive(Node* node) { + if (node == nullptr) return 0; + return 1 + getLengthRecursive(node->next); +} + void LinkedList::insertHead(int data) { Node* temp = new Node(data); temp->next = head; @@ -101,6 +106,21 @@ int LinkedList::deleteAt(int position) { } } +int LinkedList::deleteKey(int key) { + return deleteAt(indexOf(key)); +} + +void LinkedList::deleteList() { + Node* current = head; + Node* next = nullptr; + while (current != nullptr) { + next = current->next; + delete current; + current = next; + } + head = nullptr; +} + int LinkedList::dataAt(int position) { int ll_length = getLength(); if (position < 1 || position > ll_length) @@ -113,6 +133,18 @@ int LinkedList::dataAt(int position) { return current->data; } +int LinkedList::indexOf(int key) { + Node* node = head; + int count = 1; + while (node != nullptr) { + if (node->data == key) + return count; + node = node->next; + count++; + } + return -1; +} + void LinkedList::Reverse() { Node* previous = nullptr; Node* following = nullptr; diff --git a/LinkedList/LinkedList.hpp b/LinkedList/LinkedList.hpp index dff6f89..75ebfe5 100644 --- a/LinkedList/LinkedList.hpp +++ b/LinkedList/LinkedList.hpp @@ -16,6 +16,7 @@ class LinkedList { LinkedList() { head = nullptr; } Node* getHead() { return head; } int getLength(); + int getLengthRecursive(Node* node); /* Insertion Method */ void insertHead(int data); @@ -26,9 +27,12 @@ class LinkedList { int deleteHead(); int deleteEnd(); int deleteAt(int position); + int deleteKey(int key); + void deleteList(); /* Data */ int dataAt(int position); + int indexOf(int key); /* Recursive Method */ void Reverse(); diff --git a/LinkedList/test_LinkedList.cpp b/LinkedList/test_LinkedList.cpp index 8068599..7355e87 100755 --- a/LinkedList/test_LinkedList.cpp +++ b/LinkedList/test_LinkedList.cpp @@ -150,6 +150,29 @@ TEST_F(LinkedListDataInit, GetLengthTest) { ASSERT_EQ(6, ll.getLength()); } +// test getLengthRecursive method on empty linked list +TEST(LinkedListEmptyInit, GetLengthRecursiveTest) { + LinkedList ll; + ASSERT_EQ(0, ll.getLengthRecursive(ll.getHead())); + ll.insertAt(4, 3); + ASSERT_EQ(1, ll.getLengthRecursive(ll.getHead())); + ll.insertAt(2, 1); + ASSERT_EQ(2, ll.getLengthRecursive(ll.getHead())); + ll.insertAt(5, 3); + ASSERT_EQ(3, ll.getLengthRecursive(ll.getHead())); + ll.insertAt(1, 5); + ASSERT_EQ(4, ll.getLengthRecursive(ll.getHead())); + ll.insertAt(3, 2); + ASSERT_EQ(5, ll.getLengthRecursive(ll.getHead())); +} + +// test getLengthRecursive method on filled linked list +TEST_F(LinkedListDataInit, GetLengthRecursiveTest) { + ASSERT_EQ(5, ll.getLengthRecursive(ll.getHead())); + ll.insertAt(5, 3); + ASSERT_EQ(6, ll.getLengthRecursive(ll.getHead())); +} + /* Linked List Deletion */ // test deleteHead method on empty linked list @@ -157,7 +180,8 @@ TEST(LinkedListEmptyInit, DeleteHeadTest) { LinkedList ll; ASSERT_EQ(-1, ll.deleteHead()); - // after removing every node from linked list, head should point to nullptr + // after removing every node from linked list, + // head should point to nullptr ASSERT_EQ(nullptr, ll.getHead()); ASSERT_EQ(0, ll.getLength()); } @@ -166,7 +190,8 @@ TEST(LinkedListEmptyInit, DeleteHeadTest) { TEST_F(LinkedListSingleInit, DeleteHeadTest) { ASSERT_EQ(5, ll.deleteHead()); ASSERT_EQ(-1, ll.deleteHead()); - // after removing every node from linked list, head should point to nullptr + // after removing every node from linked list, + // head should point to nullptr ASSERT_EQ(nullptr, ll.getHead()); ASSERT_EQ(0, ll.getLength()); } @@ -179,7 +204,8 @@ TEST_F(LinkedListDataInit, DeleteHeadTest) { for (int i = 1; i < 6; i++) ASSERT_EQ(i, ll.deleteHead()); - // after removing every node from linked list, head should point to nullptr + // after removing every node from linked list, + // head should point to nullptr ASSERT_EQ(nullptr, ll.getHead()); ASSERT_EQ(0, ll.getLength()); } @@ -197,7 +223,8 @@ TEST(LinkedListEmptyInit, DeleteEndTest) { for (int i = 0; i < 5; i++) ASSERT_EQ(-1, ll.deleteEnd()); - // after removing every node from linked list, head should point to nullptr + // after removing every node from linked list, + // head should point to nullptr ASSERT_EQ(nullptr, ll.getHead()); ASSERT_EQ(0, ll.getLength()); } @@ -206,7 +233,8 @@ TEST(LinkedListEmptyInit, DeleteEndTest) { TEST_F(LinkedListSingleInit, DeleteEndTest) { ASSERT_EQ(5, ll.deleteEnd()); ASSERT_EQ(-1, ll.deleteEnd()); - // after removing every node from linked list, head should point to nullptr + // after removing every node from linked list, + // head should point to nullptr ASSERT_EQ(nullptr, ll.getHead()); ASSERT_EQ(0, ll.getLength()); } @@ -219,7 +247,8 @@ TEST_F(LinkedListDataInit, DeleteEndTest) { for (int i = 5; i > 0; i--) ASSERT_EQ(i, ll.deleteEnd()); - // after removing every node from linked list, head should point to nullptr + // after removing every node from linked list, + // head should point to nullptr ASSERT_EQ(nullptr, ll.getHead()); ASSERT_EQ(0, ll.getLength()); } @@ -231,7 +260,8 @@ TEST(LinkedListEmptyInit, DeleteAtTest) { ASSERT_EQ(-1, ll.deleteAt(0)); ASSERT_EQ(-1, ll.deleteAt(-5)); - // after removing every node from linked list, head should point to nullptr + // after removing every node from linked list, + // head should point to nullptr ASSERT_EQ(nullptr, ll.getHead()); ASSERT_EQ(0, ll.getLength()); } @@ -243,7 +273,8 @@ TEST_F(LinkedListSingleInit, DeleteAtTest) { ASSERT_EQ(-1, ll.deleteAt(0)); ASSERT_EQ(5, ll.deleteAt(1)); ASSERT_EQ(-1, ll.deleteAt(1)); - // after removing every node from linked list, head should point to nullptr + // after removing every node from linked list, + // head should point to nullptr ASSERT_EQ(nullptr, ll.getHead()); ASSERT_EQ(0, ll.getLength()); } @@ -259,11 +290,114 @@ TEST_F(LinkedListDataInit, DeleteAtTest) { ASSERT_EQ(1, ll.deleteAt(1)); ASSERT_EQ(2, ll.deleteAt(1)); - // after removing every node from linked list, head should point to nullptr + // after removing every node from linked list, + // head should point to nullptr + ASSERT_EQ(nullptr, ll.getHead()); + ASSERT_EQ(0, ll.getLength()); +} + +// test deleteKey method on empty linked list +TEST(LinkedListEmptyInit, DeleteKeyTest) { + LinkedList ll; + ASSERT_EQ(-1, ll.deleteKey(3)); + ASSERT_EQ(-1, ll.deleteKey(0)); + ASSERT_EQ(-1, ll.deleteKey(-5)); + + // after removing every node from linked list, + // head should point to nullptr + ASSERT_EQ(nullptr, ll.getHead()); + ASSERT_EQ(0, ll.getLength()); +} + +// test deleteKey method on single Linked list +TEST_F(LinkedListSingleInit, DeleteKeyTest) { + ASSERT_EQ(-1, ll.deleteKey(3)); + ASSERT_EQ(-1, ll.deleteKey(0)); + ASSERT_EQ(5, ll.deleteKey(5)); + ASSERT_EQ(-1, ll.deleteKey(5)); + + // after removing every node from linked list, + // head should point to nullptr + ASSERT_EQ(nullptr, ll.getHead()); + ASSERT_EQ(0, ll.getLength()); +} + +// test deleteKey method on filled Linked list +TEST_F(LinkedListDataInit, DeleteKeyTest) { + ASSERT_EQ(-1, ll.deleteKey(6)); + ASSERT_EQ(-1, ll.deleteKey(0)); + + for (int i = 1; i < 6; i++) + ASSERT_EQ(i, ll.deleteKey(i)); + + // after removing every node from linked list, + // head should point to nullptr + ASSERT_EQ(nullptr, ll.getHead()); + ASSERT_EQ(0, ll.getLength()); +} + +// test deleteList method on empty linked list +TEST(LinkedListEmptyInit, DeleteListTest) { + LinkedList ll; + ll.deleteList(); + + // after removing every node from linked list, + // head should point to nullptr + ASSERT_EQ(nullptr, ll.getHead()); + ASSERT_EQ(0, ll.getLength()); +} + +// test deleteList method on single linked list +TEST_F(LinkedListSingleInit, DeleteListTest) { + ll.deleteList(); + + // after removing every node from linked list, + // head should point to nullptr + ASSERT_EQ(nullptr, ll.getHead()); + ASSERT_EQ(0, ll.getLength()); +} + +// test deleteList method on single linked list +TEST_F(LinkedListDataInit, DeleteListTest) { + ll.deleteList(); + + // after removing every node from linked list, + // head should point to nullptr ASSERT_EQ(nullptr, ll.getHead()); ASSERT_EQ(0, ll.getLength()); } +// test indexOf method on empty linked list +TEST(LinkedListEmptyInit, IndexOfTest) { + LinkedList ll; + ASSERT_EQ(-1, ll.indexOf(2)); + ASSERT_EQ(-1, ll.indexOf(0)); + ASSERT_EQ(-1, ll.indexOf(-1)); + + // after removing every node from linked list, + // head should point to nullptr + ASSERT_EQ(nullptr, ll.getHead()); + ASSERT_EQ(0, ll.getLength()); +} + +// test indexOf method on single linked list +TEST_F(LinkedListSingleInit, IndexOfTest) { + ASSERT_EQ(-1, ll.indexOf(3)); + ASSERT_EQ(-1, ll.indexOf(0)); + ASSERT_EQ(1, ll.indexOf(5)); + ASSERT_EQ(1, ll.indexOf(5)); +} + +// test indexOf method on filled linked list +TEST_F(LinkedListDataInit, IndexOfTest) { + ASSERT_EQ(-1, ll.indexOf(6)); + ASSERT_EQ(-1, ll.indexOf(0)); + + for (int i = 1; i < 6; i++) + ASSERT_EQ(i, ll.indexOf(i)); + +} + // test dataAt method on empty linked list TEST(LinkedListEmptyInit, DataAtTest) { LinkedList ll; @@ -317,8 +451,6 @@ TEST_F(LinkedListDataInit, ReverseTest) { ASSERT_EQ(ll_vector[i], 5-i); } - - // test reverse method (recursive) on empty linked list TEST(LinkedListEmptyInit, ReverseRecursiveTest) { LinkedList ll; From 8b1d1d5ad846b21cc7dc3936c458843947f6316a Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Wed, 11 Mar 2020 19:06:38 +0530 Subject: [PATCH 034/209] add linked list docstrings --- LinkedList/LinkedList.cpp | 74 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) diff --git a/LinkedList/LinkedList.cpp b/LinkedList/LinkedList.cpp index cc0cd3c..528d4b3 100644 --- a/LinkedList/LinkedList.cpp +++ b/LinkedList/LinkedList.cpp @@ -1,6 +1,10 @@ #include #include "LinkedList.hpp" +/** + * Returns the number of node currently present in the linked list. + * @return count of node, or 0 if the list is empty. +*/ int LinkedList::getLength() { Node* temp = head; int count = 0; @@ -11,17 +15,31 @@ int LinkedList::getLength() { return count; } +/** + * Returns the number of node currently present in the linked list. + * It uses recursive approach. + * @param node starting node from where counting is start. + * @return count of node, or 0 if the list is empty. +*/ int LinkedList::getLengthRecursive(Node* node) { if (node == nullptr) return 0; return 1 + getLengthRecursive(node->next); } +/** + * Inserts new node with value 'data' at the start of linked list. + * @param data new data element that needs to be added at the start +*/ void LinkedList::insertHead(int data) { Node* temp = new Node(data); temp->next = head; head = temp; } +/** + * Inserts new node with value 'data' at the end of linked list. + * @param data new data element that needs to be append at the end +*/ void LinkedList::insertEnd(int data) { Node* newNode = new Node(data); Node* temp = head; @@ -35,6 +53,12 @@ void LinkedList::insertEnd(int data) { temp->next = newNode; } +/** + * Insert new node with value 'data' at given position in linked list. + * @param data new data element that needs to be added at given position. + * @param position position where new node will enter. + * Position is 1-based. +*/ void LinkedList::insertAt(int data, int position) { int linkedlist_len = getLength(); if (position <= 1) { @@ -56,6 +80,10 @@ void LinkedList::insertAt(int data, int position) { } } +/** + * Delete head node from linked list + * @return removedData value of deleted node +*/ int LinkedList::deleteHead() { if (head == nullptr) return -1; Node* temp = head; @@ -65,6 +93,10 @@ int LinkedList::deleteHead() { return removedData; } +/** + * Delete end node from linked list + * @return removedData value of deleted node +*/ int LinkedList::deleteEnd() { if (head == nullptr) return -1; Node* current = head; @@ -82,6 +114,12 @@ int LinkedList::deleteEnd() { return removedData; } +/** + * Delete node present at given position from linked list + * @param position position at which node needs to be deleted. + * Position is 1-based. + * @return removedData value of deleted node +*/ int LinkedList::deleteAt(int position) { int ll_length = getLength(); if (position < 1 || position > ll_length) @@ -106,10 +144,19 @@ int LinkedList::deleteAt(int position) { } } +/** + * Delete first occurance of node from linked list with value 'key' + * @param key node value that needs to be deleted + * @return removedData value of deleted node +*/ int LinkedList::deleteKey(int key) { return deleteAt(indexOf(key)); } +/** + * Deletes entire linked list. Cleans up the memory. + * head node pointer is pointing to null. +*/ void LinkedList::deleteList() { Node* current = head; Node* next = nullptr; @@ -121,6 +168,11 @@ void LinkedList::deleteList() { head = nullptr; } +/** + * Get node value present at given position in the linked list + * @param position position at which node value is needed. Position is 1-based. + * @return node value at position +*/ int LinkedList::dataAt(int position) { int ll_length = getLength(); if (position < 1 || position > ll_length) @@ -133,6 +185,11 @@ int LinkedList::dataAt(int position) { return current->data; } +/** + * Returns index of node in linked list with node value 'key'. + * Returns -1, if the key is not present. + * @param count index of node with value 'key' +*/ int LinkedList::indexOf(int key) { Node* node = head; int count = 1; @@ -145,6 +202,9 @@ int LinkedList::indexOf(int key) { return -1; } +/** + * Reverse the original linked list using iterative approach. +*/ void LinkedList::Reverse() { Node* previous = nullptr; Node* following = nullptr; @@ -159,6 +219,9 @@ void LinkedList::Reverse() { head = previous; } +/** + * Reverse the original linked list using recursive approach. +*/ void LinkedList::ReverseRecursive(Node* node) { if (node == nullptr) return; @@ -172,6 +235,9 @@ void LinkedList::ReverseRecursive(Node* node) { node->next = nullptr; } +/** + * printList simply prints the node value from head to end. +*/ void LinkedList::printList() { Node* temp = head; while (temp) { @@ -181,12 +247,20 @@ void LinkedList::printList() { std::cout << std::endl; } +/** + * printListRecursive simply prints the node value from head to end. + * It uses recursive approach. +*/ void LinkedList::printListRecursive(Node* node) { if (node == nullptr) return; std::cout << " -> " << node->data; printListRecursive(node->next); } +/** + * printReverseListRecursive simply prints the node value in reverse order, + * from tail to head. It uses recursive approach. +*/ void LinkedList::printReverseListRecursive(Node* node) { if (node == nullptr) return; printReverseListRecursive(node->next); From a4f614331d62b05f3c6c3476238f0a7517ea6dcf Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Wed, 11 Mar 2020 21:44:52 +0530 Subject: [PATCH 035/209] add get nth node from end linked list --- LinkedList/{ => LinkedList}/LinkedList.cpp | 0 LinkedList/{ => LinkedList}/LinkedList.hpp | 0 LinkedList/{ => LinkedList}/Makefile | 4 +- .../{ => LinkedList}/test_LinkedList.cpp | 0 LinkedList/getNthNodeFromEnd.cpp | 94 +++++++++++++++++++ 5 files changed, 96 insertions(+), 2 deletions(-) rename LinkedList/{ => LinkedList}/LinkedList.cpp (100%) rename LinkedList/{ => LinkedList}/LinkedList.hpp (100%) rename LinkedList/{ => LinkedList}/Makefile (64%) rename LinkedList/{ => LinkedList}/test_LinkedList.cpp (100%) create mode 100644 LinkedList/getNthNodeFromEnd.cpp diff --git a/LinkedList/LinkedList.cpp b/LinkedList/LinkedList/LinkedList.cpp similarity index 100% rename from LinkedList/LinkedList.cpp rename to LinkedList/LinkedList/LinkedList.cpp diff --git a/LinkedList/LinkedList.hpp b/LinkedList/LinkedList/LinkedList.hpp similarity index 100% rename from LinkedList/LinkedList.hpp rename to LinkedList/LinkedList/LinkedList.hpp diff --git a/LinkedList/Makefile b/LinkedList/LinkedList/Makefile similarity index 64% rename from LinkedList/Makefile rename to LinkedList/LinkedList/Makefile index 2dfc9f3..84f4171 100644 --- a/LinkedList/Makefile +++ b/LinkedList/LinkedList/Makefile @@ -1,6 +1,6 @@ CC=g++ -GTEST_INCLUDE_PATH=../googletest/googletest/include/ -GTEST_LIBRARY_PATH=../googletest/build/lib/ -lgtest -lgtest_main +GTEST_INCLUDE_PATH=../../googletest/googletest/include/ +GTEST_LIBRARY_PATH=../../googletest/build/lib/ -lgtest -lgtest_main CCFLAGS=-Wall -std=c++14 all: LinkedList.o diff --git a/LinkedList/test_LinkedList.cpp b/LinkedList/LinkedList/test_LinkedList.cpp similarity index 100% rename from LinkedList/test_LinkedList.cpp rename to LinkedList/LinkedList/test_LinkedList.cpp diff --git a/LinkedList/getNthNodeFromEnd.cpp b/LinkedList/getNthNodeFromEnd.cpp new file mode 100644 index 0000000..a2322fe --- /dev/null +++ b/LinkedList/getNthNodeFromEnd.cpp @@ -0,0 +1,94 @@ +/** + * Given a Linked List and a number n, write a function the returns the value + * at the n'th node from the end of the linked list. + * + * For example, if the input is below list and n = 3, then output is "B" + * A -> B -> C -> D -> NULL + * + * URL: https://www.geeksforgeeks.org/nth-node-from-the-end-of-a-linked-list/ +*/ + +#include +#include "LinkedList/LinkedList.hpp" + +int getNthFromEnd_UsingLengthMethod(LinkedList* ll, int position); +int getNthFromEnd_UsingTwoPointerMethod(LinkedList* ll, int position); + +int main() { + LinkedList ll; + ll.insertEnd(20); + ll.insertEnd(4); + ll.insertEnd(45); + ll.insertEnd(32); + ll.insertEnd(67); + + // Using length Method + std::cout << getNthFromEnd_UsingLengthMethod(&ll, 4) << "\n"; // 4 + std::cout << getNthFromEnd_UsingLengthMethod(&ll, 5) << "\n"; // 20 + std::cout << getNthFromEnd_UsingLengthMethod(&ll, 1) << "\n"; // 67 + std::cout << getNthFromEnd_UsingLengthMethod(&ll, 7) << "\n"; // -1 + std::cout << getNthFromEnd_UsingLengthMethod(&ll, 0) << "\n"; // -1 + std::cout << getNthFromEnd_UsingLengthMethod(&ll, -1) << "\n"; // -1 + + // Using two pointer method + std::cout << getNthFromEnd_UsingTwoPointerMethod(&ll, 4) << "\n"; // 4 + std::cout << getNthFromEnd_UsingTwoPointerMethod(&ll, 5) << "\n"; // 20 + std::cout << getNthFromEnd_UsingTwoPointerMethod(&ll, 1) << "\n"; // 67 + std::cout << getNthFromEnd_UsingTwoPointerMethod(&ll, 7) << "\n"; // -1 + std::cout << getNthFromEnd_UsingTwoPointerMethod(&ll, 0) << "\n"; // -1 + std::cout << getNthFromEnd_UsingTwoPointerMethod(&ll, -1) << "\n"; // -1 + return 0; +} + +/** + * calculates the length of linked list and then print (length - position)th + * node from the beginning of the linked list. + * Returns -1 if position is greater than linked list current length or + * less than zero. + * Time complexity: O(n) where n is the length of linked list. + * + * @param ll linked list object pointer. + * @param position position from end. Position is 1-based. + * @return nth node's value from end. +*/ +int getNthFromEnd_UsingLengthMethod(LinkedList* ll, int position) { + int length = ll->getLength(); + if (position >= length + 1 || position <= 0) + return -1; + + int positionFromStart = length - position; + Node* node = ll->getHead(); + for (int i = 0; i < positionFromStart; i++) + node = node->next; + return node->data; +} + +/** + * Maintain two pointers - reference and main pointer. Initialize both of them + * to head. Move reference pointer to n nodes from head. Now move both pointers + * one by one until the reference pointer reaches the end. Now the main pointer + * will point to nth node from the end. + * Returns -1 if position is greater than linked list current length or + * less than zero. + * Time complexity: O(n) where n is the length of linked list. + * + * @param ll linked list object pointer. + * @param position position from end. Position is 1-based. + * @return nth node's value from end. +*/ +int getNthFromEnd_UsingTwoPointerMethod(LinkedList* ll, int position) { + int length = ll->getLength(); + Node* head = ll->getHead(); + if (position >= length + 1 || position <= 0) + return -1; + Node* mainptr = head; + Node* refptr = head; + for (int i = 1; i < position; i++) { + refptr = refptr->next; + } + while (refptr->next != nullptr) { + mainptr = mainptr->next; + refptr = refptr->next; + } + return mainptr->data; +} \ No newline at end of file From a707f180e6bb93ad2dfa079011395b1f14010f2c Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Fri, 13 Mar 2020 15:53:39 +0530 Subject: [PATCH 036/209] cpp linked list find middle element --- LinkedList/findMiddle.cpp | 127 +++++++++++++++++++++++++++++++ LinkedList/getNthNodeFromEnd.cpp | 14 ++-- 2 files changed, 136 insertions(+), 5 deletions(-) create mode 100644 LinkedList/findMiddle.cpp diff --git a/LinkedList/findMiddle.cpp b/LinkedList/findMiddle.cpp new file mode 100644 index 0000000..9c30c6f --- /dev/null +++ b/LinkedList/findMiddle.cpp @@ -0,0 +1,127 @@ +/** + * Given a singly linked list, find middle of the linked list. + * For example, if given linked list is 1 -> 2 -> 3 -> 4 -> 5, + * then output should be 3. + * + * If there are even nodes, then there would be two middle nodes, we need to + * print second middle element. For example, if given linked list is + * 1 -> 2 -> 3 -> 4 -> 5 -> 6, then output should be 4. + * + * URL: https://www.geeksforgeeks.org/write-a-c-function-to-print-the-\ + * middle-of-the-linked-list/ + * cmd: g++ findMiddle.cpp LinkedList/LinkedList.cpp -Wall -std=c++14 +*/ + +#include +#include "LinkedList/LinkedList.hpp" + +int findMiddle_UsingLength(LinkedList* ll); +int findMiddle_UsingTwoPointer(LinkedList* ll); +int findMiddle_UsingOddIncrement(LinkedList* ll); + +int main() +{ + LinkedList empty_ll; + + LinkedList odd_ll; + odd_ll.insertEnd(1); + odd_ll.insertEnd(2); + odd_ll.insertEnd(3); + odd_ll.insertEnd(4); + odd_ll.insertEnd(5); + + LinkedList even_ll; + even_ll.insertEnd(1); + even_ll.insertEnd(2); + even_ll.insertEnd(3); + even_ll.insertEnd(4); + even_ll.insertEnd(5); + even_ll.insertEnd(6); + + // Using Length Method + std::cout << findMiddle_UsingLength(&empty_ll) << " "; // -1 + std::cout << findMiddle_UsingLength(&odd_ll) << " "; // 3 + std::cout << findMiddle_UsingLength(&even_ll) << "\n"; // 4 + + // Using Two Pointer Method + std::cout << findMiddle_UsingTwoPointer(&empty_ll) << " "; // -1 + std::cout << findMiddle_UsingTwoPointer(&odd_ll) << " "; // 3 + std::cout << findMiddle_UsingTwoPointer(&even_ll) << "\n"; // 4 + + // Using Odd Increment Method + std::cout << findMiddle_UsingOddIncrement(&empty_ll) << " "; // -1 + std::cout << findMiddle_UsingOddIncrement(&odd_ll) << " "; // 3 + std::cout << findMiddle_UsingOddIncrement(&even_ll) << "\n"; // 4 +} + +/** + * Find the length of linked list using getLength method. + * Now traverse the list till count/2 and return node value at count/2. + * Time complexity: O(n) where n is the length of linked list. + * + * @param ll linked list object pointer. + * @return middle node value +*/ +int findMiddle_UsingLength(LinkedList* ll) +{ + Node* node = ll->getHead(); + int len = ll->getLength(); + int middle = len / 2; + + if (node == nullptr) return -1; + + for (int i = 0; i < middle; i++) + node = node->next; + + return node->data; +} + +/** + * Traverse linked list using two pointers. Move one pointer by one and other + * by two. When fast pointer reaches end slow pointer reach middle of the + * linked list. + * + * @param ll linked list object pointer. + * @return middle node value +*/ +int findMiddle_UsingTwoPointer(LinkedList* ll) +{ + Node* head = ll->getHead(); + Node* fast = head; + Node* slow = head; + + if (slow == nullptr) return -1; + + while (fast != nullptr && fast->next != nullptr) { + fast = fast->next->next; + slow = slow->next; + } + return slow->data; +} + +/** + * Initialize mid element as head and initialize a counter as zero. Traverse + * the list from head, while traversing increment the counter and change mid + * to mid->next whenever the counter is odd. So the mid will move only half + * of the total length of the list. + * + * @param ll linked list object pointer. + * @return middle node value +*/ +int findMiddle_UsingOddIncrement(LinkedList* ll) +{ + Node* node = ll->getHead(); + if (node == nullptr) + return -1; + + Node* mid = node; + int counter = 0; + while(node) { + if (counter % 2 != 0) + mid = mid->next; + node = node->next; + counter++; + } + return mid->data; +} + diff --git a/LinkedList/getNthNodeFromEnd.cpp b/LinkedList/getNthNodeFromEnd.cpp index a2322fe..0b8ef21 100644 --- a/LinkedList/getNthNodeFromEnd.cpp +++ b/LinkedList/getNthNodeFromEnd.cpp @@ -6,6 +6,7 @@ * A -> B -> C -> D -> NULL * * URL: https://www.geeksforgeeks.org/nth-node-from-the-end-of-a-linked-list/ + * cmd: g++ getNthNodeFromEnd.cpp LinkedList/LinkedList.cpp -Wall -std=c++14 */ #include @@ -14,7 +15,8 @@ int getNthFromEnd_UsingLengthMethod(LinkedList* ll, int position); int getNthFromEnd_UsingTwoPointerMethod(LinkedList* ll, int position); -int main() { +int main() +{ LinkedList ll; ll.insertEnd(20); ll.insertEnd(4); @@ -41,7 +43,7 @@ int main() { } /** - * calculates the length of linked list and then print (length - position)th + * Calculate the length of linked list and then print (length - position)th * node from the beginning of the linked list. * Returns -1 if position is greater than linked list current length or * less than zero. @@ -51,7 +53,8 @@ int main() { * @param position position from end. Position is 1-based. * @return nth node's value from end. */ -int getNthFromEnd_UsingLengthMethod(LinkedList* ll, int position) { +int getNthFromEnd_UsingLengthMethod(LinkedList* ll, int position) +{ int length = ll->getLength(); if (position >= length + 1 || position <= 0) return -1; @@ -76,7 +79,8 @@ int getNthFromEnd_UsingLengthMethod(LinkedList* ll, int position) { * @param position position from end. Position is 1-based. * @return nth node's value from end. */ -int getNthFromEnd_UsingTwoPointerMethod(LinkedList* ll, int position) { +int getNthFromEnd_UsingTwoPointerMethod(LinkedList* ll, int position) +{ int length = ll->getLength(); Node* head = ll->getHead(); if (position >= length + 1 || position <= 0) @@ -91,4 +95,4 @@ int getNthFromEnd_UsingTwoPointerMethod(LinkedList* ll, int position) { refptr = refptr->next; } return mainptr->data; -} \ No newline at end of file +} From 8633f896915349f1fd99136fa8992bc208302837 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Fri, 13 Mar 2020 21:14:18 +0530 Subject: [PATCH 037/209] add linked list data count frequency --- LinkedList/countFrequency.cpp | 67 +++++++++++++++++++++++++++++++++++ LinkedList/findMiddle.cpp | 1 - 2 files changed, 67 insertions(+), 1 deletion(-) create mode 100644 LinkedList/countFrequency.cpp diff --git a/LinkedList/countFrequency.cpp b/LinkedList/countFrequency.cpp new file mode 100644 index 0000000..52a20af --- /dev/null +++ b/LinkedList/countFrequency.cpp @@ -0,0 +1,67 @@ +/** + * Given a singly linked list and a key, count number of occurances of given + * key in linked list. For example, if given linked list is + * 1 -> 2 -> 1 -> 2 -> 1 -> 3 -> 1 and given key is 1, then output + * should be 4. + * + * url: https://www.geeksforgeeks.org/write-a-function-that-counts-the-\ + * number-of-times-a-given-int-occurs-in-a-linked-list/ + * cmd: g++ countFrequency.cpp LinkedList/LinkedList.cpp -std=c++14 +*/ + +#include +#include "LinkedList/LinkedList.hpp" + +int countFrequency(LinkedList* ll, int key); +int countFrequencyRecursion(Node* node, int key); + +int main() +{ + LinkedList ll; + ll.insertEnd(1); + ll.insertEnd(2); + ll.insertEnd(1); + ll.insertEnd(2); + ll.insertEnd(1); + ll.insertEnd(3); + ll.insertEnd(1); + + std::cout << countFrequency(&ll, 1) << "\n"; + std::cout << countFrequencyRecursion(ll.getHead(), 1) << "\n"; + return 0; +} + +/** + * Tranversing through the linked list and count the occurance of key. + * Using non-recursive approach. + * @param ll pointer to linked list + * @param key key integer who frequency we need + * @return key count frequency +*/ +int countFrequency(LinkedList* ll, int key) +{ + Node* temp = ll->getHead(); + int count = 0; + while (temp) { + if (temp->data == key) + count++; + temp = temp->next; + } + return count; +} + +/** + * Tranversing through the linked list and count the occurance of key. + * Using non-recursive approach. + * @param node pointer to linked list node + * @param key key integer who frequency we need + * @return key count frequency +*/ +int countFrequencyRecursion(Node* node, int key) +{ + if (node == nullptr) + return 0; + if (node->data == key) + return 1 + countFrequencyRecursion(node->next, key); + return countFrequencyRecursion(node->next, key); +} diff --git a/LinkedList/findMiddle.cpp b/LinkedList/findMiddle.cpp index 9c30c6f..00cf66e 100644 --- a/LinkedList/findMiddle.cpp +++ b/LinkedList/findMiddle.cpp @@ -124,4 +124,3 @@ int findMiddle_UsingOddIncrement(LinkedList* ll) } return mid->data; } - From 593d365cdc8bf7a6dc890543c555a1f31ef21782 Mon Sep 17 00:00:00 2001 From: "priyank.chheda" Date: Sat, 14 Mar 2020 08:49:28 +0530 Subject: [PATCH 038/209] detect loop in linked list --- LinkedList/detectLoop.cpp | 63 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 LinkedList/detectLoop.cpp diff --git a/LinkedList/detectLoop.cpp b/LinkedList/detectLoop.cpp new file mode 100644 index 0000000..bfc9c2d --- /dev/null +++ b/LinkedList/detectLoop.cpp @@ -0,0 +1,63 @@ +/** + * Given a linked list, check if the linked list has loop or not. Below + * diagram shows a linked list with loop a loop. + * 1 -> 2 -> 3 + * ^ | + * | v + * 5 <- 4 + * url: https://www.geeksforgeeks.org/detect-loop-in-a-linked-list/ + * cmd: g++ detectLoop.cpp LinkedList/LinkedList.cpp -std=c++14 +*/ + +#include +#include "LinkedList/LinkedList.hpp" + +bool detectLoop(LinkedList* ll); + +int main() +{ + LinkedList ll; + ll.insertEnd(1); + ll.insertEnd(2); + ll.insertEnd(3); + ll.insertEnd(4); + ll.insertEnd(5); + + // creating loop + Node* head = ll.getHead(); + head->next->next->next->next->next = head->next; + + std::cout << detectLoop(&ll) << "\n"; + + LinkedList ll1; + ll1.insertEnd(1); + ll1.insertEnd(2); + ll1.insertEnd(3); + std::cout << detectLoop(&ll1) << "\n"; + return 0; +} + +/** + * Floyd's Cycle-Finding Algorithm: + * Traverse linked list using two pointers. Move one pointer (slowPtr) by + * one node and another pointer (fastPtr) by two nodes. + * If these pointers meet at the same node then there is a loop. + * If pointers do not meet then linked list doesn't have a loop. + * + * @param ll pointer to linked list + * @return true if loop is present, else false. +*/ +bool detectLoop(LinkedList* ll) +{ + Node* head = ll->getHead(); + Node* slowPtr = head; + Node* fastPtr = head; + + while (fastPtr != nullptr && fastPtr->next != nullptr) { + fastPtr = fastPtr->next->next; + slowPtr = slowPtr->next; + if (fastPtr == slowPtr) + return true; + } + return false; +} From ee6c01049ddec4cf0c5023a7d583b54038b6bf39 Mon Sep 17 00:00:00 2001 From: "priyank.chheda" Date: Sat, 14 Mar 2020 08:49:56 +0530 Subject: [PATCH 039/209] find number of nodes in loop linked list --- LinkedList/lengthOfLoop.cpp | 78 +++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 LinkedList/lengthOfLoop.cpp diff --git a/LinkedList/lengthOfLoop.cpp b/LinkedList/lengthOfLoop.cpp new file mode 100644 index 0000000..ebb611d --- /dev/null +++ b/LinkedList/lengthOfLoop.cpp @@ -0,0 +1,78 @@ +/** + * Write a function detectAndCountLoop() that checks whether a given Linked + * List contains loop and if loop is present then returns count of nodes in + * loop. For example, loop is present in below linked list and length of loop + * is 4. If loop is not present, then function should return 0. + * 1 -> 2 -> 3 + * ^ | + * | v + * 5 <- 4 + * url: https://www.geeksforgeeks.org/find-length-of-loop-in-linked-list/ + * cmd: g++ lengthOfLoop.cpp LinkedList/LinkedList.cpp -std=c++14 +*/ + +#include +#include "LinkedList/LinkedList.hpp" + +int detectAndCountLoop(Node* head); + +int main() +{ + LinkedList ll; + ll.insertEnd(1); + ll.insertEnd(2); + ll.insertEnd(3); + ll.insertEnd(4); + ll.insertEnd(5); + + // creating loop + Node* head = ll.getHead(); + head->next->next->next->next->next = head->next; + + std::cout << detectAndCountLoop(head) << "\n"; + + LinkedList ll1; + ll1.insertEnd(1); + ll1.insertEnd(2); + ll1.insertEnd(3); + head = ll1.getHead(); + std::cout << detectAndCountLoop(head) << "\n"; + + return 0; +} + +/** + * We know that Floyd’s Cycle detection algorithm terminates when fast and + * slow pointers meet at a common point. We also know that this common point + * is one of the loop nodes (2 or 3 or 4 or 5 in the above diagram). We store + * the address of this common point in a pointer variable say ptr. Then we + * initialize a counter with 1 and start from the common point and keeps on + * visiting next node and increasing the counter till we again reach the + * common point(ptr). At that point, the value of the counter will be equal + * to the length of the loop. + * + * @param head node pointer linked list's head + * @return length of loop +*/ +int detectAndCountLoop(Node* head) +{ + Node* slowPtr = head; + Node* fastPtr = head; + while (fastPtr != nullptr && fastPtr->next != nullptr) { + fastPtr = fastPtr->next->next; + slowPtr = slowPtr->next; + if (slowPtr == fastPtr) + break; + } + + if (fastPtr == nullptr || fastPtr->next == nullptr) + return 0; + + int counter = 1; + Node* temp = slowPtr->next; + while(temp != slowPtr) { + temp = temp->next; + counter++; + } + return counter; +} From 9bdaaec268a6feb085ad681b1274ca825c65e2a2 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sun, 15 Mar 2020 11:14:38 +0530 Subject: [PATCH 040/209] add stack library with google test cases --- Stack/Stack/Makefile | 13 ++++++ Stack/Stack/Stack.cpp | 95 ++++++++++++++++++++++++++++++++++++++ Stack/Stack/Stack.hpp | 35 ++++++++++++++ Stack/Stack/test_Stack.cpp | 85 ++++++++++++++++++++++++++++++++++ 4 files changed, 228 insertions(+) create mode 100644 Stack/Stack/Makefile create mode 100644 Stack/Stack/Stack.cpp create mode 100644 Stack/Stack/Stack.hpp create mode 100644 Stack/Stack/test_Stack.cpp diff --git a/Stack/Stack/Makefile b/Stack/Stack/Makefile new file mode 100644 index 0000000..a8b7b76 --- /dev/null +++ b/Stack/Stack/Makefile @@ -0,0 +1,13 @@ +CC=g++ +GTEST_INCLUDE_PATH=../../googletest/googletest/include/ +GTEST_LIBRARY_PATH=../../googletest/build/lib/ -lgtest -lgtest_main +CCFLAGS=-Wall -std=c++14 + +all: Stack.o + $(CC) test_Stack.cpp Stack.o $(CCFLAGS) -I$(GTEST_INCLUDE_PATH) -L$(GTEST_LIBRARY_PATH) + +Stack.o: + $(CC) -c Stack.cpp $(CCFLAGS) + +clean: + rm ./a.out *.o diff --git a/Stack/Stack/Stack.cpp b/Stack/Stack/Stack.cpp new file mode 100644 index 0000000..3135a1c --- /dev/null +++ b/Stack/Stack/Stack.cpp @@ -0,0 +1,95 @@ +#include +#include "Stack.hpp" + +/** + * Constructor + * Create new stack items array in heap memory + * @param cap maximum capacity of Stack +*/ +Stack::Stack(int cap) { + items = new int[cap]; + capacity = cap; + top = -1; +} + +/** + * Destructor + * delete stack items array from heap memory +*/ +Stack::~Stack() { + delete items; +} + +/** + * Get current size of stack + * @return total number of items currently present in stack +*/ +int Stack::size() { + return top + 1; +} + +/** + * Checks if the stack is empty + * @return true if stack is empty, else false +*/ +bool Stack::isEmpty() { + return top == -1; +} + +/** + * Checks if the stack is full + * @return true if stack is full, else false +*/ +bool Stack::isFull() { + return (top + 1) == capacity; +} + +/** + * insert(push) an integer element to stack. + * @param item to be inserted in stack + * @return status code 0, if operation is successful. + * -1, if stack is full (item not inserted). +*/ +int Stack::push(int item) { + if (isFull()) + return STACK_FULL; + items[++top] = item; + return 0; +} + +/** + * remove(pop) an integer element from stack. + * @return popped value if operation is successful. + * -2, if stack is empty (nothing to pop). +*/ +int Stack::pop() { + if (isEmpty()) + return STACK_EMPTY; + int poppedValue = items[top--]; + return poppedValue; +} + +/** + * Peek top element in stack without removing it. + * @return top item without removing it. +*/ +int Stack::peek() { + if (isEmpty()) + return STACK_EMPTY; + int peakValue = items[top]; + return peakValue; +} + +/** + * Display all elements in the stack +*/ +void Stack::display() { + std::cout << "Stack: "; + if (isEmpty()) + std::cout << "Empty\n"; + else { + for (int i = 0; i <= top ; i++) + std::cout << items[i] << " "; + std::cout << "\n"; + } +} diff --git a/Stack/Stack/Stack.hpp b/Stack/Stack/Stack.hpp new file mode 100644 index 0000000..11594a3 --- /dev/null +++ b/Stack/Stack/Stack.hpp @@ -0,0 +1,35 @@ +/** + * Stack is a linear data structure which follows a particular order in + * which the operations are performed. The order may be LIFO + * (Last In First Out) or FILO (First In Last Out) +*/ + +#ifndef STACK_H +#define STACK_H + +#define DEFAULT_CAPACITY 10 +#define STACK_FULL -1 +#define STACK_EMPTY -2 + +class Stack { +private: + int* items; + int top; + int capacity; + +public: + Stack(int cap = DEFAULT_CAPACITY); + ~Stack(); + + int push(int item); + int pop(); + int peek(); + + int size(); + bool isEmpty(); + bool isFull(); + + void display(); +}; + +#endif diff --git a/Stack/Stack/test_Stack.cpp b/Stack/Stack/test_Stack.cpp new file mode 100644 index 0000000..e6cb5b2 --- /dev/null +++ b/Stack/Stack/test_Stack.cpp @@ -0,0 +1,85 @@ +#include +#include "Stack.hpp" + +/* Fixtures */ +// generating completely full stack +class StackTest : public testing::Test { +protected: + Stack stack; + StackTest(): stack(5) {} + void SetUp() override { + for (int i = 1; i < 6; i++) + stack.push(i); + } +}; + +// test stack.isEmpty method +TEST(StackEmptyTest, isEmptyTest) { + Stack stack(5); + ASSERT_TRUE(stack.isEmpty()); + ASSERT_EQ(0, stack.push(7)); + ASSERT_FALSE(stack.isEmpty()); + ASSERT_EQ(7, stack.pop()); + ASSERT_TRUE(stack.isEmpty()); +} + +// test stack.push method +TEST(StackEmptyTest, PushTest) { + Stack stack(5); + for (int i = 1; i < 6; i++) + ASSERT_EQ(0, stack.push(i)); + ASSERT_EQ(-1, stack.push(6)); + ASSERT_EQ(5, stack.pop()); + ASSERT_EQ(0, stack.push(7)); + ASSERT_EQ(-1, stack.push(8)); +} + +// test stack.pop method +TEST_F(StackTest, PopTest) { + for (int i = 5; i > 0; i--) + ASSERT_EQ(i, stack.pop()); + ASSERT_EQ(-2, stack.pop()); + ASSERT_EQ(-2, stack.pop()); +} + +// test stack.peek method +TEST_F(StackTest, PeekTest) { + ASSERT_EQ(5, stack.peek()); + ASSERT_EQ(5, stack.peek()); + for (int i = 5; i > 0; i--) { + ASSERT_EQ(i, stack.peek()); + ASSERT_EQ(i, stack.pop()); + } + ASSERT_EQ(-2, stack.pop()); + ASSERT_EQ(-2, stack.pop()); +} + +// test stack.isFull method +TEST_F(StackTest, isFullTest) { + ASSERT_TRUE(stack.isFull()); + ASSERT_EQ(5, stack.pop()); + ASSERT_FALSE(stack.isFull()); + ASSERT_EQ(0, stack.push(5)); + ASSERT_TRUE(stack.isFull()); +} + +// test stack.size method +TEST_F(StackTest, sizeTest) { + ASSERT_EQ(5, stack.size()); + stack.push(6); + ASSERT_EQ(5, stack.size()); + stack.pop(); + stack.pop(); + ASSERT_EQ(3, stack.size()); + stack.push(6); + ASSERT_EQ(4, stack.size()); + ASSERT_EQ(6, stack.pop()); + ASSERT_EQ(3, stack.size()); + + for (int i = 3; i > 0; i--) { + ASSERT_EQ(i, stack.size()); + ASSERT_EQ(i, stack.pop()); + } + + ASSERT_TRUE(stack.isEmpty()); +} From 9e498809e666a44a54a8f1d0e836d06a0692579a Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sun, 15 Mar 2020 20:12:15 +0530 Subject: [PATCH 041/209] add queue data structure --- Queue/Queue/Makefile | 13 ++++++++ Queue/Queue/Queue.cpp | 67 ++++++++++++++++++++++++++++++++++++++ Queue/Queue/Queue.hpp | 40 +++++++++++++++++++++++ Queue/Queue/main.cpp | 23 +++++++++++++ Queue/Queue/test_Queue.cpp | 10 ++++++ 5 files changed, 153 insertions(+) create mode 100644 Queue/Queue/Makefile create mode 100644 Queue/Queue/Queue.cpp create mode 100644 Queue/Queue/Queue.hpp create mode 100644 Queue/Queue/main.cpp create mode 100644 Queue/Queue/test_Queue.cpp diff --git a/Queue/Queue/Makefile b/Queue/Queue/Makefile new file mode 100644 index 0000000..f95bba3 --- /dev/null +++ b/Queue/Queue/Makefile @@ -0,0 +1,13 @@ +CC=g++ +GTEST_INCLUDE_PATH=../../googletest/googletest/include/ +GTEST_LIBRARY_PATH=../../googletest/build/lib/ -lgtest -lgtest_main +CCFLAGS=-Wall -std=c++14 + +all: Queue.o + $(CC) test_Queue.cpp Queue.o $(CCFLAGS) -I$(GTEST_INCLUDE_PATH) -L$(GTEST_LIBRARY_PATH) + +Queue.o: + $(CC) -c Queue.cpp $(CCFLAGS) + +clean: + rm ./a.out *.o diff --git a/Queue/Queue/Queue.cpp b/Queue/Queue/Queue.cpp new file mode 100644 index 0000000..e08d46b --- /dev/null +++ b/Queue/Queue/Queue.cpp @@ -0,0 +1,67 @@ +#include +#include "Queue.hpp" + +/** + * Constructor + * Create new Queue items array in heap memory + * @param cap maximum capacity of Queue +*/ +Queue::Queue(int cap) { + items = new int[cap]; + capacity = cap; + front = -1; + rear = -1; +} + +Queue::~Queue() { + delete items; +} + +bool Queue::isFull() { + int nextRear = rear % capacity; + return nextRear = front; +} + +bool Queue::isEmpty() { + return rear == -1 && front == -1; +} + +int Queue::enqueue(int element) { + if (isEmpty()) { + front = 0; + rear = 0; + items[rear] = element; + } else if (isFull()) { + return QUEUE_FULL; + } else { + rear = (rear + 1) % capacity; + items[rear] = element; + } + return 0; +} + +int Queue::dequeue() { + if (isFull()) { + return QUEUE_EMPTY; + } + int removedValue = items[front]; + if (front == rear) { + front = -1; + rear = -1; + } else { + front = (front + 1) % capacity; + } + return removedValue; +} + +void Queue::display() { + std::cout << "Queue: "; + if (!isEmpty()) { + int temp = front; + while (temp != rear) { + std::cout << items[temp] << " "; + temp = (temp + 1) % capacity; + } + std::cout << items[temp] << "\n"; + } else std::cout << "Empty\n"; +} diff --git a/Queue/Queue/Queue.hpp b/Queue/Queue/Queue.hpp new file mode 100644 index 0000000..e31821d --- /dev/null +++ b/Queue/Queue/Queue.hpp @@ -0,0 +1,40 @@ +/** + * Like Stack, Queue is a linear structure which follows a particular order + * in which the operations are performed. The order is First In First Out + * (FIFO). A good example of queue is any queue of consumers for a resource + * where the consumer that came first is served first. + * + * The difference between stacks and queues is in removing. In a stack we + * remove the item the most recently added; in a queue, we remove the item + * the least recently added. +*/ + +#ifndef QUEUE_H +#define QUEUE_H + +#define DEFAULT_CAPACITY 10 +#define QUEUE_FULL -1 +#define QUEUE_EMPTY -2 + +class Queue { +private: + int* items; + int front; + int rear; + int capacity; + +public: + Queue(int cap = DEFAULT_CAPACITY); + ~Queue(); + + int enqueue(int item); + int dequeue(); + + int size(); + bool isEmpty(); + bool isFull(); + + void display(); +}; + +#endif diff --git a/Queue/Queue/main.cpp b/Queue/Queue/main.cpp new file mode 100644 index 0000000..ced6249 --- /dev/null +++ b/Queue/Queue/main.cpp @@ -0,0 +1,23 @@ +#include +#include "Queue.hpp" + +int main() +{ + Queue q(5); + q.display(); + q.enqueue(1); + q.display(); + q.enqueue(2); + q.display(); + q.enqueue(3); + q.display(); + q.enqueue(4); + q.display(); + q.enqueue(5); + q.display(); + q.enqueue(6); + q.display(); + q.enqueue(7); + q.display(); + return 0; +} diff --git a/Queue/Queue/test_Queue.cpp b/Queue/Queue/test_Queue.cpp new file mode 100644 index 0000000..27cdca6 --- /dev/null +++ b/Queue/Queue/test_Queue.cpp @@ -0,0 +1,10 @@ +#include +#include "Queue.hpp" + +TEST(QueueEmptyTest, EnqueueTest) { + Queue queue(5); + for (int i = 1; i < 5; i++) + ASSERT_EQ(0, queue.enqueue(i)); + ASSERT_EQ(-1, queue.enqueue(6)); + ASSERT_EQ(-1, queue.enqueue(7)); +} From 8db34efc31e84f782b25cae524b9aa8602397b5e Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Mon, 16 Mar 2020 21:47:52 +0530 Subject: [PATCH 042/209] queue bug fix --- Queue/Queue/Queue.cpp | 43 ++++++++++++++++++++------------------ Queue/Queue/Queue.hpp | 2 ++ Queue/Queue/test_Queue.cpp | 20 ++++++++++++++++-- 3 files changed, 43 insertions(+), 22 deletions(-) diff --git a/Queue/Queue/Queue.cpp b/Queue/Queue/Queue.cpp index e08d46b..0041d2a 100644 --- a/Queue/Queue/Queue.cpp +++ b/Queue/Queue/Queue.cpp @@ -9,49 +9,52 @@ Queue::Queue(int cap) { items = new int[cap]; capacity = cap; - front = -1; + front = 0; rear = -1; + item_count = 0; } Queue::~Queue() { delete items; } +int Queue::size() { + return item_count; +} + bool Queue::isFull() { - int nextRear = rear % capacity; - return nextRear = front; + return size() == capacity; } bool Queue::isEmpty() { - return rear == -1 && front == -1; + return size() == 0; } int Queue::enqueue(int element) { - if (isEmpty()) { - front = 0; - rear = 0; - items[rear] = element; - } else if (isFull()) { + if (isFull()) { return QUEUE_FULL; - } else { - rear = (rear + 1) % capacity; - items[rear] = element; } + rear = (rear + 1) % capacity; + items[rear] = element; + item_count++; return 0; } int Queue::dequeue() { - if (isFull()) { + if (isEmpty()) { return QUEUE_EMPTY; } - int removedValue = items[front]; - if (front == rear) { - front = -1; - rear = -1; - } else { - front = (front + 1) % capacity; + int removedvalue = items[front]; + front = (front + 1) % capacity; + item_count--; + return removedvalue; +} + +int Queue::peek() { + if (isEmpty()) { + return QUEUE_EMPTY; } - return removedValue; + return items[front]; } void Queue::display() { diff --git a/Queue/Queue/Queue.hpp b/Queue/Queue/Queue.hpp index e31821d..93fd488 100644 --- a/Queue/Queue/Queue.hpp +++ b/Queue/Queue/Queue.hpp @@ -22,6 +22,7 @@ class Queue { int front; int rear; int capacity; + int item_count; public: Queue(int cap = DEFAULT_CAPACITY); @@ -29,6 +30,7 @@ class Queue { int enqueue(int item); int dequeue(); + int peek(); int size(); bool isEmpty(); diff --git a/Queue/Queue/test_Queue.cpp b/Queue/Queue/test_Queue.cpp index 27cdca6..443c434 100644 --- a/Queue/Queue/test_Queue.cpp +++ b/Queue/Queue/test_Queue.cpp @@ -1,10 +1,26 @@ #include #include "Queue.hpp" +/* Fixtures */ +// generating completely full queue +class QueueTest : public testing::Test { +protected: + Queue queue; + QueueTest(): queue(5) {} + void SetUp() override { + for (int i = 1; i < 6; i++) + queue.enqueue(i); + } +}; + TEST(QueueEmptyTest, EnqueueTest) { Queue queue(5); - for (int i = 1; i < 5; i++) + for (int i = 1; i < 6; i++) ASSERT_EQ(0, queue.enqueue(i)); ASSERT_EQ(-1, queue.enqueue(6)); - ASSERT_EQ(-1, queue.enqueue(7)); + ASSERT_EQ(1, queue.dequeue()); + ASSERT_EQ(0, queue.enqueue(7)); + ASSERT_EQ(2, queue.dequeue()); + ASSERT_EQ(0, queue.enqueue(8)); + ASSERT_EQ(-1, queue.enqueue(9)); } From 109669440c152682cf3b9708fe289a772658e483 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Tue, 17 Mar 2020 18:54:08 +0530 Subject: [PATCH 043/209] add queue tests --- Queue/Queue/main.cpp | 23 --------------- Queue/Queue/test_Queue.cpp | 57 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 23 deletions(-) delete mode 100644 Queue/Queue/main.cpp diff --git a/Queue/Queue/main.cpp b/Queue/Queue/main.cpp deleted file mode 100644 index ced6249..0000000 --- a/Queue/Queue/main.cpp +++ /dev/null @@ -1,23 +0,0 @@ -#include -#include "Queue.hpp" - -int main() -{ - Queue q(5); - q.display(); - q.enqueue(1); - q.display(); - q.enqueue(2); - q.display(); - q.enqueue(3); - q.display(); - q.enqueue(4); - q.display(); - q.enqueue(5); - q.display(); - q.enqueue(6); - q.display(); - q.enqueue(7); - q.display(); - return 0; -} diff --git a/Queue/Queue/test_Queue.cpp b/Queue/Queue/test_Queue.cpp index 443c434..337719f 100644 --- a/Queue/Queue/test_Queue.cpp +++ b/Queue/Queue/test_Queue.cpp @@ -13,6 +13,7 @@ class QueueTest : public testing::Test { } }; +// test queue.enqueue method TEST(QueueEmptyTest, EnqueueTest) { Queue queue(5); for (int i = 1; i < 6; i++) @@ -24,3 +25,59 @@ TEST(QueueEmptyTest, EnqueueTest) { ASSERT_EQ(0, queue.enqueue(8)); ASSERT_EQ(-1, queue.enqueue(9)); } + +// test queue.isEmpty method +TEST(QueueEmptyTest, isEmptyTest) { + Queue queue(5); + ASSERT_TRUE(queue.isEmpty()); + ASSERT_EQ(0, queue.enqueue(1)); + ASSERT_FALSE(queue.isEmpty()); + ASSERT_EQ(1, queue.dequeue()); + ASSERT_TRUE(queue.isEmpty()); +} + +// test queue.dequeue method +TEST_F(QueueTest, DequeueTest) { + for (int i = 1; i < 6; i++) { + ASSERT_EQ(i, queue.dequeue()); + } + ASSERT_EQ(-2, queue.dequeue()); + ASSERT_EQ(0, queue.enqueue(67)); + ASSERT_EQ(67, queue.dequeue()); + ASSERT_EQ(-2, queue.dequeue()); + +} + +// test queue.peek method +TEST_F(QueueTest, PeekTest) { + ASSERT_EQ(1, queue.peek()); + ASSERT_EQ(1, queue.peek()); + for (int i = 1; i < 6; i++) { + ASSERT_EQ(i, queue.peek()); + ASSERT_EQ(i, queue.dequeue()); + } + ASSERT_EQ(-2, queue.peek()); +} + +// test queue.isFull method +TEST_F(QueueTest, isFullTest) { + ASSERT_TRUE(queue.isFull()); + ASSERT_EQ(1, queue.dequeue()); + ASSERT_FALSE(queue.isFull()); + ASSERT_EQ(0, queue.enqueue(5)); + ASSERT_TRUE(queue.isFull()); +} + +// test queue.size method +TEST_F(QueueTest, sizeTest) { + ASSERT_EQ(5, queue.size()); + queue.enqueue(6); + ASSERT_EQ(5, queue.size()); + queue.dequeue(); + queue.dequeue(); + ASSERT_EQ(3, queue.size()); + queue.enqueue(6); + ASSERT_EQ(4, queue.size()); + ASSERT_EQ(3, queue.dequeue()); + ASSERT_EQ(3, queue.size()); +} \ No newline at end of file From 3d90251f9612fe5d0ee9cfe83bbfd03b5a74c5a1 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Mon, 30 Mar 2020 18:49:10 +0530 Subject: [PATCH 044/209] add exception handling and namespace to stack --- Stack/Stack/Stack.cpp | 36 ++++++++++++++------------- Stack/Stack/Stack.hpp | 51 ++++++++++++++++++++++++-------------- Stack/Stack/test_Stack.cpp | 21 ++++++++-------- 3 files changed, 62 insertions(+), 46 deletions(-) diff --git a/Stack/Stack/Stack.cpp b/Stack/Stack/Stack.cpp index 3135a1c..85b6bd1 100644 --- a/Stack/Stack/Stack.cpp +++ b/Stack/Stack/Stack.cpp @@ -6,7 +6,7 @@ * Create new stack items array in heap memory * @param cap maximum capacity of Stack */ -Stack::Stack(int cap) { +Stack::Stack::Stack(int cap) { items = new int[cap]; capacity = cap; top = -1; @@ -16,7 +16,7 @@ Stack::Stack(int cap) { * Destructor * delete stack items array from heap memory */ -Stack::~Stack() { +Stack::Stack::~Stack() { delete items; } @@ -24,7 +24,7 @@ Stack::~Stack() { * Get current size of stack * @return total number of items currently present in stack */ -int Stack::size() { +int Stack::Stack::size() { return top + 1; } @@ -32,7 +32,7 @@ int Stack::size() { * Checks if the stack is empty * @return true if stack is empty, else false */ -bool Stack::isEmpty() { +bool Stack::Stack::isEmpty() { return top == -1; } @@ -40,7 +40,7 @@ bool Stack::isEmpty() { * Checks if the stack is full * @return true if stack is full, else false */ -bool Stack::isFull() { +bool Stack::Stack::isFull() { return (top + 1) == capacity; } @@ -48,11 +48,12 @@ bool Stack::isFull() { * insert(push) an integer element to stack. * @param item to be inserted in stack * @return status code 0, if operation is successful. - * -1, if stack is full (item not inserted). + * @throws Stack::Exception::Overflow exception if stack is full + * (item not inserted). */ -int Stack::push(int item) { +int Stack::Stack::push(int item) { if (isFull()) - return STACK_FULL; + throw OverflowException(); items[++top] = item; return 0; } @@ -60,11 +61,11 @@ int Stack::push(int item) { /** * remove(pop) an integer element from stack. * @return popped value if operation is successful. - * -2, if stack is empty (nothing to pop). + * @throws UnderflowException exception if stack is empty (nothing to pop). */ -int Stack::pop() { - if (isEmpty()) - return STACK_EMPTY; +int Stack::Stack::pop() { + if (Stack::isEmpty()) + throw UnderflowException(); int poppedValue = items[top--]; return poppedValue; } @@ -72,10 +73,11 @@ int Stack::pop() { /** * Peek top element in stack without removing it. * @return top item without removing it. + * @throws UnderflowException exception if stack is empty (nothing to peek). */ -int Stack::peek() { - if (isEmpty()) - return STACK_EMPTY; +int Stack::Stack::peek() { + if (Stack::isEmpty()) + throw UnderflowException(); int peakValue = items[top]; return peakValue; } @@ -83,9 +85,9 @@ int Stack::peek() { /** * Display all elements in the stack */ -void Stack::display() { +void Stack::Stack::display() { std::cout << "Stack: "; - if (isEmpty()) + if (Stack::isEmpty()) std::cout << "Empty\n"; else { for (int i = 0; i <= top ; i++) diff --git a/Stack/Stack/Stack.hpp b/Stack/Stack/Stack.hpp index 11594a3..58e4e91 100644 --- a/Stack/Stack/Stack.hpp +++ b/Stack/Stack/Stack.hpp @@ -8,28 +8,43 @@ #define STACK_H #define DEFAULT_CAPACITY 10 -#define STACK_FULL -1 -#define STACK_EMPTY -2 -class Stack { -private: - int* items; - int top; - int capacity; +/* StackOverflow Exception is raised when stack is overflow */ +namespace Stack { -public: - Stack(int cap = DEFAULT_CAPACITY); - ~Stack(); + class OverflowException : public std::exception { + const char* what() const throw() { + return "stack overflow exception"; + } + }; - int push(int item); - int pop(); - int peek(); + /* StackUnderflow Exception is raised when stack is underflow */ + class UnderflowException : public std::exception { + const char* what() const throw() { + return "stack underflow exception"; + } + }; - int size(); - bool isEmpty(); - bool isFull(); - void display(); -}; + class Stack { + private: + int* items; + int top; + int capacity; + public: + Stack(int cap = DEFAULT_CAPACITY); + ~Stack(); + + int push(int item); + int pop(); + int peek(); + + int size(); + bool isEmpty(); + bool isFull(); + + void display(); + }; +} #endif diff --git a/Stack/Stack/test_Stack.cpp b/Stack/Stack/test_Stack.cpp index e6cb5b2..d69f7b8 100644 --- a/Stack/Stack/test_Stack.cpp +++ b/Stack/Stack/test_Stack.cpp @@ -5,7 +5,7 @@ // generating completely full stack class StackTest : public testing::Test { protected: - Stack stack; + Stack::Stack stack; StackTest(): stack(5) {} void SetUp() override { for (int i = 1; i < 6; i++) @@ -15,7 +15,7 @@ class StackTest : public testing::Test { // test stack.isEmpty method TEST(StackEmptyTest, isEmptyTest) { - Stack stack(5); + Stack::Stack stack(5); ASSERT_TRUE(stack.isEmpty()); ASSERT_EQ(0, stack.push(7)); ASSERT_FALSE(stack.isEmpty()); @@ -25,21 +25,21 @@ TEST(StackEmptyTest, isEmptyTest) { // test stack.push method TEST(StackEmptyTest, PushTest) { - Stack stack(5); + Stack::Stack stack(5); for (int i = 1; i < 6; i++) ASSERT_EQ(0, stack.push(i)); - ASSERT_EQ(-1, stack.push(6)); + ASSERT_THROW(stack.push(6), Stack::OverflowException); ASSERT_EQ(5, stack.pop()); ASSERT_EQ(0, stack.push(7)); - ASSERT_EQ(-1, stack.push(8)); + ASSERT_THROW(stack.push(8), Stack::OverflowException); } // test stack.pop method TEST_F(StackTest, PopTest) { for (int i = 5; i > 0; i--) ASSERT_EQ(i, stack.pop()); - ASSERT_EQ(-2, stack.pop()); - ASSERT_EQ(-2, stack.pop()); + ASSERT_THROW(stack.pop(), Stack::UnderflowException); + ASSERT_THROW(stack.pop(), Stack::UnderflowException); } // test stack.peek method @@ -50,8 +50,8 @@ TEST_F(StackTest, PeekTest) { ASSERT_EQ(i, stack.peek()); ASSERT_EQ(i, stack.pop()); } - ASSERT_EQ(-2, stack.pop()); - ASSERT_EQ(-2, stack.pop()); + ASSERT_THROW(stack.pop(), Stack::UnderflowException); + ASSERT_THROW(stack.pop(), Stack::UnderflowException); } // test stack.isFull method @@ -66,7 +66,7 @@ TEST_F(StackTest, isFullTest) { // test stack.size method TEST_F(StackTest, sizeTest) { ASSERT_EQ(5, stack.size()); - stack.push(6); + ASSERT_THROW(stack.push(6), Stack::OverflowException); ASSERT_EQ(5, stack.size()); stack.pop(); stack.pop(); @@ -80,6 +80,5 @@ TEST_F(StackTest, sizeTest) { ASSERT_EQ(i, stack.size()); ASSERT_EQ(i, stack.pop()); } - ASSERT_TRUE(stack.isEmpty()); } From 3909a4980185e79642ee956bfe9233db689c9aca Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Mon, 30 Mar 2020 19:26:51 +0530 Subject: [PATCH 045/209] add stack template --- Stack/Stack/Makefile | 7 +-- Stack/Stack/Stack.cpp | 97 ----------------------------- Stack/Stack/Stack.hpp | 121 ++++++++++++++++++++++++++++++++++--- Stack/Stack/test_Stack.cpp | 6 +- 4 files changed, 119 insertions(+), 112 deletions(-) delete mode 100644 Stack/Stack/Stack.cpp diff --git a/Stack/Stack/Makefile b/Stack/Stack/Makefile index a8b7b76..2740e11 100644 --- a/Stack/Stack/Makefile +++ b/Stack/Stack/Makefile @@ -3,11 +3,8 @@ GTEST_INCLUDE_PATH=../../googletest/googletest/include/ GTEST_LIBRARY_PATH=../../googletest/build/lib/ -lgtest -lgtest_main CCFLAGS=-Wall -std=c++14 -all: Stack.o - $(CC) test_Stack.cpp Stack.o $(CCFLAGS) -I$(GTEST_INCLUDE_PATH) -L$(GTEST_LIBRARY_PATH) - -Stack.o: - $(CC) -c Stack.cpp $(CCFLAGS) +all: + $(CC) test_Stack.cpp $(CCFLAGS) -I$(GTEST_INCLUDE_PATH) -L$(GTEST_LIBRARY_PATH) clean: rm ./a.out *.o diff --git a/Stack/Stack/Stack.cpp b/Stack/Stack/Stack.cpp deleted file mode 100644 index 85b6bd1..0000000 --- a/Stack/Stack/Stack.cpp +++ /dev/null @@ -1,97 +0,0 @@ -#include -#include "Stack.hpp" - -/** - * Constructor - * Create new stack items array in heap memory - * @param cap maximum capacity of Stack -*/ -Stack::Stack::Stack(int cap) { - items = new int[cap]; - capacity = cap; - top = -1; -} - -/** - * Destructor - * delete stack items array from heap memory -*/ -Stack::Stack::~Stack() { - delete items; -} - -/** - * Get current size of stack - * @return total number of items currently present in stack -*/ -int Stack::Stack::size() { - return top + 1; -} - -/** - * Checks if the stack is empty - * @return true if stack is empty, else false -*/ -bool Stack::Stack::isEmpty() { - return top == -1; -} - -/** - * Checks if the stack is full - * @return true if stack is full, else false -*/ -bool Stack::Stack::isFull() { - return (top + 1) == capacity; -} - -/** - * insert(push) an integer element to stack. - * @param item to be inserted in stack - * @return status code 0, if operation is successful. - * @throws Stack::Exception::Overflow exception if stack is full - * (item not inserted). -*/ -int Stack::Stack::push(int item) { - if (isFull()) - throw OverflowException(); - items[++top] = item; - return 0; -} - -/** - * remove(pop) an integer element from stack. - * @return popped value if operation is successful. - * @throws UnderflowException exception if stack is empty (nothing to pop). -*/ -int Stack::Stack::pop() { - if (Stack::isEmpty()) - throw UnderflowException(); - int poppedValue = items[top--]; - return poppedValue; -} - -/** - * Peek top element in stack without removing it. - * @return top item without removing it. - * @throws UnderflowException exception if stack is empty (nothing to peek). -*/ -int Stack::Stack::peek() { - if (Stack::isEmpty()) - throw UnderflowException(); - int peakValue = items[top]; - return peakValue; -} - -/** - * Display all elements in the stack -*/ -void Stack::Stack::display() { - std::cout << "Stack: "; - if (Stack::isEmpty()) - std::cout << "Empty\n"; - else { - for (int i = 0; i <= top ; i++) - std::cout << items[i] << " "; - std::cout << "\n"; - } -} diff --git a/Stack/Stack/Stack.hpp b/Stack/Stack/Stack.hpp index 58e4e91..454cbd8 100644 --- a/Stack/Stack/Stack.hpp +++ b/Stack/Stack/Stack.hpp @@ -9,9 +9,9 @@ #define DEFAULT_CAPACITY 10 -/* StackOverflow Exception is raised when stack is overflow */ namespace Stack { + /* StackOverflow Exception is raised when stack is overflow */ class OverflowException : public std::exception { const char* what() const throw() { return "stack overflow exception"; @@ -25,10 +25,10 @@ namespace Stack { } }; - + template class Stack { private: - int* items; + T* items; int top; int capacity; @@ -36,9 +36,9 @@ namespace Stack { Stack(int cap = DEFAULT_CAPACITY); ~Stack(); - int push(int item); - int pop(); - int peek(); + int push(T item); + T pop(); + T peek(); int size(); bool isEmpty(); @@ -46,5 +46,112 @@ namespace Stack { void display(); }; + + /** + * Constructor + * Create new stack items array in heap memory + * @param cap maximum capacity of Stack + */ + template + Stack::Stack(int cap) { + items = new int[cap]; + capacity = cap; + top = -1; + } + + /** + * Destructor + * delete stack items array from heap memory + */ + template + Stack::~Stack() { + delete items; + } + + /** + * insert(push) an integer element to stack. + * @param item to be inserted in stack + * @return status code 0, if operation is successful. + * @throws Stack::OverflowException if stack is full + * (item not inserted). + */ + template + int Stack::push(T item) { + if (isFull()) + throw OverflowException(); + items[++top] = item; + return 0; + } + + /** + * remove(pop) an integer element from stack. + * @return popped value if operation is successful. + * @throws Stack::UnderflowException if stack is empty + * (nothing to pop). + */ + template + T Stack::pop() { + if (isEmpty()) + throw UnderflowException(); + T poppedValue = items[top--]; + return poppedValue; + } + + /** + * Peek top element in stack without removing it. + * @return top item without removing it. + * @throws UnderflowException exception if stack is empty + * (nothing to peek). + */ + template + T Stack::peek() { + if (isEmpty()) + throw UnderflowException(); + T peakValue = items[top]; + return peakValue; + } + + /** + * Get current size of stack + * @return total number of items currently present in stack + */ + template + int Stack::size() { + return top + 1; + } + + /** + * Checks if the stack is empty + * @return true if stack is empty, else false + */ + template + bool Stack::isEmpty() { + return top == -1; + } + + /** + * Checks if the stack is full + * @return true if stack is full, else false + */ + template + bool Stack::isFull() { + return (top + 1) == capacity; + } + + /** + * Display all elements in the stack + */ + template + void Stack::display() { + std::cout << "Stack: "; + if (isEmpty()) + std::cout << "Empty\n"; + else { + for (int i = 0; i <= top ; i++) + std::cout << items[i] << " "; + std::cout << "\n"; + } + } } -#endif + +#endif \ No newline at end of file diff --git a/Stack/Stack/test_Stack.cpp b/Stack/Stack/test_Stack.cpp index d69f7b8..99e8661 100644 --- a/Stack/Stack/test_Stack.cpp +++ b/Stack/Stack/test_Stack.cpp @@ -5,7 +5,7 @@ // generating completely full stack class StackTest : public testing::Test { protected: - Stack::Stack stack; + Stack::Stack stack; StackTest(): stack(5) {} void SetUp() override { for (int i = 1; i < 6; i++) @@ -15,7 +15,7 @@ class StackTest : public testing::Test { // test stack.isEmpty method TEST(StackEmptyTest, isEmptyTest) { - Stack::Stack stack(5); + Stack::Stack stack(5); ASSERT_TRUE(stack.isEmpty()); ASSERT_EQ(0, stack.push(7)); ASSERT_FALSE(stack.isEmpty()); @@ -25,7 +25,7 @@ TEST(StackEmptyTest, isEmptyTest) { // test stack.push method TEST(StackEmptyTest, PushTest) { - Stack::Stack stack(5); + Stack::Stack stack(5); for (int i = 1; i < 6; i++) ASSERT_EQ(0, stack.push(i)); ASSERT_THROW(stack.push(6), Stack::OverflowException); From dc0fcd65eb39c66c4e58c278a40c7dfd48096b4e Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Tue, 31 Mar 2020 18:55:27 +0530 Subject: [PATCH 046/209] add exception handling, namespace, template to queue --- Queue/Queue/Makefile | 7 +- Queue/Queue/Queue.cpp | 70 -------------- Queue/Queue/Queue.hpp | 185 ++++++++++++++++++++++++++++++++----- Queue/Queue/test_Queue.cpp | 18 ++-- Stack/Stack/Stack.hpp | 12 ++- 5 files changed, 180 insertions(+), 112 deletions(-) delete mode 100644 Queue/Queue/Queue.cpp diff --git a/Queue/Queue/Makefile b/Queue/Queue/Makefile index f95bba3..327da6c 100644 --- a/Queue/Queue/Makefile +++ b/Queue/Queue/Makefile @@ -3,11 +3,8 @@ GTEST_INCLUDE_PATH=../../googletest/googletest/include/ GTEST_LIBRARY_PATH=../../googletest/build/lib/ -lgtest -lgtest_main CCFLAGS=-Wall -std=c++14 -all: Queue.o - $(CC) test_Queue.cpp Queue.o $(CCFLAGS) -I$(GTEST_INCLUDE_PATH) -L$(GTEST_LIBRARY_PATH) - -Queue.o: - $(CC) -c Queue.cpp $(CCFLAGS) +all: + $(CC) test_Queue.cpp $(CCFLAGS) -I$(GTEST_INCLUDE_PATH) -L$(GTEST_LIBRARY_PATH) clean: rm ./a.out *.o diff --git a/Queue/Queue/Queue.cpp b/Queue/Queue/Queue.cpp deleted file mode 100644 index 0041d2a..0000000 --- a/Queue/Queue/Queue.cpp +++ /dev/null @@ -1,70 +0,0 @@ -#include -#include "Queue.hpp" - -/** - * Constructor - * Create new Queue items array in heap memory - * @param cap maximum capacity of Queue -*/ -Queue::Queue(int cap) { - items = new int[cap]; - capacity = cap; - front = 0; - rear = -1; - item_count = 0; -} - -Queue::~Queue() { - delete items; -} - -int Queue::size() { - return item_count; -} - -bool Queue::isFull() { - return size() == capacity; -} - -bool Queue::isEmpty() { - return size() == 0; -} - -int Queue::enqueue(int element) { - if (isFull()) { - return QUEUE_FULL; - } - rear = (rear + 1) % capacity; - items[rear] = element; - item_count++; - return 0; -} - -int Queue::dequeue() { - if (isEmpty()) { - return QUEUE_EMPTY; - } - int removedvalue = items[front]; - front = (front + 1) % capacity; - item_count--; - return removedvalue; -} - -int Queue::peek() { - if (isEmpty()) { - return QUEUE_EMPTY; - } - return items[front]; -} - -void Queue::display() { - std::cout << "Queue: "; - if (!isEmpty()) { - int temp = front; - while (temp != rear) { - std::cout << items[temp] << " "; - temp = (temp + 1) % capacity; - } - std::cout << items[temp] << "\n"; - } else std::cout << "Empty\n"; -} diff --git a/Queue/Queue/Queue.hpp b/Queue/Queue/Queue.hpp index 93fd488..1a0d3b7 100644 --- a/Queue/Queue/Queue.hpp +++ b/Queue/Queue/Queue.hpp @@ -13,30 +13,165 @@ #define QUEUE_H #define DEFAULT_CAPACITY 10 -#define QUEUE_FULL -1 -#define QUEUE_EMPTY -2 - -class Queue { -private: - int* items; - int front; - int rear; - int capacity; - int item_count; - -public: - Queue(int cap = DEFAULT_CAPACITY); - ~Queue(); - - int enqueue(int item); - int dequeue(); - int peek(); - - int size(); - bool isEmpty(); - bool isFull(); - - void display(); -}; + +namespace Queue { + + /** + * OverflowException is raised when you are trying to insert + * element in completely filled queue. + */ + class OverflowException : public std::exception { + const char* what() const throw() { + return "queue overflow exception"; + } + }; + + /** + * UnderflowException is raised when you are trying to access + * element from empty queue. + */ + class UnderflowException : public std::exception { + const char* what() const throw() { + return "queue underflow exception"; + } + }; + + template + class Queue { + private: + T* items; + int front; + int rear; + int capacity; + int item_count; + + public: + Queue(int cap = DEFAULT_CAPACITY); + ~Queue(); + + int enqueue(T item); + T dequeue(); + T peek(); + + int size(); + bool isEmpty(); + bool isFull(); + + void display(); + }; + + /** + * Constructor + * Create new Queue items array in heap memory + * @param cap maximum capacity of Queue + */ + template + Queue::Queue(int cap) { + items = new int[cap]; + capacity = cap; + front = 0; + rear = -1; + item_count = 0; + } + + /** + * Destructor + * delete queue items array from heap memory + */ + template + Queue::~Queue() { + delete items; + } + + /** + * enqueue(push) an element to queue. + * @param item to be enqueued in queue + * @return status code 0, if operation is successful. + * @throws Queue::OverflowException if queue is full + * (item not enqueued). + */ + template + int Queue::enqueue(T element) { + if (isFull()) { + throw OverflowException(); + } + rear = (rear + 1) % capacity; + items[rear] = element; + item_count++; + return 0; + } + + /** + * dequeue(pop) an element from queue. + * @return dequeued value if operation is successful. + * @throws Queue::UnderflowException if queue is empty + * (nothing to pop). + */ + template + T Queue::dequeue() { + if (isEmpty()) + throw UnderflowException(); + int removedvalue = items[front]; + front = (front + 1) % capacity; + item_count--; + return removedvalue; + } + + /** + * Peek top element in queue without removing it. + * @return top item without removing it. + * @throws Queue::UnderflowException exception if queue is empty + * (nothing to peek). + */ + template + T Queue::peek() { + if (isEmpty()) + throw UnderflowException(); + return items[front]; + } + + /** + * Get current size of queue + * @return total number of items currently present in queue + */ + template + int Queue::size() { + return item_count; + } + + /** + * Checks if the queue is full + * @return true if queue is full, else false + */ + template + bool Queue::isFull() { + return size() == capacity; + } + + /** + * Checks if the queue is empty + * @return true if queue is empty, else false + */ + template + bool Queue::isEmpty() { + return size() == 0; + } + + /** + * Display all elements in the queue + */ + template + void Queue::display() { + std::cout << "Queue: "; + if (!isEmpty()) { + int temp = front; + while (temp != rear) { + std::cout << items[temp] << " "; + temp = (temp + 1) % capacity; + } + std::cout << items[temp] << "\n"; + } else std::cout << "Empty\n"; + } +} #endif diff --git a/Queue/Queue/test_Queue.cpp b/Queue/Queue/test_Queue.cpp index 337719f..9e58403 100644 --- a/Queue/Queue/test_Queue.cpp +++ b/Queue/Queue/test_Queue.cpp @@ -5,7 +5,7 @@ // generating completely full queue class QueueTest : public testing::Test { protected: - Queue queue; + Queue::Queue queue; QueueTest(): queue(5) {} void SetUp() override { for (int i = 1; i < 6; i++) @@ -15,20 +15,20 @@ class QueueTest : public testing::Test { // test queue.enqueue method TEST(QueueEmptyTest, EnqueueTest) { - Queue queue(5); + Queue::Queue queue(5); for (int i = 1; i < 6; i++) ASSERT_EQ(0, queue.enqueue(i)); - ASSERT_EQ(-1, queue.enqueue(6)); + ASSERT_THROW(queue.enqueue(6), Queue::OverflowException); ASSERT_EQ(1, queue.dequeue()); ASSERT_EQ(0, queue.enqueue(7)); ASSERT_EQ(2, queue.dequeue()); ASSERT_EQ(0, queue.enqueue(8)); - ASSERT_EQ(-1, queue.enqueue(9)); + ASSERT_THROW(queue.enqueue(9), Queue::OverflowException); } // test queue.isEmpty method TEST(QueueEmptyTest, isEmptyTest) { - Queue queue(5); + Queue::Queue queue(5); ASSERT_TRUE(queue.isEmpty()); ASSERT_EQ(0, queue.enqueue(1)); ASSERT_FALSE(queue.isEmpty()); @@ -41,10 +41,10 @@ TEST_F(QueueTest, DequeueTest) { for (int i = 1; i < 6; i++) { ASSERT_EQ(i, queue.dequeue()); } - ASSERT_EQ(-2, queue.dequeue()); + ASSERT_THROW(queue.dequeue(), Queue::UnderflowException); ASSERT_EQ(0, queue.enqueue(67)); ASSERT_EQ(67, queue.dequeue()); - ASSERT_EQ(-2, queue.dequeue()); + ASSERT_THROW(queue.dequeue(), Queue::UnderflowException); } @@ -56,7 +56,7 @@ TEST_F(QueueTest, PeekTest) { ASSERT_EQ(i, queue.peek()); ASSERT_EQ(i, queue.dequeue()); } - ASSERT_EQ(-2, queue.peek()); + ASSERT_THROW(queue.peek(), Queue::UnderflowException); } // test queue.isFull method @@ -71,7 +71,7 @@ TEST_F(QueueTest, isFullTest) { // test queue.size method TEST_F(QueueTest, sizeTest) { ASSERT_EQ(5, queue.size()); - queue.enqueue(6); + ASSERT_THROW(queue.enqueue(6), Queue::OverflowException); ASSERT_EQ(5, queue.size()); queue.dequeue(); queue.dequeue(); diff --git a/Stack/Stack/Stack.hpp b/Stack/Stack/Stack.hpp index 454cbd8..117a072 100644 --- a/Stack/Stack/Stack.hpp +++ b/Stack/Stack/Stack.hpp @@ -11,14 +11,20 @@ namespace Stack { - /* StackOverflow Exception is raised when stack is overflow */ + /** + * OverflowException is raised when you are trying to insert + * element in completely filled stack. + */ class OverflowException : public std::exception { const char* what() const throw() { return "stack overflow exception"; } }; - /* StackUnderflow Exception is raised when stack is underflow */ + /** + * UnderflowException is raised when you are trying to access + * element from empty stack. + */ class UnderflowException : public std::exception { const char* what() const throw() { return "stack underflow exception"; @@ -69,7 +75,7 @@ namespace Stack { } /** - * insert(push) an integer element to stack. + * insert(push) an element to stack. * @param item to be inserted in stack * @return status code 0, if operation is successful. * @throws Stack::OverflowException if stack is full From 1dbae47f3517ad5ca08302e4ecd96f609be7c8e2 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Tue, 31 Mar 2020 20:14:19 +0530 Subject: [PATCH 047/209] stack bug fix --- Stack/Stack/Stack.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Stack/Stack/Stack.hpp b/Stack/Stack/Stack.hpp index 117a072..4d8b8e1 100644 --- a/Stack/Stack/Stack.hpp +++ b/Stack/Stack/Stack.hpp @@ -60,7 +60,7 @@ namespace Stack { */ template Stack::Stack(int cap) { - items = new int[cap]; + items = new T[cap]; capacity = cap; top = -1; } From 3749a9957e08ba354fde8eb2a214d66061578567 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Wed, 1 Apr 2020 08:42:50 +0530 Subject: [PATCH 048/209] add infix to postfix conversion --- Stack/infixToPostfix.cpp | 85 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 Stack/infixToPostfix.cpp diff --git a/Stack/infixToPostfix.cpp b/Stack/infixToPostfix.cpp new file mode 100644 index 0000000..f737e6a --- /dev/null +++ b/Stack/infixToPostfix.cpp @@ -0,0 +1,85 @@ +/** + * Infix to postfix conversion + * CMD: g++ -std=c++14 -Wall infixToPostfix.cpp + */ + +#include +#include "Stack/Stack.hpp" + +int precedence(char c); +std::string infixToPostfix(std::string infix); + +/* main driver function */ +int main() +{ + std::string exp = "a+b*(c^d-e)^(f+g*h)-i"; + std::string postfix = infixToPostfix(exp); + std::cout << postfix << std::endl; + return 0; +} + +/** + * precedence returns precedence value of an operator + * @param c operator whose precedence value is needed + * @returns precedence value of operator c + */ +int precedence(char c) +{ + if (c == '^') + return 3; + else if (c == '*' || c == '/') + return 2; + else if (c == '+' || c == '-') + return 1; + else + return -1; +} + +/** + * infixToPostfix converts infix expression into postfix expression + * @param infix infix expression that needs to be converted + * @returns postfix expression + */ +std::string infixToPostfix(std::string infix) +{ + Stack::Stack stack; + std::string postfix; + int infixLen = infix.length(); + + for (int i = 0; i < infixLen; i++) { + + // if character is an operand (alphabet) + if ((infix[i] >= 'a' && infix[i] <= 'z') || + (infix[i] >= 'A' && infix[i] <= 'Z')) { + postfix += infix[i]; + } + + //if character is opening bracket + else if (infix[i] == '(') { + stack.push(infix[i]); + } + + //if character is closing bracket + else if (infix[i] == ')') { + while (!stack.isEmpty() && stack.peek() != '(') + postfix += stack.pop(); + if (stack.peek() == '(') + stack.pop(); + } + + // if character is an operator + else { + while (!stack.isEmpty() && + precedence(infix[i]) <= precedence(stack.peek())) { + postfix += stack.pop(); + } + stack.push(infix[i]); + } + } + + // pop and append everything to postfix string till stack is empty + while (!stack.isEmpty()) + postfix += stack.pop(); + + return postfix; +} From ea29d7e2b473df2f566c4525860dc1d757d4da7b Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Fri, 3 Apr 2020 10:27:28 +0530 Subject: [PATCH 049/209] add stack balance paranthesis --- Stack/balancedParanthesis.cpp | 53 +++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Stack/balancedParanthesis.cpp diff --git a/Stack/balancedParanthesis.cpp b/Stack/balancedParanthesis.cpp new file mode 100644 index 0000000..8e2eb9e --- /dev/null +++ b/Stack/balancedParanthesis.cpp @@ -0,0 +1,53 @@ +/** + * Check for balanced parentheses in an expression + * CMD: g++ -std=c++14 -Wall balancedParanthesis.cpp + */ + +#include +#include "Stack/Stack.hpp" + +bool areParanthesisBalanced(std::string); + +/* main driver function */ +int main() +{ + std::string exp = "{a*(a+b)} + [4+5]"; + bool result = areParanthesisBalanced(exp); + if (result) std::cout << "balanced\n"; + else std::cout << "not balanced\n"; + return 0; +} + +/** + * check if the paranthesis in given expression exp is balanced or not. + * @param exp expression to be checked. + * @returns true if balance, else false +*/ +bool areParanthesisBalanced(std::string exp) +{ + Stack::Stack stack; + int expLen = exp.length(); + + for (int i = 0; i < expLen; i++) { + // if character is any of the opening braces, push it to stack + if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[') { + stack.push(exp[i]); + + // if character is any of the closing braces and peek of stack is + // corresponding opening braces, pop the opening brace from stack + // ignore every other character + } else if (exp[i] == ')' || exp[i] == '}' || exp[i] == ']') { + if ((exp[i] == ')' && stack.peek() == '(') || + (exp[i] == '}' && stack.peek() == '{') || + (exp[i] == ']' && stack.peek() == '[')) + stack.pop(); + else return false; + } + } + + // after parsing all the characters in exp, expression is unbalanced + // if stack is not empty. + if (!stack.isEmpty()) + return false; + return true; +} \ No newline at end of file From 1b0008e000d8dd153ab387f5fcd0752b70eed1c0 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Fri, 3 Apr 2020 10:38:41 +0530 Subject: [PATCH 050/209] add stack balanced paranthesis exception handling --- Stack/balancedParanthesis.cpp | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/Stack/balancedParanthesis.cpp b/Stack/balancedParanthesis.cpp index 8e2eb9e..ef83d03 100644 --- a/Stack/balancedParanthesis.cpp +++ b/Stack/balancedParanthesis.cpp @@ -25,23 +25,34 @@ int main() */ bool areParanthesisBalanced(std::string exp) { - Stack::Stack stack; + Stack::Stack stack(10); int expLen = exp.length(); for (int i = 0; i < expLen; i++) { // if character is any of the opening braces, push it to stack if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[') { - stack.push(exp[i]); + try { + stack.push(exp[i]); + } catch (Stack::OverflowException &e) { + std::cout << "Stack Overflow Exception.\n"; + std::cout << "Can't do anything. Rerun with more stack space\n"; + throw; + } // if character is any of the closing braces and peek of stack is // corresponding opening braces, pop the opening brace from stack // ignore every other character } else if (exp[i] == ')' || exp[i] == '}' || exp[i] == ']') { - if ((exp[i] == ')' && stack.peek() == '(') || - (exp[i] == '}' && stack.peek() == '{') || - (exp[i] == ']' && stack.peek() == '[')) - stack.pop(); - else return false; + try { + if ((exp[i] == ')' && stack.peek() == '(') || + (exp[i] == '}' && stack.peek() == '{') || + (exp[i] == ']' && stack.peek() == '[')) + stack.pop(); + else return false; + } catch (Stack::UnderflowException &e) { + std::cout << "underflow exception thrown\n"; + return false; + } } } From cb8306cefd0ecf463db3832a6bfc212776c55bad Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Tue, 7 Apr 2020 09:07:38 +0530 Subject: [PATCH 051/209] add stack tracking current maximum --- Stack/trackingCurrentMax.cpp | 57 ++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Stack/trackingCurrentMax.cpp diff --git a/Stack/trackingCurrentMax.cpp b/Stack/trackingCurrentMax.cpp new file mode 100644 index 0000000..caf1bfb --- /dev/null +++ b/Stack/trackingCurrentMax.cpp @@ -0,0 +1,57 @@ +/* +Tracking current Maximum Element in a stack +Given a Stack, keep track of the maximum value in it. + +- Create an auxiliary stack, say ‘maxStack’ to keep the track of maximum element +- Push the first element to both dataStack and the maxStack. +- Now from the second element, push the element to the main stack. Compare the element with the top element of the track stack, if the current element is greater than top of maxStack then push the current element to maxStack otherwise push the top element of maxStack again into it. +- If we pop an element from the main stack, then pop an element from the maxStack as well. +- Now to compute the maximum of the main stack at any point, we can simply print the top element of Track stack. + +CMD: g++ -std=c++14 -Wall trackingCurrentMax.cpp +*/ + +#include +#include "Stack/Stack.hpp" + +class StackWithMax { +private: + Stack::Stack dataStack; + Stack::Stack maxStack; // storing the max element in auxiliary stack +public: + void push(int item) { + dataStack.push(item); + if (!maxStack.isEmpty()) { + if (item >= maxStack.peek()) + maxStack.push(item); + else maxStack.push(maxStack.peek()); + } else maxStack.push(item); + } + + int pop() { + maxStack.pop(); + return dataStack.pop(); + } + + int getMax() { return maxStack.peek(); } + + // methods which are same as original stack methods + int peek() { return dataStack.peek(); } + int size() { return dataStack.size(); } + bool isEmpty() { return dataStack.isEmpty(); } + bool isFull() { return dataStack.isFull(); } + void display() { dataStack.display(); } +}; + +int main() { + StackWithMax s; + s.push(20); + std::cout << s.getMax() << std::endl; + s.push(10); + std::cout << s.getMax() << std::endl; + s.push(50); + std::cout << s.getMax() << std::endl; + s.pop(); + std::cout << s.getMax() << std::endl; + return 0; +} \ No newline at end of file From 9c555999fd9c3a4056a675f246925964d010a72e Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Wed, 8 Apr 2020 08:33:22 +0530 Subject: [PATCH 052/209] add template to linkedlist --- LinkedList/LinkedList/LinkedList.cpp | 268 ------------------ LinkedList/LinkedList/LinkedList.hpp | 321 ++++++++++++++++++++-- LinkedList/LinkedList/Makefile | 7 +- LinkedList/LinkedList/test_LinkedList.cpp | 38 +-- 4 files changed, 324 insertions(+), 310 deletions(-) delete mode 100644 LinkedList/LinkedList/LinkedList.cpp diff --git a/LinkedList/LinkedList/LinkedList.cpp b/LinkedList/LinkedList/LinkedList.cpp deleted file mode 100644 index 528d4b3..0000000 --- a/LinkedList/LinkedList/LinkedList.cpp +++ /dev/null @@ -1,268 +0,0 @@ -#include -#include "LinkedList.hpp" - -/** - * Returns the number of node currently present in the linked list. - * @return count of node, or 0 if the list is empty. -*/ -int LinkedList::getLength() { - Node* temp = head; - int count = 0; - while (temp) { - count++; - temp = temp->next; - } - return count; -} - -/** - * Returns the number of node currently present in the linked list. - * It uses recursive approach. - * @param node starting node from where counting is start. - * @return count of node, or 0 if the list is empty. -*/ -int LinkedList::getLengthRecursive(Node* node) { - if (node == nullptr) return 0; - return 1 + getLengthRecursive(node->next); -} - -/** - * Inserts new node with value 'data' at the start of linked list. - * @param data new data element that needs to be added at the start -*/ -void LinkedList::insertHead(int data) { - Node* temp = new Node(data); - temp->next = head; - head = temp; -} - -/** - * Inserts new node with value 'data' at the end of linked list. - * @param data new data element that needs to be append at the end -*/ -void LinkedList::insertEnd(int data) { - Node* newNode = new Node(data); - Node* temp = head; - if (temp == nullptr) { - head = newNode; - return; - } - while(temp->next != nullptr) { - temp = temp->next; - } - temp->next = newNode; -} - -/** - * Insert new node with value 'data' at given position in linked list. - * @param data new data element that needs to be added at given position. - * @param position position where new node will enter. - * Position is 1-based. -*/ -void LinkedList::insertAt(int data, int position) { - int linkedlist_len = getLength(); - if (position <= 1) { - insertHead(data); - return; - } else if (position >= linkedlist_len) { - insertEnd(data); - return; - } else { - Node* newNode = new Node(data); - Node* previous = head; - Node* current = head; - for (int i = 1; i < position; i++) { - previous = current; - current = current->next; - } - previous->next = newNode; - newNode->next = current; - } -} - -/** - * Delete head node from linked list - * @return removedData value of deleted node -*/ -int LinkedList::deleteHead() { - if (head == nullptr) return -1; - Node* temp = head; - int removedData = temp->data; - head = head->next; - delete temp; - return removedData; -} - -/** - * Delete end node from linked list - * @return removedData value of deleted node -*/ -int LinkedList::deleteEnd() { - if (head == nullptr) return -1; - Node* current = head; - if (head->next == nullptr) head = nullptr; - else { - Node* previous = head; - while (current->next != nullptr) { - previous = current; - current = current->next; - } - previous->next = nullptr; - } - int removedData = current->data; - delete current; - return removedData; -} - -/** - * Delete node present at given position from linked list - * @param position position at which node needs to be deleted. - * Position is 1-based. - * @return removedData value of deleted node -*/ -int LinkedList::deleteAt(int position) { - int ll_length = getLength(); - if (position < 1 || position > ll_length) - return -1; - - if (position == 1) - return deleteHead(); - else if (position == ll_length) - return deleteEnd(); - else { - Node* previous = head; - Node* current = head; - for (int i = 1; i < position; i++) { - previous = current; - current = current->next; - } - int removedData = current->data; - previous->next = current->next; - current->next = nullptr; - delete current; - return removedData; - } -} - -/** - * Delete first occurance of node from linked list with value 'key' - * @param key node value that needs to be deleted - * @return removedData value of deleted node -*/ -int LinkedList::deleteKey(int key) { - return deleteAt(indexOf(key)); -} - -/** - * Deletes entire linked list. Cleans up the memory. - * head node pointer is pointing to null. -*/ -void LinkedList::deleteList() { - Node* current = head; - Node* next = nullptr; - while (current != nullptr) { - next = current->next; - delete current; - current = next; - } - head = nullptr; -} - -/** - * Get node value present at given position in the linked list - * @param position position at which node value is needed. Position is 1-based. - * @return node value at position -*/ -int LinkedList::dataAt(int position) { - int ll_length = getLength(); - if (position < 1 || position > ll_length) - return -1; - - Node* current = head; - for (int i = 1; i < position; i++) - current = current->next; - - return current->data; -} - -/** - * Returns index of node in linked list with node value 'key'. - * Returns -1, if the key is not present. - * @param count index of node with value 'key' -*/ -int LinkedList::indexOf(int key) { - Node* node = head; - int count = 1; - while (node != nullptr) { - if (node->data == key) - return count; - node = node->next; - count++; - } - return -1; -} - -/** - * Reverse the original linked list using iterative approach. -*/ -void LinkedList::Reverse() { - Node* previous = nullptr; - Node* following = nullptr; - Node* current = head; - - while (current != nullptr) { - following = current->next; - current->next = previous; - previous = current; - current = following; - } - head = previous; -} - -/** - * Reverse the original linked list using recursive approach. -*/ -void LinkedList::ReverseRecursive(Node* node) { - if (node == nullptr) - return; - if (node->next == nullptr) { - head = node; - return; - } - ReverseRecursive(node->next); - Node* prev = node->next; - prev->next = node; - node->next = nullptr; -} - -/** - * printList simply prints the node value from head to end. -*/ -void LinkedList::printList() { - Node* temp = head; - while (temp) { - std::cout << " -> " << temp->data; - temp = temp->next; - } - std::cout << std::endl; -} - -/** - * printListRecursive simply prints the node value from head to end. - * It uses recursive approach. -*/ -void LinkedList::printListRecursive(Node* node) { - if (node == nullptr) return; - std::cout << " -> " << node->data; - printListRecursive(node->next); -} - -/** - * printReverseListRecursive simply prints the node value in reverse order, - * from tail to head. It uses recursive approach. -*/ -void LinkedList::printReverseListRecursive(Node* node) { - if (node == nullptr) return; - printReverseListRecursive(node->next); - std::cout << " -> " << node->data; -} diff --git a/LinkedList/LinkedList/LinkedList.hpp b/LinkedList/LinkedList/LinkedList.hpp index 75ebfe5..be4c896 100644 --- a/LinkedList/LinkedList/LinkedList.hpp +++ b/LinkedList/LinkedList/LinkedList.hpp @@ -1,47 +1,332 @@ #ifndef LINKEDLIST_H #define LINKEDLIST_H +template struct Node { - int data; - Node* next; + T data; + Node* next; - Node(int _data) { data = _data; next = nullptr; } + Node(T _data) { data = _data; next = nullptr; } }; +template class LinkedList { private: - Node* head; + Node* head; public: LinkedList() { head = nullptr; } - Node* getHead() { return head; } + Node* getHead() { return head; } int getLength(); - int getLengthRecursive(Node* node); + int getLengthRecursive(Node* node); /* Insertion Method */ - void insertHead(int data); - void insertEnd(int data); - void insertAt(int data, int position); + void insertHead(T data); + void insertEnd(T data); + void insertAt(T data, int position); /* Deletion Method */ - int deleteHead(); - int deleteEnd(); - int deleteAt(int position); - int deleteKey(int key); + T deleteHead(); + T deleteEnd(); + T deleteAt(int position); + T deleteKey(T key); void deleteList(); /* Data */ - int dataAt(int position); - int indexOf(int key); + T dataAt(int position); + int indexOf(T key); /* Recursive Method */ void Reverse(); - void ReverseRecursive(Node* node); + void ReverseRecursive(Node* node); /* Print Method */ void printList(); - void printListRecursive(Node* node); - void printReverseListRecursive(Node* node); + void printListRecursive(Node* node); + void printReverseListRecursive(Node* node); }; +/** + * Returns the number of node currently present in the linked list. + * @return count of node, or 0 if the list is empty. +*/ +template +int LinkedList::getLength() { + Node* temp = head; + int count = 0; + while (temp) { + count++; + temp = temp->next; + } + return count; +} + +/** + * Returns the number of node currently present in the linked list. + * It uses recursive approach. + * @param node starting node from where counting is start. + * @return count of node, or 0 if the list is empty. +*/ +template +int LinkedList::getLengthRecursive(Node* node) { + if (node == nullptr) return 0; + return 1 + getLengthRecursive(node->next); +} + +/** + * Inserts new node with value 'data' at the start of linked list. + * @param data new data element that needs to be added at the start +*/ +template +void LinkedList::insertHead(T data) { + Node* temp = new Node(data); + temp->next = head; + head = temp; +} + +/** + * Inserts new node with value 'data' at the end of linked list. + * @param data new data element that needs to be append at the end +*/ +template +void LinkedList::insertEnd(T data) { + Node* newNode = new Node(data); + Node* temp = head; + if (temp == nullptr) { + head = newNode; + return; + } + while(temp->next != nullptr) { + temp = temp->next; + } + temp->next = newNode; +} + +/** + * Insert new node with value 'data' at given position in linked list. + * @param data new data element that needs to be added at given position. + * @param position position where new node will enter. + * Position is 1-based. +*/ +template +void LinkedList::insertAt(T data, int position) { + int linkedlist_len = getLength(); + if (position <= 1) { + insertHead(data); + return; + } else if (position >= linkedlist_len) { + insertEnd(data); + return; + } else { + Node* newNode = new Node(data); + Node* previous = head; + Node* current = head; + for (int i = 1; i < position; i++) { + previous = current; + current = current->next; + } + previous->next = newNode; + newNode->next = current; + } +} + +/** + * Delete head node from linked list + * @return removedData value of deleted node +*/ +template +T LinkedList::deleteHead() { + if (head == nullptr) return -1; + Node* temp = head; + T removedData = temp->data; + head = head->next; + delete temp; + return removedData; +} + +/** + * Delete end node from linked list + * @return removedData value of deleted node +*/ +template +T LinkedList::deleteEnd() { + if (head == nullptr) return -1; + Node* current = head; + if (head->next == nullptr) head = nullptr; + else { + Node* previous = head; + while (current->next != nullptr) { + previous = current; + current = current->next; + } + previous->next = nullptr; + } + T removedData = current->data; + delete current; + return removedData; +} + +/** + * Delete node present at given position from linked list + * @param position position at which node needs to be deleted. + * Position is 1-based. + * @return removedData value of deleted node +*/ +template +T LinkedList::deleteAt(int position) { + int ll_length = getLength(); + if (position < 1 || position > ll_length) + return -1; + + if (position == 1) + return deleteHead(); + else if (position == ll_length) + return deleteEnd(); + else { + Node* previous = head; + Node* current = head; + for (int i = 1; i < position; i++) { + previous = current; + current = current->next; + } + T removedData = current->data; + previous->next = current->next; + current->next = nullptr; + delete current; + return removedData; + } +} + +/** + * Delete first occurance of node from linked list with value 'key' + * @param key node value that needs to be deleted + * @return removedData value of deleted node +*/ +template +T LinkedList::deleteKey(T key) { + return deleteAt(indexOf(key)); +} + +/** + * Deletes entire linked list. Cleans up the memory. + * head node pointer is pointing to null. +*/ +template +void LinkedList::deleteList() { + Node* current = head; + Node* next = nullptr; + while (current != nullptr) { + next = current->next; + delete current; + current = next; + } + head = nullptr; +} + +/** + * Get node value present at given position in the linked list + * @param position position at which node value is needed. Position is 1-based. + * @return node value at position +*/ +template +T LinkedList::dataAt(int position) { + int ll_length = getLength(); + if (position < 1 || position > ll_length) + return -1; + + Node* current = head; + for (int i = 1; i < position; i++) + current = current->next; + + return current->data; +} + +/** + * Returns index of node in linked list with node value 'key'. + * Returns -1, if the key is not present. + * @param count index of node with value 'key' +*/ +template +int LinkedList::indexOf(T key) { + Node* node = head; + int count = 1; + while (node != nullptr) { + if (node->data == key) + return count; + node = node->next; + count++; + } + return -1; +} + +/** + * Reverse the original linked list using iterative approach. +*/ +template +void LinkedList::Reverse() { + Node* previous = nullptr; + Node* following = nullptr; + Node* current = head; + + while (current != nullptr) { + following = current->next; + current->next = previous; + previous = current; + current = following; + } + head = previous; +} + +/** + * Reverse the original linked list using recursive approach. +*/ +template +void LinkedList::ReverseRecursive(Node* node) { + if (node == nullptr) + return; + if (node->next == nullptr) { + head = node; + return; + } + ReverseRecursive(node->next); + Node* prev = node->next; + prev->next = node; + node->next = nullptr; +} + +/** + * printList simply prints the node value from head to end. +*/ +template +void LinkedList::printList() { + Node* temp = head; + while (temp) { + std::cout << " -> " << temp->data; + temp = temp->next; + } + std::cout << std::endl; +} + +/** + * printListRecursive simply prints the node value from head to end. + * It uses recursive approach. +*/ +template +void LinkedList::printListRecursive(Node* node) { + if (node == nullptr) return; + std::cout << " -> " << node->data; + printListRecursive(node->next); +} + +/** + * printReverseListRecursive simply prints the node value in reverse order, + * from tail to head. It uses recursive approach. +*/ +template +void LinkedList::printReverseListRecursive(Node* node) { + if (node == nullptr) return; + printReverseListRecursive(node->next); + std::cout << " -> " << node->data; +} + #endif diff --git a/LinkedList/LinkedList/Makefile b/LinkedList/LinkedList/Makefile index 84f4171..0a2296d 100644 --- a/LinkedList/LinkedList/Makefile +++ b/LinkedList/LinkedList/Makefile @@ -3,11 +3,8 @@ GTEST_INCLUDE_PATH=../../googletest/googletest/include/ GTEST_LIBRARY_PATH=../../googletest/build/lib/ -lgtest -lgtest_main CCFLAGS=-Wall -std=c++14 -all: LinkedList.o - $(CC) test_LinkedList.cpp LinkedList.o $(CCFLAGS) -I$(GTEST_INCLUDE_PATH) -L$(GTEST_LIBRARY_PATH) - -LinkedList.o: - $(CC) -c LinkedList.cpp $(CCFLAGS) +all: + $(CC) test_LinkedList.cpp $(CCFLAGS) -I$(GTEST_INCLUDE_PATH) -L$(GTEST_LIBRARY_PATH) clean: rm ./a.out *.o diff --git a/LinkedList/LinkedList/test_LinkedList.cpp b/LinkedList/LinkedList/test_LinkedList.cpp index 7355e87..3d10783 100755 --- a/LinkedList/LinkedList/test_LinkedList.cpp +++ b/LinkedList/LinkedList/test_LinkedList.cpp @@ -7,7 +7,7 @@ // LinkedList containing only multiple node class LinkedListDataInit : public testing::Test { protected: - LinkedList ll; + LinkedList ll; void SetUp() override { ll.insertEnd(1); ll.insertEnd(2); @@ -20,7 +20,7 @@ class LinkedListDataInit : public testing::Test { // LinkedList containing only one node class LinkedListSingleInit : public testing::Test { protected: - LinkedList ll; + LinkedList ll; void SetUp() override { ll.insertHead(5); } @@ -28,7 +28,7 @@ class LinkedListSingleInit : public testing::Test { /* Helper Functions */ // get tail node data -int getTailData(Node* node) { +int getTailData(Node* node) { while (node->next != nullptr) { node = node->next; } @@ -36,9 +36,9 @@ int getTailData(Node* node) { } // convert linked list data to vector representation -std::vector convertLinkedListToVector(Node* head) { +std::vector convertLinkedListToVector(Node* head) { std::vector result; - Node* temp = head; + Node* temp = head; while(temp) { result.push_back(temp->data); temp = temp->next; @@ -50,7 +50,7 @@ std::vector convertLinkedListToVector(Node* head) { // test insertHead method on empty linked list TEST(LinkedListEmptyInit, InsertHeadTest) { - LinkedList ll; + LinkedList ll; ll.insertHead(1); ASSERT_EQ(1, ll.getHead()->data); ll.insertHead(2); @@ -73,7 +73,7 @@ TEST_F(LinkedListDataInit, InsertHeadTest) { // test insertEnd method on empty linked list TEST(LinkedListEmptyInit, InsertEndTest) { - LinkedList ll; + LinkedList ll; ll.insertEnd(1); ASSERT_EQ(1, ll.getHead()->data); ll.insertEnd(2); @@ -99,7 +99,7 @@ TEST_F(LinkedListDataInit, InsertEndTest) { // test insertAt method on empty linked list TEST(LinkedListEmptyInit, InsertAtTest) { - LinkedList ll; + LinkedList ll; ll.insertAt(4, 3); ll.insertAt(2, 1); ll.insertAt(5, 3); @@ -129,7 +129,7 @@ TEST_F(LinkedListDataInit, InsertAtTest) { // test getLength method on empty linked list TEST(LinkedListEmptyInit, GetLengthTest) { - LinkedList ll; + LinkedList ll; ASSERT_EQ(0, ll.getLength()); ll.insertAt(4, 3); ASSERT_EQ(1, ll.getLength()); @@ -152,7 +152,7 @@ TEST_F(LinkedListDataInit, GetLengthTest) { // test getLengthRecursive method on empty linked list TEST(LinkedListEmptyInit, GetLengthRecursiveTest) { - LinkedList ll; + LinkedList ll; ASSERT_EQ(0, ll.getLengthRecursive(ll.getHead())); ll.insertAt(4, 3); ASSERT_EQ(1, ll.getLengthRecursive(ll.getHead())); @@ -177,7 +177,7 @@ TEST_F(LinkedListDataInit, GetLengthRecursiveTest) { // test deleteHead method on empty linked list TEST(LinkedListEmptyInit, DeleteHeadTest) { - LinkedList ll; + LinkedList ll; ASSERT_EQ(-1, ll.deleteHead()); // after removing every node from linked list, @@ -212,7 +212,7 @@ TEST_F(LinkedListDataInit, DeleteHeadTest) { // test deleteEnd method on empty linked list TEST(LinkedListEmptyInit, DeleteEndTest) { - LinkedList ll; + LinkedList ll; ll.insertHead(5); ASSERT_EQ(5, ll.deleteEnd()); @@ -255,7 +255,7 @@ TEST_F(LinkedListDataInit, DeleteEndTest) { // test deleteAt method on empty linked list TEST(LinkedListEmptyInit, DeleteAtTest) { - LinkedList ll; + LinkedList ll; ASSERT_EQ(-1, ll.deleteAt(3)); ASSERT_EQ(-1, ll.deleteAt(0)); ASSERT_EQ(-1, ll.deleteAt(-5)); @@ -298,7 +298,7 @@ TEST_F(LinkedListDataInit, DeleteAtTest) { // test deleteKey method on empty linked list TEST(LinkedListEmptyInit, DeleteKeyTest) { - LinkedList ll; + LinkedList ll; ASSERT_EQ(-1, ll.deleteKey(3)); ASSERT_EQ(-1, ll.deleteKey(0)); ASSERT_EQ(-1, ll.deleteKey(-5)); @@ -338,7 +338,7 @@ TEST_F(LinkedListDataInit, DeleteKeyTest) { // test deleteList method on empty linked list TEST(LinkedListEmptyInit, DeleteListTest) { - LinkedList ll; + LinkedList ll; ll.deleteList(); // after removing every node from linked list, @@ -369,7 +369,7 @@ TEST_F(LinkedListDataInit, DeleteListTest) { // test indexOf method on empty linked list TEST(LinkedListEmptyInit, IndexOfTest) { - LinkedList ll; + LinkedList ll; ASSERT_EQ(-1, ll.indexOf(2)); ASSERT_EQ(-1, ll.indexOf(0)); ASSERT_EQ(-1, ll.indexOf(-1)); @@ -400,7 +400,7 @@ TEST_F(LinkedListDataInit, IndexOfTest) { // test dataAt method on empty linked list TEST(LinkedListEmptyInit, DataAtTest) { - LinkedList ll; + LinkedList ll; ASSERT_EQ(-1, ll.dataAt(0)); ASSERT_EQ(-1, ll.dataAt(-1)); ASSERT_EQ(-1, ll.dataAt(1)); @@ -427,7 +427,7 @@ TEST_F(LinkedListDataInit, DataAtTest) { // test reverse method on empty linked list TEST(LinkedListEmptyInit, ReverseTest) { - LinkedList ll; + LinkedList ll; ll.Reverse(); // after removing every node from linked list, @@ -453,7 +453,7 @@ TEST_F(LinkedListDataInit, ReverseTest) { // test reverse method (recursive) on empty linked list TEST(LinkedListEmptyInit, ReverseRecursiveTest) { - LinkedList ll; + LinkedList ll; ll.ReverseRecursive(ll.getHead()); // after removing every node from linked list, From 1e9275d92ccf41824fdf422495bb3a969055fe29 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Wed, 8 Apr 2020 08:37:24 +0530 Subject: [PATCH 053/209] add namespace linkedlist --- LinkedList/LinkedList/LinkedList.hpp | 565 +++++++++++----------- LinkedList/LinkedList/test_LinkedList.cpp | 38 +- 2 files changed, 302 insertions(+), 301 deletions(-) diff --git a/LinkedList/LinkedList/LinkedList.hpp b/LinkedList/LinkedList/LinkedList.hpp index be4c896..77039df 100644 --- a/LinkedList/LinkedList/LinkedList.hpp +++ b/LinkedList/LinkedList/LinkedList.hpp @@ -1,332 +1,333 @@ #ifndef LINKEDLIST_H #define LINKEDLIST_H -template -struct Node { - T data; - Node* next; +namespace LinkedList { + template + struct Node { + T data; + Node* next; - Node(T _data) { data = _data; next = nullptr; } -}; + Node(T _data) { data = _data; next = nullptr; } + }; -template -class LinkedList { -private: - Node* head; + template + class LinkedList { + private: + Node* head; -public: - LinkedList() { head = nullptr; } - Node* getHead() { return head; } - int getLength(); - int getLengthRecursive(Node* node); + public: + LinkedList() { head = nullptr; } + Node* getHead() { return head; } + int getLength(); + int getLengthRecursive(Node* node); - /* Insertion Method */ - void insertHead(T data); - void insertEnd(T data); - void insertAt(T data, int position); + /* Insertion Method */ + void insertHead(T data); + void insertEnd(T data); + void insertAt(T data, int position); - /* Deletion Method */ - T deleteHead(); - T deleteEnd(); - T deleteAt(int position); - T deleteKey(T key); - void deleteList(); + /* Deletion Method */ + T deleteHead(); + T deleteEnd(); + T deleteAt(int position); + T deleteKey(T key); + void deleteList(); - /* Data */ - T dataAt(int position); - int indexOf(T key); + /* Data */ + T dataAt(int position); + int indexOf(T key); - /* Recursive Method */ - void Reverse(); - void ReverseRecursive(Node* node); + /* Recursive Method */ + void Reverse(); + void ReverseRecursive(Node* node); - /* Print Method */ - void printList(); - void printListRecursive(Node* node); - void printReverseListRecursive(Node* node); -}; + /* Print Method */ + void printList(); + void printListRecursive(Node* node); + void printReverseListRecursive(Node* node); + }; -/** - * Returns the number of node currently present in the linked list. - * @return count of node, or 0 if the list is empty. -*/ -template -int LinkedList::getLength() { - Node* temp = head; - int count = 0; - while (temp) { - count++; - temp = temp->next; + /** + * Returns the number of node currently present in the linked list. + * @return count of node, or 0 if the list is empty. + */ + template + int LinkedList::getLength() { + Node* temp = head; + int count = 0; + while (temp) { + count++; + temp = temp->next; + } + return count; } - return count; -} - -/** - * Returns the number of node currently present in the linked list. - * It uses recursive approach. - * @param node starting node from where counting is start. - * @return count of node, or 0 if the list is empty. -*/ -template -int LinkedList::getLengthRecursive(Node* node) { - if (node == nullptr) return 0; - return 1 + getLengthRecursive(node->next); -} -/** - * Inserts new node with value 'data' at the start of linked list. - * @param data new data element that needs to be added at the start -*/ -template -void LinkedList::insertHead(T data) { - Node* temp = new Node(data); - temp->next = head; - head = temp; -} - -/** - * Inserts new node with value 'data' at the end of linked list. - * @param data new data element that needs to be append at the end -*/ -template -void LinkedList::insertEnd(T data) { - Node* newNode = new Node(data); - Node* temp = head; - if (temp == nullptr) { - head = newNode; - return; + /** + * Returns the number of node currently present in the linked list. + * It uses recursive approach. + * @param node starting node from where counting is start. + * @return count of node, or 0 if the list is empty. + */ + template + int LinkedList::getLengthRecursive(Node* node) { + if (node == nullptr) return 0; + return 1 + getLengthRecursive(node->next); } - while(temp->next != nullptr) { - temp = temp->next; + + /** + * Inserts new node with value 'data' at the start of linked list. + * @param data new data element that needs to be added at the start + */ + template + void LinkedList::insertHead(T data) { + Node* temp = new Node(data); + temp->next = head; + head = temp; } - temp->next = newNode; -} -/** - * Insert new node with value 'data' at given position in linked list. - * @param data new data element that needs to be added at given position. - * @param position position where new node will enter. - * Position is 1-based. -*/ -template -void LinkedList::insertAt(T data, int position) { - int linkedlist_len = getLength(); - if (position <= 1) { - insertHead(data); - return; - } else if (position >= linkedlist_len) { - insertEnd(data); - return; - } else { + /** + * Inserts new node with value 'data' at the end of linked list. + * @param data new data element that needs to be append at the end + */ + template + void LinkedList::insertEnd(T data) { Node* newNode = new Node(data); - Node* previous = head; - Node* current = head; - for (int i = 1; i < position; i++) { - previous = current; - current = current->next; + Node* temp = head; + if (temp == nullptr) { + head = newNode; + return; } - previous->next = newNode; - newNode->next = current; + while(temp->next != nullptr) { + temp = temp->next; + } + temp->next = newNode; } -} -/** - * Delete head node from linked list - * @return removedData value of deleted node -*/ -template -T LinkedList::deleteHead() { - if (head == nullptr) return -1; - Node* temp = head; - T removedData = temp->data; - head = head->next; - delete temp; - return removedData; -} - -/** - * Delete end node from linked list - * @return removedData value of deleted node -*/ -template -T LinkedList::deleteEnd() { - if (head == nullptr) return -1; - Node* current = head; - if (head->next == nullptr) head = nullptr; - else { - Node* previous = head; - while (current->next != nullptr) { - previous = current; - current = current->next; + /** + * Insert new node with value 'data' at given position in linked list. + * @param data new data element that needs to be added at given position. + * @param position position where new node will enter. + * Position is 1-based. + */ + template + void LinkedList::insertAt(T data, int position) { + int linkedlist_len = getLength(); + if (position <= 1) { + insertHead(data); + return; + } else if (position >= linkedlist_len) { + insertEnd(data); + return; + } else { + Node* newNode = new Node(data); + Node* previous = head; + Node* current = head; + for (int i = 1; i < position; i++) { + previous = current; + current = current->next; + } + previous->next = newNode; + newNode->next = current; } - previous->next = nullptr; } - T removedData = current->data; - delete current; - return removedData; -} -/** - * Delete node present at given position from linked list - * @param position position at which node needs to be deleted. - * Position is 1-based. - * @return removedData value of deleted node -*/ -template -T LinkedList::deleteAt(int position) { - int ll_length = getLength(); - if (position < 1 || position > ll_length) - return -1; + /** + * Delete head node from linked list + * @return removedData value of deleted node + */ + template + T LinkedList::deleteHead() { + if (head == nullptr) return -1; + Node* temp = head; + T removedData = temp->data; + head = head->next; + delete temp; + return removedData; + } - if (position == 1) - return deleteHead(); - else if (position == ll_length) - return deleteEnd(); - else { - Node* previous = head; + /** + * Delete end node from linked list + * @return removedData value of deleted node + */ + template + T LinkedList::deleteEnd() { + if (head == nullptr) return -1; Node* current = head; - for (int i = 1; i < position; i++) { - previous = current; - current = current->next; + if (head->next == nullptr) head = nullptr; + else { + Node* previous = head; + while (current->next != nullptr) { + previous = current; + current = current->next; + } + previous->next = nullptr; } T removedData = current->data; - previous->next = current->next; - current->next = nullptr; delete current; return removedData; } -} -/** - * Delete first occurance of node from linked list with value 'key' - * @param key node value that needs to be deleted - * @return removedData value of deleted node -*/ -template -T LinkedList::deleteKey(T key) { - return deleteAt(indexOf(key)); -} + /** + * Delete node present at given position from linked list + * @param position position at which node needs to be deleted. + * Position is 1-based. + * @return removedData value of deleted node + */ + template + T LinkedList::deleteAt(int position) { + int ll_length = getLength(); + if (position < 1 || position > ll_length) + return -1; -/** - * Deletes entire linked list. Cleans up the memory. - * head node pointer is pointing to null. -*/ -template -void LinkedList::deleteList() { - Node* current = head; - Node* next = nullptr; - while (current != nullptr) { - next = current->next; - delete current; - current = next; + if (position == 1) + return deleteHead(); + else if (position == ll_length) + return deleteEnd(); + else { + Node* previous = head; + Node* current = head; + for (int i = 1; i < position; i++) { + previous = current; + current = current->next; + } + T removedData = current->data; + previous->next = current->next; + current->next = nullptr; + delete current; + return removedData; + } } - head = nullptr; -} -/** - * Get node value present at given position in the linked list - * @param position position at which node value is needed. Position is 1-based. - * @return node value at position -*/ -template -T LinkedList::dataAt(int position) { - int ll_length = getLength(); - if (position < 1 || position > ll_length) - return -1; + /** + * Delete first occurance of node from linked list with value 'key' + * @param key node value that needs to be deleted + * @return removedData value of deleted node + */ + template + T LinkedList::deleteKey(T key) { + return deleteAt(indexOf(key)); + } - Node* current = head; - for (int i = 1; i < position; i++) - current = current->next; + /** + * Deletes entire linked list. Cleans up the memory. + * head node pointer is pointing to null. + */ + template + void LinkedList::deleteList() { + Node* current = head; + Node* next = nullptr; + while (current != nullptr) { + next = current->next; + delete current; + current = next; + } + head = nullptr; + } - return current->data; -} + /** + * Get node value present at given position in the linked list + * @param position position at which node value is needed. Position is 1-based. + * @return node value at position + */ + template + T LinkedList::dataAt(int position) { + int ll_length = getLength(); + if (position < 1 || position > ll_length) + return -1; -/** - * Returns index of node in linked list with node value 'key'. - * Returns -1, if the key is not present. - * @param count index of node with value 'key' -*/ -template -int LinkedList::indexOf(T key) { - Node* node = head; - int count = 1; - while (node != nullptr) { - if (node->data == key) - return count; - node = node->next; - count++; + Node* current = head; + for (int i = 1; i < position; i++) + current = current->next; + + return current->data; } - return -1; -} -/** - * Reverse the original linked list using iterative approach. -*/ -template -void LinkedList::Reverse() { - Node* previous = nullptr; - Node* following = nullptr; - Node* current = head; + /** + * Returns index of node in linked list with node value 'key'. + * Returns -1, if the key is not present. + * @param count index of node with value 'key' + */ + template + int LinkedList::indexOf(T key) { + Node* node = head; + int count = 1; + while (node != nullptr) { + if (node->data == key) + return count; + node = node->next; + count++; + } + return -1; + } - while (current != nullptr) { - following = current->next; - current->next = previous; - previous = current; - current = following; + /** + * Reverse the original linked list using iterative approach. + */ + template + void LinkedList::Reverse() { + Node* previous = nullptr; + Node* following = nullptr; + Node* current = head; + + while (current != nullptr) { + following = current->next; + current->next = previous; + previous = current; + current = following; + } + head = previous; } - head = previous; -} -/** - * Reverse the original linked list using recursive approach. -*/ -template -void LinkedList::ReverseRecursive(Node* node) { - if (node == nullptr) - return; - if (node->next == nullptr) { - head = node; - return; + /** + * Reverse the original linked list using recursive approach. + */ + template + void LinkedList::ReverseRecursive(Node* node) { + if (node == nullptr) + return; + if (node->next == nullptr) { + head = node; + return; + } + ReverseRecursive(node->next); + Node* prev = node->next; + prev->next = node; + node->next = nullptr; } - ReverseRecursive(node->next); - Node* prev = node->next; - prev->next = node; - node->next = nullptr; -} -/** - * printList simply prints the node value from head to end. -*/ -template -void LinkedList::printList() { - Node* temp = head; - while (temp) { - std::cout << " -> " << temp->data; - temp = temp->next; + /** + * printList simply prints the node value from head to end. + */ + template + void LinkedList::printList() { + Node* temp = head; + while (temp) { + std::cout << " -> " << temp->data; + temp = temp->next; + } + std::cout << std::endl; } - std::cout << std::endl; -} -/** - * printListRecursive simply prints the node value from head to end. - * It uses recursive approach. -*/ -template -void LinkedList::printListRecursive(Node* node) { - if (node == nullptr) return; - std::cout << " -> " << node->data; - printListRecursive(node->next); -} + /** + * printListRecursive simply prints the node value from head to end. + * It uses recursive approach. + */ + template + void LinkedList::printListRecursive(Node* node) { + if (node == nullptr) return; + std::cout << " -> " << node->data; + printListRecursive(node->next); + } -/** - * printReverseListRecursive simply prints the node value in reverse order, - * from tail to head. It uses recursive approach. -*/ -template -void LinkedList::printReverseListRecursive(Node* node) { - if (node == nullptr) return; - printReverseListRecursive(node->next); - std::cout << " -> " << node->data; + /** + * printReverseListRecursive simply prints the node value in reverse order, + * from tail to head. It uses recursive approach. + */ + template + void LinkedList::printReverseListRecursive(Node* node) { + if (node == nullptr) return; + printReverseListRecursive(node->next); + std::cout << " -> " << node->data; + } } - #endif diff --git a/LinkedList/LinkedList/test_LinkedList.cpp b/LinkedList/LinkedList/test_LinkedList.cpp index 3d10783..e728a1e 100755 --- a/LinkedList/LinkedList/test_LinkedList.cpp +++ b/LinkedList/LinkedList/test_LinkedList.cpp @@ -7,7 +7,7 @@ // LinkedList containing only multiple node class LinkedListDataInit : public testing::Test { protected: - LinkedList ll; + LinkedList::LinkedList ll; void SetUp() override { ll.insertEnd(1); ll.insertEnd(2); @@ -20,7 +20,7 @@ class LinkedListDataInit : public testing::Test { // LinkedList containing only one node class LinkedListSingleInit : public testing::Test { protected: - LinkedList ll; + LinkedList::LinkedList ll; void SetUp() override { ll.insertHead(5); } @@ -28,7 +28,7 @@ class LinkedListSingleInit : public testing::Test { /* Helper Functions */ // get tail node data -int getTailData(Node* node) { +int getTailData(LinkedList::Node* node) { while (node->next != nullptr) { node = node->next; } @@ -36,9 +36,9 @@ int getTailData(Node* node) { } // convert linked list data to vector representation -std::vector convertLinkedListToVector(Node* head) { +std::vector convertLinkedListToVector(LinkedList::Node* head) { std::vector result; - Node* temp = head; + LinkedList::Node* temp = head; while(temp) { result.push_back(temp->data); temp = temp->next; @@ -50,7 +50,7 @@ std::vector convertLinkedListToVector(Node* head) { // test insertHead method on empty linked list TEST(LinkedListEmptyInit, InsertHeadTest) { - LinkedList ll; + LinkedList::LinkedList ll; ll.insertHead(1); ASSERT_EQ(1, ll.getHead()->data); ll.insertHead(2); @@ -73,7 +73,7 @@ TEST_F(LinkedListDataInit, InsertHeadTest) { // test insertEnd method on empty linked list TEST(LinkedListEmptyInit, InsertEndTest) { - LinkedList ll; + LinkedList::LinkedList ll; ll.insertEnd(1); ASSERT_EQ(1, ll.getHead()->data); ll.insertEnd(2); @@ -99,7 +99,7 @@ TEST_F(LinkedListDataInit, InsertEndTest) { // test insertAt method on empty linked list TEST(LinkedListEmptyInit, InsertAtTest) { - LinkedList ll; + LinkedList::LinkedList ll; ll.insertAt(4, 3); ll.insertAt(2, 1); ll.insertAt(5, 3); @@ -129,7 +129,7 @@ TEST_F(LinkedListDataInit, InsertAtTest) { // test getLength method on empty linked list TEST(LinkedListEmptyInit, GetLengthTest) { - LinkedList ll; + LinkedList::LinkedList ll; ASSERT_EQ(0, ll.getLength()); ll.insertAt(4, 3); ASSERT_EQ(1, ll.getLength()); @@ -152,7 +152,7 @@ TEST_F(LinkedListDataInit, GetLengthTest) { // test getLengthRecursive method on empty linked list TEST(LinkedListEmptyInit, GetLengthRecursiveTest) { - LinkedList ll; + LinkedList::LinkedList ll; ASSERT_EQ(0, ll.getLengthRecursive(ll.getHead())); ll.insertAt(4, 3); ASSERT_EQ(1, ll.getLengthRecursive(ll.getHead())); @@ -177,7 +177,7 @@ TEST_F(LinkedListDataInit, GetLengthRecursiveTest) { // test deleteHead method on empty linked list TEST(LinkedListEmptyInit, DeleteHeadTest) { - LinkedList ll; + LinkedList::LinkedList ll; ASSERT_EQ(-1, ll.deleteHead()); // after removing every node from linked list, @@ -212,7 +212,7 @@ TEST_F(LinkedListDataInit, DeleteHeadTest) { // test deleteEnd method on empty linked list TEST(LinkedListEmptyInit, DeleteEndTest) { - LinkedList ll; + LinkedList::LinkedList ll; ll.insertHead(5); ASSERT_EQ(5, ll.deleteEnd()); @@ -255,7 +255,7 @@ TEST_F(LinkedListDataInit, DeleteEndTest) { // test deleteAt method on empty linked list TEST(LinkedListEmptyInit, DeleteAtTest) { - LinkedList ll; + LinkedList::LinkedList ll; ASSERT_EQ(-1, ll.deleteAt(3)); ASSERT_EQ(-1, ll.deleteAt(0)); ASSERT_EQ(-1, ll.deleteAt(-5)); @@ -298,7 +298,7 @@ TEST_F(LinkedListDataInit, DeleteAtTest) { // test deleteKey method on empty linked list TEST(LinkedListEmptyInit, DeleteKeyTest) { - LinkedList ll; + LinkedList::LinkedList ll; ASSERT_EQ(-1, ll.deleteKey(3)); ASSERT_EQ(-1, ll.deleteKey(0)); ASSERT_EQ(-1, ll.deleteKey(-5)); @@ -338,7 +338,7 @@ TEST_F(LinkedListDataInit, DeleteKeyTest) { // test deleteList method on empty linked list TEST(LinkedListEmptyInit, DeleteListTest) { - LinkedList ll; + LinkedList::LinkedList ll; ll.deleteList(); // after removing every node from linked list, @@ -369,7 +369,7 @@ TEST_F(LinkedListDataInit, DeleteListTest) { // test indexOf method on empty linked list TEST(LinkedListEmptyInit, IndexOfTest) { - LinkedList ll; + LinkedList::LinkedList ll; ASSERT_EQ(-1, ll.indexOf(2)); ASSERT_EQ(-1, ll.indexOf(0)); ASSERT_EQ(-1, ll.indexOf(-1)); @@ -400,7 +400,7 @@ TEST_F(LinkedListDataInit, IndexOfTest) { // test dataAt method on empty linked list TEST(LinkedListEmptyInit, DataAtTest) { - LinkedList ll; + LinkedList::LinkedList ll; ASSERT_EQ(-1, ll.dataAt(0)); ASSERT_EQ(-1, ll.dataAt(-1)); ASSERT_EQ(-1, ll.dataAt(1)); @@ -427,7 +427,7 @@ TEST_F(LinkedListDataInit, DataAtTest) { // test reverse method on empty linked list TEST(LinkedListEmptyInit, ReverseTest) { - LinkedList ll; + LinkedList::LinkedList ll; ll.Reverse(); // after removing every node from linked list, @@ -453,7 +453,7 @@ TEST_F(LinkedListDataInit, ReverseTest) { // test reverse method (recursive) on empty linked list TEST(LinkedListEmptyInit, ReverseRecursiveTest) { - LinkedList ll; + LinkedList::LinkedList ll; ll.ReverseRecursive(ll.getHead()); // after removing every node from linked list, From 1030930caf42738c930b1f652873e8bfd7c68fbf Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Wed, 8 Apr 2020 15:49:15 +0530 Subject: [PATCH 054/209] rename C_Deprecated to C --- {C_Deprecated => C}/dynamic_connectivity/quick_find/Makefile | 0 {C_Deprecated => C}/dynamic_connectivity/quick_find/main.c | 0 {C_Deprecated => C}/dynamic_connectivity/quick_find/quick_find.c | 0 {C_Deprecated => C}/dynamic_connectivity/quick_find/quick_find.h | 0 {C_Deprecated => C}/dynamic_connectivity/quick_union/Makefile | 0 {C_Deprecated => C}/dynamic_connectivity/quick_union/main.c | 0 .../dynamic_connectivity/quick_union/quick_union.c | 0 .../dynamic_connectivity/quick_union/quick_union.h | 0 {C_Deprecated => C}/queue/Makefile | 0 {C_Deprecated => C}/queue/main.c | 0 {C_Deprecated => C}/queue/queue.c | 0 {C_Deprecated => C}/queue/queue.h | 0 {C_Deprecated => C}/shuffling/Makefile | 0 {C_Deprecated => C}/shuffling/shuffle_array.c | 0 {C_Deprecated => C}/sorts/bubble_sort/Makefile | 0 {C_Deprecated => C}/sorts/bubble_sort/bubble_sort.c | 0 {C_Deprecated => C}/sorts/generic/Makefile | 0 {C_Deprecated => C}/sorts/generic/README.md | 0 {C_Deprecated => C}/sorts/generic/main.c | 0 {C_Deprecated => C}/sorts/generic/sort.c | 0 {C_Deprecated => C}/sorts/generic/sort.h | 0 {C_Deprecated => C}/sorts/insertion_sort/Makefile | 0 {C_Deprecated => C}/sorts/insertion_sort/insertion_sort.c | 0 {C_Deprecated => C}/sorts/merge_sort/Makefile | 0 {C_Deprecated => C}/sorts/merge_sort/merge_sort.c | 0 {C_Deprecated => C}/sorts/quick_sort/Makefile | 0 {C_Deprecated => C}/sorts/quick_sort/quick_sort.c | 0 {C_Deprecated => C}/sorts/selection_sort/Makefile | 0 {C_Deprecated => C}/sorts/selection_sort/selection_sort.c | 0 {C_Deprecated => C}/sorts/shell_sort/Makefile | 0 {C_Deprecated => C}/sorts/shell_sort/shell_sort.c | 0 {C_Deprecated => C}/stack/array_implementation/Makefile | 0 {C_Deprecated => C}/stack/array_implementation/main.c | 0 {C_Deprecated => C}/stack/array_implementation/stack.c | 0 {C_Deprecated => C}/stack/array_implementation/stack.h | 0 {C_Deprecated => C}/stack/generic_array_implementation/Makefile | 0 {C_Deprecated => C}/stack/generic_array_implementation/main.c | 0 {C_Deprecated => C}/stack/generic_array_implementation/stack.c | 0 {C_Deprecated => C}/stack/generic_array_implementation/stack.h | 0 39 files changed, 0 insertions(+), 0 deletions(-) rename {C_Deprecated => C}/dynamic_connectivity/quick_find/Makefile (100%) rename {C_Deprecated => C}/dynamic_connectivity/quick_find/main.c (100%) rename {C_Deprecated => C}/dynamic_connectivity/quick_find/quick_find.c (100%) rename {C_Deprecated => C}/dynamic_connectivity/quick_find/quick_find.h (100%) rename {C_Deprecated => C}/dynamic_connectivity/quick_union/Makefile (100%) rename {C_Deprecated => C}/dynamic_connectivity/quick_union/main.c (100%) rename {C_Deprecated => C}/dynamic_connectivity/quick_union/quick_union.c (100%) rename {C_Deprecated => C}/dynamic_connectivity/quick_union/quick_union.h (100%) rename {C_Deprecated => C}/queue/Makefile (100%) rename {C_Deprecated => C}/queue/main.c (100%) rename {C_Deprecated => C}/queue/queue.c (100%) rename {C_Deprecated => C}/queue/queue.h (100%) rename {C_Deprecated => C}/shuffling/Makefile (100%) rename {C_Deprecated => C}/shuffling/shuffle_array.c (100%) rename {C_Deprecated => C}/sorts/bubble_sort/Makefile (100%) rename {C_Deprecated => C}/sorts/bubble_sort/bubble_sort.c (100%) rename {C_Deprecated => C}/sorts/generic/Makefile (100%) rename {C_Deprecated => C}/sorts/generic/README.md (100%) rename {C_Deprecated => C}/sorts/generic/main.c (100%) rename {C_Deprecated => C}/sorts/generic/sort.c (100%) rename {C_Deprecated => C}/sorts/generic/sort.h (100%) rename {C_Deprecated => C}/sorts/insertion_sort/Makefile (100%) rename {C_Deprecated => C}/sorts/insertion_sort/insertion_sort.c (100%) rename {C_Deprecated => C}/sorts/merge_sort/Makefile (100%) rename {C_Deprecated => C}/sorts/merge_sort/merge_sort.c (100%) rename {C_Deprecated => C}/sorts/quick_sort/Makefile (100%) rename {C_Deprecated => C}/sorts/quick_sort/quick_sort.c (100%) rename {C_Deprecated => C}/sorts/selection_sort/Makefile (100%) rename {C_Deprecated => C}/sorts/selection_sort/selection_sort.c (100%) rename {C_Deprecated => C}/sorts/shell_sort/Makefile (100%) rename {C_Deprecated => C}/sorts/shell_sort/shell_sort.c (100%) rename {C_Deprecated => C}/stack/array_implementation/Makefile (100%) rename {C_Deprecated => C}/stack/array_implementation/main.c (100%) rename {C_Deprecated => C}/stack/array_implementation/stack.c (100%) rename {C_Deprecated => C}/stack/array_implementation/stack.h (100%) rename {C_Deprecated => C}/stack/generic_array_implementation/Makefile (100%) rename {C_Deprecated => C}/stack/generic_array_implementation/main.c (100%) rename {C_Deprecated => C}/stack/generic_array_implementation/stack.c (100%) rename {C_Deprecated => C}/stack/generic_array_implementation/stack.h (100%) diff --git a/C_Deprecated/dynamic_connectivity/quick_find/Makefile b/C/dynamic_connectivity/quick_find/Makefile similarity index 100% rename from C_Deprecated/dynamic_connectivity/quick_find/Makefile rename to C/dynamic_connectivity/quick_find/Makefile diff --git a/C_Deprecated/dynamic_connectivity/quick_find/main.c b/C/dynamic_connectivity/quick_find/main.c similarity index 100% rename from C_Deprecated/dynamic_connectivity/quick_find/main.c rename to C/dynamic_connectivity/quick_find/main.c diff --git a/C_Deprecated/dynamic_connectivity/quick_find/quick_find.c b/C/dynamic_connectivity/quick_find/quick_find.c similarity index 100% rename from C_Deprecated/dynamic_connectivity/quick_find/quick_find.c rename to C/dynamic_connectivity/quick_find/quick_find.c diff --git a/C_Deprecated/dynamic_connectivity/quick_find/quick_find.h b/C/dynamic_connectivity/quick_find/quick_find.h similarity index 100% rename from C_Deprecated/dynamic_connectivity/quick_find/quick_find.h rename to C/dynamic_connectivity/quick_find/quick_find.h diff --git a/C_Deprecated/dynamic_connectivity/quick_union/Makefile b/C/dynamic_connectivity/quick_union/Makefile similarity index 100% rename from C_Deprecated/dynamic_connectivity/quick_union/Makefile rename to C/dynamic_connectivity/quick_union/Makefile diff --git a/C_Deprecated/dynamic_connectivity/quick_union/main.c b/C/dynamic_connectivity/quick_union/main.c similarity index 100% rename from C_Deprecated/dynamic_connectivity/quick_union/main.c rename to C/dynamic_connectivity/quick_union/main.c diff --git a/C_Deprecated/dynamic_connectivity/quick_union/quick_union.c b/C/dynamic_connectivity/quick_union/quick_union.c similarity index 100% rename from C_Deprecated/dynamic_connectivity/quick_union/quick_union.c rename to C/dynamic_connectivity/quick_union/quick_union.c diff --git a/C_Deprecated/dynamic_connectivity/quick_union/quick_union.h b/C/dynamic_connectivity/quick_union/quick_union.h similarity index 100% rename from C_Deprecated/dynamic_connectivity/quick_union/quick_union.h rename to C/dynamic_connectivity/quick_union/quick_union.h diff --git a/C_Deprecated/queue/Makefile b/C/queue/Makefile similarity index 100% rename from C_Deprecated/queue/Makefile rename to C/queue/Makefile diff --git a/C_Deprecated/queue/main.c b/C/queue/main.c similarity index 100% rename from C_Deprecated/queue/main.c rename to C/queue/main.c diff --git a/C_Deprecated/queue/queue.c b/C/queue/queue.c similarity index 100% rename from C_Deprecated/queue/queue.c rename to C/queue/queue.c diff --git a/C_Deprecated/queue/queue.h b/C/queue/queue.h similarity index 100% rename from C_Deprecated/queue/queue.h rename to C/queue/queue.h diff --git a/C_Deprecated/shuffling/Makefile b/C/shuffling/Makefile similarity index 100% rename from C_Deprecated/shuffling/Makefile rename to C/shuffling/Makefile diff --git a/C_Deprecated/shuffling/shuffle_array.c b/C/shuffling/shuffle_array.c similarity index 100% rename from C_Deprecated/shuffling/shuffle_array.c rename to C/shuffling/shuffle_array.c diff --git a/C_Deprecated/sorts/bubble_sort/Makefile b/C/sorts/bubble_sort/Makefile similarity index 100% rename from C_Deprecated/sorts/bubble_sort/Makefile rename to C/sorts/bubble_sort/Makefile diff --git a/C_Deprecated/sorts/bubble_sort/bubble_sort.c b/C/sorts/bubble_sort/bubble_sort.c similarity index 100% rename from C_Deprecated/sorts/bubble_sort/bubble_sort.c rename to C/sorts/bubble_sort/bubble_sort.c diff --git a/C_Deprecated/sorts/generic/Makefile b/C/sorts/generic/Makefile similarity index 100% rename from C_Deprecated/sorts/generic/Makefile rename to C/sorts/generic/Makefile diff --git a/C_Deprecated/sorts/generic/README.md b/C/sorts/generic/README.md similarity index 100% rename from C_Deprecated/sorts/generic/README.md rename to C/sorts/generic/README.md diff --git a/C_Deprecated/sorts/generic/main.c b/C/sorts/generic/main.c similarity index 100% rename from C_Deprecated/sorts/generic/main.c rename to C/sorts/generic/main.c diff --git a/C_Deprecated/sorts/generic/sort.c b/C/sorts/generic/sort.c similarity index 100% rename from C_Deprecated/sorts/generic/sort.c rename to C/sorts/generic/sort.c diff --git a/C_Deprecated/sorts/generic/sort.h b/C/sorts/generic/sort.h similarity index 100% rename from C_Deprecated/sorts/generic/sort.h rename to C/sorts/generic/sort.h diff --git a/C_Deprecated/sorts/insertion_sort/Makefile b/C/sorts/insertion_sort/Makefile similarity index 100% rename from C_Deprecated/sorts/insertion_sort/Makefile rename to C/sorts/insertion_sort/Makefile diff --git a/C_Deprecated/sorts/insertion_sort/insertion_sort.c b/C/sorts/insertion_sort/insertion_sort.c similarity index 100% rename from C_Deprecated/sorts/insertion_sort/insertion_sort.c rename to C/sorts/insertion_sort/insertion_sort.c diff --git a/C_Deprecated/sorts/merge_sort/Makefile b/C/sorts/merge_sort/Makefile similarity index 100% rename from C_Deprecated/sorts/merge_sort/Makefile rename to C/sorts/merge_sort/Makefile diff --git a/C_Deprecated/sorts/merge_sort/merge_sort.c b/C/sorts/merge_sort/merge_sort.c similarity index 100% rename from C_Deprecated/sorts/merge_sort/merge_sort.c rename to C/sorts/merge_sort/merge_sort.c diff --git a/C_Deprecated/sorts/quick_sort/Makefile b/C/sorts/quick_sort/Makefile similarity index 100% rename from C_Deprecated/sorts/quick_sort/Makefile rename to C/sorts/quick_sort/Makefile diff --git a/C_Deprecated/sorts/quick_sort/quick_sort.c b/C/sorts/quick_sort/quick_sort.c similarity index 100% rename from C_Deprecated/sorts/quick_sort/quick_sort.c rename to C/sorts/quick_sort/quick_sort.c diff --git a/C_Deprecated/sorts/selection_sort/Makefile b/C/sorts/selection_sort/Makefile similarity index 100% rename from C_Deprecated/sorts/selection_sort/Makefile rename to C/sorts/selection_sort/Makefile diff --git a/C_Deprecated/sorts/selection_sort/selection_sort.c b/C/sorts/selection_sort/selection_sort.c similarity index 100% rename from C_Deprecated/sorts/selection_sort/selection_sort.c rename to C/sorts/selection_sort/selection_sort.c diff --git a/C_Deprecated/sorts/shell_sort/Makefile b/C/sorts/shell_sort/Makefile similarity index 100% rename from C_Deprecated/sorts/shell_sort/Makefile rename to C/sorts/shell_sort/Makefile diff --git a/C_Deprecated/sorts/shell_sort/shell_sort.c b/C/sorts/shell_sort/shell_sort.c similarity index 100% rename from C_Deprecated/sorts/shell_sort/shell_sort.c rename to C/sorts/shell_sort/shell_sort.c diff --git a/C_Deprecated/stack/array_implementation/Makefile b/C/stack/array_implementation/Makefile similarity index 100% rename from C_Deprecated/stack/array_implementation/Makefile rename to C/stack/array_implementation/Makefile diff --git a/C_Deprecated/stack/array_implementation/main.c b/C/stack/array_implementation/main.c similarity index 100% rename from C_Deprecated/stack/array_implementation/main.c rename to C/stack/array_implementation/main.c diff --git a/C_Deprecated/stack/array_implementation/stack.c b/C/stack/array_implementation/stack.c similarity index 100% rename from C_Deprecated/stack/array_implementation/stack.c rename to C/stack/array_implementation/stack.c diff --git a/C_Deprecated/stack/array_implementation/stack.h b/C/stack/array_implementation/stack.h similarity index 100% rename from C_Deprecated/stack/array_implementation/stack.h rename to C/stack/array_implementation/stack.h diff --git a/C_Deprecated/stack/generic_array_implementation/Makefile b/C/stack/generic_array_implementation/Makefile similarity index 100% rename from C_Deprecated/stack/generic_array_implementation/Makefile rename to C/stack/generic_array_implementation/Makefile diff --git a/C_Deprecated/stack/generic_array_implementation/main.c b/C/stack/generic_array_implementation/main.c similarity index 100% rename from C_Deprecated/stack/generic_array_implementation/main.c rename to C/stack/generic_array_implementation/main.c diff --git a/C_Deprecated/stack/generic_array_implementation/stack.c b/C/stack/generic_array_implementation/stack.c similarity index 100% rename from C_Deprecated/stack/generic_array_implementation/stack.c rename to C/stack/generic_array_implementation/stack.c diff --git a/C_Deprecated/stack/generic_array_implementation/stack.h b/C/stack/generic_array_implementation/stack.h similarity index 100% rename from C_Deprecated/stack/generic_array_implementation/stack.h rename to C/stack/generic_array_implementation/stack.h From 7457361090f7abf524f7d10d7eb489f8501b43b3 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Wed, 8 Apr 2020 15:50:25 +0530 Subject: [PATCH 055/209] rename Go_Implementation to Go --- {Go_Implementation => Go}/README.md | 0 {Go_Implementation => Go}/bst/bst.go | 0 {Go_Implementation => Go}/bst/bst_test.go | 0 {Go_Implementation => Go}/bst/checkbst.go | 0 {Go_Implementation => Go}/bst/delete.go | 0 {Go_Implementation => Go}/bst/find.go | 0 {Go_Implementation => Go}/bst/height.go | 0 {Go_Implementation => Go}/bst/insert.go | 0 {Go_Implementation => Go}/bst/traversal.go | 0 {Go_Implementation => Go}/doublylinkedlist/doublylinkedlist.go | 0 .../doublylinkedlist/doublylinkedlist_test.go | 0 {Go_Implementation => Go}/hashtable/hashtable.go | 0 {Go_Implementation => Go}/hashtable/hashtable_test.go | 0 {Go_Implementation => Go}/heap/doc.go | 0 {Go_Implementation => Go}/heap/maxheap/maxheap.go | 0 {Go_Implementation => Go}/heap/maxheap/maxheap_test.go | 0 {Go_Implementation => Go}/heap/minheap/minheap.go | 0 {Go_Implementation => Go}/heap/minheap/minheap_test.go | 0 {Go_Implementation => Go}/linkedlist/linkedlist.go | 0 {Go_Implementation => Go}/linkedlist/linkedlist_test.go | 0 {Go_Implementation => Go}/queue/queue.go | 0 {Go_Implementation => Go}/queue/queue_test.go | 0 {Go_Implementation => Go}/redblacktree/doc.go | 0 {Go_Implementation => Go}/redblacktree/find.go | 0 {Go_Implementation => Go}/redblacktree/insert.go | 0 {Go_Implementation => Go}/redblacktree/redblacktree.go | 0 {Go_Implementation => Go}/redblacktree/redblacktree_test.go | 0 {Go_Implementation => Go}/redblacktree/utils.go | 0 {Go_Implementation => Go}/search/binarysearch.go | 0 {Go_Implementation => Go}/search/binarysearch_test.go | 0 {Go_Implementation => Go}/set/set.go | 0 {Go_Implementation => Go}/set/set_test.go | 0 {Go_Implementation => Go}/shuffle/shuffle.go | 0 {Go_Implementation => Go}/sort/bubble.go | 0 {Go_Implementation => Go}/sort/countingSort.go | 0 {Go_Implementation => Go}/sort/gnome.go | 0 {Go_Implementation => Go}/sort/heap.go | 0 {Go_Implementation => Go}/sort/insertion.go | 0 {Go_Implementation => Go}/sort/merge.go | 0 {Go_Implementation => Go}/sort/oddeven.go | 0 {Go_Implementation => Go}/sort/quick.go | 0 {Go_Implementation => Go}/sort/quickselect.go | 0 {Go_Implementation => Go}/sort/selection.go | 0 {Go_Implementation => Go}/sort/shell.go | 0 {Go_Implementation => Go}/sort/sort.go | 0 {Go_Implementation => Go}/sort/sort_test.go | 0 {Go_Implementation => Go}/stack/applications/applications.go | 0 {Go_Implementation => Go}/stack/applications/applications_test.go | 0 {Go_Implementation => Go}/stack/applications/infixevaluation.go | 0 {Go_Implementation => Go}/stack/applications/infixtopostfix.go | 0 {Go_Implementation => Go}/stack/applications/infixtoprefix.go | 0 {Go_Implementation => Go}/stack/applications/utils.go | 0 {Go_Implementation => Go}/stack/stack.go | 0 {Go_Implementation => Go}/stack/stack_test.go | 0 {Go_Implementation => Go}/trie/trie.go | 0 {Go_Implementation => Go}/trie/trie_test.go | 0 56 files changed, 0 insertions(+), 0 deletions(-) rename {Go_Implementation => Go}/README.md (100%) rename {Go_Implementation => Go}/bst/bst.go (100%) rename {Go_Implementation => Go}/bst/bst_test.go (100%) rename {Go_Implementation => Go}/bst/checkbst.go (100%) rename {Go_Implementation => Go}/bst/delete.go (100%) rename {Go_Implementation => Go}/bst/find.go (100%) rename {Go_Implementation => Go}/bst/height.go (100%) rename {Go_Implementation => Go}/bst/insert.go (100%) rename {Go_Implementation => Go}/bst/traversal.go (100%) rename {Go_Implementation => Go}/doublylinkedlist/doublylinkedlist.go (100%) rename {Go_Implementation => Go}/doublylinkedlist/doublylinkedlist_test.go (100%) rename {Go_Implementation => Go}/hashtable/hashtable.go (100%) rename {Go_Implementation => Go}/hashtable/hashtable_test.go (100%) rename {Go_Implementation => Go}/heap/doc.go (100%) rename {Go_Implementation => Go}/heap/maxheap/maxheap.go (100%) rename {Go_Implementation => Go}/heap/maxheap/maxheap_test.go (100%) rename {Go_Implementation => Go}/heap/minheap/minheap.go (100%) rename {Go_Implementation => Go}/heap/minheap/minheap_test.go (100%) rename {Go_Implementation => Go}/linkedlist/linkedlist.go (100%) rename {Go_Implementation => Go}/linkedlist/linkedlist_test.go (100%) rename {Go_Implementation => Go}/queue/queue.go (100%) rename {Go_Implementation => Go}/queue/queue_test.go (100%) rename {Go_Implementation => Go}/redblacktree/doc.go (100%) rename {Go_Implementation => Go}/redblacktree/find.go (100%) rename {Go_Implementation => Go}/redblacktree/insert.go (100%) rename {Go_Implementation => Go}/redblacktree/redblacktree.go (100%) rename {Go_Implementation => Go}/redblacktree/redblacktree_test.go (100%) rename {Go_Implementation => Go}/redblacktree/utils.go (100%) rename {Go_Implementation => Go}/search/binarysearch.go (100%) rename {Go_Implementation => Go}/search/binarysearch_test.go (100%) rename {Go_Implementation => Go}/set/set.go (100%) rename {Go_Implementation => Go}/set/set_test.go (100%) rename {Go_Implementation => Go}/shuffle/shuffle.go (100%) rename {Go_Implementation => Go}/sort/bubble.go (100%) rename {Go_Implementation => Go}/sort/countingSort.go (100%) rename {Go_Implementation => Go}/sort/gnome.go (100%) rename {Go_Implementation => Go}/sort/heap.go (100%) rename {Go_Implementation => Go}/sort/insertion.go (100%) rename {Go_Implementation => Go}/sort/merge.go (100%) rename {Go_Implementation => Go}/sort/oddeven.go (100%) rename {Go_Implementation => Go}/sort/quick.go (100%) rename {Go_Implementation => Go}/sort/quickselect.go (100%) rename {Go_Implementation => Go}/sort/selection.go (100%) rename {Go_Implementation => Go}/sort/shell.go (100%) rename {Go_Implementation => Go}/sort/sort.go (100%) rename {Go_Implementation => Go}/sort/sort_test.go (100%) rename {Go_Implementation => Go}/stack/applications/applications.go (100%) rename {Go_Implementation => Go}/stack/applications/applications_test.go (100%) rename {Go_Implementation => Go}/stack/applications/infixevaluation.go (100%) rename {Go_Implementation => Go}/stack/applications/infixtopostfix.go (100%) rename {Go_Implementation => Go}/stack/applications/infixtoprefix.go (100%) rename {Go_Implementation => Go}/stack/applications/utils.go (100%) rename {Go_Implementation => Go}/stack/stack.go (100%) rename {Go_Implementation => Go}/stack/stack_test.go (100%) rename {Go_Implementation => Go}/trie/trie.go (100%) rename {Go_Implementation => Go}/trie/trie_test.go (100%) diff --git a/Go_Implementation/README.md b/Go/README.md similarity index 100% rename from Go_Implementation/README.md rename to Go/README.md diff --git a/Go_Implementation/bst/bst.go b/Go/bst/bst.go similarity index 100% rename from Go_Implementation/bst/bst.go rename to Go/bst/bst.go diff --git a/Go_Implementation/bst/bst_test.go b/Go/bst/bst_test.go similarity index 100% rename from Go_Implementation/bst/bst_test.go rename to Go/bst/bst_test.go diff --git a/Go_Implementation/bst/checkbst.go b/Go/bst/checkbst.go similarity index 100% rename from Go_Implementation/bst/checkbst.go rename to Go/bst/checkbst.go diff --git a/Go_Implementation/bst/delete.go b/Go/bst/delete.go similarity index 100% rename from Go_Implementation/bst/delete.go rename to Go/bst/delete.go diff --git a/Go_Implementation/bst/find.go b/Go/bst/find.go similarity index 100% rename from Go_Implementation/bst/find.go rename to Go/bst/find.go diff --git a/Go_Implementation/bst/height.go b/Go/bst/height.go similarity index 100% rename from Go_Implementation/bst/height.go rename to Go/bst/height.go diff --git a/Go_Implementation/bst/insert.go b/Go/bst/insert.go similarity index 100% rename from Go_Implementation/bst/insert.go rename to Go/bst/insert.go diff --git a/Go_Implementation/bst/traversal.go b/Go/bst/traversal.go similarity index 100% rename from Go_Implementation/bst/traversal.go rename to Go/bst/traversal.go diff --git a/Go_Implementation/doublylinkedlist/doublylinkedlist.go b/Go/doublylinkedlist/doublylinkedlist.go similarity index 100% rename from Go_Implementation/doublylinkedlist/doublylinkedlist.go rename to Go/doublylinkedlist/doublylinkedlist.go diff --git a/Go_Implementation/doublylinkedlist/doublylinkedlist_test.go b/Go/doublylinkedlist/doublylinkedlist_test.go similarity index 100% rename from Go_Implementation/doublylinkedlist/doublylinkedlist_test.go rename to Go/doublylinkedlist/doublylinkedlist_test.go diff --git a/Go_Implementation/hashtable/hashtable.go b/Go/hashtable/hashtable.go similarity index 100% rename from Go_Implementation/hashtable/hashtable.go rename to Go/hashtable/hashtable.go diff --git a/Go_Implementation/hashtable/hashtable_test.go b/Go/hashtable/hashtable_test.go similarity index 100% rename from Go_Implementation/hashtable/hashtable_test.go rename to Go/hashtable/hashtable_test.go diff --git a/Go_Implementation/heap/doc.go b/Go/heap/doc.go similarity index 100% rename from Go_Implementation/heap/doc.go rename to Go/heap/doc.go diff --git a/Go_Implementation/heap/maxheap/maxheap.go b/Go/heap/maxheap/maxheap.go similarity index 100% rename from Go_Implementation/heap/maxheap/maxheap.go rename to Go/heap/maxheap/maxheap.go diff --git a/Go_Implementation/heap/maxheap/maxheap_test.go b/Go/heap/maxheap/maxheap_test.go similarity index 100% rename from Go_Implementation/heap/maxheap/maxheap_test.go rename to Go/heap/maxheap/maxheap_test.go diff --git a/Go_Implementation/heap/minheap/minheap.go b/Go/heap/minheap/minheap.go similarity index 100% rename from Go_Implementation/heap/minheap/minheap.go rename to Go/heap/minheap/minheap.go diff --git a/Go_Implementation/heap/minheap/minheap_test.go b/Go/heap/minheap/minheap_test.go similarity index 100% rename from Go_Implementation/heap/minheap/minheap_test.go rename to Go/heap/minheap/minheap_test.go diff --git a/Go_Implementation/linkedlist/linkedlist.go b/Go/linkedlist/linkedlist.go similarity index 100% rename from Go_Implementation/linkedlist/linkedlist.go rename to Go/linkedlist/linkedlist.go diff --git a/Go_Implementation/linkedlist/linkedlist_test.go b/Go/linkedlist/linkedlist_test.go similarity index 100% rename from Go_Implementation/linkedlist/linkedlist_test.go rename to Go/linkedlist/linkedlist_test.go diff --git a/Go_Implementation/queue/queue.go b/Go/queue/queue.go similarity index 100% rename from Go_Implementation/queue/queue.go rename to Go/queue/queue.go diff --git a/Go_Implementation/queue/queue_test.go b/Go/queue/queue_test.go similarity index 100% rename from Go_Implementation/queue/queue_test.go rename to Go/queue/queue_test.go diff --git a/Go_Implementation/redblacktree/doc.go b/Go/redblacktree/doc.go similarity index 100% rename from Go_Implementation/redblacktree/doc.go rename to Go/redblacktree/doc.go diff --git a/Go_Implementation/redblacktree/find.go b/Go/redblacktree/find.go similarity index 100% rename from Go_Implementation/redblacktree/find.go rename to Go/redblacktree/find.go diff --git a/Go_Implementation/redblacktree/insert.go b/Go/redblacktree/insert.go similarity index 100% rename from Go_Implementation/redblacktree/insert.go rename to Go/redblacktree/insert.go diff --git a/Go_Implementation/redblacktree/redblacktree.go b/Go/redblacktree/redblacktree.go similarity index 100% rename from Go_Implementation/redblacktree/redblacktree.go rename to Go/redblacktree/redblacktree.go diff --git a/Go_Implementation/redblacktree/redblacktree_test.go b/Go/redblacktree/redblacktree_test.go similarity index 100% rename from Go_Implementation/redblacktree/redblacktree_test.go rename to Go/redblacktree/redblacktree_test.go diff --git a/Go_Implementation/redblacktree/utils.go b/Go/redblacktree/utils.go similarity index 100% rename from Go_Implementation/redblacktree/utils.go rename to Go/redblacktree/utils.go diff --git a/Go_Implementation/search/binarysearch.go b/Go/search/binarysearch.go similarity index 100% rename from Go_Implementation/search/binarysearch.go rename to Go/search/binarysearch.go diff --git a/Go_Implementation/search/binarysearch_test.go b/Go/search/binarysearch_test.go similarity index 100% rename from Go_Implementation/search/binarysearch_test.go rename to Go/search/binarysearch_test.go diff --git a/Go_Implementation/set/set.go b/Go/set/set.go similarity index 100% rename from Go_Implementation/set/set.go rename to Go/set/set.go diff --git a/Go_Implementation/set/set_test.go b/Go/set/set_test.go similarity index 100% rename from Go_Implementation/set/set_test.go rename to Go/set/set_test.go diff --git a/Go_Implementation/shuffle/shuffle.go b/Go/shuffle/shuffle.go similarity index 100% rename from Go_Implementation/shuffle/shuffle.go rename to Go/shuffle/shuffle.go diff --git a/Go_Implementation/sort/bubble.go b/Go/sort/bubble.go similarity index 100% rename from Go_Implementation/sort/bubble.go rename to Go/sort/bubble.go diff --git a/Go_Implementation/sort/countingSort.go b/Go/sort/countingSort.go similarity index 100% rename from Go_Implementation/sort/countingSort.go rename to Go/sort/countingSort.go diff --git a/Go_Implementation/sort/gnome.go b/Go/sort/gnome.go similarity index 100% rename from Go_Implementation/sort/gnome.go rename to Go/sort/gnome.go diff --git a/Go_Implementation/sort/heap.go b/Go/sort/heap.go similarity index 100% rename from Go_Implementation/sort/heap.go rename to Go/sort/heap.go diff --git a/Go_Implementation/sort/insertion.go b/Go/sort/insertion.go similarity index 100% rename from Go_Implementation/sort/insertion.go rename to Go/sort/insertion.go diff --git a/Go_Implementation/sort/merge.go b/Go/sort/merge.go similarity index 100% rename from Go_Implementation/sort/merge.go rename to Go/sort/merge.go diff --git a/Go_Implementation/sort/oddeven.go b/Go/sort/oddeven.go similarity index 100% rename from Go_Implementation/sort/oddeven.go rename to Go/sort/oddeven.go diff --git a/Go_Implementation/sort/quick.go b/Go/sort/quick.go similarity index 100% rename from Go_Implementation/sort/quick.go rename to Go/sort/quick.go diff --git a/Go_Implementation/sort/quickselect.go b/Go/sort/quickselect.go similarity index 100% rename from Go_Implementation/sort/quickselect.go rename to Go/sort/quickselect.go diff --git a/Go_Implementation/sort/selection.go b/Go/sort/selection.go similarity index 100% rename from Go_Implementation/sort/selection.go rename to Go/sort/selection.go diff --git a/Go_Implementation/sort/shell.go b/Go/sort/shell.go similarity index 100% rename from Go_Implementation/sort/shell.go rename to Go/sort/shell.go diff --git a/Go_Implementation/sort/sort.go b/Go/sort/sort.go similarity index 100% rename from Go_Implementation/sort/sort.go rename to Go/sort/sort.go diff --git a/Go_Implementation/sort/sort_test.go b/Go/sort/sort_test.go similarity index 100% rename from Go_Implementation/sort/sort_test.go rename to Go/sort/sort_test.go diff --git a/Go_Implementation/stack/applications/applications.go b/Go/stack/applications/applications.go similarity index 100% rename from Go_Implementation/stack/applications/applications.go rename to Go/stack/applications/applications.go diff --git a/Go_Implementation/stack/applications/applications_test.go b/Go/stack/applications/applications_test.go similarity index 100% rename from Go_Implementation/stack/applications/applications_test.go rename to Go/stack/applications/applications_test.go diff --git a/Go_Implementation/stack/applications/infixevaluation.go b/Go/stack/applications/infixevaluation.go similarity index 100% rename from Go_Implementation/stack/applications/infixevaluation.go rename to Go/stack/applications/infixevaluation.go diff --git a/Go_Implementation/stack/applications/infixtopostfix.go b/Go/stack/applications/infixtopostfix.go similarity index 100% rename from Go_Implementation/stack/applications/infixtopostfix.go rename to Go/stack/applications/infixtopostfix.go diff --git a/Go_Implementation/stack/applications/infixtoprefix.go b/Go/stack/applications/infixtoprefix.go similarity index 100% rename from Go_Implementation/stack/applications/infixtoprefix.go rename to Go/stack/applications/infixtoprefix.go diff --git a/Go_Implementation/stack/applications/utils.go b/Go/stack/applications/utils.go similarity index 100% rename from Go_Implementation/stack/applications/utils.go rename to Go/stack/applications/utils.go diff --git a/Go_Implementation/stack/stack.go b/Go/stack/stack.go similarity index 100% rename from Go_Implementation/stack/stack.go rename to Go/stack/stack.go diff --git a/Go_Implementation/stack/stack_test.go b/Go/stack/stack_test.go similarity index 100% rename from Go_Implementation/stack/stack_test.go rename to Go/stack/stack_test.go diff --git a/Go_Implementation/trie/trie.go b/Go/trie/trie.go similarity index 100% rename from Go_Implementation/trie/trie.go rename to Go/trie/trie.go diff --git a/Go_Implementation/trie/trie_test.go b/Go/trie/trie_test.go similarity index 100% rename from Go_Implementation/trie/trie_test.go rename to Go/trie/trie_test.go From f9ff980bab43bbcf6d94ca5455ec78d22d9009e6 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Fri, 10 Apr 2020 23:17:31 +0530 Subject: [PATCH 056/209] add exception handling to linkedlist --- LinkedList/LinkedList/LinkedList.hpp | 33 ++++++++++-- LinkedList/LinkedList/Makefile | 2 +- LinkedList/LinkedList/test_LinkedList.cpp | 65 ++++++++++++----------- 3 files changed, 65 insertions(+), 35 deletions(-) diff --git a/LinkedList/LinkedList/LinkedList.hpp b/LinkedList/LinkedList/LinkedList.hpp index 77039df..57fb7ec 100644 --- a/LinkedList/LinkedList/LinkedList.hpp +++ b/LinkedList/LinkedList/LinkedList.hpp @@ -2,6 +2,23 @@ #define LINKEDLIST_H namespace LinkedList { + + /** + * EmptyList exception is raised when you are trying to access + * element from empty linked list. + */ + class EmptyList : public std::exception { + const char* what() const throw() { + return "linked list is empty"; + } + }; + + class InvalidPosition : public std::exception { + const char* what() const throw() { + return "invalid position"; + } + }; + template struct Node { T data; @@ -134,10 +151,13 @@ namespace LinkedList { /** * Delete head node from linked list * @return removedData value of deleted node + * @throws LinkedList::EmptyList if linked list is empty. + * (can't delete from empty list) */ template T LinkedList::deleteHead() { - if (head == nullptr) return -1; + if (head == nullptr) + throw EmptyList(); Node* temp = head; T removedData = temp->data; head = head->next; @@ -148,10 +168,13 @@ namespace LinkedList { /** * Delete end node from linked list * @return removedData value of deleted node + * @throws LinkedList::EmptyList if linked list is empty. + * (can't delete from empty list) */ template T LinkedList::deleteEnd() { - if (head == nullptr) return -1; + if (head == nullptr) + throw EmptyList(); Node* current = head; if (head->next == nullptr) head = nullptr; else { @@ -172,12 +195,13 @@ namespace LinkedList { * @param position position at which node needs to be deleted. * Position is 1-based. * @return removedData value of deleted node + * @throw LinkedList::InvalidPosition if position is invalid */ template T LinkedList::deleteAt(int position) { int ll_length = getLength(); if (position < 1 || position > ll_length) - return -1; + throw InvalidPosition(); if (position == 1) return deleteHead(); @@ -228,12 +252,13 @@ namespace LinkedList { * Get node value present at given position in the linked list * @param position position at which node value is needed. Position is 1-based. * @return node value at position + * @throw LinkedList::InvalidPosition if position is invalid */ template T LinkedList::dataAt(int position) { int ll_length = getLength(); if (position < 1 || position > ll_length) - return -1; + throw InvalidPosition(); Node* current = head; for (int i = 1; i < position; i++) diff --git a/LinkedList/LinkedList/Makefile b/LinkedList/LinkedList/Makefile index 0a2296d..678bbae 100644 --- a/LinkedList/LinkedList/Makefile +++ b/LinkedList/LinkedList/Makefile @@ -7,4 +7,4 @@ all: $(CC) test_LinkedList.cpp $(CCFLAGS) -I$(GTEST_INCLUDE_PATH) -L$(GTEST_LIBRARY_PATH) clean: - rm ./a.out *.o + rm ./a.out diff --git a/LinkedList/LinkedList/test_LinkedList.cpp b/LinkedList/LinkedList/test_LinkedList.cpp index e728a1e..ccd1596 100755 --- a/LinkedList/LinkedList/test_LinkedList.cpp +++ b/LinkedList/LinkedList/test_LinkedList.cpp @@ -178,7 +178,7 @@ TEST_F(LinkedListDataInit, GetLengthRecursiveTest) { // test deleteHead method on empty linked list TEST(LinkedListEmptyInit, DeleteHeadTest) { LinkedList::LinkedList ll; - ASSERT_EQ(-1, ll.deleteHead()); + ASSERT_THROW(ll.deleteHead(), LinkedList::EmptyList); // after removing every node from linked list, // head should point to nullptr @@ -189,7 +189,7 @@ TEST(LinkedListEmptyInit, DeleteHeadTest) { // test deleteHead method on single linked list TEST_F(LinkedListSingleInit, DeleteHeadTest) { ASSERT_EQ(5, ll.deleteHead()); - ASSERT_EQ(-1, ll.deleteHead()); + ASSERT_THROW(ll.deleteHead(), LinkedList::EmptyList); // after removing every node from linked list, // head should point to nullptr ASSERT_EQ(nullptr, ll.getHead()); @@ -221,7 +221,7 @@ TEST(LinkedListEmptyInit, DeleteEndTest) { ASSERT_EQ(9, ll.deleteEnd()); for (int i = 0; i < 5; i++) - ASSERT_EQ(-1, ll.deleteEnd()); + ASSERT_THROW(ll.deleteEnd(), LinkedList::EmptyList); // after removing every node from linked list, // head should point to nullptr @@ -232,7 +232,7 @@ TEST(LinkedListEmptyInit, DeleteEndTest) { // test deleteEnd method on single linked list TEST_F(LinkedListSingleInit, DeleteEndTest) { ASSERT_EQ(5, ll.deleteEnd()); - ASSERT_EQ(-1, ll.deleteEnd()); + ASSERT_THROW(ll.deleteEnd(), LinkedList::EmptyList); // after removing every node from linked list, // head should point to nullptr ASSERT_EQ(nullptr, ll.getHead()); @@ -256,9 +256,9 @@ TEST_F(LinkedListDataInit, DeleteEndTest) { // test deleteAt method on empty linked list TEST(LinkedListEmptyInit, DeleteAtTest) { LinkedList::LinkedList ll; - ASSERT_EQ(-1, ll.deleteAt(3)); - ASSERT_EQ(-1, ll.deleteAt(0)); - ASSERT_EQ(-1, ll.deleteAt(-5)); + ASSERT_THROW(ll.deleteAt(3), LinkedList::InvalidPosition); + ASSERT_THROW(ll.deleteAt(0), LinkedList::InvalidPosition); + ASSERT_THROW(ll.deleteAt(-5), LinkedList::InvalidPosition); // after removing every node from linked list, // head should point to nullptr @@ -268,11 +268,11 @@ TEST(LinkedListEmptyInit, DeleteAtTest) { // test deleteAt method on single linked list TEST_F(LinkedListSingleInit, DeleteAtTest) { - ASSERT_EQ(-1, ll.deleteAt(2)); - ASSERT_EQ(-1, ll.deleteAt(-1)); - ASSERT_EQ(-1, ll.deleteAt(0)); + ASSERT_THROW(ll.deleteAt(2), LinkedList::InvalidPosition); + ASSERT_THROW(ll.deleteAt(-1), LinkedList::InvalidPosition); + ASSERT_THROW(ll.deleteAt(0), LinkedList::InvalidPosition); ASSERT_EQ(5, ll.deleteAt(1)); - ASSERT_EQ(-1, ll.deleteAt(1)); + ASSERT_THROW(ll.deleteAt(1), LinkedList::InvalidPosition); // after removing every node from linked list, // head should point to nullptr ASSERT_EQ(nullptr, ll.getHead()); @@ -283,9 +283,9 @@ TEST_F(LinkedListSingleInit, DeleteAtTest) { TEST_F(LinkedListDataInit, DeleteAtTest) { ASSERT_EQ(3, ll.deleteAt(3)); ASSERT_EQ(4, ll.deleteAt(3)); - ASSERT_EQ(-1, ll.deleteAt(0)); - ASSERT_EQ(-1, ll.deleteAt(5)); - ASSERT_EQ(-1, ll.deleteAt(4)); + ASSERT_THROW(ll.deleteAt(0), LinkedList::InvalidPosition); + ASSERT_THROW(ll.deleteAt(5), LinkedList::InvalidPosition); + ASSERT_THROW(ll.deleteAt(4), LinkedList::InvalidPosition); ASSERT_EQ(5, ll.deleteAt(3)); ASSERT_EQ(1, ll.deleteAt(1)); ASSERT_EQ(2, ll.deleteAt(1)); @@ -299,9 +299,10 @@ TEST_F(LinkedListDataInit, DeleteAtTest) { // test deleteKey method on empty linked list TEST(LinkedListEmptyInit, DeleteKeyTest) { LinkedList::LinkedList ll; - ASSERT_EQ(-1, ll.deleteKey(3)); - ASSERT_EQ(-1, ll.deleteKey(0)); - ASSERT_EQ(-1, ll.deleteKey(-5)); + ASSERT_THROW(ll.deleteKey(3), LinkedList::InvalidPosition); + ASSERT_THROW(ll.deleteKey(0), LinkedList::InvalidPosition); + ASSERT_THROW(ll.deleteKey(-5), LinkedList::InvalidPosition); + // after removing every node from linked list, // head should point to nullptr @@ -311,10 +312,10 @@ TEST(LinkedListEmptyInit, DeleteKeyTest) { // test deleteKey method on single Linked list TEST_F(LinkedListSingleInit, DeleteKeyTest) { - ASSERT_EQ(-1, ll.deleteKey(3)); - ASSERT_EQ(-1, ll.deleteKey(0)); + ASSERT_THROW(ll.deleteKey(3), LinkedList::InvalidPosition); + ASSERT_THROW(ll.deleteKey(0), LinkedList::InvalidPosition); ASSERT_EQ(5, ll.deleteKey(5)); - ASSERT_EQ(-1, ll.deleteKey(5)); + ASSERT_THROW(ll.deleteKey(5), LinkedList::InvalidPosition); // after removing every node from linked list, // head should point to nullptr @@ -324,8 +325,9 @@ TEST_F(LinkedListSingleInit, DeleteKeyTest) { // test deleteKey method on filled Linked list TEST_F(LinkedListDataInit, DeleteKeyTest) { - ASSERT_EQ(-1, ll.deleteKey(6)); - ASSERT_EQ(-1, ll.deleteKey(0)); + ASSERT_THROW(ll.deleteKey(6), LinkedList::InvalidPosition); + ASSERT_THROW(ll.deleteKey(0), LinkedList::InvalidPosition); + for (int i = 1; i < 6; i++) ASSERT_EQ(i, ll.deleteKey(i)); @@ -374,6 +376,7 @@ TEST(LinkedListEmptyInit, IndexOfTest) { ASSERT_EQ(-1, ll.indexOf(0)); ASSERT_EQ(-1, ll.indexOf(-1)); + // after removing every node from linked list, // head should point to nullptr ASSERT_EQ(nullptr, ll.getHead()); @@ -401,17 +404,18 @@ TEST_F(LinkedListDataInit, IndexOfTest) { // test dataAt method on empty linked list TEST(LinkedListEmptyInit, DataAtTest) { LinkedList::LinkedList ll; - ASSERT_EQ(-1, ll.dataAt(0)); - ASSERT_EQ(-1, ll.dataAt(-1)); - ASSERT_EQ(-1, ll.dataAt(1)); + ASSERT_THROW(ll.dataAt(0), LinkedList::InvalidPosition); + ASSERT_THROW(ll.dataAt(-1), LinkedList::InvalidPosition); + ASSERT_THROW(ll.dataAt(1), LinkedList::InvalidPosition); + } // test dataAt method on empty linked list TEST_F(LinkedListSingleInit, DataAtTest) { - ASSERT_EQ(-1, ll.dataAt(-2)); - ASSERT_EQ(-1, ll.dataAt(0)); + ASSERT_THROW(ll.dataAt(-2), LinkedList::InvalidPosition); + ASSERT_THROW(ll.dataAt(0), LinkedList::InvalidPosition); ASSERT_EQ(5, ll.dataAt(1)); - ASSERT_EQ(-1, ll.dataAt(2)); + ASSERT_THROW(ll.dataAt(2), LinkedList::InvalidPosition); ASSERT_EQ(1, ll.getLength()); } @@ -419,8 +423,9 @@ TEST_F(LinkedListSingleInit, DataAtTest) { TEST_F(LinkedListDataInit, DataAtTest) { for (int i = 1; i < 6; i++) ASSERT_EQ(i, ll.dataAt(i)); - ASSERT_EQ(-1, ll.dataAt(0)); - ASSERT_EQ(-1, ll.dataAt(-1)); + ASSERT_THROW(ll.dataAt(0), LinkedList::InvalidPosition); + ASSERT_THROW(ll.dataAt(-1), LinkedList::InvalidPosition); + } /* Reverse Test */ From 9f2f24dc19a9223ce0a97ed13a5a32c8a258bb91 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sat, 11 Apr 2020 22:17:49 +0530 Subject: [PATCH 057/209] update linked list count frequency code --- LinkedList/countFrequency.cpp | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/LinkedList/countFrequency.cpp b/LinkedList/countFrequency.cpp index 52a20af..3017460 100644 --- a/LinkedList/countFrequency.cpp +++ b/LinkedList/countFrequency.cpp @@ -6,28 +6,28 @@ * * url: https://www.geeksforgeeks.org/write-a-function-that-counts-the-\ * number-of-times-a-given-int-occurs-in-a-linked-list/ - * cmd: g++ countFrequency.cpp LinkedList/LinkedList.cpp -std=c++14 + * cmd: g++ -Wall -std=c++14 countFrequency.cpp */ #include #include "LinkedList/LinkedList.hpp" -int countFrequency(LinkedList* ll, int key); -int countFrequencyRecursion(Node* node, int key); +int countFrequency(LinkedList::LinkedList* ll, char key); +int countFrequencyRecursion(LinkedList::Node* node, char key); int main() { - LinkedList ll; - ll.insertEnd(1); - ll.insertEnd(2); - ll.insertEnd(1); - ll.insertEnd(2); - ll.insertEnd(1); - ll.insertEnd(3); - ll.insertEnd(1); + LinkedList::LinkedList ll; + ll.insertEnd('a'); + ll.insertEnd('b'); + ll.insertEnd('a'); + ll.insertEnd('b'); + ll.insertEnd('a'); + ll.insertEnd('c'); + ll.insertEnd('a'); - std::cout << countFrequency(&ll, 1) << "\n"; - std::cout << countFrequencyRecursion(ll.getHead(), 1) << "\n"; + std::cout << countFrequency(&ll, 'a') << "\n"; + std::cout << countFrequencyRecursion(ll.getHead(), 'a') << "\n"; return 0; } @@ -38,9 +38,9 @@ int main() * @param key key integer who frequency we need * @return key count frequency */ -int countFrequency(LinkedList* ll, int key) +int countFrequency(LinkedList::LinkedList* ll, char key) { - Node* temp = ll->getHead(); + LinkedList::Node* temp = ll->getHead(); int count = 0; while (temp) { if (temp->data == key) @@ -57,7 +57,7 @@ int countFrequency(LinkedList* ll, int key) * @param key key integer who frequency we need * @return key count frequency */ -int countFrequencyRecursion(Node* node, int key) +int countFrequencyRecursion(LinkedList::Node* node, char key) { if (node == nullptr) return 0; From 5f1b3e0e2ce0e82bfcf19ff191dd7b1e7f540362 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sat, 11 Apr 2020 22:18:04 +0530 Subject: [PATCH 058/209] update linked list detect loop code --- LinkedList/detectLoop.cpp | 43 ++++++++++++++++++++++----------------- 1 file changed, 24 insertions(+), 19 deletions(-) diff --git a/LinkedList/detectLoop.cpp b/LinkedList/detectLoop.cpp index bfc9c2d..b1b8081 100644 --- a/LinkedList/detectLoop.cpp +++ b/LinkedList/detectLoop.cpp @@ -6,34 +6,39 @@ * | v * 5 <- 4 * url: https://www.geeksforgeeks.org/detect-loop-in-a-linked-list/ - * cmd: g++ detectLoop.cpp LinkedList/LinkedList.cpp -std=c++14 + * cmd: g++ -Wall -std=c++14 detectLoop.cpp */ #include #include "LinkedList/LinkedList.hpp" -bool detectLoop(LinkedList* ll); +bool detectLoop(LinkedList::LinkedList* ll); int main() { - LinkedList ll; - ll.insertEnd(1); - ll.insertEnd(2); - ll.insertEnd(3); - ll.insertEnd(4); - ll.insertEnd(5); + LinkedList::LinkedList ll; + ll.insertEnd(1.1f); + ll.insertEnd(2.2f); + ll.insertEnd(3.3f); + ll.insertEnd(4.4f); + ll.insertEnd(5.5f); // creating loop - Node* head = ll.getHead(); + LinkedList::Node* head = ll.getHead(); head->next->next->next->next->next = head->next; - std::cout << detectLoop(&ll) << "\n"; + if (detectLoop(&ll)) + std::cout << "cycle detected\n"; + else std::cout << "cycle not detected\n"; - LinkedList ll1; - ll1.insertEnd(1); - ll1.insertEnd(2); - ll1.insertEnd(3); - std::cout << detectLoop(&ll1) << "\n"; + LinkedList::LinkedList ll1; + ll1.insertEnd(1.2f); + ll1.insertEnd(2.3f); + ll1.insertEnd(3.4f); + + if (detectLoop(&ll1)) + std::cout << "cycle detected\n"; + else std::cout << "cycle not detected\n"; return 0; } @@ -47,11 +52,11 @@ int main() * @param ll pointer to linked list * @return true if loop is present, else false. */ -bool detectLoop(LinkedList* ll) +bool detectLoop(LinkedList::LinkedList* ll) { - Node* head = ll->getHead(); - Node* slowPtr = head; - Node* fastPtr = head; + LinkedList::Node* head = ll->getHead(); + LinkedList::Node* slowPtr = head; + LinkedList::Node* fastPtr = head; while (fastPtr != nullptr && fastPtr->next != nullptr) { fastPtr = fastPtr->next->next; From 7dfefe404c1582a9f50a7ee6b90912cc35ce930a Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sun, 12 Apr 2020 18:44:54 +0530 Subject: [PATCH 059/209] update linked list find middle code --- LinkedList/findMiddle.cpp | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/LinkedList/findMiddle.cpp b/LinkedList/findMiddle.cpp index 00cf66e..7ed7537 100644 --- a/LinkedList/findMiddle.cpp +++ b/LinkedList/findMiddle.cpp @@ -9,28 +9,28 @@ * * URL: https://www.geeksforgeeks.org/write-a-c-function-to-print-the-\ * middle-of-the-linked-list/ - * cmd: g++ findMiddle.cpp LinkedList/LinkedList.cpp -Wall -std=c++14 + * cmd: g++ -Wall -std=c++14 findMiddle.cpp */ #include #include "LinkedList/LinkedList.hpp" -int findMiddle_UsingLength(LinkedList* ll); -int findMiddle_UsingTwoPointer(LinkedList* ll); -int findMiddle_UsingOddIncrement(LinkedList* ll); +int findMiddle_UsingLength(LinkedList::LinkedList* ll); +int findMiddle_UsingTwoPointer(LinkedList::LinkedList* ll); +int findMiddle_UsingOddIncrement(LinkedList::LinkedList* ll); int main() { - LinkedList empty_ll; + LinkedList::LinkedList empty_ll; - LinkedList odd_ll; + LinkedList::LinkedList odd_ll; odd_ll.insertEnd(1); odd_ll.insertEnd(2); odd_ll.insertEnd(3); odd_ll.insertEnd(4); odd_ll.insertEnd(5); - LinkedList even_ll; + LinkedList::LinkedList even_ll; even_ll.insertEnd(1); even_ll.insertEnd(2); even_ll.insertEnd(3); @@ -62,9 +62,9 @@ int main() * @param ll linked list object pointer. * @return middle node value */ -int findMiddle_UsingLength(LinkedList* ll) +int findMiddle_UsingLength(LinkedList::LinkedList* ll) { - Node* node = ll->getHead(); + LinkedList::Node* node = ll->getHead(); int len = ll->getLength(); int middle = len / 2; @@ -84,11 +84,11 @@ int findMiddle_UsingLength(LinkedList* ll) * @param ll linked list object pointer. * @return middle node value */ -int findMiddle_UsingTwoPointer(LinkedList* ll) +int findMiddle_UsingTwoPointer(LinkedList::LinkedList* ll) { - Node* head = ll->getHead(); - Node* fast = head; - Node* slow = head; + LinkedList::Node* head = ll->getHead(); + LinkedList::Node* fast = head; + LinkedList::Node* slow = head; if (slow == nullptr) return -1; @@ -108,13 +108,13 @@ int findMiddle_UsingTwoPointer(LinkedList* ll) * @param ll linked list object pointer. * @return middle node value */ -int findMiddle_UsingOddIncrement(LinkedList* ll) +int findMiddle_UsingOddIncrement(LinkedList::LinkedList* ll) { - Node* node = ll->getHead(); + LinkedList::Node* node = ll->getHead(); if (node == nullptr) return -1; - Node* mid = node; + LinkedList::Node* mid = node; int counter = 0; while(node) { if (counter % 2 != 0) From ecb899272837d3e504f88e2a25e24119a6cddf57 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sun, 12 Apr 2020 18:45:12 +0530 Subject: [PATCH 060/209] update linked list find nth node from end code --- LinkedList/getNthNodeFromEnd.cpp | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/LinkedList/getNthNodeFromEnd.cpp b/LinkedList/getNthNodeFromEnd.cpp index 0b8ef21..9f564bb 100644 --- a/LinkedList/getNthNodeFromEnd.cpp +++ b/LinkedList/getNthNodeFromEnd.cpp @@ -6,18 +6,18 @@ * A -> B -> C -> D -> NULL * * URL: https://www.geeksforgeeks.org/nth-node-from-the-end-of-a-linked-list/ - * cmd: g++ getNthNodeFromEnd.cpp LinkedList/LinkedList.cpp -Wall -std=c++14 + * cmd: g++ -Wall -std=c++14 getNthNodeFromEnd.cpp */ #include #include "LinkedList/LinkedList.hpp" -int getNthFromEnd_UsingLengthMethod(LinkedList* ll, int position); -int getNthFromEnd_UsingTwoPointerMethod(LinkedList* ll, int position); +int getNthFromEnd_UsingLengthMethod(LinkedList::LinkedList* ll, int position); +int getNthFromEnd_UsingTwoPointerMethod(LinkedList::LinkedList* ll, int position); int main() { - LinkedList ll; + LinkedList::LinkedList ll; ll.insertEnd(20); ll.insertEnd(4); ll.insertEnd(45); @@ -53,14 +53,14 @@ int main() * @param position position from end. Position is 1-based. * @return nth node's value from end. */ -int getNthFromEnd_UsingLengthMethod(LinkedList* ll, int position) +int getNthFromEnd_UsingLengthMethod(LinkedList::LinkedList* ll, int position) { int length = ll->getLength(); if (position >= length + 1 || position <= 0) return -1; int positionFromStart = length - position; - Node* node = ll->getHead(); + LinkedList::Node* node = ll->getHead(); for (int i = 0; i < positionFromStart; i++) node = node->next; return node->data; @@ -79,14 +79,14 @@ int getNthFromEnd_UsingLengthMethod(LinkedList* ll, int position) * @param position position from end. Position is 1-based. * @return nth node's value from end. */ -int getNthFromEnd_UsingTwoPointerMethod(LinkedList* ll, int position) +int getNthFromEnd_UsingTwoPointerMethod(LinkedList::LinkedList* ll, int position) { int length = ll->getLength(); - Node* head = ll->getHead(); + LinkedList::Node* head = ll->getHead(); if (position >= length + 1 || position <= 0) return -1; - Node* mainptr = head; - Node* refptr = head; + LinkedList::Node* mainptr = head; + LinkedList::Node* refptr = head; for (int i = 1; i < position; i++) { refptr = refptr->next; } From 7013ec72c16a158e36ed77217a9ffd9a60552e8c Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sun, 12 Apr 2020 18:45:36 +0530 Subject: [PATCH 061/209] update linked list length of loop --- LinkedList/lengthOfLoop.cpp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/LinkedList/lengthOfLoop.cpp b/LinkedList/lengthOfLoop.cpp index ebb611d..dabf9e2 100644 --- a/LinkedList/lengthOfLoop.cpp +++ b/LinkedList/lengthOfLoop.cpp @@ -8,17 +8,17 @@ * | v * 5 <- 4 * url: https://www.geeksforgeeks.org/find-length-of-loop-in-linked-list/ - * cmd: g++ lengthOfLoop.cpp LinkedList/LinkedList.cpp -std=c++14 + * cmd: g++ -Wall -std=c++14 lengthOfLoop.cpp */ #include #include "LinkedList/LinkedList.hpp" -int detectAndCountLoop(Node* head); +int detectAndCountLoop(LinkedList::Node* head); int main() { - LinkedList ll; + LinkedList::LinkedList ll; ll.insertEnd(1); ll.insertEnd(2); ll.insertEnd(3); @@ -26,12 +26,12 @@ int main() ll.insertEnd(5); // creating loop - Node* head = ll.getHead(); + LinkedList::Node* head = ll.getHead(); head->next->next->next->next->next = head->next; std::cout << detectAndCountLoop(head) << "\n"; - LinkedList ll1; + LinkedList::LinkedList ll1; ll1.insertEnd(1); ll1.insertEnd(2); ll1.insertEnd(3); @@ -54,10 +54,10 @@ int main() * @param head node pointer linked list's head * @return length of loop */ -int detectAndCountLoop(Node* head) +int detectAndCountLoop(LinkedList::Node* head) { - Node* slowPtr = head; - Node* fastPtr = head; + LinkedList::Node* slowPtr = head; + LinkedList::Node* fastPtr = head; while (fastPtr != nullptr && fastPtr->next != nullptr) { fastPtr = fastPtr->next->next; slowPtr = slowPtr->next; @@ -69,7 +69,7 @@ int detectAndCountLoop(Node* head) return 0; int counter = 1; - Node* temp = slowPtr->next; + LinkedList::Node* temp = slowPtr->next; while(temp != slowPtr) { temp = temp->next; counter++; From d4709381a3db0e5951cc126a1b8ced174de4438d Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Tue, 14 Apr 2020 21:42:20 +0530 Subject: [PATCH 062/209] queue code formatting --- Queue/Queue/Makefile | 2 +- Queue/Queue/Queue.hpp | 315 ++++++++++++++++++++++-------------------- 2 files changed, 169 insertions(+), 148 deletions(-) diff --git a/Queue/Queue/Makefile b/Queue/Queue/Makefile index 327da6c..5ee6250 100644 --- a/Queue/Queue/Makefile +++ b/Queue/Queue/Makefile @@ -7,4 +7,4 @@ all: $(CC) test_Queue.cpp $(CCFLAGS) -I$(GTEST_INCLUDE_PATH) -L$(GTEST_LIBRARY_PATH) clean: - rm ./a.out *.o + rm ./a.out diff --git a/Queue/Queue/Queue.hpp b/Queue/Queue/Queue.hpp index 1a0d3b7..d27d26d 100644 --- a/Queue/Queue/Queue.hpp +++ b/Queue/Queue/Queue.hpp @@ -14,164 +14,185 @@ #define DEFAULT_CAPACITY 10 -namespace Queue { - - /** - * OverflowException is raised when you are trying to insert - * element in completely filled queue. - */ - class OverflowException : public std::exception { - const char* what() const throw() { - return "queue overflow exception"; - } - }; - - /** - * UnderflowException is raised when you are trying to access - * element from empty queue. - */ - class UnderflowException : public std::exception { - const char* what() const throw() { - return "queue underflow exception"; - } - }; - - template - class Queue { - private: - T* items; - int front; - int rear; - int capacity; - int item_count; - - public: - Queue(int cap = DEFAULT_CAPACITY); - ~Queue(); - - int enqueue(T item); - T dequeue(); - T peek(); - - int size(); - bool isEmpty(); - bool isFull(); - - void display(); - }; - - /** - * Constructor - * Create new Queue items array in heap memory - * @param cap maximum capacity of Queue - */ - template - Queue::Queue(int cap) { - items = new int[cap]; - capacity = cap; - front = 0; - rear = -1; - item_count = 0; - } +namespace Queue +{ - /** - * Destructor - * delete queue items array from heap memory - */ - template - Queue::~Queue() { - delete items; +/** + * OverflowException is raised when you are trying to insert + * element in completely filled queue. + */ +class OverflowException : public std::exception +{ + const char *what() const throw() + { + return "queue overflow exception"; } +}; - /** - * enqueue(push) an element to queue. - * @param item to be enqueued in queue - * @return status code 0, if operation is successful. - * @throws Queue::OverflowException if queue is full - * (item not enqueued). - */ - template - int Queue::enqueue(T element) { - if (isFull()) { - throw OverflowException(); - } - rear = (rear + 1) % capacity; - items[rear] = element; - item_count++; - return 0; +/** + * UnderflowException is raised when you are trying to access + * element from empty queue. + */ +class UnderflowException : public std::exception +{ + const char *what() const throw() + { + return "queue underflow exception"; } +}; - /** - * dequeue(pop) an element from queue. - * @return dequeued value if operation is successful. - * @throws Queue::UnderflowException if queue is empty - * (nothing to pop). - */ - template - T Queue::dequeue() { - if (isEmpty()) - throw UnderflowException(); - int removedvalue = items[front]; - front = (front + 1) % capacity; - item_count--; - return removedvalue; - } +template +class Queue +{ +private: + T *items; + int front; + int rear; + int capacity; + int item_count; - /** - * Peek top element in queue without removing it. - * @return top item without removing it. - * @throws Queue::UnderflowException exception if queue is empty - * (nothing to peek). - */ - template - T Queue::peek() { - if (isEmpty()) - throw UnderflowException(); - return items[front]; - } +public: + Queue(int cap = DEFAULT_CAPACITY); + ~Queue(); - /** - * Get current size of queue - * @return total number of items currently present in queue - */ - template - int Queue::size() { - return item_count; - } + int enqueue(T item); + T dequeue(); + T peek(); - /** - * Checks if the queue is full - * @return true if queue is full, else false - */ - template - bool Queue::isFull() { - return size() == capacity; - } + int size(); + bool isEmpty(); + bool isFull(); - /** - * Checks if the queue is empty - * @return true if queue is empty, else false - */ - template - bool Queue::isEmpty() { - return size() == 0; - } + void display(); +}; + +/** + * Constructor + * Create new Queue items array in heap memory + * @param cap maximum capacity of Queue +*/ +template +Queue::Queue(int cap) +{ + items = new int[cap]; + capacity = cap; + front = 0; + rear = -1; + item_count = 0; +} + +/** + * Destructor + * delete queue items array from heap memory +*/ +template +Queue::~Queue() +{ + delete items; +} + +/** + * enqueue(push) an element to queue. + * @param item to be enqueued in queue + * @return status code 0, if operation is successful. + * @throw Queue::OverflowException if queue is full + * (item not enqueued). +*/ +template +int Queue::enqueue(T element) +{ + if (isFull()) + throw OverflowException(); + + rear = (rear + 1) % capacity; + items[rear] = element; + item_count++; + return 0; +} - /** - * Display all elements in the queue - */ - template - void Queue::display() { - std::cout << "Queue: "; - if (!isEmpty()) { - int temp = front; - while (temp != rear) { - std::cout << items[temp] << " "; - temp = (temp + 1) % capacity; - } - std::cout << items[temp] << "\n"; - } else std::cout << "Empty\n"; +/** + * dequeue(pop) an element from queue. + * @return dequeued value if operation is successful. + * @throw Queue::UnderflowException if queue is empty + * (nothing to pop). +*/ +template +T Queue::dequeue() +{ + if (isEmpty()) + throw UnderflowException(); + + int removedvalue = items[front]; + front = (front + 1) % capacity; + item_count--; + return removedvalue; +} + +/** + * Peek top element in queue without removing it. + * @return top item without removing it. + * @throw Queue::UnderflowException exception if queue is empty + * (nothing to peek). +*/ +template +T Queue::peek() +{ + if (isEmpty()) + throw UnderflowException(); + + return items[front]; +} + +/** + * Get current size of queue + * @return total number of items currently present in queue +*/ +template +int Queue::size() +{ + return item_count; +} + +/** + * Checks if the queue is full + * @return true if queue is full, else false +*/ +template +bool Queue::isFull() +{ + return size() == capacity; +} + +/** + * Checks if the queue is empty + * @return true if queue is empty, else false +*/ +template +bool Queue::isEmpty() +{ + return size() == 0; +} + +/** + * Display all elements in the queue +*/ +template +void Queue::display() +{ + std::cout << "Queue: "; + if (!isEmpty()) + { + int temp = front; + while (temp != rear) + { + std::cout << items[temp] << " "; + temp = (temp + 1) % capacity; + } + std::cout << items[temp] << "\n"; } + else + std::cout << "Empty\n"; } +} // namespace Queue #endif From 4934c4496e6d7f0e1440ac113ab4c524ca20502f Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Tue, 14 Apr 2020 21:42:55 +0530 Subject: [PATCH 063/209] add reverse a queue iterative and recursive approach --- Queue/ReverseQueue.cpp | 63 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Queue/ReverseQueue.cpp diff --git a/Queue/ReverseQueue.cpp b/Queue/ReverseQueue.cpp new file mode 100644 index 0000000..abda0a4 --- /dev/null +++ b/Queue/ReverseQueue.cpp @@ -0,0 +1,63 @@ +/** + * Reverse a Queue + * Input: Q = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] + * Output: Q = [100, 90, 80, 70, 60, 50, 40, 30, 20, 10] + * + * Input: [1, 2, 3, 4, 5] + * Output: [5, 4, 3, 2, 1] +*/ + +#include +#include "../Stack/Stack/Stack.hpp" +#include "Queue/Queue.hpp" + +/** + * Reversing a queue using stack. + * @param queue reference to queue object +*/ +void ReverseQueue(Queue::Queue &queue) +{ + Stack::Stack stack; + while (!queue.isEmpty()) + stack.push(queue.dequeue()); + while (!stack.isEmpty()) + queue.enqueue(stack.pop()); +} + +/** + * Reversing a queue using recursive approach + * @param queue reference to queue object +*/ +void ReverseQueueRecursive(Queue::Queue &queue) +{ + if (queue.isEmpty()) + return; + int data = queue.dequeue(); + ReverseQueueRecursive(queue); + queue.enqueue(data); +} + +/* Main Driver Function */ +int main() +{ + Queue::Queue queue; + queue.enqueue(1); + queue.enqueue(2); + queue.enqueue(3); + queue.enqueue(4); + queue.enqueue(5); + + std::cout << "Original "; + queue.display(); + + ReverseQueue(queue); + + std::cout << "Reversed "; + queue.display(); + + ReverseQueueRecursive(queue); + + std::cout << "Recursive "; + queue.display(); + return 0; +} \ No newline at end of file From feebe1fcee764ad0a65b4b4fd25b2cb44c71cfe0 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Wed, 15 Apr 2020 18:38:56 +0530 Subject: [PATCH 064/209] update stack fix typo --- Stack/Stack/Makefile | 2 +- Stack/Stack/Stack.hpp | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Stack/Stack/Makefile b/Stack/Stack/Makefile index 2740e11..8dd3307 100644 --- a/Stack/Stack/Makefile +++ b/Stack/Stack/Makefile @@ -7,4 +7,4 @@ all: $(CC) test_Stack.cpp $(CCFLAGS) -I$(GTEST_INCLUDE_PATH) -L$(GTEST_LIBRARY_PATH) clean: - rm ./a.out *.o + rm ./a.out diff --git a/Stack/Stack/Stack.hpp b/Stack/Stack/Stack.hpp index 4d8b8e1..a2919c3 100644 --- a/Stack/Stack/Stack.hpp +++ b/Stack/Stack/Stack.hpp @@ -78,7 +78,7 @@ namespace Stack { * insert(push) an element to stack. * @param item to be inserted in stack * @return status code 0, if operation is successful. - * @throws Stack::OverflowException if stack is full + * @throw Stack::OverflowException if stack is full * (item not inserted). */ template @@ -92,7 +92,7 @@ namespace Stack { /** * remove(pop) an integer element from stack. * @return popped value if operation is successful. - * @throws Stack::UnderflowException if stack is empty + * @throw Stack::UnderflowException if stack is empty * (nothing to pop). */ template @@ -106,7 +106,7 @@ namespace Stack { /** * Peek top element in stack without removing it. * @return top item without removing it. - * @throws UnderflowException exception if stack is empty + * @throw UnderflowException exception if stack is empty * (nothing to peek). */ template From 22ec7666a62ee357eaaac8a9bd24ccac59394274 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Wed, 15 Apr 2020 18:40:31 +0530 Subject: [PATCH 065/209] add insertion sort --- Sort/InsertionSort.cpp | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Sort/InsertionSort.cpp diff --git a/Sort/InsertionSort.cpp b/Sort/InsertionSort.cpp new file mode 100644 index 0000000..31de23a --- /dev/null +++ b/Sort/InsertionSort.cpp @@ -0,0 +1,42 @@ +/* + * Sorting Algorithms + * Insertion Sort (C++ implementation) + * + * Insertion sort is based on the idea that one element from the input + * elements is consumed in each iteration to find its correct position + * i.e, the position to which it belongs in a sorted array. + */ + +#include + +/** + * Insertion Sort Template Function + * @param arr actual array to sort + * @param len size of array + */ +template +void InsertionSort(T arr[], int len) { + for (int i = 0; i < len; i++) { + int index = i; + int value = arr[i]; + while (index > 0 && arr[index-1] > value) { + arr[index] = arr[index-1]; + index--; + } + arr[index] = value; + } +} + +/* Main Driver Function */ +int main() { + int arr[] = {229, 79, 46, 12, 58, 31, 34, 67, 89, 12, 67, 2}; + int arr_size = sizeof(arr) / sizeof(arr[0]); + + InsertionSort(arr, arr_size); + + for (int a: arr) + std::cout << a << " "; + std::cout << "\n"; + + return 0; +} \ No newline at end of file From bd208f7153e3d5c9592261fce9b9152d983b2589 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Thu, 16 Apr 2020 20:25:02 +0530 Subject: [PATCH 066/209] add binary search recursive and iterative approach --- Search/BinarySearch.h | 67 ++++++++++++++++++++++++++++++++++++ Search/Makefile | 10 ++++++ Search/test_BinarySearch.cpp | 56 ++++++++++++++++++++++++++++++ 3 files changed, 133 insertions(+) create mode 100644 Search/BinarySearch.h create mode 100644 Search/Makefile create mode 100644 Search/test_BinarySearch.cpp diff --git a/Search/BinarySearch.h b/Search/BinarySearch.h new file mode 100644 index 0000000..e4ab327 --- /dev/null +++ b/Search/BinarySearch.h @@ -0,0 +1,67 @@ +/** + * Search Algorithm + * Binary Search (C++ Implementation) + * + * BinarySearch is the most efficient searching algorithm having a run-time + * complexity of O(log2 N). This algorithm works only on a sorted list of + * elements. + * + * Binary search begins by comparing the middle element of the list with the + * target element. If the target value matches the middle element, its position + * in the list is returned. If it does not match, the list is divided into two + * halves. The first half consists of the first element to middle element + * whereas the second half consists of the element next to the middle element + * to the last element. +*/ + +#include + +/** + * Binary Search (Iterative Approach) + * @param data pointer to sorted array + * @param dataLend number of elements in array + * @param value item that needs to be searched +*/ +template +int binarySearch(T* data, int dataLen, T value) +{ + int start = 0; + int end = dataLen - 1; + + while (start <= end) { + int median = (start + end) / 2; + if (data[median] < value) { + start = median + 1; + } else if (data[median] > value) { + end = median - 1; + } else { + return median; + } + } + return -1; +} + +/** + * Binary Search (Recursive Approach) + * @param data pointer to sorted array + * @param start start index of sub-array + * @param end end index of sub-array + * @param value item that needs to be searched +*/ +template +int binarySearchRecursive(T* data, int start, int end, T value) +{ + if (start > end) { + return -1; + } + + int median = (start + end) / 2; + if (data[median] == value) { + return median; + } else if (data[median] > value) { + return binarySearchRecursive(data, start, median-1, value); + } else { + return binarySearchRecursive(data, median+1, end, value); + } + return -1; +} \ No newline at end of file diff --git a/Search/Makefile b/Search/Makefile new file mode 100644 index 0000000..b9e2725 --- /dev/null +++ b/Search/Makefile @@ -0,0 +1,10 @@ +CC=g++ +GTEST_INCLUDE_PATH=../googletest/googletest/include/ +GTEST_LIBRARY_PATH=../googletest/build/lib/ -lgtest -lgtest_main +CCFLAGS=-Wall -std=c++14 + +all: + $(CC) test_BinarySearch.cpp $(CCFLAGS) -I$(GTEST_INCLUDE_PATH) -L$(GTEST_LIBRARY_PATH) + +clean: + rm ./a.out diff --git a/Search/test_BinarySearch.cpp b/Search/test_BinarySearch.cpp new file mode 100644 index 0000000..a4e45ea --- /dev/null +++ b/Search/test_BinarySearch.cpp @@ -0,0 +1,56 @@ +#include +#include "BinarySearch.h" + +TEST(BinarySearch, EmptyArray) +{ + int arr[] = {}; + ASSERT_EQ(-1, binarySearch(arr, 0, 4)); +} + +TEST(BinarySearch, SingleElementArray) +{ + int arr[] = {3}; + ASSERT_EQ(-1, binarySearch(arr, 1, 4)); + ASSERT_EQ(0, binarySearch(arr, 1, 3)); +} + +TEST(BinarySearch, PositiveNumberArray) +{ + int arr[] = {2, 3, 23, 27, 56, 73, 93, 99, 789}; + ASSERT_EQ(-1, binarySearch(arr, 9, 98)); + ASSERT_EQ(3, binarySearch(arr, 9, 27)); +} + +TEST(BinarySearch, NegativeNumberArray) +{ + int arr[] = {-3, -23, -56, 37, 73, 93, 99}; + ASSERT_EQ(-1, binarySearch(arr, 7, 98)); + ASSERT_EQ(1, binarySearch(arr, 7, -23)); +} + +TEST(BinarySearchRecursive, EmptyArray) +{ + int arr[] = {}; + ASSERT_EQ(-1, binarySearchRecursive(arr, 0, -1, 4)); +} + +TEST(BinarySearchRecursive, SingleElementArray) +{ + int arr[] = {3}; + ASSERT_EQ(-1, binarySearchRecursive(arr, 0, 0, 4)); + ASSERT_EQ(0, binarySearchRecursive(arr, 0, 0, 3)); +} + +TEST(BinarySearchRecursive, PositiveNumberArray) +{ + int arr[] = {2, 3, 23, 27, 56, 73, 93, 99, 789}; + ASSERT_EQ(-1, binarySearchRecursive(arr, 0, 8, 98)); + ASSERT_EQ(3, binarySearchRecursive(arr, 0, 8, 27)); +} + +TEST(BinarySearchRecursive, NegativeNumberArray) +{ + int arr[] = {-3, -23, -56, 37, 73, 93, 99}; + ASSERT_EQ(-1, binarySearchRecursive(arr, 0, 6, 98)); + ASSERT_EQ(1, binarySearchRecursive(arr, 0, 6, -23)); +} \ No newline at end of file From ead7c591f43be038c49566043fe40442903fbf79 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Fri, 17 Apr 2020 20:16:08 +0530 Subject: [PATCH 067/209] add Fisher-Yates (Knuth) shuffling algorithm --- Shuffle/Shuffle.cpp | 46 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Shuffle/Shuffle.cpp diff --git a/Shuffle/Shuffle.cpp b/Shuffle/Shuffle.cpp new file mode 100644 index 0000000..9069ca5 --- /dev/null +++ b/Shuffle/Shuffle.cpp @@ -0,0 +1,46 @@ +/* + * Shuffling Algorithms (C++ implementation) + * + * Shuffle randomize a given array. Here shuffle means that every permutation + * of array element should equally likely. + * It uses Fisher-Yates (Knuth) shuffling algorithm. + * + * e.g. shuffle a deck of cards + * + * Fisher–Yates shuffle Algorithm works in O(n) time complexity. + * The assumption here is, we are given a function rand() that generates + * random number in O(1) time. + */ + +#include + +/** + * Shuffle Array Template Function + * @param arr actual array to sort + * @param len size of array + */ +template +void Shuffle(T arr[], int len) +{ + // use current time as seed for random generator + std::srand(std::time(nullptr)); + for (int i = 0; i < len; i++) { + int r = rand() % (i + 1); + std::swap(arr[i], arr[r]); + } +} + +/* Main Driver Function */ +int main() +{ + int arr[] = {229, 79, 46, 12, 58, 31, 34, 67, 89, 12, 67, 2}; + int len = sizeof(arr) / sizeof(arr[0]); + + Shuffle(arr, len); + + for (int a: arr) + std::cout << a << " "; + std::cout << "\n"; + + return 0; +} \ No newline at end of file From 14d7367bcb3646f404432dfddf180dea4ef0a5c4 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sat, 18 Apr 2020 11:54:44 +0530 Subject: [PATCH 068/209] add bst insert and search methods --- BinarySearchTree/BST/BST.cpp | 58 +++++++++++++++++++++ BinarySearchTree/BST/BST.hpp | 44 ++++++++++++++++ BinarySearchTree/BST/Makefile | 10 ++++ BinarySearchTree/BST/test_BST.cpp | 86 +++++++++++++++++++++++++++++++ 4 files changed, 198 insertions(+) create mode 100644 BinarySearchTree/BST/BST.cpp create mode 100644 BinarySearchTree/BST/BST.hpp create mode 100644 BinarySearchTree/BST/Makefile create mode 100644 BinarySearchTree/BST/test_BST.cpp diff --git a/BinarySearchTree/BST/BST.cpp b/BinarySearchTree/BST/BST.cpp new file mode 100644 index 0000000..ce5fb7b --- /dev/null +++ b/BinarySearchTree/BST/BST.cpp @@ -0,0 +1,58 @@ +#include "BST.hpp" + +/** + * inserts new integer data into the tree at the position, so that + * the binary search tree property is maintained. + * @param data new integer data to be inserted +*/ +void BST::insert(int data) +{ + if (root == nullptr) { + root = new Node(data); + } else { + root = insert(root, data); + } +} + +/** + * insert is an recursive internal method which works on node level + * @param data new integer data to be inserted +*/ +Node* BST::insert(Node* root, int data) +{ + if (root == nullptr) { + root = new Node(data); + } else if (data <= root->data) { + root->left = insert(root->left, data); + } else { + root->right = insert(root->right, data); + } + return root; +} + +/** + * finds the integer in binary search tree + * @param data item to be searched +*/ +bool BST::search(int data) +{ + if (root == nullptr) + return false; + + return search(root, data); +} + +/** + * search is an recursive internal method which works at node level + * @param root root of tree/sub-tre + * @param data item to be searched +*/ +bool BST::search(Node* root, int data) +{ + if (root == nullptr) + return false; + + if (data == root->data) return true; + else if (data < root->data) return search(root->left, data); + else return search(root->right, data); +} diff --git a/BinarySearchTree/BST/BST.hpp b/BinarySearchTree/BST/BST.hpp new file mode 100644 index 0000000..1152c88 --- /dev/null +++ b/BinarySearchTree/BST/BST.hpp @@ -0,0 +1,44 @@ +/** + * Binary Search Tree (C++ Implementation) + * + * Binary Search Tree is a node-based binary tree data structure + * which has the following properties: + * - The left subtree of a node contains only nodes with keys lesser + * than the node’s key. + * - The right subtree of a node contains only nodes with keys greater + * than the node’s key. + * - The left and right subtree each must also be a binary search tree. +*/ + +#ifndef BST_H +#define BST_H + +#include + +// Node struct contains actual data and address to left and right node +struct Node { + int data; + Node* left; + Node* right; + + Node(int _data) { + data = _data; + left = nullptr; + right = nullptr; + } +}; + +class BST { +private: + Node* root; + Node* insert(Node* root, int data); + bool search(Node* root, int data); + +public: + BST() { root = nullptr; } + Node* getRoot() { return root; } + void insert(int data); + bool search(int data); +}; + +#endif diff --git a/BinarySearchTree/BST/Makefile b/BinarySearchTree/BST/Makefile new file mode 100644 index 0000000..7a189c4 --- /dev/null +++ b/BinarySearchTree/BST/Makefile @@ -0,0 +1,10 @@ +CC=g++ +GTEST_INCLUDE_PATH=../../googletest/googletest/include/ +GTEST_LIBRARY_PATH=../../googletest/build/lib/ -lgtest -lgtest_main +CCFLAGS=-Wall -std=c++14 + +all: + $(CC) test_BST.cpp BST.cpp $(CCFLAGS) -I$(GTEST_INCLUDE_PATH) -L$(GTEST_LIBRARY_PATH) + +clean: + rm ./a.out diff --git a/BinarySearchTree/BST/test_BST.cpp b/BinarySearchTree/BST/test_BST.cpp new file mode 100644 index 0000000..7fac7ef --- /dev/null +++ b/BinarySearchTree/BST/test_BST.cpp @@ -0,0 +1,86 @@ +#include +#include "BST.hpp" + +/* Fixtures */ +// Binary Search Tree initial setup +class BSTDataInit : public testing::Test { +protected: + BST bst; + std::vector original{ 9, 5, 3, 10, 6, 1, 7, 4 }; + void SetUp() override { + for (int i : original) + bst.insert(i); + } +}; + +// inorder traversal +void inorder(Node* node, std::vector& output) +{ + if (node == nullptr) + return; + inorder(node->left, output); + output.push_back(node->data); + inorder(node->right, output); +} + +// inorder traversal and storing the output in vector +std::vector inorderVector(BST& tree) +{ + std::vector output; + inorder(tree.getRoot(), output); + return output; +} + +/* Binary Search Tree Insertion */ +// test insert method on empty binary search tree +TEST(BSTEmpty, InsertTest) +{ + BST bst; + bst.insert(9); + ASSERT_EQ(9, bst.getRoot()->data); + bst.insert(5); + ASSERT_EQ(5, bst.getRoot()->left->data); + bst.insert(3); + ASSERT_EQ(3, bst.getRoot()->left->left->data); + bst.insert(10); + ASSERT_EQ(10, bst.getRoot()->right->data); + bst.insert(6); + ASSERT_EQ(6, bst.getRoot()->left->right->data); + bst.insert(1); + ASSERT_EQ(1, bst.getRoot()->left->left->left->data); + bst.insert(7); + ASSERT_EQ(7, bst.getRoot()->left->right->right->data); + bst.insert(4); + ASSERT_EQ(4, bst.getRoot()->left->left->right->data); +} + +// test insert method on filled binary search tree +TEST_F(BSTDataInit, InsertTest) +{ + std::vector output = inorderVector(bst); + std::sort(original.begin(), original.end()); + ASSERT_TRUE(original == output); +} + +/* Binary Search Tree Searching */ +// test search method on empty binary search tree +TEST(BSTEmpty, SearchTest) +{ + BST bst; + ASSERT_FALSE(bst.search(4)); + ASSERT_FALSE(bst.search(-1)); + ASSERT_FALSE(bst.search(1)); +} + +// test search method on filled binary search tree +TEST_F(BSTDataInit, SearchTest) +{ + ASSERT_TRUE(bst.search(9)); + ASSERT_TRUE(bst.search(10)); + ASSERT_TRUE(bst.search(1)); + ASSERT_TRUE(bst.search(6)); + ASSERT_FALSE(bst.search(2)); + ASSERT_FALSE(bst.search(-1)); + ASSERT_FALSE(bst.search(20)); + ASSERT_FALSE(bst.search(12)); +} From d6d71684f63cff1b3e160a7c69530f0718fa45cb Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sat, 18 Apr 2020 18:45:04 +0530 Subject: [PATCH 069/209] add bst min and max method --- BinarySearchTree/BST/BST.cpp | 36 +++++++++++++++++++++++++++++ BinarySearchTree/BST/BST.hpp | 10 +++++++- BinarySearchTree/BST/test_BST.cpp | 38 +++++++++++++++++++++++++++++++ 3 files changed, 83 insertions(+), 1 deletion(-) diff --git a/BinarySearchTree/BST/BST.cpp b/BinarySearchTree/BST/BST.cpp index ce5fb7b..bbcd22d 100644 --- a/BinarySearchTree/BST/BST.cpp +++ b/BinarySearchTree/BST/BST.cpp @@ -56,3 +56,39 @@ bool BST::search(Node* root, int data) else if (data < root->data) return search(root->left, data); else return search(root->right, data); } + +/** + * returns left-most item present in binary search tree which is also + * the minimum element in bst + * @return minimum element present in bst +*/ +int BST::min() +{ + Node* root = getRoot(); + if (root == nullptr) + throw EmptyTree(); + + Node* current = root; + while (current->left != nullptr) + current = current->left; + + return current->data; +} + +/** + * returns right-most item present in binary search tree which is also + * the maximum element in bst + * @return maximum element present in bst +*/ +int BST::max() +{ + Node* root = getRoot(); + if (root == nullptr) + throw EmptyTree(); + + Node* current = root; + while (current->right != nullptr) + current = current->right; + + return current->data; +} diff --git a/BinarySearchTree/BST/BST.hpp b/BinarySearchTree/BST/BST.hpp index 1152c88..6cdde5a 100644 --- a/BinarySearchTree/BST/BST.hpp +++ b/BinarySearchTree/BST/BST.hpp @@ -13,7 +13,13 @@ #ifndef BST_H #define BST_H -#include +#include + +class EmptyTree : public std::exception { + const char* what() const throw() { + return "tree is empty"; + } +}; // Node struct contains actual data and address to left and right node struct Node { @@ -39,6 +45,8 @@ class BST { Node* getRoot() { return root; } void insert(int data); bool search(int data); + int min(); + int max(); }; #endif diff --git a/BinarySearchTree/BST/test_BST.cpp b/BinarySearchTree/BST/test_BST.cpp index 7fac7ef..225e26a 100644 --- a/BinarySearchTree/BST/test_BST.cpp +++ b/BinarySearchTree/BST/test_BST.cpp @@ -84,3 +84,41 @@ TEST_F(BSTDataInit, SearchTest) ASSERT_FALSE(bst.search(20)); ASSERT_FALSE(bst.search(12)); } + +// test min method on empty binary search tree +TEST(BSTEmpty, findMinTest) +{ + BST bst; + ASSERT_THROW(bst.min(), EmptyTree); + bst.insert(5); + ASSERT_EQ(5, bst.min()); + bst.insert(9); + ASSERT_EQ(5, bst.min()); + bst.insert(3); + ASSERT_EQ(3, bst.min()); +} + +// test min method on filled binary search tree +TEST_F(BSTDataInit, findMinTest) +{ + ASSERT_EQ(1, bst.min()); +} + +// test max method on empty binary search tree +TEST(BSTEmpty, findMaxTest) +{ + BST bst; + ASSERT_THROW(bst.max(), EmptyTree); + bst.insert(5); + ASSERT_EQ(5, bst.max()); + bst.insert(9); + ASSERT_EQ(9, bst.max()); + bst.insert(3); + ASSERT_EQ(9, bst.max()); +} + +// test max method on filled binary search tree +TEST_F(BSTDataInit, findMaxTest) +{ + ASSERT_EQ(10, bst.max()); +} From 7dbb8048b63f77bee8623c5c5d2c7c69b3d42284 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sat, 18 Apr 2020 19:59:05 +0530 Subject: [PATCH 070/209] add height method in binary search tree --- BinarySearchTree/BST/BST.cpp | 28 ++++++++++++++++++++++++++++ BinarySearchTree/BST/BST.hpp | 2 ++ BinarySearchTree/BST/test_BST.cpp | 24 ++++++++++++++++++++++++ 3 files changed, 54 insertions(+) diff --git a/BinarySearchTree/BST/BST.cpp b/BinarySearchTree/BST/BST.cpp index bbcd22d..6d37270 100644 --- a/BinarySearchTree/BST/BST.cpp +++ b/BinarySearchTree/BST/BST.cpp @@ -92,3 +92,31 @@ int BST::max() return current->data; } + +/** + * height is recursive internal method that works at node-level + * @return height of tree/sub-tree +*/ +int BST::height(Node* root) +{ + if (root == nullptr) + return -1; + + int leftHeight = height(root->left); + int rightHeight = height(root->right); + if (leftHeight > rightHeight) + return leftHeight + 1; + return rightHeight + 1; +} + +/** + * calculate height of binary search tree + * @return height of tree +*/ +int BST::height() +{ + if (root == nullptr) + throw EmptyTree(); + + return height(root); +} diff --git a/BinarySearchTree/BST/BST.hpp b/BinarySearchTree/BST/BST.hpp index 6cdde5a..b0e43b8 100644 --- a/BinarySearchTree/BST/BST.hpp +++ b/BinarySearchTree/BST/BST.hpp @@ -39,6 +39,7 @@ class BST { Node* root; Node* insert(Node* root, int data); bool search(Node* root, int data); + int height(Node* root); public: BST() { root = nullptr; } @@ -47,6 +48,7 @@ class BST { bool search(int data); int min(); int max(); + int height(); }; #endif diff --git a/BinarySearchTree/BST/test_BST.cpp b/BinarySearchTree/BST/test_BST.cpp index 225e26a..c368ba4 100644 --- a/BinarySearchTree/BST/test_BST.cpp +++ b/BinarySearchTree/BST/test_BST.cpp @@ -122,3 +122,27 @@ TEST_F(BSTDataInit, findMaxTest) { ASSERT_EQ(10, bst.max()); } + +// test height on empty binary search tree +TEST(BSTEmpty, heightTest) +{ + BST bst; + ASSERT_THROW(bst.height(), EmptyTree); + bst.insert(5); + ASSERT_EQ(0, bst.height()); + bst.insert(6); + ASSERT_EQ(1, bst.height()); + bst.insert(7); + ASSERT_EQ(2, bst.height()); + bst.insert(4); + ASSERT_EQ(2, bst.height()); + bst.insert(3); + ASSERT_EQ(2, bst.height()); + bst.insert(8); + ASSERT_EQ(3, bst.height()); +} + +TEST_F(BSTDataInit, heightTest) +{ + ASSERT_EQ(3, bst.height()); +} From c1bf3c39f05caad36e9392eb58550f8359744b25 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sun, 19 Apr 2020 11:06:07 +0530 Subject: [PATCH 071/209] add bfs traversal for bst --- BinarySearchTree/BST/BST.hpp | 2 +- BinarySearchTree/bfsTraversal.cpp | 61 +++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 BinarySearchTree/bfsTraversal.cpp diff --git a/BinarySearchTree/BST/BST.hpp b/BinarySearchTree/BST/BST.hpp index b0e43b8..b76b244 100644 --- a/BinarySearchTree/BST/BST.hpp +++ b/BinarySearchTree/BST/BST.hpp @@ -43,7 +43,7 @@ class BST { public: BST() { root = nullptr; } - Node* getRoot() { return root; } + Node* getRoot() const { return root; } void insert(int data); bool search(int data); int min(); diff --git a/BinarySearchTree/bfsTraversal.cpp b/BinarySearchTree/bfsTraversal.cpp new file mode 100644 index 0000000..f8fb998 --- /dev/null +++ b/BinarySearchTree/bfsTraversal.cpp @@ -0,0 +1,61 @@ +/** + * LevelOrder traversal of a tree is breadth first traversal for the tree + * + * Example: + * + * F + * / \ + * B G + * / \ \ + * A D I + * + * Level Order Traversal := F -> B -> G -> A -> D -> I +*/ +#include +#include +#include "BST/BST.hpp" + +void levelOrder(const BST& tree, std::vector& output); + +/* Main Operational Function */ +int main() +{ + BST tree; + int original[] = { 9, 5, 3, 10, 6, 1, 7, 4 }; + for (int i : original) + tree.insert(i); + + std::vector output; + levelOrder(tree, output); + for (int o : output) + std::cout << o << " "; + std::cout << "\n"; + return 0; +} + +/** + * Breadth First Traversal (Level Order Traversal) + * @param tree bst tree object + * @param output output of level order traversal is stored in vector +*/ +void levelOrder(const BST& tree, std::vector& output) +{ + Node* root = tree.getRoot(); + if (root == nullptr) + return; + + std::queue q; + q.push(root); + + while(!q.empty()) { + Node* node = q.front(); + output.push_back(node->data); + if (node->left != nullptr) { + q.push(node->left); + } + if (node->right != nullptr) { + q.push(node->right); + } + q.pop(); + } +} From 65405d79e0a4683ee53d316ee89bfe441cdafebb Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sun, 19 Apr 2020 11:06:16 +0530 Subject: [PATCH 072/209] add dfs traversal for bst --- BinarySearchTree/dfsTraversal.cpp | 107 ++++++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 BinarySearchTree/dfsTraversal.cpp diff --git a/BinarySearchTree/dfsTraversal.cpp b/BinarySearchTree/dfsTraversal.cpp new file mode 100644 index 0000000..317890f --- /dev/null +++ b/BinarySearchTree/dfsTraversal.cpp @@ -0,0 +1,107 @@ +/** + * Depth First Traversal of Binary Search Tree + * C++ Implementation + * + * DFS (Depth-first search) is technique used for traversing tree or graph. + * Here backtracking is used for traversal. In this traversal first the + * deepest node is visited and then backtracks to it’s parent node if no + * sibling of that node exist. +*/ + +#include +#include +#include "BST/BST.hpp" + +void preOrder(Node* node, std::vector& output); +void inOrder(Node* node, std::vector& output); +void postOrder(Node* node, std::vector& output); + +int main() +{ + BST tree; + int original[] = { 9, 5, 3, 10, 6, 1, 7, 4 }; + for (int i : original) + tree.insert(i); + + Node* root = tree.getRoot(); + std::vector output; + + preOrder(root, output); + std::cout << " PreOrder: "; + for (int o: output) + std::cout << o << " "; + std::cout << "\n"; + output.clear(); + + inOrder(root, output); + std::cout << " InOrder: "; + for (int o: output) + std::cout << o << " "; + std::cout << "\n"; + output.clear(); + + postOrder(root, output); + std::cout << "PostOrder: "; + for (int o: output) + std::cout << o << " "; + std::cout << "\n"; + output.clear(); + return 0; +} + +/** + * Pre Order Tree Traversal + * Visit the root node + * Visit all the nodes in the left subtree + * Visit all the nodes in the right subtree + * + * @param node root of tree/sub-tree + * @param output output vector to store order +*/ +void preOrder(Node* node, std::vector& output) +{ + if (node == nullptr) + return; + + output.push_back(node->data); + preOrder(node->left, output); + preOrder(node->right, output); +} + +/** + * In Order Tree Traversal + * Visit all the nodes in the left subtree + * Visit the root node + * Visit all the nodes in the right subtree + * + * @param node root of tree/sub-tree + * @param output output vector to store order +*/ +void inOrder(Node* node, std::vector& output) +{ + if (node == nullptr) + return; + + inOrder(node->left, output); + output.push_back(node->data); + inOrder(node->right, output); +} + +/** + * Post Order Tree Traversal + * Visit all the nodes in the left subtree + * Visit all the nodes in the right subtree + * Visit the root node + * + * @param node root of tree/sub-tree + * @param output output vector to store order +*/ +void postOrder(Node* node, std::vector& output) +{ + if (node == nullptr) + return; + + postOrder(node->left, output); + postOrder(node->right, output); + output.push_back(node->data); +} From a758dad8847bf9aa0d70e66e0ec53b9080b0c472 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sun, 19 Apr 2020 11:51:42 +0530 Subject: [PATCH 073/209] add bst destructor --- BinarySearchTree/BST/BST.cpp | 17 +++++++++++++++++ BinarySearchTree/BST/BST.hpp | 2 ++ 2 files changed, 19 insertions(+) diff --git a/BinarySearchTree/BST/BST.cpp b/BinarySearchTree/BST/BST.cpp index 6d37270..2065438 100644 --- a/BinarySearchTree/BST/BST.cpp +++ b/BinarySearchTree/BST/BST.cpp @@ -1,4 +1,21 @@ #include "BST.hpp" +#include + +/** + * Delete tree nodes recursively +*/ +void BST::DeleteTreeRecursive(Node* node) +{ + if (node == nullptr) + return; + + if (node->left != nullptr) + DeleteTreeRecursive(node->left); + if (node->right != nullptr) + DeleteTreeRecursive(node->right); + + delete node; +} /** * inserts new integer data into the tree at the position, so that diff --git a/BinarySearchTree/BST/BST.hpp b/BinarySearchTree/BST/BST.hpp index b76b244..a43e569 100644 --- a/BinarySearchTree/BST/BST.hpp +++ b/BinarySearchTree/BST/BST.hpp @@ -40,9 +40,11 @@ class BST { Node* insert(Node* root, int data); bool search(Node* root, int data); int height(Node* root); + void DeleteTreeRecursive(Node* node); public: BST() { root = nullptr; } + ~BST() { DeleteTreeRecursive(root); } Node* getRoot() const { return root; } void insert(int data); bool search(int data); From ed6199637377a4acbe8c56e4140ea0fed815bdaf Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Mon, 20 Apr 2020 22:06:46 +0530 Subject: [PATCH 074/209] add bubble sort --- Sort/BubbleSort.cpp | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Sort/BubbleSort.cpp diff --git a/Sort/BubbleSort.cpp b/Sort/BubbleSort.cpp new file mode 100644 index 0000000..9d2a477 --- /dev/null +++ b/Sort/BubbleSort.cpp @@ -0,0 +1,45 @@ +/* + * Sorting Algorithms + * Bubble Sort (C++ implementation) + * + * Bubble sort is a simple sorting algorithm that repeatedly steps through + * the list to be sorted, compares each pair of adjacent items and swaps + * them if they are in the wrong order. The pass through the list is repeated + * until no swaps are needed, which indicates that the list is sorted. + */ + +#include + +/** + * Bubble Sort Template Function + * @param arr actual array to sort + * @param len size of array + */ +template +void BubbleSort(T arr[], int len) { + bool swapped = false; + for (int i = 0; i < len-1; i++) { + for (int j = 0; j < len-1; j++) { + if (arr[j] > arr[j+1]) { + std::swap(arr[j], arr[j+1]); + swapped = true; + } + } + if (!swapped) + break; + } +} + +/* Main Driver Function */ +int main() { + int arr[] = {229, 79, 46, 12, 58, 31, 34, 67, 89, 12, 67, 2}; + int arr_size = sizeof(arr) / sizeof(arr[0]); + + BubbleSort(arr, arr_size); + + for (int a: arr) + std::cout << a << " "; + std::cout << "\n"; + + return 0; +} \ No newline at end of file From 3bcbe68b462557cfcd6231b95c860fe37fcabcd2 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Wed, 22 Apr 2020 18:42:49 +0530 Subject: [PATCH 075/209] add bst node deletion --- BinarySearchTree/BST/BST.cpp | 62 +++++++++++++++++++++++++++++++ BinarySearchTree/BST/BST.hpp | 3 ++ BinarySearchTree/BST/test_BST.cpp | 29 +++++++++++++++ 3 files changed, 94 insertions(+) diff --git a/BinarySearchTree/BST/BST.cpp b/BinarySearchTree/BST/BST.cpp index 2065438..f1a4711 100644 --- a/BinarySearchTree/BST/BST.cpp +++ b/BinarySearchTree/BST/BST.cpp @@ -74,6 +74,18 @@ bool BST::search(Node* root, int data) else return search(root->right, data); } +/** + * find the node with minimum value of give (sub)tree + * @param node root of sub(tree) + * @return node with minimum value +*/ +Node* BST::findMinNode(Node* node) +{ + while (node->left != nullptr) + node = node->left; + return node; +} + /** * returns left-most item present in binary search tree which is also * the minimum element in bst @@ -137,3 +149,53 @@ int BST::height() return height(root); } + +/** + * delete first occurance of value from binary search tree + * @param value node with value to be deleted +*/ +void BST::deleteNode(int value) +{ + root = deleteNode(root, value); +} + +/** + * delete is interal recursive method that works at node-level + * @param root root of (sub)tree + * @param value node with value to be deleted + * @return modified root node +*/ +Node* BST::deleteNode(Node* root, int value) +{ + if (root == nullptr) + return root; + + else if (value < root->data) + root->left = deleteNode(root->left, value); + + else if (value > root->data) + root->right = deleteNode(root->right, value); + + else { + if (root->left == nullptr && root->right == nullptr) { + delete root; + root = nullptr; + } + else if (root->left == nullptr) { + Node* temp = root; + root = root->right; + delete temp; + } + else if (root->right == nullptr) { + Node* temp = root; + root = root->left; + delete temp; + } + else { + Node* temp = findMinNode(root->right); + root->data = temp->data; + root->right = deleteNode(root->right, temp->data); + } + } + return root; +} diff --git a/BinarySearchTree/BST/BST.hpp b/BinarySearchTree/BST/BST.hpp index a43e569..589b43b 100644 --- a/BinarySearchTree/BST/BST.hpp +++ b/BinarySearchTree/BST/BST.hpp @@ -41,6 +41,8 @@ class BST { bool search(Node* root, int data); int height(Node* root); void DeleteTreeRecursive(Node* node); + Node* deleteNode(Node* node, int value); + Node* findMinNode(Node* node); public: BST() { root = nullptr; } @@ -51,6 +53,7 @@ class BST { int min(); int max(); int height(); + void deleteNode(int value); }; #endif diff --git a/BinarySearchTree/BST/test_BST.cpp b/BinarySearchTree/BST/test_BST.cpp index c368ba4..aed7e51 100644 --- a/BinarySearchTree/BST/test_BST.cpp +++ b/BinarySearchTree/BST/test_BST.cpp @@ -142,7 +142,36 @@ TEST(BSTEmpty, heightTest) ASSERT_EQ(3, bst.height()); } +// test height on filled binary search tree TEST_F(BSTDataInit, heightTest) { ASSERT_EQ(3, bst.height()); } + +// test delete node method on empty search tree +TEST(BSTEmpty, deleteNodeTest) +{ + BST bst; + bst.deleteNode(5); + ASSERT_EQ(nullptr, bst.getRoot()); +} + +// test delete node method on filled search tree +TEST_F(BSTDataInit, deleteNodeTest) +{ + bst.deleteNode(3); + ASSERT_EQ(5, bst.getRoot()->left->data); + ASSERT_EQ(4, bst.getRoot()->left->left->data); + ASSERT_EQ(nullptr, bst.getRoot()->left->left->right); + ASSERT_EQ(1, bst.getRoot()->left->left->left->data); + + bst.deleteNode(5); + Node* root = bst.getRoot(); + ASSERT_EQ(9, root->data); + ASSERT_EQ(6, root->left->data); + ASSERT_EQ(10, root->right->data); + ASSERT_EQ(4, root->left->left->data); + ASSERT_EQ(1, root->left->left->left->data); + ASSERT_EQ(7, root->left->right->data); + +} From c8d32e0b6f23d815f24fdfc496ec78dd64bbe5a2 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Wed, 22 Apr 2020 18:44:00 +0530 Subject: [PATCH 076/209] add selection sort --- Sort/SelectionSort.cpp | 49 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Sort/SelectionSort.cpp diff --git a/Sort/SelectionSort.cpp b/Sort/SelectionSort.cpp new file mode 100644 index 0000000..36d82c5 --- /dev/null +++ b/Sort/SelectionSort.cpp @@ -0,0 +1,49 @@ +/* + * Sorting Algorithms + * Selection Sort (C++ implementation) + * + * The selection sort algorithm sorts an array by repeatedly finding the + * minimum element (considering ascending order) from unsorted part and + * putting it at the beginning. The algorithm maintains two subarrays in + * a given array. + * - The subarray which is already sorted. + * - Remaining subarray which is unsorted. + * + * In every iteration of selection sort, the minimum element (considering + * ascending order) from the unsorted subarray is picked and moved to the + * sorted subarray. + */ + +#include + +/** + * Selection Sort Template Function + * @param arr actual array to sort + * @param len size of array + */ +template +void SelectionSort(int arr[], size_t len) +{ + for (int i = 0; i < len; i++) { + int min_element_index = i; + for (int j = i+1; j < len; j++) { + if (arr[j] < arr[min_element_index]) + min_element_index = j; + } + std::swap(arr[i], arr[min_element_index]); + } +} + +/* Main Driver Function */ +int main() { + int arr[] = {229, 79, 46, 12, 58, 31, 34, 67, 89, 12, 67, 2}; + int arr_size = sizeof(arr) / sizeof(arr[0]); + + SelectionSort(arr, arr_size); + + for (int a: arr) + std::cout << a << " "; + std::cout << "\n"; + + return 0; +} \ No newline at end of file From d4b87ad91e6b353cd0d344b3a10f2b149ec16325 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Wed, 22 Apr 2020 18:47:22 +0530 Subject: [PATCH 077/209] typo --- LinkedList/LinkedList/test_LinkedList.cpp | 2 +- Queue/ReverseQueue.cpp | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/LinkedList/LinkedList/test_LinkedList.cpp b/LinkedList/LinkedList/test_LinkedList.cpp index ccd1596..b99f59b 100755 --- a/LinkedList/LinkedList/test_LinkedList.cpp +++ b/LinkedList/LinkedList/test_LinkedList.cpp @@ -4,7 +4,7 @@ #include "LinkedList.hpp" /* Fixtures */ -// LinkedList containing only multiple node +// LinkedList containing multiple node class LinkedListDataInit : public testing::Test { protected: LinkedList::LinkedList ll; diff --git a/Queue/ReverseQueue.cpp b/Queue/ReverseQueue.cpp index abda0a4..0314fe4 100644 --- a/Queue/ReverseQueue.cpp +++ b/Queue/ReverseQueue.cpp @@ -5,6 +5,10 @@ * * Input: [1, 2, 3, 4, 5] * Output: [5, 4, 3, 2, 1] + * + * URL: https://www.geeksforgeeks.org/reversing-a-queue/ + * URL: https://www.geeksforgeeks.org/reversing-queue-using-recursion/ + * CMD: g++ -Wall -std=c++14 ReverseQueue.cpp */ #include @@ -60,4 +64,4 @@ int main() std::cout << "Recursive "; queue.display(); return 0; -} \ No newline at end of file +} From 6e5f31816a871053f9f8a6e58953a06e235c9c27 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Thu, 23 Apr 2020 21:45:38 +0530 Subject: [PATCH 078/209] add dynamic connectivity quick find algorithm --- DynamicConnectivity/QuickFind.cpp | 85 +++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 DynamicConnectivity/QuickFind.cpp diff --git a/DynamicConnectivity/QuickFind.cpp b/DynamicConnectivity/QuickFind.cpp new file mode 100644 index 0000000..266acdf --- /dev/null +++ b/DynamicConnectivity/QuickFind.cpp @@ -0,0 +1,85 @@ +/** + * Dynamic Connectivity + * + * Given a set of N objects + * - Union Command: connect two objects. + * - Find/connected query: is there a path connecting the two objects? + * + * Quick-Find and Quick-Union are only going to tell us if there is a path + * between two objects. It is not going to give us the complete path. + * + * Connected components: Maximal set of objects that are mutually connected. +*/ +#include + +/** + * QuickFind (Eager Approach) + * Data Structure: Integer array id[] of size N + * Interpretation: p and q are connected iff they have same id. + * + * QuickFind defect: Union too expensive + * Takes N^2 array accesses to process sequence of N union commands on + * N objects. +*/ +class QuickFind { +private: + int size; + int* id; +public: + /** + * Initializing list of size n where value is same as index + * Time Complexity: O(n) + * @param n number of elements + */ + QuickFind(int n): size(n) { + id = new int[n]; + for (int i = 0; i < size; i++) + id[i] = i; + } + + /** + * p and q are connected iff they have the same id + * Time Complexity: O(1) + * @param p element 1 + * @param q element 2 + * @return true iff two p and q are connected, else false + */ + bool connected(int p, int q) { + return id[p] == id[q]; + } + + /** + * When connecting two objects elem1 and elem2, change the id of all + * objects that have the id of elem1 to that of elem2, or vice-versa. + * Time Complexity is O(n), which is too expensive. + * @param p element 1 + * @param q element 2 + */ + void joinUnion(int p, int q) { + int pid = id[p]; + int qid = id[q]; + for (int i = 0; i < size; i++) { + if (id[i] == pid) + id[i] = qid; + } + } +}; + +/* Main Driver Function */ +int main() +{ + QuickFind quickFind(10); + quickFind.joinUnion(4, 3); + quickFind.joinUnion(3, 8); + quickFind.joinUnion(6, 5); + quickFind.joinUnion(9, 4); + quickFind.joinUnion(2, 1); + std::cout << "is 0 connected to 7? " << quickFind.connected(0, 7) << "\n"; + std::cout << "is 8 connected to 9? " << quickFind.connected(8, 9) << "\n"; + quickFind.joinUnion(5, 0); + quickFind.joinUnion(7, 2); + quickFind.joinUnion(6, 1); + quickFind.joinUnion(1, 0); + std::cout << "is 0 connected to 7? " << quickFind.connected(0, 7) << "\n"; + return 0; +} \ No newline at end of file From ecfa8bf2f689b07fae38952a4e54c2c6d9a5f57c Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Fri, 24 Apr 2020 15:42:10 +0530 Subject: [PATCH 079/209] add counting sort --- Sort/CountingSort.cpp | 68 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 Sort/CountingSort.cpp diff --git a/Sort/CountingSort.cpp b/Sort/CountingSort.cpp new file mode 100644 index 0000000..327a9a7 --- /dev/null +++ b/Sort/CountingSort.cpp @@ -0,0 +1,68 @@ +/* + * Sorting Algorithms + * Counting Sort (C++ implementation) + * + * Counting sort is a sorting algorithm that sorts the elements of an array + * by counting the number of occurrences of each unique element in the array. + * The count is stored in an auxiliary array + * and the sorting is done by mapping the count as an index of the auxiliary array. + */ + +#include + +/* Function Declaration */ +void CountSort(int arr[], int len); + +/* Main Driver Function */ +int main() { + int arr[] = {229, 79, 46, -23, 12, 58, 31, 34, 67, 89, 12, 67, 2}; + int arr_size = sizeof(arr) / sizeof(arr[0]); + + CountSort(arr, arr_size); + + for (int a: arr) + std::cout << a << " "; + std::cout << "\n"; + + return 0; +} + +/** + * Count Sort Function + * @param arr actual array to sort + * @param len size of array + */ +void CountSort(int arr[], int len) { + int minElement = *std::min_element(arr, arr+len); + int maxElement = *std::max_element(arr, arr+len); + + int outputLen = maxElement - minElement + 1; + int count[outputLen]; + int output[outputLen]; + + // initialize count and output array to all zero + for (int i = 0; i < outputLen; i++) { + count[i] = 0; + output[i] = 0; + } + + // increase number count in count array. + for (int i = 0; i < len; i++) { + count[arr[i] - minElement]++; + } + + // find cumulative frequency + for (int i = 1; i < outputLen; i++) { + count[i] += count[i-1]; + } + + for (int i = 0; i < len; i++) { + output[count[arr[i]-minElement]-1] = arr[i]; + count[arr[i]-minElement]--; //decrease count for same numbers + } + + // store output array to main array + for (int i = 0; i < len; i++) { + arr[i] = output[i]; + } +} From 6d46e585710675e2613f8495cf3477be97bc13e4 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sun, 26 Apr 2020 09:55:41 +0530 Subject: [PATCH 080/209] add gnome sort --- Sort/GnomeSort.cpp | 47 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Sort/GnomeSort.cpp diff --git a/Sort/GnomeSort.cpp b/Sort/GnomeSort.cpp new file mode 100644 index 0000000..951cefd --- /dev/null +++ b/Sort/GnomeSort.cpp @@ -0,0 +1,47 @@ +/* + * Sorting Algorithms + * Gnome Sort (C++ implementation) + * + * GnomeSort is a sorting algorithm which is similar + * to insertion sort in that it works with one item at a time + * but gets the item to the proper place by a series of swaps. + */ + +#include +#include + +/* Function declaration */ +template +void GnomeSort(T data[], int dataLen); + +/* Main Driver Function */ +int main() { + int arr[] = {229, 79, 46, 12, 58, 31, 34, 67, 89, 12, 67, 2}; + int arr_size = sizeof(arr) / sizeof(arr[0]); + + GnomeSort(arr, arr_size); + + for (int a: arr) + std::cout << a << " "; + std::cout << "\n"; + + return 0; +} + +/** + * Gnome Sort Template Function + * @param data actual array to sort + * @param dataLen size of array + */ +template +void GnomeSort(T data[], int dataLen) { + int index = 0; + while (index < dataLen) { + if (index == 0 || data[index] >= data[index - 1]) { + index++; + } else { + std::swap(data[index], data[index - 1]); + index--; + } + } +} \ No newline at end of file From 3ef8ceafff40b3fa2bfbf92551f4e3cbf1f0f66e Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sun, 26 Apr 2020 12:26:16 +0530 Subject: [PATCH 081/209] add shell sort --- Sort/ShellSort.cpp | 53 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Sort/ShellSort.cpp diff --git a/Sort/ShellSort.cpp b/Sort/ShellSort.cpp new file mode 100644 index 0000000..928f630 --- /dev/null +++ b/Sort/ShellSort.cpp @@ -0,0 +1,53 @@ +/* + * Sorting Algorithms + * Shell Sort (C++ implementation) + * + * ShellSort is mainly a variation of Insertion Sort. In insertion sort, we + * move elements only one position ahead. When an element has to be moved far + * ahead, many movements are involved. The idea of shellSort is to allow + * exchange of far items. In shellSort, we make the array h-sorted for a large + * value of h. We keep reducing the value of h until it becomes 1. An array is + * said to be h-sorted if all sublists of every h’th element is sorted. + */ +#include + +/* Function Declarations */ +template +void ShellSort(T data[], int dataLen); + +/* Main Driver Function */ +int main() { + int arr[] = {229, 79, 46, 12, 58, 31, 34, 67, 89, 12, 67, 2}; + int arr_size = sizeof(arr) / sizeof(arr[0]); + + ShellSort(arr, arr_size); + + for (int a: arr) + std::cout << a << " "; + std::cout << "\n"; + + return 0; +} + +/** + * Shell Sort Template Function + * @param data actual array to sort + * @param dataLen size of array + */ +template +void ShellSort(T data[], int dataLen) { + int h = 1; + while (h < dataLen / 3) { + h = (h * 3) + 1; + } + + while (h >= 1) { + // h-sort the array + for (int i = h; i < dataLen; i++) { + for (int j = i; j >= h && data[j] < data[j - h]; j = j - h) { + std::swap(data[j], data[j - h]); + } + } + h = h / 3; + } +} \ No newline at end of file From f6984c05742e08be04bfc7717d4c8f5a1503749b Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Mon, 27 Apr 2020 10:12:02 +0530 Subject: [PATCH 082/209] add min heap algorithm --- Heap/Heap/HeapException.hpp | 26 +++++ Heap/Heap/MinHeap.hpp | 187 ++++++++++++++++++++++++++++++++++++ 2 files changed, 213 insertions(+) create mode 100644 Heap/Heap/HeapException.hpp create mode 100644 Heap/Heap/MinHeap.hpp diff --git a/Heap/Heap/HeapException.hpp b/Heap/Heap/HeapException.hpp new file mode 100644 index 0000000..3607d42 --- /dev/null +++ b/Heap/Heap/HeapException.hpp @@ -0,0 +1,26 @@ +#ifndef HEAP_EXCEPTION_H +#define HEAP_EXCEPTION_H + +#include + +namespace Heap { + namespace Exception { + /** + * EmptyHeap exception is raised when you are trying to access + * element from empty heap. + */ + class EmptyHeap : public std::exception { + const char* what() const throw() { return "heap is empty"; } + }; + + /** + * FullHeap expection is raised when you are trying to insert + * element in completely filled heap + */ + class FullHeap : public std::exception { + const char* what() const throw() { return "heap is full"; } + }; + } +} + +#endif diff --git a/Heap/Heap/MinHeap.hpp b/Heap/Heap/MinHeap.hpp new file mode 100644 index 0000000..b4778e9 --- /dev/null +++ b/Heap/Heap/MinHeap.hpp @@ -0,0 +1,187 @@ +/** + * Heap Data Strucure - Min Heap (C++ implementation) + * + * A Heap is a special Tree-based data structure in which the tree is a + * complete binary tree. + * In a Min-Heap the key present at the root node must be minimum among the + * keys present at all of it’s children. The same property must be + * recursively true for all sub-trees in that Binary Tree. + */ +#include +#include "HeapException.hpp" + +namespace Heap { + template + class MinHeap { + private: + T* data; // pointer to array of elements in heap + int size; // current number of elements in heap + int capacity; // maximum possible size of heap + + void swim(int k); + void sink(int k); + int parent(int k) { return k / 2; } + int leftChild(int k) { return 2 * k; } + int rightChild(int k) { return 2 * k + 1; } + + public: + MinHeap(int capacity); + MinHeap(T* array, int arrayLen); + int getSize(); + bool isFull(); + bool isEmpty(); + void insert(T item); + T extractMin(); + T min(); + }; + + /** + * swim moves element at index k upward to maintain heap invariant + * @param k node index that needs to swim up + */ + template + void MinHeap::swim(int k) { + if (k <= 1) { + // k is the root node + return; + } + int p = parent(k); + if (data[p] > data[k]) { + std::swap(data[p], data[k]); + swim(p); + } + } + + /** + * sink moves element at index k downward to maintain heap invariant + * @param k node index that needs to sink down + */ + template + void MinHeap::sink(int k) { + int min = k; + + // find index of minimum value (k, k's left child, k's right child) + int left = leftChild(k); + if (left <= size) { + if (data[min] > data[left]) min = left; + } + + int right = rightChild(k); + if (right <= size) { + if (data[min] > data[right]) min = right; + } + + if (min != k) { + std::swap(data[k], data[min]); + sink(min); + } + } + + /** + * creates new empty 1-indexed heap + * @param capacity maximum possible size of heap + */ + template + MinHeap::MinHeap(int capacity) : capacity(capacity) { + data = new T[capacity + 1]; + size = 0; + } + + /** + * builds heap structure from an unorganized array data + * Time complexity of building a heap is O(n) + * @param array pointer to array + * @param arrayLen number of items in array + */ + template + MinHeap::MinHeap(T* array, int arrayLen) { + capacity = arrayLen; + data = new T[capacity + 1]; + size = arrayLen; + + for (int i = 0; i < arrayLen; i++) { + data[i + 1] = array[i]; + } + + for (int i = arrayLen / 2; i >= 1; i--) { + sink(i); + } + } + + /** + * checks if heap is full + * @return true if heap is full, else false + */ + template + bool MinHeap::isFull() { + return size >= capacity; + } + + /** + * checks if heap is empty + * @return true if heap is empty, else false + */ + template + bool MinHeap::isEmpty() { + return size == 0; + } + + /** + * get Heap size + * @return total number of elements currently present in heap + */ + template + int MinHeap::getSize() { + return size; + } + + /** + * inserts new element into heap + * @param item insert item in heap while maintaining the heap property + * @throw Heap::Exception::FullHeap when trying to insert item in + * completely filled heap + */ + template + void MinHeap::insert(T item) { + if (isFull()) + throw Exception::FullHeap(); + + size = size + 1; + data[size] = item; + swim(size); + } + + /** + * returns the minimum value (i.e. root) in the heap and + * removes it from the heap. + * @return minimum value from heap + * @throw MinHeap::Exception::EmptyHeap when trying to access item from + * empty heap + */ + template + T MinHeap::extractMin() { + if (isEmpty()) + throw Exception::EmptyHeap(); + + T minValue = data[1]; + data[1] = data[size]; + size = size - 1; + sink(1); + return minValue; + } + + /** + * returns the minimum value (i.e. root) in the heap, without + * removing it. + * @return minimum value from heap + * @throw MinHeap::Exception::EmptyHeap when trying to access item from + * empty heap + */ + template + T MinHeap::min() { + if (isEmpty()) + throw Exception::EmptyHeap(); + + return data[1]; + } +} \ No newline at end of file From 2078df67ef23513c0ec0c06f06f92c8a47ef4aab Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Wed, 29 Apr 2020 09:03:51 +0530 Subject: [PATCH 083/209] add max heap --- Heap/Heap/MaxHeap.hpp | 187 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 187 insertions(+) create mode 100644 Heap/Heap/MaxHeap.hpp diff --git a/Heap/Heap/MaxHeap.hpp b/Heap/Heap/MaxHeap.hpp new file mode 100644 index 0000000..3bf04b3 --- /dev/null +++ b/Heap/Heap/MaxHeap.hpp @@ -0,0 +1,187 @@ +/** + * Heap Data Strucure - Max Heap (C++ implementation) + * + * A Heap is a special Tree-based data structure in which the tree is a + * complete binary tree. + * In a Max-Heap the key present at the root node must be greatest among the + * keys present at all of it’s children. The same property must be recursively + * true for all sub-trees in that Binary Tree. + */ +#include +#include "HeapException.hpp" + +namespace Heap { + template + class MaxHeap { + private: + T* data; // pointer to array of elements in heap + int size; // current number of elements in heap + int capacity; // maximum possible size of heap + + void swim(int k); + void sink(int k); + int parent(int k) { return k / 2; } + int leftChild(int k) { return 2 * k; } + int rightChild(int k) { return 2 * k + 1; } + + public: + MaxHeap(int capacity); + MaxHeap(T* array, int arrayLen); + int getSize(); + bool isFull(); + bool isEmpty(); + void insert(T item); + T extractMax(); + T max(); + }; + + /** + * swim moves element at index k upward to maintain heap invariant + * @param k node index that needs to swim up + */ + template + void MaxHeap::swim(int k) { + if (k <= 1) { + // k is the root node + return; + } + int p = parent(k); + if (data[p] < data[k]) { + std::swap(data[p], data[k]); + swim(p); + } + } + + /** + * sink moves element at index k downward to maintain heap invariant + * @param k node index that needs to sink down + */ + template + void MaxHeap::sink(int k) { + int min = k; + + // find index of minimum value (k, k's left child, k's right child) + int left = leftChild(k); + if (left <= size) { + if (data[min] < data[left]) min = left; + } + + int right = rightChild(k); + if (right <= size) { + if (data[min] < data[right]) min = right; + } + + if (min != k) { + std::swap(data[k], data[min]); + sink(min); + } + } + + /** + * creates new empty 1-indexed heap + * @param capacity maximum possible size of heap + */ + template + MaxHeap::MaxHeap(int capacity) : capacity(capacity) { + data = new T[capacity + 1]; + size = 0; + } + + /** + * builds heap structure from an unorganized array data + * Time complexity of building a heap is O(n) + * @param array pointer to array + * @param arrayLen number of items in array + */ + template + MaxHeap::MaxHeap(T* array, int arrayLen) { + capacity = arrayLen; + data = new T[capacity + 1]; + size = arrayLen; + + for (int i = 0; i < arrayLen; i++) { + data[i + 1] = array[i]; + } + + for (int i = arrayLen / 2; i >= 1; i--) { + sink(i); + } + } + + /** + * checks if heap is full + * @return true if heap is full, else false + */ + template + bool MaxHeap::isFull() { + return size >= capacity; + } + + /** + * checks if heap is empty + * @return true if heap is empty, else false + */ + template + bool MaxHeap::isEmpty() { + return size == 0; + } + + /** + * get Heap size + * @return total number of elements currently present in heap + */ + template + int MaxHeap::getSize() { + return size; + } + + /** + * inserts new element into heap + * @param item insert item in heap while maintaining the heap property + * @throw Heap::Exception::FullHeap when trying to insert item in + * completely filled heap + */ + template + void MaxHeap::insert(T item) { + if (isFull()) + throw Exception::FullHeap(); + + size = size + 1; + data[size] = item; + swim(size); + } + + /** + * ExtractMax returns the maximum value (i.e. root) in the heap and + * removes it from the heap. + * @return maximum value from heap + * @throw MaxHeap::Exception::EmptyHeap when trying to access item from + * empty heap + */ + template + T MaxHeap::extractMax() { + if (isEmpty()) + throw Exception::EmptyHeap(); + + T maxValue = data[1]; + data[1] = data[size]; + size = size - 1; + sink(1); + return maxValue; + } + + /** + * Max returns the maximum value (i.e. root) in the heap, without + * removing it. + * @return maximum value from heap + * @throw MaxHeap::Exception::EmptyHeap when trying to access item from + * empty heap + */ + template + T MaxHeap::max() { + if (isEmpty()) + throw Exception::EmptyHeap(); + + return data[1]; + } +} // namespace MaxHeap \ No newline at end of file From 1fe7cb8c25b9e4295cd0de3d90dc77c50510ef27 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Thu, 30 Apr 2020 21:16:30 +0530 Subject: [PATCH 084/209] add heap tests --- Heap/Heap/Makefile | 10 +++ Heap/Heap/test_Heap.cpp | 131 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 141 insertions(+) create mode 100644 Heap/Heap/Makefile create mode 100644 Heap/Heap/test_Heap.cpp diff --git a/Heap/Heap/Makefile b/Heap/Heap/Makefile new file mode 100644 index 0000000..41b20b5 --- /dev/null +++ b/Heap/Heap/Makefile @@ -0,0 +1,10 @@ +CC=g++ +GTEST_INCLUDE_PATH=../../googletest/googletest/include/ +GTEST_LIBRARY_PATH=../../googletest/build/lib/ -lgtest -lgtest_main +CCFLAGS=-Wall -std=c++14 + +all: + $(CC) test_Heap.cpp $(CCFLAGS) -I$(GTEST_INCLUDE_PATH) -L$(GTEST_LIBRARY_PATH) + +clean: + rm ./a.out diff --git a/Heap/Heap/test_Heap.cpp b/Heap/Heap/test_Heap.cpp new file mode 100644 index 0000000..2f57c48 --- /dev/null +++ b/Heap/Heap/test_Heap.cpp @@ -0,0 +1,131 @@ +#include +#include + +#include "MaxHeap.hpp" +#include "MinHeap.hpp" + +TEST(MaxHeap, InsertTest) { + Heap::MaxHeap maxheap(5); + ASSERT_TRUE(maxheap.isEmpty()); + ASSERT_EQ(0, maxheap.getSize()); + maxheap.insert(5.3f); + ASSERT_FALSE(maxheap.isEmpty()); + maxheap.insert(10.4f); + maxheap.insert(3.24f); + ASSERT_EQ(3, maxheap.getSize()); + maxheap.insert(1.1f); + maxheap.insert(7.9f); + ASSERT_EQ(5, maxheap.getSize()); + ASSERT_TRUE(maxheap.isFull()); + ASSERT_THROW(maxheap.insert(11.0), Heap::Exception::FullHeap); +} + +TEST(MaxHeap, getSizeTest) { + Heap::MaxHeap maxheap(5); + ASSERT_TRUE(maxheap.isEmpty()); + ASSERT_EQ(0, maxheap.getSize()); + for (int i = 1; i < 6; i++) { + maxheap.insert(i); + ASSERT_EQ(i, maxheap.getSize()); + } + ASSERT_TRUE(maxheap.isFull()); + ASSERT_EQ(5, maxheap.getSize()); +} + +TEST(MaxHeap, MaxTest) { + Heap::MaxHeap maxheap(5); + ASSERT_THROW(maxheap.max(), Heap::Exception::EmptyHeap); + maxheap.insert('e'); + ASSERT_EQ('e', maxheap.max()); + maxheap.insert('c'); + ASSERT_EQ('e', maxheap.max()); + maxheap.insert('f'); + ASSERT_EQ('f', maxheap.max()); + maxheap.insert('x'); + ASSERT_EQ('x', maxheap.max()); + maxheap.insert('t'); + ASSERT_EQ('x', maxheap.max()); +} + +TEST(MaxHeap, ExtractMaxTest) { + Heap::MaxHeap maxheap(5); + ASSERT_THROW(maxheap.extractMax(), Heap::Exception::EmptyHeap); + maxheap.insert(5); + maxheap.insert(1); + maxheap.insert(3); + maxheap.insert(2); + maxheap.insert(4); + for (int i = 5; i > 0; i--) + ASSERT_EQ(i, maxheap.extractMax()); +} + +TEST(MaxHeap, BuildHeapTest) { + int arr[] = {4, 7, 2, 8, 1, 5, 3, 6, 9}; + Heap::MaxHeap maxheap(arr, 9); + for (int i = 9; i > 0; i--) { + ASSERT_EQ(i, maxheap.extractMax()); + } +} + +TEST(MinHeap, InsertTest) { + Heap::MinHeap minheap(5); + ASSERT_TRUE(minheap.isEmpty()); + ASSERT_EQ(0, minheap.getSize()); + minheap.insert(5.3f); + ASSERT_FALSE(minheap.isEmpty()); + minheap.insert(10.4f); + minheap.insert(3.24f); + ASSERT_EQ(3, minheap.getSize()); + minheap.insert(1.1f); + minheap.insert(7.9f); + ASSERT_EQ(5, minheap.getSize()); + ASSERT_TRUE(minheap.isFull()); + ASSERT_THROW(minheap.insert(11.0), Heap::Exception::FullHeap); +} + +TEST(MinHeap, getSizeTest) { + Heap::MinHeap minheap(5); + ASSERT_TRUE(minheap.isEmpty()); + ASSERT_EQ(0, minheap.getSize()); + for (int i = 1; i < 6; i++) { + minheap.insert(i); + ASSERT_EQ(i, minheap.getSize()); + } + ASSERT_TRUE(minheap.isFull()); + ASSERT_EQ(5, minheap.getSize()); +} + +TEST(MinHeap, MinTest) { + Heap::MinHeap minheap(5); + ASSERT_THROW(minheap.min(), Heap::Exception::EmptyHeap); + minheap.insert('f'); + ASSERT_EQ('f', minheap.min()); + minheap.insert('x'); + ASSERT_EQ('f', minheap.min()); + minheap.insert('e'); + ASSERT_EQ('e', minheap.min()); + minheap.insert('c'); + ASSERT_EQ('c', minheap.min()); + minheap.insert('t'); + ASSERT_EQ('c', minheap.min()); +} + +TEST(MinHeap, ExtractMinTest) { + Heap::MinHeap minheap(5); + ASSERT_THROW(minheap.extractMin(), Heap::Exception::EmptyHeap); + minheap.insert(5); + minheap.insert(1); + minheap.insert(3); + minheap.insert(2); + minheap.insert(4); + for (int i = 1; i < 6; i++) + ASSERT_EQ(i, minheap.extractMin()); +} + +TEST(MinHeap, BuildHeapTest) { + int arr[] = {4, 7, 2, 8, 1, 5, 3, 6, 9}; + Heap::MinHeap minheap(arr, 9); + for (int i = 1; i < 10; i++) { + ASSERT_EQ(i, minheap.extractMin()); + } +} \ No newline at end of file From 907aea7a403a148680af615ad441402dcb09ed0d Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sun, 3 May 2020 22:44:22 +0530 Subject: [PATCH 085/209] add quick sort --- Sort/QuickSort.cpp | 68 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 Sort/QuickSort.cpp diff --git a/Sort/QuickSort.cpp b/Sort/QuickSort.cpp new file mode 100644 index 0000000..5a0ee24 --- /dev/null +++ b/Sort/QuickSort.cpp @@ -0,0 +1,68 @@ +/* + * Sorting Algorithms + * Quick Sort (C++ implementation) + * + * QuickSort is a Divide and Conquer algorithm. + * It picks an element as pivot and partitions the given array around the + * picked pivot. It uses last element as pivot element + */ + +#include + +/* Function Declarations */ +template +void QuickSort(T data[], int low, int high); +template +int partition(T data[], int low, int high); + +/* Main Driver Function */ +int main() { + int arr[] = {229, 79, 46, 12, 58, 31, 34, 67, 89, 12, 67, 2}; + int arr_size = sizeof(arr) / sizeof(arr[0]); + + QuickSort(arr, 0, arr_size - 1); + + for (int a: arr) + std::cout << a << " "; + std::cout << "\n"; + + return 0; +} + +/** + * Quick Sort Template Function + * @param data actual array to sort + * @param low lower bound of partial array + * @param high upper bound of partial array + */ +template +void QuickSort(T data[], int low, int high) +{ + if (high <= low) { + return; + } + int j = partition(data, low, high); + QuickSort(data, low, j-1); + QuickSort(data, j+1, high); +} + +/** + * partition return partition index of pivot + * @param data actual array to sort + * @param low lower bound of partial array + * @param high upper bound of partial array +*/ +template +int partition(T data[], int low, int high) +{ + T pivot = data[high]; + int partitionIndex = low; + for (int i = low; i < high; i++) { + if (data[i] <= pivot) { + std::swap(data[i], data[partitionIndex]); + partitionIndex++; + } + } + std::swap(data[high], data[partitionIndex]); + return partitionIndex; +} \ No newline at end of file From 3b679b18dc576024d2562c5e5b075b301e0126e3 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sun, 3 May 2020 22:44:47 +0530 Subject: [PATCH 086/209] add optimized quick sort --- Sort/QuickOptimizeSort.cpp | 124 +++++++++++++++++++++++++++++++++++++ 1 file changed, 124 insertions(+) create mode 100644 Sort/QuickOptimizeSort.cpp diff --git a/Sort/QuickOptimizeSort.cpp b/Sort/QuickOptimizeSort.cpp new file mode 100644 index 0000000..5463b33 --- /dev/null +++ b/Sort/QuickOptimizeSort.cpp @@ -0,0 +1,124 @@ +/* + * Sorting Algorithms + * Quick Sort (C++ implementation) + * + * QuickSort is a Divide and Conquer algorithm. + * It picks an element as pivot and partitions the given array around the + * picked pivot. It uses last element as pivot element + */ + +#include +#define CUTOFF 7 + +/* Function Declarations */ +template +void QuickSort(T data[], int low, int high); +template +int partition(T data[], int low, int high); +template +void InsertionSort(T arr[], int low, int high); +template +int medianOfThree(T data[], int low, int high); + +/* Main Driver Function */ +int main() { + int arr[] = {229, 79, 46, 12, 58, 31, 34, 67, 89, 12, 67, 2}; + int arr_size = sizeof(arr) / sizeof(arr[0]); + + QuickSort(arr, 0, arr_size - 1); + + for (int a: arr) + std::cout << a << " "; + std::cout << "\n"; + + return 0; +} + +/** + * Quick Sort Template Function + * @param data actual array to sort + * @param low lower bound of partial array + * @param high upper bound of partial array + */ +template +void QuickSort(T data[], int low, int high) +{ + if (high <= low) { + return; + } + + // use insertion sort for data set of size <=7 + if (high <= low+CUTOFF-1) { + InsertionSort(data, low, high); + return; + } + + // Use median of Three to find the Pivot index + int median = medianOfThree(data, low, high); + std::swap(data[high], data[median]); + + int j = partition(data, low, high); + QuickSort(data, low, j-1); + QuickSort(data, j+1, high); +} + +/** + * partition return partition index of pivot + * @param data actual array to sort + * @param low lower bound of partial array + * @param high upper bound of partial array +*/ +template +int partition(T data[], int low, int high) +{ + T pivot = data[high]; + int partitionIndex = low; + for (int i = low; i < high; i++) { + if (data[i] <= pivot) { + std::swap(data[i], data[partitionIndex]); + partitionIndex++; + } + } + std::swap(data[high], data[partitionIndex]); + return partitionIndex; +} + +/** + * Insertion Sort Template Function + * @param arr actual array to sort + * @param len size of array + */ +template +void InsertionSort(T arr[], int low, int high) { + for (int i = low; i <= high; i++) { + int index = i; + int value = arr[i]; + while (index > 0 && arr[index-1] > value) { + arr[index] = arr[index-1]; + index--; + } + arr[index] = value; + } +} + +/** + * medianOfThree to return pivot index + * @param data actual array to sort + * @param low lower bound of partial array + * @param high upper bound of partial array +*/ +template +int medianOfThree(T data[], int low, int high) +{ + int mid = (low + high) / 2; + if (data[high] < data[low]) { + std::swap(data[high], data[low]); + } + if (data[low] > data[mid]) { + std::swap(data[mid], data[low]); + } + if (data[mid] > data[high]) { + std::swap(data[high], data[mid]); + } + return mid; +} \ No newline at end of file From 0c621c3625f7687959a01a4b851c07f54e92ca4e Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sun, 3 May 2020 22:45:14 +0530 Subject: [PATCH 087/209] add 3 way quick sort --- Sort/Quick3WaySort.cpp | 65 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 Sort/Quick3WaySort.cpp diff --git a/Sort/Quick3WaySort.cpp b/Sort/Quick3WaySort.cpp new file mode 100644 index 0000000..f573f4d --- /dev/null +++ b/Sort/Quick3WaySort.cpp @@ -0,0 +1,65 @@ +/* + * Sorting Algorithms + * Quick Sort (C++ implementation) + * + * Quick 3Way Sort is a variant of Quick Sort 3-way partitioning. + * 3-way quicksort is optimization which works in specific cases like when + * input to be sorted contains few unique keys, in this case having + * traditional approach of one pivot does not perform well compared to + * 3-way quicksort. + */ + +#include + +/* Function Declarations */ +template +void QuickSort(T data[], int low, int high); + +/* Main Driver Function */ +int main() { + int arr[] = {229, 79, 46, 12, 58, 31, 34, 67, 89, 12, 67, 2}; + int arr_size = sizeof(arr) / sizeof(arr[0]); + + QuickSort(arr, 0, arr_size - 1); + + for (int a: arr) + std::cout << a << " "; + std::cout << "\n"; + + return 0; +} + +/** + * Quick Sort Template Function + * @param data actual array to sort + * @param low lower bound of partial array + * @param high upper bound of partial array + */ +template +void QuickSort(T data[], int low, int high) +{ + if (high <= low) { + return; + } + + int lt = low; + int gt = high; + T pivot = data[low]; + int i = low; + + while (i <= gt) { + if (data[i] < pivot) { + std::swap(data[lt], data[i]); + lt++; + i++; + } else if (data[i] > pivot) { + std::swap(data[gt], data[i]); + gt--; + } else { + i++; + } + } + + QuickSort(data, low, lt-1); + QuickSort(data, gt+1, high); +} From 08fd5a3ba7f26b554e8f670a513e360a75d5aa09 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Mon, 4 May 2020 19:59:08 +0530 Subject: [PATCH 088/209] add quick union dynamic connectivity algorithm --- DynamicConnectivity/QuickUnion.cpp | 93 ++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 DynamicConnectivity/QuickUnion.cpp diff --git a/DynamicConnectivity/QuickUnion.cpp b/DynamicConnectivity/QuickUnion.cpp new file mode 100644 index 0000000..5e96b0f --- /dev/null +++ b/DynamicConnectivity/QuickUnion.cpp @@ -0,0 +1,93 @@ +/** + * Dynamic Connectivity + * + * Given a set of N objects + * - Union Command: connect two objects. + * - Find/connected query: is there a path connecting the two objects? + * + * Quick-Find and Quick-Union are only going to tell us if there is a path + * between two objects. It is not going to give us the complete path. + * + * Connected components: Maximal set of objects that are mutually connected. +*/ +#include + +/** + * QuickUnion (Lazy Approach) + * Data Structure: Integer array id[] of size N + * Interpretation: id[i] is parent of i + * Root/parent of i is id[id[id[...id[i]...]]] + * + * QuickUnion defect: + * - Trees can get too tall + * - Find too expensive (could be N array accesses) +*/ +class QuickUnion { +private: + int size; + int* id; + + /** + * Finding the root of element + * @param elem element of which root is needed + * @return root of elem + */ + int root(int elem) { + while (elem != id[elem]) + elem = id[elem]; + return elem; + } + +public: + /** + * Initializing list of size n where value is same as index + * Time Complexity: O(n) + * @param n number of elements + */ + QuickUnion(int n): size(n) { + id = new int[n]; + for (int i = 0; i < size; i++) + id[i] = i; + } + + /** + * p and q are connected iff they have same root + * @param p element 1 + * @param q element 2 + * @return true iff two p and q are connected, else false + */ + bool connected(int p, int q) { + return root(p) == root(q); + } + + /** + * To merge components containing p and q, set the id of p's + * root to the id of q's root + * @param p element 1 + * @param q element 2 + */ + void joinUnion(int p, int q) { + int i = root(p); + int j = root(q); + id[i] = j; + } +}; + +/* Main Driver Function */ +int main() +{ + QuickUnion quickUnion(10); + quickUnion.joinUnion(4, 3); + quickUnion.joinUnion(3, 8); + quickUnion.joinUnion(6, 5); + quickUnion.joinUnion(9, 4); + quickUnion.joinUnion(2, 1); + std::cout << "is 0 connected to 7? " << quickUnion.connected(0, 7) << "\n"; + std::cout << "is 8 connected to 9? " << quickUnion.connected(8, 9) << "\n"; + quickUnion.joinUnion(5, 0); + quickUnion.joinUnion(7, 2); + quickUnion.joinUnion(6, 1); + quickUnion.joinUnion(1, 0); + std::cout << "is 0 connected to 7? " << quickUnion.connected(0, 7) << "\n"; + return 0; +} \ No newline at end of file From 2a1de7d627cd112ff5b1d5c328ad1891ee67c469 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Wed, 6 May 2020 09:27:23 +0530 Subject: [PATCH 089/209] add weighted quick union dymanic connectivity algorithm --- DynamicConnectivity/WeightedQuickUnion.cpp | 115 +++++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 DynamicConnectivity/WeightedQuickUnion.cpp diff --git a/DynamicConnectivity/WeightedQuickUnion.cpp b/DynamicConnectivity/WeightedQuickUnion.cpp new file mode 100644 index 0000000..2a5c7eb --- /dev/null +++ b/DynamicConnectivity/WeightedQuickUnion.cpp @@ -0,0 +1,115 @@ +/** + * """ QuickFind and QuickUnion algorithms are easy to implement, + * but simply can't support huge dynamic connectivity problems. + * + * Improvement 1: Weighting + * - modify quick union to avoid tall trees + * - keep track of size of each tree (number of objects) + * - balance by linking root of smaller tree to root of larger tree + * + * Improvement 2: Path Compression + * Just after computing the root of p, set the id of each examined node to + * point to that root. + * + * Implementation of path compression: + * - Two-pass Implementation: add second loop to root() to set the id[] of each + * examined node to the root. + * - Simpler one-pass variant: Make every other node in path point to its + * grandparent (thereby halving path length) [implmented in this script] +*/ + +/** + * Optimized version of Quick Union + * Same as quick-union, but maintain extra array sz_count[i] to count + * number of objects in the tree rooted at i +*/ +#include + +class WeightedQuickUnion { +private: + int size; + int* id; + int* sz; + + /** + * Finding the root of element + * @param elem element of which root is needed + * @return root of elem + */ + int root(int elem) { + while (elem != id[elem]) { + // path compression optimization + id[elem] = id[id[elem]]; + elem = id[elem]; + } + return elem; + } + +public: + /** + * Initializing list of size n where value is same as index. + * Here it means that each node is a root of it's own tree + * Time Complexity: O(n) + * @param n number of elements + */ + WeightedQuickUnion(int n): size(n) { + id = new int[n]; + sz = new int[n]; + for (int i = 0; i < size; i++) { + id[i] = i; + sz[i] = 0; + } + } + + /** + * p and q are connected iff they have same root + * @param p element 1 + * @param q element 2 + * @return true iff two p and q are connected, else false + */ + bool connected(int p, int q) { + return root(p) == root(q); + } + + /** + * To merge components containing p and q, set the id of p's + * root to the id of q's root + * modify quick-union to: + * - link root of smaller tree to root of larger tree + * - update the sz_count[] array + * Time complexity is lg N. Depth of any node x is at most lg N. + * @param p element 1 + * @param q element 2 + */ + void joinUnion(int p, int q) { + int i = root(p); + int j = root(q); + if (i == j) return; + if (sz[i] < sz[j]) { + id[i] = j; + sz[j] += sz[i]; + } else { + id[j] = id[i]; + sz[i] += sz[j]; + } + } +}; + +/* Main Driver Function */ +int main() +{ + WeightedQuickUnion weightedQuickUnion(10); + weightedQuickUnion.joinUnion(4, 3); + weightedQuickUnion.joinUnion(3, 8); + weightedQuickUnion.joinUnion(6, 5); + weightedQuickUnion.joinUnion(9, 4); + weightedQuickUnion.joinUnion(2, 1); + std::cout << "is 0 connected to 7? " << weightedQuickUnion.connected(0, 7) << "\n"; + std::cout << "is 8 connected to 9? " << weightedQuickUnion.connected(8, 9) << "\n"; + weightedQuickUnion.joinUnion(5, 0); + weightedQuickUnion.joinUnion(7, 2); + weightedQuickUnion.joinUnion(6, 1); + weightedQuickUnion.joinUnion(1, 0); + std::cout << "is 0 connected to 7? " << weightedQuickUnion.connected(0, 7) << "\n"; + return 0; +} \ No newline at end of file From 06366fc029101b4a1121ac846b2f85b3477cc116 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Wed, 6 May 2020 09:27:49 +0530 Subject: [PATCH 090/209] add heap sort --- Sort/HeapSort.cpp | 86 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 Sort/HeapSort.cpp diff --git a/Sort/HeapSort.cpp b/Sort/HeapSort.cpp new file mode 100644 index 0000000..b8edb31 --- /dev/null +++ b/Sort/HeapSort.cpp @@ -0,0 +1,86 @@ +/* + * Sorting Algorithms + * Heap Sort (C++ implementation) + * + * HeapSort is a comparison based sorting technique based on Binary Heap + * data structure. It is similar to selection sort where we first find the + * maximum element and place the maximum element at the end. We repeat the + * same process for remaining element. Heap Sort is not stable, In-place + * sorting algorithm with guarantee NlogN time complexity in worst-case. + */ + +#include + +/* Function declarations */ +template +void HeapSort(T data[], int dataLen); +template +void heapify(T data[], int root, int length); +template +void buildHeap(T data[], int dataLen); + +/* Main Driver Function */ +int main() { + char arr[] = {'d', 't', 'a', 'b', 'q', 'z', 'd', 'e', 'x'}; + int arr_size = sizeof(arr) / sizeof(arr[0]); + + HeapSort(arr, arr_size); + + for (char a: arr) + std::cout << a << " "; + std::cout << "\n"; + + return 0; +} + +/** + * Heap Sort Template Function + * @param data actual array to sort + * @param dataLen size of array + */ +template +void HeapSort(T data[], int dataLen) +{ + buildHeap(data, dataLen); + for (int i = dataLen - 1; i > 0; i--) { + std::swap(data[0], data[i]); + heapify(data, 0, i); + } +} + +/* heapify maintains the heap invariant (property) */ +template +void heapify(T data[], int root, int length) +{ + int max = root; + int left = 2 * root + 1; + int right = 2 * root + 2; + + if (left < length && data[left] > data[max]) { + max = left; + } + + if (right < length && data[right] > data[max]) { + max = right; + } + + if (max != root) { + std::swap(data[root], data[max]); + heapify(data, max, length); + } +} + +/** + * buildHeap builds heap structure from an unorganized data list + * Time complexity of building a heap is O(n) + * @param data actual array to sort + * @param dataLen size of array +*/ +template +void buildHeap(T data[], int dataLen) +{ + for (int i = dataLen / 2; i >= 0; i--) { + heapify(data, i, dataLen); + } +} + From 8f5d4ade0ce22bea3ee8addc2c13691e0e53b46c Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Thu, 7 May 2020 12:27:08 +0530 Subject: [PATCH 091/209] add bst inorder successor algo --- BinarySearchTree/inorderSuccessor.cpp | 88 +++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 BinarySearchTree/inorderSuccessor.cpp diff --git a/BinarySearchTree/inorderSuccessor.cpp b/BinarySearchTree/inorderSuccessor.cpp new file mode 100644 index 0000000..c3fc975 --- /dev/null +++ b/BinarySearchTree/inorderSuccessor.cpp @@ -0,0 +1,88 @@ +/** + * In Binary Tree, Inorder successor of a node is the next node in Inorder + * traversal of the Binary Tree. Inorder Successor is NULL for the last node + * in Inoorder traversal. + * In Binary Search Tree, Inorder Successor of an input node can also be + * defined as the node with the smallest key greater than the key of input + * node. So, it is sometimes important to find next node in sorted order. +*/ +#include +#include "BST/BST.hpp" + +/* Functional Declaration */ +Node* inorderSuccessor(BST& tree, int value); +Node* findMinNode(Node* node); + +/* Main Operational Function */ +int main() +{ + BST tree; + int original[] = { 9, 5, 3, 10, 6, 1, 7, 4 }; + for (int i : original) + tree.insert(i); + + std::cout << "inorder successor of 1: " << inorderSuccessor(tree, 1)->data << "\n"; + std::cout << "inorder successor of 2: "; + if (inorderSuccessor(tree, 2) == nullptr) std::cout << "nullptr\n"; + else std::cout << "not nullptr\n"; + std::cout << "inorder successor of 3: " << inorderSuccessor(tree, 3)->data << "\n"; + std::cout << "inorder successor of 4: " << inorderSuccessor(tree, 4)->data << "\n"; + std::cout << "inorder successor of 5: " << inorderSuccessor(tree, 5)->data << "\n"; + std::cout << "inorder successor of 6: " << inorderSuccessor(tree, 6)->data << "\n"; + std::cout << "inorder successor of 7: " << inorderSuccessor(tree, 7)->data << "\n"; + std::cout << "inorder successor of 8: "; + if (inorderSuccessor(tree, 8) == nullptr) std::cout << "nullptr\n"; + else std::cout << "not nullptr\n"; + std::cout << "inorder successor of 9: " << inorderSuccessor(tree, 9)->data << "\n"; + std::cout << "inorder successor of 10: "; + if (inorderSuccessor(tree, 10) == nullptr) std::cout << "nullptr\n"; + else std::cout << "not nullptr\n"; + return 0; +} + +/** + * find the node with minimum value of give (sub)tree + * @param node root of sub(tree) + * @return node with minimum value +*/ +Node* findMinNode(Node* node) +{ + while (node->left != nullptr) + node = node->left; + return node; +} + +/** + * get inorder successor for given value in binary search tree + * @param value input value of which inorder successor is required + * @return inorder successor of given value +*/ +Node* inorderSuccessor(BST& tree, int value) +{ + Node* current = tree.getRoot(); + + while (current != nullptr && current->data != value) { + if (current->data > value) + current = current->left; + else if (current->data < value) + current = current->right; + } + if (current == nullptr) + return nullptr; + + if (current->right != nullptr) { + return findMinNode(current->right); + } else { + Node* successor = nullptr; + Node* ancestor = tree.getRoot(); + while(ancestor != current) { + if (current->data < ancestor->data) { + successor = ancestor; + ancestor = ancestor->left; + } else { + ancestor = ancestor->right; + } + } + return successor; + } +} From 046dfd520397d61b07761254321b4669e67c1922 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Fri, 8 May 2020 21:49:12 +0530 Subject: [PATCH 092/209] update readme --- README.md | 86 +++++++++++++++++++++++++++++++------------------------ 1 file changed, 48 insertions(+), 38 deletions(-) diff --git a/README.md b/README.md index c4d4d18..8716e79 100644 --- a/README.md +++ b/README.md @@ -1,57 +1,67 @@ # Algorithms -Data Structure Libraries and Algorithms implementation in Go - -[![GoDoc](https://godoc.org/github.com/x899/algorithms?status.svg)](https://godoc.org/github.com/x899/algorithms) [![Go Report Card](https://goreportcard.com/badge/github.com/x899/algorithms)](https://goreportcard.com/report/github.com/x899/algorithms) +Data Structure Libraries and Algorithms implementation in C++ **Disclaimer**
This repository is meant to be used as a reference to learn data structure and -algorithm in Go programming language.
To reduce unnecessary language -complexity, all the programs only uses integer or string dataset. - -**Documentation**
-[Click to view goDoc Documentation](https://godoc.org/github.com/x899/algorithms) +algorithm. ## Data structure -* Sorting Algorithms - * [Bubble Sort](https://en.wikipedia.org/wiki/Bubble_sort) - * [Selection Sort](https://en.wikipedia.org/wiki/Selection_sort) - * [Insertion Sort](https://en.wikipedia.org/wiki/Insertion_sort) - * [Merge Sort](https://en.wikipedia.org/wiki/Merge_sort) - * [Quick Sort](https://en.wikipedia.org/wiki/Quicksort) - * [Quick Select](https://en.wikipedia.org/wiki/Quickselect) - * [Shell Sort](https://en.wikipedia.org/wiki/Shellsort) - * [Heap Sort](https://en.wikipedia.org/wiki/Heapsort) -* [Stack (Array Implementation)](https://en.wikipedia.org/wiki/Stack_(abstract_data_type)) - * Infix to Postfix - * Infix to Prefix - * Infix Evaluation -* [Queue (Array Implementation)](https://en.wikipedia.org/wiki/Queue_(abstract_data_type)) -* LinkedList - * [Singly Linked List](https://en.wikipedia.org/wiki/Linked_list) - * [Doubly Linked List](https://en.wikipedia.org/wiki/Doubly_linked_list) -* [Shuffle (Using Fisher-Yates (Knuth) shuffling algorithm)](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) -* [Binary Search Tree](https://en.wikipedia.org/wiki/Binary_search_tree) -* [Binary Heap](https://en.wikipedia.org/wiki/Binary_heap) - * Min Heap - * Max Heap -* [Red Black Tree](https://en.wikipedia.org/wiki/Red%E2%80%93black_tree) +* [Dynamic Connectivity](DynamicConnectivity/) + * [Quick Find](DynamicConnectivity/QuickFind.cpp) + * [Quick Union](DynamicConnectivity/QuickUnion.cpp) + * [Weighted Quick Union](DynamicConnectivity/WeightedQuickUnion.cpp) +* [Sorting Algorithms](Sort/) + * [Bubble Sort](Sort/BubbleSort.cpp) + * [Counting Sort](Sort/CountingSort.cpp) + * [Gnome Sort](Sort/GnomeSort.cpp) + * [Heap Sort](Sort/HeapSort.cpp) + * [Insertion Sort](Sort/InsertionSort.cpp) + * [Merge Sort](Sort/MergeSort.cpp) + * [Merge Bottom Up Sort](Sort/MergeButtomUp.cpp) + * [Merge Optimize Sort](Sort/MergeOptimizeSort.cpp) + * [Odd Even Sort](Sort/OddEvenSort.cpp) + * [Quick Sort](Sort/QuickSort.cpp) + * [Quick 3Way Sort](Sort/Quick3WaySort.cpp) + * [Quick Optimize Sort](Sort/QuickOptimizeSort.cpp) + * [Quick Select](Sort/QuickSelect.cpp) + * [Selection Sort](Sort/SelectionSort.cpp) + * [Shell Sort](Sort/ShellSort.cpp) +* [Stack (Array Implementation)](Stack/Stack/) + * [Balanced Paranthesis](Stack/balancedParanthesis.cpp) + * [Infix to Prefix](Stack/infixToPostfix.cpp) + * [Track Current Maximum](Stack/trackingCurrentMax.cpp) +* [Queue (Array Implementation)](Queue/Queue/) + * [Reverse Queue](Queue/ReverseQueue.cpp) + * [Sort Queue Without Extra Space](Queue/SortQueueWithoutExtraSpace.cpp) +* [LinkedList](LinkedList/LinkedList) + * [Count Frequency](LinkedList/countFrequency.cpp) + * [Detect Loop](LinkedList/detectLoop.cpp) + * [Find Middle](LinkedList/findMiddle.cpp) + * [Get Nth Node from End](LinkedList/getNthNodeFromEnd.cpp) + * [Length of Loop](LinkedList/lengthOfLoop.cpp) +* Suffle + * [Using Fisher-Yates (Knuth) shuffling algorithm](Shuffle/Shuffle.cpp) +* [Binary Search Tree](BinarySearchTree/BST/) + * [BFS Traversal](BinarySearchTree/bfsTraversal.cpp) + * [DFS Traversal](BinarySearchTree/dfsTraversal.cpp) + * [Inorder Successor](BinarySearchTree/inorderSuccessor.cpp) + * [Is BST?](BinarySearchTree/isBST.cpp) +* [Binary Heap](Heap/Heap) + * [Min Heap](Heap/Heap/MinHeap.cpp) + * [Max Heap](Heap/Heap/MaxHeap.cpp) * Search - * [Binary Search](https://en.wikipedia.org/wiki/Binary_search_algorithm) + * [Binary Search](Search/BinarySearch.h) ## TO DO * Vertical Order Traversal of Tree * Order Statistics of Tree -* Red Black Tree Deletion -* B-Tree +* Red Black Tree * Deque using circular array * Tree Varient * Graph Varient * [cocktail sort](https://en.wikipedia.org/wiki/Cocktail_shaker_sort) -* [gnome sort](https://en.wikipedia.org/wiki/Gnome_sort) * [comb sort](https://en.wikipedia.org/wiki/Comb_sort) -* [odd-even sort](https://en.wikipedia.org/wiki/Odd%E2%80%93even_sort) -* [counting sort](https://en.wikipedia.org/wiki/Counting_sort) ## Contribution Feel Free to contribute.
-Please follow standard GoLang Guidelines. +Please follow standard C++ Guidelines. From f6565f0831928c0052eec5845a6b5f51969a7075 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sat, 9 May 2020 22:16:45 +0530 Subject: [PATCH 093/209] add sort queue without extra space --- Queue/SortQueueWithoutExtraSpace.cpp | 78 ++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 Queue/SortQueueWithoutExtraSpace.cpp diff --git a/Queue/SortQueueWithoutExtraSpace.cpp b/Queue/SortQueueWithoutExtraSpace.cpp new file mode 100644 index 0000000..07b4b81 --- /dev/null +++ b/Queue/SortQueueWithoutExtraSpace.cpp @@ -0,0 +1,78 @@ +/** + * Given a queue with random elements, we need to sort it. We are not allowed + * to use extra space. The operations allowed on queue are: + * enqueue(): Adds an item to rear of queue + * dequeue(): Removes an item from front of queue. + * isEmpty(): Checks if a queue is empty. + * + * URL: https://www.geeksforgeeks.org/sorting-queue-without-extra-space/ + * CMD: g++ -Wall -std=c++14 SortQueueWithoutExtraSpace.cpp +*/ +#include +#include +#include "Queue/Queue.hpp" + +/* Function Declarations */ +int getMinIndex(Queue::Queue& queue, int sortedIndex); +void insertMinToRear(Queue::Queue& queue, int minIndex); +void sortQueue(Queue::Queue& queue); + +/* Main Operational Function */ +int main() +{ + Queue::Queue queue; + queue.enqueue(11); + queue.enqueue(5); + queue.enqueue(4); + queue.enqueue(21); + + std::cout << "Original "; + queue.display(); + + sortQueue(queue); + + std::cout << "Sorted "; + queue.display(); + + return 0; +} + +void sortQueue(Queue::Queue& queue) +{ + int n = queue.size(); + for (int i = 1; i <= n; i++) { + int minIndex = getMinIndex(queue, i); + insertMinToRear(queue, minIndex); + } +} + +int getMinIndex(Queue::Queue& queue, int sortedIndex) +{ + int minValue = INT_MAX; + int minIndex = -1; + int n = queue.size(); + + for (int i = 0; i < n; i++) { + int value = queue.dequeue(); + if (value <= minValue && i <= (n-sortedIndex)) { + minValue = value; + minIndex = i; + } + queue.enqueue(value); + } + return minIndex; +} + +void insertMinToRear(Queue::Queue& queue, int minIndex) +{ + int n = queue.size(); + int minValue; + for (int i = 0; i < n; i++) { + int value = queue.dequeue(); + if (i == minIndex) + minValue = value; + else + queue.enqueue(value); + } + queue.enqueue(minValue); +} From c9fdff816807d3609627cc1e86dae6007bd0734b Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Tue, 12 May 2020 20:05:37 +0530 Subject: [PATCH 094/209] check binary search tree algo --- BinarySearchTree/isBST.cpp | 61 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 BinarySearchTree/isBST.cpp diff --git a/BinarySearchTree/isBST.cpp b/BinarySearchTree/isBST.cpp new file mode 100644 index 0000000..117ddb0 --- /dev/null +++ b/BinarySearchTree/isBST.cpp @@ -0,0 +1,61 @@ +/** + * check whether the given binary tree is Binary Search Tree or not. +*/ +#include +#include +#include "BST/BST.hpp" + +/* Function Declarations */ +bool isBST(Node* root); +bool isBSTUtil(Node* root, int minValue, int maxValue); + +/* Main Operational Function */ +int main() +{ + BST tree1; + int original[] = { 9, 5, 3, 10, 6, 1, 7, 4 }; + for (int i : original) + tree1.insert(i); + std::cout << "is tree1 bst? " << isBST(tree1.getRoot()) << "\n"; + + BST tree2; + tree2.insert(5); + Node* root = tree2.getRoot(); + root->right = new Node(7); + root->left = new Node(3); + root->left->left = new Node(1); + root->left->right = new Node(4); + root->right->right = new Node(6); + std::cout << "is tree2 bst? " << isBST(tree2.getRoot()) << "\n"; + + return 0; +} + +/** + * checks if binary tree is BST + * @param root root of binary (sub)tree + * @return true if binary (sub)tree is BST, else false +*/ +bool isBST(Node* root) +{ + return isBSTUtil(root, INT_MIN, INT_MAX); +} + +/** + * binary search tree check utility function + * @param root root of binary (sub)tree + * @param minValue tree nodes should be greater than minValue + * @param maxValue tree nodes should be less than maxValue + * @return true if binary (sub)tree is BST, else false +*/ +bool isBSTUtil(Node* root, int minValue, int maxValue) +{ + if (root == nullptr) + return true; + + if (root->data >= minValue && root->data < maxValue + && isBSTUtil(root->left, minValue, root->data) + && isBSTUtil(root->right, root->data, maxValue)) + return true; + return false; +} From d153583d203c49f487f371a33e36c0bbbe8f53b0 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Wed, 13 May 2020 12:20:07 +0530 Subject: [PATCH 095/209] stack delete middle element --- Stack/deleteMiddleElement.cpp | 42 +++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Stack/deleteMiddleElement.cpp diff --git a/Stack/deleteMiddleElement.cpp b/Stack/deleteMiddleElement.cpp new file mode 100644 index 0000000..e0b3a4f --- /dev/null +++ b/Stack/deleteMiddleElement.cpp @@ -0,0 +1,42 @@ +/** + * Delete middle element of a stack without using any additional + * data structure. + * URL: https://www.geeksforgeeks.org/delete-middle-element-stack/ + * CMD: g++ -std=c++14 -Wall deleteMiddleElement.cpp +*/ + +#include +#include "Stack/Stack.hpp" + +/* function declarations */ +void deleteMiddle(Stack::Stack &stack, int n, int curr=0); + +/* main driver function */ +int main() +{ + Stack::Stack stack; + for (int i = 1; i < 11; i++) + stack.push(i); + + stack.display(); + deleteMiddle(stack, stack.size()); + std::cout << "after deleting middle element\n"; + stack.display(); +} + +void deleteMiddle(Stack::Stack &stack, int n, int curr) +{ + // if stack is empty or all items are traversed + if (stack.isEmpty() || curr == n) + return; + + // remove current item + int x = stack.pop(); + + // remove other items + deleteMiddle(stack, n, curr+1); + + // put all items back except middle + if (curr != n/2) + stack.push(x); +} From ea7a8243407c8e1d9da6fc74677b75d708c5487d Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Wed, 13 May 2020 14:24:55 +0530 Subject: [PATCH 096/209] add stack bracket reversal --- Stack/bracketReversals.cpp | 57 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Stack/bracketReversals.cpp diff --git a/Stack/bracketReversals.cpp b/Stack/bracketReversals.cpp new file mode 100644 index 0000000..2fb025b --- /dev/null +++ b/Stack/bracketReversals.cpp @@ -0,0 +1,57 @@ +/** + * Minimum number of bracket reversals needed to make an expression balanced + * Given an expression with only '}' and '{'. The expression may not be + * balanced. Find minimum number of bracket reversals to make the expression + * balanced. + * URL: https://www.geeksforgeeks.org/minimum-number-of-bracket-reversals- + * needed-to-make-an-expression-balanced/ + * CMD: g++ -Wall -std=c++14 bracketReversals.cpp +*/ + +#include +#include "Stack/Stack.hpp" + +/* function declarations */ +int countMinReversals(std::string expression); + +/* main driver function */ +int main() +{ + std::string expression = "}{{}}{{{"; + std::cout << countMinReversals(expression) << "\n"; + return 0; +} + +int countMinReversals(std::string expression) +{ + int len = expression.length(); + + // length of expression must be even to make it balanced by using reversals. + if (len % 2) return -1; + + // After this loop, stack contains unbalanced part of expression, i.e., + //expression of theform "}}..}{{..{" + Stack::Stack stack; + for (char c: expression) { + if (c == '}' && !stack.isEmpty()) { + if (stack.peek()=='{') + stack.pop(); + else stack.push(c); + } else stack.push(c); + } + + // Length of the reduced expression + // red_len = (m+n) + int red_len = stack.size(); + + // count opening brackets at the end of stack + int n = 0; + while (!stack.isEmpty() && stack.peek() == '{') { + stack.pop(); + n++; + } + + // return ceil(m/2) + ceil(n/2) which is actually equal to (m+n)/2 + n%2 + // when m+n is even. + return (red_len / 2 + n % 2); +} \ No newline at end of file From 709c20a60ee7a6f1b41b988af3464aa3252794be Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Thu, 14 May 2020 09:09:57 +0530 Subject: [PATCH 097/209] add red black tree find, find max and find min method --- RedBlackTree/RedBlackTree.cpp | 63 +++++++++++++++++++++++++ RedBlackTree/RedBlackTree.hpp | 86 +++++++++++++++++++++++++++++++++++ 2 files changed, 149 insertions(+) create mode 100644 RedBlackTree/RedBlackTree.cpp create mode 100644 RedBlackTree/RedBlackTree.hpp diff --git a/RedBlackTree/RedBlackTree.cpp b/RedBlackTree/RedBlackTree.cpp new file mode 100644 index 0000000..6a7fff2 --- /dev/null +++ b/RedBlackTree/RedBlackTree.cpp @@ -0,0 +1,63 @@ +#include +#include "RedBlackTree.hpp" + +/** + * find the element in red black tree + * @param data item to be searched +*/ +bool RedBlackTree::find(int data) { + if (root == nullptr) + return false; + + return find(root, data); +} + +/** + * find is an recursive internal method which works at node level + * @param root root of tree/sub-tre + * @param data item to be searched +*/ +bool RedBlackTree::find(Node* node, int data) { + if (root == nullptr) + return false; + + if (data == root->data) return true; + else if (data < root->data) return find(root->left, data); + else return find(root->right, data); +} + +/** + * returns left-most item present in red black tree which is also + * the minimum element in red black tree + * @return minimum element present in red black tree +*/ +int RedBlackTree::min() +{ + Node* root = getRoot(); + if (root == nullptr) + throw EmptyTree(); + + Node* current = root; + while (current->left != nullptr) + current = current->left; + + return current->data; +} + +/** + * returns right-most item present in red black tree which is also + * the maximum element in red black tree + * @return maximum element present in red black tree +*/ +int RedBlackTree::max() +{ + Node* root = getRoot(); + if (root == nullptr) + throw EmptyTree(); + + Node* current = root; + while (current->right != nullptr) + current = current->right; + + return current->data; +} \ No newline at end of file diff --git a/RedBlackTree/RedBlackTree.hpp b/RedBlackTree/RedBlackTree.hpp new file mode 100644 index 0000000..aacbfeb --- /dev/null +++ b/RedBlackTree/RedBlackTree.hpp @@ -0,0 +1,86 @@ +/* + * Red Black Tree is an implementation for left leaning red black tree + * data structure in go language. + * + * Red-Black Tree is a self-balancing Binary Search Tree (BST) where every node + * has a color either red or black. Root of tree is always black. There are no + * two adjacent red nodes (A red node cannot have a red parent or red child). + * Every path from a node (including root) to any of its descendant NULL node has + * the same number of black nodes. + * + * Why Red-Black Trees + * + * Most of the BST operations (e.g., search, max, min, insert, delete.. etc) + * take O(h) time where h is the height of the BST. The cost of these + * operations may become O(n) for a skewed Binary tree. If we make sure that + * height of the tree remains O(Logn) after every insertion and deletion, then + * we can guarantee an upper bound of O(Logn) for all these operations. The + * height of a Red-Black tree is always O(Logn) where n is the number of nodes + * in the tree. + * + * The main problem with BST deletion (Hibbard Deletion) is that It is not + * symmetric. After many insertion and deletion BST become less balance. + * Researchers proved that after sufficiently long number of random insert + * and delete height of the tree becomes sqrt(n) .So now every operation + * (search, insert, delete) will take sqrt(n) time which is not good compare + * to O(logn) . + * + * This is very long standing(around 50 years) open problem to efficient + * symmetric delete for BST. for guaranteed balanced tree, we have to use + * RedBlack Tree etc. + * + * Properties + * - No Node has two red links connected to it. + * - Every path from root to null link has the same number of black links. + * - Red links lean left. +*/ + +#ifndef RBTREE_H +#define RBTREE_H + +#include + +class EmptyTree : public std::exception { + const char* what() const throw() { + return "tree is empty"; + } +}; + +// Red Black Node contains actual data and color bit along with links to left, +// right, parent node +struct Node { + int data; + int color; + Node* left; + Node* right; + Node* parent; + + Node(int _data, int _color) { + data = _data; + color = _color; + left = nullptr; + right = nullptr; + parent = nullptr; + } +}; + +class RedBlackTree { +private: + Node* root; + bool find(Node* node, int data); + // void deleteTreeRecursive(Node* node); + // void leftRotate(Node* node); + // void rightRotate(Node* node); + // void replaceNode(Node* node); + +public: + RedBlackTree() { root = nullptr; } + // ~RedBlackTree() { deleteTreeRecursive(root); } + Node* getRoot() { return root; } + // void insert(int data); + bool find(int data); + int min(); + int max(); +}; + +#endif \ No newline at end of file From b183f22b6dd6d531ee90600e106aa1443ab4e31e Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sun, 17 May 2020 23:03:28 +0530 Subject: [PATCH 098/209] add quick select algorithm --- Sort/QuickSelect.cpp | 125 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 125 insertions(+) create mode 100644 Sort/QuickSelect.cpp diff --git a/Sort/QuickSelect.cpp b/Sort/QuickSelect.cpp new file mode 100644 index 0000000..8dfd87f --- /dev/null +++ b/Sort/QuickSelect.cpp @@ -0,0 +1,125 @@ +/* + * Sorting Algorithms + * Quick Sort (C++ implementation) + * + * QuickSort is a Divide and Conquer algorithm. + * It picks an element as pivot and partitions the given array around the + * picked pivot. It uses last element as pivot element + */ + +#include +#define CUTOFF 7 + +/* Function Declarations */ +template +T QuickSelect(T data[], int dataLen, int key); +template +int partition(T data[], int low, int high); +template +int medianOfThree(T data[], int low, int high); +template +void Shuffle(T arr[], int len); + +/* Main Driver Function */ +int main() { + int arr[] = {229, 79, 46, 12, 58, 31, 34, 67, 89, 12, 67, 2}; + // char arr[] = {'d', 't', 'a', 'b', 'q', 'z', 'd', 'e', 'x'}; + int arr_size = sizeof(arr) / sizeof(arr[0]); + + int result = QuickSelect(arr, arr_size, 3); + std::cout << "3rd sorted element is " << result << "\n"; + return 0; +} + +/** + * Shuffle Array Template Function + * @param arr actual array to sort + * @param len size of array + */ +template +void Shuffle(T arr[], int len) +{ + // use current time as seed for random generator + std::srand(std::time(nullptr)); + for (int i = 0; i < len; i++) { + int r = rand() % (i + 1); + std::swap(arr[i], arr[r]); + } +} + + +/** + * Quick Sort Template Function + * @param data actual array to sort + * @param dataLen size of actual array + * @param key index of which sorted element is required + */ +template +T QuickSelect(T data[], int dataLen, int key) +{ + if (key >= dataLen) { + return -1; + } + + Shuffle(data, dataLen); + int low = 0; + int high = dataLen - 1; + + while (high > low) { + int j = partition(data, low, high); + if (j < key) { + low = j + 1; + } else if (j > key) { + high = j - 1; + } else { + return data[key]; + } + } + return data[key]; +} + +/** + * partition return partition index of pivot + * @param data actual array to sort + * @param low lower bound of partial array + * @param high upper bound of partial array +*/ +template +int partition(T data[], int low, int high) +{ + int median = medianOfThree(data, low, high); + std::swap(data[median], data[high]); + + T pivot = data[high]; + int partitionIndex = low; + for (int i = low; i < high; i++) { + if (data[i] <= pivot) { + std::swap(data[i], data[partitionIndex]); + partitionIndex++; + } + } + std::swap(data[high], data[partitionIndex]); + return partitionIndex; +} + +/** + * medianOfThree to return pivot index + * @param data actual array to sort + * @param low lower bound of partial array + * @param high upper bound of partial array +*/ +template +int medianOfThree(T data[], int low, int high) +{ + int mid = (low + high) / 2; + if (data[high] < data[low]) { + std::swap(data[high], data[low]); + } + if (data[low] > data[mid]) { + std::swap(data[mid], data[low]); + } + if (data[mid] > data[high]) { + std::swap(data[high], data[mid]); + } + return mid; +} \ No newline at end of file From e3c2857826bde9196c2c5e05e70fa9073d199895 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Fri, 22 May 2020 21:18:01 +0530 Subject: [PATCH 099/209] add odd even sort --- Sort/OddEvenSort.cpp | 58 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Sort/OddEvenSort.cpp diff --git a/Sort/OddEvenSort.cpp b/Sort/OddEvenSort.cpp new file mode 100644 index 0000000..090f1f6 --- /dev/null +++ b/Sort/OddEvenSort.cpp @@ -0,0 +1,58 @@ +/* + * Sorting Algorithms + * OddEven Sort (C++ implementation) + * + * OddEvenSort is a variation of bubble sort where the sorting is divided into + * two phases, Odd and Even Phase and it runs until all the elements are sorted + * In the odd phase we perform bubble sort on odd indexed elements and in the + * even phase we perform bubble sort on even indexed elements. + */ + +#include + +/* Function Declarations */ +template +void OddEvenSort(T data[], int dataLen); + +/* Main Driver Function */ +int main() { + int arr[] = {229, 79, 46, 12, 58, 31, 34, 67, 89, 12, 67, 2}; + int arr_size = sizeof(arr) / sizeof(arr[0]); + + OddEvenSort(arr, arr_size); + + for (int a: arr) + std::cout << a << " "; + std::cout << "\n"; + + return 0; +} + +/** + * Odd Even Sort Template Function + * @param data actual array to sort + * @param dataLen size of array + */ +template +void OddEvenSort(T data[], int dataLen) { + bool sorted = false; + + while (true) { + sorted = true; + for (int i = 1; i < dataLen-1; i += 2) { + if (data[i] > data[i+1]) { + std::swap(data[i], data[i+1]); + sorted = false; + } + } + for (int i = 0; i < dataLen-1; i += 2) { + if (data[i] > data[i+1]) { + std::swap(data[i], data[i+1]); + sorted = false; + } + } + if (sorted) { + break; + } + } +} \ No newline at end of file From 4bce9649875af5d1a99ca2365a76cf07021be4d4 Mon Sep 17 00:00:00 2001 From: Rishabh Thakur Date: Thu, 1 Oct 2020 08:45:18 +0530 Subject: [PATCH 100/209] Adding a new component --- BinarySearchTree/Nqueen | 108 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 BinarySearchTree/Nqueen diff --git a/BinarySearchTree/Nqueen b/BinarySearchTree/Nqueen new file mode 100644 index 0000000..0f0e85a --- /dev/null +++ b/BinarySearchTree/Nqueen @@ -0,0 +1,108 @@ +/* C/C++ program to solve N Queen Problem using + backtracking */ +#define N 4 +#include +#include + +/* A utility function to print solution */ +void printSolution(int board[N][N]) +{ + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) + printf(" %d ", board[i][j]); + printf("\n"); + } +} + +/* A utility function to check if a queen can + be placed on board[row][col]. Note that this + function is called when "col" queens are + already placed in columns from 0 to col -1. + So we need to check only left side for + attacking queens */ +bool isSafe(int board[N][N], int row, int col) +{ + int i, j; + + /* Check this row on left side */ + for (i = 0; i < col; i++) + if (board[row][i]) + return false; + + /* Check upper diagonal on left side */ + for (i = row, j = col; i >= 0 && j >= 0; i--, j--) + if (board[i][j]) + return false; + + /* Check lower diagonal on left side */ + for (i = row, j = col; j >= 0 && i < N; i++, j--) + if (board[i][j]) + return false; + + return true; +} + +/* A recursive utility function to solve N + Queen problem */ +bool solveNQUtil(int board[N][N], int col) +{ + /* base case: If all queens are placed + then return true */ + if (col >= N) + return true; + + /* Consider this column and try placing + this queen in all rows one by one */ + for (int i = 0; i < N; i++) { + /* Check if the queen can be placed on + board[i][col] */ + if (isSafe(board, i, col)) { + /* Place this queen in board[i][col] */ + board[i][col] = 1; + + /* recur to place rest of the queens */ + if (solveNQUtil(board, col + 1)) + return true; + + /* If placing queen in board[i][col] + doesn't lead to a solution, then + remove queen from board[i][col] */ + board[i][col] = 0; // BACKTRACK + } + } + + /* If the queen cannot be placed in any row in + this colum col then return false */ + return false; +} + +/* This function solves the N Queen problem using + Backtracking. It mainly uses solveNQUtil() to + solve the problem. It returns false if queens + cannot be placed, otherwise, return true and + prints placement of queens in the form of 1s. + Please note that there may be more than one + solutions, this function prints one of the + feasible solutions.*/ +bool solveNQ() +{ + int board[N][N] = { { 0, 0, 0, 0 }, + { 0, 0, 0, 0 }, + { 0, 0, 0, 0 }, + { 0, 0, 0, 0 } }; + + if (solveNQUtil(board, 0) == false) { + printf("Solution does not exist"); + return false; + } + + printSolution(board); + return true; +} + +// driver program to test above function +int main() +{ + solveNQ(); + return 0; +} \ No newline at end of file From b71e9c2e4c6e0aa3716dee82f49dd2a943831333 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sat, 7 Nov 2020 19:47:21 +0530 Subject: [PATCH 101/209] add red black tree cpp code implementation --- RedBlackTree/Makefile | 10 ++++ RedBlackTree/RedBlackTree.cpp | 84 ++++++++++++++------------- RedBlackTree/RedBlackTree.hpp | 28 ++++++--- RedBlackTree/find.cpp | 62 ++++++++++++++++++++ RedBlackTree/insert.cpp | 91 ++++++++++++++++++++++++++++++ RedBlackTree/test_RedBlackTree.cpp | 28 +++++++++ RedBlackTree/utils.cpp | 33 +++++++++++ 7 files changed, 286 insertions(+), 50 deletions(-) create mode 100644 RedBlackTree/Makefile create mode 100644 RedBlackTree/find.cpp create mode 100644 RedBlackTree/insert.cpp create mode 100644 RedBlackTree/test_RedBlackTree.cpp create mode 100644 RedBlackTree/utils.cpp diff --git a/RedBlackTree/Makefile b/RedBlackTree/Makefile new file mode 100644 index 0000000..556b000 --- /dev/null +++ b/RedBlackTree/Makefile @@ -0,0 +1,10 @@ +CC=g++ +GTEST_INCLUDE_PATH=../googletest/googletest/include/ +GTEST_LIBRARY_PATH=../googletest/build/lib/ -lgtest -lgtest_main +CCFLAGS=-Wall -std=c++14 + +all: + $(CC) test_RedBlackTree.cpp RedBlackTree.cpp find.cpp insert.cpp utils.cpp $(CCFLAGS) -I$(GTEST_INCLUDE_PATH) -L$(GTEST_LIBRARY_PATH) + +clean: + rm ./a.out diff --git a/RedBlackTree/RedBlackTree.cpp b/RedBlackTree/RedBlackTree.cpp index 6a7fff2..43a9ce2 100644 --- a/RedBlackTree/RedBlackTree.cpp +++ b/RedBlackTree/RedBlackTree.cpp @@ -2,62 +2,60 @@ #include "RedBlackTree.hpp" /** - * find the element in red black tree - * @param data item to be searched + * Delete red black tree nodes recursively */ -bool RedBlackTree::find(int data) { - if (root == nullptr) - return false; +void RedBlackTree::deleteTreeRecursive(Node* node) { + if (node == nullptr) + return; + + if (node->left != nullptr) + deleteTreeRecursive(node->left); + if (node->right != nullptr) + deleteTreeRecursive(node->right); + delete node; +} - return find(root, data); +/** + * returns node color + * @param node pointer to red black tree node +*/ +int RedBlackTree::getNodeColor(Node* node) { + if (node == nullptr) + return BLACK; + return node->color; } /** - * find is an recursive internal method which works at node level - * @param root root of tree/sub-tre - * @param data item to be searched + * returns uncle of node + * @param node pointer to red black tree node */ -bool RedBlackTree::find(Node* node, int data) { - if (root == nullptr) - return false; +Node* RedBlackTree::uncle(Node* node) { + if (node == nullptr || node->parent == nullptr || + node->parent->parent == nullptr) + return nullptr; - if (data == root->data) return true; - else if (data < root->data) return find(root->left, data); - else return find(root->right, data); + return sibling(node->parent); } /** - * returns left-most item present in red black tree which is also - * the minimum element in red black tree - * @return minimum element present in red black tree + * returns sibling of given node + * @param node pointer to red black tree node */ -int RedBlackTree::min() -{ - Node* root = getRoot(); - if (root == nullptr) - throw EmptyTree(); +Node* RedBlackTree::sibling(Node* node) { + if (node == nullptr || node->parent == nullptr) + return nullptr; - Node* current = root; - while (current->left != nullptr) - current = current->left; - - return current->data; + if (node == node->parent->left) + return node->parent->right; + return node->parent->left; } /** - * returns right-most item present in red black tree which is also - * the maximum element in red black tree - * @return maximum element present in red black tree + * returns grandparent of node + * @param node pointer to red black tree node */ -int RedBlackTree::max() -{ - Node* root = getRoot(); - if (root == nullptr) - throw EmptyTree(); - - Node* current = root; - while (current->right != nullptr) - current = current->right; - - return current->data; -} \ No newline at end of file +Node* RedBlackTree::grandparent(Node* node) { + if (node == nullptr || node->parent == nullptr) + return nullptr; + return node->parent->parent; +} diff --git a/RedBlackTree/RedBlackTree.hpp b/RedBlackTree/RedBlackTree.hpp index aacbfeb..44f9c34 100644 --- a/RedBlackTree/RedBlackTree.hpp +++ b/RedBlackTree/RedBlackTree.hpp @@ -40,6 +40,9 @@ #include +#define RED 0 +#define BLACK 1 + class EmptyTree : public std::exception { const char* what() const throw() { return "tree is empty"; @@ -67,17 +70,28 @@ struct Node { class RedBlackTree { private: Node* root; + int size; bool find(Node* node, int data); - // void deleteTreeRecursive(Node* node); - // void leftRotate(Node* node); - // void rightRotate(Node* node); - // void replaceNode(Node* node); + int getNodeColor(Node* node); + Node* uncle(Node* node); + Node* sibling(Node* node); + Node* grandparent(Node* node); + void leftRotate(Node* node); + void rightRotate(Node* node); + void replaceNode(Node* oldNode, Node* newNode); + void insertCase1(Node* node); + void insertCase2(Node* node); + void insertCase3(Node* node); + void insertCase4(Node* node); + void insertCase5(Node* node); + void deleteTreeRecursive(Node* node); public: - RedBlackTree() { root = nullptr; } - // ~RedBlackTree() { deleteTreeRecursive(root); } + RedBlackTree() { root = nullptr; size = 0;} + ~RedBlackTree() { deleteTreeRecursive(root); } Node* getRoot() { return root; } - // void insert(int data); + int getSize() { return size; } + void insert(int data); bool find(int data); int min(); int max(); diff --git a/RedBlackTree/find.cpp b/RedBlackTree/find.cpp new file mode 100644 index 0000000..037317b --- /dev/null +++ b/RedBlackTree/find.cpp @@ -0,0 +1,62 @@ +#include "RedBlackTree.hpp" + +/** + * find the element in red black tree + * @param data item to be searched +*/ +bool RedBlackTree::find(int data) { + if (root == nullptr) + return false; + + return find(root, data); +} + +/** + * find is an recursive internal method which works at node level + * @param root root of tree/sub-tre + * @param data item to be searched +*/ +bool RedBlackTree::find(Node* node, int data) { + if (root == nullptr) + return false; + + if (data == root->data) return true; + else if (data < root->data) return find(root->left, data); + else return find(root->right, data); +} + +/** + * returns left-most item present in red black tree which is also + * the minimum element in red black tree + * @return minimum element present in red black tree +*/ +int RedBlackTree::min() +{ + Node* root = getRoot(); + if (root == nullptr) + throw EmptyTree(); + + Node* current = root; + while (current->left != nullptr) + current = current->left; + + return current->data; +} + +/** + * returns right-most item present in red black tree which is also + * the maximum element in red black tree + * @return maximum element present in red black tree +*/ +int RedBlackTree::max() +{ + Node* root = getRoot(); + if (root == nullptr) + throw EmptyTree(); + + Node* current = root; + while (current->right != nullptr) + current = current->right; + + return current->data; +} \ No newline at end of file diff --git a/RedBlackTree/insert.cpp b/RedBlackTree/insert.cpp new file mode 100644 index 0000000..56533df --- /dev/null +++ b/RedBlackTree/insert.cpp @@ -0,0 +1,91 @@ +#include "RedBlackTree.hpp" + +/** + * inserts new integer data into the tree at the position, so that + * the red black tree property is maintained. + * @param data new integer data to be inserted +*/ +void RedBlackTree::insert(int data) { + Node* insertedNode = nullptr; + if (root == nullptr) { + root = new Node(data, RED); + insertedNode = root; + } else { + Node* node = root; + while (true) { + if (data < node->data) { + if (node->left == nullptr) { + node->left = new Node(data, RED); + insertedNode = node->left; + break; + } else { + node = node->left; + } + } else if (data > node->data) { + if (node->right == nullptr) { + node->right = new Node(data, RED); + insertedNode = node->right; + break; + } else { + node = node->right; + } + } else { + node->data = data; + return; + } + } + insertedNode->parent = node; + } + insertCase1(insertedNode); + size++; +} + +void RedBlackTree::insertCase1(Node* node) { + if (node->parent == nullptr) { + node->color = BLACK; + } else { + insertCase2(node); + } +} + +void RedBlackTree::insertCase2(Node* node) { + if (getNodeColor(node->parent) == BLACK) return; + insertCase3(node); +} + +void RedBlackTree::insertCase3(Node* node) { + Node* uncleNode = uncle(node); + if (getNodeColor(uncleNode) == RED) { + node->parent->color = BLACK; + uncleNode->color = BLACK; + grandparent(node)->color = RED; + insertCase1(grandparent(node)); + } else { + insertCase4(node); + } +} + +void RedBlackTree::insertCase4(Node* node) { + Node* grandparentNode = grandparent(node); + if (node == node->parent->right && node->parent == grandparentNode->left) { + leftRotate(node->parent); + node = node->left; + } else if (node == node->parent->left && + node->parent == grandparentNode->right) { + rightRotate(node->parent); + node = node->right; + } + insertCase5(node); +} + +void RedBlackTree::insertCase5(Node* node) { + node->parent->color = BLACK; + Node* grandparentNode = grandparent(node); + grandparentNode->color = RED; + if (node == node->parent->left && node->parent == grandparentNode->left) { + rightRotate(grandparentNode); + } else if (node == node->parent->right && + node->parent == grandparentNode->right) { + leftRotate(grandparentNode); + } +} \ No newline at end of file diff --git a/RedBlackTree/test_RedBlackTree.cpp b/RedBlackTree/test_RedBlackTree.cpp new file mode 100644 index 0000000..dc06398 --- /dev/null +++ b/RedBlackTree/test_RedBlackTree.cpp @@ -0,0 +1,28 @@ +#include +#include "RedBlackTree.hpp" +#include + +/* Fixtures */ +// Red Black Tree initial setup +class RBDataInit : public testing::Test { +protected: + RedBlackTree rb; + std::vector original{ 19, 5, 1, 18, 3, 8, 24, 13, 16, 12 }; + void SetUp() override { + for (int i : original) + rb.insert(i); + } +}; + +/* Red Black Tree Insertion */ +// test insert method on red black tree +TEST_F(RBDataInit, InsertSizeTest) { + ASSERT_EQ(10, rb.getSize()); +} + +/* Red Black Tree Find */ +// test find method on red black tree +TEST_F(RBDataInit, FindTest) { + ASSERT_TRUE(rb.find(5)); + // ASSERT_FALSE(rb.find(2)); +} diff --git a/RedBlackTree/utils.cpp b/RedBlackTree/utils.cpp new file mode 100644 index 0000000..239b0e2 --- /dev/null +++ b/RedBlackTree/utils.cpp @@ -0,0 +1,33 @@ +#include "RedBlackTree.hpp" + +void RedBlackTree::leftRotate(Node* node) { + Node* right = node->right; + replaceNode(node, right); + node->right = right->left; + if (right->left != nullptr) + right->left->parent = node; + right->left = node; + node->parent = right; +} + +void RedBlackTree::rightRotate(Node* node) { + Node* left = node->left; + replaceNode(node, left); + node->left = left->right; + if (left->right != nullptr) + left->right->parent = node; + left->right = node; + node->parent = left; +} + +void RedBlackTree::replaceNode(Node* oldNode, Node* newNode) { + if (oldNode->parent == nullptr) { + root = newNode; + } else { + if (oldNode == oldNode->parent->left) + oldNode->parent->left = newNode; + else oldNode->parent->right = newNode; + } + if (newNode != nullptr) + newNode->parent = oldNode->parent; +} \ No newline at end of file From b9cf2b4f20ab3f6ff020158710f2bd2f363f94d4 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sat, 7 Nov 2020 19:54:32 +0530 Subject: [PATCH 102/209] add merge sort optimized algorithms --- Sort/MergeBottomUp.cpp | 80 ++++++++++++++++++++++++++ Sort/MergeOptimizeSort.cpp | 115 +++++++++++++++++++++++++++++++++++++ Sort/MergeSort.cpp | 87 ++++++++++++++++++++++++++++ 3 files changed, 282 insertions(+) create mode 100644 Sort/MergeBottomUp.cpp create mode 100644 Sort/MergeOptimizeSort.cpp create mode 100644 Sort/MergeSort.cpp diff --git a/Sort/MergeBottomUp.cpp b/Sort/MergeBottomUp.cpp new file mode 100644 index 0000000..0a54491 --- /dev/null +++ b/Sort/MergeBottomUp.cpp @@ -0,0 +1,80 @@ +/* + * Sorting Algorithms + * Merge Sort (C++ implementation) + * + * Merge BottomUp algorithm first merges pairs of adjacent arrays of + * 1 elements then merges pairs of adjacent arrays of 2 elements + * and next merges pairs of adjacent arrays of 4 elements + * and so on until the whole array is merged. Hence, completely avoiding + * recursive approach. + */ + +#include + +/* Function Declarations */ +template +void MergeSort(T data[], int dataLen); +template +void merge(T data[], T aux[], int low, int mid, int high); + +/* Main Driver Function */ +int main() { + int arr[] = {229, 79, 46, 12, 58, 31, 34, 67, 89, 12, 67, 2}; + int arr_size = sizeof(arr) / sizeof(arr[0]); + + MergeSort(arr, arr_size); + + for (int a: arr) + std::cout << a << " "; + std::cout << "\n"; + + return 0; +} + +/** + * Merge Sort Template Function + * @param data actual array to sort + * @param dataLen size of array + */ +template +void MergeSort(T data[], int dataLen) { + T aux[dataLen]; + for (int sz = 1; sz < dataLen; sz = sz + sz) { + for (int low = 0; low < dataLen - sz; low += sz + sz) { + merge(data, aux, low, low + sz - 1, + std::min(low + sz + sz - 1, dataLen - 1)); + } + } +} + +/** + * merge function for Merge Sort + * @param data actual array to sort + * @param low lower bound of partial array + * @param mid middle of partial array + * @param high upper bound of partial array +*/ +template +void merge(T data[], T aux[], int low, int mid, int high) { + for (int k = low; k <= high; k++) { + aux[k] = data[k]; + } + + int i = low; + int j = mid + 1; + for (int k = low; k <= high; k++){ + if (i > mid) { + data[k] = aux[j]; + j++; + } else if (j > high) { + data[k] = aux[i]; + i++; + } else if (aux[j] < aux[i]) { + data[k] = aux[j]; + j++; + } else { + data[k] = aux[i]; + i++; + } + } +} \ No newline at end of file diff --git a/Sort/MergeOptimizeSort.cpp b/Sort/MergeOptimizeSort.cpp new file mode 100644 index 0000000..2edc9aa --- /dev/null +++ b/Sort/MergeOptimizeSort.cpp @@ -0,0 +1,115 @@ +/* + * Sorting Algorithms + * Merge Sort (C++ implementation) + * + * MergeSort (optimized version) function implements optimized version of Merge Sorting + * algorithm. It uses Insertion sort for dataset with less than or equal to 7 + * elements. It also stops if data is already sorted i.e biggest item in first + * half is less than or equal to smallest item in seconh half. It is useful for + * partially-ordered arrays. We also pass auxillary array to this function + * because creating auxillary array in the recusive routine lead to extensive + * cost of extra array creation. + */ + +#include +#define CUTOFF 7 + +/* Function Declarations */ +template +void MergeSort(T data[], T aux[], int low, int high); +template +void merge(T data[], T aux[], int low, int mid, int high); +template +void InsertionSort(T arr[], int low, int high); + +/* Main Driver Function */ +int main() { + int arr[] = {229, 79, 46, 12, 58, 31, 34, 67, 89, 12, 67, 2}; + // char arr[] = {'d', 't', 'a', 'b', 'q', 'z', 'd', 'e', 'x'}; + int arr_size = sizeof(arr) / sizeof(arr[0]); + + int aux[arr_size]; + MergeSort(arr, aux, 0, arr_size - 1); + + for (int a: arr) + std::cout << a << " "; + std::cout << "\n"; + + return 0; +} + +/** + * Merge Sort Template Function + * @param data actual array to sort + * @param low lower bound of partial array + * @param high upper bound of partial array + */ +template +void MergeSort(T data[], T aux[], int low, int high) { + if (high <= low + CUTOFF - 1) { + InsertionSort(data, low, high); + } + + if (low < high) { + int mid = (low + high) / 2; + MergeSort(data, aux, low, mid); + MergeSort(data, aux, mid+1, high); + + // stop if already sorted + // iff biggest item in fist half <= smallest item in second half + // helps for partially-ordered arrays + if (data[mid] <= data[mid+1]) { + return; + } + merge(data, aux, low, mid, high); + } +} + +/** + * Insertion Sort Template Function + * @param arr actual array to sort + * @param len size of array + */ +template +void InsertionSort(T arr[], int low, int high) { + for (int i = low; i <= high; i++) { + int index = i; + int value = arr[i]; + while (index > 0 && arr[index-1] > value) { + arr[index] = arr[index-1]; + index--; + } + arr[index] = value; + } +} + +/** + * merge function for MergeSort + * @param data actual array to sort + * @param low lower bound of partial array + * @param high upper bound of partial array +*/ +template +void merge(T data[], T aux[], int low, int mid, int high) { + for (int k = low; k <= high; k++) { + aux[k] = data[k]; + } + + int i = low; + int j = mid + 1; + for (int k = low; k <= high; k++){ + if (i > mid) { + data[k] = aux[j]; + j++; + } else if (j > high) { + data[k] = aux[i]; + i++; + } else if (aux[j] < aux[i]) { + data[k] = aux[j]; + j++; + } else { + data[k] = aux[i]; + i++; + } + } +} \ No newline at end of file diff --git a/Sort/MergeSort.cpp b/Sort/MergeSort.cpp new file mode 100644 index 0000000..08e78c2 --- /dev/null +++ b/Sort/MergeSort.cpp @@ -0,0 +1,87 @@ +/* + * Sorting Algorithms + * Merge Sort (C++ implementation) + * + * MergeSort is a Divide and Conquer algorithm. It divides input array in two + * halves, calls itself for the two halves and then merges the two sorted + * halves. + */ + +#include + +/* Function Declarations */ +template +void MergeSort(T data[], int low, int high); +template +void merge(T data[], int low, int mid, int high); + +/* Main Driver Function */ +int main() { + int arr[] = {229, 79, 46, 12, 58, 31, 34, 67, 89, 12, 67, 2}; + int arr_size = sizeof(arr) / sizeof(arr[0]); + + MergeSort(arr, 0, arr_size - 1); + + for (int a: arr) + std::cout << a << " "; + std::cout << "\n"; + + return 0; +} + +/** + * Merge Sort Template Function + * @param data actual array to sort + * @param low lower bound of partial array + * @param high upper bound of partial array + */ +template +void MergeSort(T data[], int low, int high) { + if (low < high) { + int mid = (low + high) / 2; + MergeSort(data, low, mid); + MergeSort(data, mid+1, high); + merge(data, low, mid, high); + } +} + +/** + * merge function for MergeSort + * @param data actual array to sort + * @param low lower bound of partial array + * @param high upper bound of partial array +*/ +template +void merge(T data[], int low, int mid, int high) { + T aux[high - low + 1]; + int i = low; + int j = mid + 1; + int k = 0; + + while (i <= mid && j <= high) { + if (data[i] < data[j]) { + aux[k] = data[i]; + i++; + } else { + aux[k] = data[j]; + j++; + } + k++; + } + + while (i <= mid) { + aux[k] = data[i]; + k++; + i++; + } + + while (j <= high) { + aux[k] = data[j]; + k++; + j++; + } + + for (i = low; i <= high; i++) { + data[i] = aux[i-low]; + } +} \ No newline at end of file From ee22212a8de9db1199e7a4f39b31c9bc656c83c7 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sat, 7 Nov 2020 21:49:43 +0530 Subject: [PATCH 103/209] move c, cpp and go code to subfolder --- other_languages/c/README.md | 8 ++++++++ .../c}/dynamic_connectivity/quick_find/Makefile | 0 .../c}/dynamic_connectivity/quick_find/main.c | 4 ++-- .../dynamic_connectivity/quick_find/quick_find.c | 4 ++-- .../dynamic_connectivity/quick_find/quick_find.h | 0 .../c}/dynamic_connectivity/quick_union/Makefile | 0 .../c}/dynamic_connectivity/quick_union/main.c | 4 ++-- .../quick_union/quick_union.c | 0 .../quick_union/quick_union.h | 0 {C => other_languages/c}/queue/Makefile | 0 {C => other_languages/c}/queue/main.c | 2 +- {C => other_languages/c}/queue/queue.c | 2 +- {C => other_languages/c}/queue/queue.h | 2 +- {C => other_languages/c}/shuffling/Makefile | 2 +- .../c}/shuffling/shuffle_array.c | 0 .../c}/sorts/bubble_sort/Makefile | 2 +- .../c}/sorts/bubble_sort/bubble_sort.c | 4 ++-- {C => other_languages/c}/sorts/generic/Makefile | 2 +- {C => other_languages/c}/sorts/generic/README.md | 4 +--- {C => other_languages/c}/sorts/generic/main.c | 4 ++-- {C => other_languages/c}/sorts/generic/sort.c | 10 +++++----- {C => other_languages/c}/sorts/generic/sort.h | 4 ++-- .../c}/sorts/insertion_sort/Makefile | 2 +- .../c}/sorts/insertion_sort/insertion_sort.c | 2 +- .../c}/sorts/merge_sort/Makefile | 2 +- .../c}/sorts/merge_sort/merge_sort.c | 0 .../c}/sorts/quick_sort/Makefile | 2 +- .../c}/sorts/quick_sort/quick_sort.c | 2 +- .../c}/sorts/selection_sort/Makefile | 2 +- .../c}/sorts/selection_sort/selection_sort.c | 10 +++++----- .../c}/sorts/shell_sort/Makefile | 2 +- .../c}/sorts/shell_sort/shell_sort.c | 2 +- .../c}/stack/array_implementation/Makefile | 0 .../c}/stack/array_implementation/main.c | 4 ++-- .../c}/stack/array_implementation/stack.c | 10 +++++----- .../c}/stack/array_implementation/stack.h | 2 +- .../stack/generic_array_implementation/Makefile | 0 .../c}/stack/generic_array_implementation/main.c | 6 +++--- .../stack/generic_array_implementation/stack.c | 12 ++++++------ .../stack/generic_array_implementation/stack.h | 2 +- other_languages/cpp/.DS_Store | Bin 0 -> 6148 bytes .../cpp/BinarySearchTree}/BST/BST.cpp | 0 .../cpp/BinarySearchTree}/BST/BST.hpp | 0 .../cpp/BinarySearchTree}/BST/Makefile | 0 .../cpp/BinarySearchTree}/BST/test_BST.cpp | 0 .../cpp/BinarySearchTree}/Nqueen | 0 .../cpp/BinarySearchTree}/bfsTraversal.cpp | 0 .../cpp/BinarySearchTree}/dfsTraversal.cpp | 0 .../cpp/BinarySearchTree}/inorderSuccessor.cpp | 0 .../cpp/BinarySearchTree}/isBST.cpp | 0 .../cpp/DynamicConnectivity}/QuickFind.cpp | 0 .../cpp/DynamicConnectivity}/QuickUnion.cpp | 0 .../DynamicConnectivity}/WeightedQuickUnion.cpp | 0 other_languages/cpp/Heap/.DS_Store | Bin 0 -> 6148 bytes .../cpp/Heap}/Heap/HeapException.hpp | 0 {Heap => other_languages/cpp/Heap}/Heap/Makefile | 0 .../cpp/Heap}/Heap/MaxHeap.hpp | 0 .../cpp/Heap}/Heap/MinHeap.hpp | 0 .../cpp/Heap}/Heap/test_Heap.cpp | 0 other_languages/cpp/LinkedList/.DS_Store | Bin 0 -> 6148 bytes .../cpp/LinkedList}/LinkedList/LinkedList.hpp | 0 .../cpp/LinkedList}/LinkedList/Makefile | 0 .../LinkedList}/LinkedList/test_LinkedList.cpp | 0 .../cpp/LinkedList}/countFrequency.cpp | 0 .../cpp/LinkedList}/detectLoop.cpp | 0 .../cpp/LinkedList}/findMiddle.cpp | 0 .../cpp/LinkedList}/getNthNodeFromEnd.cpp | 0 .../cpp/LinkedList}/lengthOfLoop.cpp | 0 .../cpp/Queue}/Queue/Makefile | 0 .../cpp/Queue}/Queue/Queue.hpp | 0 .../cpp/Queue}/Queue/test_Queue.cpp | 0 .../cpp/Queue}/ReverseQueue.cpp | 0 .../cpp/Queue}/SortQueueWithoutExtraSpace.cpp | 0 .../cpp/RedBlackTree}/Makefile | 0 .../cpp/RedBlackTree}/RedBlackTree.cpp | 0 .../cpp/RedBlackTree}/RedBlackTree.hpp | 0 .../cpp/RedBlackTree}/find.cpp | 0 .../cpp/RedBlackTree}/insert.cpp | 0 .../cpp/RedBlackTree}/test_RedBlackTree.cpp | 0 .../cpp/RedBlackTree}/utils.cpp | 0 .../cpp/Search}/BinarySearch.h | 0 {Search => other_languages/cpp/Search}/Makefile | 0 .../cpp/Search}/test_BinarySearch.cpp | 0 .../cpp/Shuffle}/Shuffle.cpp | 0 .../cpp/Sort}/BubbleSort.cpp | 0 .../cpp/Sort}/CountingSort.cpp | 0 {Sort => other_languages/cpp/Sort}/GnomeSort.cpp | 0 {Sort => other_languages/cpp/Sort}/HeapSort.cpp | 0 .../cpp/Sort}/InsertionSort.cpp | 0 .../cpp/Sort}/MergeBottomUp.cpp | 0 .../cpp/Sort}/MergeOptimizeSort.cpp | 0 {Sort => other_languages/cpp/Sort}/MergeSort.cpp | 0 .../cpp/Sort}/OddEvenSort.cpp | 0 .../cpp/Sort}/Quick3WaySort.cpp | 0 .../cpp/Sort}/QuickOptimizeSort.cpp | 0 .../cpp/Sort}/QuickSelect.cpp | 0 {Sort => other_languages/cpp/Sort}/QuickSort.cpp | 0 .../cpp/Sort}/SelectionSort.cpp | 0 {Sort => other_languages/cpp/Sort}/ShellSort.cpp | 0 .../cpp/Stack}/Stack/Makefile | 0 .../cpp/Stack}/Stack/Stack.hpp | 0 .../cpp/Stack}/Stack/test_Stack.cpp | 0 .../cpp/Stack}/balancedParanthesis.cpp | 0 .../cpp/Stack}/bracketReversals.cpp | 0 .../cpp/Stack}/deleteMiddleElement.cpp | 0 .../cpp/Stack}/infixToPostfix.cpp | 0 .../cpp/Stack}/trackingCurrentMax.cpp | 0 {Go => other_languages/go}/README.md | 0 {Go => other_languages/go}/bst/bst.go | 0 {Go => other_languages/go}/bst/bst_test.go | 0 {Go => other_languages/go}/bst/checkbst.go | 0 {Go => other_languages/go}/bst/delete.go | 0 {Go => other_languages/go}/bst/find.go | 0 {Go => other_languages/go}/bst/height.go | 0 {Go => other_languages/go}/bst/insert.go | 0 {Go => other_languages/go}/bst/traversal.go | 0 .../go}/doublylinkedlist/doublylinkedlist.go | 0 .../doublylinkedlist/doublylinkedlist_test.go | 0 .../go}/hashtable/hashtable.go | 0 .../go}/hashtable/hashtable_test.go | 0 {Go => other_languages/go}/heap/doc.go | 0 .../go}/heap/maxheap/maxheap.go | 0 .../go}/heap/maxheap/maxheap_test.go | 0 .../go}/heap/minheap/minheap.go | 0 .../go}/heap/minheap/minheap_test.go | 0 .../go}/linkedlist/linkedlist.go | 0 .../go}/linkedlist/linkedlist_test.go | 0 {Go => other_languages/go}/queue/queue.go | 0 {Go => other_languages/go}/queue/queue_test.go | 0 {Go => other_languages/go}/redblacktree/doc.go | 0 {Go => other_languages/go}/redblacktree/find.go | 0 .../go}/redblacktree/insert.go | 0 .../go}/redblacktree/redblacktree.go | 0 .../go}/redblacktree/redblacktree_test.go | 0 {Go => other_languages/go}/redblacktree/utils.go | 0 .../go}/search/binarysearch.go | 0 .../go}/search/binarysearch_test.go | 0 {Go => other_languages/go}/set/set.go | 0 {Go => other_languages/go}/set/set_test.go | 0 {Go => other_languages/go}/shuffle/shuffle.go | 0 {Go => other_languages/go}/sort/bubble.go | 0 {Go => other_languages/go}/sort/countingSort.go | 0 {Go => other_languages/go}/sort/gnome.go | 0 {Go => other_languages/go}/sort/heap.go | 0 {Go => other_languages/go}/sort/insertion.go | 0 {Go => other_languages/go}/sort/merge.go | 0 {Go => other_languages/go}/sort/oddeven.go | 0 {Go => other_languages/go}/sort/quick.go | 0 {Go => other_languages/go}/sort/quickselect.go | 0 {Go => other_languages/go}/sort/selection.go | 0 {Go => other_languages/go}/sort/shell.go | 0 {Go => other_languages/go}/sort/sort.go | 0 {Go => other_languages/go}/sort/sort_test.go | 0 .../go}/stack/applications/applications.go | 0 .../go}/stack/applications/applications_test.go | 0 .../go}/stack/applications/infixevaluation.go | 0 .../go}/stack/applications/infixtopostfix.go | 0 .../go}/stack/applications/infixtoprefix.go | 0 .../go}/stack/applications/utils.go | 0 {Go => other_languages/go}/stack/stack.go | 0 {Go => other_languages/go}/stack/stack_test.go | 0 {Go => other_languages/go}/trie/trie.go | 0 {Go => other_languages/go}/trie/trie_test.go | 0 163 files changed, 63 insertions(+), 57 deletions(-) create mode 100644 other_languages/c/README.md rename {C => other_languages/c}/dynamic_connectivity/quick_find/Makefile (100%) rename {C => other_languages/c}/dynamic_connectivity/quick_find/main.c (98%) rename {C => other_languages/c}/dynamic_connectivity/quick_find/quick_find.c (93%) rename {C => other_languages/c}/dynamic_connectivity/quick_find/quick_find.h (100%) rename {C => other_languages/c}/dynamic_connectivity/quick_union/Makefile (100%) rename {C => other_languages/c}/dynamic_connectivity/quick_union/main.c (98%) rename {C => other_languages/c}/dynamic_connectivity/quick_union/quick_union.c (100%) rename {C => other_languages/c}/dynamic_connectivity/quick_union/quick_union.h (100%) rename {C => other_languages/c}/queue/Makefile (100%) rename {C => other_languages/c}/queue/main.c (99%) rename {C => other_languages/c}/queue/queue.c (99%) rename {C => other_languages/c}/queue/queue.h (97%) rename {C => other_languages/c}/shuffling/Makefile (88%) rename {C => other_languages/c}/shuffling/shuffle_array.c (100%) rename {C => other_languages/c}/sorts/bubble_sort/Makefile (87%) rename {C => other_languages/c}/sorts/bubble_sort/bubble_sort.c (96%) rename {C => other_languages/c}/sorts/generic/Makefile (90%) rename {C => other_languages/c}/sorts/generic/README.md (72%) rename {C => other_languages/c}/sorts/generic/main.c (98%) rename {C => other_languages/c}/sorts/generic/sort.c (99%) rename {C => other_languages/c}/sorts/generic/sort.h (88%) rename {C => other_languages/c}/sorts/insertion_sort/Makefile (88%) rename {C => other_languages/c}/sorts/insertion_sort/insertion_sort.c (98%) rename {C => other_languages/c}/sorts/merge_sort/Makefile (87%) rename {C => other_languages/c}/sorts/merge_sort/merge_sort.c (100%) rename {C => other_languages/c}/sorts/quick_sort/Makefile (87%) rename {C => other_languages/c}/sorts/quick_sort/quick_sort.c (99%) rename {C => other_languages/c}/sorts/selection_sort/Makefile (88%) rename {C => other_languages/c}/sorts/selection_sort/selection_sort.c (97%) rename {C => other_languages/c}/sorts/shell_sort/Makefile (87%) rename {C => other_languages/c}/sorts/shell_sort/shell_sort.c (98%) rename {C => other_languages/c}/stack/array_implementation/Makefile (100%) rename {C => other_languages/c}/stack/array_implementation/main.c (98%) rename {C => other_languages/c}/stack/array_implementation/stack.c (94%) rename {C => other_languages/c}/stack/array_implementation/stack.h (95%) rename {C => other_languages/c}/stack/generic_array_implementation/Makefile (100%) rename {C => other_languages/c}/stack/generic_array_implementation/main.c (99%) rename {C => other_languages/c}/stack/generic_array_implementation/stack.c (95%) rename {C => other_languages/c}/stack/generic_array_implementation/stack.h (97%) create mode 100644 other_languages/cpp/.DS_Store rename {BinarySearchTree => other_languages/cpp/BinarySearchTree}/BST/BST.cpp (100%) rename {BinarySearchTree => other_languages/cpp/BinarySearchTree}/BST/BST.hpp (100%) rename {BinarySearchTree => other_languages/cpp/BinarySearchTree}/BST/Makefile (100%) rename {BinarySearchTree => other_languages/cpp/BinarySearchTree}/BST/test_BST.cpp (100%) rename {BinarySearchTree => other_languages/cpp/BinarySearchTree}/Nqueen (100%) rename {BinarySearchTree => other_languages/cpp/BinarySearchTree}/bfsTraversal.cpp (100%) rename {BinarySearchTree => other_languages/cpp/BinarySearchTree}/dfsTraversal.cpp (100%) rename {BinarySearchTree => other_languages/cpp/BinarySearchTree}/inorderSuccessor.cpp (100%) rename {BinarySearchTree => other_languages/cpp/BinarySearchTree}/isBST.cpp (100%) rename {DynamicConnectivity => other_languages/cpp/DynamicConnectivity}/QuickFind.cpp (100%) rename {DynamicConnectivity => other_languages/cpp/DynamicConnectivity}/QuickUnion.cpp (100%) rename {DynamicConnectivity => other_languages/cpp/DynamicConnectivity}/WeightedQuickUnion.cpp (100%) create mode 100644 other_languages/cpp/Heap/.DS_Store rename {Heap => other_languages/cpp/Heap}/Heap/HeapException.hpp (100%) rename {Heap => other_languages/cpp/Heap}/Heap/Makefile (100%) rename {Heap => other_languages/cpp/Heap}/Heap/MaxHeap.hpp (100%) rename {Heap => other_languages/cpp/Heap}/Heap/MinHeap.hpp (100%) rename {Heap => other_languages/cpp/Heap}/Heap/test_Heap.cpp (100%) create mode 100644 other_languages/cpp/LinkedList/.DS_Store rename {LinkedList => other_languages/cpp/LinkedList}/LinkedList/LinkedList.hpp (100%) rename {LinkedList => other_languages/cpp/LinkedList}/LinkedList/Makefile (100%) rename {LinkedList => other_languages/cpp/LinkedList}/LinkedList/test_LinkedList.cpp (100%) rename {LinkedList => other_languages/cpp/LinkedList}/countFrequency.cpp (100%) rename {LinkedList => other_languages/cpp/LinkedList}/detectLoop.cpp (100%) rename {LinkedList => other_languages/cpp/LinkedList}/findMiddle.cpp (100%) rename {LinkedList => other_languages/cpp/LinkedList}/getNthNodeFromEnd.cpp (100%) rename {LinkedList => other_languages/cpp/LinkedList}/lengthOfLoop.cpp (100%) rename {Queue => other_languages/cpp/Queue}/Queue/Makefile (100%) rename {Queue => other_languages/cpp/Queue}/Queue/Queue.hpp (100%) rename {Queue => other_languages/cpp/Queue}/Queue/test_Queue.cpp (100%) rename {Queue => other_languages/cpp/Queue}/ReverseQueue.cpp (100%) rename {Queue => other_languages/cpp/Queue}/SortQueueWithoutExtraSpace.cpp (100%) rename {RedBlackTree => other_languages/cpp/RedBlackTree}/Makefile (100%) rename {RedBlackTree => other_languages/cpp/RedBlackTree}/RedBlackTree.cpp (100%) rename {RedBlackTree => other_languages/cpp/RedBlackTree}/RedBlackTree.hpp (100%) rename {RedBlackTree => other_languages/cpp/RedBlackTree}/find.cpp (100%) rename {RedBlackTree => other_languages/cpp/RedBlackTree}/insert.cpp (100%) rename {RedBlackTree => other_languages/cpp/RedBlackTree}/test_RedBlackTree.cpp (100%) rename {RedBlackTree => other_languages/cpp/RedBlackTree}/utils.cpp (100%) rename {Search => other_languages/cpp/Search}/BinarySearch.h (100%) rename {Search => other_languages/cpp/Search}/Makefile (100%) rename {Search => other_languages/cpp/Search}/test_BinarySearch.cpp (100%) rename {Shuffle => other_languages/cpp/Shuffle}/Shuffle.cpp (100%) rename {Sort => other_languages/cpp/Sort}/BubbleSort.cpp (100%) rename {Sort => other_languages/cpp/Sort}/CountingSort.cpp (100%) rename {Sort => other_languages/cpp/Sort}/GnomeSort.cpp (100%) rename {Sort => other_languages/cpp/Sort}/HeapSort.cpp (100%) rename {Sort => other_languages/cpp/Sort}/InsertionSort.cpp (100%) rename {Sort => other_languages/cpp/Sort}/MergeBottomUp.cpp (100%) rename {Sort => other_languages/cpp/Sort}/MergeOptimizeSort.cpp (100%) rename {Sort => other_languages/cpp/Sort}/MergeSort.cpp (100%) rename {Sort => other_languages/cpp/Sort}/OddEvenSort.cpp (100%) rename {Sort => other_languages/cpp/Sort}/Quick3WaySort.cpp (100%) rename {Sort => other_languages/cpp/Sort}/QuickOptimizeSort.cpp (100%) rename {Sort => other_languages/cpp/Sort}/QuickSelect.cpp (100%) rename {Sort => other_languages/cpp/Sort}/QuickSort.cpp (100%) rename {Sort => other_languages/cpp/Sort}/SelectionSort.cpp (100%) rename {Sort => other_languages/cpp/Sort}/ShellSort.cpp (100%) rename {Stack => other_languages/cpp/Stack}/Stack/Makefile (100%) rename {Stack => other_languages/cpp/Stack}/Stack/Stack.hpp (100%) rename {Stack => other_languages/cpp/Stack}/Stack/test_Stack.cpp (100%) rename {Stack => other_languages/cpp/Stack}/balancedParanthesis.cpp (100%) rename {Stack => other_languages/cpp/Stack}/bracketReversals.cpp (100%) rename {Stack => other_languages/cpp/Stack}/deleteMiddleElement.cpp (100%) rename {Stack => other_languages/cpp/Stack}/infixToPostfix.cpp (100%) rename {Stack => other_languages/cpp/Stack}/trackingCurrentMax.cpp (100%) rename {Go => other_languages/go}/README.md (100%) rename {Go => other_languages/go}/bst/bst.go (100%) rename {Go => other_languages/go}/bst/bst_test.go (100%) rename {Go => other_languages/go}/bst/checkbst.go (100%) rename {Go => other_languages/go}/bst/delete.go (100%) rename {Go => other_languages/go}/bst/find.go (100%) rename {Go => other_languages/go}/bst/height.go (100%) rename {Go => other_languages/go}/bst/insert.go (100%) rename {Go => other_languages/go}/bst/traversal.go (100%) rename {Go => other_languages/go}/doublylinkedlist/doublylinkedlist.go (100%) rename {Go => other_languages/go}/doublylinkedlist/doublylinkedlist_test.go (100%) rename {Go => other_languages/go}/hashtable/hashtable.go (100%) rename {Go => other_languages/go}/hashtable/hashtable_test.go (100%) rename {Go => other_languages/go}/heap/doc.go (100%) rename {Go => other_languages/go}/heap/maxheap/maxheap.go (100%) rename {Go => other_languages/go}/heap/maxheap/maxheap_test.go (100%) rename {Go => other_languages/go}/heap/minheap/minheap.go (100%) rename {Go => other_languages/go}/heap/minheap/minheap_test.go (100%) rename {Go => other_languages/go}/linkedlist/linkedlist.go (100%) rename {Go => other_languages/go}/linkedlist/linkedlist_test.go (100%) rename {Go => other_languages/go}/queue/queue.go (100%) rename {Go => other_languages/go}/queue/queue_test.go (100%) rename {Go => other_languages/go}/redblacktree/doc.go (100%) rename {Go => other_languages/go}/redblacktree/find.go (100%) rename {Go => other_languages/go}/redblacktree/insert.go (100%) rename {Go => other_languages/go}/redblacktree/redblacktree.go (100%) rename {Go => other_languages/go}/redblacktree/redblacktree_test.go (100%) rename {Go => other_languages/go}/redblacktree/utils.go (100%) rename {Go => other_languages/go}/search/binarysearch.go (100%) rename {Go => other_languages/go}/search/binarysearch_test.go (100%) rename {Go => other_languages/go}/set/set.go (100%) rename {Go => other_languages/go}/set/set_test.go (100%) rename {Go => other_languages/go}/shuffle/shuffle.go (100%) rename {Go => other_languages/go}/sort/bubble.go (100%) rename {Go => other_languages/go}/sort/countingSort.go (100%) rename {Go => other_languages/go}/sort/gnome.go (100%) rename {Go => other_languages/go}/sort/heap.go (100%) rename {Go => other_languages/go}/sort/insertion.go (100%) rename {Go => other_languages/go}/sort/merge.go (100%) rename {Go => other_languages/go}/sort/oddeven.go (100%) rename {Go => other_languages/go}/sort/quick.go (100%) rename {Go => other_languages/go}/sort/quickselect.go (100%) rename {Go => other_languages/go}/sort/selection.go (100%) rename {Go => other_languages/go}/sort/shell.go (100%) rename {Go => other_languages/go}/sort/sort.go (100%) rename {Go => other_languages/go}/sort/sort_test.go (100%) rename {Go => other_languages/go}/stack/applications/applications.go (100%) rename {Go => other_languages/go}/stack/applications/applications_test.go (100%) rename {Go => other_languages/go}/stack/applications/infixevaluation.go (100%) rename {Go => other_languages/go}/stack/applications/infixtopostfix.go (100%) rename {Go => other_languages/go}/stack/applications/infixtoprefix.go (100%) rename {Go => other_languages/go}/stack/applications/utils.go (100%) rename {Go => other_languages/go}/stack/stack.go (100%) rename {Go => other_languages/go}/stack/stack_test.go (100%) rename {Go => other_languages/go}/trie/trie.go (100%) rename {Go => other_languages/go}/trie/trie_test.go (100%) diff --git a/other_languages/c/README.md b/other_languages/c/README.md new file mode 100644 index 0000000..2d6e4de --- /dev/null +++ b/other_languages/c/README.md @@ -0,0 +1,8 @@ +# Algorithm (C Implementation) +Data Structure Libraries and Algorithms implementation in C Language. + +## Data structure + +## Contribution +Feel Free to contribute.
+Please follow standard C Guidelines. diff --git a/C/dynamic_connectivity/quick_find/Makefile b/other_languages/c/dynamic_connectivity/quick_find/Makefile similarity index 100% rename from C/dynamic_connectivity/quick_find/Makefile rename to other_languages/c/dynamic_connectivity/quick_find/Makefile diff --git a/C/dynamic_connectivity/quick_find/main.c b/other_languages/c/dynamic_connectivity/quick_find/main.c similarity index 98% rename from C/dynamic_connectivity/quick_find/main.c rename to other_languages/c/dynamic_connectivity/quick_find/main.c index f7f2838..d0d2b58 100644 --- a/C/dynamic_connectivity/quick_find/main.c +++ b/other_languages/c/dynamic_connectivity/quick_find/main.c @@ -5,7 +5,7 @@ int main() { int n = 10; int *arr = initialize(n); - + join_union(arr, n, 4, 3); join_union(arr, n, 3, 8); join_union(arr, n, 6, 5); @@ -18,7 +18,7 @@ int main() join_union(arr, n, 6, 1); join_union(arr, n, 1, 0); printf("%d\n", connected(arr, 0, 7)); - + terminate(arr); return 0; } diff --git a/C/dynamic_connectivity/quick_find/quick_find.c b/other_languages/c/dynamic_connectivity/quick_find/quick_find.c similarity index 93% rename from C/dynamic_connectivity/quick_find/quick_find.c rename to other_languages/c/dynamic_connectivity/quick_find/quick_find.c index 5898cac..bbf67c5 100644 --- a/C/dynamic_connectivity/quick_find/quick_find.c +++ b/other_languages/c/dynamic_connectivity/quick_find/quick_find.c @@ -15,10 +15,10 @@ join_union(int *arr, int n, int p, int q) { int pid = arr[p]; int qid = arr[q]; - + for (int i = 0; i < n; i++) if (arr[i] == pid) - arr[i] = qid; + arr[i] = qid; } int diff --git a/C/dynamic_connectivity/quick_find/quick_find.h b/other_languages/c/dynamic_connectivity/quick_find/quick_find.h similarity index 100% rename from C/dynamic_connectivity/quick_find/quick_find.h rename to other_languages/c/dynamic_connectivity/quick_find/quick_find.h diff --git a/C/dynamic_connectivity/quick_union/Makefile b/other_languages/c/dynamic_connectivity/quick_union/Makefile similarity index 100% rename from C/dynamic_connectivity/quick_union/Makefile rename to other_languages/c/dynamic_connectivity/quick_union/Makefile diff --git a/C/dynamic_connectivity/quick_union/main.c b/other_languages/c/dynamic_connectivity/quick_union/main.c similarity index 98% rename from C/dynamic_connectivity/quick_union/main.c rename to other_languages/c/dynamic_connectivity/quick_union/main.c index c01681e..fcbe798 100644 --- a/C/dynamic_connectivity/quick_union/main.c +++ b/other_languages/c/dynamic_connectivity/quick_union/main.c @@ -6,7 +6,7 @@ int main() int n = 10; int *arr = initialize(n); int *sz = size_array_initialize(n); - + join_union(arr, sz, n, 4, 3); join_union(arr, sz, n, 3, 8); join_union(arr, sz, n, 6, 5); @@ -19,7 +19,7 @@ int main() join_union(arr, sz, n, 6, 1); join_union(arr, sz, n, 1, 0); printf("%d\n", connected(arr, 0, 7)); - + terminate(arr); return 0; } diff --git a/C/dynamic_connectivity/quick_union/quick_union.c b/other_languages/c/dynamic_connectivity/quick_union/quick_union.c similarity index 100% rename from C/dynamic_connectivity/quick_union/quick_union.c rename to other_languages/c/dynamic_connectivity/quick_union/quick_union.c diff --git a/C/dynamic_connectivity/quick_union/quick_union.h b/other_languages/c/dynamic_connectivity/quick_union/quick_union.h similarity index 100% rename from C/dynamic_connectivity/quick_union/quick_union.h rename to other_languages/c/dynamic_connectivity/quick_union/quick_union.h diff --git a/C/queue/Makefile b/other_languages/c/queue/Makefile similarity index 100% rename from C/queue/Makefile rename to other_languages/c/queue/Makefile diff --git a/C/queue/main.c b/other_languages/c/queue/main.c similarity index 99% rename from C/queue/main.c rename to other_languages/c/queue/main.c index 1049cec..ee2dc1a 100644 --- a/C/queue/main.c +++ b/other_languages/c/queue/main.c @@ -26,7 +26,7 @@ main(void) printf("Unable to remove element. Error Code: %d\n", ret); display(pt); - + ret = dequeue(pt, &removed_value); if (ret == 0) printf("Removed Element is %d\n", removed_value); diff --git a/C/queue/queue.c b/other_languages/c/queue/queue.c similarity index 99% rename from C/queue/queue.c rename to other_languages/c/queue/queue.c index 96b086b..a6c7053 100644 --- a/C/queue/queue.c +++ b/other_languages/c/queue/queue.c @@ -1,6 +1,6 @@ /* * Queue (C implementation) - * Author: Priyank Chheda + * Author: Priyank Chheda * E: p.chheda29@gmail.com * W: https://github.com/x899 * diff --git a/C/queue/queue.h b/other_languages/c/queue/queue.h similarity index 97% rename from C/queue/queue.h rename to other_languages/c/queue/queue.h index 315ab5e..fc43668 100644 --- a/C/queue/queue.h +++ b/other_languages/c/queue/queue.h @@ -1,6 +1,6 @@ /* * Queue (C implementation) - * Author: Priyank Chheda + * Author: Priyank Chheda * E: p.chheda29@gmail.com * W: https://github.com/x899 * diff --git a/C/shuffling/Makefile b/other_languages/c/shuffling/Makefile similarity index 88% rename from C/shuffling/Makefile rename to other_languages/c/shuffling/Makefile index 391b07a..26d38a3 100644 --- a/C/shuffling/Makefile +++ b/other_languages/c/shuffling/Makefile @@ -1,5 +1,5 @@ CC=gcc -CFLAGS=-O2 -Wall +CFLAGS=-O2 -Wall shuffle: shuffle_array.o $(CC) $(CFLAGS) -o $@ $< diff --git a/C/shuffling/shuffle_array.c b/other_languages/c/shuffling/shuffle_array.c similarity index 100% rename from C/shuffling/shuffle_array.c rename to other_languages/c/shuffling/shuffle_array.c diff --git a/C/sorts/bubble_sort/Makefile b/other_languages/c/sorts/bubble_sort/Makefile similarity index 87% rename from C/sorts/bubble_sort/Makefile rename to other_languages/c/sorts/bubble_sort/Makefile index 247b6d2..a5914a1 100644 --- a/C/sorts/bubble_sort/Makefile +++ b/other_languages/c/sorts/bubble_sort/Makefile @@ -1,5 +1,5 @@ CC=gcc -CFLAGS=-O2 -Wall +CFLAGS=-O2 -Wall sort: bubble_sort.o $(CC) $(CFLAGS) -o $@ $< diff --git a/C/sorts/bubble_sort/bubble_sort.c b/other_languages/c/sorts/bubble_sort/bubble_sort.c similarity index 96% rename from C/sorts/bubble_sort/bubble_sort.c rename to other_languages/c/sorts/bubble_sort/bubble_sort.c index 3ff610b..a4ee36a 100644 --- a/C/sorts/bubble_sort/bubble_sort.c +++ b/other_languages/c/sorts/bubble_sort/bubble_sort.c @@ -1,9 +1,9 @@ /* * Sorting Algorithms * Bubble Sort (C implementation) - * Author: Priyank Chheda + * Author: Priyank Chheda * E: p.chheda29@gmail.com - * W: https://github.com/x899 + * W: https://github.com/priyankchheda * * Bubble sort is a simple sorting algorithm that repeatedly steps through * the list to be sorted, compares each pair of adjacent items and swaps diff --git a/C/sorts/generic/Makefile b/other_languages/c/sorts/generic/Makefile similarity index 90% rename from C/sorts/generic/Makefile rename to other_languages/c/sorts/generic/Makefile index f3974cf..cfca5c2 100644 --- a/C/sorts/generic/Makefile +++ b/other_languages/c/sorts/generic/Makefile @@ -1,5 +1,5 @@ CC=gcc -CFLAGS=-O2 -Wall +CFLAGS=-O2 -Wall main: main.o sort.o diff --git a/C/sorts/generic/README.md b/other_languages/c/sorts/generic/README.md similarity index 72% rename from C/sorts/generic/README.md rename to other_languages/c/sorts/generic/README.md index d75cf8f..078885b 100644 --- a/C/sorts/generic/README.md +++ b/other_languages/c/sorts/generic/README.md @@ -6,7 +6,5 @@ 3. Selection Sort 4. Merge Sort 5. Quick Sort + 6. Shell Sort -## TO DO - 1. Generic Heap Sort - 2. Generic Radix Sort diff --git a/C/sorts/generic/main.c b/other_languages/c/sorts/generic/main.c similarity index 98% rename from C/sorts/generic/main.c rename to other_languages/c/sorts/generic/main.c index be08fbc..6ce4e28 100644 --- a/C/sorts/generic/main.c +++ b/other_languages/c/sorts/generic/main.c @@ -19,7 +19,7 @@ main(int argc, char *argv[]) 89.98, 12.3, 67.78, 2.8}; size_t elem_count = sizeof(array) / sizeof(array[0]); size_t elem_size = sizeof(array[0]); - + printf("Original Array: "); print_array(array, elem_count, elem_size); // bubble_sort(array, elem_count, elem_size, compare_int); @@ -58,7 +58,7 @@ compare_int(void* elem1, void* elem2) { int *p1 = (int*) elem1; int *p2 = (int*) elem2; - return *p1 - *p2; + return *p1 - *p2; } diff --git a/C/sorts/generic/sort.c b/other_languages/c/sorts/generic/sort.c similarity index 99% rename from C/sorts/generic/sort.c rename to other_languages/c/sorts/generic/sort.c index 8b681e5..8ed3077 100644 --- a/C/sorts/generic/sort.c +++ b/other_languages/c/sorts/generic/sort.c @@ -1,8 +1,8 @@ /* * Generic Sorting Algorithms - * Author: Priyank Chheda + * Author: Priyank Chheda * E: p.chheda29@gmail.com - * W: https://github.com/x899 + * W: https://github.com/priyankchheda * */ @@ -92,7 +92,7 @@ insertion_sort( void* array, int index = i; void *value = malloc(elem_size); memcpy(value, array + (i * elem_size), elem_size); - + while ( index > 0 && compare(array + ((index - 1) * elem_size), value) > 0) { @@ -111,8 +111,8 @@ insertion_sort( void* array, * Selection Sort Function * * The selection sort algorithm sorts an array by repeatedly finding the - * minimum element (considering ascending order) from unsorted part and - * putting it at the beginning. The algorithm maintains two subarrays in + * minimum element (considering ascending order) from unsorted part and + * putting it at the beginning. The algorithm maintains two subarrays in * a given array. * - The subarray which is already sorted. * - Remaining subarray which is unsorted. diff --git a/C/sorts/generic/sort.h b/other_languages/c/sorts/generic/sort.h similarity index 88% rename from C/sorts/generic/sort.h rename to other_languages/c/sorts/generic/sort.h index db4070b..3320007 100644 --- a/C/sorts/generic/sort.h +++ b/other_languages/c/sorts/generic/sort.h @@ -1,8 +1,8 @@ /* * Generic Sorting Algorithms - * Author: Priyank Chheda + * Author: Priyank Chheda * E: p.chheda29@gmail.com - * W: https://github.com/x899 + * W: https://github.com/priyankchheda * */ diff --git a/C/sorts/insertion_sort/Makefile b/other_languages/c/sorts/insertion_sort/Makefile similarity index 88% rename from C/sorts/insertion_sort/Makefile rename to other_languages/c/sorts/insertion_sort/Makefile index 77241d0..d84d735 100644 --- a/C/sorts/insertion_sort/Makefile +++ b/other_languages/c/sorts/insertion_sort/Makefile @@ -1,5 +1,5 @@ CC=gcc -CFLAGS=-O2 -Wall +CFLAGS=-O2 -Wall sort: insertion_sort.o $(CC) $(CFLAGS) -o $@ $< diff --git a/C/sorts/insertion_sort/insertion_sort.c b/other_languages/c/sorts/insertion_sort/insertion_sort.c similarity index 98% rename from C/sorts/insertion_sort/insertion_sort.c rename to other_languages/c/sorts/insertion_sort/insertion_sort.c index c81483c..29b2a51 100644 --- a/C/sorts/insertion_sort/insertion_sort.c +++ b/other_languages/c/sorts/insertion_sort/insertion_sort.c @@ -1,7 +1,7 @@ /* * Sorting Algorithms * Insertion Sort (C implementation) - * Author: Priyank Chheda + * Author: Priyank Chheda * E: p.chheda29@gmail.com * W: https://github.com/x899 * diff --git a/C/sorts/merge_sort/Makefile b/other_languages/c/sorts/merge_sort/Makefile similarity index 87% rename from C/sorts/merge_sort/Makefile rename to other_languages/c/sorts/merge_sort/Makefile index c6af4dd..48031d2 100644 --- a/C/sorts/merge_sort/Makefile +++ b/other_languages/c/sorts/merge_sort/Makefile @@ -1,5 +1,5 @@ CC=gcc -CFLAGS=-O2 -Wall +CFLAGS=-O2 -Wall sort: merge_sort.o $(CC) $(CFLAGS) -o $@ $< diff --git a/C/sorts/merge_sort/merge_sort.c b/other_languages/c/sorts/merge_sort/merge_sort.c similarity index 100% rename from C/sorts/merge_sort/merge_sort.c rename to other_languages/c/sorts/merge_sort/merge_sort.c diff --git a/C/sorts/quick_sort/Makefile b/other_languages/c/sorts/quick_sort/Makefile similarity index 87% rename from C/sorts/quick_sort/Makefile rename to other_languages/c/sorts/quick_sort/Makefile index 4876b99..e1609df 100644 --- a/C/sorts/quick_sort/Makefile +++ b/other_languages/c/sorts/quick_sort/Makefile @@ -1,5 +1,5 @@ CC=gcc -CFLAGS=-O2 -Wall +CFLAGS=-O2 -Wall sort: quick_sort.o $(CC) $(CFLAGS) -o $@ $< diff --git a/C/sorts/quick_sort/quick_sort.c b/other_languages/c/sorts/quick_sort/quick_sort.c similarity index 99% rename from C/sorts/quick_sort/quick_sort.c rename to other_languages/c/sorts/quick_sort/quick_sort.c index e39d15f..554b0e2 100644 --- a/C/sorts/quick_sort/quick_sort.c +++ b/other_languages/c/sorts/quick_sort/quick_sort.c @@ -1,7 +1,7 @@ /* * Sorting Algorithms * Quick Sort (C implementation) - * Author: Priyank Chheda + * Author: Priyank Chheda * E: p.chheda29@gmail.com * W: https://github.com/x899 * Quick sort is based on the divide-and-conquer approach based on the idea diff --git a/C/sorts/selection_sort/Makefile b/other_languages/c/sorts/selection_sort/Makefile similarity index 88% rename from C/sorts/selection_sort/Makefile rename to other_languages/c/sorts/selection_sort/Makefile index c8d0fea..f745415 100644 --- a/C/sorts/selection_sort/Makefile +++ b/other_languages/c/sorts/selection_sort/Makefile @@ -1,5 +1,5 @@ CC=gcc -CFLAGS=-O2 -Wall +CFLAGS=-O2 -Wall sort: selection_sort.o $(CC) $(CFLAGS) -o $@ $< diff --git a/C/sorts/selection_sort/selection_sort.c b/other_languages/c/sorts/selection_sort/selection_sort.c similarity index 97% rename from C/sorts/selection_sort/selection_sort.c rename to other_languages/c/sorts/selection_sort/selection_sort.c index 9327c96..4850193 100644 --- a/C/sorts/selection_sort/selection_sort.c +++ b/other_languages/c/sorts/selection_sort/selection_sort.c @@ -1,13 +1,13 @@ /* * Sorting Algorithms * Selection Sort (C implementation) - * Author: Priyank Chheda + * Author: Priyank Chheda * E: p.chheda29@gmail.com * W: https://github.com/x899 * * The selection sort algorithm sorts an array by repeatedly finding the - * minimum element (considering ascending order) from unsorted part and - * putting it at the beginning. The algorithm maintains two subarrays in + * minimum element (considering ascending order) from unsorted part and + * putting it at the beginning. The algorithm maintains two subarrays in * a given array. * - The subarray which is already sorted. * - Remaining subarray which is unsorted. @@ -54,7 +54,7 @@ selection_sort(int array[], size_t array_size) if (array[j] < array[min_element_index]) min_element_index = j; } - + /* swap those two element */ swap(&array[i], &array[min_element_index]); } @@ -88,4 +88,4 @@ swap(int* a, int* b) int temp = *a; *a = *b; *b = temp; -} \ No newline at end of file +} diff --git a/C/sorts/shell_sort/Makefile b/other_languages/c/sorts/shell_sort/Makefile similarity index 87% rename from C/sorts/shell_sort/Makefile rename to other_languages/c/sorts/shell_sort/Makefile index 44c44f1..4641358 100644 --- a/C/sorts/shell_sort/Makefile +++ b/other_languages/c/sorts/shell_sort/Makefile @@ -1,5 +1,5 @@ CC=gcc -CFLAGS=-O2 -Wall +CFLAGS=-O2 -Wall sort: shell_sort.o $(CC) $(CFLAGS) -o $@ $< diff --git a/C/sorts/shell_sort/shell_sort.c b/other_languages/c/sorts/shell_sort/shell_sort.c similarity index 98% rename from C/sorts/shell_sort/shell_sort.c rename to other_languages/c/sorts/shell_sort/shell_sort.c index 2908767..b627ec5 100644 --- a/C/sorts/shell_sort/shell_sort.c +++ b/other_languages/c/sorts/shell_sort/shell_sort.c @@ -1,7 +1,7 @@ /* * Sorting Algorithms * Shell Sort (C implementation) - * Author: Priyank Chheda + * Author: Priyank Chheda * E: p.chheda29@gmail.com * W: https://github.com/x899 * diff --git a/C/stack/array_implementation/Makefile b/other_languages/c/stack/array_implementation/Makefile similarity index 100% rename from C/stack/array_implementation/Makefile rename to other_languages/c/stack/array_implementation/Makefile diff --git a/C/stack/array_implementation/main.c b/other_languages/c/stack/array_implementation/main.c similarity index 98% rename from C/stack/array_implementation/main.c rename to other_languages/c/stack/array_implementation/main.c index 1ad8034..89b9fb1 100644 --- a/C/stack/array_implementation/main.c +++ b/other_languages/c/stack/array_implementation/main.c @@ -19,7 +19,7 @@ main(void) printf("Top element is %d\n", peek_value); else printf("Unable to get peek value. Error Code: %d\n", peek_return); - + int pop_value; int pop_return = pop(pt, &pop_value); if (pop_return == 0) @@ -27,7 +27,7 @@ main(void) else printf("Unable to get popped value. Error Code: %d\n", pop_return); - + int push_return = push(pt, 2); if (push_return == 0) printf("Successfully pushed to stack\n"); diff --git a/C/stack/array_implementation/stack.c b/other_languages/c/stack/array_implementation/stack.c similarity index 94% rename from C/stack/array_implementation/stack.c rename to other_languages/c/stack/array_implementation/stack.c index bff193e..7f98077 100644 --- a/C/stack/array_implementation/stack.c +++ b/other_languages/c/stack/array_implementation/stack.c @@ -1,6 +1,6 @@ /* * Stack (C implementation) - * Author: Priyank Chheda + * Author: Priyank Chheda * E: p.chheda29@gmail.com * W: https://github.com/x899 * @@ -14,8 +14,8 @@ #include "stack.h" -/** - * Create New Stack with heap memory +/** + * Create New Stack with heap memory * @param capacity Initial capacity of Stack * @return pointer to newly created stack */ @@ -83,7 +83,7 @@ int push(STACK *pt, int element) /** * peek top element from stack * @param pt Stack pointer - * @param result pointer to store peek element + * @param result pointer to store peek element * @return status code */ int peek(STACK *pt, int* result) @@ -106,7 +106,7 @@ int pop(STACK *pt, int* popped_value) { if (isEmpty(pt)) return STACK_EMPTY; - + *popped_value = pt->items[pt->top]; pt->top--; return 0; diff --git a/C/stack/array_implementation/stack.h b/other_languages/c/stack/array_implementation/stack.h similarity index 95% rename from C/stack/array_implementation/stack.h rename to other_languages/c/stack/array_implementation/stack.h index 7a8066b..f5288f3 100644 --- a/C/stack/array_implementation/stack.h +++ b/other_languages/c/stack/array_implementation/stack.h @@ -1,6 +1,6 @@ /* * Stack (C implementation) - * Author: Priyank Chheda + * Author: Priyank Chheda * E: p.chheda29@gmail.com * W: https://github.com/x899 * diff --git a/C/stack/generic_array_implementation/Makefile b/other_languages/c/stack/generic_array_implementation/Makefile similarity index 100% rename from C/stack/generic_array_implementation/Makefile rename to other_languages/c/stack/generic_array_implementation/Makefile diff --git a/C/stack/generic_array_implementation/main.c b/other_languages/c/stack/generic_array_implementation/main.c similarity index 99% rename from C/stack/generic_array_implementation/main.c rename to other_languages/c/stack/generic_array_implementation/main.c index 95119e5..c1d9961 100644 --- a/C/stack/generic_array_implementation/main.c +++ b/other_languages/c/stack/generic_array_implementation/main.c @@ -14,10 +14,10 @@ main() STACK *pt = create_stack(5, sizeof(float), NULL); printf("Size of Stack: %d\n", size(pt)); display(pt); - + float element = 1.45; push(pt, (void*)&element); - + element = 5.76; push(pt, (void*)&element); printf("Size of Stack: %d\n", size(pt)); @@ -29,7 +29,7 @@ main() printf("Top element is %.2f\n", peek_value); else printf("Unable to get peek value. Error Code: %d\n", peek_return); - + float pop_value; int pop_return = pop(pt, (void*)&pop_value); if (pop_return == 0) diff --git a/C/stack/generic_array_implementation/stack.c b/other_languages/c/stack/generic_array_implementation/stack.c similarity index 95% rename from C/stack/generic_array_implementation/stack.c rename to other_languages/c/stack/generic_array_implementation/stack.c index 946ae70..fccd236 100644 --- a/C/stack/generic_array_implementation/stack.c +++ b/other_languages/c/stack/generic_array_implementation/stack.c @@ -1,6 +1,6 @@ /* * Generic Stack (C implementation) - * Author: Priyank Chheda + * Author: Priyank Chheda * E: p.chheda29@gmail.com * W: https://github.com/x899 * @@ -16,8 +16,8 @@ #include "stack.h" -/** - * Create New Stack with heap memory +/** + * Create New Stack with heap memory * @param capacity Initial capacity of Stack * @param elem_size size of each element * @param freeFunc function to free elements in stack @@ -37,7 +37,7 @@ create_stack(int capacity, size_t elem_size, freeFunction freeFunc) } -/** +/** * Destroy Stack by freeing heap memory * @param pt Stack pointer */ @@ -51,7 +51,7 @@ destroy_stack(STACK *pt) pt->freeFunc(pt->items + (i * pt->elem_size)); } } - + free(pt->items); free(pt); } @@ -116,7 +116,7 @@ push(STACK *pt, void* element) /** * peek top element from stack * @param pt Stack pointer - * @param result pointer to store peek element + * @param result pointer to store peek element * @return status code */ int diff --git a/C/stack/generic_array_implementation/stack.h b/other_languages/c/stack/generic_array_implementation/stack.h similarity index 97% rename from C/stack/generic_array_implementation/stack.h rename to other_languages/c/stack/generic_array_implementation/stack.h index 8cdeec3..d5a7031 100644 --- a/C/stack/generic_array_implementation/stack.h +++ b/other_languages/c/stack/generic_array_implementation/stack.h @@ -1,6 +1,6 @@ /* * Generic Stack (C implementation) - * Author: Priyank Chheda + * Author: Priyank Chheda * E: p.chheda29@gmail.com * W: https://github.com/x899 * diff --git a/other_languages/cpp/.DS_Store b/other_languages/cpp/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..0912e1c1f34344e49496c0161c05e5aa797001fa GIT binary patch literal 6148 zcmeHK%TB{U44f?iO5sq63&;Ede-MQrao_^w1Aw%ssG&h^iqu;^ow0Wn5>g~is6uw- zosHMt$7~eW09?A6UIJqPL#p85gv}0-anYU(f@MT>I>!oIOfbU}Ry}Vs>>~qmcVnb@ z#ZqtW>;7`g@xXhWVK!ao#dBE}a)5JWykv2HV^EGOlzdv!Ek{Mm2erbs9TMS2---9O zafDl4bitvi_SdM|4u`nIhJ)0$`3(0Ok)q%pax8Xj@~C+Wd5U)QF$d$IoY$D6c083V?EG4Oi^n6pKOryi{}28;n?pkYA14>46R30Qm7PX`+< z0f-UJD(p)wAu(~lBw+24BNXRDi9XbY62tj$+T-At1gt&!aJW!>xUjMd6^hfd!&V8e*}~UYm9+EW#AJUS5Y?r literal 0 HcmV?d00001 diff --git a/BinarySearchTree/BST/BST.cpp b/other_languages/cpp/BinarySearchTree/BST/BST.cpp similarity index 100% rename from BinarySearchTree/BST/BST.cpp rename to other_languages/cpp/BinarySearchTree/BST/BST.cpp diff --git a/BinarySearchTree/BST/BST.hpp b/other_languages/cpp/BinarySearchTree/BST/BST.hpp similarity index 100% rename from BinarySearchTree/BST/BST.hpp rename to other_languages/cpp/BinarySearchTree/BST/BST.hpp diff --git a/BinarySearchTree/BST/Makefile b/other_languages/cpp/BinarySearchTree/BST/Makefile similarity index 100% rename from BinarySearchTree/BST/Makefile rename to other_languages/cpp/BinarySearchTree/BST/Makefile diff --git a/BinarySearchTree/BST/test_BST.cpp b/other_languages/cpp/BinarySearchTree/BST/test_BST.cpp similarity index 100% rename from BinarySearchTree/BST/test_BST.cpp rename to other_languages/cpp/BinarySearchTree/BST/test_BST.cpp diff --git a/BinarySearchTree/Nqueen b/other_languages/cpp/BinarySearchTree/Nqueen similarity index 100% rename from BinarySearchTree/Nqueen rename to other_languages/cpp/BinarySearchTree/Nqueen diff --git a/BinarySearchTree/bfsTraversal.cpp b/other_languages/cpp/BinarySearchTree/bfsTraversal.cpp similarity index 100% rename from BinarySearchTree/bfsTraversal.cpp rename to other_languages/cpp/BinarySearchTree/bfsTraversal.cpp diff --git a/BinarySearchTree/dfsTraversal.cpp b/other_languages/cpp/BinarySearchTree/dfsTraversal.cpp similarity index 100% rename from BinarySearchTree/dfsTraversal.cpp rename to other_languages/cpp/BinarySearchTree/dfsTraversal.cpp diff --git a/BinarySearchTree/inorderSuccessor.cpp b/other_languages/cpp/BinarySearchTree/inorderSuccessor.cpp similarity index 100% rename from BinarySearchTree/inorderSuccessor.cpp rename to other_languages/cpp/BinarySearchTree/inorderSuccessor.cpp diff --git a/BinarySearchTree/isBST.cpp b/other_languages/cpp/BinarySearchTree/isBST.cpp similarity index 100% rename from BinarySearchTree/isBST.cpp rename to other_languages/cpp/BinarySearchTree/isBST.cpp diff --git a/DynamicConnectivity/QuickFind.cpp b/other_languages/cpp/DynamicConnectivity/QuickFind.cpp similarity index 100% rename from DynamicConnectivity/QuickFind.cpp rename to other_languages/cpp/DynamicConnectivity/QuickFind.cpp diff --git a/DynamicConnectivity/QuickUnion.cpp b/other_languages/cpp/DynamicConnectivity/QuickUnion.cpp similarity index 100% rename from DynamicConnectivity/QuickUnion.cpp rename to other_languages/cpp/DynamicConnectivity/QuickUnion.cpp diff --git a/DynamicConnectivity/WeightedQuickUnion.cpp b/other_languages/cpp/DynamicConnectivity/WeightedQuickUnion.cpp similarity index 100% rename from DynamicConnectivity/WeightedQuickUnion.cpp rename to other_languages/cpp/DynamicConnectivity/WeightedQuickUnion.cpp diff --git a/other_languages/cpp/Heap/.DS_Store b/other_languages/cpp/Heap/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..8223fe7b8152c985ed49f79ee22cf003c76a5a85 GIT binary patch literal 6148 zcmeH~y{ZC1426^H7Q$_|w4BBV@C^o0u=fT0Sv$cC7yEg1Pks#z{%MPv#$%G|=p6nQ5bImurBhX3RFaJiiG%umwJz25KWbr01*pK6 zDWKhIyISI<@@{>4J*)4sYU>6E{W!wIPXH3Tif3>)>=#>rHQ9ow!1yEJGB8kqw<>T0 Da%~cU literal 0 HcmV?d00001 diff --git a/Heap/Heap/HeapException.hpp b/other_languages/cpp/Heap/Heap/HeapException.hpp similarity index 100% rename from Heap/Heap/HeapException.hpp rename to other_languages/cpp/Heap/Heap/HeapException.hpp diff --git a/Heap/Heap/Makefile b/other_languages/cpp/Heap/Heap/Makefile similarity index 100% rename from Heap/Heap/Makefile rename to other_languages/cpp/Heap/Heap/Makefile diff --git a/Heap/Heap/MaxHeap.hpp b/other_languages/cpp/Heap/Heap/MaxHeap.hpp similarity index 100% rename from Heap/Heap/MaxHeap.hpp rename to other_languages/cpp/Heap/Heap/MaxHeap.hpp diff --git a/Heap/Heap/MinHeap.hpp b/other_languages/cpp/Heap/Heap/MinHeap.hpp similarity index 100% rename from Heap/Heap/MinHeap.hpp rename to other_languages/cpp/Heap/Heap/MinHeap.hpp diff --git a/Heap/Heap/test_Heap.cpp b/other_languages/cpp/Heap/Heap/test_Heap.cpp similarity index 100% rename from Heap/Heap/test_Heap.cpp rename to other_languages/cpp/Heap/Heap/test_Heap.cpp diff --git a/other_languages/cpp/LinkedList/.DS_Store b/other_languages/cpp/LinkedList/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..2c6d20864d583b6f0ee1b61ea0f05d14b7c24390 GIT binary patch literal 6148 zcmeHKyG{c^3>-s>2%3~B_ZRqsRTMfpegMIxKt!Yn^jGD(_%y~3A)-r~NHl0H*|Y2O z+-j#dp8?qFbGQQ*0OoW@96U_TpSw@&sxn5T^Bo%uc)%<6_?T3mPB`}_IPZA-%^&tJ z+vnYGdzz-K6p#W^Knh3!DR7|z-g{~D+eAevAO)nrj{^REXmrP3I3~uYgCRx$;*9Aq zu49%UHct?H;h4w_&5}w?s?~^LNoT%QT`wFHlMbul!|G(K3B}@czQ08|tS2f;0V!~- zz;$jH-v96EXXgK7l6F!+3j8YtY_@(}uXv^Et&_`nuWj@vy4QTs-M9`4L$qUJv}10( f9WSFO>zc3mycdp%L1#YbMEwl7E;1?b*9v?Cj9L{! literal 0 HcmV?d00001 diff --git a/LinkedList/LinkedList/LinkedList.hpp b/other_languages/cpp/LinkedList/LinkedList/LinkedList.hpp similarity index 100% rename from LinkedList/LinkedList/LinkedList.hpp rename to other_languages/cpp/LinkedList/LinkedList/LinkedList.hpp diff --git a/LinkedList/LinkedList/Makefile b/other_languages/cpp/LinkedList/LinkedList/Makefile similarity index 100% rename from LinkedList/LinkedList/Makefile rename to other_languages/cpp/LinkedList/LinkedList/Makefile diff --git a/LinkedList/LinkedList/test_LinkedList.cpp b/other_languages/cpp/LinkedList/LinkedList/test_LinkedList.cpp similarity index 100% rename from LinkedList/LinkedList/test_LinkedList.cpp rename to other_languages/cpp/LinkedList/LinkedList/test_LinkedList.cpp diff --git a/LinkedList/countFrequency.cpp b/other_languages/cpp/LinkedList/countFrequency.cpp similarity index 100% rename from LinkedList/countFrequency.cpp rename to other_languages/cpp/LinkedList/countFrequency.cpp diff --git a/LinkedList/detectLoop.cpp b/other_languages/cpp/LinkedList/detectLoop.cpp similarity index 100% rename from LinkedList/detectLoop.cpp rename to other_languages/cpp/LinkedList/detectLoop.cpp diff --git a/LinkedList/findMiddle.cpp b/other_languages/cpp/LinkedList/findMiddle.cpp similarity index 100% rename from LinkedList/findMiddle.cpp rename to other_languages/cpp/LinkedList/findMiddle.cpp diff --git a/LinkedList/getNthNodeFromEnd.cpp b/other_languages/cpp/LinkedList/getNthNodeFromEnd.cpp similarity index 100% rename from LinkedList/getNthNodeFromEnd.cpp rename to other_languages/cpp/LinkedList/getNthNodeFromEnd.cpp diff --git a/LinkedList/lengthOfLoop.cpp b/other_languages/cpp/LinkedList/lengthOfLoop.cpp similarity index 100% rename from LinkedList/lengthOfLoop.cpp rename to other_languages/cpp/LinkedList/lengthOfLoop.cpp diff --git a/Queue/Queue/Makefile b/other_languages/cpp/Queue/Queue/Makefile similarity index 100% rename from Queue/Queue/Makefile rename to other_languages/cpp/Queue/Queue/Makefile diff --git a/Queue/Queue/Queue.hpp b/other_languages/cpp/Queue/Queue/Queue.hpp similarity index 100% rename from Queue/Queue/Queue.hpp rename to other_languages/cpp/Queue/Queue/Queue.hpp diff --git a/Queue/Queue/test_Queue.cpp b/other_languages/cpp/Queue/Queue/test_Queue.cpp similarity index 100% rename from Queue/Queue/test_Queue.cpp rename to other_languages/cpp/Queue/Queue/test_Queue.cpp diff --git a/Queue/ReverseQueue.cpp b/other_languages/cpp/Queue/ReverseQueue.cpp similarity index 100% rename from Queue/ReverseQueue.cpp rename to other_languages/cpp/Queue/ReverseQueue.cpp diff --git a/Queue/SortQueueWithoutExtraSpace.cpp b/other_languages/cpp/Queue/SortQueueWithoutExtraSpace.cpp similarity index 100% rename from Queue/SortQueueWithoutExtraSpace.cpp rename to other_languages/cpp/Queue/SortQueueWithoutExtraSpace.cpp diff --git a/RedBlackTree/Makefile b/other_languages/cpp/RedBlackTree/Makefile similarity index 100% rename from RedBlackTree/Makefile rename to other_languages/cpp/RedBlackTree/Makefile diff --git a/RedBlackTree/RedBlackTree.cpp b/other_languages/cpp/RedBlackTree/RedBlackTree.cpp similarity index 100% rename from RedBlackTree/RedBlackTree.cpp rename to other_languages/cpp/RedBlackTree/RedBlackTree.cpp diff --git a/RedBlackTree/RedBlackTree.hpp b/other_languages/cpp/RedBlackTree/RedBlackTree.hpp similarity index 100% rename from RedBlackTree/RedBlackTree.hpp rename to other_languages/cpp/RedBlackTree/RedBlackTree.hpp diff --git a/RedBlackTree/find.cpp b/other_languages/cpp/RedBlackTree/find.cpp similarity index 100% rename from RedBlackTree/find.cpp rename to other_languages/cpp/RedBlackTree/find.cpp diff --git a/RedBlackTree/insert.cpp b/other_languages/cpp/RedBlackTree/insert.cpp similarity index 100% rename from RedBlackTree/insert.cpp rename to other_languages/cpp/RedBlackTree/insert.cpp diff --git a/RedBlackTree/test_RedBlackTree.cpp b/other_languages/cpp/RedBlackTree/test_RedBlackTree.cpp similarity index 100% rename from RedBlackTree/test_RedBlackTree.cpp rename to other_languages/cpp/RedBlackTree/test_RedBlackTree.cpp diff --git a/RedBlackTree/utils.cpp b/other_languages/cpp/RedBlackTree/utils.cpp similarity index 100% rename from RedBlackTree/utils.cpp rename to other_languages/cpp/RedBlackTree/utils.cpp diff --git a/Search/BinarySearch.h b/other_languages/cpp/Search/BinarySearch.h similarity index 100% rename from Search/BinarySearch.h rename to other_languages/cpp/Search/BinarySearch.h diff --git a/Search/Makefile b/other_languages/cpp/Search/Makefile similarity index 100% rename from Search/Makefile rename to other_languages/cpp/Search/Makefile diff --git a/Search/test_BinarySearch.cpp b/other_languages/cpp/Search/test_BinarySearch.cpp similarity index 100% rename from Search/test_BinarySearch.cpp rename to other_languages/cpp/Search/test_BinarySearch.cpp diff --git a/Shuffle/Shuffle.cpp b/other_languages/cpp/Shuffle/Shuffle.cpp similarity index 100% rename from Shuffle/Shuffle.cpp rename to other_languages/cpp/Shuffle/Shuffle.cpp diff --git a/Sort/BubbleSort.cpp b/other_languages/cpp/Sort/BubbleSort.cpp similarity index 100% rename from Sort/BubbleSort.cpp rename to other_languages/cpp/Sort/BubbleSort.cpp diff --git a/Sort/CountingSort.cpp b/other_languages/cpp/Sort/CountingSort.cpp similarity index 100% rename from Sort/CountingSort.cpp rename to other_languages/cpp/Sort/CountingSort.cpp diff --git a/Sort/GnomeSort.cpp b/other_languages/cpp/Sort/GnomeSort.cpp similarity index 100% rename from Sort/GnomeSort.cpp rename to other_languages/cpp/Sort/GnomeSort.cpp diff --git a/Sort/HeapSort.cpp b/other_languages/cpp/Sort/HeapSort.cpp similarity index 100% rename from Sort/HeapSort.cpp rename to other_languages/cpp/Sort/HeapSort.cpp diff --git a/Sort/InsertionSort.cpp b/other_languages/cpp/Sort/InsertionSort.cpp similarity index 100% rename from Sort/InsertionSort.cpp rename to other_languages/cpp/Sort/InsertionSort.cpp diff --git a/Sort/MergeBottomUp.cpp b/other_languages/cpp/Sort/MergeBottomUp.cpp similarity index 100% rename from Sort/MergeBottomUp.cpp rename to other_languages/cpp/Sort/MergeBottomUp.cpp diff --git a/Sort/MergeOptimizeSort.cpp b/other_languages/cpp/Sort/MergeOptimizeSort.cpp similarity index 100% rename from Sort/MergeOptimizeSort.cpp rename to other_languages/cpp/Sort/MergeOptimizeSort.cpp diff --git a/Sort/MergeSort.cpp b/other_languages/cpp/Sort/MergeSort.cpp similarity index 100% rename from Sort/MergeSort.cpp rename to other_languages/cpp/Sort/MergeSort.cpp diff --git a/Sort/OddEvenSort.cpp b/other_languages/cpp/Sort/OddEvenSort.cpp similarity index 100% rename from Sort/OddEvenSort.cpp rename to other_languages/cpp/Sort/OddEvenSort.cpp diff --git a/Sort/Quick3WaySort.cpp b/other_languages/cpp/Sort/Quick3WaySort.cpp similarity index 100% rename from Sort/Quick3WaySort.cpp rename to other_languages/cpp/Sort/Quick3WaySort.cpp diff --git a/Sort/QuickOptimizeSort.cpp b/other_languages/cpp/Sort/QuickOptimizeSort.cpp similarity index 100% rename from Sort/QuickOptimizeSort.cpp rename to other_languages/cpp/Sort/QuickOptimizeSort.cpp diff --git a/Sort/QuickSelect.cpp b/other_languages/cpp/Sort/QuickSelect.cpp similarity index 100% rename from Sort/QuickSelect.cpp rename to other_languages/cpp/Sort/QuickSelect.cpp diff --git a/Sort/QuickSort.cpp b/other_languages/cpp/Sort/QuickSort.cpp similarity index 100% rename from Sort/QuickSort.cpp rename to other_languages/cpp/Sort/QuickSort.cpp diff --git a/Sort/SelectionSort.cpp b/other_languages/cpp/Sort/SelectionSort.cpp similarity index 100% rename from Sort/SelectionSort.cpp rename to other_languages/cpp/Sort/SelectionSort.cpp diff --git a/Sort/ShellSort.cpp b/other_languages/cpp/Sort/ShellSort.cpp similarity index 100% rename from Sort/ShellSort.cpp rename to other_languages/cpp/Sort/ShellSort.cpp diff --git a/Stack/Stack/Makefile b/other_languages/cpp/Stack/Stack/Makefile similarity index 100% rename from Stack/Stack/Makefile rename to other_languages/cpp/Stack/Stack/Makefile diff --git a/Stack/Stack/Stack.hpp b/other_languages/cpp/Stack/Stack/Stack.hpp similarity index 100% rename from Stack/Stack/Stack.hpp rename to other_languages/cpp/Stack/Stack/Stack.hpp diff --git a/Stack/Stack/test_Stack.cpp b/other_languages/cpp/Stack/Stack/test_Stack.cpp similarity index 100% rename from Stack/Stack/test_Stack.cpp rename to other_languages/cpp/Stack/Stack/test_Stack.cpp diff --git a/Stack/balancedParanthesis.cpp b/other_languages/cpp/Stack/balancedParanthesis.cpp similarity index 100% rename from Stack/balancedParanthesis.cpp rename to other_languages/cpp/Stack/balancedParanthesis.cpp diff --git a/Stack/bracketReversals.cpp b/other_languages/cpp/Stack/bracketReversals.cpp similarity index 100% rename from Stack/bracketReversals.cpp rename to other_languages/cpp/Stack/bracketReversals.cpp diff --git a/Stack/deleteMiddleElement.cpp b/other_languages/cpp/Stack/deleteMiddleElement.cpp similarity index 100% rename from Stack/deleteMiddleElement.cpp rename to other_languages/cpp/Stack/deleteMiddleElement.cpp diff --git a/Stack/infixToPostfix.cpp b/other_languages/cpp/Stack/infixToPostfix.cpp similarity index 100% rename from Stack/infixToPostfix.cpp rename to other_languages/cpp/Stack/infixToPostfix.cpp diff --git a/Stack/trackingCurrentMax.cpp b/other_languages/cpp/Stack/trackingCurrentMax.cpp similarity index 100% rename from Stack/trackingCurrentMax.cpp rename to other_languages/cpp/Stack/trackingCurrentMax.cpp diff --git a/Go/README.md b/other_languages/go/README.md similarity index 100% rename from Go/README.md rename to other_languages/go/README.md diff --git a/Go/bst/bst.go b/other_languages/go/bst/bst.go similarity index 100% rename from Go/bst/bst.go rename to other_languages/go/bst/bst.go diff --git a/Go/bst/bst_test.go b/other_languages/go/bst/bst_test.go similarity index 100% rename from Go/bst/bst_test.go rename to other_languages/go/bst/bst_test.go diff --git a/Go/bst/checkbst.go b/other_languages/go/bst/checkbst.go similarity index 100% rename from Go/bst/checkbst.go rename to other_languages/go/bst/checkbst.go diff --git a/Go/bst/delete.go b/other_languages/go/bst/delete.go similarity index 100% rename from Go/bst/delete.go rename to other_languages/go/bst/delete.go diff --git a/Go/bst/find.go b/other_languages/go/bst/find.go similarity index 100% rename from Go/bst/find.go rename to other_languages/go/bst/find.go diff --git a/Go/bst/height.go b/other_languages/go/bst/height.go similarity index 100% rename from Go/bst/height.go rename to other_languages/go/bst/height.go diff --git a/Go/bst/insert.go b/other_languages/go/bst/insert.go similarity index 100% rename from Go/bst/insert.go rename to other_languages/go/bst/insert.go diff --git a/Go/bst/traversal.go b/other_languages/go/bst/traversal.go similarity index 100% rename from Go/bst/traversal.go rename to other_languages/go/bst/traversal.go diff --git a/Go/doublylinkedlist/doublylinkedlist.go b/other_languages/go/doublylinkedlist/doublylinkedlist.go similarity index 100% rename from Go/doublylinkedlist/doublylinkedlist.go rename to other_languages/go/doublylinkedlist/doublylinkedlist.go diff --git a/Go/doublylinkedlist/doublylinkedlist_test.go b/other_languages/go/doublylinkedlist/doublylinkedlist_test.go similarity index 100% rename from Go/doublylinkedlist/doublylinkedlist_test.go rename to other_languages/go/doublylinkedlist/doublylinkedlist_test.go diff --git a/Go/hashtable/hashtable.go b/other_languages/go/hashtable/hashtable.go similarity index 100% rename from Go/hashtable/hashtable.go rename to other_languages/go/hashtable/hashtable.go diff --git a/Go/hashtable/hashtable_test.go b/other_languages/go/hashtable/hashtable_test.go similarity index 100% rename from Go/hashtable/hashtable_test.go rename to other_languages/go/hashtable/hashtable_test.go diff --git a/Go/heap/doc.go b/other_languages/go/heap/doc.go similarity index 100% rename from Go/heap/doc.go rename to other_languages/go/heap/doc.go diff --git a/Go/heap/maxheap/maxheap.go b/other_languages/go/heap/maxheap/maxheap.go similarity index 100% rename from Go/heap/maxheap/maxheap.go rename to other_languages/go/heap/maxheap/maxheap.go diff --git a/Go/heap/maxheap/maxheap_test.go b/other_languages/go/heap/maxheap/maxheap_test.go similarity index 100% rename from Go/heap/maxheap/maxheap_test.go rename to other_languages/go/heap/maxheap/maxheap_test.go diff --git a/Go/heap/minheap/minheap.go b/other_languages/go/heap/minheap/minheap.go similarity index 100% rename from Go/heap/minheap/minheap.go rename to other_languages/go/heap/minheap/minheap.go diff --git a/Go/heap/minheap/minheap_test.go b/other_languages/go/heap/minheap/minheap_test.go similarity index 100% rename from Go/heap/minheap/minheap_test.go rename to other_languages/go/heap/minheap/minheap_test.go diff --git a/Go/linkedlist/linkedlist.go b/other_languages/go/linkedlist/linkedlist.go similarity index 100% rename from Go/linkedlist/linkedlist.go rename to other_languages/go/linkedlist/linkedlist.go diff --git a/Go/linkedlist/linkedlist_test.go b/other_languages/go/linkedlist/linkedlist_test.go similarity index 100% rename from Go/linkedlist/linkedlist_test.go rename to other_languages/go/linkedlist/linkedlist_test.go diff --git a/Go/queue/queue.go b/other_languages/go/queue/queue.go similarity index 100% rename from Go/queue/queue.go rename to other_languages/go/queue/queue.go diff --git a/Go/queue/queue_test.go b/other_languages/go/queue/queue_test.go similarity index 100% rename from Go/queue/queue_test.go rename to other_languages/go/queue/queue_test.go diff --git a/Go/redblacktree/doc.go b/other_languages/go/redblacktree/doc.go similarity index 100% rename from Go/redblacktree/doc.go rename to other_languages/go/redblacktree/doc.go diff --git a/Go/redblacktree/find.go b/other_languages/go/redblacktree/find.go similarity index 100% rename from Go/redblacktree/find.go rename to other_languages/go/redblacktree/find.go diff --git a/Go/redblacktree/insert.go b/other_languages/go/redblacktree/insert.go similarity index 100% rename from Go/redblacktree/insert.go rename to other_languages/go/redblacktree/insert.go diff --git a/Go/redblacktree/redblacktree.go b/other_languages/go/redblacktree/redblacktree.go similarity index 100% rename from Go/redblacktree/redblacktree.go rename to other_languages/go/redblacktree/redblacktree.go diff --git a/Go/redblacktree/redblacktree_test.go b/other_languages/go/redblacktree/redblacktree_test.go similarity index 100% rename from Go/redblacktree/redblacktree_test.go rename to other_languages/go/redblacktree/redblacktree_test.go diff --git a/Go/redblacktree/utils.go b/other_languages/go/redblacktree/utils.go similarity index 100% rename from Go/redblacktree/utils.go rename to other_languages/go/redblacktree/utils.go diff --git a/Go/search/binarysearch.go b/other_languages/go/search/binarysearch.go similarity index 100% rename from Go/search/binarysearch.go rename to other_languages/go/search/binarysearch.go diff --git a/Go/search/binarysearch_test.go b/other_languages/go/search/binarysearch_test.go similarity index 100% rename from Go/search/binarysearch_test.go rename to other_languages/go/search/binarysearch_test.go diff --git a/Go/set/set.go b/other_languages/go/set/set.go similarity index 100% rename from Go/set/set.go rename to other_languages/go/set/set.go diff --git a/Go/set/set_test.go b/other_languages/go/set/set_test.go similarity index 100% rename from Go/set/set_test.go rename to other_languages/go/set/set_test.go diff --git a/Go/shuffle/shuffle.go b/other_languages/go/shuffle/shuffle.go similarity index 100% rename from Go/shuffle/shuffle.go rename to other_languages/go/shuffle/shuffle.go diff --git a/Go/sort/bubble.go b/other_languages/go/sort/bubble.go similarity index 100% rename from Go/sort/bubble.go rename to other_languages/go/sort/bubble.go diff --git a/Go/sort/countingSort.go b/other_languages/go/sort/countingSort.go similarity index 100% rename from Go/sort/countingSort.go rename to other_languages/go/sort/countingSort.go diff --git a/Go/sort/gnome.go b/other_languages/go/sort/gnome.go similarity index 100% rename from Go/sort/gnome.go rename to other_languages/go/sort/gnome.go diff --git a/Go/sort/heap.go b/other_languages/go/sort/heap.go similarity index 100% rename from Go/sort/heap.go rename to other_languages/go/sort/heap.go diff --git a/Go/sort/insertion.go b/other_languages/go/sort/insertion.go similarity index 100% rename from Go/sort/insertion.go rename to other_languages/go/sort/insertion.go diff --git a/Go/sort/merge.go b/other_languages/go/sort/merge.go similarity index 100% rename from Go/sort/merge.go rename to other_languages/go/sort/merge.go diff --git a/Go/sort/oddeven.go b/other_languages/go/sort/oddeven.go similarity index 100% rename from Go/sort/oddeven.go rename to other_languages/go/sort/oddeven.go diff --git a/Go/sort/quick.go b/other_languages/go/sort/quick.go similarity index 100% rename from Go/sort/quick.go rename to other_languages/go/sort/quick.go diff --git a/Go/sort/quickselect.go b/other_languages/go/sort/quickselect.go similarity index 100% rename from Go/sort/quickselect.go rename to other_languages/go/sort/quickselect.go diff --git a/Go/sort/selection.go b/other_languages/go/sort/selection.go similarity index 100% rename from Go/sort/selection.go rename to other_languages/go/sort/selection.go diff --git a/Go/sort/shell.go b/other_languages/go/sort/shell.go similarity index 100% rename from Go/sort/shell.go rename to other_languages/go/sort/shell.go diff --git a/Go/sort/sort.go b/other_languages/go/sort/sort.go similarity index 100% rename from Go/sort/sort.go rename to other_languages/go/sort/sort.go diff --git a/Go/sort/sort_test.go b/other_languages/go/sort/sort_test.go similarity index 100% rename from Go/sort/sort_test.go rename to other_languages/go/sort/sort_test.go diff --git a/Go/stack/applications/applications.go b/other_languages/go/stack/applications/applications.go similarity index 100% rename from Go/stack/applications/applications.go rename to other_languages/go/stack/applications/applications.go diff --git a/Go/stack/applications/applications_test.go b/other_languages/go/stack/applications/applications_test.go similarity index 100% rename from Go/stack/applications/applications_test.go rename to other_languages/go/stack/applications/applications_test.go diff --git a/Go/stack/applications/infixevaluation.go b/other_languages/go/stack/applications/infixevaluation.go similarity index 100% rename from Go/stack/applications/infixevaluation.go rename to other_languages/go/stack/applications/infixevaluation.go diff --git a/Go/stack/applications/infixtopostfix.go b/other_languages/go/stack/applications/infixtopostfix.go similarity index 100% rename from Go/stack/applications/infixtopostfix.go rename to other_languages/go/stack/applications/infixtopostfix.go diff --git a/Go/stack/applications/infixtoprefix.go b/other_languages/go/stack/applications/infixtoprefix.go similarity index 100% rename from Go/stack/applications/infixtoprefix.go rename to other_languages/go/stack/applications/infixtoprefix.go diff --git a/Go/stack/applications/utils.go b/other_languages/go/stack/applications/utils.go similarity index 100% rename from Go/stack/applications/utils.go rename to other_languages/go/stack/applications/utils.go diff --git a/Go/stack/stack.go b/other_languages/go/stack/stack.go similarity index 100% rename from Go/stack/stack.go rename to other_languages/go/stack/stack.go diff --git a/Go/stack/stack_test.go b/other_languages/go/stack/stack_test.go similarity index 100% rename from Go/stack/stack_test.go rename to other_languages/go/stack/stack_test.go diff --git a/Go/trie/trie.go b/other_languages/go/trie/trie.go similarity index 100% rename from Go/trie/trie.go rename to other_languages/go/trie/trie.go diff --git a/Go/trie/trie_test.go b/other_languages/go/trie/trie_test.go similarity index 100% rename from Go/trie/trie_test.go rename to other_languages/go/trie/trie_test.go From 273de24715a404898df2eebdf966d1cf8d4c7903 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sun, 8 Nov 2020 11:04:33 +0530 Subject: [PATCH 104/209] add stack python code --- other_languages/cpp/.DS_Store | Bin 6148 -> 0 bytes other_languages/cpp/Heap/.DS_Store | Bin 6148 -> 0 bytes other_languages/cpp/LinkedList/.DS_Store | Bin 6148 -> 0 bytes stack/library/stack.py | 75 +++++++++++++++++++++++ 4 files changed, 75 insertions(+) delete mode 100644 other_languages/cpp/.DS_Store delete mode 100644 other_languages/cpp/Heap/.DS_Store delete mode 100644 other_languages/cpp/LinkedList/.DS_Store create mode 100644 stack/library/stack.py diff --git a/other_languages/cpp/.DS_Store b/other_languages/cpp/.DS_Store deleted file mode 100644 index 0912e1c1f34344e49496c0161c05e5aa797001fa..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHK%TB{U44f?iO5sq63&;Ede-MQrao_^w1Aw%ssG&h^iqu;^ow0Wn5>g~is6uw- zosHMt$7~eW09?A6UIJqPL#p85gv}0-anYU(f@MT>I>!oIOfbU}Ry}Vs>>~qmcVnb@ z#ZqtW>;7`g@xXhWVK!ao#dBE}a)5JWykv2HV^EGOlzdv!Ek{Mm2erbs9TMS2---9O zafDl4bitvi_SdM|4u`nIhJ)0$`3(0Ok)q%pax8Xj@~C+Wd5U)QF$d$IoY$D6c083V?EG4Oi^n6pKOryi{}28;n?pkYA14>46R30Qm7PX`+< z0f-UJD(p)wAu(~lBw+24BNXRDi9XbY62tj$+T-At1gt&!aJW!>xUjMd6^hfd!&V8e*}~UYm9+EW#AJUS5Y?r diff --git a/other_languages/cpp/Heap/.DS_Store b/other_languages/cpp/Heap/.DS_Store deleted file mode 100644 index 8223fe7b8152c985ed49f79ee22cf003c76a5a85..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeH~y{ZC1426^H7Q$_|w4BBV@C^o0u=fT0Sv$cC7yEg1Pks#z{%MPv#$%G|=p6nQ5bImurBhX3RFaJiiG%umwJz25KWbr01*pK6 zDWKhIyISI<@@{>4J*)4sYU>6E{W!wIPXH3Tif3>)>=#>rHQ9ow!1yEJGB8kqw<>T0 Da%~cU diff --git a/other_languages/cpp/LinkedList/.DS_Store b/other_languages/cpp/LinkedList/.DS_Store deleted file mode 100644 index 2c6d20864d583b6f0ee1b61ea0f05d14b7c24390..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHKyG{c^3>-s>2%3~B_ZRqsRTMfpegMIxKt!Yn^jGD(_%y~3A)-r~NHl0H*|Y2O z+-j#dp8?qFbGQQ*0OoW@96U_TpSw@&sxn5T^Bo%uc)%<6_?T3mPB`}_IPZA-%^&tJ z+vnYGdzz-K6p#W^Knh3!DR7|z-g{~D+eAevAO)nrj{^REXmrP3I3~uYgCRx$;*9Aq zu49%UHct?H;h4w_&5}w?s?~^LNoT%QT`wFHlMbul!|G(K3B}@czQ08|tS2f;0V!~- zz;$jH-v96EXXgK7l6F!+3j8YtY_@(}uXv^Et&_`nuWj@vy4QTs-M9`4L$qUJv}10( f9WSFO>zc3mycdp%L1#YbMEwl7E;1?b*9v?Cj9L{! diff --git a/stack/library/stack.py b/stack/library/stack.py new file mode 100644 index 0000000..008271b --- /dev/null +++ b/stack/library/stack.py @@ -0,0 +1,75 @@ +""" Implementation for Stack Data Structure """ + + +class Stack: + """ A stack is an abstract data type that serves as a collection of + elements with two principal operations: push() and pop(). push() adds an + element to the top of the stack, and pop() removes an element from the top + of a stack. The order in which elements come off of a stack are + Last In, First Out (LIFO). + https://en.wikipedia.org/wiki/Stack_(abstract_data_type) + """ + + def __init__(self): + """ Initializing empty stack.""" + self._items = [] + + def push(self, item): + """ Accepts an item as a parameter and appends it to the end of the + list. Returns nothing. + + The runtime for this method is o(1), or constant time, because + appending to the end of a list happens in constant time. + + :param item: item to be inserted on top of stack + """ + self._items.append(item) + + def pop(self): + """ Returns and removes the last item for the list, which is also the + top item of the stack. + + The runtime here is constant time, because all it does is index to the + last item of the list. + + :return: return top item of the stack or None, if stack is empty + """ + if not self._items: + raise IndexError('Stack is empty') + return self._items.pop() + + def peek(self): + """ This method returns the last item in the list, which is also the + item at the top of the Stack. + + This method runs in constant time because indexing into a list is done + in constant time. + + :return: returns top of the stack or None, if stack is empty + """ + if not self._items: + raise IndexError('Stack is empty') + return self._items[-1] + + def size(self): + """ This method returns the length of the list that is representing + the stack. + + This method runs in constant time because finding the length of a list + also in constant time. + + :return: length of list + :rtype: int + """ + return len(self._items) + + def is_empty(self): + """ This method returns a boolean value describing whether or not the + stack is empty. + + Runs in constant time, because testing for equality happens in + constant time. + + :return: returns true if stack is empty, else false + """ + return self._items == [] From ac6b7ba11f642ce066e79bbc4a97f1e2c2b33719 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sun, 8 Nov 2020 11:05:09 +0530 Subject: [PATCH 105/209] add queue python code --- queue/library/queue.py | 74 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 queue/library/queue.py diff --git a/queue/library/queue.py b/queue/library/queue.py new file mode 100644 index 0000000..61cb025 --- /dev/null +++ b/queue/library/queue.py @@ -0,0 +1,74 @@ +""" Implementation for Queue Data Structure """ + + +class Queue: + """ Queue is a collection of entities that are maintained in a sequence + and can be modified by the addition of entities at one end of the + sequence and removal from the other end of the sequence. + The order in which elements come off of a queue are + First In, First Out (FIFO). + https://en.wikipedia.org/wiki/Queue_(abstract_data_type) + """ + + def __init__(self): + """ Initializing empty queue.""" + self.items = [] + + def enqueue(self, item): + """ Takes in an item and inserts that item into the 0th index of the + list that is representing the Queue. + + The runtime is O(n), or linear time, because inserting into the 0th + index of a list forces all the other items in the list to move one + index to the right. + + :param item: item to be inserted in queue + """ + self.items.insert(0, item) + + def dequeue(self): + """ Returns and removes the front-most item of the Queue, which is + represented by the last items in the list. + + The runtime is O(1), or constant time, because indexing to the end of + a list happens in constant time. + + :return: front-most item of the queue or None, if the queue is empty + """ + if not self.items: + raise IndexError('queue is empty') + return self.items.pop() + + def peek(self): + """ Returns the last item in the list, which represents the front-most + item in the Queue. + + The runtime is O(1), or constant time, because we are just indexing to + the last item of the list and returning the value found there. + + :return: front-most item of the queue or None, if the queue is empty + """ + if not self.items: + raise IndexError('queue is empty') + return self.items[-1] + + def size(self): + """ Returns the size of the Queue, which is represent bu the length + of the list + + The runtime is O(1), or constant time, because we're only returning + the length. + + :return: length of list + :rtype: int """ + return len(self.items) + + def is_empty(self): + """ Returns a boolean value expressing whether or not the list + representing the Queue is empty. + + Runs in constant time, because it's only checking for equality. + + :return: returns true if stack is empty, else false + """ + return self.items == [] From ac7bff59bc178ed9cac6fd3c6dd74e96fc66dffe Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Mon, 9 Nov 2020 20:27:13 +0530 Subject: [PATCH 106/209] add singly linked list along with test cases --- linked_list/library/linked_list.py | 171 ++++++++++++++++++++++++ linked_list/library/test_linked_list.py | 102 ++++++++++++++ 2 files changed, 273 insertions(+) create mode 100644 linked_list/library/linked_list.py create mode 100644 linked_list/library/test_linked_list.py diff --git a/linked_list/library/linked_list.py b/linked_list/library/linked_list.py new file mode 100644 index 0000000..9f0160a --- /dev/null +++ b/linked_list/library/linked_list.py @@ -0,0 +1,171 @@ +""" Implementation of Singly Linked List Data Structure """ + + +class Node: + """ Node class contains everything related to Linked List node """ + + def __init__(self, data): + """ initializing single node with data """ + self.data = data + self.next = None + + def __repr__(self): + return f"Node: data={self.data}" + + def get_data(self): + """ Return the self.data attribute. """ + return self.data + + def set_data(self, new_data): + """ replace the existing value of the self.data attribute with + new_data parameter + """ + self.data = new_data + + def get_next(self): + """ return the self.next attribute. """ + return self.next + + def set_next(self, new_next): + """ replace the existing value of the self.next attribute with + new_next parameter + """ + self.next = new_next + + +class LinkedList: + """ Singly Linked List is a linear data structure. + Unlike arrays, linked list elements are not stored at a contiguous + location; the elements are linked using pointers. + """ + + def __init__(self): + """ initializing singly linked list with zero node """ + self.head = None + + def __len__(self): + """ returns the number of nodes currently present in linked list """ + current = self.head + count = 0 + while current is not None: + count = count + 1 + current = current.get_next() + return count + + def __repr__(self): + return f"LinkedList: head={self.head}" + + def get_head(self): + """ returns the first linked list node """ + return self.head + + def is_empty(self): + """ returns true if the Linked List is empty. Otherwise, return false + """ + return self.__len__() == 0 + + def insert_head(self, data): + """ inserts node at the start of linked list """ + node = Node(data) + node.set_next(self.head) + self.head = node + + def insert_tail(self, data): + """ inserts node at the end of linked list """ + node = Node(data) + if self.head is None: + self.head = node + else: + current = self.head + while current.get_next() is not None: + current = current.get_next() + current.set_next(node) + + def insert_at(self, data, position): + """ inserts node at specified position in linked list """ + length = self.__len__() + if position <= 1: + self.insert_head(data) + elif position >= length: + self.insert_tail(data) + else: + node = Node(data) + previous = self.head + current = self.head + for _ in range(1, position): + previous = current + current = current.get_next() + previous.set_next(node) + node.set_next(current) + + def delete_head(self): + """ removes first linked list node and returns data. Raise exception, + if linkedlist is empty + """ + if self.head is None: + raise IndexError("linkedlist is empty") + node = self.head + data = node.get_data() + self.head = self.head.get_next() + return data + + def delete_tail(self): + """ removes last linked list node and returns data. raise exception, + if linkedlist is empty + """ + if self.head is None: + raise IndexError("linkedlist is empty") + current = self.head + if current.get_next() is None: + self.head = None + else: + previous = self.head + while current.get_next() is not None: + previous = current + current = current.get_next() + previous.set_next(None) + return current.get_data() + + def delete_at(self, position): + """ removes specified node from linked list and returns data. + raise exception, if position is invalid. + """ + length = self.__len__() + if position < 1 or position > length: + raise ValueError("invalid position") + + if position == 1: + return self.delete_head() + elif position == length: + return self.delete_tail() + else: + previous = self.head + current = self.head + for _ in range(1, position): + previous = current + current = current.get_next() + removed_data = current.get_data() + previous.set_next(current.get_next()) + current.set_next(None) + return removed_data + + def data_at(self, position): + """ returns node data without removing it. + raise exception, if position is invalid. + """ + length = self.__len__() + if position < 1 or position > length: + raise ValueError("invalid position") + + current = self.head() + for _ in range(1, position): + current = current.get_next() + return current.get_data() + + def print(self): + """ prints entire linked list without changing underlying data """ + current = self.head + while current is not None: + print(" -> ", current.get_data()) + current = current.get_next() + print() diff --git a/linked_list/library/test_linked_list.py b/linked_list/library/test_linked_list.py new file mode 100644 index 0000000..5f5f799 --- /dev/null +++ b/linked_list/library/test_linked_list.py @@ -0,0 +1,102 @@ +""" unittest for linked list operations """ + +import unittest +from linked_list import LinkedList + +def linkedlist_to_array(linkedlist): + """ converting linkedlist data to list """ + result = [] + current = linkedlist.get_head() + while current: + result.append(current.get_data()) + current = current.get_next() + return result + + +class TestLinkedListEmpty(unittest.TestCase): + """ tests on empty linked list """ + def setUp(self): + """ setup empty linked list """ + self.linkedlist = LinkedList() + + def test_lenght(self): + """ test for linked list lenght operation """ + self.assertEqual(len(self.linkedlist), 0) + + def test_get_head(self): + """ test for linked list get_head operation """ + self.assertIsNone(self.linkedlist.head) + + def test_is_empty(self): + """ test for linked list is_empty operation """ + self.assertTrue(self.linkedlist.is_empty()) + + def test_insert_head(self): + """ test for linked list insert_head operation """ + self.linkedlist.insert_head(45) + self.linkedlist.insert_head(34) + self.assertListEqual(linkedlist_to_array(self.linkedlist), [34, 45]) + + def test_insert_tail(self): + """ test for linked list insert_tail operation """ + self.linkedlist.insert_tail(45) + self.linkedlist.insert_tail(34) + self.linkedlist.insert_tail(56) + self.assertListEqual(linkedlist_to_array(self.linkedlist), [45, 34, 56]) + + +class TestLinkedList(unittest.TestCase): + """ tests on filled linked list """ + def setUp(self): + """ setup empty linked list """ + self.linkedlist = LinkedList() + self.linkedlist.insert_tail(1) + self.linkedlist.insert_tail(2) + self.linkedlist.insert_tail(3) + self.linkedlist.insert_tail(4) + self.linkedlist.insert_tail(5) + + def test_lenght(self): + """ test for linked list lenght operation """ + self.assertEqual(len(self.linkedlist), 5) + + def test_get_head(self): + """ test for linked list get_head operation """ + self.assertIsNotNone(self.linkedlist.head) + + def test_is_empty(self): + """ test for linked list is_empty operation """ + self.assertFalse(self.linkedlist.is_empty()) + + def test_insert_head(self): + """ test for linked list insert_head operation """ + self.linkedlist.insert_head(45) + self.assertListEqual(linkedlist_to_array(self.linkedlist), [45, 1, 2, 3, 4, 5]) + self.linkedlist.insert_head(34) + self.assertListEqual(linkedlist_to_array(self.linkedlist), [34, 45, 1, 2, 3, 4, 5]) + + def test_insert_tail(self): + """ test for linked list insert_tail operation """ + self.linkedlist.insert_tail(45) + self.assertListEqual(linkedlist_to_array(self.linkedlist), [1, 2, 3, 4, 5, 45]) + self.linkedlist.insert_tail(34) + self.assertListEqual(linkedlist_to_array(self.linkedlist), [1, 2, 3, 4, 5, 45, 34]) + self.linkedlist.insert_tail(56) + self.assertListEqual(linkedlist_to_array(self.linkedlist), [1, 2, 3, 4, 5, 45, 34, 56]) + + def test_insert_at(self): + """ test for linked list insert_at operation """ + self.linkedlist.insert_at(45, 2) + self.assertListEqual(linkedlist_to_array(self.linkedlist), [1, 45, 2, 3, 4, 5]) + self.linkedlist.insert_at(34, 4) + self.assertListEqual(linkedlist_to_array(self.linkedlist), [1, 45, 2, 34, 3, 4, 5]) + self.linkedlist.insert_at(44, 10) + self.assertListEqual(linkedlist_to_array(self.linkedlist), [1, 45, 2, 34, 3, 4, 5, 44]) + self.linkedlist.insert_at(23, 0) + self.assertListEqual(linkedlist_to_array(self.linkedlist), [23, 1, 45, 2, 34, 3, 4, 5, 44]) + self.linkedlist.insert_at(22, -2) + self.assertListEqual(linkedlist_to_array(self.linkedlist), [22, 23, 1, 45, 2, 34, 3, 4, 5, 44]) + + +if __name__ == '__main__': + unittest.main() From 7cf9dd7544b39568f8961508f7d137f507521f5d Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Mon, 9 Nov 2020 20:28:25 +0530 Subject: [PATCH 107/209] add deque data structure --- deque/deque.py | 116 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 deque/deque.py diff --git a/deque/deque.py b/deque/deque.py new file mode 100644 index 0000000..2677949 --- /dev/null +++ b/deque/deque.py @@ -0,0 +1,116 @@ +""" Implementation for Deque Data Structure """ + + +class Deque: + """ Deque (double-ended queue) is an abstract data type that generalizes + a queue, for which elements can be added to or removed from either the + front (head) or back (tail). + """ + + def __init__(self): + """ Initializing empty deque """ + self.items = [] + + def add_front(self, item): + """ Takes an item as a parameter and inserts it into the 0th index of + the list that is representing the Deque. + + The runtime is linear, or O(n), because every time you insert into + the front of a list, all the other items in the list need to shift + one position to the right. + """ + self.items.insert(0, item) + + def add_rear(self, item): + """Takes in a item as a parameter and appends the item to the end of + the list that is representing the deque. + + The runtime is constant because appending to the end of a list happens + in constant time. + """ + self.items.append(item) + + def remove_front(self): + """ Removes and returns the item in the 0th index of the list, which + represents the font of the Deque. + + The runtime is linear, or O(n), because when we remove an item from + the 0th index, all the other items have to shift one index to the left. + """ + if self.items: + return self.items.pop(0) + return None + + def remove_rear(self): + """ Removes and returns the last item of the list, which represents + the rear of the Deque. + + The runtime is constant because all we're doing is indexing to the + end of a list. + """ + if self.items: + return self.items.pop() + return None + + def peek_front(self): + """ Returns the value found at the 0th index of the list, which + represents the front of the Deque. + + The runtime is constant because all we're doing is indexing into + a list. + """ + if self.items: + return self.items[0] + return None + + def peek_rear(self): + """ Returns the value found at the -1st, or last, index. + + The runtime is constant because all we're doing is indexing into a + list. + """ + if self.items: + return self.items[-1] + return None + + def size(self): + """ Returns the length of the list, which is representing the deque. + + The runtime will be constant because all we're doing is finding the + length of a list and returning that value. + """ + return len(self.items) + + def is_empty(self): + """ Checks to see if the list representing our Deque is empty. Returns + True if it is, false if it isn't. + + The runtime is constant because all we're doing is comparing two + values. + """ + return self.items == [] + + +def main(): + """ operational function """ + deque = Deque() + print("deque is empty: ", deque.is_empty()) + print("deque size: ", deque.size()) + for i in range(5): + deque.add_front(i) + + print("after inserting 5 elements") + print("deque is empty: ", deque.is_empty()) + print("deque size: ", deque.size()) + + print("top element on deque: ", deque.peek_front()) + print("back element on deque: ", deque.peek_rear()) + print("popped element from deque: ", deque.remove_front()) + print() + print("after popping one elements") + print("deque size: ", deque.size()) + print("top element on deque: ", deque.peek_front()) + + +if __name__ == "__main__": + main() From b23009a5c6c30f0da01e377ac7fe4f5f2c5ce299 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Wed, 11 Nov 2020 13:06:00 +0530 Subject: [PATCH 108/209] add trie data structure --- trie/trie.py | 88 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 trie/trie.py diff --git a/trie/trie.py b/trie/trie.py new file mode 100644 index 0000000..ca7ecbc --- /dev/null +++ b/trie/trie.py @@ -0,0 +1,88 @@ +""" Trie is an efficient information reTrieval data structure. Using Trie, + search complexities can be brought to optimal limit (key length). If we + store keys in binary search tree, a well balanced BST will need time + proportional to M * log N, where M is maximum string length and N is + number of keys in tree. Using Trie, we can search the key in O(M) time. + However the penalty is on Trie storage requirements +""" + +class Node: + """ Node contains character and it's children trie node """ + def __init__(self, character): + self.character = character + self.children = {} + self.word_finished = False + + +class Trie: + """ Trie Data Structure implementation """ + def __init__(self): + self.root = Node(None) + + def insert(self, word): + """ inserts a word in the trie data structure""" + current = self.root + for character in word: + if character in current.children: + current = current.children[character] + else: + new_node = Node(character) + current.children[character] = new_node + current = new_node + current.word_finished = True + + def search(self, word): + """ returns true if the complete word is present in trie, + else false + """ + current = self.root + for character in word: + if character not in current.children: + return False + current = current.children[character] + return current.word_finished + + def starts_with(self, prefix): + """ returns true if any word present in the trie start with the + given prefix, else false + """ + current = self.root + for character in prefix: + if character not in current.children: + return False + current = current.children[character] + return True + + def delete(self, word): + """ deletes word by negating word_finished boolean variable """ + current = self.root + for character in word: + if character not in current.children: + raise Exception("word not present in trie") + current = current.children[character] + + if current.word_finished: + current.word_finished = False + + +def main(): + """ operational function """ + tree = Trie() + tree.insert("apple") + print("is apple present?", tree.search("apple")) # True + print("is app present?", tree.search("app")) # False + print("starts with app?", tree.starts_with("app")) # True + + print("inserting 'app' in trie") + tree.insert("app") + print("is app present?", tree.search("app")) # True + + print("removing 'app' from trie") + tree.delete("app") + print("is app present?", tree.search("app")) # False + breakpoint() + + +if __name__ == "__main__": + main() + From 1e660ab539c0441962985ed8b84772761f9db5af Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Wed, 11 Nov 2020 13:07:02 +0530 Subject: [PATCH 109/209] add bubble, insertion, selection and shell sorting algorithm --- sort/bubble.py | 35 +++++++++++++++++++++++++++++++++++ sort/insertion.py | 35 +++++++++++++++++++++++++++++++++++ sort/selection.py | 31 +++++++++++++++++++++++++++++++ sort/shell.py | 40 ++++++++++++++++++++++++++++++++++++++++ 4 files changed, 141 insertions(+) create mode 100644 sort/bubble.py create mode 100644 sort/insertion.py create mode 100644 sort/selection.py create mode 100644 sort/shell.py diff --git a/sort/bubble.py b/sort/bubble.py new file mode 100644 index 0000000..5896765 --- /dev/null +++ b/sort/bubble.py @@ -0,0 +1,35 @@ +""" Implementation of Bubble Sort algorithm +""" + + +def bubble(array): + """ Bubble sort is a simple sorting algorithm that repeatedly steps + through the list to be sorted, compares each pair of adjacent items and + swaps them if they are in the wrong order. The pass through the list is + repeated until no swaps are needed, which indicates that the list is + sorted. + + :param array: list of elements that needs to be sorted + :type array: list + """ + length = len(array) + swapped = True + + while swapped: + swapped = False + for i in range(length - 1): + if array[i] > array[i+1]: + array[i], array[i+1] = array[i+1], array[i] + swapped = True + + +def main(): + """ operational function """ + arr = [34, 56, 23, 67, 3, 68] + print(f"unsorted array: {arr}") + bubble(arr) + print(f" sorted array: {arr}") + + +if __name__ == "__main__": + main() diff --git a/sort/insertion.py b/sort/insertion.py new file mode 100644 index 0000000..59439f9 --- /dev/null +++ b/sort/insertion.py @@ -0,0 +1,35 @@ +""" Implementation of Insertion Sort algorithm +""" + + +def insertion(array): + """ Insertion sort is based on the idea that one element from the input + elements is consumed in each iteration to find its correct position + i.e, the position to which it belongs in a sorted array. + + :param array: list of elements that needs to be sorted + :type array: list + """ + length = len(array) + + for i in range(length): + index = i + value = array[i] + + while index > 0 and array[index-1] > value: + array[index] = array[index-1] + index -= 1 + + array[index] = value + + +def main(): + """ operational function """ + arr = [34, 56, 23, 67, 3, 68] + print(f"unsorted array: {arr}") + insertion(arr) + print(f" sorted array: {arr}") + + +if __name__ == "__main__": + main() diff --git a/sort/selection.py b/sort/selection.py new file mode 100644 index 0000000..6d107ff --- /dev/null +++ b/sort/selection.py @@ -0,0 +1,31 @@ +""" Implementation of Selection Sort algorithm +""" + + +def selection(array): + """ Selection sort algorithm sorts an array by repeatedly finding the + minimum element (considering ascending order) from unsorted part and + putting it at the beginning. + + :param array: list of elements that needs to be sorted + :type array: list + """ + length = len(array) + for i in range(length - 1): + min_element_index = i + for j in range(i+1, length): + if array[j] < array[min_element_index]: + min_element_index = j + array[i], array[min_element_index] = array[min_element_index], array[i] + + +def main(): + """ operational function """ + arr = [34, 56, 23, 67, 3, 68] + print(f"unsorted array: {arr}") + selection(arr) + print(f" sorted array: {arr}") + + +if __name__ == "__main__": + main() diff --git a/sort/shell.py b/sort/shell.py new file mode 100644 index 0000000..c557813 --- /dev/null +++ b/sort/shell.py @@ -0,0 +1,40 @@ +""" Implementation of Shell Sort algorithm +""" + + +def shell(array): + """ Shell sort is mainly a variation of Insertion Sort. In insertion sort, + we move elements only one position ahead. When an element has to be moved + far ahead, many movements are involved. The idea of shellSort is to allow + exchange of far items. In shellSort, we make the array h-sorted for a large + value of h. We keep reducing the value of h until it becomes 1. An array is + said to be h-sorted if all sublists of every h’th element is sorted. + + :param array: list of elements that needs to be sorted + :type array: list + """ + length = len(array) + gaps = [701, 301, 132, 57, 23, 10, 4, 1] + + for gap in gaps: + h_gap = gap + while h_gap < length: + temp = array[h_gap] + i = h_gap + while i >= gap and array[i - gap] > temp: + array[i] = array[i - gap] + i -= gap + array[i] = temp + h_gap += 1 + + +def main(): + """ operational function """ + arr = [34, 56, 23, 67, 3, 68] + print(f"unsorted array: {arr}") + shell(arr) + print(f" sorted array: {arr}") + + +if __name__ == "__main__": + main() From ac26982ede5eff8c3e54bcd313ec289d83af4ed8 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Thu, 12 Nov 2020 11:29:18 +0530 Subject: [PATCH 110/209] add binary search tree --- search/binary_search.py | 44 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 search/binary_search.py diff --git a/search/binary_search.py b/search/binary_search.py new file mode 100644 index 0000000..97edec3 --- /dev/null +++ b/search/binary_search.py @@ -0,0 +1,44 @@ +""" Implementation of Binary Search algorithm """ + + +def binary_search_iterative(array, item): + """ Iterative version of Binary search + Returns index if the item is found in the list, else returns None + """ + start = 0 + end = len(array) - 1 + + while start <= end: + median = (start + end) // 2 + if array[median] == item: + return median + if array[median] < item: + start = median + 1 + else: + end = median - 1 + return None + + +def binary_search_recursive(array, start, end, item): + """ Recursive version of binary search algorithm + Returns index if the item is found in the list, else returns None + """ + if end >= start: + median = (start + end) // 2 + if array[median] == item: + return median + if array[median] < item: + return binary_search_recursive(array, median+1, end, item) + return binary_search_recursive(array, start, median-1, item) + return None + + +def main(): + """ operational function """ + array = [34, 36, 46, 48, 67, 68, 69, 71, 73, 97] + print(binary_search_iterative(array, 34)) + print(binary_search_recursive(array, 0, len(array)-1, 97)) + + +if __name__ == "__main__": + main() From 3ea6e677a063a0a666dde19d4344d4821785970b Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Thu, 12 Nov 2020 11:29:51 +0530 Subject: [PATCH 111/209] add shuffle algorithm --- shuffle/shuffle.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 shuffle/shuffle.py diff --git a/shuffle/shuffle.py b/shuffle/shuffle.py new file mode 100644 index 0000000..3723faa --- /dev/null +++ b/shuffle/shuffle.py @@ -0,0 +1,31 @@ +""" +Shuffle randomize a given array. Here shuffle means that every permutation +of array element shoudl equally likely. +It uses Fisher-Yates (Knuth) shuffling algorithm. + +e.g. shuffle a deck of cards + +Fisher–Yates shuffle Algorithm works in O(n) time complexity. +The assumption here is, we are given a function rand() that generates +random number in O(1) time. +""" + +import random + + +def shuffle(array): + """ Fisher–Yates Shuffle Algorithm """ + for i, _ in enumerate(array): + r_int = random.randint(0, i+1) + array[i], array[r_int] = array[r_int], array[i] + + +def main(): + """ operational function """ + array = [34, 36, 46, 48, 67, 68, 69, 71, 73, 97] + shuffle(array) + print(array) + + +if __name__ == "__main__": + main() From 7793db35435916c6a02e648ad55f71802e5435b2 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Mon, 16 Nov 2020 10:01:07 +0530 Subject: [PATCH 112/209] add dynamic connectivity quick find and quick union algo --- dynamic_connectivity/quick_find.py | 68 ++++++++++++ dynamic_connectivity/quick_union.py | 75 +++++++++++++ dynamic_connectivity/weighted_quick_union.py | 110 +++++++++++++++++++ 3 files changed, 253 insertions(+) create mode 100644 dynamic_connectivity/quick_find.py create mode 100644 dynamic_connectivity/quick_union.py create mode 100644 dynamic_connectivity/weighted_quick_union.py diff --git a/dynamic_connectivity/quick_find.py b/dynamic_connectivity/quick_find.py new file mode 100644 index 0000000..203f209 --- /dev/null +++ b/dynamic_connectivity/quick_find.py @@ -0,0 +1,68 @@ +""" Quick Find is a Eager Approach. + +*Limitations:* + +- Union is too expensive (N array accesses) +- Trees are flat, but too expensive to keep them flat +""" + + +class QuickFind: + """ elem1 and elem2 are connected iff they have the same id """ + + def __init__(self, n): + """ Initializing list of size n where value is same as index + Time Complexity: O(n) + + :param n: number of elements + """ + self.data = [] + for i in range(n): + self.data.append(i) + + def connected(self, elem1, elem2): + """ elem1 and elem2 are connected iff they have the same id + Time Complexity: O(1) + + :param elem1: element 1 + :param elem2: element 2 + :return: returns true iff two elem1 and elem2 are connected, else + false + :rtype: bool + """ + return self.data[elem1] == self.data[elem2] + + def union(self, elem1, elem2): + """ When connecting two objects elem1 and elem2, change the id of all + objects that have the id of elem1 to that of elem2, or vice-versa. + Time Complexity is O(n), which is too expensive. + + :param elem1: element 1 + :param elem2: element 2 + """ + pid = self.data[elem1] + qid = self.data[elem2] + for i in range(len(self.data)): + if self.data[i] == pid: + self.data[i] = qid + + +def main(): + """ operational function """ + maze = QuickFind(10) + maze.union(4, 3) + maze.union(3, 8) + maze.union(6, 5) + maze.union(9, 4) + maze.union(2, 1) + print("is 0-7 connected: ", maze.connected(0, 7)) + print("is 8-9 connected: ", maze.connected(8, 9)) + maze.union(5, 0) + maze.union(7, 2) + maze.union(6, 1) + maze.union(1, 0) + print("is 0-7 connected: ", maze.connected(0, 7)) + + +if __name__ == "__main__": + main() diff --git a/dynamic_connectivity/quick_union.py b/dynamic_connectivity/quick_union.py new file mode 100644 index 0000000..c91310c --- /dev/null +++ b/dynamic_connectivity/quick_union.py @@ -0,0 +1,75 @@ +""" QuickUnion is a lazy approach. + +*Limitations:* + +- Trees can get too tall +- Find too expensive (could be N array accesses) +""" + + +class QuickUnion: + """ data[i] is parent of i. Root of i is id[id[...id[i]...]] """ + + def __init__(self, n): + """ Initializing list of size n where value is same as index + Here it means that each node is a root of it's own tree + Time Complexity: O(n) + + :param n: number of elements + """ + self.data = [] + for i in range(n): + self.data.append(i) + + def root(self, elem): + """ Finding the root of element + + :param elem: element of which root is needed + :return: root of elem + """ + while elem != self.data[elem]: + elem = self.data[elem] + return elem + + def connected(self, elem1, elem2): + """ elem1 and elem2 are connected iff they have same root + + :param elem1: element 1 + :param elem2: element 2 + :return: returns true iff two elem1 and elem2 are connected, else + false + :rtype: bool + """ + return self.root(elem1) == self.root(elem2) + + def union(self, elem1, elem2): + """ To merge components containing elem1 and elem2, set the id of + elem1's root to the id of elem2's root + + :param elem1: element 1 + :param elem2: element 2 + """ + root_elem1 = self.root(elem1) + root_elem2 = self.root(elem2) + self.data[root_elem1] = root_elem2 + + +def main(): + """ operational function """ + maze = QuickUnion(10) + maze.union(4, 3) + maze.union(3, 8) + maze.union(6, 5) + maze.union(9, 4) + maze.union(2, 1) + print("is 0-7 connected: ", maze.connected(0, 7)) + print("is 8-9 connected: ", maze.connected(8, 9)) + maze.union(5, 0) + maze.union(7, 2) + maze.union(6, 1) + maze.union(1, 0) + print("is 0-7 connected: ", maze.connected(0, 7)) + + +if __name__ == "__main__": + main() diff --git a/dynamic_connectivity/weighted_quick_union.py b/dynamic_connectivity/weighted_quick_union.py new file mode 100644 index 0000000..8256234 --- /dev/null +++ b/dynamic_connectivity/weighted_quick_union.py @@ -0,0 +1,110 @@ +""" QuickFind and QuickUnion algorithms are easy to implement, +but simply can't support huge dynamic connectivity problems. + +*Improvement 1:* **Weighting** + +- modify quick union to avoid tall trees +- keep track of size of each tree (number of objects) +- balance by linking root of smaller tree to root of larger tree + +*Improvement 2:* **Path Compression** + +Just after computing the root of p, set the id of each examined node to +point to that root. + +**Implementation of path compression:** + +- Two-pass Implementation: add second loop to root() to set the id[] of each + examined node to the root. +- Simpler one-pass variant: Make every other node in path point to its + grandparent (thereby halving path length) [implmented in this script] +""" + + +class WeightedQuickUnion: + """ Same as quick-union, but maintain extra array sz_count[i] to count + number of objects in the tree rooted at i + """ + + def __init__(self, n): + """ Initializing list of size n where value is same as index + Here it means that each node is a root of it's own tree + Time Complexity: O(n) + + :param n: number of elements + """ + self.data = [] + self.sz_count = [] + for i in range(n): + self.data.append(i) + self.sz_count.append(0) + + def root(self, elem): + """ Finding the root of element + + :param elem: element of which root is needed + :return: root of elem + """ + while elem != self.data[elem]: + # only one extra line for path compression + self.data[elem] = self.data[self.data[elem]] + elem = self.data[elem] + return elem + + def connected(self, elem1, elem2): + """ elem1 and elem2 are connected iff they have same root. It takes + time proportional to depth of elem1 and elem2. Time complexity is lg(N) + + :param elem1: element 1 + :param elem2: element 2 + :return: returns true iff two elem1 and elem2 are connected, else + false + :rtype: bool + """ + return self.root(elem1) == self.root(elem2) + + def union(self, elem1, elem2): + """ To merge components containing elem1 and elem2, set the id of + elem1's root to the id of elem2's root. + modify quick-union to: + + - link root of smaller tree to root of larger tree + - update the sz_count[] array + + Time complexity is lg N. Depth of any node x is at most lg N. + + :param elem1: element 1 + :param elem2: element 2 + """ + root_elem1 = self.root(elem1) + root_elem2 = self.root(elem2) + if root_elem1 == root_elem2: + return + + if self.sz_count[root_elem1] < self.sz_count[root_elem2]: + self.data[root_elem1] = root_elem2 + self.sz_count[root_elem2] += self.sz_count[root_elem1] + else: + self.data[root_elem2] = root_elem1 + self.sz_count[root_elem1] += self.sz_count[root_elem2] + + +def main(): + """ operational function """ + maze = WeightedQuickUnion(10) + maze.union(4, 3) + maze.union(3, 8) + maze.union(6, 5) + maze.union(9, 4) + maze.union(2, 1) + print("is 0-7 connected: ", maze.connected(0, 7)) + print("is 8-9 connected: ", maze.connected(8, 9)) + maze.union(5, 0) + maze.union(7, 2) + maze.union(6, 1) + maze.union(1, 0) + print("is 0-7 connected: ", maze.connected(0, 7)) + + +if __name__ == "__main__": + main() From dd6946bab0fd47ba2a34e6d6026649a4ae7c328c Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Mon, 16 Nov 2020 10:01:56 +0530 Subject: [PATCH 113/209] add gnome and oddeven sorting algorithm --- sort/gnome.py | 32 ++++++++++++++++++++++++++++++++ sort/oddeven.py | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+) create mode 100644 sort/gnome.py create mode 100644 sort/oddeven.py diff --git a/sort/gnome.py b/sort/gnome.py new file mode 100644 index 0000000..f690011 --- /dev/null +++ b/sort/gnome.py @@ -0,0 +1,32 @@ +""" Implementation of Gnome Sort algorithm +""" + + +def gnome(data): + """ GnomeSort is a sorting algorithm which is similar + to insertion sort in that it works with one item at a time + but gets the item to the proper place by a series of swaps. + + :param array: list of elements that needs to be sorted + :type array: list + """ + index = 0 + data_len = len(data) + while index < data_len: + if index == 0 or data[index] >= data[index - 1]: + index = index + 1 + else: + data[index], data[index-1] = data[index-1], data[index] + index = index - 1 + + +def main(): + """ operational function """ + arr = [34, 56, 23, 67, 3, 68] + print(f"unsorted array: {arr}") + gnome(arr) + print(f" sorted array: {arr}") + + +if __name__ == "__main__": + main() diff --git a/sort/oddeven.py b/sort/oddeven.py new file mode 100644 index 0000000..4136ff6 --- /dev/null +++ b/sort/oddeven.py @@ -0,0 +1,40 @@ +""" Implementation of Odd-Even Sort algorithm +""" + + +def oddeven(data): + """ OddEvenSort is a variation of bubble sort where the sorting is divided + into two phases, Odd and Even Phase and it runs until all the elements + are sorted. In the odd phase we perform bubble sort on odd indexed + elements and in the even phase we perform bubble sort on even indexed + elements. + + :param array: list of elements that needs to be sorted + :type array: list + """ + is_sorted = False + data_len = len(data) + + while not is_sorted: + is_sorted = True + for i in range(1, data_len-1, 2): + if data[i] > data[i+1]: + data[i], data[i+1] = data[i+1], data[i] + is_sorted = False + + for i in range(0, data_len-1, 2): + if data[i] > data[i+1]: + data[i], data[i+1] = data[i+1], data[i] + is_sorted = False + + +def main(): + """ operational function """ + arr = [34, 56, 23, 67, 3, 68] + print(f"unsorted array: {arr}") + oddeven(arr) + print(f" sorted array: {arr}") + + +if __name__ == "__main__": + main() From 56e75de3f5059b232f2d5acf15c307128caee656 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Tue, 17 Nov 2020 20:24:07 +0530 Subject: [PATCH 114/209] used list instead of dict in trie --- trie/trie.py | 41 +++++++++++++++++++++++------------------ 1 file changed, 23 insertions(+), 18 deletions(-) diff --git a/trie/trie.py b/trie/trie.py index ca7ecbc..ad45dd8 100644 --- a/trie/trie.py +++ b/trie/trie.py @@ -8,27 +8,30 @@ class Node: """ Node contains character and it's children trie node """ - def __init__(self, character): - self.character = character - self.children = {} + def __init__(self): + self.children = [None] * 26 self.word_finished = False class Trie: """ Trie Data Structure implementation """ def __init__(self): - self.root = Node(None) + self.root = Node() + + def char_to_index(self, char): + """ converts key character into index + use only 'a' through 'z' lower case + """ + return ord(char) - ord('a') def insert(self, word): """ inserts a word in the trie data structure""" current = self.root for character in word: - if character in current.children: - current = current.children[character] - else: - new_node = Node(character) - current.children[character] = new_node - current = new_node + index = self.char_to_index(character) + if not current.children[index]: + current.children[index] = Node() + current = current.children[index] current.word_finished = True def search(self, word): @@ -37,10 +40,11 @@ def search(self, word): """ current = self.root for character in word: - if character not in current.children: + index = self.char_to_index(character) + if not current.children[index]: return False - current = current.children[character] - return current.word_finished + current = current.children[index] + return current is not None and current.word_finished def starts_with(self, prefix): """ returns true if any word present in the trie start with the @@ -48,18 +52,20 @@ def starts_with(self, prefix): """ current = self.root for character in prefix: - if character not in current.children: + index = self.char_to_index(character) + if not current.children[index]: return False - current = current.children[character] + current = current.children[index] return True def delete(self, word): """ deletes word by negating word_finished boolean variable """ current = self.root for character in word: - if character not in current.children: + index = self.char_to_index(character) + if not current.children[index]: raise Exception("word not present in trie") - current = current.children[character] + current = current.children[index] if current.word_finished: current.word_finished = False @@ -80,7 +86,6 @@ def main(): print("removing 'app' from trie") tree.delete("app") print("is app present?", tree.search("app")) # False - breakpoint() if __name__ == "__main__": From 88db9a89707e43821d1d75d5be9a6f654c668a38 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Tue, 17 Nov 2020 20:27:59 +0530 Subject: [PATCH 115/209] add ternary search tries ds --- ternary_search_tries/ternary_search_tries.py | 90 ++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 ternary_search_tries/ternary_search_tries.py diff --git a/ternary_search_tries/ternary_search_tries.py b/ternary_search_tries/ternary_search_tries.py new file mode 100644 index 0000000..8176493 --- /dev/null +++ b/ternary_search_tries/ternary_search_tries.py @@ -0,0 +1,90 @@ +""" +A ternary search tree is a special trie data structure where the child nodes +of a standard trie are ordered as a binary search tree. + +Representation of ternary search trees: + +Unlike trie(standard) data structure where each node contains 26 pointers for +its children, each node in a ternary search tree contains only 3 pointers: + 1. The left pointer points to the node whose value is less than the + value in the current node. + 2. The equal pointer points to the node whose value is equal to the + value in the current node. + 3. The right pointer points to the node whose value is greater than the + value in the current node. +""" + +class Node: # pylint: disable=too-few-public-methods + """ Node contains actual data and left, middle and right node """ + def __init__(self, character): + self.character = character + self.value = None + self.left = None + self.middle = None + self.right = None + + +class TernarySearchTries: + """ Ternary Search Tries Implemenation""" + def __init__(self): + self.root = None + + def put(self, key, value): + """ inserts new key-value pair into the ternary search tries """ + def _put(node, key, value, depth): + """ recursive internal method which works on node level """ + char = key[depth] + if node is None: + node = Node(char) + + if char < node.character: + node.left = _put(node.left, key, value, depth) + elif char > node.character: + node.right = _put(node.right, key, value, depth) + elif depth < len(key) - 1: + node.middle = _put(node.middle, key, value, depth + 1) + else: + node.value = value + return node + + self.root = _put(self.root, key, value, 0) + + def get(self, key): + """ returns value of the key if the key is present, else -1 """ + def _get(node, key, depth): + """ recursive internal method which works on node level """ + if node is None: + return None + + char = key[depth] + + if char < node.character: + return _get(node.left, key, depth) + if char > node.character: + return _get(node.right, key, depth) + if depth < len(key) - 1: + return _get(node.middle, key, depth + 1) + return node + + node = _get(self.root, key, 0) + + if node is None: + return -1 + return node.value + + +def main(): + """ operational function """ + tst = TernarySearchTries() + tst.put("apple", 100) + tst.put("orange", 200) + + print(tst.get("apple")) # 100 + print(tst.get("adam")) # -1 + + tst.put("adam", 50) + print(tst.get("adam")) # 50 + + +if __name__ == "__main__": + main() From 2646abe5393f44a23964b4e35b9a6423316a5c2a Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Wed, 18 Nov 2020 19:10:12 +0530 Subject: [PATCH 116/209] add balanced parenthesis using stack --- stack/balanced_parenthesis.py | 50 +++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 stack/balanced_parenthesis.py diff --git a/stack/balanced_parenthesis.py b/stack/balanced_parenthesis.py new file mode 100644 index 0000000..2735473 --- /dev/null +++ b/stack/balanced_parenthesis.py @@ -0,0 +1,50 @@ +""" Given a string s containing just the characters + '(', ')', '{', '}', '[' and ']', determine if the input string is valid. + + An input string is valid if: + - Open brackets must be closed by the same type of brackets. + - Open brackets must be closed in the correct order. +""" + +from collections import deque + +OPEN_PARENTHESES = {'(', '{', '['} +CLOSE_PARENTHESES = {')', '}', ']'} + +def is_parentheses_matched(open_paren, close_paren): + """ checking if open_paren and close_paren are matching """ + if open_paren == '(' and close_paren == ')': + return True + if open_paren == '{' and close_paren == '}': + return True + if open_paren == '[' and close_paren == ']': + return True + return False + +def is_valid_parentheses(parentheses_string): + """ returns true if parentheses string is valid and balanced, else false """ + stack = deque() + is_valid = True + index = 0 + while index < len(parentheses_string) and is_valid: + character = parentheses_string[index] + if character in OPEN_PARENTHESES: + stack.append(character) + elif character in CLOSE_PARENTHESES: + if not stack: + is_valid = False + else: + top = stack.pop() + if not is_parentheses_matched(top, character): + is_valid = False + else: + raise Exception("invalid character") + index += 1 + + if not stack and is_valid: + return True + return False + + +print(is_valid_parentheses("({[]}{}[{({}[])}])")) # True +print(is_valid_parentheses("({[]}{}[{({}])}])")) # False From 9b4a1ebb2d2c56cf767595b98d4acc0c082b3313 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Wed, 18 Nov 2020 19:10:39 +0530 Subject: [PATCH 117/209] add palindrome using queue --- linked_list/is_palindrome.py | 67 ++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 linked_list/is_palindrome.py diff --git a/linked_list/is_palindrome.py b/linked_list/is_palindrome.py new file mode 100644 index 0000000..238b617 --- /dev/null +++ b/linked_list/is_palindrome.py @@ -0,0 +1,67 @@ +""" check if linked list is palindrome or not +""" + +class Node: + """ Node class contains everything related to Linked List node """ + def __init__(self, data): + """ initializing single node with data """ + self.data = data + self.next = None + + +class LinkedList: + """ Singly Linked List is a linear data structure """ + def __init__(self): + """ initializing singly linked list with zero node """ + self.head = None + + def insert_head(self, data): + """ inserts node at the start of linked list """ + node = Node(data) + node.next = self.head + self.head = node + + def print(self): + """ prints entire linked list without changing underlying data """ + current = self.head + while current is not None: + print(" ->", current.data, end="") + current = current.next + print() + + + def is_palindrome(self): + """ removes duplicates from list """ + stack = [] + current = self.head + + while current is not None: + stack.append(current.data) + current = current.next + + current = self.head + for _ in range(len(stack)//2): + if stack.pop() != current.data: + return False + current = current.next + + return True + + +def main(): + """ operational function """ + linkedlist = LinkedList() + linkedlist.insert_head(4) + linkedlist.insert_head(2) + linkedlist.insert_head(2) + linkedlist.insert_head(1) + linkedlist.insert_head(2) + linkedlist.insert_head(2) + linkedlist.insert_head(4) + + linkedlist.print() + print(linkedlist.is_palindrome()) + + +if __name__ == '__main__': + main() From 4d0d456e6e140942426cb2ab3a3febfeaaf0212a Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Wed, 18 Nov 2020 19:11:53 +0530 Subject: [PATCH 118/209] add linked list nth to last node --- linked_list/nth_to_last_node.py | 66 +++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 linked_list/nth_to_last_node.py diff --git a/linked_list/nth_to_last_node.py b/linked_list/nth_to_last_node.py new file mode 100644 index 0000000..f2fd605 --- /dev/null +++ b/linked_list/nth_to_last_node.py @@ -0,0 +1,66 @@ +""" Remove duplicates from linked list + input: 1 -> 6 -> 1 -> 4 -> 2 -> 2 -> 4 + output: 1 -> 6 -> 4 -> 2 +""" + +class Node: + """ Node class contains everything related to Linked List node """ + def __init__(self, data): + """ initializing single node with data """ + self.data = data + self.next = None + + +class LinkedList: + """ Singly Linked List is a linear data structure """ + def __init__(self): + """ initializing singly linked list with zero node """ + self.head = None + + def insert_head(self, data): + """ inserts node at the start of linked list """ + node = Node(data) + node.next = self.head + self.head = node + + def print(self): + """ prints entire linked list without changing underlying data """ + current = self.head + while current is not None: + print(" ->", current.data, end="") + current = current.next + print() + + + def nth_to_last_node(self, position): + """ returns nth to last node """ + fast_ptr = self.head + slow_ptr = self.head + + while position > 0: + slow_ptr = slow_ptr.next + position -= 1 + + while slow_ptr is not None: + slow_ptr = slow_ptr.next + fast_ptr = fast_ptr.next + + return fast_ptr + + +def main(): + """ operational function """ + linkedlist = LinkedList() + linkedlist.insert_head('D') + linkedlist.insert_head('C') + linkedlist.insert_head('B') + linkedlist.insert_head('A') + + linkedlist.print() + result = linkedlist.nth_to_last_node(3) + print(result.data) + + + +if __name__ == '__main__': + main() From 6d3816dd0dc062ed9449ecc99c43724d53878594 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Thu, 19 Nov 2020 11:47:56 +0530 Subject: [PATCH 119/209] add red-black tree --- red_black_tree/red_black_tree.py | 263 +++++++++++++++++++++++++++++++ 1 file changed, 263 insertions(+) create mode 100644 red_black_tree/red_black_tree.py diff --git a/red_black_tree/red_black_tree.py b/red_black_tree/red_black_tree.py new file mode 100644 index 0000000..66579eb --- /dev/null +++ b/red_black_tree/red_black_tree.py @@ -0,0 +1,263 @@ +""" +Red Black Tree is an implementation for left leaning red black tree +data structure in go language. + +Red-Black Tree is a self-balancing Binary Search Tree (BST) where every node +has a color either red or black. Root of tree is always black. There are no +two adjacent red nodes (A red node cannot have a red parent or red child). +Every path from a node (including root) to any of its descendant NULL node has +the same number of black nodes. + +Why Red-Black Trees + +Most of the BST operations (e.g., search, max, min, insert, delete.. etc) +take O(h) time where h is the height of the BST. The cost of these +operations may become O(n) for a skewed Binary tree. If we make sure that +height of the tree remains O(Logn) after every insertion and deletion, then +we can guarantee an upper bound of O(Logn) for all these operations. The +height of a Red-Black tree is always O(Logn) where n is the number of nodes +in the tree. + +The main problem with BST deletion (Hibbard Deletion) is that It is not +symmetric. After many insertion and deletion BST become less balance. +Researchers proved that after sufficiently long number of random insert +and delete height of the tree becomes sqrt(n) .So now every operation +(search, insert, delete) will take sqrt(n) time which is not good compare +to O(logn) . + +This is very long standing(around 50 years) open problem to efficient +symmetric delete for BST. for guaranteed balanced tree, we have to use +RedBlack Tree etc. + +Properties + - No Node has two red links connected to it. + - Every path from root to null link has the same number of black links. + - Red links lean left. +""" + +RED = 0 +BLACK = 1 + +class Node: # pylint: disable=too-few-public-methods + """ Red Black Node contains actual data and color bit along with + links to left, right, parent node + """ + def __init__(self, data, color): + self.data = data + self.color = color + self.left = None + self.right = None + self.parent = None + + def __repr__(self): + return f"Node (data:{self.data} color: {self.color})" + +class RedBlackTree: + """ Red Black Tree Implementation """ + def __init__(self): + self.root = None + self.size = 0 + + def insert(self, data): # pylint: disable=too-many-statements + """ inserts new integer data into the tree at the position, so that + the red black tree property is maintained. + """ + def insert_case1(node): + if node.parent is None: + node.color = BLACK + else: + insert_case2(node) + + def insert_case2(node): + if self.get_node_color(node.parent) == BLACK: + return + insert_case3(node) + + def insert_case3(node): + uncle_node = self.uncle(node) + if self.get_node_color(uncle_node) == RED: + node.parent.color = BLACK + uncle_node.color = BLACK + grandparent_node = self.grandparent(node) + grandparent_node.color = RED + insert_case1(grandparent_node) + else: + insert_case4(node) + + def insert_case4(node): + grandparent_node = self.grandparent(node) + if (node is node.parent.right and + node.parent is grandparent_node.left): + self.left_rotate(node.parent) + node = node.left + elif (node is node.parent.left and + node.parent is grandparent_node.right): + self.right_rotate(node.parent) + node = node.right + insert_case5(node) + + def insert_case5(node): + node.parent.color = BLACK + grandparent_node = self.grandparent(node) + grandparent_node.color = RED + if (node is node.parent.left and + node.parent is grandparent_node.left): + self.right_rotate(grandparent_node) + elif (node is node.parent.right and + node.parent is grandparent_node.right): + self.left_rotate(grandparent_node) + + inserted_node = None + if self.root is None: + self.root = Node(data, RED) + inserted_node = self.root + else: + node = self.root + while True: + if data < node.data: + if node.left is None: + node.left = Node(data, RED) + inserted_node = node.left + break + node = node.left + elif data > node.data: + if node.right is None: + node.right = Node(data, RED) + inserted_node = node.right + break + node = node.right + else: + node.data = data + return + inserted_node.parent = node + insert_case1(inserted_node) + self.size += 1 + + def search(self, data): + """ finds the integer in red black tree + """ + def _search(root, data): + """ recursive internal method which works at node level """ + if root is None: + return False + + # pylint: disable=no-else-return + if data == root.data: + return True + elif data < root.data: + return _search(root.left, data) + else: + return _search(root.right, data) + + if self.root is None: + return False + return _search(self.root, data) + + def min(self): + """ returns left-most item present in red black tree which is also + the minimum element in rb-tree + """ + if self.root is None: + raise Exception("tree is empty") + + current = self.root + while current.left is not None: + current = current.left + return current.data + + def max(self): + """ returns right-most item present in red black tree which is also + the maximum element in rb-tree + """ + if self.root is None: + raise Exception("tree is empty") + + current = self.root + while current.right is not None: + current = current.right + return current.data + + @staticmethod + def get_node_color(node): + """ returns node color """ + if node is None: + return BLACK + return node.color + + @staticmethod + def uncle(node): + """ returns uncle of node """ + if node is None or node.parent is None or node.parent.parent is None: + return None + return RedBlackTree.sibling(node.parent) + + @staticmethod + def sibling(node): + """ returns sibling of given node """ + if node is None or node.parent is None: + return None + + if node is node.parent.left: + return node.parent.right + return node.parent.left + + @staticmethod + def grandparent(node): + """ returns grandparent of node """ + if node is None or node.parent is None: + return None + return node.parent.parent + + def left_rotate(self, node): + """ performs left rotation on given node """ + right = node.right + self.replace_node(node, right) + node.right = right.left + if right.left is not None: + right.left.parent = node + right.left = node + node.parent = right + + def right_rotate(self, node): + """ performs right rotation on given node """ + left = node.left + self.replace_node(node, left) + node.left = left.right + if left.right is not None: + left.right.parent = node + left.right = node + node.parent = left + + def replace_node(self, old_node, new_node): + """ replace old node with new node """ + if old_node.parent is None: + self.root = new_node + else: + if old_node is old_node.parent.left: + old_node.parent.left = new_node + else: + old_node.parent.right = new_node + + if new_node is not None: + new_node.parent = old_node.parent + + +def main(): + """ operational function """ + rb_tree = RedBlackTree() + rb_tree.insert(1) + rb_tree.insert(2) + rb_tree.insert(3) + rb_tree.insert(4) + rb_tree.insert(5) + + print("min value:", rb_tree.min()) + print("max value:", rb_tree.max()) + + print("is 1 present?", rb_tree.search(1)) + print("is 11 present?", rb_tree.search(11)) + print("is 5 present?", rb_tree.search(5)) + + +if __name__ == "__main__": + main() From be7d8f225d72b89c80901a931fd06dd5499114bf Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Thu, 19 Nov 2020 11:50:58 +0530 Subject: [PATCH 120/209] add avl tree --- avl_tree/avl_tree.py | 200 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 200 insertions(+) create mode 100644 avl_tree/avl_tree.py diff --git a/avl_tree/avl_tree.py b/avl_tree/avl_tree.py new file mode 100644 index 0000000..d15d204 --- /dev/null +++ b/avl_tree/avl_tree.py @@ -0,0 +1,200 @@ +""" AVL Tree Implementation in Python + +AVL tree is a self-balancing Binary Search Tree (BST) where the difference +between heights of left and right subtrees cannot be more than one for +all nodes. +""" + +class Node: # pylint: disable=too-few-public-methods + """ Node contains actual data and address to left and right node """ + def __init__(self, data): + self.data = data + self.left = None + self.right = None + self.height = 1 + + +class AVLTree: + """ AVL Tree Implementation """ + def __init__(self): + self.root = None + + def insert(self, key): + """ inserts new integer data into the tree at the position, so that + the AVL tree property is maintained. + """ + def _insert(root, key): + """ recursive internal method which works on node level """ + if root is None: + return Node(key) + + if key < root.data: + root.left = _insert(root.left, key) + else: + root.right = _insert(root.right, key) + + root.height = max(self.get_height(root.left), + self.get_height(root.right)) + 1 + + balance_factor = self.get_balance_factor(root) + + # if node is unbalanced + # case 1 - left left + if balance_factor > 1 and key < root.left.data: + return self.right_rotate(root) + + # case 2 - right right + if balance_factor < -1 and key > root.right.data: + return self.left_rotate(root) + + # case 3 - left right + if balance_factor > 1 and key > root.left.data: + root.left = self.left_rotate(root.left) + return self.right_rotate(root) + + # case 4 - right left + if balance_factor < -1 and key < root.right.data: + root.right = self.right_rotate(root.right) + return self.left_rotate(root) + + return root + + self.root = _insert(self.root, key) + + def delete(self, key): + """ delete value from AVL tree """ + def find_min_node(node): + """ find the node with minimum value of give (sub)tree """ + while node.left is not None: + node = node.left + return node + + def _delete(root, key): + """ interal recursive method that works at node-level """ + if root is None: + return root + + if key < root.data: + root.left = _delete(root.left, key) + elif key > root.data: + root.right = _delete(root.right, key) + else: + if root.left is None and root.right is None: + del root + root = None + elif root.left is None: + temp = root + root = root.right + del temp + elif root.right is None: + temp = root + root = root.left + del temp + else: + temp = find_min_node(root.right) + root.data = temp.data + root.right = _delete(root.right, temp.data) + + root.height = max(self.get_height(root.left), + self.get_height(root.right)) + 1 + + balance_factor = self.get_balance_factor(root) + + # if node is unbalanced + # case 1 - left left + if balance_factor > 1 and self.get_balance_factor(root.left) >= 0: + return self.right_rotate(root) + + # case 2 - right right + if balance_factor < -1 and self.get_balance_factor(root.right) <= 0: + return self.left_rotate(root) + + # case 3 - left right + if balance_factor > 1 and self.get_balance_factor(root.left) < 0: + root.left = self.left_rotate(root.left) + return self.right_rotate(root) + + # case 4 - right left + if balance_factor < -1 and self.get_balance_factor(root.right) > 0: + root.right = self.right_rotate(root.right) + return self.left_rotate(root) + + return root + + self.root = _delete(self.root, key) + + def right_rotate(self, node): + """ perform right rotation on given node """ + left_node = node.left + subtree = left_node.right + + # perform rotation + left_node.right = node + node.left = subtree + + node.height = max(self.get_height(node.left), + self.get_height(node.right)) + 1 + left_node.height = max(self.get_height(left_node.left), + self.get_height(left_node.right)) + 1 + return left_node + + def left_rotate(self, node): + """ perform left rotation on given node """ + right_node = node.right + subtree = right_node.left + + # perform rotation + right_node.left = node + node.right = subtree + + node.height = max(self.get_height(node.left), + self.get_height(node.right)) + 1 + right_node.height = max(self.get_height(right_node.left), + self.get_height(right_node.right)) + 1 + return right_node + + @staticmethod + def get_height(node): + """ returns height of node """ + if node is None: + return 0 + + return node.height + + def get_balance_factor(self, node): + """ returns balance factor at node """ + if node is None: + return 0 + + return self.get_height(node.left) - self.get_height(node.right) + + +def pre_order(node): + """ prints pre order traversal """ + if node is None: + return + + print(node.data, end=" ") + pre_order(node.left) + pre_order(node.right) + + +def main(): + """ operational function """ + avl_tree = AVLTree() + for elem in [9, 5, 10, 0, 6, 11, -1, 1, 2]: + avl_tree.insert(elem) + + print("preorder traversal after insertion") + pre_order(avl_tree.root) # 9 1 0 -1 5 2 6 10 11 + print() + + avl_tree.delete(10) + + print("preorder traversal after deletion") + pre_order(avl_tree.root) # 1 0 -1 9 5 2 6 11 + print() + + +if __name__ == "__main__": + main() From a03ee2c9887ce024b2ff5852b3e165e22c37443c Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sun, 22 Nov 2020 22:12:06 +0530 Subject: [PATCH 121/209] add max heap priority queue --- heap/maxheap.py | 99 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 heap/maxheap.py diff --git a/heap/maxheap.py b/heap/maxheap.py new file mode 100644 index 0000000..72e42a8 --- /dev/null +++ b/heap/maxheap.py @@ -0,0 +1,99 @@ +""" Implementation of Max Heap Data Structure """ + + +class MaxHeap: + """ Max Heap is a complete binary tree. + In Max Heap, the key at root must be maximum among all keys + present in Binary Heap. The same property must be recursively true for + all nodes in Binary Tree. + """ + + def __init__(self): + """ initialize new empty 1-indexed heap """ + self.data = [None] + + def length(self): + """ returns total number of items present in heap """ + return len(self.data) - 1 + + def is_empty(self): + """ checks if heap is empty or not """ + return self.length() == 0 + + def insert(self, item): + """ inserts new item into heap while maintaining heap invariant """ + self.data.append(item) + self.swim(self.length()) + + def get_max(self): + """ get_max returns the maximum value (i.e. root) in the heap, + without removing it. Returns None, if the heap is empty. + """ + if self.is_empty(): + return None + return self.data[1] + + def extract_max(self): + """ extract_max returns the maximum value (i.e. root) in the heap + and removes it from the heap. Returns None, if heap is empty. + """ + if self.is_empty(): + return None + + max_value = self.data[1] + self.data[1] = self.data[self.length()] + self.data = self.data[:self.length()] + self.sink(1) + return max_value + + def swim(self, index): + """ swim moves element at index upward to maintain heap invariant """ + if index <= 1: + return + + parent = index // 2 + if self.data[parent] < self.data[index]: + self.data[parent], self.data[index] = self.data[index], self.data[parent] + self.swim(parent) + + def sink(self, index): + """ sink moves element at index downward to maintain heap invariant """ + max_index = index + left = index * 2 + right = (index * 2) + 1 + + if left <= self.length(): + if self.data[max_index] < self.data[left]: + max_index = left + + if right <= self.length(): + if self.data[max_index] < self.data[right]: + max_index = right + + if max_index != index: + self.data[index], self.data[max_index] = self.data[max_index], self.data[index] + self.sink(max_index) + + +def main(): + """ operational function """ + mheap = MaxHeap() + mheap.insert(5) + mheap.insert(3) + print(mheap.get_max()) + mheap.insert(1) + mheap.insert(6) + mheap.insert(2) + print(mheap.data) + print(mheap.extract_max()) + print(mheap.data) + print(mheap.extract_max()) + mheap.insert(3) + print(mheap.extract_max()) + print(mheap.extract_max()) + print(mheap.extract_max()) + print(mheap.data) + + +if __name__ == "__main__": + main() From 5c37d6c4ca5893fa6b64e2315be0b5db6a8ce80c Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sun, 22 Nov 2020 22:12:17 +0530 Subject: [PATCH 122/209] add min heap priority queue --- heap/minheap.py | 99 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 heap/minheap.py diff --git a/heap/minheap.py b/heap/minheap.py new file mode 100644 index 0000000..5d729fc --- /dev/null +++ b/heap/minheap.py @@ -0,0 +1,99 @@ +""" Implementation of Min Heap Data Structure """ + + +class MinHeap: + """ MinHeap is a complete binary tree. + In MinHeap, the key at root must be minimum among all keys + present in Binary Heap. The same property must be recursively true for + all nodes in Binary Tree. + """ + + def __init__(self): + """ initialize new empty 1-indexed heap """ + self.data = [None] + + def length(self): + """ returns total number of items present in heap """ + return len(self.data) - 1 + + def is_empty(self): + """ checks if heap is empty or not """ + return self.length() == 0 + + def insert(self, item): + """ inserts new item into heap while maintaining heap invariant """ + self.data.append(item) + self.swim(self.length()) + + def get_min(self): + """ get_min returns the minimum value (i.e. root) in the heap, + without removing it. Returns None, if the heap is empty. + """ + if self.is_empty(): + return None + return self.data[1] + + def extract_min(self): + """ extract_min returns the minimum value (i.e. root) in the heap + and removes it from the heap. Returns None, if heap is empty. + """ + if self.is_empty(): + return None + + min_value = self.data[1] + self.data[1] = self.data[self.length()] + self.data = self.data[:self.length()] + self.sink(1) + return min_value + + def swim(self, index): + """ swim moves element at index upward to maintain heap invariant """ + if index <= 1: + return + + parent = index // 2 + if self.data[parent] > self.data[index]: + self.data[parent], self.data[index] = self.data[index], self.data[parent] + self.swim(parent) + + def sink(self, index): + """ sink moves element at index downward to maintain heap invariant """ + min_index = index + left = index * 2 + right = (index * 2) + 1 + + if left <= self.length(): + if self.data[min_index] > self.data[left]: + min_index = left + + if right <= self.length(): + if self.data[min_index] > self.data[right]: + min_index = right + + if min_index != index: + self.data[index], self.data[min_index] = self.data[min_index], self.data[index] + self.sink(min_index) + + +def main(): + """ operational function """ + mheap = MinHeap() + mheap.insert(5) + mheap.insert(3) + print(mheap.get_min()) + mheap.insert(1) + mheap.insert(6) + mheap.insert(2) + print(mheap.data) + print(mheap.extract_min()) + print(mheap.data) + print(mheap.extract_min()) + mheap.insert(3) + print(mheap.extract_min()) + print(mheap.extract_min()) + print(mheap.extract_min()) + print(mheap.data) + + +if __name__ == "__main__": + main() From 223ec7e832bbdf1a57d148703ba1ced2a3d9a4a3 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Tue, 24 Nov 2020 12:59:54 +0530 Subject: [PATCH 123/209] add general tree data structure --- tree/library/tree.py | 61 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 tree/library/tree.py diff --git a/tree/library/tree.py b/tree/library/tree.py new file mode 100644 index 0000000..eab9ad5 --- /dev/null +++ b/tree/library/tree.py @@ -0,0 +1,61 @@ +""" Implementation of General Tree Data Structure +""" + +class TreeNode: + """ General tree implementation """ + def __init__(self, data): + self.data = data + self.children = [] + self.parent = None + + def add_child(self, child): + """ adding child to tree node """ + child.parent = self + self.children.append(child) + + def get_level(self): + """ get level of node by calculating how many ancestor it has """ + level = 0 + parent = self.parent + while parent: + level += 1 + parent = parent.parent + + return level + + def print_tree(self): + """ print tree in proper hierarchical format """ + spaces = ' ' * self.get_level() * 3 + prefix = spaces + "|__" if self.parent else "" + print(prefix + self.data) + if self.children: + for child in self.children: + child.print_tree() + + +def build_product_tree(): + """ operational code """ + root = TreeNode("Electronics") + + laptop = TreeNode("Laptop") + laptop.add_child(TreeNode("Mac")) + laptop.add_child(TreeNode("Surface")) + laptop.add_child(TreeNode("Thinkpad")) + + cellphone = TreeNode("Cell Phone") + cellphone.add_child(TreeNode("iPhone")) + cellphone.add_child(TreeNode("Google Pixel")) + cellphone.add_child(TreeNode("Vivo")) + + television = TreeNode("TV") + television.add_child(TreeNode("Samsung")) + television.add_child(TreeNode("LG")) + + root.add_child(laptop) + root.add_child(cellphone) + root.add_child(television) + + root.print_tree() + +if __name__ == '__main__': + build_product_tree() From c5e0fe7c8a7b39368a6270ce6aa23179204717b9 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Tue, 24 Nov 2020 13:04:16 +0530 Subject: [PATCH 124/209] add doubly linked list ds --- linked_list/library/doubly_linked_list.py | 186 ++++++++++++++++++++++ 1 file changed, 186 insertions(+) create mode 100644 linked_list/library/doubly_linked_list.py diff --git a/linked_list/library/doubly_linked_list.py b/linked_list/library/doubly_linked_list.py new file mode 100644 index 0000000..f40554a --- /dev/null +++ b/linked_list/library/doubly_linked_list.py @@ -0,0 +1,186 @@ +""" Implementation of Doubly linked list Data Structure """ + +class Node: + """ Node class contains everything related to linked list node """ + + def __init__(self, data): + """ initializing single node with data """ + self.data = data + self.next = None + self.previous = None + + +class DoublyLinkedList: + """ A Doubly linked list (DLL) contains an extra pointer, typically + called previous pointer, together with next pointer and data which + are there in singly linked list. + """ + def __init__(self): + """ initializing doublt linked list with zero node """ + self.head = None + + def is_empty(self): + """ returns True if the linked list is empty. Otherwise, return False. """ + return self.head is None + + def __len__(self): + """ Traverses the linked list and returns an integer value representing + the number of nodes in the linked list. + + The time complexity is O(n) because every node in the linked list + must be visited in order to calculate the size of the linked list. + """ + if self.head is None: + return 0 + + count = 0 + current = self.head + + # While there are still Nodes left to count + while current is not None: + count += 1 + current = current.next + return count + + def insert_head(self, data): + """ inserts node at the start of doubly linked list """ + if self.head is None: + self.head = Node(data) + return + + new_node = Node(data) + current = self.head + new_node.next = current + current.previous = new_node + self.head = new_node + + def insert_tail(self, data): + """ inserts node at the end of doubly linked list """ + if self.head is None: + self.head = Node(data) + return + + current = self.head + new_node = Node(data) + while current.next is not None: + current = current.next + current.next = new_node + new_node.previous = current + + def insert_at(self, position, data): + """ inserts node at particular position in doubly linked list. + index starts from 0. + """ + dll_size = len(self) + if position < 0 or position > dll_size: + raise Exception("Invalid position") + + if position == dll_size: + self.insert_tail(data) + return + + if position == 0: + self.insert_head(data) + return + + current = self.head + for _ in range(0, position): + current = current.next + + new_node = Node(data) + previous = current.previous + previous.next = new_node + current.previous = new_node + new_node.next = current + new_node.previous = previous + + def delete_head(self): + """ removes first node and returns data. Raise exception, + if doubly linked list is empty + """ + if self.head is None: + raise Exception("linked list is already empty") + + if self.head.next is None: + self.head = None + return + + self.head = self.head.next + self.head.previous = None + + def delete_tail(self): + """ removes last node and returns data. raise exception, + if doubly linked list is empty + """ + if self.head is None: + raise Exception("linked list is already empty") + + if self.head.next is None: + self.head = None + return + + current = self.head + while current.next is not None: + current = current.next + + previous = current.previous + current.previous = None + previous.next = None + del current + + def delete_at(self, position): + """ removes specified node from doubly linked list and returns data. + raise exception, if position is invalid. + """ + dll_size = len(self) + if position < 0 or position > dll_size: + raise Exception("Invalid position") + + if position == 0: + self.delete_head() + elif position == dll_size: + self.delete_tail() + else: + current = self.head + for _ in range(0, position): + current = current.next + + previous_node = current.previous + next_node = current.next + previous_node.next = next_node + next_node.previous = previous_node + del current + + def print(self): + """ prints entire linked list without changing underlying data """ + current = self.head + while current is not None: + print(" <->", current.data, end="") + current = current.next + print() + + +def main(): + """ operational function """ + dll = DoublyLinkedList() + print("is_empty?", dll.is_empty()) + dll.insert_head(3) + print("is_empty?", dll.is_empty()) + dll.insert_head(2) + dll.insert_head(1) + dll.insert_tail(4) + dll.insert_tail(5) + dll.insert_tail(6) + print("size?", len(dll)) + dll.print() + + dll.insert_at(3, 66) + dll.print() + + print("deleting head") + dll.delete_at(3) + dll.print() + + +if __name__ == '__main__': + main() From 6df48b0466d94886188569fd0f61bea5595b696d Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Wed, 25 Nov 2020 14:09:39 +0530 Subject: [PATCH 125/209] rename heap to priority_queue --- {heap => priority_queue}/maxheap.py | 0 {heap => priority_queue}/minheap.py | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename {heap => priority_queue}/maxheap.py (100%) rename {heap => priority_queue}/minheap.py (100%) diff --git a/heap/maxheap.py b/priority_queue/maxheap.py similarity index 100% rename from heap/maxheap.py rename to priority_queue/maxheap.py diff --git a/heap/minheap.py b/priority_queue/minheap.py similarity index 100% rename from heap/minheap.py rename to priority_queue/minheap.py From 3a3ce3fa472ffbac42f598444ca23c94ffa4222e Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Wed, 25 Nov 2020 14:10:15 +0530 Subject: [PATCH 126/209] add hashtable linear probing --- hashtable/linear_probing.py | 54 +++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 hashtable/linear_probing.py diff --git a/hashtable/linear_probing.py b/hashtable/linear_probing.py new file mode 100644 index 0000000..7d439df --- /dev/null +++ b/hashtable/linear_probing.py @@ -0,0 +1,54 @@ +class LinearProbing: + def __init__(self): + self.size = 10 + self.arr = [None for _ in range(self.size)] + + def get_hash(self, key): + hash_value = 0 + for char in key: + hash_value += ord(char) + return hash_value % self.size + + def put(self, key, value): + index = self.get_hash(key) + if self.arr[index] is not None: + if self.arr[index][0] == key: + # update existing value + self.arr[index] = (key, value) + return + + # rehash try to find another slot + index = (index + 1) % self.size + + # insert new value + self.arr[index] = (key, value) + + def get(self, key): + index = self.get_hash(key) + if self.arr[index] is not None: + if self.arr[index][0] == key: + return self.arr[index][1] + + index = (index + 1) % self.size + + # if key is not present + return None + + +def main(): + """ operational function """ + table = LinearProbing() + table.put("apple", 10) + table.put("orange", 20) + table.put("car", 30) + table.put("table", 40) + + print(table.get("orange")) # 20 + print(table.get("kevin")) # None + + table.put("orange", 50) + print(table.get("orange")) # 50 + +if __name__ == "__main__": + main() + From 0e5478f54955bea6b2965e97ae621037d0346b87 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Wed, 25 Nov 2020 14:10:33 +0530 Subject: [PATCH 127/209] add hashtable separate chaining --- hashtable/separate_chaining.py | 52 ++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 hashtable/separate_chaining.py diff --git a/hashtable/separate_chaining.py b/hashtable/separate_chaining.py new file mode 100644 index 0000000..64e745c --- /dev/null +++ b/hashtable/separate_chaining.py @@ -0,0 +1,52 @@ +class HashTable: + def __init__(self): + self.max = 10 + self.arr = [[] for _ in range(self.max)] + + def get_hash(self, key): + hash_value = 0 + for char in key: + hash_value += ord(char) + return hash_value % self.max + + def __getitem__(self, key): + hash_value = self.get_hash(key) + for element in self.arr[hash_value]: + if element in self.arr[hash_value]: + if element[0] == key: + return element[1] + + def __setitem__(self, key, value): + hash_value = self.get_hash(key) + for index, element in enumerate(self.arr[hash_value]): + if element and element[0] == key: + self.arr[hash_value][index] = (key, value) + return + + self.arr[hash_value].append((key, value)) + + def __delitem__(self, key): + hash_value = self.get_hash(key) + for index, element in enumerate(self.arr[hash_value]): + if element[0] == key: + del self.arr[hash_value][index] + + +def main(): + """ operational function """ + table = HashTable() + table["march 6"] = 120 + table["march 6"] = 78 + table["march 8"] = 67 + table["march 9"] = 4 + table["march 17"] = 459 + + print(table["march 6"]) # 78 + print(table["march 17"]) # 459 + + del table["march 17"] + print(table["march 17"]) # None + + +if __name__ == "__main__": + main() From a6a6d839b3ba5968f16a883e638e486903630eae Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Fri, 27 Nov 2020 12:35:23 +0530 Subject: [PATCH 128/209] add circular linked list --- linked_list/library/circular_linked_list.py | 118 ++++++++++++++++++++ 1 file changed, 118 insertions(+) create mode 100644 linked_list/library/circular_linked_list.py diff --git a/linked_list/library/circular_linked_list.py b/linked_list/library/circular_linked_list.py new file mode 100644 index 0000000..5ba416c --- /dev/null +++ b/linked_list/library/circular_linked_list.py @@ -0,0 +1,118 @@ +""" Implementation of Circular Linked List Data Structure + Circular linked list is a linked list where all nodes are connected to + form a circle. There is no NULL at the end. A circular linked list can + be a singly circular linked list or doubly circular linked list. +""" + +class Node: + """ Node class contains everything related to Linked List node """ + def __init__(self, data): + """ initializing single node with data """ + self.data = data + self.next = None + + +class CircularLinkedList: + """ Circular linked list is a linked list where all nodes are connected + to form a circle. + """ + def __init__(self): + """ initializing circular linked list with zero node """ + self.head = None + + def __len__(self): + """ get number of nodes currently present in circular linked list """ + if self.head is None: + return 0 + + current = self.head + count = 1 + while current.next is not self.head: + count += 1 + current = current.next + return count + + def insert_head(self, data): + """ inserts node at the start of linked list """ + if self.head is None: + self.head = Node(data) + self.head.next = self.head + return + + new_node = Node(data) + current = self.head + while current.next is not self.head: + current = current.next + current.next = new_node + new_node.next = self.head + self.head = new_node + + def insert_tail(self, data): + """ inserts node at the end of linked list """ + if self.head is None: + self.head = Node(data) + self.head.next = self.head + return + + new_node = Node(data) + current = self.head + while current.next is not self.head: + current = current.next + current.next = new_node + new_node.next = self.head + + def remove(self, key): + """ remove data key from circular linked list """ + if self.head.data == key: + previous = self.head + while previous.next is not self.head: + previous = previous.next + previous.next = self.head.next + self.head = previous.next + return + + current = self.head.next + previous = self.head + while current is not self.head: + if current.data == key: + break + previous = current + current = current.next + previous.next = current.next + + def print(self): + """ prints entire linked list without changing underlying data """ + current = self.head + while current is not None: + print(" ->", current.data, end="") + current = current.next + if current == self.head: + break + print(end=" -> ...") + print() + + +def main(): + """ operational function """ + cll = CircularLinkedList() + cll.insert_tail('C') + cll.print() + cll.insert_tail('D') + cll.print() + cll.insert_head('B') + cll.print() + cll.insert_head('A') + cll.print() + print("size:", len(cll)) + + cll.remove('B') + cll.print() + print("size:", len(cll)) + + cll.remove('A') + cll.print() + print("size:", len(cll)) + + +if __name__ == '__main__': + main() From 4eab382cec9e88e57274f4e068b63d692e843f1f Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sat, 28 Nov 2020 00:19:16 +0530 Subject: [PATCH 129/209] rename folders --- {other_languages/c => c_language}/README.md | 0 .../c => c_language}/dynamic_connectivity/quick_find/Makefile | 0 .../c => c_language}/dynamic_connectivity/quick_find/main.c | 0 .../c => c_language}/dynamic_connectivity/quick_find/quick_find.c | 0 .../c => c_language}/dynamic_connectivity/quick_find/quick_find.h | 0 .../c => c_language}/dynamic_connectivity/quick_union/Makefile | 0 .../c => c_language}/dynamic_connectivity/quick_union/main.c | 0 .../dynamic_connectivity/quick_union/quick_union.c | 0 .../dynamic_connectivity/quick_union/quick_union.h | 0 {other_languages/c => c_language}/queue/Makefile | 0 {other_languages/c => c_language}/queue/main.c | 0 {other_languages/c => c_language}/queue/queue.c | 0 {other_languages/c => c_language}/queue/queue.h | 0 {other_languages/c => c_language}/shuffling/Makefile | 0 {other_languages/c => c_language}/shuffling/shuffle_array.c | 0 {other_languages/c => c_language}/sorts/bubble_sort/Makefile | 0 {other_languages/c => c_language}/sorts/bubble_sort/bubble_sort.c | 0 {other_languages/c => c_language}/sorts/generic/Makefile | 0 {other_languages/c => c_language}/sorts/generic/README.md | 0 {other_languages/c => c_language}/sorts/generic/main.c | 0 {other_languages/c => c_language}/sorts/generic/sort.c | 0 {other_languages/c => c_language}/sorts/generic/sort.h | 0 {other_languages/c => c_language}/sorts/insertion_sort/Makefile | 0 .../c => c_language}/sorts/insertion_sort/insertion_sort.c | 0 {other_languages/c => c_language}/sorts/merge_sort/Makefile | 0 {other_languages/c => c_language}/sorts/merge_sort/merge_sort.c | 0 {other_languages/c => c_language}/sorts/quick_sort/Makefile | 0 {other_languages/c => c_language}/sorts/quick_sort/quick_sort.c | 0 {other_languages/c => c_language}/sorts/selection_sort/Makefile | 0 .../c => c_language}/sorts/selection_sort/selection_sort.c | 0 {other_languages/c => c_language}/sorts/shell_sort/Makefile | 0 {other_languages/c => c_language}/sorts/shell_sort/shell_sort.c | 0 .../c => c_language}/stack/array_implementation/Makefile | 0 .../c => c_language}/stack/array_implementation/main.c | 0 .../c => c_language}/stack/array_implementation/stack.c | 0 .../c => c_language}/stack/array_implementation/stack.h | 0 .../c => c_language}/stack/generic_array_implementation/Makefile | 0 .../c => c_language}/stack/generic_array_implementation/main.c | 0 .../c => c_language}/stack/generic_array_implementation/stack.c | 0 .../c => c_language}/stack/generic_array_implementation/stack.h | 0 {other_languages/cpp => cpp}/BinarySearchTree/BST/BST.cpp | 0 {other_languages/cpp => cpp}/BinarySearchTree/BST/BST.hpp | 0 {other_languages/cpp => cpp}/BinarySearchTree/BST/Makefile | 0 {other_languages/cpp => cpp}/BinarySearchTree/BST/test_BST.cpp | 0 {other_languages/cpp => cpp}/BinarySearchTree/Nqueen | 0 {other_languages/cpp => cpp}/BinarySearchTree/bfsTraversal.cpp | 0 {other_languages/cpp => cpp}/BinarySearchTree/dfsTraversal.cpp | 0 .../cpp => cpp}/BinarySearchTree/inorderSuccessor.cpp | 0 {other_languages/cpp => cpp}/BinarySearchTree/isBST.cpp | 0 {other_languages/cpp => cpp}/DynamicConnectivity/QuickFind.cpp | 0 {other_languages/cpp => cpp}/DynamicConnectivity/QuickUnion.cpp | 0 .../cpp => cpp}/DynamicConnectivity/WeightedQuickUnion.cpp | 0 {other_languages/cpp => cpp}/Heap/Heap/HeapException.hpp | 0 {other_languages/cpp => cpp}/Heap/Heap/Makefile | 0 {other_languages/cpp => cpp}/Heap/Heap/MaxHeap.hpp | 0 {other_languages/cpp => cpp}/Heap/Heap/MinHeap.hpp | 0 {other_languages/cpp => cpp}/Heap/Heap/test_Heap.cpp | 0 {other_languages/cpp => cpp}/LinkedList/LinkedList/LinkedList.hpp | 0 {other_languages/cpp => cpp}/LinkedList/LinkedList/Makefile | 0 .../cpp => cpp}/LinkedList/LinkedList/test_LinkedList.cpp | 0 {other_languages/cpp => cpp}/LinkedList/countFrequency.cpp | 0 {other_languages/cpp => cpp}/LinkedList/detectLoop.cpp | 0 {other_languages/cpp => cpp}/LinkedList/findMiddle.cpp | 0 {other_languages/cpp => cpp}/LinkedList/getNthNodeFromEnd.cpp | 0 {other_languages/cpp => cpp}/LinkedList/lengthOfLoop.cpp | 0 {other_languages/cpp => cpp}/Queue/Queue/Makefile | 0 {other_languages/cpp => cpp}/Queue/Queue/Queue.hpp | 0 {other_languages/cpp => cpp}/Queue/Queue/test_Queue.cpp | 0 {other_languages/cpp => cpp}/Queue/ReverseQueue.cpp | 0 {other_languages/cpp => cpp}/Queue/SortQueueWithoutExtraSpace.cpp | 0 {other_languages/cpp => cpp}/RedBlackTree/Makefile | 0 {other_languages/cpp => cpp}/RedBlackTree/RedBlackTree.cpp | 0 {other_languages/cpp => cpp}/RedBlackTree/RedBlackTree.hpp | 0 {other_languages/cpp => cpp}/RedBlackTree/find.cpp | 0 {other_languages/cpp => cpp}/RedBlackTree/insert.cpp | 0 {other_languages/cpp => cpp}/RedBlackTree/test_RedBlackTree.cpp | 0 {other_languages/cpp => cpp}/RedBlackTree/utils.cpp | 0 {other_languages/cpp => cpp}/Search/BinarySearch.h | 0 {other_languages/cpp => cpp}/Search/Makefile | 0 {other_languages/cpp => cpp}/Search/test_BinarySearch.cpp | 0 {other_languages/cpp => cpp}/Shuffle/Shuffle.cpp | 0 {other_languages/cpp => cpp}/Sort/BubbleSort.cpp | 0 {other_languages/cpp => cpp}/Sort/CountingSort.cpp | 0 {other_languages/cpp => cpp}/Sort/GnomeSort.cpp | 0 {other_languages/cpp => cpp}/Sort/HeapSort.cpp | 0 {other_languages/cpp => cpp}/Sort/InsertionSort.cpp | 0 {other_languages/cpp => cpp}/Sort/MergeBottomUp.cpp | 0 {other_languages/cpp => cpp}/Sort/MergeOptimizeSort.cpp | 0 {other_languages/cpp => cpp}/Sort/MergeSort.cpp | 0 {other_languages/cpp => cpp}/Sort/OddEvenSort.cpp | 0 {other_languages/cpp => cpp}/Sort/Quick3WaySort.cpp | 0 {other_languages/cpp => cpp}/Sort/QuickOptimizeSort.cpp | 0 {other_languages/cpp => cpp}/Sort/QuickSelect.cpp | 0 {other_languages/cpp => cpp}/Sort/QuickSort.cpp | 0 {other_languages/cpp => cpp}/Sort/SelectionSort.cpp | 0 {other_languages/cpp => cpp}/Sort/ShellSort.cpp | 0 {other_languages/cpp => cpp}/Stack/Stack/Makefile | 0 {other_languages/cpp => cpp}/Stack/Stack/Stack.hpp | 0 {other_languages/cpp => cpp}/Stack/Stack/test_Stack.cpp | 0 {other_languages/cpp => cpp}/Stack/balancedParanthesis.cpp | 0 {other_languages/cpp => cpp}/Stack/bracketReversals.cpp | 0 {other_languages/cpp => cpp}/Stack/deleteMiddleElement.cpp | 0 {other_languages/cpp => cpp}/Stack/infixToPostfix.cpp | 0 {other_languages/cpp => cpp}/Stack/trackingCurrentMax.cpp | 0 {other_languages/go => golang}/README.md | 0 {other_languages/go => golang}/bst/bst.go | 0 {other_languages/go => golang}/bst/bst_test.go | 0 {other_languages/go => golang}/bst/checkbst.go | 0 {other_languages/go => golang}/bst/delete.go | 0 {other_languages/go => golang}/bst/find.go | 0 {other_languages/go => golang}/bst/height.go | 0 {other_languages/go => golang}/bst/insert.go | 0 {other_languages/go => golang}/bst/traversal.go | 0 .../go => golang}/doublylinkedlist/doublylinkedlist.go | 0 .../go => golang}/doublylinkedlist/doublylinkedlist_test.go | 0 {other_languages/go => golang}/hashtable/hashtable.go | 0 {other_languages/go => golang}/hashtable/hashtable_test.go | 0 {other_languages/go => golang}/heap/doc.go | 0 {other_languages/go => golang}/heap/maxheap/maxheap.go | 0 {other_languages/go => golang}/heap/maxheap/maxheap_test.go | 0 {other_languages/go => golang}/heap/minheap/minheap.go | 0 {other_languages/go => golang}/heap/minheap/minheap_test.go | 0 {other_languages/go => golang}/linkedlist/linkedlist.go | 0 {other_languages/go => golang}/linkedlist/linkedlist_test.go | 0 {other_languages/go => golang}/queue/queue.go | 0 {other_languages/go => golang}/queue/queue_test.go | 0 {other_languages/go => golang}/redblacktree/doc.go | 0 {other_languages/go => golang}/redblacktree/find.go | 0 {other_languages/go => golang}/redblacktree/insert.go | 0 {other_languages/go => golang}/redblacktree/redblacktree.go | 0 {other_languages/go => golang}/redblacktree/redblacktree_test.go | 0 {other_languages/go => golang}/redblacktree/utils.go | 0 {other_languages/go => golang}/search/binarysearch.go | 0 {other_languages/go => golang}/search/binarysearch_test.go | 0 {other_languages/go => golang}/set/set.go | 0 {other_languages/go => golang}/set/set_test.go | 0 {other_languages/go => golang}/shuffle/shuffle.go | 0 {other_languages/go => golang}/sort/bubble.go | 0 {other_languages/go => golang}/sort/countingSort.go | 0 {other_languages/go => golang}/sort/gnome.go | 0 {other_languages/go => golang}/sort/heap.go | 0 {other_languages/go => golang}/sort/insertion.go | 0 {other_languages/go => golang}/sort/merge.go | 0 {other_languages/go => golang}/sort/oddeven.go | 0 {other_languages/go => golang}/sort/quick.go | 0 {other_languages/go => golang}/sort/quickselect.go | 0 {other_languages/go => golang}/sort/selection.go | 0 {other_languages/go => golang}/sort/shell.go | 0 {other_languages/go => golang}/sort/sort.go | 0 {other_languages/go => golang}/sort/sort_test.go | 0 {other_languages/go => golang}/stack/applications/applications.go | 0 .../go => golang}/stack/applications/applications_test.go | 0 .../go => golang}/stack/applications/infixevaluation.go | 0 .../go => golang}/stack/applications/infixtopostfix.go | 0 .../go => golang}/stack/applications/infixtoprefix.go | 0 {other_languages/go => golang}/stack/applications/utils.go | 0 {other_languages/go => golang}/stack/stack.go | 0 {other_languages/go => golang}/stack/stack_test.go | 0 {other_languages/go => golang}/trie/trie.go | 0 {other_languages/go => golang}/trie/trie_test.go | 0 160 files changed, 0 insertions(+), 0 deletions(-) rename {other_languages/c => c_language}/README.md (100%) rename {other_languages/c => c_language}/dynamic_connectivity/quick_find/Makefile (100%) rename {other_languages/c => c_language}/dynamic_connectivity/quick_find/main.c (100%) rename {other_languages/c => c_language}/dynamic_connectivity/quick_find/quick_find.c (100%) rename {other_languages/c => c_language}/dynamic_connectivity/quick_find/quick_find.h (100%) rename {other_languages/c => c_language}/dynamic_connectivity/quick_union/Makefile (100%) rename {other_languages/c => c_language}/dynamic_connectivity/quick_union/main.c (100%) rename {other_languages/c => c_language}/dynamic_connectivity/quick_union/quick_union.c (100%) rename {other_languages/c => c_language}/dynamic_connectivity/quick_union/quick_union.h (100%) rename {other_languages/c => c_language}/queue/Makefile (100%) rename {other_languages/c => c_language}/queue/main.c (100%) rename {other_languages/c => c_language}/queue/queue.c (100%) rename {other_languages/c => c_language}/queue/queue.h (100%) rename {other_languages/c => c_language}/shuffling/Makefile (100%) rename {other_languages/c => c_language}/shuffling/shuffle_array.c (100%) rename {other_languages/c => c_language}/sorts/bubble_sort/Makefile (100%) rename {other_languages/c => c_language}/sorts/bubble_sort/bubble_sort.c (100%) rename {other_languages/c => c_language}/sorts/generic/Makefile (100%) rename {other_languages/c => c_language}/sorts/generic/README.md (100%) rename {other_languages/c => c_language}/sorts/generic/main.c (100%) rename {other_languages/c => c_language}/sorts/generic/sort.c (100%) rename {other_languages/c => c_language}/sorts/generic/sort.h (100%) rename {other_languages/c => c_language}/sorts/insertion_sort/Makefile (100%) rename {other_languages/c => c_language}/sorts/insertion_sort/insertion_sort.c (100%) rename {other_languages/c => c_language}/sorts/merge_sort/Makefile (100%) rename {other_languages/c => c_language}/sorts/merge_sort/merge_sort.c (100%) rename {other_languages/c => c_language}/sorts/quick_sort/Makefile (100%) rename {other_languages/c => c_language}/sorts/quick_sort/quick_sort.c (100%) rename {other_languages/c => c_language}/sorts/selection_sort/Makefile (100%) rename {other_languages/c => c_language}/sorts/selection_sort/selection_sort.c (100%) rename {other_languages/c => c_language}/sorts/shell_sort/Makefile (100%) rename {other_languages/c => c_language}/sorts/shell_sort/shell_sort.c (100%) rename {other_languages/c => c_language}/stack/array_implementation/Makefile (100%) rename {other_languages/c => c_language}/stack/array_implementation/main.c (100%) rename {other_languages/c => c_language}/stack/array_implementation/stack.c (100%) rename {other_languages/c => c_language}/stack/array_implementation/stack.h (100%) rename {other_languages/c => c_language}/stack/generic_array_implementation/Makefile (100%) rename {other_languages/c => c_language}/stack/generic_array_implementation/main.c (100%) rename {other_languages/c => c_language}/stack/generic_array_implementation/stack.c (100%) rename {other_languages/c => c_language}/stack/generic_array_implementation/stack.h (100%) rename {other_languages/cpp => cpp}/BinarySearchTree/BST/BST.cpp (100%) rename {other_languages/cpp => cpp}/BinarySearchTree/BST/BST.hpp (100%) rename {other_languages/cpp => cpp}/BinarySearchTree/BST/Makefile (100%) rename {other_languages/cpp => cpp}/BinarySearchTree/BST/test_BST.cpp (100%) rename {other_languages/cpp => cpp}/BinarySearchTree/Nqueen (100%) rename {other_languages/cpp => cpp}/BinarySearchTree/bfsTraversal.cpp (100%) rename {other_languages/cpp => cpp}/BinarySearchTree/dfsTraversal.cpp (100%) rename {other_languages/cpp => cpp}/BinarySearchTree/inorderSuccessor.cpp (100%) rename {other_languages/cpp => cpp}/BinarySearchTree/isBST.cpp (100%) rename {other_languages/cpp => cpp}/DynamicConnectivity/QuickFind.cpp (100%) rename {other_languages/cpp => cpp}/DynamicConnectivity/QuickUnion.cpp (100%) rename {other_languages/cpp => cpp}/DynamicConnectivity/WeightedQuickUnion.cpp (100%) rename {other_languages/cpp => cpp}/Heap/Heap/HeapException.hpp (100%) rename {other_languages/cpp => cpp}/Heap/Heap/Makefile (100%) rename {other_languages/cpp => cpp}/Heap/Heap/MaxHeap.hpp (100%) rename {other_languages/cpp => cpp}/Heap/Heap/MinHeap.hpp (100%) rename {other_languages/cpp => cpp}/Heap/Heap/test_Heap.cpp (100%) rename {other_languages/cpp => cpp}/LinkedList/LinkedList/LinkedList.hpp (100%) rename {other_languages/cpp => cpp}/LinkedList/LinkedList/Makefile (100%) rename {other_languages/cpp => cpp}/LinkedList/LinkedList/test_LinkedList.cpp (100%) rename {other_languages/cpp => cpp}/LinkedList/countFrequency.cpp (100%) rename {other_languages/cpp => cpp}/LinkedList/detectLoop.cpp (100%) rename {other_languages/cpp => cpp}/LinkedList/findMiddle.cpp (100%) rename {other_languages/cpp => cpp}/LinkedList/getNthNodeFromEnd.cpp (100%) rename {other_languages/cpp => cpp}/LinkedList/lengthOfLoop.cpp (100%) rename {other_languages/cpp => cpp}/Queue/Queue/Makefile (100%) rename {other_languages/cpp => cpp}/Queue/Queue/Queue.hpp (100%) rename {other_languages/cpp => cpp}/Queue/Queue/test_Queue.cpp (100%) rename {other_languages/cpp => cpp}/Queue/ReverseQueue.cpp (100%) rename {other_languages/cpp => cpp}/Queue/SortQueueWithoutExtraSpace.cpp (100%) rename {other_languages/cpp => cpp}/RedBlackTree/Makefile (100%) rename {other_languages/cpp => cpp}/RedBlackTree/RedBlackTree.cpp (100%) rename {other_languages/cpp => cpp}/RedBlackTree/RedBlackTree.hpp (100%) rename {other_languages/cpp => cpp}/RedBlackTree/find.cpp (100%) rename {other_languages/cpp => cpp}/RedBlackTree/insert.cpp (100%) rename {other_languages/cpp => cpp}/RedBlackTree/test_RedBlackTree.cpp (100%) rename {other_languages/cpp => cpp}/RedBlackTree/utils.cpp (100%) rename {other_languages/cpp => cpp}/Search/BinarySearch.h (100%) rename {other_languages/cpp => cpp}/Search/Makefile (100%) rename {other_languages/cpp => cpp}/Search/test_BinarySearch.cpp (100%) rename {other_languages/cpp => cpp}/Shuffle/Shuffle.cpp (100%) rename {other_languages/cpp => cpp}/Sort/BubbleSort.cpp (100%) rename {other_languages/cpp => cpp}/Sort/CountingSort.cpp (100%) rename {other_languages/cpp => cpp}/Sort/GnomeSort.cpp (100%) rename {other_languages/cpp => cpp}/Sort/HeapSort.cpp (100%) rename {other_languages/cpp => cpp}/Sort/InsertionSort.cpp (100%) rename {other_languages/cpp => cpp}/Sort/MergeBottomUp.cpp (100%) rename {other_languages/cpp => cpp}/Sort/MergeOptimizeSort.cpp (100%) rename {other_languages/cpp => cpp}/Sort/MergeSort.cpp (100%) rename {other_languages/cpp => cpp}/Sort/OddEvenSort.cpp (100%) rename {other_languages/cpp => cpp}/Sort/Quick3WaySort.cpp (100%) rename {other_languages/cpp => cpp}/Sort/QuickOptimizeSort.cpp (100%) rename {other_languages/cpp => cpp}/Sort/QuickSelect.cpp (100%) rename {other_languages/cpp => cpp}/Sort/QuickSort.cpp (100%) rename {other_languages/cpp => cpp}/Sort/SelectionSort.cpp (100%) rename {other_languages/cpp => cpp}/Sort/ShellSort.cpp (100%) rename {other_languages/cpp => cpp}/Stack/Stack/Makefile (100%) rename {other_languages/cpp => cpp}/Stack/Stack/Stack.hpp (100%) rename {other_languages/cpp => cpp}/Stack/Stack/test_Stack.cpp (100%) rename {other_languages/cpp => cpp}/Stack/balancedParanthesis.cpp (100%) rename {other_languages/cpp => cpp}/Stack/bracketReversals.cpp (100%) rename {other_languages/cpp => cpp}/Stack/deleteMiddleElement.cpp (100%) rename {other_languages/cpp => cpp}/Stack/infixToPostfix.cpp (100%) rename {other_languages/cpp => cpp}/Stack/trackingCurrentMax.cpp (100%) rename {other_languages/go => golang}/README.md (100%) rename {other_languages/go => golang}/bst/bst.go (100%) rename {other_languages/go => golang}/bst/bst_test.go (100%) rename {other_languages/go => golang}/bst/checkbst.go (100%) rename {other_languages/go => golang}/bst/delete.go (100%) rename {other_languages/go => golang}/bst/find.go (100%) rename {other_languages/go => golang}/bst/height.go (100%) rename {other_languages/go => golang}/bst/insert.go (100%) rename {other_languages/go => golang}/bst/traversal.go (100%) rename {other_languages/go => golang}/doublylinkedlist/doublylinkedlist.go (100%) rename {other_languages/go => golang}/doublylinkedlist/doublylinkedlist_test.go (100%) rename {other_languages/go => golang}/hashtable/hashtable.go (100%) rename {other_languages/go => golang}/hashtable/hashtable_test.go (100%) rename {other_languages/go => golang}/heap/doc.go (100%) rename {other_languages/go => golang}/heap/maxheap/maxheap.go (100%) rename {other_languages/go => golang}/heap/maxheap/maxheap_test.go (100%) rename {other_languages/go => golang}/heap/minheap/minheap.go (100%) rename {other_languages/go => golang}/heap/minheap/minheap_test.go (100%) rename {other_languages/go => golang}/linkedlist/linkedlist.go (100%) rename {other_languages/go => golang}/linkedlist/linkedlist_test.go (100%) rename {other_languages/go => golang}/queue/queue.go (100%) rename {other_languages/go => golang}/queue/queue_test.go (100%) rename {other_languages/go => golang}/redblacktree/doc.go (100%) rename {other_languages/go => golang}/redblacktree/find.go (100%) rename {other_languages/go => golang}/redblacktree/insert.go (100%) rename {other_languages/go => golang}/redblacktree/redblacktree.go (100%) rename {other_languages/go => golang}/redblacktree/redblacktree_test.go (100%) rename {other_languages/go => golang}/redblacktree/utils.go (100%) rename {other_languages/go => golang}/search/binarysearch.go (100%) rename {other_languages/go => golang}/search/binarysearch_test.go (100%) rename {other_languages/go => golang}/set/set.go (100%) rename {other_languages/go => golang}/set/set_test.go (100%) rename {other_languages/go => golang}/shuffle/shuffle.go (100%) rename {other_languages/go => golang}/sort/bubble.go (100%) rename {other_languages/go => golang}/sort/countingSort.go (100%) rename {other_languages/go => golang}/sort/gnome.go (100%) rename {other_languages/go => golang}/sort/heap.go (100%) rename {other_languages/go => golang}/sort/insertion.go (100%) rename {other_languages/go => golang}/sort/merge.go (100%) rename {other_languages/go => golang}/sort/oddeven.go (100%) rename {other_languages/go => golang}/sort/quick.go (100%) rename {other_languages/go => golang}/sort/quickselect.go (100%) rename {other_languages/go => golang}/sort/selection.go (100%) rename {other_languages/go => golang}/sort/shell.go (100%) rename {other_languages/go => golang}/sort/sort.go (100%) rename {other_languages/go => golang}/sort/sort_test.go (100%) rename {other_languages/go => golang}/stack/applications/applications.go (100%) rename {other_languages/go => golang}/stack/applications/applications_test.go (100%) rename {other_languages/go => golang}/stack/applications/infixevaluation.go (100%) rename {other_languages/go => golang}/stack/applications/infixtopostfix.go (100%) rename {other_languages/go => golang}/stack/applications/infixtoprefix.go (100%) rename {other_languages/go => golang}/stack/applications/utils.go (100%) rename {other_languages/go => golang}/stack/stack.go (100%) rename {other_languages/go => golang}/stack/stack_test.go (100%) rename {other_languages/go => golang}/trie/trie.go (100%) rename {other_languages/go => golang}/trie/trie_test.go (100%) diff --git a/other_languages/c/README.md b/c_language/README.md similarity index 100% rename from other_languages/c/README.md rename to c_language/README.md diff --git a/other_languages/c/dynamic_connectivity/quick_find/Makefile b/c_language/dynamic_connectivity/quick_find/Makefile similarity index 100% rename from other_languages/c/dynamic_connectivity/quick_find/Makefile rename to c_language/dynamic_connectivity/quick_find/Makefile diff --git a/other_languages/c/dynamic_connectivity/quick_find/main.c b/c_language/dynamic_connectivity/quick_find/main.c similarity index 100% rename from other_languages/c/dynamic_connectivity/quick_find/main.c rename to c_language/dynamic_connectivity/quick_find/main.c diff --git a/other_languages/c/dynamic_connectivity/quick_find/quick_find.c b/c_language/dynamic_connectivity/quick_find/quick_find.c similarity index 100% rename from other_languages/c/dynamic_connectivity/quick_find/quick_find.c rename to c_language/dynamic_connectivity/quick_find/quick_find.c diff --git a/other_languages/c/dynamic_connectivity/quick_find/quick_find.h b/c_language/dynamic_connectivity/quick_find/quick_find.h similarity index 100% rename from other_languages/c/dynamic_connectivity/quick_find/quick_find.h rename to c_language/dynamic_connectivity/quick_find/quick_find.h diff --git a/other_languages/c/dynamic_connectivity/quick_union/Makefile b/c_language/dynamic_connectivity/quick_union/Makefile similarity index 100% rename from other_languages/c/dynamic_connectivity/quick_union/Makefile rename to c_language/dynamic_connectivity/quick_union/Makefile diff --git a/other_languages/c/dynamic_connectivity/quick_union/main.c b/c_language/dynamic_connectivity/quick_union/main.c similarity index 100% rename from other_languages/c/dynamic_connectivity/quick_union/main.c rename to c_language/dynamic_connectivity/quick_union/main.c diff --git a/other_languages/c/dynamic_connectivity/quick_union/quick_union.c b/c_language/dynamic_connectivity/quick_union/quick_union.c similarity index 100% rename from other_languages/c/dynamic_connectivity/quick_union/quick_union.c rename to c_language/dynamic_connectivity/quick_union/quick_union.c diff --git a/other_languages/c/dynamic_connectivity/quick_union/quick_union.h b/c_language/dynamic_connectivity/quick_union/quick_union.h similarity index 100% rename from other_languages/c/dynamic_connectivity/quick_union/quick_union.h rename to c_language/dynamic_connectivity/quick_union/quick_union.h diff --git a/other_languages/c/queue/Makefile b/c_language/queue/Makefile similarity index 100% rename from other_languages/c/queue/Makefile rename to c_language/queue/Makefile diff --git a/other_languages/c/queue/main.c b/c_language/queue/main.c similarity index 100% rename from other_languages/c/queue/main.c rename to c_language/queue/main.c diff --git a/other_languages/c/queue/queue.c b/c_language/queue/queue.c similarity index 100% rename from other_languages/c/queue/queue.c rename to c_language/queue/queue.c diff --git a/other_languages/c/queue/queue.h b/c_language/queue/queue.h similarity index 100% rename from other_languages/c/queue/queue.h rename to c_language/queue/queue.h diff --git a/other_languages/c/shuffling/Makefile b/c_language/shuffling/Makefile similarity index 100% rename from other_languages/c/shuffling/Makefile rename to c_language/shuffling/Makefile diff --git a/other_languages/c/shuffling/shuffle_array.c b/c_language/shuffling/shuffle_array.c similarity index 100% rename from other_languages/c/shuffling/shuffle_array.c rename to c_language/shuffling/shuffle_array.c diff --git a/other_languages/c/sorts/bubble_sort/Makefile b/c_language/sorts/bubble_sort/Makefile similarity index 100% rename from other_languages/c/sorts/bubble_sort/Makefile rename to c_language/sorts/bubble_sort/Makefile diff --git a/other_languages/c/sorts/bubble_sort/bubble_sort.c b/c_language/sorts/bubble_sort/bubble_sort.c similarity index 100% rename from other_languages/c/sorts/bubble_sort/bubble_sort.c rename to c_language/sorts/bubble_sort/bubble_sort.c diff --git a/other_languages/c/sorts/generic/Makefile b/c_language/sorts/generic/Makefile similarity index 100% rename from other_languages/c/sorts/generic/Makefile rename to c_language/sorts/generic/Makefile diff --git a/other_languages/c/sorts/generic/README.md b/c_language/sorts/generic/README.md similarity index 100% rename from other_languages/c/sorts/generic/README.md rename to c_language/sorts/generic/README.md diff --git a/other_languages/c/sorts/generic/main.c b/c_language/sorts/generic/main.c similarity index 100% rename from other_languages/c/sorts/generic/main.c rename to c_language/sorts/generic/main.c diff --git a/other_languages/c/sorts/generic/sort.c b/c_language/sorts/generic/sort.c similarity index 100% rename from other_languages/c/sorts/generic/sort.c rename to c_language/sorts/generic/sort.c diff --git a/other_languages/c/sorts/generic/sort.h b/c_language/sorts/generic/sort.h similarity index 100% rename from other_languages/c/sorts/generic/sort.h rename to c_language/sorts/generic/sort.h diff --git a/other_languages/c/sorts/insertion_sort/Makefile b/c_language/sorts/insertion_sort/Makefile similarity index 100% rename from other_languages/c/sorts/insertion_sort/Makefile rename to c_language/sorts/insertion_sort/Makefile diff --git a/other_languages/c/sorts/insertion_sort/insertion_sort.c b/c_language/sorts/insertion_sort/insertion_sort.c similarity index 100% rename from other_languages/c/sorts/insertion_sort/insertion_sort.c rename to c_language/sorts/insertion_sort/insertion_sort.c diff --git a/other_languages/c/sorts/merge_sort/Makefile b/c_language/sorts/merge_sort/Makefile similarity index 100% rename from other_languages/c/sorts/merge_sort/Makefile rename to c_language/sorts/merge_sort/Makefile diff --git a/other_languages/c/sorts/merge_sort/merge_sort.c b/c_language/sorts/merge_sort/merge_sort.c similarity index 100% rename from other_languages/c/sorts/merge_sort/merge_sort.c rename to c_language/sorts/merge_sort/merge_sort.c diff --git a/other_languages/c/sorts/quick_sort/Makefile b/c_language/sorts/quick_sort/Makefile similarity index 100% rename from other_languages/c/sorts/quick_sort/Makefile rename to c_language/sorts/quick_sort/Makefile diff --git a/other_languages/c/sorts/quick_sort/quick_sort.c b/c_language/sorts/quick_sort/quick_sort.c similarity index 100% rename from other_languages/c/sorts/quick_sort/quick_sort.c rename to c_language/sorts/quick_sort/quick_sort.c diff --git a/other_languages/c/sorts/selection_sort/Makefile b/c_language/sorts/selection_sort/Makefile similarity index 100% rename from other_languages/c/sorts/selection_sort/Makefile rename to c_language/sorts/selection_sort/Makefile diff --git a/other_languages/c/sorts/selection_sort/selection_sort.c b/c_language/sorts/selection_sort/selection_sort.c similarity index 100% rename from other_languages/c/sorts/selection_sort/selection_sort.c rename to c_language/sorts/selection_sort/selection_sort.c diff --git a/other_languages/c/sorts/shell_sort/Makefile b/c_language/sorts/shell_sort/Makefile similarity index 100% rename from other_languages/c/sorts/shell_sort/Makefile rename to c_language/sorts/shell_sort/Makefile diff --git a/other_languages/c/sorts/shell_sort/shell_sort.c b/c_language/sorts/shell_sort/shell_sort.c similarity index 100% rename from other_languages/c/sorts/shell_sort/shell_sort.c rename to c_language/sorts/shell_sort/shell_sort.c diff --git a/other_languages/c/stack/array_implementation/Makefile b/c_language/stack/array_implementation/Makefile similarity index 100% rename from other_languages/c/stack/array_implementation/Makefile rename to c_language/stack/array_implementation/Makefile diff --git a/other_languages/c/stack/array_implementation/main.c b/c_language/stack/array_implementation/main.c similarity index 100% rename from other_languages/c/stack/array_implementation/main.c rename to c_language/stack/array_implementation/main.c diff --git a/other_languages/c/stack/array_implementation/stack.c b/c_language/stack/array_implementation/stack.c similarity index 100% rename from other_languages/c/stack/array_implementation/stack.c rename to c_language/stack/array_implementation/stack.c diff --git a/other_languages/c/stack/array_implementation/stack.h b/c_language/stack/array_implementation/stack.h similarity index 100% rename from other_languages/c/stack/array_implementation/stack.h rename to c_language/stack/array_implementation/stack.h diff --git a/other_languages/c/stack/generic_array_implementation/Makefile b/c_language/stack/generic_array_implementation/Makefile similarity index 100% rename from other_languages/c/stack/generic_array_implementation/Makefile rename to c_language/stack/generic_array_implementation/Makefile diff --git a/other_languages/c/stack/generic_array_implementation/main.c b/c_language/stack/generic_array_implementation/main.c similarity index 100% rename from other_languages/c/stack/generic_array_implementation/main.c rename to c_language/stack/generic_array_implementation/main.c diff --git a/other_languages/c/stack/generic_array_implementation/stack.c b/c_language/stack/generic_array_implementation/stack.c similarity index 100% rename from other_languages/c/stack/generic_array_implementation/stack.c rename to c_language/stack/generic_array_implementation/stack.c diff --git a/other_languages/c/stack/generic_array_implementation/stack.h b/c_language/stack/generic_array_implementation/stack.h similarity index 100% rename from other_languages/c/stack/generic_array_implementation/stack.h rename to c_language/stack/generic_array_implementation/stack.h diff --git a/other_languages/cpp/BinarySearchTree/BST/BST.cpp b/cpp/BinarySearchTree/BST/BST.cpp similarity index 100% rename from other_languages/cpp/BinarySearchTree/BST/BST.cpp rename to cpp/BinarySearchTree/BST/BST.cpp diff --git a/other_languages/cpp/BinarySearchTree/BST/BST.hpp b/cpp/BinarySearchTree/BST/BST.hpp similarity index 100% rename from other_languages/cpp/BinarySearchTree/BST/BST.hpp rename to cpp/BinarySearchTree/BST/BST.hpp diff --git a/other_languages/cpp/BinarySearchTree/BST/Makefile b/cpp/BinarySearchTree/BST/Makefile similarity index 100% rename from other_languages/cpp/BinarySearchTree/BST/Makefile rename to cpp/BinarySearchTree/BST/Makefile diff --git a/other_languages/cpp/BinarySearchTree/BST/test_BST.cpp b/cpp/BinarySearchTree/BST/test_BST.cpp similarity index 100% rename from other_languages/cpp/BinarySearchTree/BST/test_BST.cpp rename to cpp/BinarySearchTree/BST/test_BST.cpp diff --git a/other_languages/cpp/BinarySearchTree/Nqueen b/cpp/BinarySearchTree/Nqueen similarity index 100% rename from other_languages/cpp/BinarySearchTree/Nqueen rename to cpp/BinarySearchTree/Nqueen diff --git a/other_languages/cpp/BinarySearchTree/bfsTraversal.cpp b/cpp/BinarySearchTree/bfsTraversal.cpp similarity index 100% rename from other_languages/cpp/BinarySearchTree/bfsTraversal.cpp rename to cpp/BinarySearchTree/bfsTraversal.cpp diff --git a/other_languages/cpp/BinarySearchTree/dfsTraversal.cpp b/cpp/BinarySearchTree/dfsTraversal.cpp similarity index 100% rename from other_languages/cpp/BinarySearchTree/dfsTraversal.cpp rename to cpp/BinarySearchTree/dfsTraversal.cpp diff --git a/other_languages/cpp/BinarySearchTree/inorderSuccessor.cpp b/cpp/BinarySearchTree/inorderSuccessor.cpp similarity index 100% rename from other_languages/cpp/BinarySearchTree/inorderSuccessor.cpp rename to cpp/BinarySearchTree/inorderSuccessor.cpp diff --git a/other_languages/cpp/BinarySearchTree/isBST.cpp b/cpp/BinarySearchTree/isBST.cpp similarity index 100% rename from other_languages/cpp/BinarySearchTree/isBST.cpp rename to cpp/BinarySearchTree/isBST.cpp diff --git a/other_languages/cpp/DynamicConnectivity/QuickFind.cpp b/cpp/DynamicConnectivity/QuickFind.cpp similarity index 100% rename from other_languages/cpp/DynamicConnectivity/QuickFind.cpp rename to cpp/DynamicConnectivity/QuickFind.cpp diff --git a/other_languages/cpp/DynamicConnectivity/QuickUnion.cpp b/cpp/DynamicConnectivity/QuickUnion.cpp similarity index 100% rename from other_languages/cpp/DynamicConnectivity/QuickUnion.cpp rename to cpp/DynamicConnectivity/QuickUnion.cpp diff --git a/other_languages/cpp/DynamicConnectivity/WeightedQuickUnion.cpp b/cpp/DynamicConnectivity/WeightedQuickUnion.cpp similarity index 100% rename from other_languages/cpp/DynamicConnectivity/WeightedQuickUnion.cpp rename to cpp/DynamicConnectivity/WeightedQuickUnion.cpp diff --git a/other_languages/cpp/Heap/Heap/HeapException.hpp b/cpp/Heap/Heap/HeapException.hpp similarity index 100% rename from other_languages/cpp/Heap/Heap/HeapException.hpp rename to cpp/Heap/Heap/HeapException.hpp diff --git a/other_languages/cpp/Heap/Heap/Makefile b/cpp/Heap/Heap/Makefile similarity index 100% rename from other_languages/cpp/Heap/Heap/Makefile rename to cpp/Heap/Heap/Makefile diff --git a/other_languages/cpp/Heap/Heap/MaxHeap.hpp b/cpp/Heap/Heap/MaxHeap.hpp similarity index 100% rename from other_languages/cpp/Heap/Heap/MaxHeap.hpp rename to cpp/Heap/Heap/MaxHeap.hpp diff --git a/other_languages/cpp/Heap/Heap/MinHeap.hpp b/cpp/Heap/Heap/MinHeap.hpp similarity index 100% rename from other_languages/cpp/Heap/Heap/MinHeap.hpp rename to cpp/Heap/Heap/MinHeap.hpp diff --git a/other_languages/cpp/Heap/Heap/test_Heap.cpp b/cpp/Heap/Heap/test_Heap.cpp similarity index 100% rename from other_languages/cpp/Heap/Heap/test_Heap.cpp rename to cpp/Heap/Heap/test_Heap.cpp diff --git a/other_languages/cpp/LinkedList/LinkedList/LinkedList.hpp b/cpp/LinkedList/LinkedList/LinkedList.hpp similarity index 100% rename from other_languages/cpp/LinkedList/LinkedList/LinkedList.hpp rename to cpp/LinkedList/LinkedList/LinkedList.hpp diff --git a/other_languages/cpp/LinkedList/LinkedList/Makefile b/cpp/LinkedList/LinkedList/Makefile similarity index 100% rename from other_languages/cpp/LinkedList/LinkedList/Makefile rename to cpp/LinkedList/LinkedList/Makefile diff --git a/other_languages/cpp/LinkedList/LinkedList/test_LinkedList.cpp b/cpp/LinkedList/LinkedList/test_LinkedList.cpp similarity index 100% rename from other_languages/cpp/LinkedList/LinkedList/test_LinkedList.cpp rename to cpp/LinkedList/LinkedList/test_LinkedList.cpp diff --git a/other_languages/cpp/LinkedList/countFrequency.cpp b/cpp/LinkedList/countFrequency.cpp similarity index 100% rename from other_languages/cpp/LinkedList/countFrequency.cpp rename to cpp/LinkedList/countFrequency.cpp diff --git a/other_languages/cpp/LinkedList/detectLoop.cpp b/cpp/LinkedList/detectLoop.cpp similarity index 100% rename from other_languages/cpp/LinkedList/detectLoop.cpp rename to cpp/LinkedList/detectLoop.cpp diff --git a/other_languages/cpp/LinkedList/findMiddle.cpp b/cpp/LinkedList/findMiddle.cpp similarity index 100% rename from other_languages/cpp/LinkedList/findMiddle.cpp rename to cpp/LinkedList/findMiddle.cpp diff --git a/other_languages/cpp/LinkedList/getNthNodeFromEnd.cpp b/cpp/LinkedList/getNthNodeFromEnd.cpp similarity index 100% rename from other_languages/cpp/LinkedList/getNthNodeFromEnd.cpp rename to cpp/LinkedList/getNthNodeFromEnd.cpp diff --git a/other_languages/cpp/LinkedList/lengthOfLoop.cpp b/cpp/LinkedList/lengthOfLoop.cpp similarity index 100% rename from other_languages/cpp/LinkedList/lengthOfLoop.cpp rename to cpp/LinkedList/lengthOfLoop.cpp diff --git a/other_languages/cpp/Queue/Queue/Makefile b/cpp/Queue/Queue/Makefile similarity index 100% rename from other_languages/cpp/Queue/Queue/Makefile rename to cpp/Queue/Queue/Makefile diff --git a/other_languages/cpp/Queue/Queue/Queue.hpp b/cpp/Queue/Queue/Queue.hpp similarity index 100% rename from other_languages/cpp/Queue/Queue/Queue.hpp rename to cpp/Queue/Queue/Queue.hpp diff --git a/other_languages/cpp/Queue/Queue/test_Queue.cpp b/cpp/Queue/Queue/test_Queue.cpp similarity index 100% rename from other_languages/cpp/Queue/Queue/test_Queue.cpp rename to cpp/Queue/Queue/test_Queue.cpp diff --git a/other_languages/cpp/Queue/ReverseQueue.cpp b/cpp/Queue/ReverseQueue.cpp similarity index 100% rename from other_languages/cpp/Queue/ReverseQueue.cpp rename to cpp/Queue/ReverseQueue.cpp diff --git a/other_languages/cpp/Queue/SortQueueWithoutExtraSpace.cpp b/cpp/Queue/SortQueueWithoutExtraSpace.cpp similarity index 100% rename from other_languages/cpp/Queue/SortQueueWithoutExtraSpace.cpp rename to cpp/Queue/SortQueueWithoutExtraSpace.cpp diff --git a/other_languages/cpp/RedBlackTree/Makefile b/cpp/RedBlackTree/Makefile similarity index 100% rename from other_languages/cpp/RedBlackTree/Makefile rename to cpp/RedBlackTree/Makefile diff --git a/other_languages/cpp/RedBlackTree/RedBlackTree.cpp b/cpp/RedBlackTree/RedBlackTree.cpp similarity index 100% rename from other_languages/cpp/RedBlackTree/RedBlackTree.cpp rename to cpp/RedBlackTree/RedBlackTree.cpp diff --git a/other_languages/cpp/RedBlackTree/RedBlackTree.hpp b/cpp/RedBlackTree/RedBlackTree.hpp similarity index 100% rename from other_languages/cpp/RedBlackTree/RedBlackTree.hpp rename to cpp/RedBlackTree/RedBlackTree.hpp diff --git a/other_languages/cpp/RedBlackTree/find.cpp b/cpp/RedBlackTree/find.cpp similarity index 100% rename from other_languages/cpp/RedBlackTree/find.cpp rename to cpp/RedBlackTree/find.cpp diff --git a/other_languages/cpp/RedBlackTree/insert.cpp b/cpp/RedBlackTree/insert.cpp similarity index 100% rename from other_languages/cpp/RedBlackTree/insert.cpp rename to cpp/RedBlackTree/insert.cpp diff --git a/other_languages/cpp/RedBlackTree/test_RedBlackTree.cpp b/cpp/RedBlackTree/test_RedBlackTree.cpp similarity index 100% rename from other_languages/cpp/RedBlackTree/test_RedBlackTree.cpp rename to cpp/RedBlackTree/test_RedBlackTree.cpp diff --git a/other_languages/cpp/RedBlackTree/utils.cpp b/cpp/RedBlackTree/utils.cpp similarity index 100% rename from other_languages/cpp/RedBlackTree/utils.cpp rename to cpp/RedBlackTree/utils.cpp diff --git a/other_languages/cpp/Search/BinarySearch.h b/cpp/Search/BinarySearch.h similarity index 100% rename from other_languages/cpp/Search/BinarySearch.h rename to cpp/Search/BinarySearch.h diff --git a/other_languages/cpp/Search/Makefile b/cpp/Search/Makefile similarity index 100% rename from other_languages/cpp/Search/Makefile rename to cpp/Search/Makefile diff --git a/other_languages/cpp/Search/test_BinarySearch.cpp b/cpp/Search/test_BinarySearch.cpp similarity index 100% rename from other_languages/cpp/Search/test_BinarySearch.cpp rename to cpp/Search/test_BinarySearch.cpp diff --git a/other_languages/cpp/Shuffle/Shuffle.cpp b/cpp/Shuffle/Shuffle.cpp similarity index 100% rename from other_languages/cpp/Shuffle/Shuffle.cpp rename to cpp/Shuffle/Shuffle.cpp diff --git a/other_languages/cpp/Sort/BubbleSort.cpp b/cpp/Sort/BubbleSort.cpp similarity index 100% rename from other_languages/cpp/Sort/BubbleSort.cpp rename to cpp/Sort/BubbleSort.cpp diff --git a/other_languages/cpp/Sort/CountingSort.cpp b/cpp/Sort/CountingSort.cpp similarity index 100% rename from other_languages/cpp/Sort/CountingSort.cpp rename to cpp/Sort/CountingSort.cpp diff --git a/other_languages/cpp/Sort/GnomeSort.cpp b/cpp/Sort/GnomeSort.cpp similarity index 100% rename from other_languages/cpp/Sort/GnomeSort.cpp rename to cpp/Sort/GnomeSort.cpp diff --git a/other_languages/cpp/Sort/HeapSort.cpp b/cpp/Sort/HeapSort.cpp similarity index 100% rename from other_languages/cpp/Sort/HeapSort.cpp rename to cpp/Sort/HeapSort.cpp diff --git a/other_languages/cpp/Sort/InsertionSort.cpp b/cpp/Sort/InsertionSort.cpp similarity index 100% rename from other_languages/cpp/Sort/InsertionSort.cpp rename to cpp/Sort/InsertionSort.cpp diff --git a/other_languages/cpp/Sort/MergeBottomUp.cpp b/cpp/Sort/MergeBottomUp.cpp similarity index 100% rename from other_languages/cpp/Sort/MergeBottomUp.cpp rename to cpp/Sort/MergeBottomUp.cpp diff --git a/other_languages/cpp/Sort/MergeOptimizeSort.cpp b/cpp/Sort/MergeOptimizeSort.cpp similarity index 100% rename from other_languages/cpp/Sort/MergeOptimizeSort.cpp rename to cpp/Sort/MergeOptimizeSort.cpp diff --git a/other_languages/cpp/Sort/MergeSort.cpp b/cpp/Sort/MergeSort.cpp similarity index 100% rename from other_languages/cpp/Sort/MergeSort.cpp rename to cpp/Sort/MergeSort.cpp diff --git a/other_languages/cpp/Sort/OddEvenSort.cpp b/cpp/Sort/OddEvenSort.cpp similarity index 100% rename from other_languages/cpp/Sort/OddEvenSort.cpp rename to cpp/Sort/OddEvenSort.cpp diff --git a/other_languages/cpp/Sort/Quick3WaySort.cpp b/cpp/Sort/Quick3WaySort.cpp similarity index 100% rename from other_languages/cpp/Sort/Quick3WaySort.cpp rename to cpp/Sort/Quick3WaySort.cpp diff --git a/other_languages/cpp/Sort/QuickOptimizeSort.cpp b/cpp/Sort/QuickOptimizeSort.cpp similarity index 100% rename from other_languages/cpp/Sort/QuickOptimizeSort.cpp rename to cpp/Sort/QuickOptimizeSort.cpp diff --git a/other_languages/cpp/Sort/QuickSelect.cpp b/cpp/Sort/QuickSelect.cpp similarity index 100% rename from other_languages/cpp/Sort/QuickSelect.cpp rename to cpp/Sort/QuickSelect.cpp diff --git a/other_languages/cpp/Sort/QuickSort.cpp b/cpp/Sort/QuickSort.cpp similarity index 100% rename from other_languages/cpp/Sort/QuickSort.cpp rename to cpp/Sort/QuickSort.cpp diff --git a/other_languages/cpp/Sort/SelectionSort.cpp b/cpp/Sort/SelectionSort.cpp similarity index 100% rename from other_languages/cpp/Sort/SelectionSort.cpp rename to cpp/Sort/SelectionSort.cpp diff --git a/other_languages/cpp/Sort/ShellSort.cpp b/cpp/Sort/ShellSort.cpp similarity index 100% rename from other_languages/cpp/Sort/ShellSort.cpp rename to cpp/Sort/ShellSort.cpp diff --git a/other_languages/cpp/Stack/Stack/Makefile b/cpp/Stack/Stack/Makefile similarity index 100% rename from other_languages/cpp/Stack/Stack/Makefile rename to cpp/Stack/Stack/Makefile diff --git a/other_languages/cpp/Stack/Stack/Stack.hpp b/cpp/Stack/Stack/Stack.hpp similarity index 100% rename from other_languages/cpp/Stack/Stack/Stack.hpp rename to cpp/Stack/Stack/Stack.hpp diff --git a/other_languages/cpp/Stack/Stack/test_Stack.cpp b/cpp/Stack/Stack/test_Stack.cpp similarity index 100% rename from other_languages/cpp/Stack/Stack/test_Stack.cpp rename to cpp/Stack/Stack/test_Stack.cpp diff --git a/other_languages/cpp/Stack/balancedParanthesis.cpp b/cpp/Stack/balancedParanthesis.cpp similarity index 100% rename from other_languages/cpp/Stack/balancedParanthesis.cpp rename to cpp/Stack/balancedParanthesis.cpp diff --git a/other_languages/cpp/Stack/bracketReversals.cpp b/cpp/Stack/bracketReversals.cpp similarity index 100% rename from other_languages/cpp/Stack/bracketReversals.cpp rename to cpp/Stack/bracketReversals.cpp diff --git a/other_languages/cpp/Stack/deleteMiddleElement.cpp b/cpp/Stack/deleteMiddleElement.cpp similarity index 100% rename from other_languages/cpp/Stack/deleteMiddleElement.cpp rename to cpp/Stack/deleteMiddleElement.cpp diff --git a/other_languages/cpp/Stack/infixToPostfix.cpp b/cpp/Stack/infixToPostfix.cpp similarity index 100% rename from other_languages/cpp/Stack/infixToPostfix.cpp rename to cpp/Stack/infixToPostfix.cpp diff --git a/other_languages/cpp/Stack/trackingCurrentMax.cpp b/cpp/Stack/trackingCurrentMax.cpp similarity index 100% rename from other_languages/cpp/Stack/trackingCurrentMax.cpp rename to cpp/Stack/trackingCurrentMax.cpp diff --git a/other_languages/go/README.md b/golang/README.md similarity index 100% rename from other_languages/go/README.md rename to golang/README.md diff --git a/other_languages/go/bst/bst.go b/golang/bst/bst.go similarity index 100% rename from other_languages/go/bst/bst.go rename to golang/bst/bst.go diff --git a/other_languages/go/bst/bst_test.go b/golang/bst/bst_test.go similarity index 100% rename from other_languages/go/bst/bst_test.go rename to golang/bst/bst_test.go diff --git a/other_languages/go/bst/checkbst.go b/golang/bst/checkbst.go similarity index 100% rename from other_languages/go/bst/checkbst.go rename to golang/bst/checkbst.go diff --git a/other_languages/go/bst/delete.go b/golang/bst/delete.go similarity index 100% rename from other_languages/go/bst/delete.go rename to golang/bst/delete.go diff --git a/other_languages/go/bst/find.go b/golang/bst/find.go similarity index 100% rename from other_languages/go/bst/find.go rename to golang/bst/find.go diff --git a/other_languages/go/bst/height.go b/golang/bst/height.go similarity index 100% rename from other_languages/go/bst/height.go rename to golang/bst/height.go diff --git a/other_languages/go/bst/insert.go b/golang/bst/insert.go similarity index 100% rename from other_languages/go/bst/insert.go rename to golang/bst/insert.go diff --git a/other_languages/go/bst/traversal.go b/golang/bst/traversal.go similarity index 100% rename from other_languages/go/bst/traversal.go rename to golang/bst/traversal.go diff --git a/other_languages/go/doublylinkedlist/doublylinkedlist.go b/golang/doublylinkedlist/doublylinkedlist.go similarity index 100% rename from other_languages/go/doublylinkedlist/doublylinkedlist.go rename to golang/doublylinkedlist/doublylinkedlist.go diff --git a/other_languages/go/doublylinkedlist/doublylinkedlist_test.go b/golang/doublylinkedlist/doublylinkedlist_test.go similarity index 100% rename from other_languages/go/doublylinkedlist/doublylinkedlist_test.go rename to golang/doublylinkedlist/doublylinkedlist_test.go diff --git a/other_languages/go/hashtable/hashtable.go b/golang/hashtable/hashtable.go similarity index 100% rename from other_languages/go/hashtable/hashtable.go rename to golang/hashtable/hashtable.go diff --git a/other_languages/go/hashtable/hashtable_test.go b/golang/hashtable/hashtable_test.go similarity index 100% rename from other_languages/go/hashtable/hashtable_test.go rename to golang/hashtable/hashtable_test.go diff --git a/other_languages/go/heap/doc.go b/golang/heap/doc.go similarity index 100% rename from other_languages/go/heap/doc.go rename to golang/heap/doc.go diff --git a/other_languages/go/heap/maxheap/maxheap.go b/golang/heap/maxheap/maxheap.go similarity index 100% rename from other_languages/go/heap/maxheap/maxheap.go rename to golang/heap/maxheap/maxheap.go diff --git a/other_languages/go/heap/maxheap/maxheap_test.go b/golang/heap/maxheap/maxheap_test.go similarity index 100% rename from other_languages/go/heap/maxheap/maxheap_test.go rename to golang/heap/maxheap/maxheap_test.go diff --git a/other_languages/go/heap/minheap/minheap.go b/golang/heap/minheap/minheap.go similarity index 100% rename from other_languages/go/heap/minheap/minheap.go rename to golang/heap/minheap/minheap.go diff --git a/other_languages/go/heap/minheap/minheap_test.go b/golang/heap/minheap/minheap_test.go similarity index 100% rename from other_languages/go/heap/minheap/minheap_test.go rename to golang/heap/minheap/minheap_test.go diff --git a/other_languages/go/linkedlist/linkedlist.go b/golang/linkedlist/linkedlist.go similarity index 100% rename from other_languages/go/linkedlist/linkedlist.go rename to golang/linkedlist/linkedlist.go diff --git a/other_languages/go/linkedlist/linkedlist_test.go b/golang/linkedlist/linkedlist_test.go similarity index 100% rename from other_languages/go/linkedlist/linkedlist_test.go rename to golang/linkedlist/linkedlist_test.go diff --git a/other_languages/go/queue/queue.go b/golang/queue/queue.go similarity index 100% rename from other_languages/go/queue/queue.go rename to golang/queue/queue.go diff --git a/other_languages/go/queue/queue_test.go b/golang/queue/queue_test.go similarity index 100% rename from other_languages/go/queue/queue_test.go rename to golang/queue/queue_test.go diff --git a/other_languages/go/redblacktree/doc.go b/golang/redblacktree/doc.go similarity index 100% rename from other_languages/go/redblacktree/doc.go rename to golang/redblacktree/doc.go diff --git a/other_languages/go/redblacktree/find.go b/golang/redblacktree/find.go similarity index 100% rename from other_languages/go/redblacktree/find.go rename to golang/redblacktree/find.go diff --git a/other_languages/go/redblacktree/insert.go b/golang/redblacktree/insert.go similarity index 100% rename from other_languages/go/redblacktree/insert.go rename to golang/redblacktree/insert.go diff --git a/other_languages/go/redblacktree/redblacktree.go b/golang/redblacktree/redblacktree.go similarity index 100% rename from other_languages/go/redblacktree/redblacktree.go rename to golang/redblacktree/redblacktree.go diff --git a/other_languages/go/redblacktree/redblacktree_test.go b/golang/redblacktree/redblacktree_test.go similarity index 100% rename from other_languages/go/redblacktree/redblacktree_test.go rename to golang/redblacktree/redblacktree_test.go diff --git a/other_languages/go/redblacktree/utils.go b/golang/redblacktree/utils.go similarity index 100% rename from other_languages/go/redblacktree/utils.go rename to golang/redblacktree/utils.go diff --git a/other_languages/go/search/binarysearch.go b/golang/search/binarysearch.go similarity index 100% rename from other_languages/go/search/binarysearch.go rename to golang/search/binarysearch.go diff --git a/other_languages/go/search/binarysearch_test.go b/golang/search/binarysearch_test.go similarity index 100% rename from other_languages/go/search/binarysearch_test.go rename to golang/search/binarysearch_test.go diff --git a/other_languages/go/set/set.go b/golang/set/set.go similarity index 100% rename from other_languages/go/set/set.go rename to golang/set/set.go diff --git a/other_languages/go/set/set_test.go b/golang/set/set_test.go similarity index 100% rename from other_languages/go/set/set_test.go rename to golang/set/set_test.go diff --git a/other_languages/go/shuffle/shuffle.go b/golang/shuffle/shuffle.go similarity index 100% rename from other_languages/go/shuffle/shuffle.go rename to golang/shuffle/shuffle.go diff --git a/other_languages/go/sort/bubble.go b/golang/sort/bubble.go similarity index 100% rename from other_languages/go/sort/bubble.go rename to golang/sort/bubble.go diff --git a/other_languages/go/sort/countingSort.go b/golang/sort/countingSort.go similarity index 100% rename from other_languages/go/sort/countingSort.go rename to golang/sort/countingSort.go diff --git a/other_languages/go/sort/gnome.go b/golang/sort/gnome.go similarity index 100% rename from other_languages/go/sort/gnome.go rename to golang/sort/gnome.go diff --git a/other_languages/go/sort/heap.go b/golang/sort/heap.go similarity index 100% rename from other_languages/go/sort/heap.go rename to golang/sort/heap.go diff --git a/other_languages/go/sort/insertion.go b/golang/sort/insertion.go similarity index 100% rename from other_languages/go/sort/insertion.go rename to golang/sort/insertion.go diff --git a/other_languages/go/sort/merge.go b/golang/sort/merge.go similarity index 100% rename from other_languages/go/sort/merge.go rename to golang/sort/merge.go diff --git a/other_languages/go/sort/oddeven.go b/golang/sort/oddeven.go similarity index 100% rename from other_languages/go/sort/oddeven.go rename to golang/sort/oddeven.go diff --git a/other_languages/go/sort/quick.go b/golang/sort/quick.go similarity index 100% rename from other_languages/go/sort/quick.go rename to golang/sort/quick.go diff --git a/other_languages/go/sort/quickselect.go b/golang/sort/quickselect.go similarity index 100% rename from other_languages/go/sort/quickselect.go rename to golang/sort/quickselect.go diff --git a/other_languages/go/sort/selection.go b/golang/sort/selection.go similarity index 100% rename from other_languages/go/sort/selection.go rename to golang/sort/selection.go diff --git a/other_languages/go/sort/shell.go b/golang/sort/shell.go similarity index 100% rename from other_languages/go/sort/shell.go rename to golang/sort/shell.go diff --git a/other_languages/go/sort/sort.go b/golang/sort/sort.go similarity index 100% rename from other_languages/go/sort/sort.go rename to golang/sort/sort.go diff --git a/other_languages/go/sort/sort_test.go b/golang/sort/sort_test.go similarity index 100% rename from other_languages/go/sort/sort_test.go rename to golang/sort/sort_test.go diff --git a/other_languages/go/stack/applications/applications.go b/golang/stack/applications/applications.go similarity index 100% rename from other_languages/go/stack/applications/applications.go rename to golang/stack/applications/applications.go diff --git a/other_languages/go/stack/applications/applications_test.go b/golang/stack/applications/applications_test.go similarity index 100% rename from other_languages/go/stack/applications/applications_test.go rename to golang/stack/applications/applications_test.go diff --git a/other_languages/go/stack/applications/infixevaluation.go b/golang/stack/applications/infixevaluation.go similarity index 100% rename from other_languages/go/stack/applications/infixevaluation.go rename to golang/stack/applications/infixevaluation.go diff --git a/other_languages/go/stack/applications/infixtopostfix.go b/golang/stack/applications/infixtopostfix.go similarity index 100% rename from other_languages/go/stack/applications/infixtopostfix.go rename to golang/stack/applications/infixtopostfix.go diff --git a/other_languages/go/stack/applications/infixtoprefix.go b/golang/stack/applications/infixtoprefix.go similarity index 100% rename from other_languages/go/stack/applications/infixtoprefix.go rename to golang/stack/applications/infixtoprefix.go diff --git a/other_languages/go/stack/applications/utils.go b/golang/stack/applications/utils.go similarity index 100% rename from other_languages/go/stack/applications/utils.go rename to golang/stack/applications/utils.go diff --git a/other_languages/go/stack/stack.go b/golang/stack/stack.go similarity index 100% rename from other_languages/go/stack/stack.go rename to golang/stack/stack.go diff --git a/other_languages/go/stack/stack_test.go b/golang/stack/stack_test.go similarity index 100% rename from other_languages/go/stack/stack_test.go rename to golang/stack/stack_test.go diff --git a/other_languages/go/trie/trie.go b/golang/trie/trie.go similarity index 100% rename from other_languages/go/trie/trie.go rename to golang/trie/trie.go diff --git a/other_languages/go/trie/trie_test.go b/golang/trie/trie_test.go similarity index 100% rename from other_languages/go/trie/trie_test.go rename to golang/trie/trie_test.go From 4aee4f250f335f7fd27fa7b49c753ef210b25d3a Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sat, 28 Nov 2020 01:04:26 +0530 Subject: [PATCH 130/209] modified gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index b1a87fb..db4ede0 100644 --- a/.gitignore +++ b/.gitignore @@ -56,3 +56,4 @@ dkms.conf # google test source code googletest .vscode +venv From 2a316b59ae9ae1a61fb3a36a6cedb61aab1c4bc9 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sun, 29 Nov 2020 19:44:17 +0530 Subject: [PATCH 131/209] add linked list find middle node --- linked_list/find_middle_node.py | 47 +++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 linked_list/find_middle_node.py diff --git a/linked_list/find_middle_node.py b/linked_list/find_middle_node.py new file mode 100644 index 0000000..1b32410 --- /dev/null +++ b/linked_list/find_middle_node.py @@ -0,0 +1,47 @@ +""" Find middle node in linked lists +""" + +class Node: + """ Node class contains everything related to Linked List node """ + def __init__(self, data): + """ initializing single node with data """ + self.data = data + self.next = None + + +class LinkedList: + """ Singly Linked List is a linear data structure """ + def __init__(self): + """ initializing singly linked list with zero node """ + self.head = None + + def insert_head(self, data): + """ inserts node at the start of linked list """ + node = Node(data) + node.next = self.head + self.head = node + + def get_middle_node(self): + """ find middle node in linkedlist using two pointer approach """ + fast_ptr = self.head + slow_ptr = self.head + + while fast_ptr.next is not None and fast_ptr.next.next is not None: + fast_ptr = fast_ptr.next.next + slow_ptr = slow_ptr.next + + return slow_ptr.data + +def main(): + """ operational function """ + linkedlist = LinkedList() + linkedlist.insert_head(10) + linkedlist.insert_head(9) + linkedlist.insert_head(7) + linkedlist.insert_head(5) + linkedlist.insert_head(1) + + print(linkedlist.get_middle_node()) + +if __name__ == '__main__': + main() From c99b973c89fb5cd1f4ad206335d71f7244962b22 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sun, 29 Nov 2020 19:44:41 +0530 Subject: [PATCH 132/209] add linked list is circular --- linked_list/is_circular.py | 126 +++++++++++++++++++++++++++++++++++++ 1 file changed, 126 insertions(+) create mode 100644 linked_list/is_circular.py diff --git a/linked_list/is_circular.py b/linked_list/is_circular.py new file mode 100644 index 0000000..49187c9 --- /dev/null +++ b/linked_list/is_circular.py @@ -0,0 +1,126 @@ +""" Josephus Circle using circular linked list + URL: https://www.geeksforgeeks.org/josephus-circle-using-circular-linked-list/ + + There are n people standing in a circle waiting to be executed. The + counting out begins at some point in the circle and proceeds around the + circle in a fixed direction. In each step, a certain number of people are + skipped and the next person is executed. The elimination proceeds around + the circle (which is becoming smaller and smaller as the executed people + are removed), until only the last person remains, who is given freedom. + Given the total number of persons n and a number m which indicates that + m-1 persons are skipped and m-th person is killed in circle. The task is + to choose the place in the initial circle so that you are the last one + remaining and so survive. + + Example: + Input: Length of circle: n = 4 + Count to choose next: m = 2 + Output : 1 + + Input: n = 5 + m = 3 + Output: 4 +""" + +class Node: + """ Node class contains everything related to Linked List node """ + def __init__(self, data): + """ initializing single node with data """ + self.data = data + self.next = None + + +class LinkedList: + """ Singly Linked List is a linear data structure """ + def __init__(self): + """ initializing singly linked list with zero node """ + self.head = None + + def insert_tail(self, data): + """ inserts node at the end of linked list """ + node = Node(data) + if self.head is None: + self.head = node + else: + current = self.head + while current.next is not None: + current = current.next + current.next = node + + def print(self): + """ prints entire linked list without changing underlying data """ + current = self.head + while current is not None: + print(" ->", current.data, end="") + current = current.next + print() + + +class CircularLinkedList: + """ Circular linked list is a linked list where all nodes are connected + to form a circle. + """ + def __init__(self): + """ initializing circular linked list with zero node """ + self.head = None + + def insert_tail(self, data): + """ inserts node at the end of linked list """ + if self.head is None: + self.head = Node(data) + self.head.next = self.head + return + + new_node = Node(data) + current = self.head + while current.next is not self.head: + current = current.next + current.next = new_node + new_node.next = self.head + + def print(self): + """ prints entire linked list without changing underlying data """ + current = self.head + while current is not None: + print(" ->", current.data, end="") + current = current.next + if current == self.head: + break + print(end=" -> ...") + print() + + +def is_circular(llist): + """ returns true if linkedlist is circular, else false """ + if llist.head is None: + return False + + current = llist.head.next + while current is not llist.head: + if current is None: + return False + current = current.next + return True + + +def main(): + """ operational function """ + cll = CircularLinkedList() + cll.insert_tail(1) + cll.insert_tail(2) + cll.insert_tail(3) + cll.insert_tail(4) + cll.print() + print("is circular?", is_circular(cll)) + + ll = LinkedList() + ll.insert_tail(1) + ll.insert_tail(2) + ll.insert_tail(3) + ll.insert_tail(4) + ll.print() + print("is circular?", is_circular(ll)) + + +if __name__ == '__main__': + main() From 606bb581290a353b24f996939876cf7313121831 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Tue, 1 Dec 2020 19:13:12 +0530 Subject: [PATCH 133/209] remove duplicates from singly linked list --- linked_list/remove_duplicates_singly.py | 67 +++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 linked_list/remove_duplicates_singly.py diff --git a/linked_list/remove_duplicates_singly.py b/linked_list/remove_duplicates_singly.py new file mode 100644 index 0000000..0619042 --- /dev/null +++ b/linked_list/remove_duplicates_singly.py @@ -0,0 +1,67 @@ +""" Remove duplicates from linked list + input: 1 -> 6 -> 1 -> 4 -> 2 -> 2 -> 4 + output: 1 -> 6 -> 4 -> 2 +""" + +class Node: + """ Node class contains everything related to Linked List node """ + def __init__(self, data): + """ initializing single node with data """ + self.data = data + self.next = None + + +class LinkedList: + """ Singly Linked List is a linear data structure """ + def __init__(self): + """ initializing singly linked list with zero node """ + self.head = None + + def insert_head(self, data): + """ inserts node at the start of linked list """ + node = Node(data) + node.next = self.head + self.head = node + + def print(self): + """ prints entire linked list without changing underlying data """ + current = self.head + while current is not None: + print(" ->", current.data, end="") + current = current.next + print() + + + def remove_duplicates(self): + """ removes duplicates from list """ + duplicates = set() + previous = None + current = self.head + + while current is not None: + if current.data not in duplicates: + duplicates.add(current.data) + previous = current + else: + previous.next = current.next + current = current.next + + +def main(): + """ operational function """ + linkedlist = LinkedList() + linkedlist.insert_head(4) + linkedlist.insert_head(2) + linkedlist.insert_head(2) + linkedlist.insert_head(4) + linkedlist.insert_head(1) + linkedlist.insert_head(6) + linkedlist.insert_head(1) + + linkedlist.print() + linkedlist.remove_duplicates() + linkedlist.print() + + +if __name__ == '__main__': + main() From 870a4efb8078da3f4d7a6ba7409af4067040fe93 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Thu, 3 Dec 2020 09:59:35 +0530 Subject: [PATCH 134/209] add linked list josephus circle --- linked_list/josephus_circle.py | 127 +++++++++++++++++++++++++++++++++ 1 file changed, 127 insertions(+) create mode 100644 linked_list/josephus_circle.py diff --git a/linked_list/josephus_circle.py b/linked_list/josephus_circle.py new file mode 100644 index 0000000..c1faa3c --- /dev/null +++ b/linked_list/josephus_circle.py @@ -0,0 +1,127 @@ +""" Josephus Circle using circular linked list + URL: https://www.geeksforgeeks.org/josephus-circle-using-circular-linked-list/ + + There are n people standing in a circle waiting to be executed. The + counting out begins at some point in the circle and proceeds around the + circle in a fixed direction. In each step, a certain number of people are + skipped and the next person is executed. The elimination proceeds around + the circle (which is becoming smaller and smaller as the executed people + are removed), until only the last person remains, who is given freedom. + Given the total number of persons n and a number m which indicates that + m-1 persons are skipped and m-th person is killed in circle. The task is + to choose the place in the initial circle so that you are the last one + remaining and so survive. + + Example: + Input: Length of circle: n = 4 + Count to choose next: m = 2 + Output : 1 + + Input: n = 5 + m = 3 + Output: 4 +""" + +class Node: + """ Node class contains everything related to Linked List node """ + def __init__(self, data): + """ initializing single node with data """ + self.data = data + self.next = None + + +class CircularLinkedList: + """ Circular linked list is a linked list where all nodes are connected + to form a circle. + """ + def __init__(self): + """ initializing circular linked list with zero node """ + self.head = None + + def __len__(self): + """ get number of nodes currently present in circular linked list """ + if self.head is None: + return 0 + + current = self.head + count = 1 + while current.next is not self.head: + count += 1 + current = current.next + return count + + def insert_tail(self, data): + """ inserts node at the end of linked list """ + if self.head is None: + self.head = Node(data) + self.head.next = self.head + return + + new_node = Node(data) + current = self.head + while current.next is not self.head: + current = current.next + current.next = new_node + new_node.next = self.head + + def remove_node(self, node): + """ remove node from circular linked list """ + if self.head == node: + previous = self.head + while previous.next is not self.head: + previous = previous.next + previous.next = self.head.next + self.head = previous.next + return + + current = self.head.next + previous = self.head + while current is not self.head: + if current == node: + break + previous = current + current = current.next + previous.next = current.next + + def print(self): + """ prints entire linked list without changing underlying data """ + current = self.head + while current is not None: + print(" ->", current.data, end="") + current = current.next + if current == self.head: + break + print(end=" -> ...") + print() + + +def josephus_circle(cll, step): + """ josephus circle solution """ + current = cll.head + + while len(cll) > 1: + count = 1 + while count != step: + current = current.next + count += 1 + print("removing:", current.data) + cll.remove_node(current) + current = current.next + + +def main(): + """ operational function """ + total_people = 5 + step = 3 + + cll = CircularLinkedList() + for i in range(1, total_people+1): + cll.insert_tail(i) + cll.print() + + josephus_circle(cll, step) + cll.print() + + +if __name__ == '__main__': + main() From 3219db1002025efd92ab6838e91a0f677c99fb17 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Mon, 7 Dec 2020 18:50:18 +0530 Subject: [PATCH 135/209] linked list merge two sorted list --- linked_list/merge_two_sorted_list.py | 94 ++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 linked_list/merge_two_sorted_list.py diff --git a/linked_list/merge_two_sorted_list.py b/linked_list/merge_two_sorted_list.py new file mode 100644 index 0000000..6b374b4 --- /dev/null +++ b/linked_list/merge_two_sorted_list.py @@ -0,0 +1,94 @@ +""" Merge two sorted linked lists +""" + +class Node: + """ Node class contains everything related to Linked List node """ + def __init__(self, data): + """ initializing single node with data """ + self.data = data + self.next = None + + +class LinkedList: + """ Singly Linked List is a linear data structure """ + def __init__(self): + """ initializing singly linked list with zero node """ + self.head = None + + def insert_head(self, data): + """ inserts node at the start of linked list """ + node = Node(data) + node.next = self.head + self.head = node + +def print_linkedlist(head): + """ prints entire linked list without changing underlying data """ + current = head + while current is not None: + print(" ->", current.data, end="") + current = current.next + print() + + +def merge_sorted(linkedlist1, linkedlist2): + """ merge two sorted linked lists """ + node1_ptr = linkedlist1.head + node2_ptr = linkedlist2.head + s_ptr = None + + if node1_ptr is None: + return node2_ptr + + if node2_ptr is None: + return node1_ptr + + if node1_ptr.data > node2_ptr.data: + s_ptr = node2_ptr + node2_ptr = node2_ptr.next + else: + s_ptr = node1_ptr + node1_ptr = node1_ptr.next + + result_head = s_ptr + + while node1_ptr and node2_ptr: + if node1_ptr.data > node2_ptr.data: + s_ptr.next = node2_ptr + s_ptr = node2_ptr + node2_ptr = node2_ptr.next + else: + s_ptr.next = node1_ptr + s_ptr = node1_ptr + node1_ptr = node1_ptr.next + + if node2_ptr is None: + s_ptr.next = node1_ptr + elif node1_ptr is None: + s_ptr.next = node2_ptr + + return result_head + + + +def main(): + """ operational function """ + linkedlist1 = LinkedList() + linkedlist1.insert_head(10) + linkedlist1.insert_head(9) + linkedlist1.insert_head(7) + linkedlist1.insert_head(5) + linkedlist1.insert_head(1) + + linkedlist2 = LinkedList() + linkedlist2.insert_head(8) + linkedlist2.insert_head(6) + linkedlist2.insert_head(4) + linkedlist2.insert_head(3) + linkedlist2.insert_head(2) + linkedlist2.insert_head(1) + + print_linkedlist(merge_sorted(linkedlist1, linkedlist2)) + + +if __name__ == '__main__': + main() From 02712fc5e434a1a1a18a27ac36e3713ae121cccc Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Mon, 7 Dec 2020 18:50:37 +0530 Subject: [PATCH 136/209] add linkedlist node_swap --- linked_list/node_swap.py | 82 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 linked_list/node_swap.py diff --git a/linked_list/node_swap.py b/linked_list/node_swap.py new file mode 100644 index 0000000..ac423a0 --- /dev/null +++ b/linked_list/node_swap.py @@ -0,0 +1,82 @@ +""" Swap two nodes in a linked list + input: 1 -> 5 -> 2 -> 3 -> 7 -> 9 -> 10 + output: 1 -> 7 -> 2 -> 3 -> 5 -> 9 -> 10 +""" + +class Node: + """ Node class contains everything related to Linked List node """ + def __init__(self, data): + """ initializing single node with data """ + self.data = data + self.next = None + + +class LinkedList: + """ Singly Linked List is a linear data structure """ + def __init__(self): + """ initializing singly linked list with zero node """ + self.head = None + + def insert_head(self, data): + """ inserts node at the start of linked list """ + node = Node(data) + node.next = self.head + self.head = node + + def print(self): + """ prints entire linked list without changing underlying data """ + current = self.head + while current is not None: + print(" ->", current.data, end="") + current = current.next + print() + + + def swap_node(self, node1, node2): + """ swap node1 with node2 """ + previous1 = None + current1 = self.head + while current1 is not None: + if current1 is node1: + break + previous1 = current1 + current1 = current1.next + + previous2 = None + current2 = self.head + while current2 is not None: + if current2 is node2: + break + previous2 = current2 + current2 = current2.next + + if previous1 is not None: + previous1.next = current2 + else: + self.head = current2 + if previous2 is not None: + previous2.next = current1 + else: + self.head = current1 + + current1.next, current2.next = current2.next, current1.next + + +def main(): + """ operational function """ + linkedlist = LinkedList() + linkedlist.insert_head(10) + linkedlist.insert_head(9) + linkedlist.insert_head(7) + linkedlist.insert_head(3) + linkedlist.insert_head(2) + linkedlist.insert_head(5) + linkedlist.insert_head(1) + + linkedlist.print() + linkedlist.swap_node(linkedlist.head.next, linkedlist.head.next.next.next.next) + linkedlist.print() + + +if __name__ == '__main__': + main() From ccd5be8589f6924d8e64d38603bacfce6a51a7cd Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Wed, 9 Dec 2020 19:15:32 +0530 Subject: [PATCH 137/209] add linkedlist reverse algo --- linked_list/reverse_singly_list.py | 62 ++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 linked_list/reverse_singly_list.py diff --git a/linked_list/reverse_singly_list.py b/linked_list/reverse_singly_list.py new file mode 100644 index 0000000..39a9d42 --- /dev/null +++ b/linked_list/reverse_singly_list.py @@ -0,0 +1,62 @@ +""" Reverse linked lists +""" + +class Node: + """ Node class contains everything related to Linked List node """ + def __init__(self, data): + """ initializing single node with data """ + self.data = data + self.next = None + + +class LinkedList: + """ Singly Linked List is a linear data structure """ + def __init__(self): + """ initializing singly linked list with zero node """ + self.head = None + + def insert_head(self, data): + """ inserts node at the start of linked list """ + node = Node(data) + node.next = self.head + self.head = node + + def print(self): + """ prints entire linked list without changing underlying data """ + current = self.head + while current is not None: + print(" ->", current.data, end="") + current = current.next + print() + + def reverse(self): + """ reverse linked list """ + previous = None + following = None + current = self.head + + while current is not None: + following = current.next + current.next = previous + previous = current + current = following + + self.head = previous + + +def main(): + """ operational function """ + linkedlist = LinkedList() + linkedlist.insert_head(10) + linkedlist.insert_head(9) + linkedlist.insert_head(7) + linkedlist.insert_head(5) + linkedlist.insert_head(1) + + linkedlist.print() + linkedlist.reverse() + linkedlist.print() + + +if __name__ == '__main__': + main() From 76ae1086b22124cc1dd46a77f34c58438fb18500 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Wed, 9 Dec 2020 19:16:07 +0530 Subject: [PATCH 138/209] add doubly linked list reverse algo --- linked_list/reverse_doubly_list.py | 75 ++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 linked_list/reverse_doubly_list.py diff --git a/linked_list/reverse_doubly_list.py b/linked_list/reverse_doubly_list.py new file mode 100644 index 0000000..5d18e65 --- /dev/null +++ b/linked_list/reverse_doubly_list.py @@ -0,0 +1,75 @@ +""" Reverse Doubly linked list + URL: https://www.geeksforgeeks.org/reverse-a-doubly-linked-list/ +""" + +class Node: + """ Node class contains everything related to linked list node """ + + def __init__(self, data): + """ initializing single node with data """ + self.data = data + self.next = None + self.previous = None + + +class DoublyLinkedList: + """ A Doubly linked list (DLL) contains an extra pointer, typically + called previous pointer, together with next pointer and data which + are there in singly linked list. + """ + def __init__(self): + """ initializing doublt linked list with zero node """ + self.head = None + + def insert_tail(self, data): + """ inserts node at the end of doubly linked list """ + if self.head is None: + self.head = Node(data) + return + + current = self.head + new_node = Node(data) + while current.next is not None: + current = current.next + current.next = new_node + new_node.previous = current + + def print(self): + """ prints entire linked list without changing underlying data """ + current = self.head + while current is not None: + print(" <->", current.data, end="") + current = current.next + print() + + def reverse(self): + """ reverse doubly linked list """ + temp = None + current = self.head + + while current is not None: + temp = current.previous + current.previous = current.next + current.next = temp + current = current.previous + + if temp is not None: + self.head = temp.previous + +def main(): + """ operational function """ + dll = DoublyLinkedList() + dll.insert_tail(1) + dll.insert_tail(2) + dll.insert_tail(3) + dll.insert_tail(4) + dll.insert_tail(5) + dll.insert_tail(6) + dll.print() + + dll.reverse() + dll.print() + + +if __name__ == '__main__': + main() From ff8dde9a605b4d04908c6591798ed5a92e268951 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Thu, 10 Dec 2020 23:58:26 +0530 Subject: [PATCH 139/209] add doubly linked list remove duplicates --- linked_list/remove_duplicates_doubly.py | 83 +++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 linked_list/remove_duplicates_doubly.py diff --git a/linked_list/remove_duplicates_doubly.py b/linked_list/remove_duplicates_doubly.py new file mode 100644 index 0000000..9d2beb9 --- /dev/null +++ b/linked_list/remove_duplicates_doubly.py @@ -0,0 +1,83 @@ +""" Reverse Doubly linked list + URL: https://www.geeksforgeeks.org/reverse-a-doubly-linked-list/ +""" + +class Node: + """ Node class contains everything related to linked list node """ + + def __init__(self, data): + """ initializing single node with data """ + self.data = data + self.next = None + self.previous = None + + +class DoublyLinkedList: + """ A Doubly linked list (DLL) contains an extra pointer, typically + called previous pointer, together with next pointer and data which + are there in singly linked list. + """ + def __init__(self): + """ initializing doublt linked list with zero node """ + self.head = None + + def insert_tail(self, data): + """ inserts node at the end of doubly linked list """ + if self.head is None: + self.head = Node(data) + return + + current = self.head + new_node = Node(data) + while current.next is not None: + current = current.next + current.next = new_node + new_node.previous = current + + def print(self): + """ prints entire linked list without changing underlying data """ + current = self.head + while current is not None: + print(" <->", current.data, end="") + current = current.next + print() + + def remove_duplicates(self): + """ removes duplicates from list """ + duplicates = set() + current = self.head + + while current is not None: + if current.data not in duplicates: + duplicates.add(current.data) + current = current.next + else: + previous_node = current.previous + del_node = current + current = current.next + previous_node.next = current + if current is not None: + current.previous = previous_node + del_node.previous = None + del_node.next = None + del del_node + + +def main(): + """ operational function """ + dll = DoublyLinkedList() + dll.insert_tail(4) + dll.insert_tail(2) + dll.insert_tail(2) + dll.insert_tail(4) + dll.insert_tail(1) + dll.insert_tail(6) + dll.insert_tail(1) + dll.print() + + dll.remove_duplicates() + dll.print() + + +if __name__ == '__main__': + main() From 2dd8d6a2094ee9c091fe502b38d0d8f147c2668f Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sat, 12 Dec 2020 23:48:04 +0530 Subject: [PATCH 140/209] add linked list rotation --- linked_list/rotate.py | 68 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 linked_list/rotate.py diff --git a/linked_list/rotate.py b/linked_list/rotate.py new file mode 100644 index 0000000..8eb5141 --- /dev/null +++ b/linked_list/rotate.py @@ -0,0 +1,68 @@ +""" Remove duplicates from linked list + input: 1 -> 6 -> 1 -> 4 -> 2 -> 2 -> 4 + output: 1 -> 6 -> 4 -> 2 +""" + +class Node: + """ Node class contains everything related to Linked List node """ + def __init__(self, data): + """ initializing single node with data """ + self.data = data + self.next = None + + +class LinkedList: + """ Singly Linked List is a linear data structure """ + def __init__(self): + """ initializing singly linked list with zero node """ + self.head = None + + def insert_head(self, data): + """ inserts node at the start of linked list """ + node = Node(data) + node.next = self.head + self.head = node + + def print(self): + """ prints entire linked list without changing underlying data """ + current = self.head + while current is not None: + print(" ->", current.data, end="") + current = current.next + print() + + + def rotate(self, position): + """ rotate linked list from given position """ + node_ptr = self.head + last_ptr = self.head + + while position > 1: + node_ptr = node_ptr.next + position -= 1 + + while last_ptr.next is not None: + last_ptr = last_ptr.next + + last_ptr.next = self.head + self.head = node_ptr.next + node_ptr.next = None + + +def main(): + """ operational function """ + linkedlist = LinkedList() + linkedlist.insert_head(6) + linkedlist.insert_head(5) + linkedlist.insert_head(4) + linkedlist.insert_head(3) + linkedlist.insert_head(2) + linkedlist.insert_head(1) + + linkedlist.print() + linkedlist.rotate(4) + linkedlist.print() + + +if __name__ == '__main__': + main() From 0955496157117872dea1b8f6531246dae3c03610 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Mon, 14 Dec 2020 12:54:06 +0530 Subject: [PATCH 141/209] add merge sort --- sort/merge.py | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 sort/merge.py diff --git a/sort/merge.py b/sort/merge.py new file mode 100644 index 0000000..93b9179 --- /dev/null +++ b/sort/merge.py @@ -0,0 +1,51 @@ +""" Implementation of Merge Sort algorithm +""" + + +def merge(data): + """ MergeSort is a Divide and Conquer algorithm. It divides input array + in two halves, calls itself for the two halves and then merges the + two sorted halves. + + :param array: list of elements that needs to be sorted + :type array: list + """ + if len(data) > 1: + mid = len(data) // 2 + lefthalf = data[:mid] + righthalf = data[mid:] + + merge(lefthalf) + merge(righthalf) + + i = j = k = 0 + while i < len(lefthalf) and j < len(righthalf): + if lefthalf[i] < righthalf[j]: + data[k] = lefthalf[i] + i = i + 1 + else: + data[k] = righthalf[j] + j = j + 1 + k = k + 1 + + while i < len(lefthalf): + data[k] = lefthalf[i] + i = i + 1 + k = k + 1 + + while j < len(righthalf): + data[k] = righthalf[j] + j = j + 1 + k = k + 1 + + +def main(): + """ operational function """ + arr = [34, 56, 23, 67, 3, 68] + print(f"unsorted array: {arr}") + merge(arr) + print(f" sorted array: {arr}") + + +if __name__ == "__main__": + main() From 57670993b2d062dc2fea44b86e3e540485565fc4 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Mon, 14 Dec 2020 12:54:19 +0530 Subject: [PATCH 142/209] add quick sort --- sort/quick.py | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 sort/quick.py diff --git a/sort/quick.py b/sort/quick.py new file mode 100644 index 0000000..16b79c4 --- /dev/null +++ b/sort/quick.py @@ -0,0 +1,49 @@ +""" Implementation of Quick Sort algorithm +""" + + +def partition(data, low, high): + """ partition return partition index of pivot + + :param array: list of elements that needs to be sorted + :param low: lower index of sub-array + :param high: higher index of sub-array + :returns: partition index of pivot + """ + pivot = data[high] + partition_index = low + for i in range(low, high): + if data[i] <= pivot: + data[i], data[partition_index] = data[partition_index], data[i] + partition_index += 1 + + data[high], data[partition_index] = data[partition_index], data[high] + return partition_index + + +def quick(data, low, high): + """ QuickSort is a Divide and Conquer algorithm. + It picks an element as pivot and partitions the given array around the + picked pivot. It uses last element as pivot element + + :param array: list of elements that needs to be sorted + :param low: lower index of sub-array + :param high: higher index of sub-array + """ + if high <= low: + return + j = partition(data, low, high) + quick(data, low, j-1) + quick(data, j+1, high) + + +def main(): + """ operational function """ + arr = [34, 56, 23, 67, 3, 68] + print(f"unsorted array: {arr}") + quick(arr, 0, len(arr)-1) + print(f" sorted array: {arr}") + + +if __name__ == "__main__": + main() From 8ccc5fbf429a69fdd8b56e244fab77f3f73aab5c Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Wed, 16 Dec 2020 19:56:40 +0530 Subject: [PATCH 143/209] add linked list sum of two list --- linked_list/sum_two_lists.py | 88 ++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 linked_list/sum_two_lists.py diff --git a/linked_list/sum_two_lists.py b/linked_list/sum_two_lists.py new file mode 100644 index 0000000..523809e --- /dev/null +++ b/linked_list/sum_two_lists.py @@ -0,0 +1,88 @@ +""" You are given two non-empty linked lists representing two non-negative + integers. The digits are stored in reverse order, and each of their + nodes contains a single digit. Add the two numbers and return the sum + as a linked list. + + You may assume the two numbers do not contain any leading zero, + except the number 0 itself. + + Input: l1 = [2,4,3], l2 = [5,6,4] + Output: [7,0,8] + Explanation: 342 + 465 = 807. +""" + +class Node: + """ Node class contains everything related to Linked List node """ + def __init__(self, data): + """ initializing single node with data """ + self.data = data + self.next = None + + +class LinkedList: + """ Singly Linked List is a linear data structure """ + def __init__(self): + """ initializing singly linked list with zero node """ + self.head = None + + def insert_head(self, data): + """ inserts node at the start of linked list """ + node = Node(data) + node.next = self.head + self.head = node + + def print(self): + """ prints entire linked list without changing underlying data """ + current = self.head + while current is not None: + print(" ->", current.data, end="") + current = current.next + print() + + +def add_two_numbers(list1, list2): + """ add two numbers which are represented by linkedlist """ + carry = 0 + current1 = list1.head + current2 = list2.head + result = LinkedList() + result.insert_head(0) + result_pointer = result.head + + while current1 or current2: + val1 = getattr(current1, 'data', 0) + val2 = getattr(current2, 'data', 0) + temp_val = carry + val1 + val2 + carry = temp_val // 10 + result_pointer.next = Node(temp_val % 10) + result_pointer = result_pointer.next + current1 = getattr(current1, 'next', None) + current2 = getattr(current2, 'next', None) + + if carry > 0: + result_pointer.next = Node(carry) + + result.head = result.head.next + return result + + + +def main(): + """ operational function """ + linkedlist1 = LinkedList() + linkedlist1.insert_head(3) + linkedlist1.insert_head(6) + linkedlist1.insert_head(5) + linkedlist1.print() + + linkedlist2 = LinkedList() + linkedlist2.insert_head(2) + linkedlist2.insert_head(4) + linkedlist2.insert_head(8) + linkedlist2.print() + + add_two_numbers(linkedlist1, linkedlist2).print() + + +if __name__ == '__main__': + main() From 56bf265bf472210b5dd88f6d856e4271b5a1e1fd Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Thu, 17 Dec 2020 01:12:17 +0530 Subject: [PATCH 144/209] add split circular linked list algo --- linked_list/split_circular_lists.py | 93 +++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 linked_list/split_circular_lists.py diff --git a/linked_list/split_circular_lists.py b/linked_list/split_circular_lists.py new file mode 100644 index 0000000..354a211 --- /dev/null +++ b/linked_list/split_circular_lists.py @@ -0,0 +1,93 @@ +""" Split a Circular Linked List into two halves + If there are odd number of nodes, then first list should contain one extra. + + Input: A -> B -> C -> D -> ... + Output: A -> B -> ... and C -> D -> ... + + URL: https://www.geeksforgeeks.org/split-a-circular-linked-list-into-two-halves/ +""" + +class Node: + """ Node class contains everything related to Linked List node """ + def __init__(self, data): + """ initializing single node with data """ + self.data = data + self.next = None + + +class CircularLinkedList: + """ Circular linked list is a linked list where all nodes are connected + to form a circle. + """ + def __init__(self): + """ initializing circular linked list with zero node """ + self.head = None + + def insert_tail(self, data): + """ inserts node at the end of linked list """ + if self.head is None: + self.head = Node(data) + self.head.next = self.head + return + + new_node = Node(data) + current = self.head + while current.next is not self.head: + current = current.next + current.next = new_node + new_node.next = self.head + + def print(self): + """ prints entire linked list without changing underlying data """ + current = self.head + while current is not None: + print(" ->", current.data, end="") + current = current.next + if current == self.head: + break + print(end=" -> ...") + print() + + +def split_list(cll): + """ split a circular linked list into two halves """ + slow_ptr = cll.head + fast_ptr = cll.head + + while (fast_ptr.next is not cll.head and + fast_ptr.next.next is not cll.head): + slow_ptr = slow_ptr.next + fast_ptr = fast_ptr.next.next + + while fast_ptr.next is not cll.head: + fast_ptr = fast_ptr.next + + cll1 = CircularLinkedList() + cll2 = CircularLinkedList() + + cll1.head = cll.head + cll2.head = slow_ptr.next + slow_ptr.next = cll1.head + fast_ptr.next = cll2.head + + return cll1, cll2 + + +def main(): + """ operational function """ + cll = CircularLinkedList() + cll.insert_tail('A') + cll.insert_tail('B') + cll.insert_tail('C') + cll.insert_tail('D') + cll.insert_tail('E') + cll.insert_tail('F') + cll.insert_tail('G') + cll.print() + + cll1, cll2 = split_list(cll) + cll1.print() + cll2.print() + +if __name__ == '__main__': + main() From 5062a8504b529a9d2e8aafc72565bd022ec40a8a Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Thu, 17 Dec 2020 01:12:43 +0530 Subject: [PATCH 145/209] add get min special stack algo --- stack/getmin_special_stack.py | 64 +++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 stack/getmin_special_stack.py diff --git a/stack/getmin_special_stack.py b/stack/getmin_special_stack.py new file mode 100644 index 0000000..fcb13c4 --- /dev/null +++ b/stack/getmin_special_stack.py @@ -0,0 +1,64 @@ +""" +Problem Statement: +Design a Data Structure SpecialStack that supports all the stack operations +like push(), pop(), isEmpty(), isFull() and an additional operation getMin() +which should return minimum element from the SpecialStack. All these +operations of SpecialStack must be O(1). To implement SpecialStack, you +should only use standard Stack data structure and no other data structure +like arrays, list, .. etc. + +URL: https://www.geeksforgeeks.org/design-and-implement-special-stack-data-structure/ +""" + +class SpecialStack: + """ special stack with get_min functionality """ + def __init__(self): + self.data = [] + self.aux_min = [] + + def push(self, element): + """ push element into stack """ + if not self.data: + self.aux_min.append(element) + else: + self.aux_min.append(min(self.aux_min[-1], element)) + self.data.append(element) + + def pop(self): + """ pop element from stack """ + if not self.data: + raise IndexError("stack is empty") + self.aux_min.pop() + return self.data.pop() + + def get_min(self): + """ returns minimum element present in stack + Time complexity: O(1) + """ + if self.aux_min: + return self.aux_min[-1] + return None + + +def main(): + """ operational function """ + ss = SpecialStack() + ss.push(30) + ss.push(20) + ss.push(10) + print(ss.get_min()) + ss.push(5) + print(ss.get_min()) + + ss.pop() + print(ss.get_min()) # 10 + ss.pop() + print(ss.get_min()) # 20 + ss.pop() + print(ss.get_min()) # 30 + ss.pop() + print(ss.get_min()) # None + + +if __name__ == "__main__": + main() From 6ce2fcf42f86a953f7305416aa4a32414b4c4667 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Thu, 17 Dec 2020 22:42:29 +0530 Subject: [PATCH 146/209] add stack integer to binary --- stack/integer_to_binary.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 stack/integer_to_binary.py diff --git a/stack/integer_to_binary.py b/stack/integer_to_binary.py new file mode 100644 index 0000000..b42ea5a --- /dev/null +++ b/stack/integer_to_binary.py @@ -0,0 +1,22 @@ +""" converting decimal integer to binary using + stack data structure +""" +from collections import deque + + +def convert_integer_to_binary(number): + """ converting decimal integer to binary """ + stack = deque() + while number: + stack.append(number % 2) + number = number // 2 + + binary_str = '' + while stack: + binary_str += str(stack.pop()) + + return binary_str + + +if __name__ == '__main__': + print(convert_integer_to_binary(242)) From a5bb26e9d4e87ca767b76107f8a23c9f5ea7015f Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Thu, 17 Dec 2020 22:42:55 +0530 Subject: [PATCH 147/209] add stack queue using stack --- stack/queue_using_stack.py | 53 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 stack/queue_using_stack.py diff --git a/stack/queue_using_stack.py b/stack/queue_using_stack.py new file mode 100644 index 0000000..68c953f --- /dev/null +++ b/stack/queue_using_stack.py @@ -0,0 +1,53 @@ +""" +Problem Statement: +We are given a stack data structure with push and pop operations, the task is +to implement a queue using instances of stack data structure and operations +on them. + +URL: https://www.geeksforgeeks.org/queue-using-stacks/ +""" + +class Queue: + """ Queue implementation using two Stacks """ + def __init__(self): + self.stack = [] + self.aux_stack = [] + + def enqueue(self, element): + """ enqueue element to queue """ + while self.stack: + self.aux_stack.append(self.stack.pop()) + self.aux_stack.append(element) + + while self.aux_stack: + self.stack.append(self.aux_stack.pop()) + + def dequeue(self): + """ dequeue element to queue """ + if not self.stack: + raise IndexError("queue is empty") + return self.stack.pop() + + +def main(): + """ operational function """ + queue = Queue() + queue.enqueue(1) + queue.enqueue(2) + queue.enqueue(3) + print(queue.dequeue()) + print(queue.dequeue()) + print(queue.dequeue()) + + queue.enqueue(4) + queue.enqueue(5) + print(queue.dequeue()) + print(queue.dequeue()) + try: + print(queue.dequeue()) + except IndexError as err: + print(err) + + +if __name__ == '__main__': + main() From 3480f467aeea42d9667cd06237af063b3abba162 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sat, 19 Dec 2020 20:08:28 +0530 Subject: [PATCH 148/209] add two stack in an array algo --- stack/two_stack_in_an_array.py | 64 ++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 stack/two_stack_in_an_array.py diff --git a/stack/two_stack_in_an_array.py b/stack/two_stack_in_an_array.py new file mode 100644 index 0000000..84827c3 --- /dev/null +++ b/stack/two_stack_in_an_array.py @@ -0,0 +1,64 @@ +""" +Problem Statement: +Implementation of twoStacks should use only one array, i.e., both stacks +should use the same array for storing elements. + +URL: https://www.geeksforgeeks.org/implement-two-stacks-in-an-array/ +""" + +class TwoStacks: + def __init__(self, capacity): + self.arr = [None] * capacity + self.index1 = -1 + self.index2 = capacity + + def push1(self, element1): + """ push element to stack 1 """ + self.index1 += 1 + if self.index1 >= self.index2: + self.index1 -= 1 + raise IndexError("array is full") + self.arr[self.index1] = element1 + + + def push2(self, element2): + """ push element to stack 2 """ + self.index2 -= 1 + if self.index1 >= self.index2: + self.index2 += 1 + raise IndexError("array is full") + self.arr[self.index2] = element2 + + def pop1(self): + """ pop element from stack 1 """ + popped_element = self.arr[self.index1] + self.arr[self.index1] = None + self.index1 -= 1 + return popped_element + + def pop2(self): + """ pop element from stack 2 """ + popped_element = self.arr[self.index2] + self.arr[self.index2] = None + self.index2 += 1 + return popped_element + + +def main(): + """ operational function """ + ts = TwoStacks(5) + ts.push1(5) + ts.push2(10) + ts.push2(15) + ts.push1(11) + ts.push2(7) + + print(ts.pop1()) + ts.push2(40) + print(ts.pop2()) + print(ts.arr) # [5, None, 7, 15, 10] + + +if __name__ == "__main__": + main() + From b792422f781a9cfd69e39815f0caf80cebc03f1f Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sun, 20 Dec 2020 20:10:09 +0530 Subject: [PATCH 149/209] add binary search tree library --- .../library/binary_search_tree.py | 174 ++++++++++++++++++ 1 file changed, 174 insertions(+) create mode 100644 binary_search_tree/library/binary_search_tree.py diff --git a/binary_search_tree/library/binary_search_tree.py b/binary_search_tree/library/binary_search_tree.py new file mode 100644 index 0000000..eda2ef5 --- /dev/null +++ b/binary_search_tree/library/binary_search_tree.py @@ -0,0 +1,174 @@ +""" +Binary Search Tree (Python Implementation) + +Binary Search Tree is a node-based binary tree data structure +which has the following properties: +- The left subtree of a node contains only nodes with keys lesser + than the node’s key. +- The right subtree of a node contains only nodes with keys greater + than the node’s key. +- The left and right subtree each must also be a binary search tree. +""" + +class Node: + """ Node contains actual data and address to left and right node """ + def __init__(self, data): + self.data = data + self.left = None + self.right = None + + +class BinarySearchTree: + """ Binary Search Tree Implementation """ + def __init__(self): + self.root = None + + def insert(self, data): + """ inserts new integer data into the tree at the position, so that + the binary search tree property is maintained. + """ + def _insert(root, data): + """ recursive internal method which works on node level """ + if root is None: + root = Node(data) + elif data <= root.data: + root.left = _insert(root.left, data) + else: + root.right = _insert(root.right, data) + return root + + if self.root is None: + self.root = Node(data) + else: + self.root = _insert(self.root, data) + + def search(self, data): + """ finds the integer in binary search tree + """ + def _search(root, data): + """ recursive internal method which works at node level """ + if root is None: + return False + + if data == root.data: + return True + elif data < root.data: + return _search(root.left, data) + else: + return _search(root.right, data) + + if self.root is None: + return False + return _search(self.root, data) + + def delete(self, data): + """ delete value from binary search tree """ + def find_min_node(node): + """ find the node with minimum value of give (sub)tree """ + while node.left is not None: + node = node.left + return node + + def _delete(root, data): + """ interal recursive method that works at node-level """ + if root is None: + return root + + if data < root.data: + root.left = _delete(root.left, data) + elif data > root.data: + root.right = _delete(root.right, data) + else: + if root.left is None and root.right is None: + del root + root = None + elif root.left is None: + temp = root + root = root.right + del temp + elif root.right is None: + temp = root + root = root.left + del temp + else: + temp = find_min_node(root.right) + root.data = temp.data + root.right = _delete(root.right, temp.data) + return root + + self.root = _delete(self.root, data) + + def min(self): + """ returns left-most item present in binary search tree which is also + the minimum element in bst + """ + if self.root is None: + raise Exception("tree is empty") + + current = self.root + while current.left is not None: + current = current.left + return current.data + + def max(self): + """ returns right-most item present in binary search tree which is also + the maximum element in bst + """ + if self.root is None: + raise Exception("tree is empty") + + current = self.root + while current.right is not None: + current = current.right + return current.data + + def height(self): + """ calculate height of binary search tree + """ + def _height(root): + """ recursive internal method that works at node-level """ + if root is None: + return -1 + + left_height = _height(root.left) + right_height = _height(root.right) + if left_height > right_height: + return left_height + 1 + return right_height + 1 + + if self.root is None: + return -1 + return _height(self.root) + + +def main(): + """ operational function """ + bst = BinarySearchTree() + bst.insert(4) + bst.insert(2) + bst.insert(8) + bst.insert(5) + bst.insert(10) + + print("is 4 present in bst?", bst.search(4)) + print("is 5 present in bst?", bst.search(5)) + print("is 11 present in bst?", bst.search(11)) + + print("min value:", bst.min()) + print("max value:", bst.max()) + print("height of bst:", bst.height()) + + bst.delete(10) + bst.delete(8) + bst.delete(2) + + + print("is 8 present in bst?", bst.search(8)) + print("is 10 present in bst?", bst.search(10)) + + print("min value:", bst.min()) + print("max value:", bst.max()) + + +if __name__ == "__main__": + main() From 12048834ac82d9cfcae928beb2484e9a2faacbe2 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Wed, 23 Dec 2020 19:51:21 +0530 Subject: [PATCH 150/209] add bst bfs traversal algo --- binary_search_tree/bfs_traversals.py | 75 ++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 binary_search_tree/bfs_traversals.py diff --git a/binary_search_tree/bfs_traversals.py b/binary_search_tree/bfs_traversals.py new file mode 100644 index 0000000..ea30898 --- /dev/null +++ b/binary_search_tree/bfs_traversals.py @@ -0,0 +1,75 @@ +""" Binary Search Tree Traversals + + DFS (Depth-first search) is technique used for traversing tree or graph. + + Here backtracking is used for traversal. In this traversal first the + deepest node is visited and then backtracks to it’s parent node if no + sibling of that node exist. +""" + +from collections import deque + + +class Node: + """ Node contains actual data and address to left and right node """ + def __init__(self, data): + self.data = data + self.left = None + self.right = None + + +class BinarySearchTree: + """ Binary Search Tree Implementation """ + def __init__(self): + self.root = None + + def insert(self, data): + """ inserts new integer data into the tree at the position, so that + the binary search tree property is maintained. + """ + def _insert(root, data): + """ recursive internal method which works on node level """ + if root is None: + root = Node(data) + elif data <= root.data: + root.left = _insert(root.left, data) + else: + root.right = _insert(root.right, data) + return root + + if self.root is None: + self.root = Node(data) + else: + self.root = _insert(self.root, data) + + + def level_order_traversal(self): + """ Breadth First Traversal (Level Order Traversal) """ + if self.root is None: + return + + queue = deque() + queue.append(self.root) + + while queue: + node = queue[0] + print(node.data, end=" ") + if node.left is not None: + queue.append(node.left) + if node.right is not None: + queue.append(node.right) + queue.popleft() + + +def main(): + """ operational function """ + bst = BinarySearchTree() + for elem in [9, 5, 3, 10, 6, 1, 7, 4]: + bst.insert(elem) + + bst.level_order_traversal() + print() + + +if __name__ == "__main__": + main() From 6ec95ec38803372ed849de88ce3736a117f9c155 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Thu, 24 Dec 2020 13:13:37 +0530 Subject: [PATCH 151/209] add bst compare two bst --- binary_search_tree/compare_two_bst.py | 50 +++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 binary_search_tree/compare_two_bst.py diff --git a/binary_search_tree/compare_two_bst.py b/binary_search_tree/compare_two_bst.py new file mode 100644 index 0000000..e844cf2 --- /dev/null +++ b/binary_search_tree/compare_two_bst.py @@ -0,0 +1,50 @@ +""" Check whether thw two binary search tree are identical or not +""" + +class Node: + """ Node contains actual data and address to left and right node """ + def __init__(self, data): + self.data = data + self.left = None + self.right = None + + +def is_identical(root1, root2): + """ checks if two bst are identical """ + if root1 is None and root2 is None: + return True + + if root1 is not None and root2 is None: + return False + + if root1 is None and root2 is not None: + return False + + if (root1.data == root2.data and + is_identical(root1.left, root2.left) and + is_identical(root1.right, root2.right)): + return True + return False + + +def main(): + """ operational function """ + root1 = Node(5) + root1.left = Node(3) + root1.right = Node(8) + root1.left.left = Node(2) + root1.left.right = Node(4) + + root2 = Node(5) + root2.left = Node(3) + root2.right = Node(8) + root2.left.left = Node(2) + + print(is_identical(root1, root2)) + + root2.left.right = Node(4) + print(is_identical(root1, root2)) + + +if __name__ == "__main__": + main() From 83571cf00fe8ef6a6a10d5d2dd9b040e97112765 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Fri, 25 Dec 2020 01:06:29 +0530 Subject: [PATCH 152/209] add bst dfs traversal algo --- binary_search_tree/dfs_traversals.py | 100 +++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 binary_search_tree/dfs_traversals.py diff --git a/binary_search_tree/dfs_traversals.py b/binary_search_tree/dfs_traversals.py new file mode 100644 index 0000000..d41c211 --- /dev/null +++ b/binary_search_tree/dfs_traversals.py @@ -0,0 +1,100 @@ +""" Binary Search Tree Traversals + + DFS (Depth-first search) is technique used for traversing tree or graph. + + Here backtracking is used for traversal. In this traversal first the + deepest node is visited and then backtracks to it’s parent node if no + sibling of that node exist. +""" + +class Node: + """ Node contains actual data and address to left and right node """ + def __init__(self, data): + self.data = data + self.left = None + self.right = None + + +class BinarySearchTree: + """ Binary Search Tree Implementation """ + def __init__(self): + self.root = None + + def insert(self, data): + """ inserts new integer data into the tree at the position, so that + the binary search tree property is maintained. + """ + def _insert(root, data): + """ recursive internal method which works on node level """ + if root is None: + root = Node(data) + elif data <= root.data: + root.left = _insert(root.left, data) + else: + root.right = _insert(root.right, data) + return root + + if self.root is None: + self.root = Node(data) + else: + self.root = _insert(self.root, data) + + +def preorder_traversal(node): + """ Pre Order Tree Traversal + * Visit the root node + * Visit all the nodes in the left subtree + * Visit all the nodes in the right subtree + """ + if node is None: + return + + print(node.data, end=" ") + preorder_traversal(node.left) + preorder_traversal(node.right) + + +def inorder_traversal(node): + """ In Order Tree Traversal + * Visit all the nodes in the left subtree + * Visit the root node + * Visit all the nodes in the right subtree + """ + if node is None: + return + + inorder_traversal(node.left) + print(node.data, end=" ") + inorder_traversal(node.right) + + +def postorder_traversal(node): + """ Post Order Tree Traversal + * Visit all the nodes in the left subtree + * Visit all the nodes in the right subtree + * Visit the root node + """ + if node is None: + return + + postorder_traversal(node.left) + postorder_traversal(node.right) + print(node.data, end=" ") + + +def main(): + """ operational function """ + bst = BinarySearchTree() + for elem in [9, 5, 3, 10, 6, 1, 7, 4]: + bst.insert(elem) + + preorder_traversal(bst.root) + print() + inorder_traversal(bst.root) + print() + postorder_traversal(bst.root) + print() + + +if __name__ == "__main__": + main() From fa013c8418f9907e851e7e427d836869ad9f2eb8 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Fri, 25 Dec 2020 01:06:49 +0530 Subject: [PATCH 153/209] add is_bst algo --- binary_search_tree/is_bst.py | 73 ++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 binary_search_tree/is_bst.py diff --git a/binary_search_tree/is_bst.py b/binary_search_tree/is_bst.py new file mode 100644 index 0000000..a28825a --- /dev/null +++ b/binary_search_tree/is_bst.py @@ -0,0 +1,73 @@ +""" check whether the given binary tree is Binary Search Tree or not +""" + +import sys + +class Node: + """ Node contains actual data and address to left and right node """ + def __init__(self, data): + self.data = data + self.left = None + self.right = None + + +class BinarySearchTree: + """ Binary Search Tree Implementation """ + def __init__(self): + self.root = None + + def insert(self, data): + """ inserts new integer data into the tree at the position, so that + the binary search tree property is maintained. + """ + def _insert(root, data): + """ recursive internal method which works on node level """ + if root is None: + root = Node(data) + elif data <= root.data: + root.left = _insert(root.left, data) + else: + root.right = _insert(root.right, data) + return root + + if self.root is None: + self.root = Node(data) + else: + self.root = _insert(self.root, data) + + +def is_bst(root): + """ checks if binary tree is binary search tree """ + def is_bst_util(root, min_value, max_value): + """ binary search tree check utility function """ + if root is None: + return True + + if (root.data >= min_value and root.data < max_value + and is_bst_util(root.left, min_value, root.data) + and is_bst_util(root.right, root.data, max_value)): + return True + return False + + return is_bst_util(root, -sys.maxsize - 1, sys.maxsize) + + +def main(): + """ operational function """ + bst1 = BinarySearchTree() + for elem in [9, 5, 3, 10, 6, 1, 7, 4]: + bst1.insert(elem) + print("is BST?", is_bst(bst1.root)) + + bst2 = BinarySearchTree() + bst2.root = Node(5) + bst2.root.right = Node(7) + bst2.root.left = Node(5) + bst2.root.left.left = Node(1) + bst2.root.left.right = Node(4) + bst2.root.right.right = Node(6) + print("is BST?", is_bst(bst2.root)) + + +if __name__ == "__main__": + main() From 1f4d0ae052d916dd306fd063051ac3c4fe8baa44 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sun, 27 Dec 2020 19:51:03 +0530 Subject: [PATCH 154/209] add bst lowest common ancestor algo --- binary_search_tree/lowest_common_ancestor.py | 55 ++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 binary_search_tree/lowest_common_ancestor.py diff --git a/binary_search_tree/lowest_common_ancestor.py b/binary_search_tree/lowest_common_ancestor.py new file mode 100644 index 0000000..4e93449 --- /dev/null +++ b/binary_search_tree/lowest_common_ancestor.py @@ -0,0 +1,55 @@ +""" Lowest Common Ancestor in Binary Search Tree +""" + + +class Node: + """ Node contains actual data and address to left and right node """ + def __init__(self, data): + self.data = data + self.left = None + self.right = None + + +class BinarySearchTree: + """ Binary Search Tree Implementation """ + def __init__(self): + self.root = None + + def insert(self, data): + """ inserts new integer data into the tree at the position, so that + the binary search tree property is maintained. + """ + def _insert(root, data): + """ recursive internal method which works on node level """ + if root is None: + root = Node(data) + elif data <= root.data: + root.left = _insert(root.left, data) + else: + root.right = _insert(root.right, data) + return root + + self.root = _insert(self.root, data) + + +def lowest_common_ancestor(root, a, b): + """ lowest common ancestor in BST """ + if root.data > max(a, b): + return lowest_common_ancestor(root.left, a, b) + if root.data < min(a, b): + return lowest_common_ancestor(root.right, a, b) + return root + + +def main(): + """ operational function """ + bst = BinarySearchTree() + for elem in [9, 5, 3, 10, 6, 1, 7, 4]: + bst.insert(elem) + + lca_node = lowest_common_ancestor(bst.root, 5, 4) + print("lowest_common_ancestor for 5 and 4:", lca_node.data) + + +if __name__ == "__main__": + main() From 91f90a0b37af28acfdb595d2ae992f5b986c7b65 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Mon, 28 Dec 2020 21:15:13 +0530 Subject: [PATCH 155/209] add binary tree depth first traversal --- binary_tree/depth_first_traversal.py | 61 ++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 binary_tree/depth_first_traversal.py diff --git a/binary_tree/depth_first_traversal.py b/binary_tree/depth_first_traversal.py new file mode 100644 index 0000000..dfd18c2 --- /dev/null +++ b/binary_tree/depth_first_traversal.py @@ -0,0 +1,61 @@ +""" Depth First Traversals of Binary Tree + - Inorder Traversals (left, root, right) + - Preorder Traversals (root, left, right) + - Postorder Traversals (left, righti, root) +""" + +class Node: + """ class representing node in binary tree """ + def __init__(self, data): + self.data = data + self.left = None + self.right = None + + +def inorder(root): + """ inorder traversal (left, root, right) """ + if root is not None: + inorder(root.left) + print(root.data, end=" ") + inorder(root.right) + + +def preorder(root): + """ preorder traversal (root, left, right) """ + if root is not None: + print(root.data, end=" ") + preorder(root.left) + preorder(root.right) + + +def postorder(root): + """ postorder traversal (left, right, root) """ + if root is not None: + postorder(root.left) + postorder(root.right) + print(root.data, end=" ") + + +def main(): + """ operational function """ + root = Node(1) + root.left = Node(2) + root.right = Node(3) + root.left.left = Node(4) + root.left.right = Node(5) + + print("Inorder Traversals: ", end="") + inorder(root) + print() + + print("Preorder Traversals: ", end="") + preorder(root) + print() + + print("Postorder Traversals: ", end="") + postorder(root) + print() + + +if __name__ == "__main__": + main() From 490a5aa6c6432eed3835831a940529db54c4899f Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Mon, 28 Dec 2020 21:15:51 +0530 Subject: [PATCH 156/209] add binary tree level order traversal --- binary_tree/level_order_traversal.py | 44 ++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 binary_tree/level_order_traversal.py diff --git a/binary_tree/level_order_traversal.py b/binary_tree/level_order_traversal.py new file mode 100644 index 0000000..085c32c --- /dev/null +++ b/binary_tree/level_order_traversal.py @@ -0,0 +1,44 @@ +""" Level Order Traversal On Binary Tree +""" + +from collections import deque + + +class Node: + """ class representing node in binary tree """ + def __init__(self, data): + self.data = data + self.left = None + self.right = None + + +def level_order(root): + """ level order traversal of binary tree using queue """ + if root is None: + return + + queue = deque([root]) + + while queue: + node = queue.popleft() + print(node.data, end=" ") + if node.left is not None: + queue.append(node.left) + if node.right is not None: + queue.append(node.right) + + +def main(): + """ operational function """ + + root = Node(1) + root.left = Node(2) + root.right = Node(3) + root.left.left = Node(4) + root.left.right = Node(5) + + level_order(root) + + +if __name__ == "__main__": + main() From 001ddb637d713ff8e1361c94ef080a904a0d7c5a Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Tue, 29 Dec 2020 23:57:53 +0530 Subject: [PATCH 157/209] add binary tree vertical order traversal algo --- binary_tree/vertical_order_traversal.py | 51 +++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 binary_tree/vertical_order_traversal.py diff --git a/binary_tree/vertical_order_traversal.py b/binary_tree/vertical_order_traversal.py new file mode 100644 index 0000000..5fead45 --- /dev/null +++ b/binary_tree/vertical_order_traversal.py @@ -0,0 +1,51 @@ +""" Vertical Order Traversal On Binary Tree +""" + +from collections import defaultdict + + +class Node: + """ class representing node in binary tree """ + def __init__(self, data): + self.data = data + self.left = None + self.right = None + + +def preorder(root, horizontal_dist, hd_map): + if root is None: + return + + hd_map[horizontal_dist].append(root.data) + preorder(root.left, horizontal_dist-1, hd_map) + preorder(root.right, horizontal_dist+1, hd_map) + + +def vertical_order(root): + """ vertical order traversal of binary tree """ + hd_map = defaultdict(list) + horizontal_dist = 0 + preorder(root, horizontal_dist, hd_map) + for key, value in hd_map.items(): + print(f"{key}: {value}") + + +def main(): + """ operational function """ + + root = Node(2) + root.left = Node(7) + root.left.left = Node(2) + root.left.right = Node(6) + root.left.right.left = Node(5) + root.left.right.right = Node(11) + root.right = Node(5) + root.right.right = Node(9) + root.right.right.left = Node(4) + + vertical_order(root) + + +if __name__ == "__main__": + main() + From 7c9f4a3fc9a51814e1e8a3fa42490d8c82f6c51d Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Fri, 8 Jan 2021 23:58:21 +0530 Subject: [PATCH 158/209] add binary tree lowest common ancestor algo --- binary_tree/lowest_common_ancestor.py | 55 +++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 binary_tree/lowest_common_ancestor.py diff --git a/binary_tree/lowest_common_ancestor.py b/binary_tree/lowest_common_ancestor.py new file mode 100644 index 0000000..e8fe876 --- /dev/null +++ b/binary_tree/lowest_common_ancestor.py @@ -0,0 +1,55 @@ +""" Lowest Common Ancestor in Binary Tree +""" + + +class Node: + """ Node contains actual data and address to left and right node """ + def __init__(self, data): + self.data = data + self.left = None + self.right = None + + +def lowest_common_ancestor(root, a, b): + """ lowest common ancestor in BST """ + if root is None: + return None + + if root.data == a or root.data == b: + return root + + left = lowest_common_ancestor(root.left, a, b) + right = lowest_common_ancestor(root.right, a, b) + + if left is not None and right is not None: + return root + + if left is None and right is None: + return None + + if left is not None: + return left + else: + return right + + +def main(): + """ operational function """ + root = Node(2) + root.left = Node(7) + root.left.left = Node(21) + root.left.right = Node(6) + root.left.right.left = Node(5) + root.left.right.right = Node(11) + root.right = Node(5) + root.right.right = Node(9) + root.right.right.left = Node(4) + root.right.right.left.right = Node(40) + root.right.right.left.right.right = Node(46) + + lca_node = lowest_common_ancestor(root, 21, 11) + print("lowest_common_ancestor for 21 and 11:", lca_node.data) + + +if __name__ == "__main__": + main() From 333c1b7342cbf93393bc35d98dc98d0f5a3bbad4 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sat, 9 Jan 2021 23:26:12 +0530 Subject: [PATCH 159/209] rename cpp heap folder --- cpp/Heap/{Heap => }/HeapException.hpp | 0 cpp/Heap/{Heap => }/Makefile | 0 cpp/Heap/{Heap => }/MaxHeap.hpp | 0 cpp/Heap/{Heap => }/MinHeap.hpp | 0 cpp/Heap/{Heap => }/test_Heap.cpp | 0 5 files changed, 0 insertions(+), 0 deletions(-) rename cpp/Heap/{Heap => }/HeapException.hpp (100%) rename cpp/Heap/{Heap => }/Makefile (100%) rename cpp/Heap/{Heap => }/MaxHeap.hpp (100%) rename cpp/Heap/{Heap => }/MinHeap.hpp (100%) rename cpp/Heap/{Heap => }/test_Heap.cpp (100%) diff --git a/cpp/Heap/Heap/HeapException.hpp b/cpp/Heap/HeapException.hpp similarity index 100% rename from cpp/Heap/Heap/HeapException.hpp rename to cpp/Heap/HeapException.hpp diff --git a/cpp/Heap/Heap/Makefile b/cpp/Heap/Makefile similarity index 100% rename from cpp/Heap/Heap/Makefile rename to cpp/Heap/Makefile diff --git a/cpp/Heap/Heap/MaxHeap.hpp b/cpp/Heap/MaxHeap.hpp similarity index 100% rename from cpp/Heap/Heap/MaxHeap.hpp rename to cpp/Heap/MaxHeap.hpp diff --git a/cpp/Heap/Heap/MinHeap.hpp b/cpp/Heap/MinHeap.hpp similarity index 100% rename from cpp/Heap/Heap/MinHeap.hpp rename to cpp/Heap/MinHeap.hpp diff --git a/cpp/Heap/Heap/test_Heap.cpp b/cpp/Heap/test_Heap.cpp similarity index 100% rename from cpp/Heap/Heap/test_Heap.cpp rename to cpp/Heap/test_Heap.cpp From cccf2521e605a5605c4c639535b59d297ea46e4f Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sat, 9 Jan 2021 23:26:35 +0530 Subject: [PATCH 160/209] remove untested nqueen --- cpp/BinarySearchTree/Nqueen | 108 ------------------------------------ 1 file changed, 108 deletions(-) delete mode 100644 cpp/BinarySearchTree/Nqueen diff --git a/cpp/BinarySearchTree/Nqueen b/cpp/BinarySearchTree/Nqueen deleted file mode 100644 index 0f0e85a..0000000 --- a/cpp/BinarySearchTree/Nqueen +++ /dev/null @@ -1,108 +0,0 @@ -/* C/C++ program to solve N Queen Problem using - backtracking */ -#define N 4 -#include -#include - -/* A utility function to print solution */ -void printSolution(int board[N][N]) -{ - for (int i = 0; i < N; i++) { - for (int j = 0; j < N; j++) - printf(" %d ", board[i][j]); - printf("\n"); - } -} - -/* A utility function to check if a queen can - be placed on board[row][col]. Note that this - function is called when "col" queens are - already placed in columns from 0 to col -1. - So we need to check only left side for - attacking queens */ -bool isSafe(int board[N][N], int row, int col) -{ - int i, j; - - /* Check this row on left side */ - for (i = 0; i < col; i++) - if (board[row][i]) - return false; - - /* Check upper diagonal on left side */ - for (i = row, j = col; i >= 0 && j >= 0; i--, j--) - if (board[i][j]) - return false; - - /* Check lower diagonal on left side */ - for (i = row, j = col; j >= 0 && i < N; i++, j--) - if (board[i][j]) - return false; - - return true; -} - -/* A recursive utility function to solve N - Queen problem */ -bool solveNQUtil(int board[N][N], int col) -{ - /* base case: If all queens are placed - then return true */ - if (col >= N) - return true; - - /* Consider this column and try placing - this queen in all rows one by one */ - for (int i = 0; i < N; i++) { - /* Check if the queen can be placed on - board[i][col] */ - if (isSafe(board, i, col)) { - /* Place this queen in board[i][col] */ - board[i][col] = 1; - - /* recur to place rest of the queens */ - if (solveNQUtil(board, col + 1)) - return true; - - /* If placing queen in board[i][col] - doesn't lead to a solution, then - remove queen from board[i][col] */ - board[i][col] = 0; // BACKTRACK - } - } - - /* If the queen cannot be placed in any row in - this colum col then return false */ - return false; -} - -/* This function solves the N Queen problem using - Backtracking. It mainly uses solveNQUtil() to - solve the problem. It returns false if queens - cannot be placed, otherwise, return true and - prints placement of queens in the form of 1s. - Please note that there may be more than one - solutions, this function prints one of the - feasible solutions.*/ -bool solveNQ() -{ - int board[N][N] = { { 0, 0, 0, 0 }, - { 0, 0, 0, 0 }, - { 0, 0, 0, 0 }, - { 0, 0, 0, 0 } }; - - if (solveNQUtil(board, 0) == false) { - printf("Solution does not exist"); - return false; - } - - printSolution(board); - return true; -} - -// driver program to test above function -int main() -{ - solveNQ(); - return 0; -} \ No newline at end of file From 15bee7071880237ca3952d2c6db34f1853e41c62 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sun, 10 Jan 2021 23:21:24 +0530 Subject: [PATCH 161/209] add binary tree top view algo --- binary_tree/top_view.py | 57 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 binary_tree/top_view.py diff --git a/binary_tree/top_view.py b/binary_tree/top_view.py new file mode 100644 index 0000000..4b5e39f --- /dev/null +++ b/binary_tree/top_view.py @@ -0,0 +1,57 @@ +""" Top View of Binary Tree +""" + +from collections import deque + + +class Node: + """ class representing node in binary tree """ + def __init__(self, data): + self.data = data + self.left = None + self.right = None + +def top_view(root): + """ top view of binary tree """ + if root is None: + return + + level_map = {} + + # queue of root and it's corresponding horizontal distance + queue = deque([(root, 0)]) + + while queue: + node, hd = queue.popleft() + if hd not in level_map: + print(node.data, end=" ") + level_map[hd] = node.data + + if node.left is not None: + queue.append((node.left, hd-1)) + + if node.right is not None: + queue.append((node.right, hd+1)) + + +def main(): + """ operational function """ + root = Node(2) + root.left = Node(7) + root.left.left = Node(2) + root.left.right = Node(6) + root.left.right.left = Node(5) + root.left.right.right = Node(11) + root.right = Node(5) + root.right.right = Node(9) + root.right.right.left = Node(4) + root.right.right.left.right = Node(40) + root.right.right.left.right.right = Node(46) + + top_view(root) + + +if __name__ == "__main__": + main() + + From 13802667699efe210ce09b507398c5cc512f03c8 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Tue, 12 Jan 2021 00:37:39 +0530 Subject: [PATCH 162/209] add find duplicates in array algo --- array/duplicates_array.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 array/duplicates_array.py diff --git a/array/duplicates_array.py b/array/duplicates_array.py new file mode 100644 index 0000000..929290c --- /dev/null +++ b/array/duplicates_array.py @@ -0,0 +1,32 @@ +""" +Problem: +The problem is that we want to find duplicates in a one-dimensional +array of integers in O(N) running time where the integer values are +smaller than the length of the array! + +Solution: +1. brute-force approach (comparing items with all the rest) but it has + O(N^2) running time complexity +2. hashmap (dict in python): Traverse the given array and try to insert each + item in a hashtable with the value as the key. If you can not insert the + item it means it is duplicate + problem: not an in-place algorithm +3. Absolute values: with this approach we can achieve O(N) running time + algorithm that is in-place as well + + check the sign of T[abs(T[i])]: + if it is positive: + flip the sign T[abs(T[i])] = -T[abs(T[i])] + else + the given i item is a repetition +""" + +def duplicates(arr): + for num in arr: + if arr[abs(num)] >= 0: + arr[abs(num)] = - arr[abs(num)] + else: + print("duplicate entry:", abs(num)) + + +duplicates([1, 3, 4, 5, 5, 3, 4, 2]) From 1cc30eaa6cdf25729f63a5c3a6d2a9a40c8ba77f Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Wed, 13 Jan 2021 22:13:11 +0530 Subject: [PATCH 163/209] add inplace reverse array algo --- array/reverse_array_inplace.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 array/reverse_array_inplace.py diff --git a/array/reverse_array_inplace.py b/array/reverse_array_inplace.py new file mode 100644 index 0000000..8afef5f --- /dev/null +++ b/array/reverse_array_inplace.py @@ -0,0 +1,12 @@ +""" The problem is that we want to reverse a T[] array in O(N) linear + time complexity and we want the algorithm to be in-place as well! + + For example: input is [1,2,3,4,5] then the output is [5,4,3,2,1] +""" + +arr = [1, 2, 3, 4, 5, 6] + +for i in range(len(arr) // 2): + arr[i], arr[len(arr)-1-i] = arr[len(arr)-1-i], arr[i] + +print(arr) From c0688a8b28eba0d40358b33f1c2245697b4634d6 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Thu, 14 Jan 2021 23:49:38 +0530 Subject: [PATCH 164/209] add array largest sum subarray algo --- array/largest_sum_subarray.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 array/largest_sum_subarray.py diff --git a/array/largest_sum_subarray.py b/array/largest_sum_subarray.py new file mode 100644 index 0000000..e6d7e68 --- /dev/null +++ b/array/largest_sum_subarray.py @@ -0,0 +1,25 @@ +""" algorithm to find the sum of contiguous subarray within a one-dimensional + array of numbers which has the largest sum! + +Solution: + - If the array contains all negative numbers: the solution is the number + in the array with the smallest magnitude + - If the array contains all positive numbers: solution is the sum of all + the items + - If it contains negative and positive numbers as well thats when the + problem gets a bit more complex + solution: Kadane's Algorithm +""" + +def kadane_algorithm(nums): + max_global = nums[0] + max_current = nums[0] + + for i in range(1, len(nums)): + max_current = max(nums[i], max_current + nums[i]) + if max_current > max_global: + max_global = max_current + + return max_global + +print(kadane_algorithm([1, -2, 3, 4, -5, 8])) From 004ee7283084cc5b3732828665ca9b98d223704e Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sat, 16 Jan 2021 23:38:23 +0530 Subject: [PATCH 165/209] add array largest rectangle histogram algo --- array/largest_rectangle_histogram.py | 45 ++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 array/largest_rectangle_histogram.py diff --git a/array/largest_rectangle_histogram.py b/array/largest_rectangle_histogram.py new file mode 100644 index 0000000..f0ba736 --- /dev/null +++ b/array/largest_rectangle_histogram.py @@ -0,0 +1,45 @@ +""" Largest Rectangle in Histogram + leetcode: https://leetcode.com/problems/largest-rectangle-in-histogram/ + + Given n non-negative integers representing the histogram's bar height + where the width of each bar is 1, find the area of largest rectangle in + the histogram. + + Sample: + Input: [2,1,5,6,2,3] + Output: 10 +""" + +from collections import deque + + +def largest_rectangle_area(heights): + """ return largest rectangle in histogram """ + stack = [-1] + max_area = 0 + + for i in range(len(heights)): + # we are saving indexes in stack that is why we comparing last element in stack + # with current height to check if last element in stack not bigger then + # current element + while stack[-1] != -1 and heights[stack[-1]] >= heights[i]: + lastElementIndex = stack.pop() + max_area = max(max_area, heights[lastElementIndex] * (i - stack[-1] - 1)) + stack.append(i) + + # we went through all elements of heights array + # let's check if we have something left in stack + while stack[-1] != -1: + lastElementIndex = stack.pop() + max_area = max(max_area, heights[lastElementIndex] * (len(heights) - stack[-1] - 1)) + + return max_area + + +def main(): + """ operational function """ + print(largest_rectangle_area([2, 1, 5, 6, 2, 3])) + + +if __name__ == "__main__": + main() From d92cc7e3a6e2cdb65b1b5267635ee5958db12cba Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Wed, 20 Jan 2021 23:19:43 +0530 Subject: [PATCH 166/209] add anagram algo --- misc/anagram.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 misc/anagram.py diff --git a/misc/anagram.py b/misc/anagram.py new file mode 100644 index 0000000..51561e6 --- /dev/null +++ b/misc/anagram.py @@ -0,0 +1,25 @@ +""" check whether two words (or phrases) are anagrams or not + +Solution: + Method 1: Sorting + Method 2: Counting Characters +""" + +def check_anagram(str1, str2): + if len(str1) != len(str2): + return False + + count = [0] * 256 + for i in range(len(str1)): + count[ord(str1[i])] += 1 + count[ord(str2[i])] -= 1 + + for i in count: + if i != 0: + return False + + return True + + +print(check_anagram('restful', 'fluster')) # True +print(check_anagram('restful', 'flustez')) # False From c6f814d9732374259a2478666247adbd1a5eb37c Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Thu, 21 Jan 2021 23:20:31 +0530 Subject: [PATCH 167/209] add integer reversion algo --- misc/integer_reversion.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 misc/integer_reversion.py diff --git a/misc/integer_reversion.py b/misc/integer_reversion.py new file mode 100644 index 0000000..9999080 --- /dev/null +++ b/misc/integer_reversion.py @@ -0,0 +1,15 @@ +""" Design an efficient algorithm to reverse a given integer. For example if + the input of the algorithm is 1234 then the output should be 4321. +""" + +def integer_reverse(number): + result = 0 + + while number: + remainder = number % 10 + result = result * 10 + remainder + number = number // 10 + + return result + +print(integer_reverse(1234)) From 33c883d893dccdc4eb2b83aadb917f5227fc1ec6 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sun, 24 Jan 2021 14:48:59 +0530 Subject: [PATCH 168/209] add palindrome check algo --- misc/palindrome_check.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 misc/palindrome_check.py diff --git a/misc/palindrome_check.py b/misc/palindrome_check.py new file mode 100644 index 0000000..babb9fc --- /dev/null +++ b/misc/palindrome_check.py @@ -0,0 +1,17 @@ +""" Design an optimal algorithm for checking whether a given string is + palindrome or not! +""" + +def check_palindrome(original): + for i in range(len(original) // 2): + if original[i] != original[len(original)-1-i]: + return False + return True + + +def check_palindrome_pythonic(original): + return original == original[::-1] + + +print(check_palindrome_pythonic("madam")) +print(check_palindrome("hello")) From f5c29b387e6e8b593f726bd82e6cd06f5da714d8 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sun, 24 Jan 2021 14:51:35 +0530 Subject: [PATCH 169/209] update docstring --- linked_list/nth_to_last_node.py | 6 +++--- linked_list/remove_duplicates_singly.py | 2 +- linked_list/reverse_singly_list.py | 4 +++- linked_list/rotate.py | 6 +++--- 4 files changed, 10 insertions(+), 8 deletions(-) diff --git a/linked_list/nth_to_last_node.py b/linked_list/nth_to_last_node.py index f2fd605..3442186 100644 --- a/linked_list/nth_to_last_node.py +++ b/linked_list/nth_to_last_node.py @@ -1,6 +1,6 @@ -""" Remove duplicates from linked list - input: 1 -> 6 -> 1 -> 4 -> 2 -> 2 -> 4 - output: 1 -> 6 -> 4 -> 2 +""" Return nth element from last node + input: A -> B -> C -> D + output: B """ class Node: diff --git a/linked_list/remove_duplicates_singly.py b/linked_list/remove_duplicates_singly.py index 0619042..41c9729 100644 --- a/linked_list/remove_duplicates_singly.py +++ b/linked_list/remove_duplicates_singly.py @@ -1,4 +1,4 @@ -""" Remove duplicates from linked list +""" Remove duplicates from singly linked list input: 1 -> 6 -> 1 -> 4 -> 2 -> 2 -> 4 output: 1 -> 6 -> 4 -> 2 """ diff --git a/linked_list/reverse_singly_list.py b/linked_list/reverse_singly_list.py index 39a9d42..7debae6 100644 --- a/linked_list/reverse_singly_list.py +++ b/linked_list/reverse_singly_list.py @@ -1,4 +1,6 @@ -""" Reverse linked lists +""" Reverse singly linked lists + input: 1 -> 5 -> 7 -> 9 -> 10 + output: 10 -> 9 -> 7 -> 5 -> 1 """ class Node: diff --git a/linked_list/rotate.py b/linked_list/rotate.py index 8eb5141..c0c5dd2 100644 --- a/linked_list/rotate.py +++ b/linked_list/rotate.py @@ -1,6 +1,6 @@ -""" Remove duplicates from linked list - input: 1 -> 6 -> 1 -> 4 -> 2 -> 2 -> 4 - output: 1 -> 6 -> 4 -> 2 +""" Rotate singly linked list n times + input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 + output: 5 -> 6 -> 1 -> 2 -> 3 -> 4 """ class Node: From 2c9e998b8a651283019137ea62370ebc91598f7c Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sat, 30 Jan 2021 23:20:36 +0530 Subject: [PATCH 170/209] add basic graph algo --- graph/library/graph.py | 78 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 graph/library/graph.py diff --git a/graph/library/graph.py b/graph/library/graph.py new file mode 100644 index 0000000..7366961 --- /dev/null +++ b/graph/library/graph.py @@ -0,0 +1,78 @@ +""" Implementation of Graph Data Structure and Graph Theory Algorithms + in Python +""" + +class Graph: + """ Graph data structure Wrapper""" + def __init__(self, graph_dict=None): + """ initialize a graph object + if no dictionary or none is given, an empty dictionary + will be used + :param graph_dict: initial graph setup + """ + if not graph_dict: + graph_dict = {} + self._graph_dict = graph_dict + + def is_vertex(self, node): + """ Returns true if node is vertex of graph, otherwise false """ + return node in self._graph_dict + + def add_vertex(self, node): + """ Adds new vertex to graph. If vertex is already present in graph, + no action will take place. + :param node: new node to be added to graph + """ + if node not in self._graph_dict: + self._graph_dict[node] = [] + + def add_edge(self, node, neighbour): + """ Adds new directed edge to graph starting from 'node' to 'neighbor' + It will insert node to graph, if the node is not already present + :param node: starting graph vertex + :param neighbour: ending graph vertex + """ + if node not in self._graph_dict: + self.add_vertex(node) + if neighbour not in self._graph_dict: + self.add_vertex(neighbour) + self._graph_dict[node].append(neighbour) + + def order(self): + """ Order returns the order of a graph i.e. number of vertices + :returns: returns number of vertices + """ + return len(list(self._graph_dict)) + + def vertices(self): + """ return list of all vertices in graph """ + return list(self._graph_dict) + + def neighbours(self, node): + """ returns all vertices of given node + :param node: graph vertex + :returns: all node neighbour vertices + """ + return self._graph_dict[node] + + def show_edges(self): + """ show all the graph edges """ + for node in self._graph_dict: + for neighbour in self._graph_dict[node]: + print(f"{node} -> {neighbour}") + + +def main(): + """ Operational Function """ + g_dict = { + '1': ['2', '3'], + '2': ['3', '1'], + '3': ['1', '2', '4'], + '4': ['3'] + } + g_obj = Graph(g_dict) + g_obj.show_edges() + + +if __name__ == "__main__": + main() From 973362dd0d695a5e7bb03c520a51d58074b69567 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Thu, 4 Feb 2021 23:45:12 +0530 Subject: [PATCH 171/209] add graph depth first search algo --- graph/depth_first_search.py | 68 +++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 graph/depth_first_search.py diff --git a/graph/depth_first_search.py b/graph/depth_first_search.py new file mode 100644 index 0000000..94bd078 --- /dev/null +++ b/graph/depth_first_search.py @@ -0,0 +1,68 @@ +""" Depth First Search Graph Traversal Algorithm + + Depth-first search (DFS) is an algorithm for traversing or searching + graph data structures. The algorithm starts at the root node (selecting + some arbitrary node as the root node in the case of a graph) and explores + as far as possible along each branch before backtracking. + + Time Complexity: O(V+E) +""" + +from collections import deque + + +def depth_first_search_recursion(graph, root): + """ Depth first search graph traversal algorithm - iterative approach """ + def dfs_util(graph, vertex, visited): + visited.add(vertex) + print(vertex, end=" ") + + for neighbour in graph[vertex]: + if neighbour not in visited: + dfs_util(graph, neighbour, visited) + + visited = set() + dfs_util(graph, root, visited) + + +def depth_first_search_iteration(graph, root): + """ Depth first search graph traversal algorithm - iterative approach """ + visited = set() + stack = deque([root]) + visited.add(root) + + while stack: + vertex = stack.pop() + print(vertex, end=" ") + + for neighbour in graph[vertex]: + if neighbour not in visited: + visited.add(neighbour) + stack.append(neighbour) + + +def main(): + """ operational function """ + graph = { + "A": ["B", "C", "D"], + "B": ["E"], + "C": ["F", "G"], + "D": ["H"], + "E": ["I"], + "F": ["J"], + "G": [], + "H": [], + "I": [], + "J": [] + } + print("Depth First Traversal (Recursion): ", end="") + depth_first_search_recursion(graph, 'A') + print() + + print("Depth First Traversal (Iteration): ", end="") + depth_first_search_iteration(graph, 'A') + print() + + +if __name__ == "__main__": + main() From 66daa2dc8eb09abc94676fc7b3d7e43b80c84206 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Mon, 12 Apr 2021 23:26:50 +0530 Subject: [PATCH 172/209] update README.md --- README.md | 134 ++++++++++++++++++++++++++++++++++++------------------ 1 file changed, 89 insertions(+), 45 deletions(-) diff --git a/README.md b/README.md index 8716e79..588cf4d 100644 --- a/README.md +++ b/README.md @@ -5,52 +5,96 @@ Data Structure Libraries and Algorithms implementation in C++ This repository is meant to be used as a reference to learn data structure and algorithm. +## Algorithms in Other Languages +* [C](c_language/) +* [C++](cpp/) +* [Golang](golang/) + ## Data structure -* [Dynamic Connectivity](DynamicConnectivity/) - * [Quick Find](DynamicConnectivity/QuickFind.cpp) - * [Quick Union](DynamicConnectivity/QuickUnion.cpp) - * [Weighted Quick Union](DynamicConnectivity/WeightedQuickUnion.cpp) -* [Sorting Algorithms](Sort/) - * [Bubble Sort](Sort/BubbleSort.cpp) - * [Counting Sort](Sort/CountingSort.cpp) - * [Gnome Sort](Sort/GnomeSort.cpp) - * [Heap Sort](Sort/HeapSort.cpp) - * [Insertion Sort](Sort/InsertionSort.cpp) - * [Merge Sort](Sort/MergeSort.cpp) - * [Merge Bottom Up Sort](Sort/MergeButtomUp.cpp) - * [Merge Optimize Sort](Sort/MergeOptimizeSort.cpp) - * [Odd Even Sort](Sort/OddEvenSort.cpp) - * [Quick Sort](Sort/QuickSort.cpp) - * [Quick 3Way Sort](Sort/Quick3WaySort.cpp) - * [Quick Optimize Sort](Sort/QuickOptimizeSort.cpp) - * [Quick Select](Sort/QuickSelect.cpp) - * [Selection Sort](Sort/SelectionSort.cpp) - * [Shell Sort](Sort/ShellSort.cpp) -* [Stack (Array Implementation)](Stack/Stack/) - * [Balanced Paranthesis](Stack/balancedParanthesis.cpp) - * [Infix to Prefix](Stack/infixToPostfix.cpp) - * [Track Current Maximum](Stack/trackingCurrentMax.cpp) -* [Queue (Array Implementation)](Queue/Queue/) - * [Reverse Queue](Queue/ReverseQueue.cpp) - * [Sort Queue Without Extra Space](Queue/SortQueueWithoutExtraSpace.cpp) -* [LinkedList](LinkedList/LinkedList) - * [Count Frequency](LinkedList/countFrequency.cpp) - * [Detect Loop](LinkedList/detectLoop.cpp) - * [Find Middle](LinkedList/findMiddle.cpp) - * [Get Nth Node from End](LinkedList/getNthNodeFromEnd.cpp) - * [Length of Loop](LinkedList/lengthOfLoop.cpp) -* Suffle - * [Using Fisher-Yates (Knuth) shuffling algorithm](Shuffle/Shuffle.cpp) -* [Binary Search Tree](BinarySearchTree/BST/) - * [BFS Traversal](BinarySearchTree/bfsTraversal.cpp) - * [DFS Traversal](BinarySearchTree/dfsTraversal.cpp) - * [Inorder Successor](BinarySearchTree/inorderSuccessor.cpp) - * [Is BST?](BinarySearchTree/isBST.cpp) -* [Binary Heap](Heap/Heap) - * [Min Heap](Heap/Heap/MinHeap.cpp) - * [Max Heap](Heap/Heap/MaxHeap.cpp) -* Search - * [Binary Search](Search/BinarySearch.h) +* [Array](array) + * [Find duplicates in array](array/duplicates_array.py) + * [Largest Rectangle in Histogram](array/largest_rectangle_histogram.py) + * [Largest Sum of Contiguous subarray within an array](array/largest_sum_subarray.py) + * [Inplace array reversal](array/reverse_array_inplace.py) +* [AVL Tree](avl_tree/avl_tree.py) +* [Binary Search Tree](binary_search_tree/library/binary_search_tree.py) + * [BFS Traversal](binary_search_tree/bfs_traversals.py) + * [Compare two BST](binary_search_tree/compare_two_bst.py) + * [DFS Traversal](binary_search_tree/dfs_traversals.py) + * [Is BST?](binary_search_tree/is_bst.py) + * [Lowest Common Ancestor](binary_search_tree/lowest_common_ancestor.py) +* [Binary Tree](binary_tree/) + * [Depth First Traversal](binary_tree/depth_first_traversal.py) + * [Level Order Traversal](binary_tree/level_order_traversal.py) + * [Lowest Common Ancestor](binary_tree/lowest_common_ancestor.py) + * [Top View](binary_tree/top_view.py) + * [Vertical Order Traversal](binary_tree/vertical_order_traversal.py) +* [Deque](deque/deque.py) +* [Dynamic Connectivity](dynamic_connectivity/) + * [Quick Find](dynamic_connectivity/quick_find.py) + * [Quick Union](dynamic_connectivity/quick_union.py) + * [Weighted Quick Union](dynamic_connectivity/weighted_quick_union.py) +* [Graph](graph/library/graph.py) + * [Bellman Ford Algorithm](graph/bellman_ford_algorithm.py) + * [Breadth First Search](graph/breadth_first_search.py) + * [Connected Componenets](graph/connected_components.py) + * [Depth First Search](graph/depth_first_search.py) + * [Dijkstra Algorithm](graph/dijkstra_algorithm.py) + * [Kosaraju Algorithm](graph/kosaraju_algorithm.py) + * [Kruskal Algorithm](graph/kruskal_algorithm.py) + * [Prim Algorithm](graph/prim_algorithm.py) + * [Topological Sort](graph/topological_sort.py) +* [Hash Table](hashtable/) + * [Linear Probing](hashtable/linear_probing.py) + * [Separate Chaining](hashtable/separate_chaining.py) +* [Linked List](linked_list/) + * [Singly Linked List](linked_list/library/linked_list.py) + * [Find Middle Node](linked_list/find_middle_node.py) + * [Is Palindrome?](linked_list/is_palindrome.py) + * [Merge Two Sorted Linked List](linked_list/merge_two_sorted_list.py) + * [Node Swap](linked_list/node_swap.py) + * [Remove duplicates from Singly Linked List](linked_list/remove_duplicates_singly.py) + * [Return nth element from last node](linked_list/nth_to_last_node.py) + * [Reverse Singly Linked List](linked_list/reverse_singly_list.py) + * [Rotate](linked_list/rotate.py) + * [Sum of two lists](linked_list/sum_two_lists.py) + * [Doubly Linked List](linked_list/library/doubly_linked_list.py) + * [Remove duplicates from Doubly Linked List](linked_list/remove_duplicates_doubly.py) + * [Reverse Doubly Linked List](linked_list/reverse_doubly_list.py) + * [Circular Linked List](linked_list/library/circular_linked_list.py) + * [Is Circular?](linked_list/is_circular.py) + * [Josephus Circle](linked_list/josephus_circle.py) + * [Split Circular Lists](linked_list/split_circular_lists.py) +* [Miscellaneous](misc/) + * [Anagram](misc/anagram.py) + * [Integer Reversion](misc/integer_reversion.py) + * [Palindrome Check](misc/palindrome_check.py) +* [Priority Queue/Binary Heap](priority_queue/) + * [Min Heap](priority_queue/minheap.py) + * [Max Heap](priority_queue/maxheap.py) +* [Queue](queue/library/queue.py) +* [Red Black Tree](red_black_tree/red_black_tree.py) +* [Binary Search](search/binary_search.py) +* [Shuffle using Fisher-Yates (Knuth) shuffling algorithm](shuffle/shuffle.py) +* [Sorting Algorithms](sort/) + * [Bubble Sort](sort/bubble.py) + * [Gnome Sort](sort/gnome.py) + * [Insertion Sort](sort/insertion.py) + * [Merge Sort](sort/merge.py) + * [Odd Even Sort](sort/oddeven.py) + * [Quick Sort](sort/quick.py) + * [Selection Sort](sort/selection.py) + * [Shell Sort](sort/shell.py) +* [Stack](stack/library/stack.py) + * [Balanced Paranthesis](stack/balanced_parenthesis.py) + * [Track Current Minimum](stack/getmin_special_stack.py) + * [Integer to Binary](stack/integer_to_binary.py) + * [Queue using Stack](stack/queue_using_stack.py) + * [Two Stack in an Array](stack/two_stack_in_an_array.py) +* [Ternary Search Tries](ternary_search_tries/ternary_search_tries.py) +* [Tree](tree/library/tree.py) +* [Trie](trie/trie.py) + ## TO DO * Vertical Order Traversal of Tree From 7a370d0b61047dfb8289f3ca689e6a73a1478a64 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Fri, 28 May 2021 23:01:09 +0530 Subject: [PATCH 173/209] update c-lang readme --- c_language/README.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/c_language/README.md b/c_language/README.md index 2d6e4de..69500f4 100644 --- a/c_language/README.md +++ b/c_language/README.md @@ -2,6 +2,22 @@ Data Structure Libraries and Algorithms implementation in C Language. ## Data structure +* [Dynamic Connectivity](dynamic_connectivity/) + * [Quick Find](dynamic_connectivity/quick_find/) + * [Quick Union](dynamic_connectivity/quick_union/) +* [Sorting Algorithms](sorts/) + * [Bubble Sort](sorts/bubble_sort/) + * [Insertion Sort](sorts/insertion_sort/) + * [Selection Sort](sorts/selection_sort/) + * [Merge Sort](sorts/merge_sort/) + * [Quick Sort](sorts/quick_sort/) + * [Shell Sort](sorts/shell_sort/) + * [Generic](sorts/generic/) +* [Stack](stack/) + * [Array Implementation](stack/array_implementation/) + * [Generic Implementation](stack/generic_array_implementation/) +* [Queue](queue/) +* [Shuffle](shuffling/) ## Contribution Feel Free to contribute.
From 58f6f98936d77239620cfbfb41e04b04663092bb Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sat, 29 May 2021 19:12:31 +0530 Subject: [PATCH 174/209] update golang readme --- golang/README.md | 72 +++++++++++++++++++----------------------------- 1 file changed, 29 insertions(+), 43 deletions(-) diff --git a/golang/README.md b/golang/README.md index c4d4d18..bb86b45 100644 --- a/golang/README.md +++ b/golang/README.md @@ -1,56 +1,42 @@ # Algorithms Data Structure Libraries and Algorithms implementation in Go -[![GoDoc](https://godoc.org/github.com/x899/algorithms?status.svg)](https://godoc.org/github.com/x899/algorithms) [![Go Report Card](https://goreportcard.com/badge/github.com/x899/algorithms)](https://goreportcard.com/report/github.com/x899/algorithms) - **Disclaimer**
This repository is meant to be used as a reference to learn data structure and algorithm in Go programming language.
To reduce unnecessary language complexity, all the programs only uses integer or string dataset. -**Documentation**
-[Click to view goDoc Documentation](https://godoc.org/github.com/x899/algorithms) - ## Data structure -* Sorting Algorithms - * [Bubble Sort](https://en.wikipedia.org/wiki/Bubble_sort) - * [Selection Sort](https://en.wikipedia.org/wiki/Selection_sort) - * [Insertion Sort](https://en.wikipedia.org/wiki/Insertion_sort) - * [Merge Sort](https://en.wikipedia.org/wiki/Merge_sort) - * [Quick Sort](https://en.wikipedia.org/wiki/Quicksort) - * [Quick Select](https://en.wikipedia.org/wiki/Quickselect) - * [Shell Sort](https://en.wikipedia.org/wiki/Shellsort) - * [Heap Sort](https://en.wikipedia.org/wiki/Heapsort) -* [Stack (Array Implementation)](https://en.wikipedia.org/wiki/Stack_(abstract_data_type)) - * Infix to Postfix - * Infix to Prefix - * Infix Evaluation -* [Queue (Array Implementation)](https://en.wikipedia.org/wiki/Queue_(abstract_data_type)) +* [Binary Search Tree](bst/) * LinkedList - * [Singly Linked List](https://en.wikipedia.org/wiki/Linked_list) - * [Doubly Linked List](https://en.wikipedia.org/wiki/Doubly_linked_list) -* [Shuffle (Using Fisher-Yates (Knuth) shuffling algorithm)](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) -* [Binary Search Tree](https://en.wikipedia.org/wiki/Binary_search_tree) -* [Binary Heap](https://en.wikipedia.org/wiki/Binary_heap) - * Min Heap - * Max Heap -* [Red Black Tree](https://en.wikipedia.org/wiki/Red%E2%80%93black_tree) -* Search - * [Binary Search](https://en.wikipedia.org/wiki/Binary_search_algorithm) - -## TO DO -* Vertical Order Traversal of Tree -* Order Statistics of Tree -* Red Black Tree Deletion -* B-Tree -* Deque using circular array -* Tree Varient -* Graph Varient -* [cocktail sort](https://en.wikipedia.org/wiki/Cocktail_shaker_sort) -* [gnome sort](https://en.wikipedia.org/wiki/Gnome_sort) -* [comb sort](https://en.wikipedia.org/wiki/Comb_sort) -* [odd-even sort](https://en.wikipedia.org/wiki/Odd%E2%80%93even_sort) -* [counting sort](https://en.wikipedia.org/wiki/Counting_sort) + * [Singly Linked List](linkedlist/) + * [Doubly Linked List](doublylinkedlist/) +* [HashTable](hashtable/) +* [Binary Heap](heap/) + * [MaxHeap](heap/maxheap) + * [MinHeap](heap/minheap) +* [Queue](queue/) +* [Red Black Tree](redblacktree/) +* [Binary Search](search/) +* [Set](set/) +* [Shuffle (Using Fisher-Yates (Knuth) shuffling algorithm)](shuffle/) +* [Sorting Algorithms](sort/) + * [Bubble Sort](sort/bubble.go) + * [Counting Sort](sort/countingSort.go) + * [Gnome Sort](sort/gnome.go) + * [Heap Sort](sort/heap.go) + * [Insertion Sort](sort/insertion.go) + * [Merge Sort](sort/merge.go) + * [Odd Even Sort](sort/oddeven.go) + * [Quick Sort](sort/quick.go) + * [Quick Select](sort/quickselect.go) + * [Selection Sort](sort/selection.go) + * [Shell Sort](sort/shell.go) +* [Stack](stack/) + * [Infix to Postfix](stack/applications/infixtopostfix.go) + * [Infix to Prefix](stack/applications/infixtoprefix.go) + * [Infix Evaluation](stack/applications/infixevaluation.go) +* [Trie](trie/) ## Contribution Feel Free to contribute.
From df2af651912496c1a03d2c986e53f4e6cd976b4f Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Mon, 31 May 2021 14:43:53 +0530 Subject: [PATCH 175/209] add cpp readme file --- cpp/README.md | 82 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 cpp/README.md diff --git a/cpp/README.md b/cpp/README.md new file mode 100644 index 0000000..eb46cb9 --- /dev/null +++ b/cpp/README.md @@ -0,0 +1,82 @@ +# C++ Algorithms +Data Structure Libraries and Algorithms implementation in C++ + +**Disclaimer**
+This repository is meant to be used as a reference to learn data structure and +algorithm. + +## Data structure +* [Dynamic Connectivity](DynamicConnectivity/) + * [Quick Find](DynamicConnectivity/QuickFind.cpp) + * [Quick Union](DynamicConnectivity/QuickUnion.cpp) + * [Weighted Quick Union](DynamicConnectivity/WeightedQuickUnion.cpp) +* [Sorting Algorithms](Sort/) + * [Bubble Sort](Sort/BubbleSort.cpp) + * [Counting Sort](Sort/CountingSort.cpp) + * [Gnome Sort](Sort/GnomeSort.cpp) + * [Heap Sort](Sort/HeapSort.cpp) + * [Insertion Sort](Sort/InsertionSort.cpp) + * [Merge Sort](Sort/MergeSort.cpp) + * [Merge Bottom Up Sort](Sort/MergeButtomUp.cpp) + * [Merge Optimize Sort](Sort/MergeOptimizeSort.cpp) + * [Odd Even Sort](Sort/OddEvenSort.cpp) + * [Quick Sort](Sort/QuickSort.cpp) + * [Quick 3Way Sort](Sort/Quick3WaySort.cpp) + * [Quick Optimize Sort](Sort/QuickOptimizeSort.cpp) + * [Quick Select](Sort/QuickSelect.cpp) + * [Selection Sort](Sort/SelectionSort.cpp) + * [Shell Sort](Sort/ShellSort.cpp) +* [Stack (Array Implementation)](Stack/Stack/) + * [Balanced Paranthesis](Stack/balancedParanthesis.cpp) + * [Infix to Postfix](Stack/infixToPostfix.cpp) + * [Track Current Maximum](Stack/trackingCurrentMax.cpp) + * [Bracket Reversals](Stack/bracketReversals.cpp) + * [Delete Middle Element](Stack/deleteMiddleElement.cpp) +* [Queue (Array Implementation)](Queue/Queue/) + * [Reverse Queue](Queue/ReverseQueue.cpp) + * [Sort Queue Without Extra Space](Queue/SortQueueWithoutExtraSpace.cpp) +* [LinkedList](LinkedList/LinkedList) + * [Count Frequency](LinkedList/countFrequency.cpp) + * [Detect Loop](LinkedList/detectLoop.cpp) + * [Find Middle](LinkedList/findMiddle.cpp) + * [Get Nth Node from End](LinkedList/getNthNodeFromEnd.cpp) + * [Length of Loop](LinkedList/lengthOfLoop.cpp) +* Suffle + * [Using Fisher-Yates (Knuth) shuffling algorithm](Shuffle/Shuffle.cpp) +* [Binary Search Tree](BinarySearchTree/BST/) + * [BFS Traversal](BinarySearchTree/bfsTraversal.cpp) + * [DFS Traversal](BinarySearchTree/dfsTraversal.cpp) + * [Inorder Successor](BinarySearchTree/inorderSuccessor.cpp) + * [Is BST?](BinarySearchTree/isBST.cpp) +* [Binary Heap](Heap) + * [Min Heap](Heap/MinHeap.cpp) + * [Max Heap](Heap/MaxHeap.cpp) +* [Binary Search](Search/BinarySearch.h) +* [Red Black Tree](RedBlackTree/) +* [Bitwise](Bitwise/) + * [Find the element that appears once in an array where every other element appears twice](Bitwise/unique_number.cpp) + * [Count number of common elements between two arrays](Bitwise/common_elements.cpp) + * [Find the two non-repeating elements in an array of repeating elements](Bitwise/two_unique_numbers.cpp) + * [Print all subsequences of a string](Bitwise/string_subsequence.cpp) + * [Subset sum queries using bitset](Bitwise/subset_sum_queries_bitset.cpp) + * [Unique element in an array where all elements occur k times except one](Bitwise/unique_number_k_times.cpp) +* [Maths](Maths/) + * [Count Divisors of Factorial](Maths/count_divisors_of_factorial.cpp) + * [Find all divisors of a natural number](Maths/divisors.cpp) + * [Extended Euclidean Algorithm](Maths/extended_euclidean_algorithm.cpp) + * [GCD(HCF) of two numbers (Euclidean Algorithm)](Maths/gcd_euclidean.cpp) + * [Least Prime Factor of numbers till n](Maths/least_prime_factor.cpp) + * [Legendre’s formula (Given p and n, find the largest x such that p^x divides n!)](Maths/legendres_formula.cpp) + * [Modular Exponentiation (Power in Modular Arithmetic)](Maths/modular_exponential.cpp) + * [Modular Multiplicative Inverse](Maths/modular_multiplicative_inverse.cpp) + * [Total number of divisors for a given number](Maths/number_of_divisors.cpp) + * [Prime Factorization using Sieve O(log n) for multiple queries](Maths/prime_factors_using_sieve.cpp) + * [Print all prime factors of a given number](Maths/prime_factors.cpp) + * [Segmented Sieve (Print Primes in a Range)](Maths/segmented_sieve.cpp) + * [Sieve of Eratosthenes](Maths/sieve_of_eratosthenes.cpp) + * [Sum of all proper divisors of a natural number](Maths/sum_of_divisors.cpp) + + +## Contribution +Feel Free to contribute.
+Please follow standard C++ Guidelines. From 8308eefb77b36ce016033a4d189dd25a0ee2fc85 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Tue, 1 Jun 2021 10:29:42 +0530 Subject: [PATCH 176/209] update readme tabs to spaces --- README.md | 16 +++--- c_language/README.md | 20 +++---- cpp/README.md | 70 +++++++++++------------ golang/README.md | 32 +++++------ linked_list/library/doubly_linked_list.py | 3 +- 5 files changed, 71 insertions(+), 70 deletions(-) diff --git a/README.md b/README.md index 588cf4d..5e0964c 100644 --- a/README.md +++ b/README.md @@ -18,11 +18,11 @@ algorithm. * [Inplace array reversal](array/reverse_array_inplace.py) * [AVL Tree](avl_tree/avl_tree.py) * [Binary Search Tree](binary_search_tree/library/binary_search_tree.py) - * [BFS Traversal](binary_search_tree/bfs_traversals.py) - * [Compare two BST](binary_search_tree/compare_two_bst.py) - * [DFS Traversal](binary_search_tree/dfs_traversals.py) - * [Is BST?](binary_search_tree/is_bst.py) - * [Lowest Common Ancestor](binary_search_tree/lowest_common_ancestor.py) + * [BFS Traversal](binary_search_tree/bfs_traversals.py) + * [Compare two BST](binary_search_tree/compare_two_bst.py) + * [DFS Traversal](binary_search_tree/dfs_traversals.py) + * [Is BST?](binary_search_tree/is_bst.py) + * [Lowest Common Ancestor](binary_search_tree/lowest_common_ancestor.py) * [Binary Tree](binary_tree/) * [Depth First Traversal](binary_tree/depth_first_traversal.py) * [Level Order Traversal](binary_tree/level_order_traversal.py) @@ -31,9 +31,9 @@ algorithm. * [Vertical Order Traversal](binary_tree/vertical_order_traversal.py) * [Deque](deque/deque.py) * [Dynamic Connectivity](dynamic_connectivity/) - * [Quick Find](dynamic_connectivity/quick_find.py) - * [Quick Union](dynamic_connectivity/quick_union.py) - * [Weighted Quick Union](dynamic_connectivity/weighted_quick_union.py) + * [Quick Find](dynamic_connectivity/quick_find.py) + * [Quick Union](dynamic_connectivity/quick_union.py) + * [Weighted Quick Union](dynamic_connectivity/weighted_quick_union.py) * [Graph](graph/library/graph.py) * [Bellman Ford Algorithm](graph/bellman_ford_algorithm.py) * [Breadth First Search](graph/breadth_first_search.py) diff --git a/c_language/README.md b/c_language/README.md index 69500f4..c86006b 100644 --- a/c_language/README.md +++ b/c_language/README.md @@ -3,19 +3,19 @@ Data Structure Libraries and Algorithms implementation in C Language. ## Data structure * [Dynamic Connectivity](dynamic_connectivity/) - * [Quick Find](dynamic_connectivity/quick_find/) - * [Quick Union](dynamic_connectivity/quick_union/) + * [Quick Find](dynamic_connectivity/quick_find/) + * [Quick Union](dynamic_connectivity/quick_union/) * [Sorting Algorithms](sorts/) - * [Bubble Sort](sorts/bubble_sort/) - * [Insertion Sort](sorts/insertion_sort/) - * [Selection Sort](sorts/selection_sort/) - * [Merge Sort](sorts/merge_sort/) - * [Quick Sort](sorts/quick_sort/) - * [Shell Sort](sorts/shell_sort/) + * [Bubble Sort](sorts/bubble_sort/) + * [Insertion Sort](sorts/insertion_sort/) + * [Selection Sort](sorts/selection_sort/) + * [Merge Sort](sorts/merge_sort/) + * [Quick Sort](sorts/quick_sort/) + * [Shell Sort](sorts/shell_sort/) * [Generic](sorts/generic/) * [Stack](stack/) - * [Array Implementation](stack/array_implementation/) - * [Generic Implementation](stack/generic_array_implementation/) + * [Array Implementation](stack/array_implementation/) + * [Generic Implementation](stack/generic_array_implementation/) * [Queue](queue/) * [Shuffle](shuffling/) diff --git a/cpp/README.md b/cpp/README.md index eb46cb9..cfbeb32 100644 --- a/cpp/README.md +++ b/cpp/README.md @@ -7,47 +7,47 @@ algorithm. ## Data structure * [Dynamic Connectivity](DynamicConnectivity/) - * [Quick Find](DynamicConnectivity/QuickFind.cpp) - * [Quick Union](DynamicConnectivity/QuickUnion.cpp) - * [Weighted Quick Union](DynamicConnectivity/WeightedQuickUnion.cpp) + * [Quick Find](DynamicConnectivity/QuickFind.cpp) + * [Quick Union](DynamicConnectivity/QuickUnion.cpp) + * [Weighted Quick Union](DynamicConnectivity/WeightedQuickUnion.cpp) * [Sorting Algorithms](Sort/) - * [Bubble Sort](Sort/BubbleSort.cpp) - * [Counting Sort](Sort/CountingSort.cpp) - * [Gnome Sort](Sort/GnomeSort.cpp) - * [Heap Sort](Sort/HeapSort.cpp) - * [Insertion Sort](Sort/InsertionSort.cpp) - * [Merge Sort](Sort/MergeSort.cpp) - * [Merge Bottom Up Sort](Sort/MergeButtomUp.cpp) - * [Merge Optimize Sort](Sort/MergeOptimizeSort.cpp) - * [Odd Even Sort](Sort/OddEvenSort.cpp) - * [Quick Sort](Sort/QuickSort.cpp) - * [Quick 3Way Sort](Sort/Quick3WaySort.cpp) - * [Quick Optimize Sort](Sort/QuickOptimizeSort.cpp) - * [Quick Select](Sort/QuickSelect.cpp) - * [Selection Sort](Sort/SelectionSort.cpp) - * [Shell Sort](Sort/ShellSort.cpp) + * [Bubble Sort](Sort/BubbleSort.cpp) + * [Counting Sort](Sort/CountingSort.cpp) + * [Gnome Sort](Sort/GnomeSort.cpp) + * [Heap Sort](Sort/HeapSort.cpp) + * [Insertion Sort](Sort/InsertionSort.cpp) + * [Merge Sort](Sort/MergeSort.cpp) + * [Merge Bottom Up Sort](Sort/MergeButtomUp.cpp) + * [Merge Optimize Sort](Sort/MergeOptimizeSort.cpp) + * [Odd Even Sort](Sort/OddEvenSort.cpp) + * [Quick Sort](Sort/QuickSort.cpp) + * [Quick 3Way Sort](Sort/Quick3WaySort.cpp) + * [Quick Optimize Sort](Sort/QuickOptimizeSort.cpp) + * [Quick Select](Sort/QuickSelect.cpp) + * [Selection Sort](Sort/SelectionSort.cpp) + * [Shell Sort](Sort/ShellSort.cpp) * [Stack (Array Implementation)](Stack/Stack/) - * [Balanced Paranthesis](Stack/balancedParanthesis.cpp) - * [Infix to Postfix](Stack/infixToPostfix.cpp) - * [Track Current Maximum](Stack/trackingCurrentMax.cpp) - * [Bracket Reversals](Stack/bracketReversals.cpp) - * [Delete Middle Element](Stack/deleteMiddleElement.cpp) + * [Balanced Paranthesis](Stack/balancedParanthesis.cpp) + * [Infix to Postfix](Stack/infixToPostfix.cpp) + * [Track Current Maximum](Stack/trackingCurrentMax.cpp) + * [Bracket Reversals](Stack/bracketReversals.cpp) + * [Delete Middle Element](Stack/deleteMiddleElement.cpp) * [Queue (Array Implementation)](Queue/Queue/) - * [Reverse Queue](Queue/ReverseQueue.cpp) - * [Sort Queue Without Extra Space](Queue/SortQueueWithoutExtraSpace.cpp) + * [Reverse Queue](Queue/ReverseQueue.cpp) + * [Sort Queue Without Extra Space](Queue/SortQueueWithoutExtraSpace.cpp) * [LinkedList](LinkedList/LinkedList) - * [Count Frequency](LinkedList/countFrequency.cpp) - * [Detect Loop](LinkedList/detectLoop.cpp) - * [Find Middle](LinkedList/findMiddle.cpp) - * [Get Nth Node from End](LinkedList/getNthNodeFromEnd.cpp) - * [Length of Loop](LinkedList/lengthOfLoop.cpp) + * [Count Frequency](LinkedList/countFrequency.cpp) + * [Detect Loop](LinkedList/detectLoop.cpp) + * [Find Middle](LinkedList/findMiddle.cpp) + * [Get Nth Node from End](LinkedList/getNthNodeFromEnd.cpp) + * [Length of Loop](LinkedList/lengthOfLoop.cpp) * Suffle - * [Using Fisher-Yates (Knuth) shuffling algorithm](Shuffle/Shuffle.cpp) + * [Using Fisher-Yates (Knuth) shuffling algorithm](Shuffle/Shuffle.cpp) * [Binary Search Tree](BinarySearchTree/BST/) - * [BFS Traversal](BinarySearchTree/bfsTraversal.cpp) - * [DFS Traversal](BinarySearchTree/dfsTraversal.cpp) - * [Inorder Successor](BinarySearchTree/inorderSuccessor.cpp) - * [Is BST?](BinarySearchTree/isBST.cpp) + * [BFS Traversal](BinarySearchTree/bfsTraversal.cpp) + * [DFS Traversal](BinarySearchTree/dfsTraversal.cpp) + * [Inorder Successor](BinarySearchTree/inorderSuccessor.cpp) + * [Is BST?](BinarySearchTree/isBST.cpp) * [Binary Heap](Heap) * [Min Heap](Heap/MinHeap.cpp) * [Max Heap](Heap/MaxHeap.cpp) diff --git a/golang/README.md b/golang/README.md index bb86b45..3c937f6 100644 --- a/golang/README.md +++ b/golang/README.md @@ -9,8 +9,8 @@ complexity, all the programs only uses integer or string dataset. ## Data structure * [Binary Search Tree](bst/) * LinkedList - * [Singly Linked List](linkedlist/) - * [Doubly Linked List](doublylinkedlist/) + * [Singly Linked List](linkedlist/) + * [Doubly Linked List](doublylinkedlist/) * [HashTable](hashtable/) * [Binary Heap](heap/) * [MaxHeap](heap/maxheap) @@ -21,21 +21,21 @@ complexity, all the programs only uses integer or string dataset. * [Set](set/) * [Shuffle (Using Fisher-Yates (Knuth) shuffling algorithm)](shuffle/) * [Sorting Algorithms](sort/) - * [Bubble Sort](sort/bubble.go) - * [Counting Sort](sort/countingSort.go) - * [Gnome Sort](sort/gnome.go) - * [Heap Sort](sort/heap.go) - * [Insertion Sort](sort/insertion.go) - * [Merge Sort](sort/merge.go) - * [Odd Even Sort](sort/oddeven.go) - * [Quick Sort](sort/quick.go) - * [Quick Select](sort/quickselect.go) - * [Selection Sort](sort/selection.go) - * [Shell Sort](sort/shell.go) + * [Bubble Sort](sort/bubble.go) + * [Counting Sort](sort/countingSort.go) + * [Gnome Sort](sort/gnome.go) + * [Heap Sort](sort/heap.go) + * [Insertion Sort](sort/insertion.go) + * [Merge Sort](sort/merge.go) + * [Odd Even Sort](sort/oddeven.go) + * [Quick Sort](sort/quick.go) + * [Quick Select](sort/quickselect.go) + * [Selection Sort](sort/selection.go) + * [Shell Sort](sort/shell.go) * [Stack](stack/) - * [Infix to Postfix](stack/applications/infixtopostfix.go) - * [Infix to Prefix](stack/applications/infixtoprefix.go) - * [Infix Evaluation](stack/applications/infixevaluation.go) + * [Infix to Postfix](stack/applications/infixtopostfix.go) + * [Infix to Prefix](stack/applications/infixtoprefix.go) + * [Infix Evaluation](stack/applications/infixevaluation.go) * [Trie](trie/) ## Contribution diff --git a/linked_list/library/doubly_linked_list.py b/linked_list/library/doubly_linked_list.py index f40554a..dd6f901 100644 --- a/linked_list/library/doubly_linked_list.py +++ b/linked_list/library/doubly_linked_list.py @@ -20,7 +20,8 @@ def __init__(self): self.head = None def is_empty(self): - """ returns True if the linked list is empty. Otherwise, return False. """ + """ returns True if the linked list is empty. Otherwise, return False. + """ return self.head is None def __len__(self): From 3b731fd4b34beba9ecb7c5cefe9394dfcfbbe084 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Thu, 3 Jun 2021 20:04:21 +0530 Subject: [PATCH 177/209] add divisors algo --- cpp/Maths/divisors.cpp | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 cpp/Maths/divisors.cpp diff --git a/cpp/Maths/divisors.cpp b/cpp/Maths/divisors.cpp new file mode 100644 index 0000000..ff6e199 --- /dev/null +++ b/cpp/Maths/divisors.cpp @@ -0,0 +1,39 @@ +/** + * Find all divisors of a natural number + * + * Given a natural number n, print all distinct divisors of it. + * + * Examples: + * Input : n = 10 + * Output: 1 2 5 10 + * + * Input: n = 100 + * Output: 1 2 4 5 10 20 25 50 100 + * + * Input: n = 125 + * Output: 1 5 25 125 + * + * URL: https://www.geeksforgeeks.org/find-divisors-natural-number-set-1/ + * https://www.geeksforgeeks.org/find-all-divisors-of-a-natural-number-set-2/ + * + */ + +#include + +void getDivisors(int n) +{ + for (int i = 1; i * i <= n; i++) { // time complexity: sqrt(n) + if (n % i == 0) { + if (n/i == i) + std::cout << i << " "; + else std::cout << i << " " << n/i << " "; + } + } +} + +int main() +{ + int n = 100; + getDivisors(n); + return 0; +} \ No newline at end of file From 8dae033f7f349ca25a41017a188756dc4dee1be0 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sat, 5 Jun 2021 17:29:35 +0530 Subject: [PATCH 178/209] add prime factor algo --- cpp/Maths/prime_factors.cpp | 46 +++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 cpp/Maths/prime_factors.cpp diff --git a/cpp/Maths/prime_factors.cpp b/cpp/Maths/prime_factors.cpp new file mode 100644 index 0000000..0480e56 --- /dev/null +++ b/cpp/Maths/prime_factors.cpp @@ -0,0 +1,46 @@ +/** + * Print all prime factors of a given number + * + * Given a number n, write an efficient function to print all prime factors + * of n. For example, if the input number is 12, then output should be “2 2 3”. + * And if the input number is 315, then output should be “3 3 5 7”. + * + * Link: https://www.geeksforgeeks.org/print-all-prime-factors-of-a-given-number/ + * + */ + +#include + +void primeFactors(int n) +{ + // while n is divisible by 2, print 2 and divide n by 2. + while (n % 2 == 0) { + std::cout << "2 "; + n = n / 2; + } + + // after dividing by 2, n must be odd + // start a loop from i = 3 to square root of n. While i divides n, + // print i and divide n by i. After i fails to divide n, + // increment i by 2 and continue. + for (int i = 3; i * i <= n; i = i + 2) { + while(n % i == 0) { + std::cout << i << " "; + n = n / i; + } + } + + // if resultant n is a prime number and is greater than 2, then n will + // not become 1 by above two steps. So print n if it is greater than 2. + if (n > 2) + std::cout << n; + + std::cout << std::endl; +} + +int main() +{ + int n = 315; + primeFactors(n); + return 0; +} \ No newline at end of file From 169223819461c1fe04c5464d26f07b16b5011563 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sun, 6 Jun 2021 21:27:49 +0530 Subject: [PATCH 179/209] add segment tree --- segment_tree/segment_tree.py | 110 +++++++++++++++++++++++++++++++++++ 1 file changed, 110 insertions(+) create mode 100644 segment_tree/segment_tree.py diff --git a/segment_tree/segment_tree.py b/segment_tree/segment_tree.py new file mode 100644 index 0000000..e5c6de7 --- /dev/null +++ b/segment_tree/segment_tree.py @@ -0,0 +1,110 @@ +""" Segment Tree is a data structure that allows answering range queries over an array effectively, + while still being flexible enough to allow modifying the array. Time complexity for both queries + i.e. range query and update query is O(log n) +""" + +class SegmentTree: + """ implementation of segment tree """ + def __init__(self, arr, func): + """ segment tree initialization """ + self.arr = arr + self.func = func + self.size = len(arr) + + # If you have n values in the input array, the maximum number of + # nodes in the segment tree array can not exceed 4n. + self.seg_tree = [None] * (4 * self.size) + + self.build_segment_tree(0, self.size - 1, 0) + + def build_segment_tree(self, node_left, node_right, node_index): + """ build segment tree from input array """ + if node_left > node_right: + return + + if node_left == node_right: + self.seg_tree[node_index] = self.arr[node_left] + return + + mid = node_left + (node_right - node_left) // 2 + left_child = node_index * 2 + 1 + right_child = node_index * 2 + 2 + self.build_segment_tree(node_left, mid, left_child) + self.build_segment_tree(mid + 1, node_right, right_child) + self.seg_tree[node_index] = self.func(self.seg_tree[left_child], self.seg_tree[right_child]) + + def range_query(self, query_left, query_right): + """ returns result for range queries """ + def _range_sum(query_left, query_right, node_left, node_right, node_index): + """ internal recursive function """ + if node_left > node_right: + return 0 + + if node_right < query_left or node_left > query_right: + return 0 + + if query_left <= node_left and query_right >= node_right: + return self.seg_tree[node_index] + + mid = node_left + (node_right - node_left) // 2 + left_child = node_index * 2 + 1 + right_child = node_index * 2 + 2 + + left = _range_sum(query_left, query_right, node_left, mid, left_child) + right = _range_sum(query_left, query_right, mid + 1, node_right, right_child) + return self.func(left, right) + + return _range_sum(query_left, query_right, 0, self.size - 1, 0) + + def update(self, index, value): + """ update segment tree """ + def _update(index, value, node_left, node_right, node_index): + """ internal recursive function """ + if index < node_left or index > node_right: + return + + if node_left == node_right: + self.seg_tree[node_index] = value + return + + mid = node_left + (node_right - node_left) // 2 + left_child = node_index * 2 + 1 + right_child = node_index * 2 + 2 + + if index > mid: + _update(index, value, mid + 1, node_right, right_child) + else: + _update(index, value, node_left, mid, left_child) + + self.seg_tree[node_index] = self.func(self.seg_tree[left_child], self.seg_tree[right_child]) + + _update(index, value, 0, self.size - 1, 0) + + +def main(): + """ operational function """ + + def addition(obj1, obj2): + return obj1 + obj2 + + st = SegmentTree([3, 5, 6, 10, 0, 1], addition) + assert st.range_query(-1, 8) == 25 + assert st.range_query(2, 3) == 16 + st.update(4, 10) + assert st.range_query(-1, 8) == 35 + assert st.range_query(2, 3) == 16 + + + def maximum(obj1, obj2): + return obj1 if obj1 >= obj2 else obj2 + + st = SegmentTree([3, 5, 6, 10, 0, 1], maximum) + assert st.range_query(-1, 8) == 10 + assert st.range_query(2, 3) == 10 + st.update(4, 20) + assert st.range_query(-1, 8) == 20 + assert st.range_query(2, 3) == 10 + + +if __name__ == "__main__": + main() From 91c2b28608de37b3f14a54bd7ea93d633e7c2e98 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Mon, 7 Jun 2021 20:01:12 +0530 Subject: [PATCH 180/209] add segment tree lazy propagation --- segment_tree/lazy_propagation.py | 126 +++++++++++++++++++++++++++++++ 1 file changed, 126 insertions(+) create mode 100644 segment_tree/lazy_propagation.py diff --git a/segment_tree/lazy_propagation.py b/segment_tree/lazy_propagation.py new file mode 100644 index 0000000..0c7734c --- /dev/null +++ b/segment_tree/lazy_propagation.py @@ -0,0 +1,126 @@ +""" Segment Tree is a data structure that allows answering range queries over an array effectively, + while still being flexible enough to allow modifying the array. Lazy propagation is used to + update an interval from l to r, instead of a single element. Time complexity for both queries + i.e. range query and update query is O(log n) +""" + +class LazyPropagation: + """ implementation of lazy propagation in segment tree """ + def __init__(self, arr, func): + """ segment tree initialization """ + self.arr = arr + self.func = func + self.size = len(arr) + + # If you have n values in the input array, the maximum number of + # nodes in the segment tree array can not exceed 4n. + self.seg_tree = [None] * (4 * self.size) + self.lazy_tree = [0] * (4 * self.size) + + self.build_segment_tree(0, self.size - 1, 0) + + def build_segment_tree(self, node_left, node_right, node_index): + """ build segment tree from input array """ + if node_left > node_right: + return + + if node_left == node_right: # base case + self.seg_tree[node_index] = self.arr[node_left] + return + + mid = node_left + (node_right - node_left) // 2 + left_child = node_index * 2 + 1 + right_child = node_index * 2 + 2 + self.build_segment_tree(node_left, mid, left_child) + self.build_segment_tree(mid + 1, node_right, right_child) + self.seg_tree[node_index] = self.func(self.seg_tree[left_child], self.seg_tree[right_child]) + + def range_query(self, query_left, query_right): + """ returns result for range queries """ + def _range_query(query_left, query_right, node_left, node_right, node_index): + """ internal recursive function """ + if self.lazy_tree[node_index] != 0: + # complete the pending update + self.seg_tree[node_index] += self.lazy_tree[node_index] + if node_left != node_right: + self.lazy_tree[2 * node_index + 1] += self.lazy_tree[node_index] + self.lazy_tree[2 * node_index + 2] += self.lazy_tree[node_index] + self.lazy_tree[node_index] = 0 + + # no overlap + if node_left > node_right: + return 0 + + if node_right < query_left or node_left > query_right: + return 0 + + # complete overlap + if query_left <= node_left and query_right >= node_right: + return self.seg_tree[node_index] + + # partial overlap + mid = node_left + (node_right - node_left) // 2 + left_child = node_index * 2 + 1 + right_child = node_index * 2 + 2 + + left = _range_query(query_left, query_right, node_left, mid, left_child) + right = _range_query(query_left, query_right, mid + 1, node_right, right_child) + return self.func(left, right) + + return _range_query(query_left, query_right, 0, self.size - 1, 0) + + def range_update(self, query_left, query_right, value): + """ update segment tree """ + def _range_update(query_left, query_right, value, node_left, node_right, node_index): + """ internal recursive function """ + if self.lazy_tree[node_index] != 0: + # complete the pending update + self.seg_tree[node_index] += self.lazy_tree[node_index] + if node_left != node_right: + self.lazy_tree[2 * node_index + 1] += self.lazy_tree[node_index] + self.lazy_tree[2 * node_index + 2] += self.lazy_tree[node_index] + self.lazy_tree[node_index] = 0 + + # no overlap + if node_left > node_right: + return 0 + + if node_right < query_left or node_left > query_right: + return 0 + + # complete overlap + if node_left >= query_left and node_right <= query_right: + self.seg_tree[node_index] += value + # if the current node is not leaf node + if node_left != node_right: + self.lazy_tree[2 * node_index + 1] += value + self.lazy_tree[2 * node_index + 2] += value + return + + # partial overlap + mid = node_left + (node_right - node_left) // 2 + left_child = node_index * 2 + 1 + right_child = node_index * 2 + 2 + + _range_update(query_left, query_right, value, mid + 1, node_right, right_child) + _range_update(query_left, query_right, value, node_left, mid, left_child) + + self.seg_tree[node_index] = self.func(self.seg_tree[left_child], self.seg_tree[right_child]) + + _range_update(query_left, query_right, value, 0, self.size - 1, 0) + + +def main(): + """ operational function """ + + st = LazyPropagation([2, 4, 1, 6, 7], max) + + # add 4 to all the values in the range [3, 5] + # after update: [2, 4, 1, 10, 11] + st.range_update(3, 5, 4) + + # find the max value in range [2, 5] + assert st.range_query(2, 5) == 11 + +if __name__ == "__main__": + main() From 1180b6d28f5bb37c162f9737e8047276400a67c4 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Fri, 11 Jun 2021 21:23:02 +0530 Subject: [PATCH 181/209] add fenwick tree --- fenwick_tree/fenwick_tree.py | 78 ++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 fenwick_tree/fenwick_tree.py diff --git a/fenwick_tree/fenwick_tree.py b/fenwick_tree/fenwick_tree.py new file mode 100644 index 0000000..dc4c2e2 --- /dev/null +++ b/fenwick_tree/fenwick_tree.py @@ -0,0 +1,78 @@ +""" A Fenwick tree or binary indexed tree is a data structure that can + efficiently update elements and calculate prefix sums in a table of + numbers. + + space complexity for fenwick tree is O(n) + time complexity to create fenwick tree is O(nlogn) + time complexity to update value is O(logn) + time complexity to get prefix sum is O(logn) + + * References + http://www.geeksforgeeks.org/binary-indexed-tree-or-fenwick-tree-2/ + https://www.youtube.com/watch?v=CWDQJGaN1gY +""" + +class FenwickTree: + """ implementation of fenwick tree """ + def __init__(self, arr): + """ fenwick tree initialization """ + self.arr = arr + self.size = len(self.arr) + self.bi_tree = [0] * (self.size + 1) + self.build_fenwick_tree() + + def build_fenwick_tree(self): + """ build fenwick tree from input array """ + for i in range(self.size): + self.update(i, self.arr[i]) + + def update(self, index, value): + """ updates the binary indexed tree with the given value """ + index = index + 1 + while index < len(self.bi_tree): + self.bi_tree[index] += value + index += index & -index + + def get_sum(self, index): + """ calculates the sum of the elements from the beginning to the index + """ + result = 0 + index = index + 1 + while index > 0: + result += self.bi_tree[index] + index -= index & -index + return result + + def get_range_sum(self, left, right): + """ calculates the sum from the given range """ + return self.get_sum(right) - self.get_sum(left - 1) + + +def main(): + """ operational function """ + f_tree = FenwickTree([3, 2, -1, 6, 5, 4, -3, 3, 7, 2, 3]) + assert 3 == f_tree.get_sum(0) + assert 5 == f_tree.get_sum(1) + assert 4 == f_tree.get_sum(2) + assert 10 == f_tree.get_sum(3) + assert 15 == f_tree.get_sum(4) + assert 19 == f_tree.get_sum(5) + assert 16 == f_tree.get_sum(6) + + assert f_tree.get_range_sum(2, 4) == 10 + assert f_tree.get_range_sum(1, 4) == 12 + assert f_tree.get_range_sum(2, 6) == 11 + assert f_tree.get_range_sum(0, 1) == 5 + + f_tree.update(3, 10) + f_tree.update(0, 5) + + assert 8 == f_tree.get_sum(0) + assert f_tree.get_range_sum(2, 4) == 20 + assert f_tree.get_range_sum(1, 4) == 22 + assert f_tree.get_range_sum(2, 6) == 21 + assert f_tree.get_range_sum(0, 1) == 10 + + +if __name__ == '__main__': + main() From e6b5e33dfeb7ba8d7cf578528e1374d10adc90c2 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Mon, 12 Jul 2021 18:53:39 +0530 Subject: [PATCH 182/209] add bitwise common elements --- cpp/Bitwise/common_elements.cpp | 40 +++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 cpp/Bitwise/common_elements.cpp diff --git a/cpp/Bitwise/common_elements.cpp b/cpp/Bitwise/common_elements.cpp new file mode 100644 index 0000000..b636ece --- /dev/null +++ b/cpp/Bitwise/common_elements.cpp @@ -0,0 +1,40 @@ +/** + * Count number of common elements between two arrays by using bitset and + * Bitwise operation + * + * Given two arrays a[] and b[], the task is to find the count of common + * elements in both the given arrays. Note that both the arrays contain + * distinct (individually) positive integers. + * + * Input: a[] = {1, 2, 3}, b[] = {2, 4, 3} + * Output: 2 + * Explanation: 2 and 3 are common to both the arrays. + */ + +#include + +#define MAX 1000 + +int count_common(int arr[], int n, int brr[], int m) +{ + std::bitset a, b; + for (int i = 0; i < n; i++) + a.set(arr[i]); + + for (int i = 0; i < m; i++) + b.set(brr[i]); + + std::bitset result = a & b; + return result.count(); +} + +int main() +{ + int a[] = { 1, 4, 7, 2, 3 }; + int b[] = { 2, 11, 7, 4, 15, 20, 24 }; + int n = sizeof(a) / sizeof(a[0]); + int m = sizeof(b) / sizeof(b[0]); + + std::cout << count_common(a, n, b, m) << "\n"; // 3 + return 0; +} From 2d699ec354e8941386b9d7d0d16c829fcc8665ed Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sat, 17 Jul 2021 20:04:43 +0530 Subject: [PATCH 183/209] add bitwise string subsequence --- cpp/Bitwise/string_subsequence.cpp | 33 ++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 cpp/Bitwise/string_subsequence.cpp diff --git a/cpp/Bitwise/string_subsequence.cpp b/cpp/Bitwise/string_subsequence.cpp new file mode 100644 index 0000000..911dd7e --- /dev/null +++ b/cpp/Bitwise/string_subsequence.cpp @@ -0,0 +1,33 @@ +/** + * Print all subsequences of a string + * + * Given a string s, print all possible subsequences of the given string in + * an iterative manner. + * + * Input : abc + * Output : a, b, c, ab, ac, bc, abc + * + * URL: https://www.geeksforgeeks.org/print-subsequences-string-iterative- + * method/ + */ + +#include + +int main() +{ + std::string s = "abc"; + int no_of_subsequence = (1 << s.size()) - 1; + for (int i = 1; i <= no_of_subsequence; i++) { + int temp = i; + int j= 0; + while (temp > 0) { + if (temp & 1) + std::cout << s[j]; + j++; + temp = temp >> 1; + } + std::cout << " "; + } + std::cout << "\n"; + return 0; +} From 1e2bb3c4dc43b9264f9fd91310ef61ddaa73ee7b Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Mon, 19 Jul 2021 21:05:13 +0530 Subject: [PATCH 184/209] add cpp bitwise unique number --- cpp/Bitwise/unique_number.cpp | 48 +++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 cpp/Bitwise/unique_number.cpp diff --git a/cpp/Bitwise/unique_number.cpp b/cpp/Bitwise/unique_number.cpp new file mode 100644 index 0000000..5dcee0f --- /dev/null +++ b/cpp/Bitwise/unique_number.cpp @@ -0,0 +1,48 @@ +/** + * Find the element that appears once in an array where every other element + * appears twice + * + * Given an array of integers. All numbers occur twice except one number which + * occurs once. Find the number in O(n) and constant extra space. + * + * Input: a[] = {7, 3, 5, 4, 5, 3, 4} + * Output: 7 + * + * Solution: + * The best solution is to use XOR. XOR of all array elements gives us the + * number with a single occurrence. The idea is based on the following two + * facts. + * a) XOR of a number with itself is 0. + * b) XOR of a number with 0 is number itself. + * + * Let us consider the above example. + * Let ^ be xor operator as in C and C++. + * + * res = 7 ^ 3 ^ 5 ^ 4 ^ 5 ^ 3 ^ 4 + * + * Since XOR is associative and commutative, above + * expression can be written as: + * res = 7 ^ (3 ^ 3) ^ (4 ^ 4) ^ (5 ^ 5) + * = 7 ^ 0 ^ 0 ^ 0 + * = 7 ^ 0 + * = 7 + */ + +#include + + +int findSingle(int arr[], int size) +{ + int result = arr[0]; + for (int i = 1; i < size; i++) + result = result ^ arr[i]; + return result; +} + +int main() +{ + int arr[] = {7, 3, 5, 4, 5, 3, 4}; + int n = sizeof(arr)/sizeof(arr[0]); + std::cout << "element occuring once is " << findSingle(arr, n) << "\n"; + return 0; +} From fee81484b6e927a0f6a27834e373aae26493ce80 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Thu, 22 Jul 2021 21:25:53 +0530 Subject: [PATCH 185/209] cpp bitwise subset sum queries --- cpp/Bitwise/subset_sum_queries_bitset.cpp | 47 +++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 cpp/Bitwise/subset_sum_queries_bitset.cpp diff --git a/cpp/Bitwise/subset_sum_queries_bitset.cpp b/cpp/Bitwise/subset_sum_queries_bitset.cpp new file mode 100644 index 0000000..6ce4cbf --- /dev/null +++ b/cpp/Bitwise/subset_sum_queries_bitset.cpp @@ -0,0 +1,47 @@ +/** + * Subset sum queries using bitset + * + * Given an array arr[] and a number of queries, where in each query we have + * to check whether a subset whose sum is equal to given number exists in the + * array or not. + * + * Input : arr[] = {1, 2, 3} + * query[] = {5, 3, 8} + * Output : Yes, Yes, No + * Explanation: + * There is a subset with sum 5, subset is {2, 3} + * There is a subset with sum 3, subset is {1, 2} + * There is no subset with sum 8. + * + * URL: https://www.geeksforgeeks.org/subset-sum-queries-using-bitset/ + */ + +#include +#define MAX 1000 + +int main() +{ + int arr[] = { 3, 1, 5 }; + int n = sizeof(arr)/sizeof(arr[0]); + + int query[] = { 8, 7 }; + int nq = sizeof(query)/sizeof(query[0]); + + std::bitset bit; + bit[0] = 1; // set the 0th bit because subset sum of 0 exists + for (int i = 0; i < n; i++) { + // Do OR of following two + // 1. All previous sums. We keep previous value of bit. + // 2. arr[i] added to every previous sum. We move all previous + // indexes arr[i] ahead. + bit |= (bit << arr[i]); + } + + for (int i = 0; i < nq; i++) { + int res = query[i]; + std::cout << res << " -> "; + // if res is a subset sum, then res'th bit must be set + bit[res] ? std::cout << "YES\n" : std::cout << "NO\n"; + } + return 0; +} From 7d3b0bece6f3822c9a2ea7bff77f4fc062ed10d6 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Mon, 26 Jul 2021 15:19:51 +0530 Subject: [PATCH 186/209] add cpp bitwise two unique numbers --- cpp/Bitwise/two_unique_numbers.cpp | 54 ++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 cpp/Bitwise/two_unique_numbers.cpp diff --git a/cpp/Bitwise/two_unique_numbers.cpp b/cpp/Bitwise/two_unique_numbers.cpp new file mode 100644 index 0000000..4647a90 --- /dev/null +++ b/cpp/Bitwise/two_unique_numbers.cpp @@ -0,0 +1,54 @@ +/** + * Find the two non-repeating elements in an array of repeating elements. + * Given an array in which all numbers except two are repeated once. (i.e. we + * have 2n+2 numbers and n numbers are occurring twice and remaining two have + * occurred once). Find those two numbers in the most efficient way. + * + * URL: https://www.geeksforgeeks.org/find-two-non-repeating-elements-in-an- + * array-of-repeating-elements/ + */ + +#include +#include + +int two_unique_numbers(int arr[], int n) +{ + // xor all elements in array + int result; + for (int i = 0; i < n; i++) + result ^= arr[i]; + + // Check the first bit which is set + int _result = result; + int index = 0; + while (_result > 0) { + if (_result & 1) break; + index++; + _result = _result >> 1; + } + + // check the elements where index-th bit is set + int mask = 1 << index; + std::vector temp_arr; + for (int i = 0; i < n; i++) { + if (arr[i] & mask) + temp_arr.push_back(arr[i]); + } + + // XOR all element from above step + int a = 0; + for (int i = 0; i < temp_arr.size(); i++) + a ^= temp_arr[i]; + + int b = result ^ a; + std::cout << a << " " << b << "\n"; + + return 0; +} + +int main() +{ + int arr[] = {2, 3, 7, 9, 11, 2, 3, 11}; + int n = sizeof(arr)/sizeof(arr[0]); + two_unique_numbers(arr, n); +} From c8b9a08be215e97e1f4effc59253b115a7b8fe62 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sun, 1 Aug 2021 10:05:56 +0530 Subject: [PATCH 187/209] cpp bitwise unique number k times --- cpp/Bitwise/unique_number_k_times.cpp | 52 +++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 cpp/Bitwise/unique_number_k_times.cpp diff --git a/cpp/Bitwise/unique_number_k_times.cpp b/cpp/Bitwise/unique_number_k_times.cpp new file mode 100644 index 0000000..98576d0 --- /dev/null +++ b/cpp/Bitwise/unique_number_k_times.cpp @@ -0,0 +1,52 @@ +/** + * Unique element in an array where all elements occur k times except one + * + * Given an array which contains all elements occurring k times, but one + * occurs only once. Find that unique element. + * Input: arr[] = {6, 2, 5, 2, 2, 6, 6} k = 3 + * Output: 5 + * Explanation: Every element appears 3 times accept 5. + * + * URL: https://www.geeksforgeeks.org/find-unique-element-element-occurs-k- + * times-except-one/ + */ + +#include +#include + +int find_unique(int arr[], int n, int k) +{ + std::vector counter(8 * sizeof(int), 0); + + // store all bit information of all numbers in counter array + for (int i = 0; i < n; i++) { + int j = 0; + int num = arr[i]; + while (num > 0) { + if (num & 1) + counter[j]++; + num = num >> 1; + j++; + } + } + + // take modulo k of all elements in counter + // remaining bits represents binary value of result + int result = 0; + for (int i = 0; i < counter.size(); i++) { + counter[i] %= k; + result += counter[i] * (1 << i); + } + + return result; +} + +int main() +{ + int arr[] = {6, 6, 2, 5, 2, 5, 2, 2, 6, 6, 5, 5, 11}; + int n = sizeof(arr)/sizeof(arr[0]); + int k = 4; + std::cout << find_unique(arr, n, k) << "\n"; + + return 0; +} From 9431f0e0d2282c645f3ff80f27bf536053185b63 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Thu, 5 Aug 2021 19:12:00 +0530 Subject: [PATCH 188/209] add cpp sum of divisors --- cpp/Maths/sum_of_divisors.cpp | 59 +++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 cpp/Maths/sum_of_divisors.cpp diff --git a/cpp/Maths/sum_of_divisors.cpp b/cpp/Maths/sum_of_divisors.cpp new file mode 100644 index 0000000..996b658 --- /dev/null +++ b/cpp/Maths/sum_of_divisors.cpp @@ -0,0 +1,59 @@ +/** + * Sum of all proper divisors of a natural number + * + * Given a natural number, calculate sum of all its proper divisors. A proper + * divisor of a natural number is the divisor that is strictly less than + * the number. + * + * For example, number 20 has 5 proper divisors: 1, 2, 4, 5, 10, and the + * divisor summation is: 1 + 2 + 4 + 5 + 10 = 22. + * + * Example: + * Input : num = 10 + * Output: 8 + * // proper divisors 1 + 2 + 5 = 8 + * + * Input : num = 36 + * Output: 55 + * // proper divisors 1 + 2 + 3 + 4 + 6 + 9 + 12 + 18 = 55 + * + * URL:https://www.geeksforgeeks.org/sum-of-all-proper-divisors-of-a-natural-number/ + * + */ + +#include + +#define MAX 1000 + +int sumOfDivisors(int n) +{ + // sieve of erathothenes + std::bitset prime; + prime.set(); + for (int p = 2; p * p <= MAX; p++) + if (prime[p]) + for (int i = p * p; i <= MAX; i += p) + prime.reset(i); + + int total = 1; + for (int p = 2; p <= MAX; p++) { + if (prime[p]) { + int res = 1; + int count = 1; + while (n % p == 0) { + n = n / p; + count *= p; + res += count; + } + total *= res; + } + } + return total; +} + +int main() +{ + int sum = sumOfDivisors(2400); + std::cout << sum << std::endl; // Output: 7812 + return 0; +} \ No newline at end of file From ba8cb6dac59824fe345ae9ad7514ba3c33e7d58c Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Fri, 6 Aug 2021 10:10:52 +0530 Subject: [PATCH 189/209] add cpp number of divisors --- cpp/Maths/number_of_divisors.cpp | 60 ++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 cpp/Maths/number_of_divisors.cpp diff --git a/cpp/Maths/number_of_divisors.cpp b/cpp/Maths/number_of_divisors.cpp new file mode 100644 index 0000000..c882139 --- /dev/null +++ b/cpp/Maths/number_of_divisors.cpp @@ -0,0 +1,60 @@ +/** + * Total number of divisors for a given number + * Given a positive integer n, we have to find the total number of divisors + * for n. + * + * Examples: + * + * Input : n = 25 + * Output : 3 + * Divisors are 1, 5 and 25. + * + * Input : n = 24 + * Output : 8 + * Divisors are 1, 2, 3, 4, 6, 8, 12 and 24. + * + * URL: https://www.geeksforgeeks.org/total-number-divisors-given-number/ + * + */ + +#include + +#define MAX 1000 + +int numberOfDivisors(int n) +{ + // sieve of eratosthenes + std::bitset primes; + primes.set(); + for (int p = 2; p * p <= MAX; p++) { + if (primes[p]) + for (int i = p * p; i <= MAX; i += p) + primes.reset(i); + } + + // traversing through all prime numbers + int total = 1; + for (int p = 2; p <= MAX && n > 1; p++) { + if (primes[p]) { + // calculate number of divisor with formula + // total divisor is (p1+1) * (p2+1) *.....* (pn+1) + // where n = (a1 ^ p1) * (a2 ^ p2) .... * (an ^ pn) + // ai being prime divisor for n and pi are their respective + // power in factorization + int count = 0; + while (n % p == 0) { + n = n / p; + count++; + } + total *= count + 1; + } + } + return total; +} + +int main() +{ + int n = 48; + std::cout << numberOfDivisors(n) << std::endl; + return 0; +} \ No newline at end of file From e38903a81b3d5c56ae9b50138f72ccae3857c2f2 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sat, 7 Aug 2021 11:37:47 +0530 Subject: [PATCH 190/209] add cpp sieve of eratosthenes --- cpp/Maths/sieve_of_eratosthenes.cpp | 53 +++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 cpp/Maths/sieve_of_eratosthenes.cpp diff --git a/cpp/Maths/sieve_of_eratosthenes.cpp b/cpp/Maths/sieve_of_eratosthenes.cpp new file mode 100644 index 0000000..414d68c --- /dev/null +++ b/cpp/Maths/sieve_of_eratosthenes.cpp @@ -0,0 +1,53 @@ +/** + * Sieve of Eratosthenes + * + * Given a number n, print all primes smaller than or equal to n. It is also + * given that n is a small number. + * + * Example: + * + * Input : n = 10 + * Output : 2 3 5 7 + * + * Input : n = 20 + * Output: 2 3 5 7 11 13 17 19 + * + * URL: https://www.geeksforgeeks.org/sieve-of-eratosthenes + */ + +#include +#include +#define MAX 31 + +void sieve_of_eratosthenes(int n) +{ + // create a bitset prime[0..n] and set all entires to 1. A value at + // prime[i] will finally be false(0) if i is not prime, else true(1). + std::bitset prime; + prime.set(); + for (int p = 2; p * p <= n; p++) { + // if prime[p] is not changed, then it is a prime. + if (prime[p]) { + // update all multiples of p greater than or equal to the + // square of it numbers which are multiple of p and are + // less than p^2 are already been marked. + for (int i = p * p; i <= n; i += p) + prime.reset(i); + } + } + + // print all prime numbers + for (int p = 2; p <= n; p++) + if (prime[p]) + std::cout << p << " "; +} + + +int main() +{ + int n = 30; + std::cout << "Prime Numbers less than or equal to N:\n"; + sieve_of_eratosthenes(n); + std::cout << std::endl; + return 0; +} From 1c1fd5f6f209c48fd36b864f8f476db486cdee54 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sat, 7 Aug 2021 22:21:45 +0530 Subject: [PATCH 191/209] add cpp gcd euclidean --- cpp/Maths/gcd_euclidean.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 cpp/Maths/gcd_euclidean.cpp diff --git a/cpp/Maths/gcd_euclidean.cpp b/cpp/Maths/gcd_euclidean.cpp new file mode 100644 index 0000000..f0aba36 --- /dev/null +++ b/cpp/Maths/gcd_euclidean.cpp @@ -0,0 +1,30 @@ +/** + * GCD(HCF) of two numbers (Euclidean Algorithm) + * GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers + * is the largest number that divides both of them. + * + * Explanation: + * 36 = 2 x 2 x 3 x 3 + * 60 = 2 x 2 x 3 x 5 + * GCD = 2 x 2 x 3 = 12 + * + * The time complexity for the above algorithm is O(log(min(a,b))). + * + */ + +#include + +// recursive function to return gcd of a and b +int gcd(int a, int b) +{ + if (b == 0) + return a; + return gcd(b, a % b); +} + +int main() +{ + int a = 98, b = 56; + std::cout << "GCD of " << a << " and " << b << " is " << gcd(a, b) << "\n"; + return 0; +} From b3e16e3278ea9a7d06619dce512d1a0d51656644 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Mon, 9 Aug 2021 12:45:47 +0530 Subject: [PATCH 192/209] add cpp least prime factor --- cpp/Maths/least_prime_factor.cpp | 54 ++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 cpp/Maths/least_prime_factor.cpp diff --git a/cpp/Maths/least_prime_factor.cpp b/cpp/Maths/least_prime_factor.cpp new file mode 100644 index 0000000..165049c --- /dev/null +++ b/cpp/Maths/least_prime_factor.cpp @@ -0,0 +1,54 @@ +/** + * Least Prime Factor of numbers till n + * + * Given a number n, print least prime factors of all numbers from 1 to n. + * The least prime factor of an integer n is the smallest prime number that + * divides the number. The least prime factor of all even numbers is 2. A prime + * number is its own least prime factor (as well as its own greatest prime + * factor). + * + * Note: We need to print 1 for 1. + * Example : + * + * Input : 6 + * Output : Least Prime factor of 1: 1 + * Least Prime factor of 2: 2 + * Least Prime factor of 3: 3 + * Least Prime factor of 4: 2 + * Least Prime factor of 5: 5 + * Least Prime factor of 6: 2 + */ + +#include + +void leastPrimeFactors(int n) +{ + int leastPrime[n+1]; + memset(leastPrime, 0, sizeof(leastPrime)); + + leastPrime[1] = 1; + + for (int i = 2; i <= n; i++) { + // if i is prime + if (leastPrime[i] == 0) + leastPrime[i] = i; + + // mark it as a divisor for all its multiples if not already marked + for (int j = i*i; j <= n; j += i) { + if (leastPrime[j] == 0) + leastPrime[j] = i; + } + } + + // print least prime factor of numbers till n + for (int i = 2; i <= n; i++) + std::cout << "Least Prime factor of " << i << ": " + << leastPrime[i] << std::endl; +} + +int main() +{ + int n = 20; + leastPrimeFactors(n); + return 0; +} \ No newline at end of file From 23948eaaa3327035176063b9ba4d2dbcbe58ed96 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Thu, 12 Aug 2021 09:42:46 +0530 Subject: [PATCH 193/209] add cpp math segmented sieve --- cpp/Maths/segmented_sieve.cpp | 74 +++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 cpp/Maths/segmented_sieve.cpp diff --git a/cpp/Maths/segmented_sieve.cpp b/cpp/Maths/segmented_sieve.cpp new file mode 100644 index 0000000..f764a6b --- /dev/null +++ b/cpp/Maths/segmented_sieve.cpp @@ -0,0 +1,74 @@ +/** + * Segmented Sieve (Print Primes in a Range) + * + * Given a range [low, high], print all primes in this range? + * For example, if the given range is [10, 20], then output is 11, 13, 17, 19. + * + * URL: https://www.geeksforgeeks.org/segmented-sieve-print-primes-in-a-range/ + * + */ + +#include +#include +#include + +#define MAX 1000000 + +// sieve of eratosthenes +void simple_sieve(std::vector &primes, int n) +{ + std::bitset prime; + prime.set(); + for (int p = 2; p * p <= n; p++) { + if (prime[p]) { + for (int i = p * p; i <= n; i += p) + prime.reset(i); + } + } + + for (int p = 2; p <= n; p++) + if (prime[p]) + primes.push_back(p); +} + +void primes_in_range(int low, int high) +{ + // compute all primes smaller or equal to square root of high using + // simple sieve + int limit = floor(sqrt(high)) + 1; + std::vector primes; + simple_sieve(primes, limit); + + std::bitset segsieve; + segsieve.set(); + if (low == 1) low++; + + // use the found primes by simple sieve to find + // primes in given range + for (int i = 0; primes[i] * primes[i] <= high; i++) { + int p = primes[i]; + // find the minimum number in [low..high] that is + // multiple of primes[i] (divisible by primes[i]) + int j = floor(low/p) * p; + if (j < low) + j += p; + + // j is the first multiple of primes[i] in range [low..high] + for (; j <= high; j += p) { + if (j != p) + segsieve[j-low] = 0; + } + } + for (int i = low; i <= high; i++) { + if (i <= 1) continue; + if (segsieve[i-low]) + std::cout << i << " "; + } + std::cout << std::endl; +} + +int main() +{ + primes_in_range(10, 20); + return 0; +} From be006ecdc7d0244377836ba0629ab1375416f055 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sat, 14 Aug 2021 19:01:23 +0530 Subject: [PATCH 194/209] add cpp count divisors of factorial --- cpp/Maths/count_divisors_of_factorial.cpp | 71 +++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 cpp/Maths/count_divisors_of_factorial.cpp diff --git a/cpp/Maths/count_divisors_of_factorial.cpp b/cpp/Maths/count_divisors_of_factorial.cpp new file mode 100644 index 0000000..ad2fc77 --- /dev/null +++ b/cpp/Maths/count_divisors_of_factorial.cpp @@ -0,0 +1,71 @@ +/** + * Count Divisors of Factorial + * Given a number n, count total number of divisors of n!. + * + * Explanation: + * Input : n = 4 + * Output: 24 + * 4! is 24. Divisors of 24 are 1, 2, 3, 4, 6, 8, 12 and 24. + * + * Input : n = 5 + * Output : 16 + * 5! is 120. Divisors of 120 are 1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24, 30, + * 40, 60 and 120 + * + * Input : n = 6 + * Output : 30 + * + * URL: https://www.geeksforgeeks.org/count-divisors-of-factorial/ + * + */ + +#include +#include + +#define MAX 1000000 + +// sieve of eratosthenes +void sieve(std::vector &primes, int n) +{ + std::bitset prime; + prime.set(); + for (int p = 2; p * p <= n; p++) { + if (prime[p]) { + for (int i = p * p; i <= n; i += p) + prime.reset(i); + } + } + + for (int p = 2; p <= n; p++) + if (prime[p]) + primes.push_back(p); +} + +int factorialDivisors(int n) +{ + std::vector primes; + sieve(primes, n); // create sieve + + // find exponents of all primes which divides n and less than n + int result = 1; + for (int i = 0; i < primes.size(); i++) { + int p = primes[i]; + + // Find the highest power (stored in exp) + // of allPrimes[i] that divides n using Legendre's formula. + int exp = 0; + while (p <= n) { + exp = exp + (n/p); + p = p * primes[i]; + } + // Multiply exponents of all primes less than n + result = result * (exp + 1); + } + return result; +} + +int main() +{ + std::cout << factorialDivisors(6) << "\n"; + return 0; +} From 3c1c16fc64abb2ff2205301421183cc059617865 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sun, 15 Aug 2021 10:32:33 +0530 Subject: [PATCH 195/209] add cpp prime factors using sieve --- cpp/Maths/prime_factors_using_sieve.cpp | 59 +++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 cpp/Maths/prime_factors_using_sieve.cpp diff --git a/cpp/Maths/prime_factors_using_sieve.cpp b/cpp/Maths/prime_factors_using_sieve.cpp new file mode 100644 index 0000000..cf6d80c --- /dev/null +++ b/cpp/Maths/prime_factors_using_sieve.cpp @@ -0,0 +1,59 @@ +/** + * Prime Factorization using Sieve O(log n) for multiple queries + * + * To calculate to smallest prime factor for every number we will use the + * sieve of eratosthenes. In original Sieve, every time we mark a number + * as not-prime, we store the corresponding smallest prime factor for that + * number. + * + * Now, after we are done with precalculating the smallest prime factor for + * every number we will divide our number n (whose prime factorziation is to + * be calculated) by its corresponding smallest prime factor till n becomes 1. + * + * URL: https://www.geeksforgeeks.org/prime-factorization-using-sieve-olog-n-multiple-queries/ + */ + +#include +#include + +#define MAX 10000 + +// stores smallest prime factor for every number +int spf[MAX+1]; + +void sieve() +{ + memset(spf, 0, MAX+1); + spf[1] = 1; + + for (int i = 2; i <= MAX; i++) { + if (spf[i] == 0) + spf[i] = i; + + for (int j = i * i; j <= MAX; j += i) { + if (spf[j] == 0) + spf[j] = i; + } + } +} + +std::vector primeFactorsUsingSieve(int n) +{ + std::vector result; + while (n > 1) { + result.push_back(spf[n]); + n = n / spf[n]; + } + return result; +} + +int main() +{ + sieve(); + int n = 1224; + std::vector result = primeFactorsUsingSieve(n); + for (int i = 0; i < result.size(); i++) + std::cout << result[i] << " "; + std::cout << std::endl; + return 0; +} \ No newline at end of file From 9481c8cf4a392539a162aa5a9459d633dcd9a1a4 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Mon, 16 Aug 2021 12:17:28 +0530 Subject: [PATCH 196/209] add cpp maths modular exponential --- cpp/Maths/modular_exponential.cpp | 58 +++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 cpp/Maths/modular_exponential.cpp diff --git a/cpp/Maths/modular_exponential.cpp b/cpp/Maths/modular_exponential.cpp new file mode 100644 index 0000000..27ec750 --- /dev/null +++ b/cpp/Maths/modular_exponential.cpp @@ -0,0 +1,58 @@ +/** + * Modular Exponentiation (Power in Modular Arithmetic) + * Given three large numbers x, y and p, compute (xy) % p. + * + * Example: + * Input: x = 2, y = 3, p = 5 + * Output: 3 + * Explanation: 2^3 % 5 = 8 % 5 = 3. + * + * Input: x = 2, y = 5, p = 13 + * Output: 6 + * Explanation: 2^5 % 13 = 32 % 13 = 6. + */ + +#include +typedef long long ll; + +/* + * Modular Exponentiation (recursive version) + * time complexity = O(log b) + * space complexity = O(log b) + */ +ll mod_power_recursive(ll a, ll b, ll c) +{ + if (b == 0) return 1; + ll temp = mod_power_recursive(a, b/2, c); + + if (b % 2 == 0) { + return ((temp % c) * (temp % c)) % c; + } else { + return ((a % c) * (temp % c) * (temp % c)) % c; + } +} + + +/* + * Modular Exponentiation (iterative version) + * time complexity = O(log b) + * space complexity = O(1) + */ +ll mod_power_iterative(ll a, ll b, ll c) +{ + ll result = 1; + while (b != 0) { + if (b % 2 != 0) { + result = ((result % c) * (a % c)) % c; + } + a = ((a % c) * (a % c)) % c; + b = b / 2; + } + return result; +} + +int main() +{ + std::cout << mod_power_recursive(13, 7, 7) << std::endl; + std::cout << mod_power_iterative(13, 7, 7) << std::endl; +} From eadd80a724753029d6988568df8772bda67b1d05 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Wed, 18 Aug 2021 17:26:20 +0530 Subject: [PATCH 197/209] add cpp modular multiplicative inverse --- cpp/Maths/modular_multiplicative_inverse.cpp | 67 ++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 cpp/Maths/modular_multiplicative_inverse.cpp diff --git a/cpp/Maths/modular_multiplicative_inverse.cpp b/cpp/Maths/modular_multiplicative_inverse.cpp new file mode 100644 index 0000000..ba7d800 --- /dev/null +++ b/cpp/Maths/modular_multiplicative_inverse.cpp @@ -0,0 +1,67 @@ +/** + * Modular Multiplicative Inverse + * + * Given two integers ‘a’ and ‘m’, find modular multiplicative inverse of ‘a’ + * under modulo ‘m’. The modular multiplicative inverse is an integer ‘x’ + * such that. + * + * a x ≅ 1 (mod m) + * + * The value of x should be in {0, 1, 2, … m-1}, i.e., in the range of + * integer modulo m. The multiplicative inverse of “a modulo m” exists + * if and only if a and m are relatively prime (i.e., if gcd(a, m) = 1). + * + * Examples: + * + * Input: a = 3, m = 11 + * Output: 4 + * Since (4*3) mod 11 = 1, 4 is modulo inverse of 3(under 11). + * One might think, 15 also as a valid output as "(15*3) mod 11" + * is also 1, but 15 is not in ring {0, 1, 2, ... 10}, so not + * valid. + * + * Input: a = 10, m = 17 + * Output: 12 + * Since (10*12) mod 17 = 1, 12 is modulo inverse of 10(under 17). + * + */ + +#include +#include +using namespace std; + +// extended euclidean algorithm +tuple extended_gcd(int a, int b) +{ + if (a == 0) + return make_tuple(b, 0, 1); + + int gcd, x, y; + + // unpack tuple returned by function into variables + tie(gcd, x, y) = extended_gcd(b % a, a); + + return make_tuple(gcd, (y - (b/a) * x), x); +} + +void modular_multiplicative_inverse(int a, int m) +{ + tuple t = extended_gcd(a, m); + + int gcd = get<0>(t); + int x = get<1>(t); + + if (gcd != 1) + cout << "Inverse doesn't exist\n"; + else { + // m is added to handle negative x + int result = (x % m + m) % m; + cout << "modular multiplicative inverse is " << result << "\n"; + } +} + +int main() +{ + modular_multiplicative_inverse(3, 11); + return 0; +} From 5274f7427a5370a8219e0d88146334acaccaf68d Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Wed, 18 Aug 2021 17:27:04 +0530 Subject: [PATCH 198/209] add cpp extended euclidean algo --- cpp/Maths/extended_euclidean_algorithm.cpp | 56 ++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 cpp/Maths/extended_euclidean_algorithm.cpp diff --git a/cpp/Maths/extended_euclidean_algorithm.cpp b/cpp/Maths/extended_euclidean_algorithm.cpp new file mode 100644 index 0000000..27c9d61 --- /dev/null +++ b/cpp/Maths/extended_euclidean_algorithm.cpp @@ -0,0 +1,56 @@ +/** + * Extended Euclidean Algorithm + * The extended Euclidean algorithm is an extension to the Euclidean + * algorithm, which computes, besides the greatest common divisor of integers + * a and b, the coefficients of Bézout’s identity, that is integers x and y + * such that + * + * ax + by = gcd(a, b) + * + * Example: + * gcd(30, 50) = 10 + * Here, x = 2 y = -1 as 30 * 2 + 50 * -1 = 10 + * + * gcd(2740, 1760) = 20 + * Here, x = 9 y = -14 as 2740 * 9 + 1760 * -14 = 20 + * + */ + +#include +#include // std::tuple, std::make_tuple, std::tie +using namespace std; + +// function for Extended Euclidean algorithm +// returns multiple values using tuple in C++ +tuple extended_gcd(int a, int b) +{ + if (a == 0) + return make_tuple(b, 0, 1); + + int gcd, x, y; + + // unpack tuple returned by function into variables + tie(gcd, x, y) = extended_gcd(b % a, a); + + return make_tuple(gcd, (y - (b/a) * x), x); +} + +// main function +int main() +{ + int a = 30; + int b = 50; + + tuple t = extended_gcd(a, b); + + int gcd = get<0>(t); + int x = get<1>(t); + int y = get<2>(t); + + cout << "GCD is " << gcd << endl; + cout << "x = " << x << " y = " << y << endl; + + cout << a << "*" << x << " + " << b << "*" << y << " = " << gcd << "\n"; + + return 0; +} From 70b276d17b80e764a6677ea4b879efb80c8c522f Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Thu, 19 Aug 2021 13:00:49 +0530 Subject: [PATCH 199/209] add cpp legendres formula --- cpp/Maths/legendres_formula.cpp | 42 +++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 cpp/Maths/legendres_formula.cpp diff --git a/cpp/Maths/legendres_formula.cpp b/cpp/Maths/legendres_formula.cpp new file mode 100644 index 0000000..cea10f4 --- /dev/null +++ b/cpp/Maths/legendres_formula.cpp @@ -0,0 +1,42 @@ +/** + * Legendre’s formula (Given p and n, find the largest x such that p^x + * divides n!) + * + * Given an integer n and a prime number p, find the largest x such that + * p^x (p raised to power x) divides n! (factorial) + * + * Input: n = 7, p = 3 + * Output: x = 2 + * Explanation: 32 divides 7! and 2 is the largest such power of 3. + * + * Input: n = 10, p = 3 + * Output: x = 4 + * Explanation: 34 divides 10! and 4 is the largest such power of 3. + * + * URL: https://www.geeksforgeeks.org/legendres-formula-highest-power-of- + * prime-number-that-divides-n/ + * + */ + +#include + +// returns largest power of p that divides n! +int largest_power(int n, int p) +{ + int result = 0; + + // calculate x = n/p + n/(p^2) + n/(p^3) + .... + while (n) { + n /= p; + result += n; + } + return result; +} + +int main() +{ + int n = 10, p = 3; + std::cout << "the largest power of " << p <<" that divides " << n << + "! is " << largest_power(n, p) << std::endl; + return 0; +} From 563dacf9dfdeb1e458557d07de821b7dd0a1c4b6 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Mon, 23 Aug 2021 09:14:05 +0530 Subject: [PATCH 200/209] add dynamic array using ctypes --- dynamic_array/dynamic_array.py | 72 ++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 dynamic_array/dynamic_array.py diff --git a/dynamic_array/dynamic_array.py b/dynamic_array/dynamic_array.py new file mode 100644 index 0000000..dcbe8f7 --- /dev/null +++ b/dynamic_array/dynamic_array.py @@ -0,0 +1,72 @@ +""" Dynamic array is similar to an array, but with the difference that its + size can be dynamically modified at runtime. + We are using C style raw array using ctypes modules instead of python + built-in list. +""" + +import ctypes + + +class DynamicArray: + def __init__(self, capacity): + self._idx = 0 + self.lenght = 0 + self.capacity = capacity + self.array = self._make_array() + + def __getitem__(self, key): + if key < 0 or key >= self.lenght: + raise IndexError('dynamic array index out of range') + return self.array[key] + + def __len__(self): + return self.lenght + + def __iter__(self): + return self + + def __next__(self): + if self._idx >= self.lenght: + self._idx = 0 + raise StopIteration + result = self.array[self._idx] + self._idx += 1 + return result + + def _make_array(self): + return (ctypes.py_object * self.capacity)() + + def _resize(self, new_capacity): + self.capacity = new_capacity + _array = self._make_array() + for i in range(self.lenght): + _array[i] = self.array[i] + self.array = _array + + def append(self, value): + if self.lenght >= self.capacity: + self._resize(self.capacity * 2) + self.array[self.lenght] = value + self.lenght += 1 + + def insert_at(self, elem, index): + if index < 0 or index > self.lenght: + raise IndexError("dynamic array index out of range") + if self.lenght >= self.capacity: + self._resize(self.capacity * 2) + idx = self.lenght - 1 + while idx >= index: + self.array[idx + 1] = self.array[idx] + idx -= 1 + self.array[index] = elem + self.lenght += 1 + + def remove_at(self, index): + if index < 0 or index >= self.lenght: + raise IndexError("dynamic array index out of range") + idx = index + while idx < self.lenght - 1: + self.array[idx] = self.array[idx+1] + idx += 1 + self.array[self.lenght] = None + self.lenght -= 1 From 1d5e14fe618d960fad7b3ef6de19f4d4e4dbd256 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Tue, 24 Aug 2021 19:26:47 +0530 Subject: [PATCH 201/209] add graph breadth first search --- graph/breadth_first_search.py | 53 +++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 graph/breadth_first_search.py diff --git a/graph/breadth_first_search.py b/graph/breadth_first_search.py new file mode 100644 index 0000000..5f26bc0 --- /dev/null +++ b/graph/breadth_first_search.py @@ -0,0 +1,53 @@ +""" Breadth-First Search Graph Traversal Algorithm + + Breadth-First Search is a traversing algorithm where you should start + traversing from a selected node (source or starting node) and traverse + the graph layerwise thus exploring the neighbour nodes (nodes which + are directly connected to source node). You must then move towards the + next-level neighbour nodes. + + Time Complexity: O(V+E) + Space Complexity: O(V) +""" + +from collections import deque + +def breadth_first_search(graph, root): + """ graph traversal algorithm + breadth first search implementation + """ + visited = set() + queue = deque([root]) + visited.add(root) + + while queue: + vertex = queue.popleft() + print(str(vertex), end=" ") + + for neighbour in graph[vertex]: + if neighbour not in visited: + visited.add(neighbour) + queue.append(neighbour) + + +def main(): + """ operational function """ + graph = { + "A": ["B", "C", "D"], + "B": ["E"], + "C": ["F", "G"], + "D": ["H"], + "E": ["I"], + "F": ["J"], + "G": [], + "H": [], + "I": [], + "J": [] + } + print("Breadth First Traversal: ", end="") + breadth_first_search(graph, "A") + print() + + +if __name__ == "__main__": + main() From 241115c64a7518c34f672eb2b851b05f353247f1 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Wed, 25 Aug 2021 19:46:50 +0530 Subject: [PATCH 202/209] add graph connected components --- graph/connected_components.py | 43 +++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 graph/connected_components.py diff --git a/graph/connected_components.py b/graph/connected_components.py new file mode 100644 index 0000000..0b21054 --- /dev/null +++ b/graph/connected_components.py @@ -0,0 +1,43 @@ +""" Finding Connected Components using BFS Graph Traversal Algorithms +""" + +def find_components(graph): + """ breadth first search graph traversal algorithm """ + connected_components = [] + vertices = list(graph) + + while vertices: + start_node = vertices.pop() + queue = [start_node] + visited = [start_node] + + while queue: + node = queue.pop(0) + for neighbour in graph[node]: + if neighbour not in visited: + queue.append(neighbour) + visited.append(neighbour) + vertices.remove(neighbour) + connected_components.append(visited) + return connected_components + + +def main(): + """ operational function """ + graph = { + '1': ['2', '3'], + '2': ['3', '1'], + '3': ['1', '2', '4'], + '4': ['3'], + '5': ['7', '6'], + '6': ['5'], + '7': ['5'], + '8': [], + '9': [], + } + + print(find_components(graph)) + + +if __name__ == "__main__": + main() From cf7a2f9e2cd6e3744333f23badf01429682034bd Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sat, 28 Aug 2021 21:27:52 +0530 Subject: [PATCH 203/209] add graph topological sort --- graph/topological_sort.py | 46 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 graph/topological_sort.py diff --git a/graph/topological_sort.py b/graph/topological_sort.py new file mode 100644 index 0000000..f79c104 --- /dev/null +++ b/graph/topological_sort.py @@ -0,0 +1,46 @@ +""" Topological Sort + +Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of +vertices such that for every directed edge uv, vertex u comes before v in +the ordering. Topological Sorting for a graph is not possible if the graph is +not a DAG. +""" + +def topological_sort(graph): + """ topological sort python implementation """ + stack = [] + visited = set() + + def topological_sort_util(vertex): + """ modified depth-first search recursive algorithm """ + visited.add(vertex) + for node in graph[vertex]: + if node not in visited: + topological_sort_util(node) + stack.append(vertex) + + + for vertex in list(graph): + if vertex not in visited: + topological_sort_util(vertex) + + stack.reverse() + return stack + + +def main(): + """ operational function """ + graph = { + 0: [1, 2, 5], + 1: [4], + 2: [], + 3: [2, 4, 5, 6], + 4: [], + 5: [2], + 6: [0, 4] + } + print(topological_sort(graph)) + + +if __name__ == "__main__": + main() From ccbf97f9484c01f4ea0e0d334df0a1a4233a7259 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sun, 29 Aug 2021 11:38:25 +0530 Subject: [PATCH 204/209] add graph dijkstra algorithm --- graph/dijkstra_algorithm.py | 48 +++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 graph/dijkstra_algorithm.py diff --git a/graph/dijkstra_algorithm.py b/graph/dijkstra_algorithm.py new file mode 100644 index 0000000..8de0ede --- /dev/null +++ b/graph/dijkstra_algorithm.py @@ -0,0 +1,48 @@ +""" Dijkstra's Algorithm to calculate single sources shortest path +""" + +import heapq + +def calculate_distances(graph, starting_vertex): + distances = {vertex: float('infinity') for vertex in graph} + distances[starting_vertex] = 0 + + pq = [(0, starting_vertex)] + while len(pq) > 0: + current_distance, current_vertex = heapq.heappop(pq) + + # Nodes can get added to the priority queue multiple times. We only + # process a vertex the first time we remove it from the priority queue. + if current_distance > distances[current_vertex]: + continue + + for neighbor, weight in graph[current_vertex].items(): + distance = current_distance + weight + + # Only consider this new path if it's better than any path we've + # already found. + if distance < distances[neighbor]: + distances[neighbor] = distance + heapq.heappush(pq, (distance, neighbor)) + + return distances + + +def main(): + """ operational function """ + graph = { + 'A': {'B': 5, 'E': 9, 'H': 8}, + 'B': {'C': 12, 'D': 15, 'H': 4}, + 'C': {'D': 3, 'G': 11}, + 'D': {'G': 9}, + 'E': {'F': 4, 'G': 20, 'H': 5}, + 'F': {'C': 1, 'G': 13}, + 'G': {}, + 'H': {'C': 7, 'F': 6} + } + + print(calculate_distances(graph, 'A')) + + +if __name__ == "__main__": + main() From d71181253e4e2f4268e53078c42790560892e9cd Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Wed, 20 Oct 2021 15:25:59 +0530 Subject: [PATCH 205/209] reverse an array --- array/reverse_array_inplace.py | 41 ++++++++++++++++++++++++++++++---- 1 file changed, 37 insertions(+), 4 deletions(-) diff --git a/array/reverse_array_inplace.py b/array/reverse_array_inplace.py index 8afef5f..1d3e763 100644 --- a/array/reverse_array_inplace.py +++ b/array/reverse_array_inplace.py @@ -4,9 +4,42 @@ For example: input is [1,2,3,4,5] then the output is [5,4,3,2,1] """ -arr = [1, 2, 3, 4, 5, 6] +def iterative_reverse(arr): + """ reverse a list using iterative approach """ + start = 0 + end = len(arr) - 1 + while start < end: + arr[start], arr[end] = arr[end], arr[start] + start += 1 + end -= 1 -for i in range(len(arr) // 2): - arr[i], arr[len(arr)-1-i] = arr[len(arr)-1-i], arr[i] -print(arr) +def recursive_reverse(arr, start, end): + """ reverse a list using recursive approach """ + if start < end: + arr[start], arr[end] = arr[end], arr[start] + recursive_reverse(arr, start + 1, end - 1) + + +def python_slicing_reverse(arr): + """ reverse list using python list slicing """ + return arr[::-1] + + +def main(): + """ operational function """ + arr = [1, 2, 3, 4, 5, 6] + iterative_reverse(arr) + assert arr == [6, 5, 4, 3, 2, 1] + + arr = [1, 2, 3, 4, 5] + recursive_reverse(arr, 0, len(arr) - 1) + assert arr == [5, 4, 3, 2, 1] + + arr = [1, 2, 3, 4, 5] + arr = python_slicing_reverse(arr) + assert arr == [5, 4, 3, 2, 1] + + +if __name__ == '__main__': + main() From 0e10a108eb7acbe40ea87c46f027234666cf1466 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Mon, 25 Oct 2021 19:32:16 +0530 Subject: [PATCH 206/209] find min max in array --- array/min_max_arr.py | 112 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 112 insertions(+) create mode 100644 array/min_max_arr.py diff --git a/array/min_max_arr.py b/array/min_max_arr.py new file mode 100644 index 0000000..fa2361f --- /dev/null +++ b/array/min_max_arr.py @@ -0,0 +1,112 @@ +""" Maximum and minimum of an array using minimum number of comparisons + + Tournament Method and pair comparison approaches make the equal number of comparisons + when n is a power of 2. + In general, pair comparison seems to be the best. +""" + +def getminmax_linear_search(arr): + """ Linear method + Initialize values of min and max as minimum and maximum of the first two elements + respectively. Starting from 3rd, compare each element with max and min, and + change max and min accordingly + """ + if len(arr) == 0: + return None, None + + if len(arr) == 1: + return arr[0], arr[0] + + min_num = None + max_num = None + if arr[0] > arr[1]: + max_num = arr[0] + min_num = arr[1] + else: + max_num = arr[1] + min_num = arr[0] + + for idx in range(2, len(arr)): + if min_num > arr[idx]: + min_num = arr[idx] + if max_num < arr[idx]: + max_num = arr[idx] + + return min_num, max_num + + +def getminmax_tournament(arr, low, high): + """ Tournament Method + Divide the array into two parts and compare the maximums and minimums of the two + parts to get the maximum and the minimum of the whole array. + """ + if low == high: + return arr[low], arr[low] + + if abs(low - high) == 1: + min_num = None + max_num = None + if arr[low] > arr[high]: + max_num = arr[low] + min_num = arr[high] + else: + max_num = arr[high] + min_num = arr[low] + return min_num, max_num + + else: + mid = (low + high) // 2 + min_num_1, max_num_1 = getminmax_tournament(arr, low, mid) + min_num_2, max_num_2 = getminmax_tournament(arr, mid+1, high) + return min(min_num_1, min_num_2), max(max_num_1, max_num_2) + + +def getminmax_pair_compare(arr): + """ Compare in pairs + If n is odd then initialize min and max as first element. + If n is even then initialize min and max as minimum and maximum of the first two elements respectively. + For rest of the elements, pick them in pairs and compare their maximum and minimum + with max and min respectively. + """ + if len(arr) == 0: + return None, None + if len(arr) == 1: + return arr[0], arr[0] + + min_num = None + max_num = None + index = 0 + if len(arr) % 2 == 0: + if arr[0] > arr[1]: + max_num = arr[0] + min_num = arr[1] + else: + max_num = arr[1] + min_num = arr[0] + index = 2 + else: + max_num = arr[0] + min_num = arr[0] + index = 1 + while index < len(arr) - 1: + if arr[index] > arr[index + 1]: + max_num = max(arr[index], max_num) + min_num = min(arr[index + 1], min_num) + else: + max_num = max(arr[index + 1], max_num) + min_num = min(arr[index], min_num) + index += 2 + + return min_num, max_num + + +def main(): + """ operational function """ + arr = [1000, 11, 445, 100, 3300, 3000] + print(getminmax_linear_search(arr)) + print(getminmax_tournament(arr, 0, len(arr) - 1)) + print(getminmax_pair_compare(arr)) + + +if __name__ == '__main__': + main() From c435acc3e7a067de534372f8f7156f8fcf6e04ab Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sun, 21 Nov 2021 18:45:30 +0530 Subject: [PATCH 207/209] add quick select python algo --- array/kth_largest.py | 63 ++++++++++++++++++++++++++++++++++++++++ cpp/Sort/QuickSelect.cpp | 22 +++++++------- 2 files changed, 74 insertions(+), 11 deletions(-) create mode 100644 array/kth_largest.py diff --git a/array/kth_largest.py b/array/kth_largest.py new file mode 100644 index 0000000..a174aa1 --- /dev/null +++ b/array/kth_largest.py @@ -0,0 +1,63 @@ +""" +Given an array arr[] and an integer K where K is smaller than size of array, +the task is to find the Kth smallest element in the given array. +It is given that all array elements are distinct. + +Input: arr[] = 7 10 4 3 20 15; K = 3 +Output: 7 +Explanation: 3rd smallest element in the given array is 7. + +Solution: We are going to solve this using quick select algorithm +""" + +class QuickSelect: + """ QuickSelect is a selection algorithm to find the k-th smallest element in + an unordered list. It is related to the quick sort sorting algorithm. + """ + def __init__(self, arr, k): + self.arr = arr + self.k = k + + def partition(self, low, high): + """ return partition index of pivot """ + idx = low + j = low + while j < high: + if self.arr[j] <= self.arr[high]: + self.arr[idx], self.arr[j] = self.arr[j], self.arr[idx] + idx += 1 + j += 1 + self.arr[idx], self.arr[high] = self.arr[high], self.arr[idx] + return idx + + def run(self, low, high): + """ main quick select algorithm """ + if self.k >= len(self.arr): + raise Exception('k can not be larger than array length') + + while low < high: + pivot = self.partition(low, high) + if pivot < self.k: + low = pivot + 1 + elif pivot > self.k: + high = pivot - 1 + else: + return self.arr[self.k] + return self.arr[self.k] + + +def kth_largest(arr, k): + """ returns kth largest element in the array """ + qs = QuickSelect(arr, k - 1) + return qs.run(0, len(arr) - 1) + + +def main(): + """ operational function """ + assert kth_largest([7, 10, 4, 3, 20, 15], 1) == 3 + assert kth_largest([7, 10, 4, 3, 20, 15], 3) == 7 + assert kth_largest([7, 10, 4, 3, 20, 15], 6) == 20 + + +if __name__ == '__main__': + main() diff --git a/cpp/Sort/QuickSelect.cpp b/cpp/Sort/QuickSelect.cpp index 8dfd87f..1997531 100644 --- a/cpp/Sort/QuickSelect.cpp +++ b/cpp/Sort/QuickSelect.cpp @@ -111,15 +111,15 @@ int partition(T data[], int low, int high) template int medianOfThree(T data[], int low, int high) { - int mid = (low + high) / 2; - if (data[high] < data[low]) { - std::swap(data[high], data[low]); - } - if (data[low] > data[mid]) { - std::swap(data[mid], data[low]); - } - if (data[mid] > data[high]) { - std::swap(data[high], data[mid]); - } - return mid; + int mid = (low + high) / 2; + if (data[high] < data[low]) { + std::swap(data[high], data[low]); + } + if (data[low] > data[mid]) { + std::swap(data[mid], data[low]); + } + if (data[mid] > data[high]) { + std::swap(data[high], data[mid]); + } + return mid; } \ No newline at end of file From c361aa9071573fa9966d5b02d05e524815abcf2b Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sat, 1 Jan 2022 10:20:08 +0530 Subject: [PATCH 208/209] folder restructure --- {c_language => _other_languages/c_language}/README.md | 0 .../c_language}/dynamic_connectivity/quick_find/Makefile | 0 .../c_language}/dynamic_connectivity/quick_find/main.c | 0 .../c_language}/dynamic_connectivity/quick_find/quick_find.c | 0 .../c_language}/dynamic_connectivity/quick_find/quick_find.h | 0 .../c_language}/dynamic_connectivity/quick_union/Makefile | 0 .../c_language}/dynamic_connectivity/quick_union/main.c | 0 .../c_language}/dynamic_connectivity/quick_union/quick_union.c | 0 .../c_language}/dynamic_connectivity/quick_union/quick_union.h | 0 {c_language => _other_languages/c_language}/queue/Makefile | 0 {c_language => _other_languages/c_language}/queue/main.c | 0 {c_language => _other_languages/c_language}/queue/queue.c | 0 {c_language => _other_languages/c_language}/queue/queue.h | 0 {c_language => _other_languages/c_language}/shuffling/Makefile | 0 .../c_language}/shuffling/shuffle_array.c | 0 .../c_language}/sorts/bubble_sort/Makefile | 0 .../c_language}/sorts/bubble_sort/bubble_sort.c | 0 .../c_language}/sorts/generic/Makefile | 0 .../c_language}/sorts/generic/README.md | 0 {c_language => _other_languages/c_language}/sorts/generic/main.c | 0 {c_language => _other_languages/c_language}/sorts/generic/sort.c | 0 {c_language => _other_languages/c_language}/sorts/generic/sort.h | 0 .../c_language}/sorts/insertion_sort/Makefile | 0 .../c_language}/sorts/insertion_sort/insertion_sort.c | 0 .../c_language}/sorts/merge_sort/Makefile | 0 .../c_language}/sorts/merge_sort/merge_sort.c | 0 .../c_language}/sorts/quick_sort/Makefile | 0 .../c_language}/sorts/quick_sort/quick_sort.c | 0 .../c_language}/sorts/selection_sort/Makefile | 0 .../c_language}/sorts/selection_sort/selection_sort.c | 0 .../c_language}/sorts/shell_sort/Makefile | 0 .../c_language}/sorts/shell_sort/shell_sort.c | 0 .../c_language}/stack/array_implementation/Makefile | 0 .../c_language}/stack/array_implementation/main.c | 0 .../c_language}/stack/array_implementation/stack.c | 0 .../c_language}/stack/array_implementation/stack.h | 0 .../c_language}/stack/generic_array_implementation/Makefile | 0 .../c_language}/stack/generic_array_implementation/main.c | 0 .../c_language}/stack/generic_array_implementation/stack.c | 0 .../c_language}/stack/generic_array_implementation/stack.h | 0 {cpp => _other_languages/cpp}/BinarySearchTree/BST/BST.cpp | 0 {cpp => _other_languages/cpp}/BinarySearchTree/BST/BST.hpp | 0 {cpp => _other_languages/cpp}/BinarySearchTree/BST/Makefile | 0 {cpp => _other_languages/cpp}/BinarySearchTree/BST/test_BST.cpp | 0 {cpp => _other_languages/cpp}/BinarySearchTree/bfsTraversal.cpp | 0 {cpp => _other_languages/cpp}/BinarySearchTree/dfsTraversal.cpp | 0 .../cpp}/BinarySearchTree/inorderSuccessor.cpp | 0 {cpp => _other_languages/cpp}/BinarySearchTree/isBST.cpp | 0 {cpp => _other_languages/cpp}/Bitwise/common_elements.cpp | 0 {cpp => _other_languages/cpp}/Bitwise/string_subsequence.cpp | 0 .../cpp}/Bitwise/subset_sum_queries_bitset.cpp | 0 {cpp => _other_languages/cpp}/Bitwise/two_unique_numbers.cpp | 0 {cpp => _other_languages/cpp}/Bitwise/unique_number.cpp | 0 {cpp => _other_languages/cpp}/Bitwise/unique_number_k_times.cpp | 0 {cpp => _other_languages/cpp}/DynamicConnectivity/QuickFind.cpp | 0 {cpp => _other_languages/cpp}/DynamicConnectivity/QuickUnion.cpp | 0 .../cpp}/DynamicConnectivity/WeightedQuickUnion.cpp | 0 {cpp => _other_languages/cpp}/Heap/HeapException.hpp | 0 {cpp => _other_languages/cpp}/Heap/Makefile | 0 {cpp => _other_languages/cpp}/Heap/MaxHeap.hpp | 0 {cpp => _other_languages/cpp}/Heap/MinHeap.hpp | 0 {cpp => _other_languages/cpp}/Heap/test_Heap.cpp | 0 .../cpp}/LinkedList/LinkedList/LinkedList.hpp | 0 {cpp => _other_languages/cpp}/LinkedList/LinkedList/Makefile | 0 .../cpp}/LinkedList/LinkedList/test_LinkedList.cpp | 0 {cpp => _other_languages/cpp}/LinkedList/countFrequency.cpp | 0 {cpp => _other_languages/cpp}/LinkedList/detectLoop.cpp | 0 {cpp => _other_languages/cpp}/LinkedList/findMiddle.cpp | 0 {cpp => _other_languages/cpp}/LinkedList/getNthNodeFromEnd.cpp | 0 {cpp => _other_languages/cpp}/LinkedList/lengthOfLoop.cpp | 0 .../cpp}/Maths/count_divisors_of_factorial.cpp | 0 {cpp => _other_languages/cpp}/Maths/divisors.cpp | 0 .../cpp}/Maths/extended_euclidean_algorithm.cpp | 0 {cpp => _other_languages/cpp}/Maths/gcd_euclidean.cpp | 0 {cpp => _other_languages/cpp}/Maths/least_prime_factor.cpp | 0 {cpp => _other_languages/cpp}/Maths/legendres_formula.cpp | 0 {cpp => _other_languages/cpp}/Maths/modular_exponential.cpp | 0 .../cpp}/Maths/modular_multiplicative_inverse.cpp | 0 {cpp => _other_languages/cpp}/Maths/number_of_divisors.cpp | 0 {cpp => _other_languages/cpp}/Maths/prime_factors.cpp | 0 {cpp => _other_languages/cpp}/Maths/prime_factors_using_sieve.cpp | 0 {cpp => _other_languages/cpp}/Maths/segmented_sieve.cpp | 0 {cpp => _other_languages/cpp}/Maths/sieve_of_eratosthenes.cpp | 0 {cpp => _other_languages/cpp}/Maths/sum_of_divisors.cpp | 0 {cpp => _other_languages/cpp}/Queue/Queue/Makefile | 0 {cpp => _other_languages/cpp}/Queue/Queue/Queue.hpp | 0 {cpp => _other_languages/cpp}/Queue/Queue/test_Queue.cpp | 0 {cpp => _other_languages/cpp}/Queue/ReverseQueue.cpp | 0 .../cpp}/Queue/SortQueueWithoutExtraSpace.cpp | 0 {cpp => _other_languages/cpp}/README.md | 0 {cpp => _other_languages/cpp}/RedBlackTree/Makefile | 0 {cpp => _other_languages/cpp}/RedBlackTree/RedBlackTree.cpp | 0 {cpp => _other_languages/cpp}/RedBlackTree/RedBlackTree.hpp | 0 {cpp => _other_languages/cpp}/RedBlackTree/find.cpp | 0 {cpp => _other_languages/cpp}/RedBlackTree/insert.cpp | 0 {cpp => _other_languages/cpp}/RedBlackTree/test_RedBlackTree.cpp | 0 {cpp => _other_languages/cpp}/RedBlackTree/utils.cpp | 0 {cpp => _other_languages/cpp}/Search/BinarySearch.h | 0 {cpp => _other_languages/cpp}/Search/Makefile | 0 {cpp => _other_languages/cpp}/Search/test_BinarySearch.cpp | 0 {cpp => _other_languages/cpp}/Shuffle/Shuffle.cpp | 0 {cpp => _other_languages/cpp}/Sort/BubbleSort.cpp | 0 {cpp => _other_languages/cpp}/Sort/CountingSort.cpp | 0 {cpp => _other_languages/cpp}/Sort/GnomeSort.cpp | 0 {cpp => _other_languages/cpp}/Sort/HeapSort.cpp | 0 {cpp => _other_languages/cpp}/Sort/InsertionSort.cpp | 0 {cpp => _other_languages/cpp}/Sort/MergeBottomUp.cpp | 0 {cpp => _other_languages/cpp}/Sort/MergeOptimizeSort.cpp | 0 {cpp => _other_languages/cpp}/Sort/MergeSort.cpp | 0 {cpp => _other_languages/cpp}/Sort/OddEvenSort.cpp | 0 {cpp => _other_languages/cpp}/Sort/Quick3WaySort.cpp | 0 {cpp => _other_languages/cpp}/Sort/QuickOptimizeSort.cpp | 0 {cpp => _other_languages/cpp}/Sort/QuickSelect.cpp | 0 {cpp => _other_languages/cpp}/Sort/QuickSort.cpp | 0 {cpp => _other_languages/cpp}/Sort/SelectionSort.cpp | 0 {cpp => _other_languages/cpp}/Sort/ShellSort.cpp | 0 {cpp => _other_languages/cpp}/Stack/Stack/Makefile | 0 {cpp => _other_languages/cpp}/Stack/Stack/Stack.hpp | 0 {cpp => _other_languages/cpp}/Stack/Stack/test_Stack.cpp | 0 {cpp => _other_languages/cpp}/Stack/balancedParanthesis.cpp | 0 {cpp => _other_languages/cpp}/Stack/bracketReversals.cpp | 0 {cpp => _other_languages/cpp}/Stack/deleteMiddleElement.cpp | 0 {cpp => _other_languages/cpp}/Stack/infixToPostfix.cpp | 0 {cpp => _other_languages/cpp}/Stack/trackingCurrentMax.cpp | 0 {golang => _other_languages/golang}/README.md | 0 {golang => _other_languages/golang}/bst/bst.go | 0 {golang => _other_languages/golang}/bst/bst_test.go | 0 {golang => _other_languages/golang}/bst/checkbst.go | 0 {golang => _other_languages/golang}/bst/delete.go | 0 {golang => _other_languages/golang}/bst/find.go | 0 {golang => _other_languages/golang}/bst/height.go | 0 {golang => _other_languages/golang}/bst/insert.go | 0 {golang => _other_languages/golang}/bst/traversal.go | 0 .../golang}/doublylinkedlist/doublylinkedlist.go | 0 .../golang}/doublylinkedlist/doublylinkedlist_test.go | 0 {golang => _other_languages/golang}/hashtable/hashtable.go | 0 {golang => _other_languages/golang}/hashtable/hashtable_test.go | 0 {golang => _other_languages/golang}/heap/doc.go | 0 {golang => _other_languages/golang}/heap/maxheap/maxheap.go | 0 {golang => _other_languages/golang}/heap/maxheap/maxheap_test.go | 0 {golang => _other_languages/golang}/heap/minheap/minheap.go | 0 {golang => _other_languages/golang}/heap/minheap/minheap_test.go | 0 {golang => _other_languages/golang}/linkedlist/linkedlist.go | 0 {golang => _other_languages/golang}/linkedlist/linkedlist_test.go | 0 {golang => _other_languages/golang}/queue/queue.go | 0 {golang => _other_languages/golang}/queue/queue_test.go | 0 {golang => _other_languages/golang}/redblacktree/doc.go | 0 {golang => _other_languages/golang}/redblacktree/find.go | 0 {golang => _other_languages/golang}/redblacktree/insert.go | 0 {golang => _other_languages/golang}/redblacktree/redblacktree.go | 0 .../golang}/redblacktree/redblacktree_test.go | 0 {golang => _other_languages/golang}/redblacktree/utils.go | 0 {golang => _other_languages/golang}/search/binarysearch.go | 0 {golang => _other_languages/golang}/search/binarysearch_test.go | 0 {golang => _other_languages/golang}/set/set.go | 0 {golang => _other_languages/golang}/set/set_test.go | 0 {golang => _other_languages/golang}/shuffle/shuffle.go | 0 {golang => _other_languages/golang}/sort/bubble.go | 0 {golang => _other_languages/golang}/sort/countingSort.go | 0 {golang => _other_languages/golang}/sort/gnome.go | 0 {golang => _other_languages/golang}/sort/heap.go | 0 {golang => _other_languages/golang}/sort/insertion.go | 0 {golang => _other_languages/golang}/sort/merge.go | 0 {golang => _other_languages/golang}/sort/oddeven.go | 0 {golang => _other_languages/golang}/sort/quick.go | 0 {golang => _other_languages/golang}/sort/quickselect.go | 0 {golang => _other_languages/golang}/sort/selection.go | 0 {golang => _other_languages/golang}/sort/shell.go | 0 {golang => _other_languages/golang}/sort/sort.go | 0 {golang => _other_languages/golang}/sort/sort_test.go | 0 .../golang}/stack/applications/applications.go | 0 .../golang}/stack/applications/applications_test.go | 0 .../golang}/stack/applications/infixevaluation.go | 0 .../golang}/stack/applications/infixtopostfix.go | 0 .../golang}/stack/applications/infixtoprefix.go | 0 {golang => _other_languages/golang}/stack/applications/utils.go | 0 {golang => _other_languages/golang}/stack/stack.go | 0 {golang => _other_languages/golang}/stack/stack_test.go | 0 {golang => _other_languages/golang}/trie/trie.go | 0 {golang => _other_languages/golang}/trie/trie_test.go | 0 180 files changed, 0 insertions(+), 0 deletions(-) rename {c_language => _other_languages/c_language}/README.md (100%) rename {c_language => _other_languages/c_language}/dynamic_connectivity/quick_find/Makefile (100%) rename {c_language => _other_languages/c_language}/dynamic_connectivity/quick_find/main.c (100%) rename {c_language => _other_languages/c_language}/dynamic_connectivity/quick_find/quick_find.c (100%) rename {c_language => _other_languages/c_language}/dynamic_connectivity/quick_find/quick_find.h (100%) rename {c_language => _other_languages/c_language}/dynamic_connectivity/quick_union/Makefile (100%) rename {c_language => _other_languages/c_language}/dynamic_connectivity/quick_union/main.c (100%) rename {c_language => _other_languages/c_language}/dynamic_connectivity/quick_union/quick_union.c (100%) rename {c_language => _other_languages/c_language}/dynamic_connectivity/quick_union/quick_union.h (100%) rename {c_language => _other_languages/c_language}/queue/Makefile (100%) rename {c_language => _other_languages/c_language}/queue/main.c (100%) rename {c_language => _other_languages/c_language}/queue/queue.c (100%) rename {c_language => _other_languages/c_language}/queue/queue.h (100%) rename {c_language => _other_languages/c_language}/shuffling/Makefile (100%) rename {c_language => _other_languages/c_language}/shuffling/shuffle_array.c (100%) rename {c_language => _other_languages/c_language}/sorts/bubble_sort/Makefile (100%) rename {c_language => _other_languages/c_language}/sorts/bubble_sort/bubble_sort.c (100%) rename {c_language => _other_languages/c_language}/sorts/generic/Makefile (100%) rename {c_language => _other_languages/c_language}/sorts/generic/README.md (100%) rename {c_language => _other_languages/c_language}/sorts/generic/main.c (100%) rename {c_language => _other_languages/c_language}/sorts/generic/sort.c (100%) rename {c_language => _other_languages/c_language}/sorts/generic/sort.h (100%) rename {c_language => _other_languages/c_language}/sorts/insertion_sort/Makefile (100%) rename {c_language => _other_languages/c_language}/sorts/insertion_sort/insertion_sort.c (100%) rename {c_language => _other_languages/c_language}/sorts/merge_sort/Makefile (100%) rename {c_language => _other_languages/c_language}/sorts/merge_sort/merge_sort.c (100%) rename {c_language => _other_languages/c_language}/sorts/quick_sort/Makefile (100%) rename {c_language => _other_languages/c_language}/sorts/quick_sort/quick_sort.c (100%) rename {c_language => _other_languages/c_language}/sorts/selection_sort/Makefile (100%) rename {c_language => _other_languages/c_language}/sorts/selection_sort/selection_sort.c (100%) rename {c_language => _other_languages/c_language}/sorts/shell_sort/Makefile (100%) rename {c_language => _other_languages/c_language}/sorts/shell_sort/shell_sort.c (100%) rename {c_language => _other_languages/c_language}/stack/array_implementation/Makefile (100%) rename {c_language => _other_languages/c_language}/stack/array_implementation/main.c (100%) rename {c_language => _other_languages/c_language}/stack/array_implementation/stack.c (100%) rename {c_language => _other_languages/c_language}/stack/array_implementation/stack.h (100%) rename {c_language => _other_languages/c_language}/stack/generic_array_implementation/Makefile (100%) rename {c_language => _other_languages/c_language}/stack/generic_array_implementation/main.c (100%) rename {c_language => _other_languages/c_language}/stack/generic_array_implementation/stack.c (100%) rename {c_language => _other_languages/c_language}/stack/generic_array_implementation/stack.h (100%) rename {cpp => _other_languages/cpp}/BinarySearchTree/BST/BST.cpp (100%) rename {cpp => _other_languages/cpp}/BinarySearchTree/BST/BST.hpp (100%) rename {cpp => _other_languages/cpp}/BinarySearchTree/BST/Makefile (100%) rename {cpp => _other_languages/cpp}/BinarySearchTree/BST/test_BST.cpp (100%) rename {cpp => _other_languages/cpp}/BinarySearchTree/bfsTraversal.cpp (100%) rename {cpp => _other_languages/cpp}/BinarySearchTree/dfsTraversal.cpp (100%) rename {cpp => _other_languages/cpp}/BinarySearchTree/inorderSuccessor.cpp (100%) rename {cpp => _other_languages/cpp}/BinarySearchTree/isBST.cpp (100%) rename {cpp => _other_languages/cpp}/Bitwise/common_elements.cpp (100%) rename {cpp => _other_languages/cpp}/Bitwise/string_subsequence.cpp (100%) rename {cpp => _other_languages/cpp}/Bitwise/subset_sum_queries_bitset.cpp (100%) rename {cpp => _other_languages/cpp}/Bitwise/two_unique_numbers.cpp (100%) rename {cpp => _other_languages/cpp}/Bitwise/unique_number.cpp (100%) rename {cpp => _other_languages/cpp}/Bitwise/unique_number_k_times.cpp (100%) rename {cpp => _other_languages/cpp}/DynamicConnectivity/QuickFind.cpp (100%) rename {cpp => _other_languages/cpp}/DynamicConnectivity/QuickUnion.cpp (100%) rename {cpp => _other_languages/cpp}/DynamicConnectivity/WeightedQuickUnion.cpp (100%) rename {cpp => _other_languages/cpp}/Heap/HeapException.hpp (100%) rename {cpp => _other_languages/cpp}/Heap/Makefile (100%) rename {cpp => _other_languages/cpp}/Heap/MaxHeap.hpp (100%) rename {cpp => _other_languages/cpp}/Heap/MinHeap.hpp (100%) rename {cpp => _other_languages/cpp}/Heap/test_Heap.cpp (100%) rename {cpp => _other_languages/cpp}/LinkedList/LinkedList/LinkedList.hpp (100%) rename {cpp => _other_languages/cpp}/LinkedList/LinkedList/Makefile (100%) rename {cpp => _other_languages/cpp}/LinkedList/LinkedList/test_LinkedList.cpp (100%) rename {cpp => _other_languages/cpp}/LinkedList/countFrequency.cpp (100%) rename {cpp => _other_languages/cpp}/LinkedList/detectLoop.cpp (100%) rename {cpp => _other_languages/cpp}/LinkedList/findMiddle.cpp (100%) rename {cpp => _other_languages/cpp}/LinkedList/getNthNodeFromEnd.cpp (100%) rename {cpp => _other_languages/cpp}/LinkedList/lengthOfLoop.cpp (100%) rename {cpp => _other_languages/cpp}/Maths/count_divisors_of_factorial.cpp (100%) rename {cpp => _other_languages/cpp}/Maths/divisors.cpp (100%) rename {cpp => _other_languages/cpp}/Maths/extended_euclidean_algorithm.cpp (100%) rename {cpp => _other_languages/cpp}/Maths/gcd_euclidean.cpp (100%) rename {cpp => _other_languages/cpp}/Maths/least_prime_factor.cpp (100%) rename {cpp => _other_languages/cpp}/Maths/legendres_formula.cpp (100%) rename {cpp => _other_languages/cpp}/Maths/modular_exponential.cpp (100%) rename {cpp => _other_languages/cpp}/Maths/modular_multiplicative_inverse.cpp (100%) rename {cpp => _other_languages/cpp}/Maths/number_of_divisors.cpp (100%) rename {cpp => _other_languages/cpp}/Maths/prime_factors.cpp (100%) rename {cpp => _other_languages/cpp}/Maths/prime_factors_using_sieve.cpp (100%) rename {cpp => _other_languages/cpp}/Maths/segmented_sieve.cpp (100%) rename {cpp => _other_languages/cpp}/Maths/sieve_of_eratosthenes.cpp (100%) rename {cpp => _other_languages/cpp}/Maths/sum_of_divisors.cpp (100%) rename {cpp => _other_languages/cpp}/Queue/Queue/Makefile (100%) rename {cpp => _other_languages/cpp}/Queue/Queue/Queue.hpp (100%) rename {cpp => _other_languages/cpp}/Queue/Queue/test_Queue.cpp (100%) rename {cpp => _other_languages/cpp}/Queue/ReverseQueue.cpp (100%) rename {cpp => _other_languages/cpp}/Queue/SortQueueWithoutExtraSpace.cpp (100%) rename {cpp => _other_languages/cpp}/README.md (100%) rename {cpp => _other_languages/cpp}/RedBlackTree/Makefile (100%) rename {cpp => _other_languages/cpp}/RedBlackTree/RedBlackTree.cpp (100%) rename {cpp => _other_languages/cpp}/RedBlackTree/RedBlackTree.hpp (100%) rename {cpp => _other_languages/cpp}/RedBlackTree/find.cpp (100%) rename {cpp => _other_languages/cpp}/RedBlackTree/insert.cpp (100%) rename {cpp => _other_languages/cpp}/RedBlackTree/test_RedBlackTree.cpp (100%) rename {cpp => _other_languages/cpp}/RedBlackTree/utils.cpp (100%) rename {cpp => _other_languages/cpp}/Search/BinarySearch.h (100%) rename {cpp => _other_languages/cpp}/Search/Makefile (100%) rename {cpp => _other_languages/cpp}/Search/test_BinarySearch.cpp (100%) rename {cpp => _other_languages/cpp}/Shuffle/Shuffle.cpp (100%) rename {cpp => _other_languages/cpp}/Sort/BubbleSort.cpp (100%) rename {cpp => _other_languages/cpp}/Sort/CountingSort.cpp (100%) rename {cpp => _other_languages/cpp}/Sort/GnomeSort.cpp (100%) rename {cpp => _other_languages/cpp}/Sort/HeapSort.cpp (100%) rename {cpp => _other_languages/cpp}/Sort/InsertionSort.cpp (100%) rename {cpp => _other_languages/cpp}/Sort/MergeBottomUp.cpp (100%) rename {cpp => _other_languages/cpp}/Sort/MergeOptimizeSort.cpp (100%) rename {cpp => _other_languages/cpp}/Sort/MergeSort.cpp (100%) rename {cpp => _other_languages/cpp}/Sort/OddEvenSort.cpp (100%) rename {cpp => _other_languages/cpp}/Sort/Quick3WaySort.cpp (100%) rename {cpp => _other_languages/cpp}/Sort/QuickOptimizeSort.cpp (100%) rename {cpp => _other_languages/cpp}/Sort/QuickSelect.cpp (100%) rename {cpp => _other_languages/cpp}/Sort/QuickSort.cpp (100%) rename {cpp => _other_languages/cpp}/Sort/SelectionSort.cpp (100%) rename {cpp => _other_languages/cpp}/Sort/ShellSort.cpp (100%) rename {cpp => _other_languages/cpp}/Stack/Stack/Makefile (100%) rename {cpp => _other_languages/cpp}/Stack/Stack/Stack.hpp (100%) rename {cpp => _other_languages/cpp}/Stack/Stack/test_Stack.cpp (100%) rename {cpp => _other_languages/cpp}/Stack/balancedParanthesis.cpp (100%) rename {cpp => _other_languages/cpp}/Stack/bracketReversals.cpp (100%) rename {cpp => _other_languages/cpp}/Stack/deleteMiddleElement.cpp (100%) rename {cpp => _other_languages/cpp}/Stack/infixToPostfix.cpp (100%) rename {cpp => _other_languages/cpp}/Stack/trackingCurrentMax.cpp (100%) rename {golang => _other_languages/golang}/README.md (100%) rename {golang => _other_languages/golang}/bst/bst.go (100%) rename {golang => _other_languages/golang}/bst/bst_test.go (100%) rename {golang => _other_languages/golang}/bst/checkbst.go (100%) rename {golang => _other_languages/golang}/bst/delete.go (100%) rename {golang => _other_languages/golang}/bst/find.go (100%) rename {golang => _other_languages/golang}/bst/height.go (100%) rename {golang => _other_languages/golang}/bst/insert.go (100%) rename {golang => _other_languages/golang}/bst/traversal.go (100%) rename {golang => _other_languages/golang}/doublylinkedlist/doublylinkedlist.go (100%) rename {golang => _other_languages/golang}/doublylinkedlist/doublylinkedlist_test.go (100%) rename {golang => _other_languages/golang}/hashtable/hashtable.go (100%) rename {golang => _other_languages/golang}/hashtable/hashtable_test.go (100%) rename {golang => _other_languages/golang}/heap/doc.go (100%) rename {golang => _other_languages/golang}/heap/maxheap/maxheap.go (100%) rename {golang => _other_languages/golang}/heap/maxheap/maxheap_test.go (100%) rename {golang => _other_languages/golang}/heap/minheap/minheap.go (100%) rename {golang => _other_languages/golang}/heap/minheap/minheap_test.go (100%) rename {golang => _other_languages/golang}/linkedlist/linkedlist.go (100%) rename {golang => _other_languages/golang}/linkedlist/linkedlist_test.go (100%) rename {golang => _other_languages/golang}/queue/queue.go (100%) rename {golang => _other_languages/golang}/queue/queue_test.go (100%) rename {golang => _other_languages/golang}/redblacktree/doc.go (100%) rename {golang => _other_languages/golang}/redblacktree/find.go (100%) rename {golang => _other_languages/golang}/redblacktree/insert.go (100%) rename {golang => _other_languages/golang}/redblacktree/redblacktree.go (100%) rename {golang => _other_languages/golang}/redblacktree/redblacktree_test.go (100%) rename {golang => _other_languages/golang}/redblacktree/utils.go (100%) rename {golang => _other_languages/golang}/search/binarysearch.go (100%) rename {golang => _other_languages/golang}/search/binarysearch_test.go (100%) rename {golang => _other_languages/golang}/set/set.go (100%) rename {golang => _other_languages/golang}/set/set_test.go (100%) rename {golang => _other_languages/golang}/shuffle/shuffle.go (100%) rename {golang => _other_languages/golang}/sort/bubble.go (100%) rename {golang => _other_languages/golang}/sort/countingSort.go (100%) rename {golang => _other_languages/golang}/sort/gnome.go (100%) rename {golang => _other_languages/golang}/sort/heap.go (100%) rename {golang => _other_languages/golang}/sort/insertion.go (100%) rename {golang => _other_languages/golang}/sort/merge.go (100%) rename {golang => _other_languages/golang}/sort/oddeven.go (100%) rename {golang => _other_languages/golang}/sort/quick.go (100%) rename {golang => _other_languages/golang}/sort/quickselect.go (100%) rename {golang => _other_languages/golang}/sort/selection.go (100%) rename {golang => _other_languages/golang}/sort/shell.go (100%) rename {golang => _other_languages/golang}/sort/sort.go (100%) rename {golang => _other_languages/golang}/sort/sort_test.go (100%) rename {golang => _other_languages/golang}/stack/applications/applications.go (100%) rename {golang => _other_languages/golang}/stack/applications/applications_test.go (100%) rename {golang => _other_languages/golang}/stack/applications/infixevaluation.go (100%) rename {golang => _other_languages/golang}/stack/applications/infixtopostfix.go (100%) rename {golang => _other_languages/golang}/stack/applications/infixtoprefix.go (100%) rename {golang => _other_languages/golang}/stack/applications/utils.go (100%) rename {golang => _other_languages/golang}/stack/stack.go (100%) rename {golang => _other_languages/golang}/stack/stack_test.go (100%) rename {golang => _other_languages/golang}/trie/trie.go (100%) rename {golang => _other_languages/golang}/trie/trie_test.go (100%) diff --git a/c_language/README.md b/_other_languages/c_language/README.md similarity index 100% rename from c_language/README.md rename to _other_languages/c_language/README.md diff --git a/c_language/dynamic_connectivity/quick_find/Makefile b/_other_languages/c_language/dynamic_connectivity/quick_find/Makefile similarity index 100% rename from c_language/dynamic_connectivity/quick_find/Makefile rename to _other_languages/c_language/dynamic_connectivity/quick_find/Makefile diff --git a/c_language/dynamic_connectivity/quick_find/main.c b/_other_languages/c_language/dynamic_connectivity/quick_find/main.c similarity index 100% rename from c_language/dynamic_connectivity/quick_find/main.c rename to _other_languages/c_language/dynamic_connectivity/quick_find/main.c diff --git a/c_language/dynamic_connectivity/quick_find/quick_find.c b/_other_languages/c_language/dynamic_connectivity/quick_find/quick_find.c similarity index 100% rename from c_language/dynamic_connectivity/quick_find/quick_find.c rename to _other_languages/c_language/dynamic_connectivity/quick_find/quick_find.c diff --git a/c_language/dynamic_connectivity/quick_find/quick_find.h b/_other_languages/c_language/dynamic_connectivity/quick_find/quick_find.h similarity index 100% rename from c_language/dynamic_connectivity/quick_find/quick_find.h rename to _other_languages/c_language/dynamic_connectivity/quick_find/quick_find.h diff --git a/c_language/dynamic_connectivity/quick_union/Makefile b/_other_languages/c_language/dynamic_connectivity/quick_union/Makefile similarity index 100% rename from c_language/dynamic_connectivity/quick_union/Makefile rename to _other_languages/c_language/dynamic_connectivity/quick_union/Makefile diff --git a/c_language/dynamic_connectivity/quick_union/main.c b/_other_languages/c_language/dynamic_connectivity/quick_union/main.c similarity index 100% rename from c_language/dynamic_connectivity/quick_union/main.c rename to _other_languages/c_language/dynamic_connectivity/quick_union/main.c diff --git a/c_language/dynamic_connectivity/quick_union/quick_union.c b/_other_languages/c_language/dynamic_connectivity/quick_union/quick_union.c similarity index 100% rename from c_language/dynamic_connectivity/quick_union/quick_union.c rename to _other_languages/c_language/dynamic_connectivity/quick_union/quick_union.c diff --git a/c_language/dynamic_connectivity/quick_union/quick_union.h b/_other_languages/c_language/dynamic_connectivity/quick_union/quick_union.h similarity index 100% rename from c_language/dynamic_connectivity/quick_union/quick_union.h rename to _other_languages/c_language/dynamic_connectivity/quick_union/quick_union.h diff --git a/c_language/queue/Makefile b/_other_languages/c_language/queue/Makefile similarity index 100% rename from c_language/queue/Makefile rename to _other_languages/c_language/queue/Makefile diff --git a/c_language/queue/main.c b/_other_languages/c_language/queue/main.c similarity index 100% rename from c_language/queue/main.c rename to _other_languages/c_language/queue/main.c diff --git a/c_language/queue/queue.c b/_other_languages/c_language/queue/queue.c similarity index 100% rename from c_language/queue/queue.c rename to _other_languages/c_language/queue/queue.c diff --git a/c_language/queue/queue.h b/_other_languages/c_language/queue/queue.h similarity index 100% rename from c_language/queue/queue.h rename to _other_languages/c_language/queue/queue.h diff --git a/c_language/shuffling/Makefile b/_other_languages/c_language/shuffling/Makefile similarity index 100% rename from c_language/shuffling/Makefile rename to _other_languages/c_language/shuffling/Makefile diff --git a/c_language/shuffling/shuffle_array.c b/_other_languages/c_language/shuffling/shuffle_array.c similarity index 100% rename from c_language/shuffling/shuffle_array.c rename to _other_languages/c_language/shuffling/shuffle_array.c diff --git a/c_language/sorts/bubble_sort/Makefile b/_other_languages/c_language/sorts/bubble_sort/Makefile similarity index 100% rename from c_language/sorts/bubble_sort/Makefile rename to _other_languages/c_language/sorts/bubble_sort/Makefile diff --git a/c_language/sorts/bubble_sort/bubble_sort.c b/_other_languages/c_language/sorts/bubble_sort/bubble_sort.c similarity index 100% rename from c_language/sorts/bubble_sort/bubble_sort.c rename to _other_languages/c_language/sorts/bubble_sort/bubble_sort.c diff --git a/c_language/sorts/generic/Makefile b/_other_languages/c_language/sorts/generic/Makefile similarity index 100% rename from c_language/sorts/generic/Makefile rename to _other_languages/c_language/sorts/generic/Makefile diff --git a/c_language/sorts/generic/README.md b/_other_languages/c_language/sorts/generic/README.md similarity index 100% rename from c_language/sorts/generic/README.md rename to _other_languages/c_language/sorts/generic/README.md diff --git a/c_language/sorts/generic/main.c b/_other_languages/c_language/sorts/generic/main.c similarity index 100% rename from c_language/sorts/generic/main.c rename to _other_languages/c_language/sorts/generic/main.c diff --git a/c_language/sorts/generic/sort.c b/_other_languages/c_language/sorts/generic/sort.c similarity index 100% rename from c_language/sorts/generic/sort.c rename to _other_languages/c_language/sorts/generic/sort.c diff --git a/c_language/sorts/generic/sort.h b/_other_languages/c_language/sorts/generic/sort.h similarity index 100% rename from c_language/sorts/generic/sort.h rename to _other_languages/c_language/sorts/generic/sort.h diff --git a/c_language/sorts/insertion_sort/Makefile b/_other_languages/c_language/sorts/insertion_sort/Makefile similarity index 100% rename from c_language/sorts/insertion_sort/Makefile rename to _other_languages/c_language/sorts/insertion_sort/Makefile diff --git a/c_language/sorts/insertion_sort/insertion_sort.c b/_other_languages/c_language/sorts/insertion_sort/insertion_sort.c similarity index 100% rename from c_language/sorts/insertion_sort/insertion_sort.c rename to _other_languages/c_language/sorts/insertion_sort/insertion_sort.c diff --git a/c_language/sorts/merge_sort/Makefile b/_other_languages/c_language/sorts/merge_sort/Makefile similarity index 100% rename from c_language/sorts/merge_sort/Makefile rename to _other_languages/c_language/sorts/merge_sort/Makefile diff --git a/c_language/sorts/merge_sort/merge_sort.c b/_other_languages/c_language/sorts/merge_sort/merge_sort.c similarity index 100% rename from c_language/sorts/merge_sort/merge_sort.c rename to _other_languages/c_language/sorts/merge_sort/merge_sort.c diff --git a/c_language/sorts/quick_sort/Makefile b/_other_languages/c_language/sorts/quick_sort/Makefile similarity index 100% rename from c_language/sorts/quick_sort/Makefile rename to _other_languages/c_language/sorts/quick_sort/Makefile diff --git a/c_language/sorts/quick_sort/quick_sort.c b/_other_languages/c_language/sorts/quick_sort/quick_sort.c similarity index 100% rename from c_language/sorts/quick_sort/quick_sort.c rename to _other_languages/c_language/sorts/quick_sort/quick_sort.c diff --git a/c_language/sorts/selection_sort/Makefile b/_other_languages/c_language/sorts/selection_sort/Makefile similarity index 100% rename from c_language/sorts/selection_sort/Makefile rename to _other_languages/c_language/sorts/selection_sort/Makefile diff --git a/c_language/sorts/selection_sort/selection_sort.c b/_other_languages/c_language/sorts/selection_sort/selection_sort.c similarity index 100% rename from c_language/sorts/selection_sort/selection_sort.c rename to _other_languages/c_language/sorts/selection_sort/selection_sort.c diff --git a/c_language/sorts/shell_sort/Makefile b/_other_languages/c_language/sorts/shell_sort/Makefile similarity index 100% rename from c_language/sorts/shell_sort/Makefile rename to _other_languages/c_language/sorts/shell_sort/Makefile diff --git a/c_language/sorts/shell_sort/shell_sort.c b/_other_languages/c_language/sorts/shell_sort/shell_sort.c similarity index 100% rename from c_language/sorts/shell_sort/shell_sort.c rename to _other_languages/c_language/sorts/shell_sort/shell_sort.c diff --git a/c_language/stack/array_implementation/Makefile b/_other_languages/c_language/stack/array_implementation/Makefile similarity index 100% rename from c_language/stack/array_implementation/Makefile rename to _other_languages/c_language/stack/array_implementation/Makefile diff --git a/c_language/stack/array_implementation/main.c b/_other_languages/c_language/stack/array_implementation/main.c similarity index 100% rename from c_language/stack/array_implementation/main.c rename to _other_languages/c_language/stack/array_implementation/main.c diff --git a/c_language/stack/array_implementation/stack.c b/_other_languages/c_language/stack/array_implementation/stack.c similarity index 100% rename from c_language/stack/array_implementation/stack.c rename to _other_languages/c_language/stack/array_implementation/stack.c diff --git a/c_language/stack/array_implementation/stack.h b/_other_languages/c_language/stack/array_implementation/stack.h similarity index 100% rename from c_language/stack/array_implementation/stack.h rename to _other_languages/c_language/stack/array_implementation/stack.h diff --git a/c_language/stack/generic_array_implementation/Makefile b/_other_languages/c_language/stack/generic_array_implementation/Makefile similarity index 100% rename from c_language/stack/generic_array_implementation/Makefile rename to _other_languages/c_language/stack/generic_array_implementation/Makefile diff --git a/c_language/stack/generic_array_implementation/main.c b/_other_languages/c_language/stack/generic_array_implementation/main.c similarity index 100% rename from c_language/stack/generic_array_implementation/main.c rename to _other_languages/c_language/stack/generic_array_implementation/main.c diff --git a/c_language/stack/generic_array_implementation/stack.c b/_other_languages/c_language/stack/generic_array_implementation/stack.c similarity index 100% rename from c_language/stack/generic_array_implementation/stack.c rename to _other_languages/c_language/stack/generic_array_implementation/stack.c diff --git a/c_language/stack/generic_array_implementation/stack.h b/_other_languages/c_language/stack/generic_array_implementation/stack.h similarity index 100% rename from c_language/stack/generic_array_implementation/stack.h rename to _other_languages/c_language/stack/generic_array_implementation/stack.h diff --git a/cpp/BinarySearchTree/BST/BST.cpp b/_other_languages/cpp/BinarySearchTree/BST/BST.cpp similarity index 100% rename from cpp/BinarySearchTree/BST/BST.cpp rename to _other_languages/cpp/BinarySearchTree/BST/BST.cpp diff --git a/cpp/BinarySearchTree/BST/BST.hpp b/_other_languages/cpp/BinarySearchTree/BST/BST.hpp similarity index 100% rename from cpp/BinarySearchTree/BST/BST.hpp rename to _other_languages/cpp/BinarySearchTree/BST/BST.hpp diff --git a/cpp/BinarySearchTree/BST/Makefile b/_other_languages/cpp/BinarySearchTree/BST/Makefile similarity index 100% rename from cpp/BinarySearchTree/BST/Makefile rename to _other_languages/cpp/BinarySearchTree/BST/Makefile diff --git a/cpp/BinarySearchTree/BST/test_BST.cpp b/_other_languages/cpp/BinarySearchTree/BST/test_BST.cpp similarity index 100% rename from cpp/BinarySearchTree/BST/test_BST.cpp rename to _other_languages/cpp/BinarySearchTree/BST/test_BST.cpp diff --git a/cpp/BinarySearchTree/bfsTraversal.cpp b/_other_languages/cpp/BinarySearchTree/bfsTraversal.cpp similarity index 100% rename from cpp/BinarySearchTree/bfsTraversal.cpp rename to _other_languages/cpp/BinarySearchTree/bfsTraversal.cpp diff --git a/cpp/BinarySearchTree/dfsTraversal.cpp b/_other_languages/cpp/BinarySearchTree/dfsTraversal.cpp similarity index 100% rename from cpp/BinarySearchTree/dfsTraversal.cpp rename to _other_languages/cpp/BinarySearchTree/dfsTraversal.cpp diff --git a/cpp/BinarySearchTree/inorderSuccessor.cpp b/_other_languages/cpp/BinarySearchTree/inorderSuccessor.cpp similarity index 100% rename from cpp/BinarySearchTree/inorderSuccessor.cpp rename to _other_languages/cpp/BinarySearchTree/inorderSuccessor.cpp diff --git a/cpp/BinarySearchTree/isBST.cpp b/_other_languages/cpp/BinarySearchTree/isBST.cpp similarity index 100% rename from cpp/BinarySearchTree/isBST.cpp rename to _other_languages/cpp/BinarySearchTree/isBST.cpp diff --git a/cpp/Bitwise/common_elements.cpp b/_other_languages/cpp/Bitwise/common_elements.cpp similarity index 100% rename from cpp/Bitwise/common_elements.cpp rename to _other_languages/cpp/Bitwise/common_elements.cpp diff --git a/cpp/Bitwise/string_subsequence.cpp b/_other_languages/cpp/Bitwise/string_subsequence.cpp similarity index 100% rename from cpp/Bitwise/string_subsequence.cpp rename to _other_languages/cpp/Bitwise/string_subsequence.cpp diff --git a/cpp/Bitwise/subset_sum_queries_bitset.cpp b/_other_languages/cpp/Bitwise/subset_sum_queries_bitset.cpp similarity index 100% rename from cpp/Bitwise/subset_sum_queries_bitset.cpp rename to _other_languages/cpp/Bitwise/subset_sum_queries_bitset.cpp diff --git a/cpp/Bitwise/two_unique_numbers.cpp b/_other_languages/cpp/Bitwise/two_unique_numbers.cpp similarity index 100% rename from cpp/Bitwise/two_unique_numbers.cpp rename to _other_languages/cpp/Bitwise/two_unique_numbers.cpp diff --git a/cpp/Bitwise/unique_number.cpp b/_other_languages/cpp/Bitwise/unique_number.cpp similarity index 100% rename from cpp/Bitwise/unique_number.cpp rename to _other_languages/cpp/Bitwise/unique_number.cpp diff --git a/cpp/Bitwise/unique_number_k_times.cpp b/_other_languages/cpp/Bitwise/unique_number_k_times.cpp similarity index 100% rename from cpp/Bitwise/unique_number_k_times.cpp rename to _other_languages/cpp/Bitwise/unique_number_k_times.cpp diff --git a/cpp/DynamicConnectivity/QuickFind.cpp b/_other_languages/cpp/DynamicConnectivity/QuickFind.cpp similarity index 100% rename from cpp/DynamicConnectivity/QuickFind.cpp rename to _other_languages/cpp/DynamicConnectivity/QuickFind.cpp diff --git a/cpp/DynamicConnectivity/QuickUnion.cpp b/_other_languages/cpp/DynamicConnectivity/QuickUnion.cpp similarity index 100% rename from cpp/DynamicConnectivity/QuickUnion.cpp rename to _other_languages/cpp/DynamicConnectivity/QuickUnion.cpp diff --git a/cpp/DynamicConnectivity/WeightedQuickUnion.cpp b/_other_languages/cpp/DynamicConnectivity/WeightedQuickUnion.cpp similarity index 100% rename from cpp/DynamicConnectivity/WeightedQuickUnion.cpp rename to _other_languages/cpp/DynamicConnectivity/WeightedQuickUnion.cpp diff --git a/cpp/Heap/HeapException.hpp b/_other_languages/cpp/Heap/HeapException.hpp similarity index 100% rename from cpp/Heap/HeapException.hpp rename to _other_languages/cpp/Heap/HeapException.hpp diff --git a/cpp/Heap/Makefile b/_other_languages/cpp/Heap/Makefile similarity index 100% rename from cpp/Heap/Makefile rename to _other_languages/cpp/Heap/Makefile diff --git a/cpp/Heap/MaxHeap.hpp b/_other_languages/cpp/Heap/MaxHeap.hpp similarity index 100% rename from cpp/Heap/MaxHeap.hpp rename to _other_languages/cpp/Heap/MaxHeap.hpp diff --git a/cpp/Heap/MinHeap.hpp b/_other_languages/cpp/Heap/MinHeap.hpp similarity index 100% rename from cpp/Heap/MinHeap.hpp rename to _other_languages/cpp/Heap/MinHeap.hpp diff --git a/cpp/Heap/test_Heap.cpp b/_other_languages/cpp/Heap/test_Heap.cpp similarity index 100% rename from cpp/Heap/test_Heap.cpp rename to _other_languages/cpp/Heap/test_Heap.cpp diff --git a/cpp/LinkedList/LinkedList/LinkedList.hpp b/_other_languages/cpp/LinkedList/LinkedList/LinkedList.hpp similarity index 100% rename from cpp/LinkedList/LinkedList/LinkedList.hpp rename to _other_languages/cpp/LinkedList/LinkedList/LinkedList.hpp diff --git a/cpp/LinkedList/LinkedList/Makefile b/_other_languages/cpp/LinkedList/LinkedList/Makefile similarity index 100% rename from cpp/LinkedList/LinkedList/Makefile rename to _other_languages/cpp/LinkedList/LinkedList/Makefile diff --git a/cpp/LinkedList/LinkedList/test_LinkedList.cpp b/_other_languages/cpp/LinkedList/LinkedList/test_LinkedList.cpp similarity index 100% rename from cpp/LinkedList/LinkedList/test_LinkedList.cpp rename to _other_languages/cpp/LinkedList/LinkedList/test_LinkedList.cpp diff --git a/cpp/LinkedList/countFrequency.cpp b/_other_languages/cpp/LinkedList/countFrequency.cpp similarity index 100% rename from cpp/LinkedList/countFrequency.cpp rename to _other_languages/cpp/LinkedList/countFrequency.cpp diff --git a/cpp/LinkedList/detectLoop.cpp b/_other_languages/cpp/LinkedList/detectLoop.cpp similarity index 100% rename from cpp/LinkedList/detectLoop.cpp rename to _other_languages/cpp/LinkedList/detectLoop.cpp diff --git a/cpp/LinkedList/findMiddle.cpp b/_other_languages/cpp/LinkedList/findMiddle.cpp similarity index 100% rename from cpp/LinkedList/findMiddle.cpp rename to _other_languages/cpp/LinkedList/findMiddle.cpp diff --git a/cpp/LinkedList/getNthNodeFromEnd.cpp b/_other_languages/cpp/LinkedList/getNthNodeFromEnd.cpp similarity index 100% rename from cpp/LinkedList/getNthNodeFromEnd.cpp rename to _other_languages/cpp/LinkedList/getNthNodeFromEnd.cpp diff --git a/cpp/LinkedList/lengthOfLoop.cpp b/_other_languages/cpp/LinkedList/lengthOfLoop.cpp similarity index 100% rename from cpp/LinkedList/lengthOfLoop.cpp rename to _other_languages/cpp/LinkedList/lengthOfLoop.cpp diff --git a/cpp/Maths/count_divisors_of_factorial.cpp b/_other_languages/cpp/Maths/count_divisors_of_factorial.cpp similarity index 100% rename from cpp/Maths/count_divisors_of_factorial.cpp rename to _other_languages/cpp/Maths/count_divisors_of_factorial.cpp diff --git a/cpp/Maths/divisors.cpp b/_other_languages/cpp/Maths/divisors.cpp similarity index 100% rename from cpp/Maths/divisors.cpp rename to _other_languages/cpp/Maths/divisors.cpp diff --git a/cpp/Maths/extended_euclidean_algorithm.cpp b/_other_languages/cpp/Maths/extended_euclidean_algorithm.cpp similarity index 100% rename from cpp/Maths/extended_euclidean_algorithm.cpp rename to _other_languages/cpp/Maths/extended_euclidean_algorithm.cpp diff --git a/cpp/Maths/gcd_euclidean.cpp b/_other_languages/cpp/Maths/gcd_euclidean.cpp similarity index 100% rename from cpp/Maths/gcd_euclidean.cpp rename to _other_languages/cpp/Maths/gcd_euclidean.cpp diff --git a/cpp/Maths/least_prime_factor.cpp b/_other_languages/cpp/Maths/least_prime_factor.cpp similarity index 100% rename from cpp/Maths/least_prime_factor.cpp rename to _other_languages/cpp/Maths/least_prime_factor.cpp diff --git a/cpp/Maths/legendres_formula.cpp b/_other_languages/cpp/Maths/legendres_formula.cpp similarity index 100% rename from cpp/Maths/legendres_formula.cpp rename to _other_languages/cpp/Maths/legendres_formula.cpp diff --git a/cpp/Maths/modular_exponential.cpp b/_other_languages/cpp/Maths/modular_exponential.cpp similarity index 100% rename from cpp/Maths/modular_exponential.cpp rename to _other_languages/cpp/Maths/modular_exponential.cpp diff --git a/cpp/Maths/modular_multiplicative_inverse.cpp b/_other_languages/cpp/Maths/modular_multiplicative_inverse.cpp similarity index 100% rename from cpp/Maths/modular_multiplicative_inverse.cpp rename to _other_languages/cpp/Maths/modular_multiplicative_inverse.cpp diff --git a/cpp/Maths/number_of_divisors.cpp b/_other_languages/cpp/Maths/number_of_divisors.cpp similarity index 100% rename from cpp/Maths/number_of_divisors.cpp rename to _other_languages/cpp/Maths/number_of_divisors.cpp diff --git a/cpp/Maths/prime_factors.cpp b/_other_languages/cpp/Maths/prime_factors.cpp similarity index 100% rename from cpp/Maths/prime_factors.cpp rename to _other_languages/cpp/Maths/prime_factors.cpp diff --git a/cpp/Maths/prime_factors_using_sieve.cpp b/_other_languages/cpp/Maths/prime_factors_using_sieve.cpp similarity index 100% rename from cpp/Maths/prime_factors_using_sieve.cpp rename to _other_languages/cpp/Maths/prime_factors_using_sieve.cpp diff --git a/cpp/Maths/segmented_sieve.cpp b/_other_languages/cpp/Maths/segmented_sieve.cpp similarity index 100% rename from cpp/Maths/segmented_sieve.cpp rename to _other_languages/cpp/Maths/segmented_sieve.cpp diff --git a/cpp/Maths/sieve_of_eratosthenes.cpp b/_other_languages/cpp/Maths/sieve_of_eratosthenes.cpp similarity index 100% rename from cpp/Maths/sieve_of_eratosthenes.cpp rename to _other_languages/cpp/Maths/sieve_of_eratosthenes.cpp diff --git a/cpp/Maths/sum_of_divisors.cpp b/_other_languages/cpp/Maths/sum_of_divisors.cpp similarity index 100% rename from cpp/Maths/sum_of_divisors.cpp rename to _other_languages/cpp/Maths/sum_of_divisors.cpp diff --git a/cpp/Queue/Queue/Makefile b/_other_languages/cpp/Queue/Queue/Makefile similarity index 100% rename from cpp/Queue/Queue/Makefile rename to _other_languages/cpp/Queue/Queue/Makefile diff --git a/cpp/Queue/Queue/Queue.hpp b/_other_languages/cpp/Queue/Queue/Queue.hpp similarity index 100% rename from cpp/Queue/Queue/Queue.hpp rename to _other_languages/cpp/Queue/Queue/Queue.hpp diff --git a/cpp/Queue/Queue/test_Queue.cpp b/_other_languages/cpp/Queue/Queue/test_Queue.cpp similarity index 100% rename from cpp/Queue/Queue/test_Queue.cpp rename to _other_languages/cpp/Queue/Queue/test_Queue.cpp diff --git a/cpp/Queue/ReverseQueue.cpp b/_other_languages/cpp/Queue/ReverseQueue.cpp similarity index 100% rename from cpp/Queue/ReverseQueue.cpp rename to _other_languages/cpp/Queue/ReverseQueue.cpp diff --git a/cpp/Queue/SortQueueWithoutExtraSpace.cpp b/_other_languages/cpp/Queue/SortQueueWithoutExtraSpace.cpp similarity index 100% rename from cpp/Queue/SortQueueWithoutExtraSpace.cpp rename to _other_languages/cpp/Queue/SortQueueWithoutExtraSpace.cpp diff --git a/cpp/README.md b/_other_languages/cpp/README.md similarity index 100% rename from cpp/README.md rename to _other_languages/cpp/README.md diff --git a/cpp/RedBlackTree/Makefile b/_other_languages/cpp/RedBlackTree/Makefile similarity index 100% rename from cpp/RedBlackTree/Makefile rename to _other_languages/cpp/RedBlackTree/Makefile diff --git a/cpp/RedBlackTree/RedBlackTree.cpp b/_other_languages/cpp/RedBlackTree/RedBlackTree.cpp similarity index 100% rename from cpp/RedBlackTree/RedBlackTree.cpp rename to _other_languages/cpp/RedBlackTree/RedBlackTree.cpp diff --git a/cpp/RedBlackTree/RedBlackTree.hpp b/_other_languages/cpp/RedBlackTree/RedBlackTree.hpp similarity index 100% rename from cpp/RedBlackTree/RedBlackTree.hpp rename to _other_languages/cpp/RedBlackTree/RedBlackTree.hpp diff --git a/cpp/RedBlackTree/find.cpp b/_other_languages/cpp/RedBlackTree/find.cpp similarity index 100% rename from cpp/RedBlackTree/find.cpp rename to _other_languages/cpp/RedBlackTree/find.cpp diff --git a/cpp/RedBlackTree/insert.cpp b/_other_languages/cpp/RedBlackTree/insert.cpp similarity index 100% rename from cpp/RedBlackTree/insert.cpp rename to _other_languages/cpp/RedBlackTree/insert.cpp diff --git a/cpp/RedBlackTree/test_RedBlackTree.cpp b/_other_languages/cpp/RedBlackTree/test_RedBlackTree.cpp similarity index 100% rename from cpp/RedBlackTree/test_RedBlackTree.cpp rename to _other_languages/cpp/RedBlackTree/test_RedBlackTree.cpp diff --git a/cpp/RedBlackTree/utils.cpp b/_other_languages/cpp/RedBlackTree/utils.cpp similarity index 100% rename from cpp/RedBlackTree/utils.cpp rename to _other_languages/cpp/RedBlackTree/utils.cpp diff --git a/cpp/Search/BinarySearch.h b/_other_languages/cpp/Search/BinarySearch.h similarity index 100% rename from cpp/Search/BinarySearch.h rename to _other_languages/cpp/Search/BinarySearch.h diff --git a/cpp/Search/Makefile b/_other_languages/cpp/Search/Makefile similarity index 100% rename from cpp/Search/Makefile rename to _other_languages/cpp/Search/Makefile diff --git a/cpp/Search/test_BinarySearch.cpp b/_other_languages/cpp/Search/test_BinarySearch.cpp similarity index 100% rename from cpp/Search/test_BinarySearch.cpp rename to _other_languages/cpp/Search/test_BinarySearch.cpp diff --git a/cpp/Shuffle/Shuffle.cpp b/_other_languages/cpp/Shuffle/Shuffle.cpp similarity index 100% rename from cpp/Shuffle/Shuffle.cpp rename to _other_languages/cpp/Shuffle/Shuffle.cpp diff --git a/cpp/Sort/BubbleSort.cpp b/_other_languages/cpp/Sort/BubbleSort.cpp similarity index 100% rename from cpp/Sort/BubbleSort.cpp rename to _other_languages/cpp/Sort/BubbleSort.cpp diff --git a/cpp/Sort/CountingSort.cpp b/_other_languages/cpp/Sort/CountingSort.cpp similarity index 100% rename from cpp/Sort/CountingSort.cpp rename to _other_languages/cpp/Sort/CountingSort.cpp diff --git a/cpp/Sort/GnomeSort.cpp b/_other_languages/cpp/Sort/GnomeSort.cpp similarity index 100% rename from cpp/Sort/GnomeSort.cpp rename to _other_languages/cpp/Sort/GnomeSort.cpp diff --git a/cpp/Sort/HeapSort.cpp b/_other_languages/cpp/Sort/HeapSort.cpp similarity index 100% rename from cpp/Sort/HeapSort.cpp rename to _other_languages/cpp/Sort/HeapSort.cpp diff --git a/cpp/Sort/InsertionSort.cpp b/_other_languages/cpp/Sort/InsertionSort.cpp similarity index 100% rename from cpp/Sort/InsertionSort.cpp rename to _other_languages/cpp/Sort/InsertionSort.cpp diff --git a/cpp/Sort/MergeBottomUp.cpp b/_other_languages/cpp/Sort/MergeBottomUp.cpp similarity index 100% rename from cpp/Sort/MergeBottomUp.cpp rename to _other_languages/cpp/Sort/MergeBottomUp.cpp diff --git a/cpp/Sort/MergeOptimizeSort.cpp b/_other_languages/cpp/Sort/MergeOptimizeSort.cpp similarity index 100% rename from cpp/Sort/MergeOptimizeSort.cpp rename to _other_languages/cpp/Sort/MergeOptimizeSort.cpp diff --git a/cpp/Sort/MergeSort.cpp b/_other_languages/cpp/Sort/MergeSort.cpp similarity index 100% rename from cpp/Sort/MergeSort.cpp rename to _other_languages/cpp/Sort/MergeSort.cpp diff --git a/cpp/Sort/OddEvenSort.cpp b/_other_languages/cpp/Sort/OddEvenSort.cpp similarity index 100% rename from cpp/Sort/OddEvenSort.cpp rename to _other_languages/cpp/Sort/OddEvenSort.cpp diff --git a/cpp/Sort/Quick3WaySort.cpp b/_other_languages/cpp/Sort/Quick3WaySort.cpp similarity index 100% rename from cpp/Sort/Quick3WaySort.cpp rename to _other_languages/cpp/Sort/Quick3WaySort.cpp diff --git a/cpp/Sort/QuickOptimizeSort.cpp b/_other_languages/cpp/Sort/QuickOptimizeSort.cpp similarity index 100% rename from cpp/Sort/QuickOptimizeSort.cpp rename to _other_languages/cpp/Sort/QuickOptimizeSort.cpp diff --git a/cpp/Sort/QuickSelect.cpp b/_other_languages/cpp/Sort/QuickSelect.cpp similarity index 100% rename from cpp/Sort/QuickSelect.cpp rename to _other_languages/cpp/Sort/QuickSelect.cpp diff --git a/cpp/Sort/QuickSort.cpp b/_other_languages/cpp/Sort/QuickSort.cpp similarity index 100% rename from cpp/Sort/QuickSort.cpp rename to _other_languages/cpp/Sort/QuickSort.cpp diff --git a/cpp/Sort/SelectionSort.cpp b/_other_languages/cpp/Sort/SelectionSort.cpp similarity index 100% rename from cpp/Sort/SelectionSort.cpp rename to _other_languages/cpp/Sort/SelectionSort.cpp diff --git a/cpp/Sort/ShellSort.cpp b/_other_languages/cpp/Sort/ShellSort.cpp similarity index 100% rename from cpp/Sort/ShellSort.cpp rename to _other_languages/cpp/Sort/ShellSort.cpp diff --git a/cpp/Stack/Stack/Makefile b/_other_languages/cpp/Stack/Stack/Makefile similarity index 100% rename from cpp/Stack/Stack/Makefile rename to _other_languages/cpp/Stack/Stack/Makefile diff --git a/cpp/Stack/Stack/Stack.hpp b/_other_languages/cpp/Stack/Stack/Stack.hpp similarity index 100% rename from cpp/Stack/Stack/Stack.hpp rename to _other_languages/cpp/Stack/Stack/Stack.hpp diff --git a/cpp/Stack/Stack/test_Stack.cpp b/_other_languages/cpp/Stack/Stack/test_Stack.cpp similarity index 100% rename from cpp/Stack/Stack/test_Stack.cpp rename to _other_languages/cpp/Stack/Stack/test_Stack.cpp diff --git a/cpp/Stack/balancedParanthesis.cpp b/_other_languages/cpp/Stack/balancedParanthesis.cpp similarity index 100% rename from cpp/Stack/balancedParanthesis.cpp rename to _other_languages/cpp/Stack/balancedParanthesis.cpp diff --git a/cpp/Stack/bracketReversals.cpp b/_other_languages/cpp/Stack/bracketReversals.cpp similarity index 100% rename from cpp/Stack/bracketReversals.cpp rename to _other_languages/cpp/Stack/bracketReversals.cpp diff --git a/cpp/Stack/deleteMiddleElement.cpp b/_other_languages/cpp/Stack/deleteMiddleElement.cpp similarity index 100% rename from cpp/Stack/deleteMiddleElement.cpp rename to _other_languages/cpp/Stack/deleteMiddleElement.cpp diff --git a/cpp/Stack/infixToPostfix.cpp b/_other_languages/cpp/Stack/infixToPostfix.cpp similarity index 100% rename from cpp/Stack/infixToPostfix.cpp rename to _other_languages/cpp/Stack/infixToPostfix.cpp diff --git a/cpp/Stack/trackingCurrentMax.cpp b/_other_languages/cpp/Stack/trackingCurrentMax.cpp similarity index 100% rename from cpp/Stack/trackingCurrentMax.cpp rename to _other_languages/cpp/Stack/trackingCurrentMax.cpp diff --git a/golang/README.md b/_other_languages/golang/README.md similarity index 100% rename from golang/README.md rename to _other_languages/golang/README.md diff --git a/golang/bst/bst.go b/_other_languages/golang/bst/bst.go similarity index 100% rename from golang/bst/bst.go rename to _other_languages/golang/bst/bst.go diff --git a/golang/bst/bst_test.go b/_other_languages/golang/bst/bst_test.go similarity index 100% rename from golang/bst/bst_test.go rename to _other_languages/golang/bst/bst_test.go diff --git a/golang/bst/checkbst.go b/_other_languages/golang/bst/checkbst.go similarity index 100% rename from golang/bst/checkbst.go rename to _other_languages/golang/bst/checkbst.go diff --git a/golang/bst/delete.go b/_other_languages/golang/bst/delete.go similarity index 100% rename from golang/bst/delete.go rename to _other_languages/golang/bst/delete.go diff --git a/golang/bst/find.go b/_other_languages/golang/bst/find.go similarity index 100% rename from golang/bst/find.go rename to _other_languages/golang/bst/find.go diff --git a/golang/bst/height.go b/_other_languages/golang/bst/height.go similarity index 100% rename from golang/bst/height.go rename to _other_languages/golang/bst/height.go diff --git a/golang/bst/insert.go b/_other_languages/golang/bst/insert.go similarity index 100% rename from golang/bst/insert.go rename to _other_languages/golang/bst/insert.go diff --git a/golang/bst/traversal.go b/_other_languages/golang/bst/traversal.go similarity index 100% rename from golang/bst/traversal.go rename to _other_languages/golang/bst/traversal.go diff --git a/golang/doublylinkedlist/doublylinkedlist.go b/_other_languages/golang/doublylinkedlist/doublylinkedlist.go similarity index 100% rename from golang/doublylinkedlist/doublylinkedlist.go rename to _other_languages/golang/doublylinkedlist/doublylinkedlist.go diff --git a/golang/doublylinkedlist/doublylinkedlist_test.go b/_other_languages/golang/doublylinkedlist/doublylinkedlist_test.go similarity index 100% rename from golang/doublylinkedlist/doublylinkedlist_test.go rename to _other_languages/golang/doublylinkedlist/doublylinkedlist_test.go diff --git a/golang/hashtable/hashtable.go b/_other_languages/golang/hashtable/hashtable.go similarity index 100% rename from golang/hashtable/hashtable.go rename to _other_languages/golang/hashtable/hashtable.go diff --git a/golang/hashtable/hashtable_test.go b/_other_languages/golang/hashtable/hashtable_test.go similarity index 100% rename from golang/hashtable/hashtable_test.go rename to _other_languages/golang/hashtable/hashtable_test.go diff --git a/golang/heap/doc.go b/_other_languages/golang/heap/doc.go similarity index 100% rename from golang/heap/doc.go rename to _other_languages/golang/heap/doc.go diff --git a/golang/heap/maxheap/maxheap.go b/_other_languages/golang/heap/maxheap/maxheap.go similarity index 100% rename from golang/heap/maxheap/maxheap.go rename to _other_languages/golang/heap/maxheap/maxheap.go diff --git a/golang/heap/maxheap/maxheap_test.go b/_other_languages/golang/heap/maxheap/maxheap_test.go similarity index 100% rename from golang/heap/maxheap/maxheap_test.go rename to _other_languages/golang/heap/maxheap/maxheap_test.go diff --git a/golang/heap/minheap/minheap.go b/_other_languages/golang/heap/minheap/minheap.go similarity index 100% rename from golang/heap/minheap/minheap.go rename to _other_languages/golang/heap/minheap/minheap.go diff --git a/golang/heap/minheap/minheap_test.go b/_other_languages/golang/heap/minheap/minheap_test.go similarity index 100% rename from golang/heap/minheap/minheap_test.go rename to _other_languages/golang/heap/minheap/minheap_test.go diff --git a/golang/linkedlist/linkedlist.go b/_other_languages/golang/linkedlist/linkedlist.go similarity index 100% rename from golang/linkedlist/linkedlist.go rename to _other_languages/golang/linkedlist/linkedlist.go diff --git a/golang/linkedlist/linkedlist_test.go b/_other_languages/golang/linkedlist/linkedlist_test.go similarity index 100% rename from golang/linkedlist/linkedlist_test.go rename to _other_languages/golang/linkedlist/linkedlist_test.go diff --git a/golang/queue/queue.go b/_other_languages/golang/queue/queue.go similarity index 100% rename from golang/queue/queue.go rename to _other_languages/golang/queue/queue.go diff --git a/golang/queue/queue_test.go b/_other_languages/golang/queue/queue_test.go similarity index 100% rename from golang/queue/queue_test.go rename to _other_languages/golang/queue/queue_test.go diff --git a/golang/redblacktree/doc.go b/_other_languages/golang/redblacktree/doc.go similarity index 100% rename from golang/redblacktree/doc.go rename to _other_languages/golang/redblacktree/doc.go diff --git a/golang/redblacktree/find.go b/_other_languages/golang/redblacktree/find.go similarity index 100% rename from golang/redblacktree/find.go rename to _other_languages/golang/redblacktree/find.go diff --git a/golang/redblacktree/insert.go b/_other_languages/golang/redblacktree/insert.go similarity index 100% rename from golang/redblacktree/insert.go rename to _other_languages/golang/redblacktree/insert.go diff --git a/golang/redblacktree/redblacktree.go b/_other_languages/golang/redblacktree/redblacktree.go similarity index 100% rename from golang/redblacktree/redblacktree.go rename to _other_languages/golang/redblacktree/redblacktree.go diff --git a/golang/redblacktree/redblacktree_test.go b/_other_languages/golang/redblacktree/redblacktree_test.go similarity index 100% rename from golang/redblacktree/redblacktree_test.go rename to _other_languages/golang/redblacktree/redblacktree_test.go diff --git a/golang/redblacktree/utils.go b/_other_languages/golang/redblacktree/utils.go similarity index 100% rename from golang/redblacktree/utils.go rename to _other_languages/golang/redblacktree/utils.go diff --git a/golang/search/binarysearch.go b/_other_languages/golang/search/binarysearch.go similarity index 100% rename from golang/search/binarysearch.go rename to _other_languages/golang/search/binarysearch.go diff --git a/golang/search/binarysearch_test.go b/_other_languages/golang/search/binarysearch_test.go similarity index 100% rename from golang/search/binarysearch_test.go rename to _other_languages/golang/search/binarysearch_test.go diff --git a/golang/set/set.go b/_other_languages/golang/set/set.go similarity index 100% rename from golang/set/set.go rename to _other_languages/golang/set/set.go diff --git a/golang/set/set_test.go b/_other_languages/golang/set/set_test.go similarity index 100% rename from golang/set/set_test.go rename to _other_languages/golang/set/set_test.go diff --git a/golang/shuffle/shuffle.go b/_other_languages/golang/shuffle/shuffle.go similarity index 100% rename from golang/shuffle/shuffle.go rename to _other_languages/golang/shuffle/shuffle.go diff --git a/golang/sort/bubble.go b/_other_languages/golang/sort/bubble.go similarity index 100% rename from golang/sort/bubble.go rename to _other_languages/golang/sort/bubble.go diff --git a/golang/sort/countingSort.go b/_other_languages/golang/sort/countingSort.go similarity index 100% rename from golang/sort/countingSort.go rename to _other_languages/golang/sort/countingSort.go diff --git a/golang/sort/gnome.go b/_other_languages/golang/sort/gnome.go similarity index 100% rename from golang/sort/gnome.go rename to _other_languages/golang/sort/gnome.go diff --git a/golang/sort/heap.go b/_other_languages/golang/sort/heap.go similarity index 100% rename from golang/sort/heap.go rename to _other_languages/golang/sort/heap.go diff --git a/golang/sort/insertion.go b/_other_languages/golang/sort/insertion.go similarity index 100% rename from golang/sort/insertion.go rename to _other_languages/golang/sort/insertion.go diff --git a/golang/sort/merge.go b/_other_languages/golang/sort/merge.go similarity index 100% rename from golang/sort/merge.go rename to _other_languages/golang/sort/merge.go diff --git a/golang/sort/oddeven.go b/_other_languages/golang/sort/oddeven.go similarity index 100% rename from golang/sort/oddeven.go rename to _other_languages/golang/sort/oddeven.go diff --git a/golang/sort/quick.go b/_other_languages/golang/sort/quick.go similarity index 100% rename from golang/sort/quick.go rename to _other_languages/golang/sort/quick.go diff --git a/golang/sort/quickselect.go b/_other_languages/golang/sort/quickselect.go similarity index 100% rename from golang/sort/quickselect.go rename to _other_languages/golang/sort/quickselect.go diff --git a/golang/sort/selection.go b/_other_languages/golang/sort/selection.go similarity index 100% rename from golang/sort/selection.go rename to _other_languages/golang/sort/selection.go diff --git a/golang/sort/shell.go b/_other_languages/golang/sort/shell.go similarity index 100% rename from golang/sort/shell.go rename to _other_languages/golang/sort/shell.go diff --git a/golang/sort/sort.go b/_other_languages/golang/sort/sort.go similarity index 100% rename from golang/sort/sort.go rename to _other_languages/golang/sort/sort.go diff --git a/golang/sort/sort_test.go b/_other_languages/golang/sort/sort_test.go similarity index 100% rename from golang/sort/sort_test.go rename to _other_languages/golang/sort/sort_test.go diff --git a/golang/stack/applications/applications.go b/_other_languages/golang/stack/applications/applications.go similarity index 100% rename from golang/stack/applications/applications.go rename to _other_languages/golang/stack/applications/applications.go diff --git a/golang/stack/applications/applications_test.go b/_other_languages/golang/stack/applications/applications_test.go similarity index 100% rename from golang/stack/applications/applications_test.go rename to _other_languages/golang/stack/applications/applications_test.go diff --git a/golang/stack/applications/infixevaluation.go b/_other_languages/golang/stack/applications/infixevaluation.go similarity index 100% rename from golang/stack/applications/infixevaluation.go rename to _other_languages/golang/stack/applications/infixevaluation.go diff --git a/golang/stack/applications/infixtopostfix.go b/_other_languages/golang/stack/applications/infixtopostfix.go similarity index 100% rename from golang/stack/applications/infixtopostfix.go rename to _other_languages/golang/stack/applications/infixtopostfix.go diff --git a/golang/stack/applications/infixtoprefix.go b/_other_languages/golang/stack/applications/infixtoprefix.go similarity index 100% rename from golang/stack/applications/infixtoprefix.go rename to _other_languages/golang/stack/applications/infixtoprefix.go diff --git a/golang/stack/applications/utils.go b/_other_languages/golang/stack/applications/utils.go similarity index 100% rename from golang/stack/applications/utils.go rename to _other_languages/golang/stack/applications/utils.go diff --git a/golang/stack/stack.go b/_other_languages/golang/stack/stack.go similarity index 100% rename from golang/stack/stack.go rename to _other_languages/golang/stack/stack.go diff --git a/golang/stack/stack_test.go b/_other_languages/golang/stack/stack_test.go similarity index 100% rename from golang/stack/stack_test.go rename to _other_languages/golang/stack/stack_test.go diff --git a/golang/trie/trie.go b/_other_languages/golang/trie/trie.go similarity index 100% rename from golang/trie/trie.go rename to _other_languages/golang/trie/trie.go diff --git a/golang/trie/trie_test.go b/_other_languages/golang/trie/trie_test.go similarity index 100% rename from golang/trie/trie_test.go rename to _other_languages/golang/trie/trie_test.go From 38a5de72db14ef2664489da9857b598d24c4e276 Mon Sep 17 00:00:00 2001 From: priyankchheda Date: Sat, 16 Apr 2022 19:22:37 +0530 Subject: [PATCH 209/209] add prim algorithm --- graph/prim_algorithm.py | 107 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 graph/prim_algorithm.py diff --git a/graph/prim_algorithm.py b/graph/prim_algorithm.py new file mode 100644 index 0000000..63fc764 --- /dev/null +++ b/graph/prim_algorithm.py @@ -0,0 +1,107 @@ +""" Prim's Algorithm for finding minimum spanning tree +""" + +import heapq + +class Edge: + """ undirected edge interface API """ + def __init__(self, vertex1, vertex2, weight): + self.vertex1 = vertex1 + self.vertex2 = vertex2 + self.weight = weight + + def other(self, vertex): + """ return other vertex of the edge """ + if vertex == self.vertex1: + return self.vertex2 + return self.vertex1 + + def __repr__(self): + return f"({self.vertex1}, {self.vertex2}, {self.weight})" + + def __lt__(self, other): + return self.weight < other.weight + + +class EdgeWeightedGraph: + """ undirected weighted graph representation using adjacency list """ + def __init__(self, vertices_count): + self.vertices_count = vertices_count + self.edges = [] + + self.adjacency_list = list() + for _ in range(self.vertices_count): + self.adjacency_list.append(set()) + + def add_edge(self, edge): + """ add edge to undirected weighted graph """ + self.adjacency_list[edge.vertex1].add(edge) + self.adjacency_list[edge.vertex2].add(edge) + self.edges.append(edge) + + def adjacent(self, vertex): + """ edges incident to vertex """ + return self.adjacency_list[vertex] + + +class MinimumSpanningTree: + """ Prim's Algorithm Python 3 Implementation """ + def __init__(self, graph): + self.graph = graph + self.mst_edges = [] + self.mst_weight = 0 + self.marked = [False] * self.graph.vertices_count + self.priority_queue = [] + + def visit(self, vertex): + """ mark vertex and add adjcent edges to priority queue """ + self.marked[vertex] = True + for edge in self.graph.adjacent(vertex): + if not self.marked[edge.other(vertex)]: + heapq.heappush(self.priority_queue, edge) + + def run(self): + """ run prim's algorithm to find minimum spanning tree """ + self.visit(0) + + while self.priority_queue: + edge = heapq.heappop(self.priority_queue) + if self.marked[edge.vertex1] and self.marked[edge.vertex2]: + continue + self.mst_edges.append(edge) + self.mst_weight += edge.weight + if not self.marked[edge.vertex1]: + self.visit(edge.vertex1) + if not self.marked[edge.vertex2]: + self.visit(edge.vertex2) + + +def main(): + """ operational function """ + graph = EdgeWeightedGraph(8) + graph.add_edge(Edge(2, 3, 0.17)) + graph.add_edge(Edge(0, 7, 0.16)) + graph.add_edge(Edge(5, 7, 0.28)) + graph.add_edge(Edge(1, 7, 0.19)) + graph.add_edge(Edge(6, 2, 0.40)) + graph.add_edge(Edge(3, 6, 0.52)) + graph.add_edge(Edge(6, 0, 0.58)) + graph.add_edge(Edge(2, 7, 0.34)) + graph.add_edge(Edge(4, 5, 0.35)) + graph.add_edge(Edge(1, 2, 0.36)) + graph.add_edge(Edge(4, 7, 0.37)) + graph.add_edge(Edge(0, 2, 0.26)) + graph.add_edge(Edge(1, 3, 0.29)) + graph.add_edge(Edge(1, 5, 0.32)) + graph.add_edge(Edge(0, 4, 0.38)) + graph.add_edge(Edge(6, 4, 0.93)) + + spanning_tree = MinimumSpanningTree(graph) + spanning_tree.run() + for edge in spanning_tree.mst_edges: + print(edge) + print(spanning_tree.mst_weight) + + +if __name__ == "__main__": + main()