From ff88740b6ed6f8a22a842ed816e4f3ba9c57536f Mon Sep 17 00:00:00 2001 From: akshita aggarwal Date: Wed, 3 Oct 2018 14:19:00 +0530 Subject: [PATCH 1/2] linkedlist implementation n c++ --- .github/ISSUE_TEMPLATE/add-algorithm.md | 21 ++ .github/ISSUE_TEMPLATE/add-documentation.md | 17 ++ .github/ISSUE_TEMPLATE/bug_report.md | 35 +++ .github/ISSUE_TEMPLATE/feature_request.md | 17 ++ .../ISSUE_TEMPLATE/improve-an-algorithm.md | 19 ++ .github/PULL_REQUEST_TEMPLATE.md | 56 ++++ CODE_OF_CONDUCT.md | 46 +++ CONTRIBUTING.md | 54 ++++ Data Structures/.gitkeep | 0 .../Linked Lists/C++/linkedlist.cpp | 135 +++++++++ .../Linked Lists/Java/SinglyLinkedList.java | 264 ++++++++++++++++++ Data Structures/Stack/Java/Stack.java | 152 ++++++++++ Dynamic Programming/.gitkeep | 0 Graphs/.gitkeep | 0 Graphs/cpp/dijkstra_shortest_path.cpp | 124 ++++++++ Greedy/.gitkeep | 0 JS Design Patterns/singleton.js | 60 ++++ Java Design Patterns/.gitkeep | 0 Java Design Patterns/DAO /DaoPatternDemo.java | 20 ++ Java Design Patterns/DAO /README.md | 14 + Java Design Patterns/DAO /Student.java | 25 ++ Java Design Patterns/DAO /StudentDao.java | 8 + Java Design Patterns/DAO /StudentDaoImpl.java | 38 +++ Java Design Patterns/Singleton/README.md | 23 ++ Java Design Patterns/Singleton/Singleton.java | 17 ++ Java Design Patterns/builder /README.md | 17 ++ Java Design Patterns/builder /builder.java | 70 +++++ LICENSE | 21 ++ Machine Learning/.gitkeep | 0 Maths/Euclidean Algorithm/C++/GCD.cpp | 20 ++ Maths/Euclidean Algorithm/C/GCD.c | 16 ++ Maths/Euclidean Algorithm/Java/GCD.java | 12 + Maths/Euclidean Algorithm/Python/GCD.py | 9 + Maths/Euclidean Algorithm/README.md | 15 + README.md | 76 +++++ Searching/.gitkeep | 0 Searching/Binary Search/C++/BinarySearch.cpp | 48 ++++ Searching/Binary Search/C/BinarySearch.c | 48 ++++ .../Binary Search/Java/BinarySearch.java | 44 +++ .../Binary Search/Python/BinarySearch.py | 23 ++ Searching/Binary Search/README.md | 33 +++ Searching/Linear Search/C++/LinearSearch.cpp | 37 +++ Searching/Linear Search/C/LinearSearch.c | 24 ++ .../Linear Search/Java/LinearSearch.java | 34 +++ .../Linear Search/Python/LinearSearch.py | 16 ++ Searching/Linear Search/README.md | 26 ++ Sorting/Bubble Sort/C#/BubbleSort.cs | 58 ++++ Sorting/Bubble Sort/Java/BubbleSort.java | 50 ++++ Sorting/Heap Sort/C++/HeapSort.cpp | 81 ++++++ Sorting/Heap Sort/HeapSort.java | 74 +++++ .../Insertion Sort/Java/InsertionSort.java | 34 +++ .../Merge Sort/C++/Arrays/MergeSortArray.cpp | 110 ++++++++ .../Merge Sort/C++/Arrays/MergeSortArray.h | 19 ++ .../C++/Arrays/MergeSortArrayTest.cpp | 73 +++++ .../C++/Linked Lists/MergeSortLinkedList.cpp | 215 ++++++++++++++ .../C++/Linked Lists/MergeSortLinkedList.h | 39 +++ .../Linked Lists/MergeSortLinkedListTest.cpp | 94 +++++++ Sorting/Merge Sort/C++/MergeSortArray.cpp | 105 +++++++ Sorting/Merge Sort/Java/MergeSort.java | 77 +++++ Sorting/Quick Sort/C++/QuickSort.cpp | 81 ++++++ Sorting/Quick Sort/Java/QuickSort.java | 80 ++++++ Sorting/Radix Sort/C/RadixSort.cpp | 73 +++++ .../Selection Sort/Java/SelectionSort.java | 43 +++ String Manipulation/.gitkeep | 0 64 files changed, 3040 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/add-algorithm.md create mode 100644 .github/ISSUE_TEMPLATE/add-documentation.md create mode 100644 .github/ISSUE_TEMPLATE/bug_report.md create mode 100644 .github/ISSUE_TEMPLATE/feature_request.md create mode 100644 .github/ISSUE_TEMPLATE/improve-an-algorithm.md create mode 100644 .github/PULL_REQUEST_TEMPLATE.md create mode 100644 CODE_OF_CONDUCT.md create mode 100644 CONTRIBUTING.md create mode 100644 Data Structures/.gitkeep create mode 100644 Data Structures/Linked Lists/C++/linkedlist.cpp create mode 100644 Data Structures/Linked Lists/Java/SinglyLinkedList.java create mode 100644 Data Structures/Stack/Java/Stack.java create mode 100644 Dynamic Programming/.gitkeep create mode 100644 Graphs/.gitkeep create mode 100644 Graphs/cpp/dijkstra_shortest_path.cpp create mode 100644 Greedy/.gitkeep create mode 100644 JS Design Patterns/singleton.js create mode 100644 Java Design Patterns/.gitkeep create mode 100644 Java Design Patterns/DAO /DaoPatternDemo.java create mode 100644 Java Design Patterns/DAO /README.md create mode 100644 Java Design Patterns/DAO /Student.java create mode 100644 Java Design Patterns/DAO /StudentDao.java create mode 100644 Java Design Patterns/DAO /StudentDaoImpl.java create mode 100644 Java Design Patterns/Singleton/README.md create mode 100644 Java Design Patterns/Singleton/Singleton.java create mode 100644 Java Design Patterns/builder /README.md create mode 100644 Java Design Patterns/builder /builder.java create mode 100644 LICENSE create mode 100644 Machine Learning/.gitkeep create mode 100644 Maths/Euclidean Algorithm/C++/GCD.cpp create mode 100644 Maths/Euclidean Algorithm/C/GCD.c create mode 100644 Maths/Euclidean Algorithm/Java/GCD.java create mode 100644 Maths/Euclidean Algorithm/Python/GCD.py create mode 100644 Maths/Euclidean Algorithm/README.md create mode 100644 README.md create mode 100644 Searching/.gitkeep create mode 100644 Searching/Binary Search/C++/BinarySearch.cpp create mode 100644 Searching/Binary Search/C/BinarySearch.c create mode 100644 Searching/Binary Search/Java/BinarySearch.java create mode 100644 Searching/Binary Search/Python/BinarySearch.py create mode 100644 Searching/Binary Search/README.md create mode 100644 Searching/Linear Search/C++/LinearSearch.cpp create mode 100644 Searching/Linear Search/C/LinearSearch.c create mode 100644 Searching/Linear Search/Java/LinearSearch.java create mode 100644 Searching/Linear Search/Python/LinearSearch.py create mode 100644 Searching/Linear Search/README.md create mode 100644 Sorting/Bubble Sort/C#/BubbleSort.cs create mode 100644 Sorting/Bubble Sort/Java/BubbleSort.java create mode 100644 Sorting/Heap Sort/C++/HeapSort.cpp create mode 100644 Sorting/Heap Sort/HeapSort.java create mode 100644 Sorting/Insertion Sort/Java/InsertionSort.java create mode 100644 Sorting/Merge Sort/C++/Arrays/MergeSortArray.cpp create mode 100644 Sorting/Merge Sort/C++/Arrays/MergeSortArray.h create mode 100644 Sorting/Merge Sort/C++/Arrays/MergeSortArrayTest.cpp create mode 100644 Sorting/Merge Sort/C++/Linked Lists/MergeSortLinkedList.cpp create mode 100644 Sorting/Merge Sort/C++/Linked Lists/MergeSortLinkedList.h create mode 100644 Sorting/Merge Sort/C++/Linked Lists/MergeSortLinkedListTest.cpp create mode 100644 Sorting/Merge Sort/C++/MergeSortArray.cpp create mode 100644 Sorting/Merge Sort/Java/MergeSort.java create mode 100644 Sorting/Quick Sort/C++/QuickSort.cpp create mode 100644 Sorting/Quick Sort/Java/QuickSort.java create mode 100644 Sorting/Radix Sort/C/RadixSort.cpp create mode 100644 Sorting/Selection Sort/Java/SelectionSort.java create mode 100644 String Manipulation/.gitkeep diff --git a/.github/ISSUE_TEMPLATE/add-algorithm.md b/.github/ISSUE_TEMPLATE/add-algorithm.md new file mode 100644 index 00000000..31de8f20 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/add-algorithm.md @@ -0,0 +1,21 @@ +--- +name: Add Algorithm +about: Add an algorithm to the repository + +--- + +Please search if an issue has already be placed before adding another issue. + +If you want to add an algorithm to the repository. +Please include the following in the issue. + +## Title: +Algorithm (Language) + +## Body: + Include the specific variant of the algorithm you want to add. + + +Are you working on this? - **Yes/No** +(**If you are going to work on the issue yourself, make sure you comment on the issue to let others know.** +We do not want multiple people to be working in the same issue without notice.) diff --git a/.github/ISSUE_TEMPLATE/add-documentation.md b/.github/ISSUE_TEMPLATE/add-documentation.md new file mode 100644 index 00000000..6baa1649 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/add-documentation.md @@ -0,0 +1,17 @@ +--- +name: Add Documentation +about: Add documentation for an algorithm + +--- + +Please search if an issue has already be placed before adding another issue. + +If you want to add an algorithm to the repository. +Please include the following in the issue. + +## Title: +Documentation of Algorithm + +Are you working on this? - **Yes/No** +(**If you are going to work on the issue yourself, make sure you comment on the issue to let others know.** +We do not want multiple people to be working in the same issue without notice.) diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 00000000..b7353733 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,35 @@ +--- +name: Bug report +about: Create a report to help us improve + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Desktop (please complete the following information):** + - OS: [e.g. iOS] + - Browser [e.g. chrome, safari] + - Version [e.g. 22] + +**Smartphone (please complete the following information):** + - Device: [e.g. iPhone6] + - OS: [e.g. iOS8.1] + - Browser [e.g. stock browser, safari] + - Version [e.g. 22] + +**Additional context** +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 00000000..066b2d92 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,17 @@ +--- +name: Feature request +about: Suggest an idea for this project + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/ISSUE_TEMPLATE/improve-an-algorithm.md b/.github/ISSUE_TEMPLATE/improve-an-algorithm.md new file mode 100644 index 00000000..0b71407e --- /dev/null +++ b/.github/ISSUE_TEMPLATE/improve-an-algorithm.md @@ -0,0 +1,19 @@ +--- +name: Improve an algorithm +about: Improve an existing algorithm + +--- + +Please search if an issue has already be placed before adding another issue. + +If you want to improve an algorithm in the repository. +Please include the following in the issue. + +## Title: +Algorithm (Language) + +##Body: +Why was wrong with the algorithm. How you plan to improve it. + +*If you are going to work on the issue yourself, make sure you comment on the issue to let others know.* +We do not want multiple people to be working in the same issue without notice. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000..a9ff8766 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,56 @@ +IMPORTANT: Please do not create a Pull Request without creating an issue first. + +Any change needs to be discussed before proceeding. + +## Description +Please describe what changes you have made. + +For Example: + +* Added a file(s) named '...' that implements '...'. + +* Changed the algorithm for performance/readablity/bugs. + +* Added documentation to the algorithm + + +## Related Issue + +This project only accepts pull requests related to open issues. + +If suggesting a new feature or change, please discuss it in an issue first. + +If fixing a bug, there should be an issue describing it with steps to reproduce. + +Please link to the issue here: + +## How Has This Been Tested? (Optional) + +Please describe in detail how you tested your changes. +You can skip this if you have not added any tests. + +## Screenshots (Optional) + +## Types of changes + +What types of changes does your code introduce? Put an `x` in all the boxes that apply: + +- [ ] Bug fix (change which fixes an issue with the algorithm) + +- [ ] New Algorithm (non-breaking change which adds functionality) + +- [ ] Documentation + +## Checklist: +Go over all the following points, and put an `x` in all the boxes that apply. + +If you're unsure about any of these, don't hesitate to ask. We're here to help! + +- [ ] My code follows the code style of this project. + +- [ ] My change requires a change to the documentation. + +- [ ] I have updated the documentation accordingly. + +- [ ] I have read the **CONTRIBUTING** document. + diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..787cbde7 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,46 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at glitter [here](https://gitter.im/asiatik-open). The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 00000000..df82cbfb --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,54 @@ +# How to Contribute +We'd love to accept your patches and contributions to this project. +We love your input! We want to make contributing to this project as easy and transparent as possible, whether it's: + +- Reporting a bug +- Discussing the current state of the code +- Submitting a fix +- Proposing new features +- Becoming a maintainer + +There are just a few small guidelines you need to follow. + +## We Develop with Github +We use github to host code, to track issues and feature requests, as well as accept pull requests. + +## We Use [Github Flow](https://guides.github.com/introduction/flow/index.html), So All Code Changes Happen Through Pull Requests +Pull requests are the best way to propose changes to the codebase (we use [Github Flow](https://guides.github.com/introduction/flow/index.html)). We actively welcome your pull requests: + +1. Fork the repo. +2. Create your new feature branch from `master`. +3. If you've added code that should be tested, we suggest to add tests. +4. Ensure the test suite passes. +5. Issue that pull request from your feature branch! + +## Adding a new algorithm or data structure. + +Make sure you adhere to the `algorithm/language/file` folder structure while adding code. + +Additionally we recommend using standard convention for your language such as indentation and variable naming while writing the algorithm. +Useful comments will be a help. Finally, if you can write tests for you code, we urge you to do so. + +## Any contributions you make will be under the MIT License +In short, when you submit code changes, your submissions are understood to be under the same MIT License +that covers the project. Feel free to contact the maintainers if that's a concern. + +## Report bugs using Github's issues +We use GitHub issues to track public bugs. Report a bug by opening a new issue; it's that easy! + +## Code reviews + +All submissions require review. We +use GitHub pull requests for this purpose. Consult +[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more +information on using pull requests. + +## Contact Us + +You can contact us through glitter [here](https://gitter.im/asiatik-open) + +## Community Guidelines + +This project follows [Google's Open Source Community +Guidelines](https://opensource.google.com/conduct/). + diff --git a/Data Structures/.gitkeep b/Data Structures/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/Data Structures/Linked Lists/C++/linkedlist.cpp b/Data Structures/Linked Lists/C++/linkedlist.cpp new file mode 100644 index 00000000..78e28f8a --- /dev/null +++ b/Data Structures/Linked Lists/C++/linkedlist.cpp @@ -0,0 +1,135 @@ +#include +using namespace std; + +int l; +void FindLocation(); +struct student{ + int data; + student* link; +} *start,*loc,*ptr1; + +void insertion_begin(int y){ + student* temp=new student(); + temp->data=y; + temp->link=start; + start=temp; +} +void insertion_end(int y){ + student* temp=new student(); + temp->data=y; + if(start==NULL){ + temp->link=NULL; + start=temp; +} + else{ + student* ptr=start; + while(ptr->link!=NULL) + ptr=ptr->link; + temp->link=NULL; + ptr->link=temp; +} +} +void insertion_after(int y){ + + student* temp=new student(); + temp->data=y; + cout<>l; + FindLocation(); + + if(loc==NULL){ + temp->link=start; + start=temp; + } + else{ + temp->link=loc->link; + loc->link=temp; + } +} +void insertion_at(){ + int a,count=1,item; + cout<<"enter the location at which data to be inserted: "; + cin>>a; + cout<>item; + student* temp=new student(); + student* ptr=start; + while(ptr->link!=NULL){ + if(count==a){ + temp->data=item; + temp->link=ptr->link; + ptr->link=temp; + } + else{ + count++; + ptr=ptr->link; + + } +} + +} +void FindLocation(){ + ptr1=start; + while(ptr1!=NULL){ + if(ptr1->data==l){ + loc=ptr1; + return; + } + else + ptr1=ptr1->link; + } + loc=NULL; + +} +void display() +{ + student* temp=start; + while(temp!=NULL){ + cout<data<<" "; + temp=temp->link; +} +cout<>n; + while(1){ + cout<<"select from the following: "<>k; + switch(k) + { + case 1: cout<<"enter the number:"; + for(i=0;i>x; + insertion_begin(x); + } + break; + case 2: cout<<"enter the number:"; + for(i=0;i>x; + insertion_end(x); + } + break; + case 3: cout<<"enter the element to be inserted: "; + cin>>m; + insertion_after(m); + break; + case 4: insertion_at(); + break; + case 5: display(); + break; + case 6: return(0); + default: cout<<"incorrect choice"< { + + /* Linked List Node */ + private static class Node { + + /*data in Node*/ + K data; + /*Next node reference*/ + Node next; + + Node() { + } + + /** + * Constructor + * + * @param d to initialize data + */ + Node(K d) { + data = d; + } + } + /*Head Reference to Front of List */ + private Node headNode; + /*Size of List*/ + private int listSize; + + /** + * Constructor for class SinglyLinkedList Initialize head Reference to Null + * Initialize Size of list to 0 + */ + public SinglyLinkedList() { + headNode = null; + listSize = 0; + } + + /* + * @return head Reference of Node + */ + public Node headNode() { + return headNode; + } + + /* + * @return size of list + */ + public int listSize() { + return listSize; + } + + /** + * create new new Node increment in list size + * + * @param T data to store in new node + * @return Reference of new Node + */ + private Node addNode(T data) { + Node newNode = new Node(data); + listSize++; + return newNode; + } + + /** + * Add Node at the end of list + * + * @param data for data of new Node + */ + public void addAtEnd(T data) { + Node newNode = addNode(data); + if (headNode == null) { + headNode = newNode; + } else { + Node temp = headNode; + while (temp.next != null) { + temp = temp.next; + } + temp.next = newNode; + } + } + + /** + * Add Node at the front of List + * @param data for date of new node + */ + public void addAtFront(T data) { + Node newNode = addNode(data); + newNode.next = headNode; + headNode = newNode; + } + /** + * add Node at specific index + * + * @param data to add data in new Node + * @param index index where new node has to be created + */ + public void addAtPosition(T data, int index) { + if (index <= 0) { + this.addAtFront(data); + } else if (index >= listSize) { + this.addAtEnd(data); + } else { + Node newNode = addNode(data); + Node temp = headNode; + Node tempTail = null; + int tempIndex = 0; + while (tempIndex < index && temp.next != null) { + tempTail = temp; + temp = temp.next; + tempIndex++; + } + newNode.next = temp; + tempTail.next = newNode; + } + } + /** + * delete Given key + * @param key data to be deleted + * @return + * true if deleted successfully + * false if deletion was unsuccessful + */ + public boolean delete(T key) { + if (headNode != null) { + if (headNode.data == key) { + headNode = headNode.next; + } else { + Node temp = headNode; + Node tempTail = null; + while (temp != null && temp.data != key) { + tempTail = temp; + temp = temp.next; + } + if (temp == null) { + return false; + } else { + tempTail.next = temp.next; + } + } + listSize--; + return true; + } + return false; + } + /** + * delete first node + * @return + * true if deleted successfully + * false if deletion was unsuccessful + */ + public boolean deleteHead() { + if (headNode != null) { + headNode = headNode.next; + listSize--; + return true; + } + return false; + } + /** + * delete last node + * @return + * true if deleted successfully + * false if deletion was unsuccessful + */ + public boolean deleteTail() { + if (headNode != null) { + Node temp = headNode; + Node tempTail = temp; + while (temp.next != null) { + tempTail = temp; + temp = temp.next; + + } + tempTail.next = null; + listSize--; + return true; + } + return false; + } + /** + * delete node at specific index + * @param index the node to be deleted + * @return + * true if deleted successfully + * false if deletion was unsuccessful + */ + public boolean deleteIndex(int index) { + if (headNode != null) { + if (index >= 0 && index < listSize) { + if (index == 0) { + this.deleteHead(); + } else if (index == listSize - 1) { + this.deleteTail(); + } else { + Node temp = headNode; + Node tempTail = null; + int tempIndex = 0; + while (tempIndex < index && temp != null) { + tempTail = temp; + temp = temp.next; + tempIndex++; + } + if (temp != null) { + tempTail.next = temp.next; + } + } + listSize--; + return true; + } + return false; + } + return false; + } + /** + * delete whole list + * @return + * true if deleted successfully + * false if deletion was unsuccessful + */ + public boolean deleteList() { + while (headNode != null) { + headNode = headNode.next; + } + return true; + } + + /** + * Print List + */ + public void printList() { + + Node temp = headNode; + while (temp != null) { + System.out.print(temp.data); + System.out.print(" "); + temp = temp.next; + } + System.out.println(); + } + // Driver Program + public static void main(String args[]) + { + SinglyLinkedList obj; + obj = new SinglyLinkedList(); + obj.addAtEnd('A'); + obj.addAtEnd('B'); + obj.addAtEnd('C'); + obj.addAtFront('D'); + obj.addAtPosition('E' ,3); + obj.printList(); + obj.deleteIndex(2); + obj.printList(); + obj.delete('A'); + obj.printList(); + obj.deleteHead(); + obj.printList(); + obj.deleteTail(); + obj.printList(); + } +} diff --git a/Data Structures/Stack/Java/Stack.java b/Data Structures/Stack/Java/Stack.java new file mode 100644 index 00000000..7a90b9a3 --- /dev/null +++ b/Data Structures/Stack/Java/Stack.java @@ -0,0 +1,152 @@ + +/** + * This class Implements Stack + * @author hamza39460 + */ +public class Stack { + /** + * node for stack + */ + private static class Node{ + // data to store in node + K data; + // next node reference + Node next; + /** + * Constructor for Class Node + * @param data to be saved in node + */ + public Node(K data){this.data=data; + next=null; + } + } + // reference to head node of stack + private Node headNode; + // stack size + private int stackSize; + /** + * constructor for class stack + * initialize head node reference to null + * initialize stack size to zero + */ + public Stack(){ + headNode=null; + stackSize=0; + } + /** + * to create new node + * @param data to be saved in node + * @return new created node + */ + private Node addNode(T data) + { + Node newNode=new Node(data); + return newNode; + } + /** + * @return size of stack + */ + public int stackSize() + { + return stackSize; + } + /** + * to push in stack + * @param data to be pushed in stack + */ + public void push(T data) + { + Node newNode=addNode(data); + newNode.next=headNode; + headNode=newNode; + stackSize++; + } + /** + * removes top element + * @return top element if not empty + * else return false + */ + public T pop() + { + if (headNode!=null) + { + T data=(T)headNode.data; + headNode=headNode.next; + stackSize--; + return data; + } + else + return null; + } + /** + * to get top element of stack + * @return top of stack if stack is not empty + * else return null + */ + public T top() + { + if (headNode!=null) + return (T)headNode.data; + else + return null; + } + /** + * to check if stack is empty + * @return + * true if stack is empty + * false if stack is not empty + */ + boolean is_empty() + { + if (headNode==null) + return true; + return false; + } + /** + * check if an element exist in stack + * @param key element to check + * @return + * true if element exists + * false if element does not exist + */ + boolean exist(T key) + { + if(headNode==null) + return false; + else if (headNode.data==key) + return true; + else { + Node temp=headNode; + while (temp!=null&&temp.data!=key) + { + temp=temp.next; + } + if (temp!=null) + return true; + } + return false; + } + /* + pop all elements from stack + */ + public void popAll(){ + while (headNode!=null) + headNode=headNode.next; + } + // driver program + public static void main(String args[]) + { + Stack obj; + obj = new Stack(); + obj.push(2.2); + obj.push(3.3); + obj.push(4.4); + obj.push(5.5); + obj.push(6.6); + while(!obj.is_empty()) + { + System.out.println(obj.pop()); + } + + } +} diff --git a/Dynamic Programming/.gitkeep b/Dynamic Programming/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/Graphs/.gitkeep b/Graphs/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/Graphs/cpp/dijkstra_shortest_path.cpp b/Graphs/cpp/dijkstra_shortest_path.cpp new file mode 100644 index 00000000..23f85aa0 --- /dev/null +++ b/Graphs/cpp/dijkstra_shortest_path.cpp @@ -0,0 +1,124 @@ +/* + * dijkstra_shortest_path.cpp + * + * Created On: 2-Oct-182018 + * Author: hplapi + */ +#include +#include +#include +#include + +using namespace std; + +map s_path; +vector unvisited; // unvisited nodes in the graph + +map dijkstra_shortest_path(char, vector >); +void initialize(int,char); // initialisation of each vertex +char find_min(); // find minimum weighted node in unvisited vector +void relax(int,int,int); // relaxation of each node next to the one passed +void print_path(char, map); // print shortest paths + +/* utility method for dijkstra's shortest path algortithm + parameters: + s: source node for shortest path + graph: 2d array of weights along where x[i][j] is the weight of edge i->j + Example graph is like below, with edges named A-E: + A B C D E + A 0 10 0 0 5 + B 0 0 1 0 2 + C 0 0 0 4 0 + D 7 0 6 0 0 + E 0 3 9 2 0 + returns: + Returns map mapping minimum weight of each node from starting node 's' + Example response for above graph: + A : 0 + B : 10 + C : 11 + D : 15 +*/ +map dijkstra_shortest_path(char s, vector > graph) +{ int n = graph.size(); + initialize(n,s); + + while(unvisited.size()!=0) // no unvisited node should be left + { char c=find_min(); + for(int i=0;i((char)('A'+i),INT_MAX)); + } + s_path[s]=0; // mark distance for source node as 0 + } + +char find_min() +{ /* c : minimum weighted node in unvisited + a : weight of node c + k : its index in the unvisited vector + */ + char c=unvisited[0]; + int a=s_path.find(unvisited[0])->second,k=0; + for(int i=1;isecond; + if(jsecond; + c=unvisited[i]; + k=i; + } + } + unvisited.erase(unvisited.begin()+k); // delete visited node + return c; + } + +void relax(int i,int j,int w) +{ if(s_path[(char)('A'+i)]>s_path[(char)('A'+j)]+w) + s_path[(char)('A'+i)]=s_path[(char)('A'+j)]+w; + } + + +// main function +int main() +{ + int n=5; // number of nodes in graph + char s='A'; // source node + vector > graph; // directed graph + map paths; // nodes with their distances from source + + /* Define graph like below + A B C D E + A 0 10 0 0 5 + B 0 0 1 0 2 + C 0 0 0 4 0 + D 7 0 6 0 0 + E 0 3 9 2 0 + */ + vector x={0, 10, 0, 0, 5}; + graph.push_back(x); + x = {0, 0, 1, 0, 2}; + graph.push_back(x); + x = {0, 0, 0, 4, 0}; + graph.push_back(x); + x = {7, 0, 6, 0, 0}; + graph.push_back(x); + x = {0, 3, 9, 2, 0}; + graph.push_back(x); + + paths = dijkstra_shortest_path(s, graph); + print_path(s, paths); + return 0; +} + +void print_path(char s, map s_path) +{ for(int i=0;i **Data Access Object Interface** - This interface defines the standard operations to be performed on a model object(s). + +> **Data Access Object concrete class** - This class implements above interface. This class is responsible to get data from a data source which can be database / xml or any other storage mechanism. + +> **Model Object or Value Object** - This object is simple POJO containing get/set methods to store data retrieved using DAO class. + +We are going to create a Student object acting as a Model or Value Object.StudentDao is +Data Access Object Interface.StudentDaoImpl is concrete class implementing Data Access Object Interface. +DaoPatternDemo, our demo class, will use StudentDao to demonstrate the use of Data Access Object pattern. + diff --git a/Java Design Patterns/DAO /Student.java b/Java Design Patterns/DAO /Student.java new file mode 100644 index 00000000..f82409e2 --- /dev/null +++ b/Java Design Patterns/DAO /Student.java @@ -0,0 +1,25 @@ +public class Student { + private String name; + private int rollNo; + + Student(String name, int rollNo){ + this.name = name; + this.rollNo = rollNo; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getRollNo() { + return rollNo; + } + + public void setRollNo(int rollNo) { + this.rollNo = rollNo; + } +} \ No newline at end of file diff --git a/Java Design Patterns/DAO /StudentDao.java b/Java Design Patterns/DAO /StudentDao.java new file mode 100644 index 00000000..d1a7a511 --- /dev/null +++ b/Java Design Patterns/DAO /StudentDao.java @@ -0,0 +1,8 @@ +import java.util.List; + +public interface StudentDao { + public List getAllStudents(); + public Student getStudent(int rollNo); + public void updateStudent(Student student); + public void deleteStudent(Student student); +} \ No newline at end of file diff --git a/Java Design Patterns/DAO /StudentDaoImpl.java b/Java Design Patterns/DAO /StudentDaoImpl.java new file mode 100644 index 00000000..1c1663c0 --- /dev/null +++ b/Java Design Patterns/DAO /StudentDaoImpl.java @@ -0,0 +1,38 @@ +import java.util.ArrayList; +import java.util.List; + +public class StudentDaoImpl implements StudentDao { + + //list is working as a database + List students; + + public StudentDaoImpl(){ + students = new ArrayList(); + Student student1 = new Student("Robert",0); + Student student2 = new Student("John",1); + students.add(student1); + students.add(student2); + } + @Override + public void deleteStudent(Student student) { + students.remove(student.getRollNo()); + System.out.println("Student: Roll No " + student.getRollNo() + ", deleted from database"); + } + + //retrive list of students from the database + @Override + public List getAllStudents() { + return students; + } + + @Override + public Student getStudent(int rollNo) { + return students.get(rollNo); + } + + @Override + public void updateStudent(Student student) { + students.get(student.getRollNo()).setName(student.getName()); + System.out.println("Student: Roll No " + student.getRollNo() + ", updated in the database"); + } +} \ No newline at end of file diff --git a/Java Design Patterns/Singleton/README.md b/Java Design Patterns/Singleton/README.md new file mode 100644 index 00000000..a395ba35 --- /dev/null +++ b/Java Design Patterns/Singleton/README.md @@ -0,0 +1,23 @@ + +## Singleton + +Singleton Pattern is one of the Gangs of Four Design patterns +and comes in the Creational Design Pattern category. +From the definition, it seems to be a very simple design pattern but when it comes to implementation, +it comes with a lot of implementation concerns. + +*Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine.* +> The singleton class must provide a global access point to get the instance of the class. + +> Singleton pattern is used for logging, drivers objects, caching and thread pool. + +> Singleton design pattern is also used in other design patterns like Abstract Factory, Builder, Prototype, Facade etc. + +> Singleton design pattern is used in core java classes also, for example java.lang.Runtime, java.awt.Desktop. + +*To implement Singleton pattern, we have different approaches but all of them have following common concepts.* +>Private constructor to restrict instantiation of the class from other classes. + +>Private static variable of the same class that is the only instance of the class. + +>Public static method that returns the instance of the class, this is the global access point for outer world to get the instance of the singleton class. diff --git a/Java Design Patterns/Singleton/Singleton.java b/Java Design Patterns/Singleton/Singleton.java new file mode 100644 index 00000000..896dc76f --- /dev/null +++ b/Java Design Patterns/Singleton/Singleton.java @@ -0,0 +1,17 @@ +public class SingletonClass +{ + //static instance of SingletonClass + private static SingletonClass sInstance; + //unreachable constructor + private SingletonClass() { + + } + //access method to static instance of SingletonClass + public static SingletonClass getInstance() + { + if(sInstance == null){ + sInstance = new SingletonClass(); + } + return sInstance; + } +} diff --git a/Java Design Patterns/builder /README.md b/Java Design Patterns/builder /README.md new file mode 100644 index 00000000..fdf97f1d --- /dev/null +++ b/Java Design Patterns/builder /README.md @@ -0,0 +1,17 @@ +## Builder Pattern + Builder pattern was introduced to solve some of the problems with Factory and Abstract Factory design patterns when the Object contains a lot of attributes. + There are three major issues with Factory and Abstract Factory design patterns when the Object contains a lot of attributes. + +> Too Many arguments to pass from client program to the Factory class that can be error prone because most of the time, the type of arguments are same and from client side its hard to maintain the order of the argument. +> Some of the parameters might be optional but in Factory pattern, we are forced to send all the parameters and optional parameters need to send as NULL. +> If the object is heavy and its creation is complex, then all that complexity will be part of Factory classes that is confusing. + + We can solve the issues with large number of parameters by providing a constructor with required parameters and then different setter methods to set the optional parameters. The problem with this approach is that the Object state will be inconsistent until unless all the attributes are set explicitly. + Builder pattern solves the issue with large number of optional parameters and inconsistent state by providing a way to build the object step-by-step and provide a method that will actually return the final Object. + +## How to implement the design pattern in Java + +> First of all you need to create a static nested class and then copy all the arguments from the outer class to the Builder class. We should follow the naming convention and if the class name is Computer then builder class should be named as ComputerBuilder. +> Java Builder class should have a public constructor with all the required attributes as parameters. +> Java Builder class should have methods to set the optional parameters and it should return the same Builder object after setting the optional attribute. +> The final step is to provide a build() method in the builder class that will return the Object needed by client program. For this we need to have a private constructor in the Class with Builder class as argument. diff --git a/Java Design Patterns/builder /builder.java b/Java Design Patterns/builder /builder.java new file mode 100644 index 00000000..485c9171 --- /dev/null +++ b/Java Design Patterns/builder /builder.java @@ -0,0 +1,70 @@ + +class Computer { + + //required parameters + private String HDD; + private String RAM; + + //optional parameters + private boolean isGraphicsCardEnabled; + private boolean isBluetoothEnabled; + public String getHDD() { + return HDD; + } + public String getRAM() { + return RAM; + } + public boolean isGraphicsCardEnabled() { + return isGraphicsCardEnabled; + } + public boolean isBluetoothEnabled() { + return isBluetoothEnabled; + } + private Computer(ComputerBuilder builder) { + this.HDD=builder.HDD; + this.RAM=builder.RAM; + this.isGraphicsCardEnabled=builder.isGraphicsCardEnabled; + this.isBluetoothEnabled=builder.isBluetoothEnabled; + } + + //Builder Class + public static class ComputerBuilder{ + + // required parameters + private String HDD; + private String RAM; + + // optional parameters + private boolean isGraphicsCardEnabled; + private boolean isBluetoothEnabled; + + public ComputerBuilder(String hdd, String ram){ + this.HDD=hdd; + this.RAM=ram; + } + public ComputerBuilder setGraphicsCardEnabled(boolean isGraphicsCardEnabled) { + this.isGraphicsCardEnabled = isGraphicsCardEnabled; + return this; + } + public ComputerBuilder setBluetoothEnabled(boolean isBluetoothEnabled) { + this.isBluetoothEnabled = isBluetoothEnabled; + return this; + } + public Computer build(){ + return new Computer(this); + } + } +} + + + + +public class TestBuilderPattern { + public static void main(String[] args) { + // Using builder to get the object in a single line of code and + // without any inconsistent state or arguments management issues + Computer comp = new Computer.ComputerBuilder( + "500 GB", "2 GB").setBluetoothEnabled(true) + .setGraphicsCardEnabled(true).build(); + } +} diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..db238c2c --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Asiatik + +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. diff --git a/Machine Learning/.gitkeep b/Machine Learning/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/Maths/Euclidean Algorithm/C++/GCD.cpp b/Maths/Euclidean Algorithm/C++/GCD.cpp new file mode 100644 index 00000000..6e070776 --- /dev/null +++ b/Maths/Euclidean Algorithm/C++/GCD.cpp @@ -0,0 +1,20 @@ +#include + +//Using template here to support both long and ints. +template +integer gcd(integer a, integer b) +{ + if (a == 0 || b == 0) + { + return a + b; + } + return gcd(b, b % a); +} + +int main( int argv,char* argc[] ) +{ + std::cout << gcd (100,10) << std::endl; + std::cout << gcd (-100,10) << std::endl; + std::cout << gcd (3,1) << std::endl; + std::cout << gcd(3L,1L); +} diff --git a/Maths/Euclidean Algorithm/C/GCD.c b/Maths/Euclidean Algorithm/C/GCD.c new file mode 100644 index 00000000..218a06f7 --- /dev/null +++ b/Maths/Euclidean Algorithm/C/GCD.c @@ -0,0 +1,16 @@ +#include "stdio.h" + +//You should probably function overload to support longs as well. +int gcd(int a, int b) +{ + if (a==0 || b==0) + { + return a + b; + } + return gcd(b, b % a); +} + +int main(int argc, char* argv[]) +{ + printf("%d\n%d\n%d",gcd(100,10),gcd(100,-10),gcd(3,7)); +} diff --git a/Maths/Euclidean Algorithm/Java/GCD.java b/Maths/Euclidean Algorithm/Java/GCD.java new file mode 100644 index 00000000..d9a14ad3 --- /dev/null +++ b/Maths/Euclidean Algorithm/Java/GCD.java @@ -0,0 +1,12 @@ +public class GCD{ + + public static int gcd(int a, int b){ + if ( a==0 || b==0){ + return a+b; + } + return gcd(b, b % a) + } + + public static void main(String args[]){ + } +} diff --git a/Maths/Euclidean Algorithm/Python/GCD.py b/Maths/Euclidean Algorithm/Python/GCD.py new file mode 100644 index 00000000..1eb4b3de --- /dev/null +++ b/Maths/Euclidean Algorithm/Python/GCD.py @@ -0,0 +1,9 @@ +#Using python3 +def gcd(a, b): + if a == 0 or b == 0: + return a + b + return gcd(b, a % b) + +if __name__=='__main__': + print (gcd(10,100)) + print (gcd(9,145)) diff --git a/Maths/Euclidean Algorithm/README.md b/Maths/Euclidean Algorithm/README.md new file mode 100644 index 00000000..058a639b --- /dev/null +++ b/Maths/Euclidean Algorithm/README.md @@ -0,0 +1,15 @@ +# Euclidean Algorithm + +[Wikipedia Entry](https://en.wikipedia.org/wiki/Euclidean_algorithm) + +This is one of the fastest method for finding the greatest common divisior between two numbers. + + +## Pseudocode + + function gcd(a, b) + while b ≠ 0 + t := b; + b := a mod b; + a := t; + return a; diff --git a/README.md b/README.md new file mode 100644 index 00000000..eba79bc2 --- /dev/null +++ b/README.md @@ -0,0 +1,76 @@ +# codezilla + +[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT) +[![Gitter](https://img.shields.io/gitter/room/DAVFoundation/DAV-Contributors.svg?)](https://gitter.im/asiatik-open/codezilla) + +codezilla 🦖 One giant collection of algorithms & design patterns. + +> The pandora box of algorithms and data structures + +Feel free to contribute. Create an issue, let others know which algorithm/data structure you are planning to add. Fork the repo. And make a PR! + +> The goal is to create a codebase for developers to access. Later we aim to develop extensions using this codebase to support multiple IDEs. + + +## How To Contribute to This Project +Here are 3 quick and painless steps to contribute to this project: + +* Add a a program to implement an algorithm in any language. +To do so, first create an issue with the task you are doing, for example: "Issue - creating bubble sort in C". Create a pull request in response to that issue and finally submit it for review. + +* Name your branch Like `#23 Add Bubble Sort in C`. + + Also create a directory for any new algorithm if it doesn't exist. + eg. `observable_pattern`, `bubble_sort`. + Inside these directories you can create a folder for the programming language you want to add. And finally add your own file named `program_name.language_extension` (`bubble_sort.cpp`) + Create a commit of the form - fixes #(issue_number) + +* Finally, wait for it to be merged! + +## Getting Started +* Fork this repository (Click the Fork button in the top right of this page, click your Profile Image) +* Clone your fork down to your local machine + + ```sh + $ git clone https://github.com/Asiatik/codezilla.git + ``` + +* Create a branch + + ```sh + $ git checkout -b branch-name + ``` + +* Make your changes +* Commit and Push + + ```sh + $ git add filename + $ git commit -m 'commit message' + $ git push origin branch-name + ``` + +* Create a New Pull Request from your forked repository (Click the New Pull Request button located at the top of your repo) +* Wait for your PR review and merge approval! +* __Star this repository__ if you had fun! + + +Don't forget to include the comments as seen above. Feel free to include additional information about the language you chose in your comments too! Like a link to a helpful introduction or tutorial. + +## Reference Links +* [Tutorial: Creating your first pull request](https://github.com/Roshanjossey/first-contributions) + +* [Managing your Forked Repo](https://help.github.com/articles/fork-a-repo/) + +* [Syncing a Fork](https://help.github.com/articles/syncing-a-fork/) + +* [Keep Your Fork Synced](https://gist.github.com/CristinaSolana/1885435) + +* [Awesome README examples ![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/sindresorhus/awesome) + +* [Github-Flavored Markdown](https://guides.github.com/features/mastering-markdown/) + +## Additional References Added By Contributors + +* [GitHub license explained](https://choosealicense.com) + diff --git a/Searching/.gitkeep b/Searching/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/Searching/Binary Search/C++/BinarySearch.cpp b/Searching/Binary Search/C++/BinarySearch.cpp new file mode 100644 index 00000000..341fdde4 --- /dev/null +++ b/Searching/Binary Search/C++/BinarySearch.cpp @@ -0,0 +1,48 @@ +#include + +/* +* Binary search algorithm +* This is the exact implementation of the pseudocode written in README. +* Notice that even if the array list contains multiple items, +* it will return only one index. +* Thus this algorithm is well suited to find if a item is present. +* And not for finding the exact index if multiple items are present. +* +* With C++ you have to be careful of integer overflows. +* So we must make sure that the length of itemList is below that of int. +* Also the size of the array must also be sent. +*/ + +//Notice that itemList is passed as a pointer here. No expensive copying takes place. +int binarySearch(int itemList[],int itemListSize,int item) +{ + int leftIndex = 0; + int rightIndex = itemListSize; + int middleIndex; + while (leftIndex <= rightIndex) + { + middleIndex = (leftIndex+rightIndex)/2; + if (itemList[middleIndex] < item) + { + leftIndex = middleIndex + 1; + } + else if(itemList[middleIndex] > item) + { + rightIndex = middleIndex - 1; + } + else{ + return middleIndex; + } + } + return -1; + +} + +//Simple demonstration for the algorithm +int main(int argc,char* argv[]) +{ + int arr[] = {1,2,3,4,5}; + std::cout << binarySearch(arr,sizeof(arr)/sizeof(arr[0]),3) << std::endl; + std::cout << binarySearch(arr,sizeof(arr)/sizeof(arr[0]),0); + +} diff --git a/Searching/Binary Search/C/BinarySearch.c b/Searching/Binary Search/C/BinarySearch.c new file mode 100644 index 00000000..8f30b75c --- /dev/null +++ b/Searching/Binary Search/C/BinarySearch.c @@ -0,0 +1,48 @@ +#include "stdio.h" + +/* +* Binary search algorithm +* This is the exact implementation of the pseudocode written in README. +* Notice that even if the array list contains multiple items, +* it will return only one index. +* Thus this algorithm is well suited to find if a item is present. +* And not for finding the exact index if multiple items are present. +* +* With C you have to be careful of integer overflows. +* So we must make sure that the length of itemList is below that of int. +* Also the size of the array must also be sent. +*/ + +//Notice that itemList is passed as a pointer. No expensive copying takes place. +int binarySearch(int itemList[],int itemListSize,int item) +{ + int leftIndex = 0; + int rightIndex = itemListSize; + int middleIndex; + while (leftIndex <= rightIndex) + { + middleIndex = (leftIndex+rightIndex)/2; + if (itemList[middleIndex] < item) + { + leftIndex = middleIndex + 1; + } + else if(itemList[middleIndex] > item) + { + rightIndex = middleIndex - 1; + } + else{ + return middleIndex; + } + } + return -1; + +} + +//Simple demonstration for the algorithm +int main(int argc,char* argv[]) +{ + int arr[] = {1,2,3,4,5}; + printf("%d",binarySearch(arr,sizeof(arr)/sizeof(arr[0]),3)); + printf("%d",binarySearch(arr,sizeof(arr)/sizeof(arr[0]),0)); + +} diff --git a/Searching/Binary Search/Java/BinarySearch.java b/Searching/Binary Search/Java/BinarySearch.java new file mode 100644 index 00000000..1a965b2e --- /dev/null +++ b/Searching/Binary Search/Java/BinarySearch.java @@ -0,0 +1,44 @@ +public class BinarySearch{ + + /** + * Binary search algorithm + * This is the exact implementation of the pseudocode written in README. + * Notice that even if the array list contains multiple items, + * it will return only one index. + * Thus this algorithm is well suited to find if a item is present. + * And not for finding the exact index if multiple items are present. + * + * With java you have to be careful of integer overflows. + * So we must make sure that the length of itemList is below that of int. + * + * @param itemList List of all the sorted items + * @param item The item to search for + * @return Index of the item + */ + public static int binarySearch(int itemList[],int item){ + int leftIndex=0; + int rightIndex=itemList.length-1; + int middleIndex; + + while(leftIndex<=rightIndex){ + middleIndex=(leftIndex+rightIndex)/2; + + if(itemList[middleIndex]item){ + rightIndex=middleIndex-1; + } + else{ + return middleIndex; + } + } + return -1; + } + + //Simple desmonstration of the function + public static void main(String args[]){ + System.out.println(binarySearch(new int[]{1,2,3,4,5},6)); + System.out.println(binarySearch(new int[]{1,2,3,4,5},3)); + } +} diff --git a/Searching/Binary Search/Python/BinarySearch.py b/Searching/Binary Search/Python/BinarySearch.py new file mode 100644 index 00000000..75cb8261 --- /dev/null +++ b/Searching/Binary Search/Python/BinarySearch.py @@ -0,0 +1,23 @@ +""" +This is a simple binary search algorithm for python. +This is the exact implementation of the pseudocode written in README. +""" + +def binary_search(item_list,item): + left_index = 0 + right_index = len(item_list)-1 + + while left_index <= right_index: + middle_index = (left_index+right_index) / 2 + if item_list[middle_index] < item: + left_index=middle_index+1 + elif item_list[middle_index] > item: + right_index=middle_index-1 + else: + return middle_index + return None + +#Simple demonstration of the function +if __name__=='__main__': + print (binary_search([1,3,5,7],3)) + print (binary_search([1,2,5,7,97],0)) diff --git a/Searching/Binary Search/README.md b/Searching/Binary Search/README.md new file mode 100644 index 00000000..a8829ca7 --- /dev/null +++ b/Searching/Binary Search/README.md @@ -0,0 +1,33 @@ +# Binary Search + +>Worst Case Time Complexity: O(log n) + +>Space Complexity: (O(1)) + +[Wikipedia Entry](https://en.wikipedia.org/wiki/Binary_search_algorithm) + +## Pseudocode + +A is the array, n is the size of array and T is the item + + + function binary_search(A, n, T): + L := 0 + R := n − 1 + + while L <= R: + m := floor((L + R) / 2) + if A[m] < T: + L := m + 1 + else if A[m] > T: + R := m - 1 + else: + return m + return unsuccessful + +Notice that even if the array list contains multiple items, it will return only one index. +Thus this algorithm is well suited to find if a item is present. +And not for finding the exact index if multiple items are present. + +Binary search can also be obtain the indexes of the items present. +And unlike the version here which works on numbers, binary search can work on any sorted array. For example binary search can be used in lexiographically arranged strings. diff --git a/Searching/Linear Search/C++/LinearSearch.cpp b/Searching/Linear Search/C++/LinearSearch.cpp new file mode 100644 index 00000000..0d6c4b40 --- /dev/null +++ b/Searching/Linear Search/C++/LinearSearch.cpp @@ -0,0 +1,37 @@ +#include + +/** +* Linear search algorithm +* This is the exact implementation of the pseudocode written in README. +* Notice that even if the array list contains multiple items, +* it will return only one index. +* Thus this algorithm is well suited to find if a item is present. +* And not for finding the exact index if multiple items are present. +* With C++ you have to be careful of integer overflows. +* So we must make sure that the length of itemList is below that of int. +*/ + +//Notice that itemList is passed by pointer. No unnecessary copy takes place. +int linearSearch(int itemList[],int itemListSize,int item) +{ + int index=0; + while (index < itemListSize) + { + if (itemList[index] == item) + { + return index; + } + index++; + } + return -1; + +} + + //Simple demonstration for the algorithm +int main(int argc,char* argv[]) +{ + int arr[] = {1,2,3,4,5}; + std::cout << linearSearch(arr,sizeof(arr)/sizeof(arr[0]),3) << std::endl; + std::cout << linearSearch(arr,sizeof(arr)/sizeof(arr[0]),0); + +} diff --git a/Searching/Linear Search/C/LinearSearch.c b/Searching/Linear Search/C/LinearSearch.c new file mode 100644 index 00000000..94eaedc0 --- /dev/null +++ b/Searching/Linear Search/C/LinearSearch.c @@ -0,0 +1,24 @@ +#include "stdio.h" + +int linearSearch(int itemList[],int itemListSize,int item) +{ + int index=0; + while (index < itemListSize) + { + if (itemList[index] == item) + { + return index; + } + index++; + } + return -1; + +} + //Simple demonstration for the algorithm +int main(int argc,char* argv[]) +{ + int arr[] = {1,2,3,4,5}; + printf("%d\n",linearSearch(arr,sizeof(arr)/sizeof(arr[0]),3)); + printf("%d",linearSearch(arr,sizeof(arr)/sizeof(arr[0]),0)); + +} diff --git a/Searching/Linear Search/Java/LinearSearch.java b/Searching/Linear Search/Java/LinearSearch.java new file mode 100644 index 00000000..9467206e --- /dev/null +++ b/Searching/Linear Search/Java/LinearSearch.java @@ -0,0 +1,34 @@ +public class LinearSearch{ + + /** + * Linear search algorithm + * This is the exact implementation of the pseudocode written in README. + * Notice that even if the array list contains multiple items, + * it will return only one index. + * Thus this algorithm is well suited to find if a item is present. + * And not for finding the exact index if multiple items are present. + * + * With java you have to be careful of integer overflows. + * So we must make sure that the length of itemList is below that of int. + * + * @param itemList List of all the sorted items + * @param item The item to search for + * @return Index of the item + */ + public static int linearSearch(int[] itemList,int item){ + int index=0; + while ( index < itemList.length ){ + if ( itemList[index] == item ){ + return index; + } + index++; + } + return -1; + } + + //Simple desmonstration of the function + public static void main(String args[]){ + System.out.println(linearSearch(new int[]{1,2,3,4,5},6)); + System.out.println(linearSearch(new int[]{1,2,3,4,5},3)); + } +} diff --git a/Searching/Linear Search/Python/LinearSearch.py b/Searching/Linear Search/Python/LinearSearch.py new file mode 100644 index 00000000..9f8e5f20 --- /dev/null +++ b/Searching/Linear Search/Python/LinearSearch.py @@ -0,0 +1,16 @@ +""" +This is a simple Linear search algorithm for python. +This is the exact implementation of the pseudocode written in README. +""" +def linear_search(item_list,item): + index=0 + while index < len(item_list): + if item_list[index] == item: + return index + index+=1 + return None + +#Simple demonstration of the function +if __name__=='__main__': + print (linear_search([1,3,5,7],3)) + print (linear_search([1,2,5,7,97],0)) diff --git a/Searching/Linear Search/README.md b/Searching/Linear Search/README.md new file mode 100644 index 00000000..336aea0a --- /dev/null +++ b/Searching/Linear Search/README.md @@ -0,0 +1,26 @@ +# Linear Search + +>Worst Case Time Complexity: O(n) + +>Space Complexity: O(1) + +[Wikipedia Entry](https://en.wikipedia.org/wiki/Linear_search) + +## Pseudocode + +A is the array, n is the size of array and T is the item + + + function linear_search(A, n, T): + i=0 + while i < n: + if A[i] == T: + return i + i=i+1 + return unsuccessful + +Notice that even if the array list contains multiple items, it will return only one index. +Thus this algorithm is well suited to find if a item is present. +And not for finding the exact index if multiple items are present. + +This algorithm is rarely used since there are always better options like binary search or hash tables. diff --git a/Sorting/Bubble Sort/C#/BubbleSort.cs b/Sorting/Bubble Sort/C#/BubbleSort.cs new file mode 100644 index 00000000..e5179140 --- /dev/null +++ b/Sorting/Bubble Sort/C#/BubbleSort.cs @@ -0,0 +1,58 @@ +using System; + +namespace BubbleSort +{ + class Program + { + static void Main(string[] args) + { + // declare an array of integers that are not sorted + int[] nums = { 5, 10, 3, 2, 4 }; + + + // Use this to know when to stop the sorting routine + bool swapped; + + // Here we use a do loop but could have used for or while loops as well. + do + { + // set swapped to false so that we can ensure at least one pass on the array + swapped = false; + + // This loop will iterate over the array from beginning to end + for (int i = 0; i < nums.Length - 1; i++) + { + // here we use the i for the position in the array + // So i is the first value to compare and i + 1 compare the next two sets of values, etc. + // Once i is incremented at the end of this loop, we compare the next two sets of values, etc. + if (nums[i] > nums[i + 1]) + { + // swap routine. Could be a separate method as well but is used inline for simplicity here + // temp is used to hold the right value in the comparison so we don't lose it. That value will be replaced in the next step + int temp = nums[i + 1]; + + // Here we replace the right value with the large value that was on the left. See why we needed the temp variable above? + nums[i + 1] = nums[i]; + + // Now we assign the value that is in temp, the smaller value, to the location that was just vacated by the larger number + nums[i] = temp; + + // Indicate that we did a swap, which means we need to continue to check the remaining values. + swapped = true; + } + } + } while (swapped == true); + + // output the sorted array to the console + + Console.Write("After: "); + for (int i = 0; i < nums.Length; i ++) + { + Console.Write("{0}, ", nums[i]); + } + + // Use Console.ReadLine() in the event application was started with debugging. + Console.ReadLine(); + } + } +} diff --git a/Sorting/Bubble Sort/Java/BubbleSort.java b/Sorting/Bubble Sort/Java/BubbleSort.java new file mode 100644 index 00000000..aabfffa3 --- /dev/null +++ b/Sorting/Bubble Sort/Java/BubbleSort.java @@ -0,0 +1,50 @@ +//Bubble sort Algorithm +// Java program for implementation of BubbleSort + +class BubbleSort +{ + /* Fuction Implementing Bubble Sort Algorithm */ + void sort(int arr[]) + { + int swapped; + int length = arr.length; + for(int i=0; iarr[j+1]) + { + int temp=arr[j+1]; + arr[j+1]=arr[j]; + arr[j]=temp; + swapped=1; + } + } + if(swapped==0) + break; + } + } + + /* A utility function to print array of size n */ + static void printArray(int arr[]) + { + int n = arr.length; + for (int i=0; i +using namespace std; + +// To heapify a subtree rooted with node i which is +// an index in arr[]. n is size of heap +//using max heap for this implementation. +//In max heap the the root node is the largest +void heapify(int arr[], int n, int i) +{ + int largest = i; // Initialize largest as root + int l = 2*i + 1; // left = 2*i + 1 + int r = 2*i + 2; // right = 2*i + 2 + + // If left child is larger than root + if (l < n && arr[l] > arr[largest]) + largest = l; + + // If right child is larger than largest so far + if (r < n && arr[r] > arr[largest]) + largest = r; + + // If largest is not root + if (largest != i) + { + swap(arr[i], arr[largest]); + + // Recursively heapify the affected sub-tree + heapify(arr, n, largest); + } +} + +// main function to do heap sort +//we recursively call the heapify function in heapSort +void heapSort(int arr[], int n) +{ + // Build heap (rearrange array) + for (int i = n / 2 - 1; i >= 0; i--) + heapify(arr, n, i); + + // One by one extract an element from heap + for (int i=n-1; i>=0; i--) + { + // Move current root to end + swap(arr[0], arr[i]); + + // call max heapify on the reduced heap + heapify(arr, i, 0); + } +} + +/* A utility function to print array of size n */ +void printArray(int arr[], int n) +{ + for (int i=0; i>size_of_arr; + int arr[size_of_arr]; + for(int i=0;i>arr[i]; + } + + heapSort(arr, size_of_arr); + + cout << "Sorted array is \n"; + printArray(arr, size_of_arr); +} diff --git a/Sorting/Heap Sort/HeapSort.java b/Sorting/Heap Sort/HeapSort.java new file mode 100644 index 00000000..37d57222 --- /dev/null +++ b/Sorting/Heap Sort/HeapSort.java @@ -0,0 +1,74 @@ +// Java program for implementation of Heap Sort +public class HeapSort +{ + public void sort(int arr[]) + { + int n = arr.length; + + // Build heap (rearrange array) + for (int i = n / 2 - 1; i >= 0; i--) + heapify(arr, n, i); + + // One by one extract an element from heap + for (int i=n-1; i>=0; i--) + { + // Move current root to end + int temp = arr[0]; + arr[0] = arr[i]; + arr[i] = temp; + + // call max heapify on the reduced heap + heapify(arr, i, 0); + } + } + + // To heapify a subtree rooted with node i which is + // an index in arr[]. n is size of heap + void heapify(int arr[], int n, int i) + { + int largest = i; // Initialize largest as root + int l = 2*i + 1; // left = 2*i + 1 + int r = 2*i + 2; // right = 2*i + 2 + + // If left child is larger than root + if (l < n && arr[l] > arr[largest]) + largest = l; + + // If right child is larger than largest so far + if (r < n && arr[r] > arr[largest]) + largest = r; + + // If largest is not root + if (largest != i) + { + int swap = arr[i]; + arr[i] = arr[largest]; + arr[largest] = swap; + + // Recursively heapify the affected sub-tree + heapify(arr, n, largest); + } + } + + /* A utility function to print array of size n */ + static void printArray(int arr[]) + { + int n = arr.length; + for (int i=0; i=0&&arr[t]>temp;t--) + { + arr[t+1]=arr[t]; + } + arr[t+1]=temp; + } + } + // driver program + public static void main(String args[]) + { + int arr[] = {10,1,0,11,12,20,21}; + + System.out.println("Given Array"); + System.out.print(Arrays.toString(arr)); + InsertionSort ob = new InsertionSort(); + ob.sort(arr); + + System.out.println("\nSorted array"); + System.out.print(Arrays.toString(arr)); + } +} diff --git a/Sorting/Merge Sort/C++/Arrays/MergeSortArray.cpp b/Sorting/Merge Sort/C++/Arrays/MergeSortArray.cpp new file mode 100644 index 00000000..47d4abf9 --- /dev/null +++ b/Sorting/Merge Sort/C++/Arrays/MergeSortArray.cpp @@ -0,0 +1,110 @@ +// This is an implemation of MergeSortArray class + +#include +#include +#include +#include "MergeSortArray.h" + +// Uncommenet to debug the code +//#define DEBUG + +// This is not a memober of class +template +void printArray(T *arr, N left, N right) { + for (N i = left; i <= right; i++) { + std::cout << arr[i] << " "; + } + std::cout << std::endl; +} + +template +MergeSortArray::MergeSortArray() { + newArray = nullptr; +} + +template +void MergeSortArray::mergeSort(T* arr, N len) { + newArray = new T[len]; +#ifdef DEBUG + std::cout << "Length: " << len << std::endl; +#endif + sort(arr, 0, len-1); +} + +// left index, right index of the array to sort +template +void MergeSortArray::sort(T* arr, N left, N right) { + if (right == left) return; + // Split the array + N mid = floor((left+right) / 2); + +#ifdef DEBUG + std::cout << "Left start: " << left << " "; + std::cout << "Left end: " << mid << std::endl; + printArray(arr, left, mid); +#endif + // Call merge sort on left chunk + sort(arr, left, mid); +#ifdef DEBUG + std::cout << "Right start: " << mid+1 << " "; + std::cout << "Right end: " << right << std::endl; + printArray(arr, mid+1, right); +#endif + // Call merge sort on right chunk + sort(arr, mid+1, right); + // Merge the sorted elemnts on right side + mergeTheArray(arr, left, mid, right); +} + +template +void MergeSortArray::mergeTheArray(T* arr, N left, N mid, N right) { +#ifdef DEBUG + std::cout << "Merging the array: " << std::endl; + std::cout << "Left start: " << left << " Mid: " << mid << " Right end : " << right << std::endl; +#endif + // Left chunk is arr[left....mid] + // Right chunk is arr[mid+1....right] + + N k = left; + N i = left; + N j = mid+1; + // Compare left and right chunk + while (i <= mid && j <= right) { + if (arr[i] > arr[j]) { + newArray[k] = arr[j]; + j++; + } + else { + newArray[k] = arr[i]; + i++; + } + k++; + } + // Copy the rest of the elements from left chunk if any + if (i <= mid) { + for (; k <= right; k++) { + newArray[k] = arr[i]; + i++; + } + } + // Copy the rest of the elements from right chunk if any + else if (j <= right) { + for (; k <= right; k++) { + newArray[k] = arr[j]; + j++; + } + } + // arr[left...right] is replaced with sorted values stored in newArray[left....right] + for (k = left; k <= right; k++) { + arr[k] = newArray[k]; + } +#ifdef DEBUG + // print the sorted part + printArray(arr, left, right); +#endif +} + +template +MergeSortArray::~MergeSortArray() { + delete[] newArray; +} diff --git a/Sorting/Merge Sort/C++/Arrays/MergeSortArray.h b/Sorting/Merge Sort/C++/Arrays/MergeSortArray.h new file mode 100644 index 00000000..8c455028 --- /dev/null +++ b/Sorting/Merge Sort/C++/Arrays/MergeSortArray.h @@ -0,0 +1,19 @@ +#ifndef MERGESORTARRAY_H +#define MERGESORTARRAY_H + +template +class MergeSortArray { +public: + MergeSortArray(); + void mergeSort(T* arr, N len); + ~MergeSortArray(); +private: + void sort(T* arr, N left, N right); + void mergeTheArray(T* arr, N left_start, N right_start, N right_end); + // Buffer + T *newArray; +}; +// To avoid linker error +#include "MergeSortArray.cpp" + +#endif diff --git a/Sorting/Merge Sort/C++/Arrays/MergeSortArrayTest.cpp b/Sorting/Merge Sort/C++/Arrays/MergeSortArrayTest.cpp new file mode 100644 index 00000000..4cec0652 --- /dev/null +++ b/Sorting/Merge Sort/C++/Arrays/MergeSortArrayTest.cpp @@ -0,0 +1,73 @@ +/********************************************************************************* +* Instructions: +* To compile: g++ MergeSort_ArrayTest.cpp -o MergeSort_ArrayTest -std=c++11 +* To run: ./MergeSort_ArrayTest [#elements] +* Where #elements is number of elements in an array, default is 100. +* Author: Mounika Ponugoti +*********************************************************************************/ +#include +#include +#include +#include +#include +#include "MergeSortArray.h" + +// Number of elements in an array +int length = 100; + +// Prints the array +template +void printArray(T *arr, N length) { + for (N i = 0; i < length; i++) { + std::cout << arr[i] << " "; + } + std::cout << std::endl; +} + +// Initialize the array with random values +template +void initializeArray(T *arr, N length) { + for (N i = 0; i < length; i++) { + arr[i] = static_cast (rand()) / static_cast (RAND_MAX/10); + } +} + +int main(int argc, char **argv) +{ + if (argc == 2) { + length = std::atoi(argv[1]); + } + if (argc > 2) { + std::cout << "Usage: ./main [#elemnts]" << std::endl; + exit(1); + } + // Seed for random number generator + srand(time(NULL)); + // Sorting integer Array + int *arr = new int[length]; + initializeArray(arr, length); + std::cout << "Unsorted Array: " << std::endl; + printArray(arr, length); + + MergeSortArray mergeSort_obj; + mergeSort_obj.mergeSort(arr, length); + std::cout << "Sorted Array: " << std::endl; + printArray(arr, length); + + // Sorting floating point numbers + float *arr_f = new float[length]; + initializeArray(arr_f, length); + std::cout << "Unsorted Array: " << std::endl; + std::cout << std::fixed << std::setprecision(2); + printArray(arr_f, length); + + MergeSortArray mergeSort_obj_2; + mergeSort_obj_2.mergeSort(arr_f, length); + std::cout << "Sorted Array: " << std::endl; + printArray(arr_f, length); + + // Free the allocated memory + delete[] arr; + delete[] arr_f; + return 0; +} diff --git a/Sorting/Merge Sort/C++/Linked Lists/MergeSortLinkedList.cpp b/Sorting/Merge Sort/C++/Linked Lists/MergeSortLinkedList.cpp new file mode 100644 index 00000000..25be65fe --- /dev/null +++ b/Sorting/Merge Sort/C++/Linked Lists/MergeSortLinkedList.cpp @@ -0,0 +1,215 @@ +// This is an implemation of MergeSortLinkedList class + +#include +#include +#include +#include "MergeSortLinkedList.h" + +// Uncommenet to debug the code +//#define DEBUG + +// This is not a memober of class +template +void printList(Node* temp) { + while (temp != nullptr) { + std::cout << "|" << temp->val << "|-->"; + temp = temp->next; + } + std::cout << "null" << std::endl; + return; +} + +template +MergeSortLinkedList::MergeSortLinkedList() { +} + +template +T2 MergeSortLinkedList::getLength(Node* temp) { + T2 length = 0; + while (temp != nullptr) { + temp = temp->next; + length++; + } + return length; +} +// When the node is given +template +void MergeSortLinkedList::insertItem(Node*& head, Node* afterNode, T1 item) { + // empty list or insert in the end + if ((head == nullptr) || (afterNode->next == nullptr)) { + insertItemAtEnd(head, item); + } + else { // insert in the middle + Node* N = new Node(item); + N->next = afterNode->next; + afterNode->next = N; + } + return; +} +//when the item is given +template +void MergeSortLinkedList::insertItem(Node*& head, T1 afterItem, T1 item) { + // empty list or insert in the end + Node* findNode = head; + // find the node + while ((head != nullptr)&&(findNode->val != afterItem) && (findNode->next != nullptr)) { + findNode = findNode->next; + } + if ((head == nullptr) || (findNode->next == nullptr)) { + insertItemAtEnd(head, item); + } + else { // insert in the middle + Node* N = new Node(item); + N->next = findNode->next; + findNode->next = N; + } + return; +} + +template +void MergeSortLinkedList::insertItemAtEnd(Node*& head, T1 item) { + // already initialized with item + Node* N = new Node(item); + if (head == nullptr) { + head = N; + } + else { + Node* temp = head; + while (temp->next != nullptr) { + temp = temp->next; + } + temp->next = N; + } + return; +} + +template +void MergeSortLinkedList::deleteItem(Node*& head, T1 item) { + Node* prev, *deleteNode; + deleteNode = head; + while ((deleteNode != nullptr) && (deleteNode->val != item)) { + prev = deleteNode; + deleteNode = deleteNode->next; + } + if (deleteNode == nullptr) { + return; + } + else if (deleteNode == head) { + head = deleteNode->next; + } + else { + prev->next = deleteNode->next; + } + delete deleteNode; + return; +} + +template +void MergeSortLinkedList::deleteItemAtEnd(Node*& head) { + Node* curr, *prev; + curr = head; + if (curr == nullptr) return; + while (curr->next != nullptr) { + prev = curr; + curr = curr->next; + } + if (curr == head) head = nullptr; + else prev->next = nullptr; + delete curr; + return; +} + +template +void MergeSortLinkedList::mergeSort(Node*& newList) { + sort(newList); +} + +// left index, right index of the array to sort +template +void MergeSortLinkedList::sort(Node*& Head) { + // base case + if (Head == nullptr || Head->next == nullptr) return; + // Split the list + T2 mid = ceil(getLength(Head) / 2); + Node* newRightHead = nullptr; + Node* newLeftHead = nullptr; +#ifdef DEBUG + std::cout << "List: "; + printList(Head); + std::cout << "mid point: " << mid << std::endl; +#endif + newLeftHead = Head; + for (T2 i = 1; i < mid; i++) { + newLeftHead = newLeftHead->next; + } + // start of the right part + newRightHead = newLeftHead->next; + newLeftHead->next = nullptr; + // reset to beginning + newLeftHead = Head; +#ifdef DEBUG + std::cout << "Left start: " << newLeftHead->val << " "; + printList(newLeftHead); +#endif + // Call merge sort on left chunk + sort(newLeftHead); +#ifdef DEBUG + std::cout << "Right start: " << newRightHead->val << " "; + printList(newRightHead); +#endif + // Call merge sort on right chunk + sort(newRightHead); + // Merge the sorted elemnts on right side + Head = mergeSortedLists(newLeftHead, newRightHead); +} + +template +Node* MergeSortLinkedList::mergeSortedLists(Node* leftHead, Node* rightHead) { +#ifdef DEBUG + std::cout << "Merging the array: " << std::endl; +#endif + Node* result = new Node; // dummy node + Node* temp = result; + + while (leftHead != nullptr && rightHead != nullptr) { + if (leftHead->val > rightHead->val) { + // move the right side list elememt to end of result + temp->next = rightHead; + rightHead = rightHead->next; + } + else { + // move the left side list elememt to end of result + temp->next = leftHead; + leftHead = leftHead->next; + } + temp = temp->next; + temp->next = nullptr; + + } + // add rest of the elements + if (leftHead != nullptr) { + // just point to leftover list + temp->next = leftHead; + } + else if (rightHead != nullptr) { + temp->next = rightHead; + } +#ifdef DEBUG + // print the sorted part + std::cout << "--Left sorted: "; + printList(leftHead); + std::cout << "--Right sorted: "; + printList(rightHead); +#endif + // to delete dummy node + rightHead = result->next; + // delete dummy node + delete result; + + return rightHead; +} + +template +MergeSortLinkedList::~MergeSortLinkedList() { + +} diff --git a/Sorting/Merge Sort/C++/Linked Lists/MergeSortLinkedList.h b/Sorting/Merge Sort/C++/Linked Lists/MergeSortLinkedList.h new file mode 100644 index 00000000..b927edb3 --- /dev/null +++ b/Sorting/Merge Sort/C++/Linked Lists/MergeSortLinkedList.h @@ -0,0 +1,39 @@ +#ifndef MERGESORTLINKEDLIST_H +#define MERGESORTLINKEDLIST_H + +// Node of a linked list +template +class Node { +public: + T val; + Node* next; + Node() { + next = nullptr; + } + Node(T value) { + next = nullptr; + val = value; + } +}; + +template +class MergeSortLinkedList { +public: + MergeSortLinkedList(); + T2 getLength(Node* N); + void insertItem(Node*& head, Node* afterNode, T1 item); + void insertItem(Node*& head, T1 afterItem, T1 item); + void insertItemAtEnd(Node*& head, T1 item); + void deleteItemAtEnd(Node*& head); + void deleteItem(Node*& head, T1 item); + void mergeSort(Node*& newList); + ~MergeSortLinkedList(); +private: + void sort(Node*& Head); + Node* mergeSortedLists(Node* leftHead, Node* rightHead); +}; + +// To avoid linker error +#include "MergeSortLinkedList.cpp" + +#endif diff --git a/Sorting/Merge Sort/C++/Linked Lists/MergeSortLinkedListTest.cpp b/Sorting/Merge Sort/C++/Linked Lists/MergeSortLinkedListTest.cpp new file mode 100644 index 00000000..c8b05150 --- /dev/null +++ b/Sorting/Merge Sort/C++/Linked Lists/MergeSortLinkedListTest.cpp @@ -0,0 +1,94 @@ +/********************************************************************************* +* Instructions: +* To compile: g++ MergeSort_LinkedlistTest.cpp -o MergeSort_LinkedlistTest -std=c++11 +* To run: ./MergeSort_LinkedlistTest [#elements] +* Where #elements is number of elements in an array, default is 100. +* Author: Mounika Ponugoti +*********************************************************************************/ +#include +#include +#include +#include +#include +#include "MergeSortLinkedList.h" + +#define NUM_MAX 15 + +// Number of elements in an array +int length = 100; + +// Initialize the list with random values +template +void initializeList(Node*& newList, T2 length) { + // mark head + Node* head = nullptr; + for (T2 i = 0; i < length; i++) { + // new node + Node* N = new Node; + N->val = static_cast (rand()) / static_cast (RAND_MAX / NUM_MAX); + // If the list is empty this is the head + if (newList == nullptr) { + newList = N; + head = newList; + } + else { + newList->next = N; + newList = newList->next; + } + } + newList = head; + head = nullptr; + delete head; +} + +int main(int argc, char **argv) +{ + if (argc == 2) { + length = std::atoi(argv[1]); + } + if (argc > 2) { + std::cout << "Usage: ./main [#elemnts]" << std::endl; + exit(1); + } + // Seed for random number generator + srand(time(NULL)); + // Sorting integer Array + Node *newList = nullptr; + initializeList(newList, length); + std::cout << "Unsorted Array: " << std::endl; + printList (newList); + + MergeSortLinkedList mergeSort_obj; + mergeSort_obj.mergeSort(newList); + std::cout << "Sorted Array: " << std::endl; + printList(newList); + + // Sorting floating point numbers + Node *newList_f = nullptr; + MergeSortLinkedList mergeSort_obj_2; + // Slower, because always go through the entire list to find where to add new element + mergeSort_obj_2.insertItem(newList_f, -2, 150); + mergeSort_obj_2.insertItemAtEnd(newList_f, 10.5); + mergeSort_obj_2.insertItemAtEnd(newList_f, 0.1); + mergeSort_obj_2.insertItemAtEnd(newList_f, 4.5); + mergeSort_obj_2.insertItemAtEnd(newList_f, 2.7); + mergeSort_obj_2.insertItem(newList_f, newList_f->next, 8.9); + mergeSort_obj_2.insertItem(newList_f, 4.5, 12.9); + mergeSort_obj_2.insertItemAtEnd(newList_f, 0.01); + mergeSort_obj_2.insertItem(newList_f, newList_f->next->next->next, -1.9); + mergeSort_obj_2.insertItem(newList_f, 0.01, 100); + +// initializeList(newList_f, length); + std::cout << "Unsorted Array: " << std::endl; + std::cout << std::fixed << std::setprecision(2); + printList(newList_f); + + mergeSort_obj_2.mergeSort(newList_f); + std::cout << "Sorted Array: " << std::endl; + printList(newList_f); + + // Free the allocated memory */ + delete[] newList; + delete[] newList_f; + return 0; +} diff --git a/Sorting/Merge Sort/C++/MergeSortArray.cpp b/Sorting/Merge Sort/C++/MergeSortArray.cpp new file mode 100644 index 00000000..6b329f2b --- /dev/null +++ b/Sorting/Merge Sort/C++/MergeSortArray.cpp @@ -0,0 +1,105 @@ +//Program to perform Merge sort on an array +//A much better sorting algorithm for an array would be quicksort +//For linked lists, merge sort will be much better. +#include +using namespace std; + +void merge(int arr[], int left, int middle, int right) +{ + int n1 = middle - left + 1;//get the number of elements from left to mid + int n2 = right - middle;//get the number of elements from mid to right. + int i,j,k; + + + //creating temporary arrays + int Left[n1], Right[n2]; + //the below loops are made to copy the data into the left + //and right side array + for(i=0;i>n; + int arr[n]; + for(int i=0;i>arr[i]; + } + int startIndex; + int endIndex; + + //the range of startIndex and endIndex should be between + //0 and size_of_array-1 + //including this to sort sub parts of the array + //as well as the entire array if needed based on the + //input given. + + cin>>startIndex;//between 0 and n-1 + cin>>endIndex;//between 0 and n-1 + + mergeSort(arr,startIndex,endIndex); + //after mergesort print the array. Can also print the sorted array from the given startIndex and EndIndex + for(int i=0;i1) + { + int mid=(arr.length)/2; + int sizel=mid; // size for left sub array + int sizer=arr.length-mid; // size for right sub array + int[] larr=new int[sizel]; // left sub array + int[] rarr=new int[sizer]; // right sub array + int t=0; + for (int i=0;i + +using namespace std; + +class QuickSort +{ + /* This function takes last element as pivot, + places the pivot element at its correct + position in sorted array, and places all + smaller (smaller than pivot) to left of + pivot and all greater elements to right + of pivot */ + public: + + int partition(int arr[], int low, int high) + { + int pivot = arr[high]; + int i = (low-1); // index of smaller element + for (int j=low; j Array to be sorted, + low --> Starting index, + high --> Ending index */ + void sort(int arr[], int low, int high) + { + if (low < high) + { + /* pi is partitioning index, arr[pi] is + now at right place */ + int pi = partition(arr, low, high); + + // Recursively sort elements before + // partition and after partition + sort(arr, low, pi-1); + sort(arr, pi+1, high); + } + } +}; + + // Driver program +int main() +{ + int arr[] = {10, 7, 8, 9, 1, 5}; + int n = *(&arr + 1) - arr; + + QuickSort ob; + ob.sort(arr, 0, n-1); + + cout<<"sorted array: "; + for (int i=0; i Array to be sorted, + low --> Starting index, + high --> Ending index */ + void sort(int arr[], int low, int high) + { + if (low < high) + { + /* pi is partitioning index, arr[pi] is + now at right place */ + int pi = partition(arr, low, high); + + // Recursively sort elements before + // partition and after partition + sort(arr, low, pi-1); + sort(arr, pi+1, high); + } + } + + /* A utility function to print array of size n */ + static void printArray(int arr[]) + { + int n = arr.length; + for (int i=0; i +using namespace std; + +// A utility function to get maximum value in arr[] +int getMax(int arr[], int n) +{ + int mx = arr[0]; + for (int i = 1; i < n; i++) + if (arr[i] > mx) + mx = arr[i]; + return mx; +} + +// A function to do counting sort of arr[] according to +// the digit represented by exp. +void countSort(int arr[], int n, int exp) +{ + int output[n]; // output array + int i, count[10] = {0}; + + // Store count of occurrences in count[] + for (i = 0; i < n; i++) + count[ (arr[i]/exp)%10 ]++; + + // Change count[i] so that count[i] now contains actual + // position of this digit in output[] + for (i = 1; i < 10; i++) + count[i] += count[i - 1]; + + // Build the output array + for (i = n - 1; i >= 0; i--) + { + output[count[ (arr[i]/exp)%10 ] - 1] = arr[i]; + count[ (arr[i]/exp)%10 ]--; + } + + // Copy the output array to arr[], so that arr[] now + // contains sorted numbers according to current digit + for (i = 0; i < n; i++) + arr[i] = output[i]; +} + +// The main function to that sorts arr[] of size n using +// Radix Sort +void radixsort(int arr[], int n) +{ + // Find the maximum number to know number of digits + int m = getMax(arr, n); + + // Do counting sort for every digit. Note that instead + // of passing digit number, exp is passed. exp is 10^i + // where i is current digit number + for (int exp = 1; m/exp > 0; exp *= 10) + countSort(arr, n, exp); +} + +// A utility function to print an array +void print(int arr[], int n) +{ + for (int i = 0; i < n; i++) + cout << arr[i] << " "; +} + +// Driver program to test above functions +int main() +{ + int arr[] = {170, 45, 75, 90, 802, 24, 2, 66}; + int n = sizeof(arr)/sizeof(arr[0]); + radixsort(arr, n); + print(arr, n); + return 0; +} diff --git a/Sorting/Selection Sort/Java/SelectionSort.java b/Sorting/Selection Sort/Java/SelectionSort.java new file mode 100644 index 00000000..506ed1d0 --- /dev/null +++ b/Sorting/Selection Sort/Java/SelectionSort.java @@ -0,0 +1,43 @@ +// Java program for implementation of Selection Sort +class SelectionSort +{ + void sort(int arr[]) + { + int n = arr.length; + + // One by one move boundary of unsorted subarray + for (int i = 0; i < n-1; i++) + { + // Find the minimum element in unsorted array + int min_idx = i; + for (int j = i+1; j < n; j++) + if (arr[j] < arr[min_idx]) + min_idx = j; + + // Swap the found minimum element with the first + // element + int temp = arr[min_idx]; + arr[min_idx] = arr[i]; + arr[i] = temp; + } + } + + // Prints the array + void printArray(int arr[]) + { + int n = arr.length; + for (int i=0; i Date: Wed, 3 Oct 2018 20:54:58 +0530 Subject: [PATCH 2/2] Update linkedlist.cpp --- Data Structures/Linked Lists/C++/linkedlist.cpp | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/Data Structures/Linked Lists/C++/linkedlist.cpp b/Data Structures/Linked Lists/C++/linkedlist.cpp index 78e28f8a..91324406 100644 --- a/Data Structures/Linked Lists/C++/linkedlist.cpp +++ b/Data Structures/Linked Lists/C++/linkedlist.cpp @@ -33,7 +33,8 @@ void insertion_after(int y){ student* temp=new student(); temp->data=y; - cout<>l; + cout<>l; FindLocation(); if(loc==NULL){ @@ -93,8 +94,7 @@ int main() { start=NULL; int i,n,x,k,m; - cout<>n; + while(1){ cout<<"select from the following: "<>k; switch(k) { - case 1: cout<<"enter the number:"; + case 1: cout<>n; + cout<<"enter the number:"; for(i=0;i>x; insertion_begin(x); } break; - case 2: cout<<"enter the number:"; + case 2: cout<>n; + cout<<"enter the number:"; for(i=0;i>x; insertion_end(x);