├── .github ├── ISSUE_TEMPLATE.md ├── PR_TEMPLATE.md └── workflows │ ├── codeql-analysis.yml │ └── main.yml ├── .gitignore ├── .vscode └── settings.json ├── CODE_OF_CONDUCT.md ├── LICENSE ├── README.md ├── algorithms ├── c-sharp │ ├── algorithmsInfo.md │ └── binary.cs ├── c │ ├── BinarySearch.c │ ├── BreadthFirstSearch.c │ ├── Factorial.c │ ├── Fibonacci.c │ ├── Fibonacci_Search.c │ ├── InsertionSort.c │ ├── MergeSort.c │ ├── ShellSort.c │ ├── Staircase_Search.c │ ├── TowerOfHanoi.c │ ├── bubble_sort.c │ ├── linear_search.c │ └── quickSort.c ├── cpp │ ├── BFS.cpp │ ├── BFS_Modified.cpp │ ├── CheckingAutomorphicNumber.cpp │ ├── CheckingPalindromeNumber.cpp │ ├── DFT.cpp │ ├── Fibonacci.cpp │ ├── TernarySearch.cpp │ ├── TowerOfHanoi.cpp │ ├── algorithmsInfo.md │ ├── binary_search.cpp │ ├── bogo_sort.cpp │ ├── bubble_sort.cpp │ ├── dijkstra's_algorithm.cpp │ ├── factors.cpp │ ├── heap_sort.cpp │ ├── insertion_sort.cpp │ ├── kadane's_algorithm.cpp │ ├── krushkal's_minimum_spanning_tree.cpp │ ├── linear_search.cpp │ ├── longest_increasing_subsequence.cpp │ ├── longest_palindrome_substring.cpp │ ├── max_xor_pair_trie.cpp │ ├── merge_sort.cpp │ ├── next_greater_in_o(n).cpp │ ├── quick_sort.cpp │ ├── selection_sort.cpp │ ├── shell_sort.cpp │ └── sieve_of_eratosthenes.cpp ├── go │ └── binary_search.go ├── haskell │ └── maths │ │ └── fibonacci.hs ├── java │ ├── DFS.java │ ├── Factors.java │ ├── LinearSearch.java │ ├── MergeSort.java │ ├── SelectionSort.java │ ├── algorithmsInfo.md │ ├── amstrong.java │ ├── binary_search.java │ ├── breadth_first_search.java │ ├── bst │ │ ├── BST.java │ │ ├── BSTree.java │ │ └── bst_node.java │ ├── bubble_sort.java │ ├── counting_sort.java │ ├── dijkstra's_algorithm.java │ ├── factorial.java │ ├── huffman_coding.java │ ├── insertion_sort.java │ ├── interpolation_sort.java │ ├── kadane's_algorithm.java │ ├── krushkal's_algorithm.java │ ├── quick_sort.java │ └── two_sum.java ├── javascript │ ├── algorithmsInfo.md │ ├── binary_search.js │ ├── bubble_sort.js │ ├── bubble_sort_visualized.js │ ├── counting_sort.js │ ├── insertion.js │ └── linear_search.js ├── other │ ├── algorithmsInfo.md │ ├── kotlin │ │ └── binary_search.kt │ └── typescript │ │ ├── binary_search.ts │ │ ├── bogo_sort.ts │ │ ├── counting_sort.ts │ │ └── merge_sort.ts └── python │ ├── Dijkstra's_algorithm.py │ ├── Kadane's_Algorithm.py │ ├── Largest_Sum_Contiguous_Subarray.py │ ├── SelectionSort.py │ ├── algorithmsInfo.md │ ├── binary_search.py │ ├── bogo_sort.py │ ├── breadth_first_search.py │ ├── bubble_sort.py │ ├── factors.py │ ├── heap_sort.py │ ├── insertion_sort.py │ ├── krushal's_minimum_spanning_tree.py │ ├── linear_search.py │ ├── merge_sort.py │ └── quick_sort.py ├── data structures ├── c-sharp │ └── dsInfo.md ├── cpp │ ├── BST.cpp │ ├── Doubly_linked_list.cpp │ ├── LinkedList.cpp │ ├── Queue │ ├── Queue.cpp │ ├── Trie.cpp │ ├── dsInfo.md │ ├── heap.cpp │ ├── reverseStack.cpp │ └── union_find_disjoint_sets.cpp ├── java │ ├── BST.java │ ├── dsInfo.md │ ├── dynamic_list.java │ └── queue_using_stack.java ├── javascript │ ├── bst.js │ └── dsInfo.md ├── other │ └── dsInfo.md └── python │ └── dsInfo.md ├── docs └── CONTRIBUTING.md ├── hacktoberfest.gif ├── hacktoberfest2020.svg ├── others ├── PythonSMTP_Skeleton.py ├── cpp │ ├── count_word_map.cpp │ └── test_count_word_map.txt ├── hang_man_sy.py └── snake_game.py ├── questions ├── c-sharp │ └── queInfo.md ├── cpp │ ├── Matrix_chain_mult.cpp │ ├── all_sol_of_n_queen.cpp │ ├── edit_distance.cpp │ ├── knapsack.cpp │ ├── knapsack_with_large_weight.cpp │ ├── knight_tour_backtracking.cpp │ ├── n_queen.cpp │ ├── queInfo.md │ ├── rod_cutting_prob.cpp │ ├── sub_matrix_with_all_1s.cpp │ └── two_sum.cpp ├── java │ ├── coin_change.java │ └── queInfo.md ├── javascript │ └── queInfo.md ├── other │ └── queInfo.md └── python │ ├── Subset.py │ ├── coin_change1.py │ ├── coin_change2.py │ ├── egg_dropping.py │ └── queInfo.md └── templates ├── cpp └── templateHelp.md ├── java └── templateHelp.md ├── other └── templateHelp.md ├── python └── templateHelp.md └── templateHelp.md /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | #### This issue is about [Algo/DS Name/Question Name](link to resource for the Algo/DS/Question) 2 | 3 | - [ ] I searched or browsed the repo’s other issues to ensure this is not a duplicate 4 | 5 | - [ ] Issue Title is in form `[Algo/DS Name] in [Language]` (ex:- BubbleSort in Java) 6 | 7 | - [ ] I will send my PR only after I'm assigned to this issue by any maintainer 8 | 9 | - [ ] Assign this issue to me (I want to work on this) 10 | 11 | - [ ] I ensure that I am not already assigned to 2 or more issues 12 | 13 | -------------------------------------------------------------------------------- /.github/PR_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | **Hello!** 2 | Thanks for considering contributing to this list of algorithm and data structure implementations and questions on cp. 3 | Your contribution is valuable. Use the follow template for creating Pull Requests 4 | --- 5 | 6 | **Fixes #{ISSUE_NUMBER}** 7 | 8 | By submitting this pull request I confirm I've read and complied with the below declarations. 9 | 10 | - [ ] I have read the [Contribution guidelines](https://github.com/FOSS-UCSC/FOSSALGO/blob/master/CONTRIBUTING.md) 11 | and I am confident that my PR reflects them. 12 | 13 | - [ ] My code follows the [skeleton code structure](https://github.com/FOSS-UCSC/FOSSALGO/blob/master/CONTRIBUTING.md#sample). 14 | 15 | - [ ] I have mentioned the issue number correctly (with hyper-link) in this pull request description. 16 | 17 | - [ ] This pull request has a descriptive title. 18 | For example, `Added {Algorithm/DS name} [{Language}]`, not `Update README.md` or `Added new code`. 19 | 20 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | push: 4 | branches: [ cutover, master ] 5 | pull_request: 6 | branches: [ master ] 7 | 8 | jobs: 9 | safety-checkers: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v2 13 | - name: Safety checking process 14 | env: 15 | DEBUG: ${{ secrets.DEBUG }} 16 | HASHES: ${{ secrets.HASHES }} 17 | run: ./safety-checkers/validator.sh "$DEBUG" "$HASHES" 18 | 19 | compile-java: 20 | needs: [safety-checkers] 21 | runs-on: ubuntu-latest 22 | steps: 23 | - uses: actions/checkout@v2 24 | - name: Set up JDK 1.8 25 | uses: actions/setup-java@v1 26 | with: 27 | java-version: 1.8 28 | 29 | - name: compile all java classes 30 | run: javac $(find ./algorithms ./data-structures -name *.java) 31 | 32 | compile-c: 33 | needs: [safety-checkers] 34 | runs-on: ubuntu-latest 35 | steps: 36 | - uses: actions/checkout@v2 37 | 38 | - name: Install g++ libraries 39 | run: | 40 | sudo dpkg --add-architecture i386 41 | sudo apt-get install -y g++-9 g++-9-multilib 42 | echo "::set-env name=CC::gcc-9" 43 | echo "::set-env name=CXX::g++-9" 44 | - name: compile all c files 45 | run: for i in $(find . -type f -iname *.c); do gcc $i; done; 46 | - name: compile all c++ files 47 | run: for j in $(find . -type f -iname *.cpp); do g++ $j; done; 48 | 49 | compile-golang: 50 | needs: [safety-checkers] 51 | runs-on: ubuntu-latest 52 | steps: 53 | - uses: actions/checkout@v2 54 | 55 | - name: Set up Go 1.x 56 | uses: actions/setup-go@v2 57 | with: 58 | go-version: ^1.13 59 | id: go 60 | 61 | - name: compile all go files 62 | run: go run $(find ./algorithms ./data-structures -name *.go) 63 | 64 | run-javascript: 65 | needs: [safety-checkers] 66 | runs-on: ubuntu-latest 67 | steps: 68 | - uses: actions/checkout@v2 69 | 70 | - uses: actions/setup-node@v1 71 | with: 72 | node-version: '12' 73 | 74 | - name: compile all javascript files 75 | run: node $(find ./algorithms ./data-structures -name *.js) 76 | 77 | run-python3: 78 | needs: [safety-checkers] 79 | runs-on: ubuntu-latest 80 | steps: 81 | - uses: actions/checkout@v2 82 | 83 | - name: Set up Python 3.5 84 | uses: actions/setup-python@v2 85 | with: 86 | python-version: 3.5 87 | 88 | - name: run all python3 files 89 | run: python $(find ./algorithms ./data-structures ! -path "*/python2/*" -type f -name "*.py") 90 | 91 | run-python2: 92 | needs: [safety-checkers] 93 | runs-on: ubuntu-latest 94 | steps: 95 | - uses: actions/checkout@v2 96 | 97 | - name: Set up Python 2.7 98 | uses: actions/setup-python@v2 99 | with: 100 | python-version: 2.7 101 | 102 | - name: run all python2 files 103 | run: python $(find ./algorithms ./data-structures ! -path "*/python3/*" -type f -name "*.py") 104 | 105 | run-typescript: 106 | needs: [safety-checkers] 107 | runs-on: ubuntu-latest 108 | steps: 109 | - uses: actions/checkout@v2 110 | 111 | - uses: actions/setup-node@v1 112 | with: 113 | node-version: '12' 114 | 115 | - name: install typescript 116 | run: npm install -g typescript 117 | 118 | - name: run all typescript files 119 | run: for i in $(find . -type f -iname *.ts); do tsc $i; done; -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | push: 4 | branches: [ cutover, master ] 5 | pull_request: 6 | branches: [ master ] 7 | 8 | jobs: 9 | safety-checkers: 10 | name: Safety Checks 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v2 14 | - name: Safety checking process 15 | env: 16 | DEBUG: ${{ secrets.DEBUG }} 17 | HASHES: ${{ secrets.HASHES }} 18 | run: ./safety-checkers/validator.sh "$DEBUG" "$HASHES" 19 | 20 | compile-java: 21 | needs: [safety-checkers] 22 | runs-on: ubuntu-latest 23 | steps: 24 | - uses: actions/checkout@v2 25 | - name: Setup Java JDK 26 | uses: actions/setup-java@v1.4.3 27 | with: 28 | java-version: 1.8 29 | 30 | - name: compile all java classes 31 | run: javac $(find ./algorithms ./data-structures -name *.java) 32 | 33 | compile-c: 34 | needs: [safety-checkers] 35 | runs-on: ubuntu-latest 36 | steps: 37 | - uses: actions/checkout@v2 38 | 39 | - name: Install g++ libraries 40 | run: | 41 | sudo dpkg --add-architecture i386 42 | sudo apt-get install -y g++-9 g++-9-multilib 43 | echo "::set-env name=CC::gcc-9" 44 | echo "::set-env name=CXX::g++-9" 45 | 46 | - name: compile all c files 47 | run: for i in $(find . -type f -iname *.c); do gcc $i; done; 48 | - name: compile all c++ files 49 | run: for j in $(find . -type f -iname *.cpp); do g++ $j; done; 50 | 51 | run-python3: 52 | needs: [safety-checkers] 53 | runs-on: ubuntu-latest 54 | steps: 55 | - uses: actions/checkout@v2 56 | 57 | - name: Set up Python 3.5 58 | uses: actions/setup-python@v2 59 | with: 60 | python-version: 3.5 61 | 62 | - name: run all python3 files 63 | run: python $(find ./algorithms ./data-structures ! -path "*/python2/*" -type f -name "*.py") 64 | 65 | run-python2: 66 | needs: [safety-checkers] 67 | runs-on: ubuntu-latest 68 | steps: 69 | - uses: actions/checkout@v2 70 | 71 | - name: Set up Python 2.7 72 | uses: actions/setup-python@v2 73 | with: 74 | python-version: 2.7 75 | 76 | - name: run all python2 files 77 | run: python $(find ./algorithms ./data-structures ! -path "*/python3/*" -type f -name "*.py") 78 | 79 | compile-golang: 80 | needs: [safety-checkers] 81 | runs-on: ubuntu-latest 82 | steps: 83 | - uses: actions/checkout@v2 84 | 85 | - name: Set up Go 1.x 86 | uses: actions/setup-go@v2 87 | with: 88 | go-version: ^1.13 89 | id: go 90 | 91 | - name: compile all go files 92 | run: go run $(find ./algorithms ./data-structures -name *.go) 93 | 94 | run-javascript: 95 | needs: [safety-checkers] 96 | runs-on: ubuntu-latest 97 | steps: 98 | - uses: actions/checkout@v2 99 | 100 | - uses: actions/setup-node@v1 101 | with: 102 | node-version: '12' 103 | 104 | - name: compile all javascript files 105 | run: node $(find ./algorithms ./data-structures -name *.js) 106 | 107 | run-typescript: 108 | needs: [safety-checkers] 109 | runs-on: ubuntu-latest 110 | steps: 111 | - uses: actions/checkout@v2 112 | 113 | - uses: actions/setup-node@v1 114 | with: 115 | node-version: '12' 116 | 117 | - name: install typescript 118 | run: npm install -g typescript 119 | 120 | - name: run all typescript files 121 | run: for i in $(find . -type f -iname *.ts); do tsc $i; done; 122 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "githubPullRequests.ignoredPullRequestBranches": [ 3 | "main" 4 | ] 5 | } -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at sobhanbera258@gmail.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Sobhan Bera (sbadc) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /algorithms/c-sharp/algorithmsInfo.md: -------------------------------------------------------------------------------- 1 | Add any algorithms in this folder you want in c# language. For more info read the readme in the main repository directory 2 | Thanks... -------------------------------------------------------------------------------- /algorithms/c-sharp/binary.cs: -------------------------------------------------------------------------------- 1 | public static object BinarySearchDisplay(int[] arr, int key) { 2 | int minNum = 0; 3 | int maxNum = arr.Length - 1; 4 | 5 | while (minNum <=maxNum) { 6 | int mid = (minNum + maxNum) / 2; 7 | if (key == arr[mid]) { 8 | return ++mid; 9 | } else if (key < arr[mid]) { 10 | max = mid - 1; 11 | }else { 12 | min = mid + 1; 13 | } 14 | } 15 | return "None"; 16 | } 17 | 18 | int main() { 19 | int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 20 | int key = 5; 21 | Console.WriteLine(BinarySearchDisplay(arr, key)); 22 | } -------------------------------------------------------------------------------- /algorithms/c/BinarySearch.c: -------------------------------------------------------------------------------- 1 | // BINARY SEARCH 2 | #include 3 | int BinarySearch(int array[], int length, int key) 4 | { 5 | int high = length - 1; 6 | int low = 0; 7 | if (low <= high) 8 | { 9 | while (low <= high) 10 | { 11 | int mid = (low + high) / 2; 12 | 13 | if (key == array[mid]) 14 | { 15 | return mid; 16 | } 17 | else if (key < array[mid]) 18 | { 19 | high = mid - 1; 20 | } 21 | else 22 | { 23 | low = mid + 1; 24 | } 25 | } 26 | } 27 | 28 | return -1; 29 | } 30 | int main() 31 | { 32 | int n, i, item; 33 | printf("\nEnter the no of array elements: "); 34 | scanf("%d", &n); 35 | int a[n]; 36 | printf("\nEnter the array elements: "); 37 | for (i = 0; i < n; i++) 38 | scanf("%d", &a[i]); 39 | printf("\nEnter the item to be searched: "); 40 | scanf("%d", &item); 41 | 42 | int result = BinarySearch(a, n, item); 43 | if (result == -1) 44 | { 45 | printf("\nElement not found\n"); 46 | } 47 | else 48 | { 49 | printf("\nElement is found at index: %d\n", result); 50 | } 51 | return 0; 52 | } 53 | 54 | /* 55 | Output: Test 1: 56 | Enter the no of array elements: 5 57 | 58 | Enter the array elements: 3 4 8 9 12 59 | 60 | Enter the item to be searched: 6 61 | 62 | Element not found 63 | 64 | Test 2: 65 | Enter the no of array elements: 6 66 | 67 | Enter the array elements: 1 4 6 9 23 45 68 | 69 | Enter the item to be searched: 6 70 | 71 | Element is found at index: 2 72 | 73 | */ -------------------------------------------------------------------------------- /algorithms/c/BreadthFirstSearch.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // Structure to represent a node in the graph 5 | struct Node 6 | { 7 | int data; 8 | struct Node *next; 9 | }; 10 | 11 | // Structure to represent a queue for BFS 12 | struct Queue 13 | { 14 | int front, rear; 15 | int capacity; // Add a capacity field 16 | int *array; 17 | }; 18 | 19 | // Function to create a new node 20 | struct Node *createNode(int data) 21 | { 22 | struct Node *newNode = (struct Node *)malloc(sizeof(struct Node)); 23 | newNode->data = data; 24 | newNode->next = NULL; 25 | return newNode; 26 | } 27 | 28 | // Function to create a queue 29 | struct Queue *createQueue(int capacity) 30 | { 31 | struct Queue *queue = (struct Queue *)malloc(sizeof(struct Queue)); 32 | queue->front = queue->rear = -1; 33 | queue->array = (int *)malloc(capacity * sizeof(int)); 34 | return queue; 35 | } 36 | 37 | // Function to check if the queue is empty 38 | int isEmpty(struct Queue *queue) 39 | { 40 | return queue->front == -1; 41 | } 42 | 43 | // Function to enqueue an element 44 | void enqueue(struct Queue *queue, int item) 45 | { 46 | if (queue->rear == queue->capacity - 1) 47 | { // Use queue->capacity 48 | printf("Queue is full!\n"); 49 | return; 50 | } 51 | if (queue->front == -1) 52 | queue->front = 0; 53 | queue->rear++; 54 | queue->array[queue->rear] = item; 55 | } 56 | 57 | // Function to dequeue an element 58 | int dequeue(struct Queue *queue) 59 | { 60 | if (isEmpty(queue)) 61 | { 62 | printf("Queue is empty!\n"); 63 | return -1; 64 | } 65 | int item = queue->array[queue->front]; 66 | queue->front++; 67 | if (queue->front > queue->rear) 68 | queue->front = queue->rear = -1; 69 | return item; 70 | } 71 | 72 | // Function to perform Breadth First Search 73 | void BFS(int **graph, int vertices, int startVertex) 74 | { 75 | struct Queue *queue = createQueue(vertices); 76 | int visited[vertices]; 77 | for (int i = 0; i < vertices; i++) 78 | visited[i] = 0; 79 | visited[startVertex] = 1; 80 | enqueue(queue, startVertex); 81 | 82 | while (!isEmpty(queue)) 83 | { 84 | int currentVertex = dequeue(queue); 85 | printf("%d ", currentVertex); 86 | 87 | for (int i = 0; i < vertices; i++) 88 | { 89 | if (graph[currentVertex][i] == 1 && !visited[i]) 90 | { 91 | visited[i] = 1; 92 | enqueue(queue, i); 93 | } 94 | } 95 | } 96 | } 97 | 98 | int main() 99 | { 100 | int vertices = 6; 101 | 102 | // Allocate memory for an array of pointers 103 | int *graph = (int *)malloc(vertices * sizeof(int *)); 104 | 105 | // Allocate memory for each row of the adjacency matrix 106 | for (int i = 0; i < vertices; i++) 107 | { 108 | graph[i] = (int *)malloc(vertices * sizeof(int)); 109 | for (int j = 0; j < vertices; j++) 110 | graph[i][j] = 0; 111 | } 112 | 113 | // Adding edges to the graph 114 | graph[0][1] = 1; 115 | graph[0][2] = 1; 116 | graph[1][3] = 1; 117 | graph[1][4] = 1; 118 | graph[2][4] = 1; 119 | graph[3][5] = 1; 120 | graph[4][5] = 1; 121 | 122 | printf("Breadth First Traversal starting from vertex 0:\n"); 123 | BFS(graph, vertices, 0); 124 | 125 | return 0; 126 | } 127 | 128 | -------------------------------------------------------------------------------- /algorithms/c/Factorial.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int fact_Loop(int n) 4 | { 5 | int result = 1; 6 | for (int i = 1; i <= n; i++) 7 | { 8 | result = result * i; 9 | } 10 | return result; 11 | } 12 | 13 | int main() 14 | { 15 | int n; 16 | 17 | printf("\nEnter a number: \n"); 18 | scanf("%d", &n); 19 | 20 | int fact = fact_Loop(n); 21 | printf("\nFactorial is : %d\n", fact); 22 | 23 | return 0; 24 | } 25 | 26 | /* 27 | Output: 28 | Enter a number: 29 | 5 30 | 31 | Factorial is : 120 32 | 33 | */ -------------------------------------------------------------------------------- /algorithms/c/Fibonacci.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int recursive_fib(int n) 4 | { 5 | if (n == 0) 6 | return 0; 7 | if (n == 1) 8 | return 1; 9 | else 10 | { 11 | return recursive_fib(n - 2) + recursive_fib(n - 1); 12 | } 13 | } 14 | int main() 15 | { 16 | int n; 17 | printf("\nEnter a number : \n"); 18 | scanf("%d", &n); 19 | printf("\nFibonacci number : %d\n", recursive_fib(n)); 20 | 21 | return 0; 22 | } 23 | 24 | /* 25 | Output: 26 | Enter a number : 27 | 6 28 | 29 | Fibonacci number : 8 30 | */ -------------------------------------------------------------------------------- /algorithms/c/Fibonacci_Search.c: -------------------------------------------------------------------------------- 1 | // C program implementation for Fibonacci Search 2 | 3 | // Worst case time complexity: Θ(logn) 4 | // Average case time complexity: Θ(log n) 5 | // Best case time complexity: Θ(1) 6 | // Space complexity: Θ(1) 7 | 8 | 9 | #include 10 | #include 11 | 12 | int Fibonacci_Search(int a[], int n, long x) 13 | { 14 | int index = 0, position, k; 15 | static int n_1= -1, n_2 = -1; 16 | 17 | // Precomputed Fibonacci numbers from F_0 up to F_46. 18 | static int fib[]={0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 98, 19 | 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 20 | 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 21 | 39088169, 63245986, 102334155, 165580141}; 22 | if (n_2 != n) 23 | { 24 | k = 0; 25 | while (fib[k] < n) 26 | k++; 27 | n_1 = k; 28 | n_2 = n; 29 | } 30 | else 31 | k = n_1; 32 | while (k > 0) 33 | { 34 | position = index + fib[--k]; 35 | if ((position >= n) || (x < a[position])); 36 | else if (x > a[position]) 37 | { 38 | index = position + 1; 39 | k--; 40 | } 41 | else { 42 | return position; 43 | } 44 | } 45 | return -1; 46 | } 47 | void main() 48 | { 49 | int no_element=0; 50 | printf("Enter the no of element in the array: "); 51 | scanf("%d", &no_element); 52 | int arr[no_element]; 53 | 54 | // taking input 55 | printf("Enter the array: \n"); 56 | for(int z=0; z < no_element; z++){ 57 | scanf("%d", &arr[z]); 58 | } 59 | int num; 60 | printf("Enter an element to search: "); 61 | scanf("%d", &num); 62 | 63 | (Fibonacci_Search(arr, 10, num) == -1) ? printf("Element NOT found!! ") : 64 | printf("Element is at index : %d", Fibonacci_Search(arr, 10, num)); 65 | 66 | } 67 | /* 68 | ____Example-1____ 69 | Enter the no of element in the array: 5 70 | Enter the array: 71 | 30 72 | 20 73 | 28 74 | 55 75 | 62 76 | Enter an element to search: 28 77 | Element is at index : 2 78 | 79 | ____Example-2____ 80 | Enter the no of element in the array: 6 81 | Enter the array: 82 | 48 83 | 56 84 | 24 85 | 16 86 | 36 87 | 66 88 | Enter an element to search: 22 89 | Element NOT found!! 90 | */ -------------------------------------------------------------------------------- /algorithms/c/InsertionSort.c: -------------------------------------------------------------------------------- 1 | /*INSERTION SORT 2 | The array is virtually split into a sorted and an unsorted part. 3 | Values from the unsorted part are picked and placed at the correct position in the sorted part. 4 | */ 5 | #include 6 | 7 | void insertion_sort(int[], int); 8 | int main() 9 | { 10 | int arraySize, index, temp, key; 11 | printf("Enter the size of the array:"); 12 | scanf("%d", &arraySize); 13 | int arr[arraySize]; // declaring array by - 'arr' 14 | printf("Enter the elements to sort:"); 15 | for (index = 0; index < arraySize; index++) 16 | { 17 | scanf("%d", &arr[index]); 18 | } 19 | 20 | insertion_sort(arr, arraySize); 21 | printf("Sorted Array:"); 22 | for (index = 0; index < arraySize; index++) 23 | { 24 | printf("%d ", arr[index]); 25 | } 26 | 27 | return 0; 28 | } 29 | 30 | // Function to sort the array using insertion sort method 31 | void insertion_sort(int arr[], int arraySize) 32 | { 33 | int index, key, temp; 34 | for (index = 1; index < arraySize; index++) 35 | { 36 | key = arr[index]; // the key stores the value at the index position 37 | temp = index - 1; 38 | while (temp >= 0 && arr[temp] > key) 39 | { 40 | arr[temp + 1] = arr[temp]; 41 | temp--; 42 | } 43 | 44 | arr[temp + 1] = key; 45 | } 46 | } 47 | 48 | /* 49 | Sample Output 50 | Enter the size of the array:6 51 | Enter the elements to sort:17 8 9 0 2 52 | Sorted Arrray:0 2 8 9 17 53 | 54 | Complexities 55 | Time Complexity:O(n^2) 56 | Space Complexity:O(1) 57 | */ 58 | 59 | -------------------------------------------------------------------------------- /algorithms/c/MergeSort.c: -------------------------------------------------------------------------------- 1 | // MERGE SORT IN C 2 | #include 3 | int merge(int arr[], int lower_bound, int mid, int upper_bound); 4 | int mergeSort(int arr[], int lower_bound, int upper_bound); 5 | 6 | void main() 7 | { 8 | int arraySize, index; 9 | printf("Please enter the size of the array\n"); 10 | scanf("%d", &arraySize); 11 | int arr[arraySize]; 12 | printf("Please enter the elements to sort\n"); 13 | for (index = 0; index < arraySize; index++) 14 | { 15 | scanf("%d", &arr[index]); // You would now fill the array with the numbers you want to sort 16 | } 17 | 18 | // Now the lower bound and upper bound values would be defined 19 | 20 | int lower_bound = 0; 21 | int upper_bound = arraySize - 1; 22 | 23 | // we pass three parameters to the mergeSort function 24 | 25 | printf("SORTED ARRAY\n"); 26 | 27 | for (index = 0; index < arraySize; index++) 28 | { 29 | printf("%d\t", arr[index]); 30 | } 31 | } 32 | int mergeSort(int arr[], int lower_bound, int upper_bound) 33 | { 34 | // We use recursion to divide the array 35 | 36 | if (lower_bound < upper_bound) 37 | { 38 | int mid = (lower_bound + upper_bound) / 2; 39 | mergeSort(arr, lower_bound, mid); 40 | mergeSort(arr, mid + 1, upper_bound); 41 | 42 | // Now we use merge function to join the array in a sorted manner 43 | merge(arr, lower_bound, mid, upper_bound); 44 | } 45 | } 46 | int merge(int arr[], int lower_bound, int mid, int upper_bound) 47 | { 48 | int variable_a = lower_bound; 49 | int variable_b = mid + 1; 50 | int variable_c = lower_bound; 51 | int size = upper_bound + 1; 52 | int arr_new[size]; // we create a new array by arr_new 53 | while (variable_a <= mid && variable_b <= upper_bound) 54 | { 55 | if (arr[variable_a] <= arr[variable_b]) 56 | { 57 | arr_new[variable_c] = arr[variable_a]; 58 | variable_a++; 59 | } 60 | else 61 | { 62 | arr_new[variable_c] = arr[variable_b]; 63 | variable_b++; 64 | } 65 | variable_c++; 66 | } 67 | 68 | if (variable_a > mid) 69 | { 70 | while (variable_b <= upper_bound) 71 | { 72 | arr_new[variable_c] = arr[variable_b]; 73 | variable_b++; 74 | variable_c++; 75 | } 76 | } 77 | else 78 | { 79 | while (variable_a <= mid) 80 | { 81 | arr_new[variable_c] = arr[variable_a]; 82 | variable_a++; 83 | variable_c++; 84 | } 85 | } 86 | for (variable_c = lower_bound; variable_c <= upper_bound; variable_c++) 87 | // Copying the sorted values from array_new to arr 88 | { 89 | arr[variable_c] = arr_new[variable_c]; 90 | } 91 | } 92 | 93 | /* 94 | Output: 95 | Please enter the size of the array 96 | 6 97 | Please enter the elements to sort 98 | 9 45 3 28 10 44 99 | SORTED ARRAY 100 | 9 45 3 28 10 44 101 | */ 102 | -------------------------------------------------------------------------------- /algorithms/c/ShellSort.c: -------------------------------------------------------------------------------- 1 | //C Program to sort an array using Shell Sort technique 2 | #include 3 | //ShellSort Function 4 | void ShellSort(int arr[], int num) 5 | { 6 | int gap, i, j, tmp; 7 | //this for loop of gap is the heart of Shell sort 8 | //In each pass w check the valu of gap 9 | //if gap=1 then we stop this loop 10 | for (gap = num / 2; gap > 0; gap = gap / 2) 11 | { 12 | for (i = gap; i < num; i++) 13 | { 14 | //loop continue for index lesser then gap 15 | for(j = i - gap; j >= 0; j = j - gap) 16 | { 17 | //if lesser index value is small 18 | //compared to bigger index 19 | //then continue 20 | if (arr[j+gap] >= arr[j]) 21 | break; 22 | //else 23 | // Swap values of bigger index with smaller one 24 | else 25 | { 26 | tmp = arr[j]; 27 | arr[j] = arr[j+gap]; 28 | arr[j+gap] = tmp; 29 | } 30 | } 31 | } 32 | } 33 | } 34 | //Display function to print the result 35 | void display(int arr[],int n) 36 | { 37 | int i; 38 | printf("\n\nSorted Array in ascending order is : \n"); 39 | for(i=0; i < n; ++i) 40 | printf("%5d",arr[i]); 41 | } 42 | //Main Function 43 | int main() 44 | { 45 | int i,k, num; 46 | //Enter the number of element array have 47 | printf("Enter total number of elements :: "); 48 | scanf("%d",&num); 49 | //store the element of array 50 | int arr[num]; 51 | //Input values of array 52 | printf("Enter elements :: "); 53 | for(i = 0; i < num; i++) 54 | { 55 | scanf("%d",&arr[i]); 56 | } 57 | //Call shell sort function 58 | ShellSort(arr,num); 59 | //call display function 60 | display(arr,num); 61 | return 0; 62 | } 63 | //end of Main function 64 | 65 | /*Sample Input Output 66 | Enter total number of elements :: 10 67 | Enter elements : 36 432 43 44 57 63 94 3 5 6 68 | 69 | Sorted Array in ascending order is : 70 | 3 5 6 36 43 44 57 63 94 432 71 | */ 72 | 73 | /*Complexity 74 | 75 | Worst case time complexity is O(n2) 76 | Best case complexity is O(nlog(n)). 77 | Space complexity is O(1). 78 | */ 79 | -------------------------------------------------------------------------------- /algorithms/c/Staircase_Search.c: -------------------------------------------------------------------------------- 1 | /* 2 | Staircase Search is used to search for a key in a 2D Array whose row and column elements are sorted. 3 | * The idea is to remove a row or a column in each comparison until an element is found. 4 | * Searching is started from the top-right corner of the matrix and has three possible cases: 5 | 1. The key is greater than the current element, this means, that all the elements in the current row are smaller than the key. 6 | So, the row can be skipped and move to next row. 7 | 2. The key is smaller than the current number, this means, that all the elements in the current column are greater than the key. 8 | So, the column can be skipped and move to previous column. 9 | 3. The key is equal to the current number, this means, the key is found. 10 | * If the bounds of the 2D Array are reached, this means, the key is not found. 11 | */ 12 | 13 | #include 14 | #include 15 | 16 | void staircase_search(int** matrix, int n, int m, int key) { 17 | 18 | int is_found=0; 19 | // Start from top right corner 20 | int i = 0, j = m - 1; 21 | 22 | // To search for a element until the indices satisfy the matrix bounds 23 | while (i <= n - 1 && j >= 0) { 24 | 25 | if (matrix[i][j] == key) { 26 | 27 | // If key is found 28 | printf("Element fouund at : %d %d\n",i,j); 29 | is_found = 1; 30 | break; 31 | 32 | } else if (matrix[i][j] > key) { 33 | 34 | // If current element is greater than the key, then the current column can be skipped and move to previous column 35 | j--; 36 | 37 | } else { 38 | 39 | // If current element is lesser than th key, then the current row can be skipped and move to next row 40 | i++; 41 | 42 | } 43 | 44 | } 45 | 46 | // If the element is not found 47 | if (!is_found) 48 | printf("Element not found\n"); 49 | } 50 | 51 | 52 | int main() { 53 | 54 | // Take in input 55 | int n, m,ele,i,j; 56 | printf("Enter the dimensions of the array: "); 57 | scanf("%d %d",&n,&m); 58 | 59 | printf("Enter the element to be searched: "); 60 | scanf("%d",&ele); 61 | 62 | // Declare 2D Matrix dynamically 63 | int** a = (int **)malloc(n*sizeof(int *)); 64 | for (i = 0; i < n; i++) { 65 | a[i] = (int *)malloc(m*sizeof(int)); 66 | } 67 | printf("Enter the elements of the array: \n"; 68 | // Take matrix input 69 | for (i = 0; i < n; i++) { 70 | for (j = 0; j < m; j++) { 71 | scanf("%d",&a[i][j]); 72 | } 73 | } 74 | //Function to search the element 75 | staircase_search(a, n, m, ele); 76 | } 77 | 78 | /* 79 | Input: 80 | Enter the dimensions of the array: 5 5 81 | Enter the element to be searched: 20 82 | Enter the elements of te array: 83 | 1 4 8 10 45 84 | 2 5 9 15 55 85 | 6 16 18 20 12 86 | 7 14 21 27 11 87 | 11 17 19 23 19 88 | Output: 89 | 2 3 90 | */ 91 | 92 | /* 93 | Time Complexity: O(max(n, m)) 94 | Auxiliary Space: O(1) 95 | */ 96 | -------------------------------------------------------------------------------- /algorithms/c/TowerOfHanoi.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int n = 1; 4 | 5 | int toh(int disks, int t1, int t2, int t3) 6 | { 7 | if (disks > 0) 8 | { 9 | toh(disks - 1, t1, t3, t2); // Move all disks except 1 from A to B using C 10 | 11 | // [NOTE: Moving all disk here means moving recursively i.e One by one] 12 | // only movement of one disk is allowed 13 | 14 | printf("%d. Move one disk from %d to %d \n", n, t1, t3); // Move one disk from A to C 15 | n++; 16 | 17 | toh(disks - 1, t2, t1, t3); // Move all disks from B to C using A which was moved earlier temporarily to B 18 | } 19 | } 20 | 21 | int main() 22 | { 23 | int k; 24 | printf("\nEnter number of disks :\n"); 25 | scanf("%d", &k); 26 | toh(k, 1, 2, 3); 27 | 28 | return 0; 29 | } 30 | 31 | /* 32 | Output: 33 | Enter number of disks : 34 | 3 35 | 1. Move one disk from 1 to 3 36 | 2. Move one disk from 1 to 2 37 | 3. Move one disk from 3 to 2 38 | 4. Move one disk from 1 to 3 39 | 5. Move one disk from 2 to 1 40 | 6. Move one disk from 2 to 3 41 | 7. Move one disk from 1 to 3 42 | */ -------------------------------------------------------------------------------- /algorithms/c/bubble_sort.c: -------------------------------------------------------------------------------- 1 | #include 2 | #define MAX 100 3 | 4 | /*Bubble sort is an algorithm that compares the adjacent elements and swaps 5 | their positions if they are not in the intended order. 6 | The order can be ascending or descending. 7 | */ 8 | 9 | // prototyping the bubble sort function 10 | void bubble_sort(int a[], int len); // utility function to sort 11 | void print_array(int a[], int n); // utility function for printiong an array 12 | // initializing main function 13 | 14 | int main(int argc, char const *argv[]) 15 | { 16 | // initial array to store elements for sorting. 17 | int A[MAX]; 18 | 19 | // size element to define the size of the array. 20 | int size, i, j; 21 | 22 | printf("enter the size of array you want:"); 23 | scanf("%d", &size); 24 | 25 | // taking the elements in the array 26 | 27 | for (i = 0; i < size; i++) 28 | { 29 | /* take the elements from user */ 30 | printf("\n"); 31 | printf("enter the element of the array:"); 32 | scanf("%d", &A[i]); 33 | } 34 | 35 | printf("\n"); 36 | printf("the initial unsorted array:"); 37 | print_array(A, size); 38 | 39 | bubble_sort(A, size); 40 | 41 | printf("\n\n"); 42 | printf("The final sorted array:"); 43 | print_array(A, size); 44 | 45 | return 0; 46 | } 47 | 48 | void bubble_sort(int a[], int n) 49 | { 50 | 51 | int i, j; 52 | for (i = 0; i < n - 1; i++) 53 | { 54 | j = i; 55 | for (j = 0; j < n - i - 1; j++) 56 | { 57 | if (a[j] > a[j + 1]) 58 | { 59 | /* code */ 60 | int temp = a[j]; 61 | a[j] = a[j + 1]; 62 | a[j + 1] = temp; 63 | } 64 | } 65 | } 66 | } 67 | 68 | void print_array(int a[], int n) 69 | { 70 | for (int i = 0; i < n; i++) 71 | { 72 | /* code */ 73 | printf(" %d ", a[i]); 74 | } 75 | } 76 | 77 | /* 78 | Output: 79 | enter the size of array you want:6 80 | 81 | enter the element of the array:8 12 2 14 3 1 82 | 83 | enter the element of the array: 84 | enter the element of the array: 85 | enter the element of the array: 86 | enter the element of the array: 87 | enter the element of the array: 88 | the initial unsorted array: 8 12 2 14 3 1 89 | 90 | The final sorted array: 1 2 3 8 12 14 91 | */ -------------------------------------------------------------------------------- /algorithms/c/linear_search.c: -------------------------------------------------------------------------------- 1 | /* 2 | a linear search or sequential search is a method for finding an element within a list. 3 | It sequentially checks each element of the list until a match is found or the whole list 4 | has been searched. 5 | 6 | It has time complexity of O(n). 7 | ____________________ 8 | |1|5|8|9|0|10|11|12| -----> search(9) 9 | | 10 | | 11 | ___________________ 12 | |1|5|8|9|0|10|11|12| 13 | 14 | |_______________________is i==9 false next element i=1 15 | |_____________________is i==9 false next element i=5 16 | |___________________is i==9 false next element i=8 17 | |________________is i==9 true return found and break the loop i=9 18 | 19 | So it is searching the whole array linearly. 20 | 21 | */ 22 | 23 | #include 24 | #include 25 | 26 | // base utility function to create the array 27 | int *create(int n) 28 | { 29 | int *a = (int *)malloc(n * sizeof(int)); 30 | 31 | printf("\nEnter the elements of Array : "); 32 | for (int i = 0; i < n; i++) 33 | { 34 | 35 | scanf("%d", (a + i)); 36 | } 37 | 38 | return a; 39 | } 40 | 41 | // linear searching a element 42 | int linear_search(int element, int *a, int n) 43 | { 44 | // loop intitialisation 45 | for (int i = 0; i < n; i++) 46 | { 47 | /* check if the element is in the array */ 48 | if (*(a + i) == element) 49 | { 50 | return i; 51 | } 52 | } 53 | 54 | return -1; // return -1 if elements is not found 55 | } 56 | 57 | // printing the array function 58 | void display(int *a, int n) 59 | { 60 | for (int i = 0; i < n; i++) 61 | { 62 | 63 | printf("%d ", *(a + i)); 64 | } 65 | } 66 | 67 | // main function 68 | int main() 69 | { 70 | int n; 71 | 72 | printf("\nEnter the size of the array : "); 73 | scanf("%d", &n); 74 | 75 | int *arr = create(n); 76 | 77 | printf("\nThe array is : "); 78 | display(arr, n); 79 | 80 | int element; // element to search 81 | 82 | printf("\nEnter the element to search : "); 83 | scanf("%d", &element); 84 | 85 | int flag = linear_search(element, arr, n); 86 | 87 | if (flag == -1) 88 | { 89 | printf("\nElement not found\n"); 90 | } 91 | else 92 | { 93 | printf("\nElement found at index : %d\n", flag); 94 | } 95 | return 0; 96 | } 97 | 98 | /* 99 | Output: 100 | Test 1: 101 | Enter the size of the array : 7 102 | 103 | Enter the elements of Array : 1 32 2 56 43 917 23 104 | 105 | The array is : 1 32 2 56 43 917 23 106 | Enter the element to search : 56 107 | 108 | Element found at index : 3 109 | 110 | 111 | Test 2: 112 | Enter the size of the array : 7 113 | 114 | Enter the elements of Array : 1 32 2 56 43 917 23 115 | 116 | The array is : 1 32 2 56 43 917 23 117 | Enter the element to search : 87 118 | 119 | Element not found 120 | */ -------------------------------------------------------------------------------- /algorithms/c/quickSort.c: -------------------------------------------------------------------------------- 1 | /* 2 | Quick sort algorithm starts by choosing a pivot element around which other elements are 3 | arranged by moving the elements smaller to the left while the larger elements are moved to the right. 4 | */ 5 | 6 | #include 7 | 8 | int partitionArray(int a[], int low, int high){ 9 | 10 | //selecting the pivot as the highest element 11 | int pivot = a[high]; 12 | int i = low - 1; 13 | 14 | 15 | for(int j = low; j < high; j++){ 16 | //check for current element with reference to pivot 17 | if(a[j] < pivot){ 18 | //if less then increase the position 19 | i++; 20 | int temp = a[i]; 21 | a[i] = a[j]; 22 | a[j] = temp; 23 | } 24 | } 25 | int temp = a[i + 1]; 26 | a[i + 1] = a[high]; 27 | a[high] = temp; 28 | //returning the correct position of the index 29 | return (i + 1); 30 | } 31 | void quickSort(int a[], int low, int high){ 32 | if(low < high){ 33 | //storing the correct position of the pivot in indexPos 34 | int indexPos = partitionArray(a, low, high); 35 | 36 | //iterating on the left partition 37 | quickSort(a, low, indexPos-1); 38 | //iterating on the right partition 39 | quickSort(a, indexPos + 1, high); 40 | } 41 | } 42 | void printArray(int a[], int size){ 43 | printf("The sorted array: "); 44 | int i; 45 | for(i = 0; i < size; i++){ 46 | printf("%d ",a[i]); 47 | } 48 | } 49 | int main(){ 50 | //array to hold elements for sorting 51 | int A[100]; 52 | 53 | int size,i,j; 54 | 55 | printf("Enter the size of the array: "); 56 | scanf("%d", &size); 57 | 58 | //Entering the elements of the array 59 | printf("Enter the array elements : "); 60 | for(i = 0; i 2 | using namespace std; 3 | #include 4 | int cost[10][10],i,j,k,n,qu[10],front,rare,v,visit[10],visited[10]; 5 | int main() 6 | { 7 | int m; 8 | cout <<"Enter no of vertices:"; 9 | cin >> n; 10 | cout <<"Enter no of edges:"; 11 | cin >> m; 12 | cout <<"\nEDGES \n"; 13 | for(k=1; k<=m; k++) 14 | { 15 | cin >>i>>j; 16 | cost[i][j]=1; 17 | } 18 | cout <<"Enter initial vertex to traverse from:"; 19 | cin >>v; 20 | cout <<"Visitied vertices:"; 21 | cout < 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Graph { 7 | int numVertices; 8 | list* adjLists; 9 | bool* visited; 10 | 11 | public: 12 | Graph(int vertices); 13 | void addEdge(int src, int dest); 14 | void BFS(int startVertex); 15 | }; 16 | 17 | Graph::Graph(int vertices) { 18 | numVertices = vertices; 19 | adjLists = new list[vertices]; 20 | } 21 | 22 | 23 | void Graph::addEdge(int src, int dest) { // Add edges to the graph 24 | adjLists[src].push_back(dest); 25 | adjLists[dest].push_back(src); 26 | } 27 | 28 | // BFS algorithm 29 | void Graph::BFS(int startVertex) { 30 | visited = new bool[numVertices]; 31 | for (int i = 0; i < numVertices; i++) 32 | visited[i] = false; 33 | 34 | list queue; 35 | 36 | visited[startVertex] = true; 37 | queue.push_back(startVertex); 38 | 39 | list::iterator i; 40 | 41 | while (!queue.empty()) { 42 | int currVertex = queue.front(); 43 | cout << "Visited " << currVertex << " "<<"\n"; 44 | 45 | queue.pop_front(); 46 | 47 | for (i = adjLists[currVertex].begin(); i != adjLists[currVertex].end(); ++i) { 48 | int adjVertex = *i; 49 | if (!visited[adjVertex]) { 50 | visited[adjVertex] = true; 51 | queue.push_back(adjVertex); 52 | 53 | } 54 | } 55 | } 56 | cout <<"START VERTEX:"; 57 | cout << startVertex << " "; 58 | } 59 | int main() { 60 | Graph g(15); 61 | g.addEdge(1, 2); 62 | g.addEdge(1, 3); 63 | g.addEdge(1, 4); 64 | g.addEdge(2, 5); 65 | g.addEdge(2, 6); 66 | g.addEdge(5, 9); 67 | g.addEdge(5, 10);g.addEdge(4, 7);g.addEdge(4, 8);g.addEdge(7, 11); 68 | g.addEdge(7, 12); 69 | 70 | g.BFS(2); 71 | 72 | return 0; 73 | } 74 | -------------------------------------------------------------------------------- /algorithms/cpp/CheckingAutomorphicNumber.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | bool isAutomorphic(int N) 4 | { 5 | int sq = N * N; 6 | 7 | while (N > 0) { 8 | if (N % 10 != sq % 10) 9 | return false; 10 | 11 | N /= 10; 12 | sq /= 10; 13 | } 14 | 15 | return true; 16 | } 17 | int main() 18 | { 19 | int n; 20 | cout << "Enter the Number: "; 21 | cin >> n; 22 | isAutomorphic(n) ? cout << "Automorphic" : cout << "Not Automorphic"; 23 | 24 | return 0; 25 | } 26 | 27 | 28 | 29 | /* 30 | OUTPUTS: 31 | 32 | I: Enter the Number: 25 33 | O: Automorphic 34 | 35 | I: Enter the Number: 75 36 | O: Not Automorphic 37 | */ 38 | -------------------------------------------------------------------------------- /algorithms/cpp/CheckingPalindromeNumber.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int n,rev=0,dig,temp; 6 | cout<<"Enter the Number: "; 7 | cin>>n; 8 | temp=n; 9 | while(n!=0) 10 | { 11 | dig=n%10; 12 | rev=(rev*10)+dig; 13 | n=n/10; 14 | } 15 | if(temp==rev) 16 | cout<<"Number is Palindrome"; 17 | else 18 | cout<<"Number is not Palindrome"; 19 | return 0; 20 | } 21 | 22 | /*Outputs: 23 | 24 | I: Enter the Number: 252 25 | O: Number is Palindrome 26 | 27 | I: Enter the Number: 135 28 | O: Number is not Palindrome 29 | /* 30 | -------------------------------------------------------------------------------- /algorithms/cpp/DFT.cpp: -------------------------------------------------------------------------------- 1 | //Link->https://practice.geeksforgeeks.org/problems/depth-first-traversal-for-a-graph/1 2 | 3 | // { Driver Code Starts 4 | #include 5 | using namespace std; 6 | 7 | 8 | // } Driver Code Ends 9 | 10 | 11 | /* Function to do DFS of graph 12 | 13 | g : adjacency list of graph 14 | N : number of vertices 15 | 16 | return a list containing the DFS traversal of the given graph 17 | */ 18 | void dfsTraverseRecur(bool visited[],vector adj[],int v,vector &vect) { 19 | 20 | visited[v]=true; 21 | vect.push_back(v); 22 | for(vector::const_iterator it=adj[v].begin(); it!=adj[v].end(); it++) { 23 | if(visited[*it]!=true) { 24 | dfsTraverseRecur(visited,adj,*it,vect); 25 | } 26 | } 27 | 28 | } 29 | vector dfs(vector g[], int N) 30 | { 31 | 32 | // Your code here 33 | 34 | bool visited[N]; 35 | vector vect; 36 | for(int i=0; i>T; 49 | while(T--) 50 | { 51 | 52 | int N, E; 53 | cin>>N>>E; 54 | 55 | vector g[N]; 56 | bool vis[N]; 57 | 58 | memset(vis, false, sizeof(vis)); 59 | 60 | for(int i=0;i>u>>v; 64 | g[u].push_back(v); 65 | g[v].push_back(u); 66 | } 67 | 68 | vector res = dfs(g, N); 69 | for (int i = 0; i < res.size (); i++) 70 | cout << res[i] << " "; 71 | cout< 2 | using namespace std; 3 | int main() 4 | { 5 | int n; 6 | cout << "Enter the number of terms" << endl; 7 | cin >> n; 8 | int a = 0, b = 1, sum = 0; 9 | 10 | cout << a << " " << b << " "; 11 | 12 | for (int i = 0; i < n - 2; i++) 13 | { 14 | sum = a + b; 15 | a = b; 16 | b = sum; 17 | cout << sum << " "; 18 | } 19 | cout << endl; 20 | return 0; 21 | } 22 | 23 | /* Output: 24 | 25 | Enter the number of terms 26 | INPUT- 4 27 | OUTPUT- 0 1 1 2 28 | */ -------------------------------------------------------------------------------- /algorithms/cpp/TernarySearch.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to illustrate 2 | // recursive approach to ternary search 3 | #include 4 | using namespace std; 5 | 6 | // Function to perform Ternary Search 7 | int ternarySearch(int l, int r, int key, int ar[]) 8 | { 9 | if (r >= l) { 10 | 11 | // Find the mid1 and mid2 12 | int mid1 = l + (r - l) / 3; 13 | int mid2 = r - (r - l) / 3; 14 | 15 | // Check if key is present at any mid 16 | if (ar[mid1] == key) { 17 | return mid1; 18 | } 19 | if (ar[mid2] == key) { 20 | return mid2; 21 | } 22 | 23 | // Since key is not present at mid, 24 | // check in which region it is present 25 | // then repeat the Search operation 26 | // in that region 27 | if (key < ar[mid1]) { 28 | 29 | // The key lies in between l and mid1 30 | return ternarySearch(l, mid1 - 1, key, ar); 31 | } 32 | else if (key > ar[mid2]) { 33 | 34 | // The key lies in between mid2 and r 35 | return ternarySearch(mid2 + 1, r, key, ar); 36 | } 37 | else { 38 | 39 | // The key lies in between mid1 and mid2 40 | return ternarySearch(mid1 + 1, mid2 - 1, key, ar); 41 | } 42 | } 43 | 44 | // Key not found 45 | return -1; 46 | } 47 | 48 | // Driver code 49 | int main() 50 | { 51 | int l, r, p, key; 52 | 53 | // Get the array 54 | // Sort the array if not sorted 55 | int ar[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 56 | 57 | // Starting index 58 | l = 0; 59 | 60 | // length of array 61 | r = 9; 62 | 63 | // Checking for 5 64 | 65 | // Key to be searched in the array 66 | key = 5; 67 | 68 | // Search the key using ternarySearch 69 | p = ternarySearch(l, r, key, ar); 70 | 71 | // Print the result 72 | cout << "Index of " << key 73 | << " is " << p << endl; 74 | 75 | // Checking for 50 76 | 77 | // Key to be searched in the array 78 | key = 50; 79 | 80 | // Search the key using ternarySearch 81 | p = ternarySearch(l, r, key, ar); 82 | 83 | // Print the result 84 | cout << "Index of " << key 85 | << " is " << p << endl; 86 | } 87 | 88 | // This code is contributed 89 | // by Akanksha_Rai 90 | 91 | -------------------------------------------------------------------------------- /algorithms/cpp/TowerOfHanoi.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void move(int n, char tower_one, char tower_two, char tower_three) 5 | { 6 | if (n == 1) 7 | { 8 | cout << "Transfer from Tower " << tower_one << " to Tower " << tower_three << endl; 9 | } 10 | else 11 | { 12 | move(n - 1, tower_one, tower_three, tower_two); 13 | cout << "Transfer from Tower " << tower_one << " to Tower " << tower_three << endl; 14 | move(n - 1, tower_two, tower_one, tower_three); 15 | } 16 | } 17 | 18 | int main() 19 | { 20 | int n; 21 | cout << "Enter the number of Discs :" << endl; 22 | cin >> n; 23 | 24 | move(n, 'A', 'B', 'C'); // Move n discs from Tower A to C using B 25 | return 0; 26 | } 27 | 28 | /* Output: 29 | 30 | Enter the number of Discs : 31 | IP - 3 32 | OP - 33 | Transfer from Tower A to Tower C 34 | Transfer from Tower A to Tower B 35 | Transfer from Tower C to Tower B 36 | Transfer from Tower A to Tower C 37 | Transfer from Tower B to Tower A 38 | Transfer from Tower B to Tower C 39 | Transfer from Tower A to Tower C 40 | */ -------------------------------------------------------------------------------- /algorithms/cpp/algorithmsInfo.md: -------------------------------------------------------------------------------- 1 | Add any algorithms in this folder you want in C++ language. For more info read the readme in the main repository directory 2 | Thanks... -------------------------------------------------------------------------------- /algorithms/cpp/binary_search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // funtion to search any element present in the given array. 5 | bool binarySearch(int arr[], int n, int x) { 6 | // two pointers left and right which would come closer to the element to find. 7 | int left = 0, right = n-1, middle; 8 | 9 | while(left <= right) { 10 | // to check only the middle indexed element in the given array. 11 | middle = (left + right) / 2; 12 | if(arr[middle] == x) { 13 | return true; 14 | }else if(arr[middle] > x) { 15 | right = middle - 1; 16 | }else { 17 | left = middle + 1; 18 | } 19 | } 20 | // return false finally when there is no element x present in the given array. 21 | return false; 22 | } 23 | 24 | int main() { 25 | // Example array... 26 | int arr[] = {5, 10, 30, 37, 99, 239, 274, 590, 874, 1023}; 27 | int n = sizeof(arr) / sizeof(arr[0]), q; 28 | // asking the user to provide the number of queries to do in the above array. 29 | cout << "Enter number of queries: "; 30 | cin >> q; 31 | for(int i = 0; i < q; ++i) { 32 | int x; 33 | // element input by user 34 | cout << "Enter number to search: "; 35 | cin >> x; 36 | // checking wheter it is present in the array-arr 37 | if(binarySearch(arr, n, x)) { 38 | cout << x << " is present in the array.\n"; 39 | }else { 40 | cout << x << " is not present in the array.\n"; 41 | } 42 | } 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /algorithms/cpp/bogo_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | bool isSorted(vector v, int n) { 6 | while (--n > 1) { 7 | if (v[n] < v[n-1]) { 8 | return false; 9 | } 10 | } 11 | return true; 12 | } 13 | 14 | void shuffle(vector v, int n) { 15 | 16 | for (int i = 0; i < n; i++) { 17 | swap(v[i], v[rand() % n]); 18 | } 19 | } 20 | void bogosort(vector v, int n) { 21 | 22 | while(!isSorted(v, n)) 23 | shuffle(v, n); 24 | } 25 | 26 | void printarr(vector v, int n) { 27 | for (int i = 0; i < n; i++) { 28 | cout << v[i] << ' '; 29 | } 30 | cout << endl; 31 | } 32 | 33 | int main() 34 | { 35 | cout << "Enter Size of the Array: "; 36 | int n; 37 | cin >> n; 38 | std::vector v(n); 39 | 40 | cout << "Enter the elements of the Array: " ; 41 | for (auto &i : v) { 42 | cin >> i; 43 | } 44 | bogosort(v, n); 45 | cout << "Sorted Array: " ; 46 | printarr(v, n); 47 | return 0; 48 | 49 | } 50 | 51 | -------------------------------------------------------------------------------- /algorithms/cpp/bubble_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void bubSort(int arr[], int n) 5 | { 6 | for (int i = 0; i < n-1; i++) 7 | for (int j = 0; j < n-i-1; j++) 8 | if (arr[j] > arr[j+1]) 9 | swap(arr[j], arr[j+1]); 10 | } 11 | 12 | int main() 13 | { 14 | int n; 15 | cin>>n; 16 | 17 | int*arr=new int[n]; 18 | 19 | for(int i=0;i>arr[i]; 21 | 22 | bubSort(arr,n); 23 | 24 | for(int i=0;i 2 | using namespace std; 3 | int N; 4 | int graph[10][10]; 5 | int dist[10]; 6 | bool visited[10]; 7 | int parent[10]; 8 | void createGraph() 9 | { 10 | int i,j,max,u,v,w; 11 | cout<<"Enter the number of nodes : "; 12 | cin>>N; 13 | for(i=0;i<=N;i++) 14 | for(j=0;j<=N;j++) 15 | graph[i][j]=0; 16 | max=N*(N+1); 17 | for(i=0;i>u>>v>>w; 21 | if(u==-1) break; 22 | else 23 | { 24 | graph[u][v]=w; 25 | graph[v][u]=w; 26 | } 27 | } 28 | } 29 | int minDistance() 30 | { 31 | int min = 10000, minDist; 32 | for (int v = 0; v < N; v++) 33 | if (visited[v] == false && dist[v] <= min) 34 | { 35 | min = dist[v]; 36 | minDist = v; 37 | } 38 | return minDist; 39 | } 40 | void printPath(int j) 41 | { 42 | if (parent[j]==-1) 43 | return; 44 | printPath(parent[j]); 45 | cout<>src; 52 | for (int i = 0; i < N; i++) 53 | { 54 | parent[0] = -1; 55 | dist[i] = 10000; 56 | visited[i] = false; 57 | } 58 | dist[src] = 0; 59 | for (int count = 0; count < N-1; count++) 60 | { 61 | int u = minDistance(); 62 | visited[u] = true; 63 | for (int v = 0; v < N; v++) 64 | if (!visited[v] && graph[u][v] && 65 | dist[u] + graph[u][v] < dist[v]) 66 | { 67 | parent[v] = u; 68 | dist[v] = dist[u] + graph[u][v]; 69 | } 70 | } 71 | cout<<"Src->Dest\tDistance\tPath"<"< 4 | #include 5 | #include 6 | #include 7 | #include 8 | /** 9 | * Function to calculate factors of a given number. 10 | * @param n number whose factors we need to calculate. 11 | * @return all factors of number. 12 | */ 13 | 14 | std::vector factors(int64_t n) { 15 | std::vector ans; 16 | if (n < 1) { 17 | return ans; 18 | } 19 | ans.push_back(1); 20 | int64_t d = 0; 21 | if (n == 1) return ans; 22 | for (int i = 2; i <= static_cast(sqrt(n));i++) { 23 | if (n % i == 0) { 24 | ans.push_back(i); 25 | d = n / i; 26 | if (d != i) { 27 | ans.push_back(d); 28 | } 29 | } 30 | } 31 | 32 | ans.push_back(n); 33 | sort(ans.begin(), ans.end()); 34 | return ans; 35 | } 36 | 37 | /** Test function 38 | * @returns void 39 | */ 40 | void tests() { 41 | std::cout << "Test 1:\t n=1\n"; 42 | std::vector out1 = {1}; 43 | assert(factors(1) == out1); 44 | std::cout << "passed\n"; 45 | 46 | std::cout << "Test 2:\t n=5\n"; 47 | std::vector out2 = {1, 5}; 48 | assert(factors(5) == out2); 49 | std::cout << "passed\n"; 50 | 51 | std::cout << "Test 3:\t n=24\n"; 52 | std::vector out3 = {1, 2, 3, 4, 6, 8, 12, 24}; 53 | assert(factors(24) == out3); 54 | std::cout << "passed\n"; 55 | 56 | std::cout << "Test 4:\t n=-24\n"; 57 | std::vector out4 = {}; 58 | assert(factors(-24) == out4); 59 | std::cout << "passed\n"; 60 | } 61 | 62 | /** Main function 63 | * @returns 0 on exit 64 | */ 65 | int main() { 66 | tests(); 67 | return 0; 68 | } 69 | -------------------------------------------------------------------------------- /algorithms/cpp/heap_sort.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for implementation of Heap Sort 2 | #include 3 | 4 | using namespace std; 5 | 6 | void heapify(int arr[], int n, int i) { 7 | int largest = i; 8 | int l = 2*i +1; 9 | int r = 2*i +2; 10 | 11 | if(l < n && arr[l] > arr[largest]) 12 | largest = l; 13 | if(r < n && arr[r] > arr[largest]) 14 | largest = r; 15 | 16 | if(largest != i) { 17 | swap(arr[i], arr[largest]); 18 | heapify(arr, n, largest); 19 | } 20 | } 21 | 22 | void heapSort(int arr[], int n) { 23 | for (int i = n/2 - 1; i>=0; i--) 24 | heapify(arr, n, i); 25 | for (int i=n-1; i>=0; i--) { 26 | swap(arr[0], arr[i]); 27 | heapify(arr, i, 0); 28 | } 29 | } 30 | 31 | void printArray(int arr[], int n) { 32 | for (int i=0; i 2 | using namespace std; 3 | 4 | void insSort(int arr[], int n) 5 | { 6 | int k, j; 7 | for (int i = 1; i < n; i++) 8 | { 9 | k = arr[i]; 10 | j = i - 1; 11 | while (j >= 0 && arr[j] > k) 12 | { 13 | arr[j + 1] = arr[j]; 14 | j = j - 1; 15 | } 16 | arr[j + 1] = k; 17 | } 18 | } 19 | 20 | int main() 21 | { 22 | int n; 23 | cin>>n; 24 | 25 | int*arr=new int[n]; 26 | 27 | for(int i=0;i>arr[i]; 29 | 30 | insSort(arr,n); 31 | 32 | for(int i=0;i 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int t; 8 | cin>>t; 9 | while(t--) 10 | { 11 | int n; 12 | cin>>n; 13 | int arr[n]; 14 | for(int i=0;i>arr[i]; 16 | 17 | // Kadane's Algorithm 18 | int max_so_far=INT_MIN,max_ending_here=0; 19 | 20 | for(int i=0;isiize[py]) 19 | swap(px,py); 20 | par[px] = py; 21 | siize[py] += siize[px]; 22 | siize[px] = 0; 23 | } 24 | } 25 | 26 | // structure of an edge. 27 | int n,m; 28 | struct edge 29 | { 30 | int a,b,w; 31 | }; 32 | 33 | // Comparator function for sorting the edges. 34 | bool comp(edge A,edge B) 35 | { 36 | if(A.w < B.w) 37 | return 1; 38 | return 0; 39 | } 40 | 41 | edge ar[maxn]; 42 | 43 | signed main() 44 | { 45 | 46 | #ifndef ONLINE_JUDGE 47 | freopen("input.txt", "r", stdin); 48 | freopen("output.txt", "w", stdout); 49 | #endif 50 | int n,m; 51 | cin>>n>>m; 52 | 53 | // Initialize DSU. 54 | for(int i=1; i<=n; i++) 55 | par[i] = i ,siize[i] = 1; 56 | 57 | for(int i=0; i>ar[i].a >>ar[i].b >>ar[i].w; 61 | } 62 | 63 | // sum - weight of MST. 64 | int sum=0 ; 65 | sort(ar,ar+m,comp); 66 | for(int i=0; i 2 | 3 | using namespace std; 4 | int main() 5 | { 6 | int n,i,item,flag=0,r; 7 | 8 | cout<<"enter number of elements"; 9 | cin>>n; 10 | int a[n]; 11 | cout<<"enter array elements"; 12 | for(i=0;i<=n-1;i++) 13 | { 14 | cin>>a[i] 15 | 16 | } 17 | cout<<"enter item to be found"; 18 | cin>>item; 19 | for(i=0;i<=n-1;i++) 20 | { 21 | if(a[i]==item) 22 | { 23 | cout<& a) { 4 | int n=a.size(); 5 | if(n<=1) return n; 6 | vectorh(n,1); 7 | 8 | for(int i=1;i 3 | using namespace std; 4 | 5 | // Function to print a substring str[low..high] 6 | void printSubStr(string str, int low, int high) 7 | { 8 | for (int i = low; i <= high; ++i) 9 | cout << str[i]; 10 | } 11 | 12 | // This function prints the 13 | // longest palindrome substring 14 | // It also returns the length 15 | // of the longest palindrome 16 | int longestPalSubstr(string str) 17 | { 18 | // get length of input string 19 | int n = str.size(); 20 | 21 | // All substrings of length 1 22 | // are palindromes 23 | int maxLength = 1, start = 0; 24 | 25 | // Nested loop to mark start and end index 26 | for (int i = 0; i < str.length(); i++) { 27 | for (int j = i; j < str.length(); j++) { 28 | int flag = 1; 29 | 30 | // Check palindrome 31 | for (int k = 0; k < (j - i + 1) / 2; k++) 32 | if (str[i + k] != str[j - k]) 33 | flag = 0; 34 | 35 | // Palindrome 36 | if (flag && (j - i + 1) > maxLength) { 37 | start = i; 38 | maxLength = j - i + 1; 39 | } 40 | } 41 | } 42 | 43 | cout << "Longest palindrome substring is: "; 44 | printSubStr(str, start, start + maxLength - 1); 45 | 46 | // return length of LPS 47 | return maxLength; 48 | } 49 | 50 | // Driver Code 51 | int main() 52 | { 53 | string str = "forgeeksskeegfor"; 54 | cout << "\nLength is: " 55 | << longestPalSubstr(str); 56 | return 0; 57 | } 58 | -------------------------------------------------------------------------------- /algorithms/cpp/max_xor_pair_trie.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for the above approach 2 | #include 3 | using namespace std; 4 | 5 | // Structure of Trie 6 | class node { 7 | public: 8 | node* left; 9 | node* right; 10 | }; 11 | 12 | // Function to insert binary 13 | // representation of element x 14 | // in the Trie 15 | void insert(int x, node* head) 16 | { 17 | // Store the head 18 | node* curr = head; 19 | 20 | for (int i = 30; i >= 0; i--) { 21 | 22 | // Find the i-th bit 23 | int val = (x >> i) & 1; 24 | 25 | if (val == 0) { 26 | 27 | // If curr->left is NULL 28 | if (!curr->left) 29 | curr->left = new node(); 30 | 31 | // Update curr to curr->left 32 | curr = curr->left; 33 | } 34 | else { 35 | 36 | // If curr->right is NULL 37 | if (!curr->right) 38 | curr->right = new node(); 39 | 40 | // Update curr to curr->right 41 | curr = curr->right; 42 | } 43 | } 44 | } 45 | 46 | // Function that finds the maximum 47 | // Bitwise XOR value for all such pairs 48 | int findMaximumXOR(int arr[], int n) 49 | { 50 | // head Node of Trie 51 | node* head = new node(); 52 | 53 | // Insert each element in trie 54 | for (int i = 0; i < n; i++) { 55 | insert(arr[i], head); 56 | } 57 | 58 | // Stores the maximum XOR value 59 | int ans = 0; 60 | 61 | // Traverse the given array 62 | for (int i = 0; i < n; i++) { 63 | 64 | // Stores the XOR with current 65 | // value arr[i] 66 | int curr_xor = 0; 67 | 68 | int M = pow(2, 30); 69 | 70 | node* curr = head; 71 | 72 | for (int j = 30; j >= 0; j--) { 73 | 74 | // Finding ith bit 75 | int val = (arr[i] >> j) & 1; 76 | 77 | // Check if the bit is 0 78 | if (val == 0) { 79 | 80 | // If right node exists 81 | if (curr->right) { 82 | 83 | // Update the currentXOR 84 | curr_xor += M; 85 | curr = curr->right; 86 | } 87 | 88 | else { 89 | curr = curr->left; 90 | } 91 | } 92 | 93 | else { 94 | 95 | // Check if left node exists 96 | if (curr->left) { 97 | 98 | // Update the currentXOR 99 | curr_xor += M; 100 | curr = curr->left; 101 | } 102 | else { 103 | curr = curr->right; 104 | } 105 | } 106 | 107 | // Update M to M/2 for next set bit 108 | M /= 2; 109 | } 110 | 111 | // Update the maximum XOR 112 | ans = max(ans, curr_xor); 113 | } 114 | 115 | // Return the maximum XOR found 116 | return ans; 117 | } 118 | 119 | // Driver Code 120 | int main() 121 | { 122 | // Given array arr[] 123 | int arr[] = { 1, 2, 3, 4 }; 124 | 125 | int N = sizeof(arr) / sizeof(arr[0]); 126 | 127 | // Function Call 128 | cout << findMaximumXOR(arr, N); 129 | 130 | return 0; 131 | } 132 | -------------------------------------------------------------------------------- /algorithms/cpp/merge_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void Merge(int* A, int, int, int); 4 | void Merge_Sort(int* A, int p, int r); 5 | int main() 6 | { 7 | int len, n, i; 8 | cout << "Array size: "; 9 | cin >> len; 10 | int a[len]; 11 | for (i = 0; i < len; i++) { 12 | cout << "Enter element " << i + 1 << ": "; 13 | cin >> a[i]; 14 | } 15 | cout << "Initial array: "; 16 | for (int i = 0; i < len; i++) { 17 | cout << a[i] << " "; 18 | } 19 | 20 | Merge_Sort(a, 0, len - 1); 21 | cout << "\nSorted array: "; 22 | for (int i = 0; i < len; i++) { 23 | cout << a[i] << " "; 24 | } 25 | cout << "\n"; 26 | return 0; 27 | } 28 | void Merge(int* arr, int p, int q, int r) 29 | { 30 | int n1 = q - p + 1; 31 | int n2 = r - q; 32 | int L[n1 + 1]; 33 | int R[n2 + 1]; 34 | for (int i = 0; i < n1; i++) 35 | L[i] = arr[p + i]; 36 | for (int j = 0; j < n2; j++) 37 | R[j] = arr[q + 1 + j]; 38 | int i = 0; 39 | int j = 0; 40 | int n = 0; 41 | while (i != n1 && j != n2) { 42 | if (L[i] > R[j]) { 43 | arr[p + n] = R[j]; 44 | j++; 45 | } 46 | else { 47 | arr[p + n] = L[i]; 48 | i++; 49 | } 50 | n++; 51 | } 52 | while (j != n2) { 53 | arr[p + n] = R[j]; 54 | j++; 55 | n++; 56 | } 57 | while (i != n1) { 58 | arr[p + n] = L[i]; 59 | i++; 60 | n++; 61 | } 62 | } 63 | void Merge_Sort(int* arr, int p, int r) 64 | { 65 | if (r > p) { 66 | int q; 67 | q = (p + r) / 2; 68 | Merge_Sort(arr, p, q); 69 | Merge_Sort(arr, q + 1, r); 70 | Merge(arr, p, q, r); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /algorithms/cpp/next_greater_in_o(n).cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int n; 7 | cin>>n; 8 | int arr[n]; 9 | for(int i=0;i>arr[i]; 11 | 12 | stack s,ind; 13 | s.push(arr[0]); 14 | ind.push(0); 15 | cout<<"Element Next greater Index of ele Index of greater\n"; 16 | for(int i=1;i 3 | using namespace std; 4 | 5 | void swap(int* a, int* b) 6 | { 7 | int t = *a; 8 | *a = *b; 9 | *b = t; 10 | } 11 | 12 | int partition (int arr[], int low, int high) 13 | { 14 | int pivot = arr[high]; 15 | int i = (low - 1); 16 | 17 | for (int j = low; j <= high - 1; j++) 18 | { 19 | if (arr[j] < pivot) 20 | { 21 | i++; 22 | swap(&arr[i], &arr[j]); 23 | } 24 | } 25 | swap(&arr[i + 1], &arr[high]); 26 | return (i + 1); 27 | } 28 | 29 | void quickSort(int arr[], int low, int high) 30 | { 31 | if (low < high) 32 | { 33 | int pi = partition(arr, low, high); 34 | quickSort(arr, low, pi - 1); 35 | quickSort(arr, pi + 1, high); 36 | } 37 | } 38 | 39 | void printArray(int arr[], int size) 40 | { 41 | int i; 42 | for (i = 0; i < size; i++) 43 | cout << arr[i] << " "; 44 | cout << endl; 45 | } 46 | 47 | int main() 48 | { 49 | int arr[] = {56, 43, 10, 91, 2, 45}; 50 | int n = sizeof(arr) / sizeof(arr[0]); 51 | quickSort(arr, 0, n - 1); 52 | cout << "Sorted array: \n"; 53 | printArray(arr, n); 54 | return 0; 55 | } 56 | -------------------------------------------------------------------------------- /algorithms/cpp/selection_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void selSort(int arr[], int n) 5 | { 6 | int k; 7 | for (int i = 0; i < n-1; i++) 8 | { 9 | k = i; 10 | for (int j = i+1; j < n; j++) 11 | if (arr[j] < arr[k]) 12 | k = j; 13 | swap(arr[k],arr[i]); 14 | } 15 | } 16 | 17 | int main() 18 | { 19 | int n; 20 | cin>>n; 21 | 22 | int*arr=new int[n]; 23 | 24 | for(int i=0;i>arr[i]; 26 | 27 | selSort(arr,n); 28 | 29 | for(int i=0;i 2 | using namespace std; 3 | 4 | /* function to sort arr using shellSort */ 5 | int shellSort(int arr[], int n) 6 | { 7 | for (int gap = n / 2; gap > 0; gap /= 2) 8 | { 9 | for (int i = gap; i < n; i += 1) 10 | { 11 | int temp = arr[i]; 12 | 13 | int j; 14 | for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) 15 | arr[j] = arr[j - gap]; 16 | 17 | arr[j] = temp; 18 | } 19 | } 20 | return 0; 21 | } 22 | 23 | void printArray(int arr[], int n) 24 | { 25 | for (int i = 0; i < n; i++) 26 | cout << arr[i] << " "; 27 | } 28 | 29 | int main() 30 | { 31 | int arr[] = {12, 34, 54, 2, 3}, i; 32 | int n = sizeof(arr) / sizeof(arr[0]); 33 | 34 | cout << "Array before sorting: \n"; 35 | printArray(arr, n); 36 | 37 | shellSort(arr, n); 38 | 39 | cout << "\nArray after sorting: \n"; 40 | printArray(arr, n); 41 | 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /algorithms/cpp/sieve_of_eratosthenes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void SieveOfEratosthenes(int n) 5 | { 6 | bool prime[n+1]; 7 | memset(prime, true, sizeof(prime)); 8 | 9 | for (int p=2; p*p<=n; p++) 10 | { 11 | if (prime[p] == true) 12 | { 13 | for (int i=p*p; i<=n; i += p) 14 | prime[i] = false; 15 | } 16 | } 17 | for (int p=2; p<=n; p++) 18 | if (prime[p]) 19 | cout << p << " "; 20 | } 21 | 22 | int main() 23 | { 24 | int n = 30; 25 | cout << "Following are the prime numbers smaller " 26 | << " than or equal to " << n << endl; 27 | SieveOfEratosthenes(n); 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /algorithms/go/binary_search.go: -------------------------------------------------------------------------------- 1 | package main 2 | import "fmt" 3 | 4 | func binarySearch(needle int, haystack []int) bool { 5 | 6 | low := 0 7 | high := len(haystack) - 1 8 | 9 | for low <= high{ 10 | median := (low + high) / 2 11 | 12 | if haystack[median] < needle { 13 | low = median + 1 14 | }else{ 15 | high = median - 1 16 | } 17 | } 18 | 19 | if low == len(haystack) || haystack[low] != needle { 20 | return false 21 | } 22 | 23 | return true 24 | } 25 | 26 | 27 | func main(){ 28 | items := []int{1,2, 9, 20, 31, 45, 63, 70, 100} 29 | fmt.Println(binarySearch(63, items)) 30 | } -------------------------------------------------------------------------------- /algorithms/haskell/maths/fibonacci.hs: -------------------------------------------------------------------------------- 1 | fib 0 = 0 2 | fib 1 = 1 3 | fib n = fib (n - 1) + fib (n - 2) -------------------------------------------------------------------------------- /algorithms/java/DFS.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | 4 | class Graph 5 | { 6 | private int V; 7 | 8 | private LinkedList adj[]; 9 | 10 | 11 | @SuppressWarnings("unchecked") 12 | Graph(int v) 13 | { 14 | V = v; 15 | adj = new LinkedList[v]; 16 | for (int i=0; i i = adj[v].listIterator(); 35 | while (i.hasNext()) 36 | { 37 | int n = i.next(); 38 | if (!visited[n]) 39 | DFSUtil(n, visited); 40 | } 41 | } 42 | 43 | 44 | void DFS(int v) 45 | { 46 | 47 | boolean visited[] = new boolean[V]; 48 | 49 | 50 | DFSUtil(v, visited); 51 | } 52 | 53 | public static void main(String args[]) 54 | { 55 | Graph g = new Graph(4); 56 | 57 | g.addEdge(0, 1); 58 | g.addEdge(0, 2); 59 | g.addEdge(1, 2); 60 | g.addEdge(2, 0); 61 | g.addEdge(2, 3); 62 | g.addEdge(3, 3); 63 | 64 | System.out.println("Following is Depth First Traversal "+ 65 | "(starting from vertex 2)"); 66 | 67 | g.DFS(2); 68 | } 69 | } 70 | 71 | -------------------------------------------------------------------------------- /algorithms/java/Factors.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.Math; 3 | 4 | public class Factors { 5 | 6 | /** 7 | * Function to calculate factors of a given number. 8 | * 9 | * @param n The number whose factors we need to calculate. 10 | * @return all factors of number. 11 | */ 12 | public static ArrayList factors(int n) { 13 | ArrayList ans = new ArrayList(); 14 | if (n < 1) return ans; 15 | ans.add(Long.valueOf(1)); 16 | long d = 0; 17 | if (n == 1) return ans; 18 | for (long i = 2; i <= Math.sqrt(n);i++) { 19 | if (n % i == 0) { 20 | ans.add(i); 21 | d = n / i; 22 | if (d != i) { 23 | ans.add(d); 24 | } 25 | } 26 | } 27 | 28 | ans.add(Long.valueOf(n)); 29 | Collections.sort(ans); 30 | return ans; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /algorithms/java/LinearSearch.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class LinearSearch { 4 | 5 | public static int linearSearch(int[] arr, int target) { 6 | for (int i = 0; i < arr.length; i++) { 7 | if (arr[i] == target) { 8 | return i; 9 | } 10 | } 11 | return -1; 12 | } 13 | 14 | public static void main(String[] args) { 15 | Scanner scanner = new Scanner(System.in); 16 | 17 | // Example Usage 18 | int[] exampleArray = {10, 5, 7, 2, 8, 4}; 19 | int targetElement = 7; 20 | 21 | int result = linearSearch(exampleArray, targetElement); 22 | 23 | if (result != -1) { 24 | System.out.println("Element " + targetElement + " found at index " + result); 25 | } else { 26 | System.out.println("Element " + targetElement + " not found"); 27 | } 28 | 29 | // Additional Test Cases 30 | int[] testArray1 = {1, 2, 3, 4, 5}; 31 | int target1 = 3; 32 | int result1 = linearSearch(testArray1, target1); 33 | System.out.println("Test Case 1: Element " + target1 + " found at index " + result1); 34 | 35 | int[] testArray2 = {11, 22, 33, 44, 55}; 36 | int target2 = 66; 37 | int result2 = linearSearch(testArray2, target2); 38 | System.out.println("Test Case 2: Element " + target2 + " not found"); 39 | 40 | // Custom Input 41 | System.out.print("Enter the length of the array: "); 42 | int length = scanner.nextInt(); 43 | int[] customArray = new int[length]; 44 | 45 | System.out.println("Enter the elements of the array:"); 46 | for (int i = 0; i < length; i++) { 47 | customArray[i] = scanner.nextInt(); 48 | } 49 | 50 | System.out.print("Enter the element to search for: "); 51 | int targetElementCustom = scanner.nextInt(); 52 | 53 | int resultCustom = linearSearch(customArray, targetElementCustom); 54 | 55 | if (resultCustom != -1) { 56 | System.out.println("Element " + targetElementCustom + " found at index " + resultCustom); 57 | } else { 58 | System.out.println("Element " + targetElementCustom + " not found"); 59 | } 60 | } 61 | } 62 | 63 | /* 64 | Example Usage: 65 | Element 7 found at index 2 66 | Test Case 1: Element 3 found at index 2 67 | Test Case 2: Element 66 not found 68 | 69 | CUSTOM EXAMPLE: 70 | 71 | Enter the length of the array: 5 72 | Enter the elements of the array: 73 | 1 3 5 7 9 74 | Enter the element to search for: 5 75 | Element 5 found at index 2 76 | 77 | 78 | */ 79 | 80 | 81 | 82 | 83 | 84 | 85 | -------------------------------------------------------------------------------- /algorithms/java/MergeSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class MergeSort { 4 | 5 | public static void merge(int[] arr, int left, int mid, int right) { 6 | // Calculate the sizes of the two subarrays 7 | int size1 = mid - left + 1; 8 | int size2 = right - mid; 9 | 10 | // Create temporary arrays 11 | int[] leftArray = new int[size1]; 12 | int[] rightArray = new int[size2]; 13 | 14 | // Copy data to temporary arrays 15 | for (int i = 0; i < size1; ++i) 16 | leftArray[i] = arr[left + i]; 17 | for (int j = 0; j < size2; ++j) 18 | rightArray[j] = arr[mid + 1 + j]; 19 | 20 | // Merge the temporary arrays 21 | 22 | // Initial indexes of first and second subarrays 23 | int i = 0, j = 0; 24 | 25 | // Initial index of merged subarray array 26 | int k = left; 27 | while (i < size1 && j < size2) { 28 | if (leftArray[i] <= rightArray[j]) { 29 | arr[k] = leftArray[i]; 30 | i++; 31 | } else { 32 | arr[k] = rightArray[j]; 33 | j++; 34 | } 35 | k++; 36 | } 37 | 38 | // Copy remaining elements of leftArray[], if any 39 | while (i < size1) { 40 | arr[k] = leftArray[i]; 41 | i++; 42 | k++; 43 | } 44 | 45 | // Copy remaining elements of rightArray[], if any 46 | while (j < size2) { 47 | arr[k] = rightArray[j]; 48 | j++; 49 | k++; 50 | } 51 | } 52 | 53 | 54 | public static void mergeSort(int[] arr, int left, int right) { 55 | if (left < right) { 56 | // Find the middle point 57 | int mid = (left + right) / 2; 58 | 59 | // Recursive calls for left and right subarrays 60 | mergeSort(arr, left, mid); 61 | mergeSort(arr, mid + 1, right); 62 | 63 | // Merge the sorted subarrays 64 | merge(arr, left, mid, right); 65 | } 66 | } 67 | 68 | public static void main(String[] args) { 69 | Scanner scanner = new Scanner(System.in); 70 | 71 | // Input prompt for array size 72 | System.out.print("Enter the size of the array: "); 73 | int size = scanner.nextInt(); 74 | 75 | // Input prompt for array elements 76 | System.out.println("Enter the elements of the array:"); 77 | int[] arr = new int[size]; 78 | for (int i = 0; i < size; i++) { 79 | arr[i] = scanner.nextInt(); 80 | } 81 | 82 | // Perform Merge Sort 83 | mergeSort(arr, 0, size - 1); 84 | 85 | // Output the sorted array 86 | System.out.println("Sorted array:"); 87 | for (int i : arr) { 88 | System.out.print(i + " "); 89 | } 90 | } 91 | } 92 | 93 | 94 | /* 95 | Enter the size of the array: 5 96 | Enter the elements of the array: 97 | 12 5 7 3 9 98 | Sorted array: 99 | 3 5 7 9 12 100 | 101 | */ -------------------------------------------------------------------------------- /algorithms/java/SelectionSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class SelectionSort { 4 | 5 | /** 6 | * This method performs the selection sort algorithm on the input array. 7 | * 8 | * @param arr The array to be sorted. 9 | */ 10 | public static void selectionSort(int[] arr) { 11 | int n = arr.length; 12 | 13 | for (int i = 0; i < n - 1; i++) { 14 | // Assume the current index has the minimum value 15 | int minIndex = i; 16 | 17 | for (int j = i + 1; j < n; j++) { 18 | // If a smaller element is found, update minIndex 19 | if (arr[j] < arr[minIndex]) { 20 | minIndex = j; 21 | } 22 | } 23 | 24 | // Swap the found minimum element with the element at index i 25 | int temp = arr[minIndex]; 26 | arr[minIndex] = arr[i]; 27 | arr[i] = temp; 28 | } 29 | } 30 | 31 | public static void main(String[] args) { 32 | Scanner scanner = new Scanner(System.in); 33 | 34 | // Input prompt for array size 35 | System.out.print("Enter the size of the array: "); 36 | int size = scanner.nextInt(); 37 | 38 | // Input prompt for array elements 39 | System.out.println("Enter the elements of the array:"); 40 | int[] arr = new int[size]; 41 | for (int i = 0; i < size; i++) { 42 | arr[i] = scanner.nextInt(); 43 | } 44 | 45 | // Perform Selection Sort 46 | selectionSort(arr); 47 | 48 | // Output the sorted array 49 | System.out.println("Sorted array:"); 50 | for (int i : arr) { 51 | System.out.print(i + " "); 52 | } 53 | } 54 | } 55 | /* 56 | 57 | Enter the size of the array: 6 58 | Enter the elements of the array: 59 | 12 5 7 3 9 2 60 | 61 | Sorted array: 62 | 2 3 5 7 9 12 63 | 64 | */ -------------------------------------------------------------------------------- /algorithms/java/algorithmsInfo.md: -------------------------------------------------------------------------------- 1 | Add any algorithms in this folder you want in java language. For more info read the readme in the main repository directory 2 | Thanks... -------------------------------------------------------------------------------- /algorithms/java/amstrong.java: -------------------------------------------------------------------------------- 1 | public class amstrong { 2 | static boolean isArmstrong(int number){ 3 | boolean amstrong = false; 4 | int n = 0; 5 | int num = number, digit = 0; 6 | 7 | double t= 0; 8 | 9 | while (num > 0){ 10 | num = num / 10; 11 | n+=1; 12 | } 13 | num = number; 14 | while(num > 0) { 15 | digit = num % 10; 16 | t = t + Math.pow(digit, n); 17 | num =num / 10; 18 | } 19 | long total = Math.round(t); 20 | if(number == total){ 21 | amstrong = true; 22 | } 23 | 24 | return amstrong; 25 | } 26 | 27 | public static void main(String[] args) { 28 | System.out.println(isArmstrong(153)); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /algorithms/java/binary_search.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class BinarySearch { 4 | public static void main(String[] args) { 5 | Scanner sc = new Scanner(System.in); 6 | //Example array... 7 | int arr[] = {5, 10, 30, 37, 99, 239, 274, 590, 874, 1023}; 8 | //asking the user to provide the number of queries to do in the above array. 9 | System.out.print("Enter number of queries: "); 10 | int q = sc.nextInt(); 11 | for(int i = 0; i < q; ++i) { 12 | //element input by user 13 | System.out.print("Enter number to search: "); 14 | int x = sc.nextInt(); 15 | //checking wheter it is present in the array-arr 16 | if(binarySearch(arr, x)) { 17 | System.out.println(x + " is present in the array."); 18 | }else { 19 | System.out.println(x + " is not present in the array."); 20 | } 21 | } 22 | } 23 | 24 | //funtion to search any element present in the given array. 25 | public static boolean binarySearch(int arr[], int x) { 26 | //two pointers left and right which would come closer to the element to find. 27 | int left = 0, right = arr.length - 1, middle; 28 | 29 | while(left <= right) { 30 | //to check only the middle indexed element in the given array. 31 | middle = (left + right) / 2; 32 | if(arr[middle] == x) { 33 | return true; 34 | }else if(arr[middle] > x) { 35 | right = middle - 1; 36 | }else { 37 | left = middle + 1; 38 | } 39 | } 40 | //return false finally when there is no element x present in the given array. 41 | return false; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /algorithms/java/breadth_first_search.java: -------------------------------------------------------------------------------- 1 | // Illustration of Breadth First Search in java 2 | //Refrence: https://www.geeksforgeeks.org/breadth-first-search-or-bfs-for-a-graph/ 3 | import java.io.*; 4 | import java.util.*; 5 | 6 | class BSF 7 | { 8 | private int V; 9 | private LinkedList adj[]; 10 | 11 | Graph(int v) 12 | { 13 | V = v; 14 | adj = new LinkedList[v]; 15 | for (int i=0; i queue = new LinkedList(); 27 | visited[s]=true; 28 | queue.add(s); 29 | while (queue.size() != 0) { 30 | s = queue.poll(); 31 | System.out.print(s+" "); 32 | Iterator i = adj[s].listIterator(); 33 | while (i.hasNext()) { 34 | int n = i.next(); 35 | if (!visited[n]) { 36 | visited[n] = true; 37 | queue.add(n); 38 | } 39 | } 40 | } 41 | } 42 | 43 | 44 | public static void main(String args[]) { 45 | Graph g = new Graph(4); 46 | 47 | g.addEdge(0, 1); 48 | g.addEdge(0, 2); 49 | g.addEdge(1, 2); 50 | g.addEdge(2, 0); 51 | g.addEdge(2, 3); 52 | g.addEdge(3, 3); 53 | 54 | System.out.println("Following is Breadth First Traversal "+ 55 | "(starting from vertex 2)"); 56 | 57 | g.BFS(2); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /algorithms/java/bst/BST.java: -------------------------------------------------------------------------------- 1 | 2 | public interface BST { 3 | 4 | public int getSize(); 5 | 6 | public int getHeight(); 7 | 8 | public void ShowPreorder(); 9 | 10 | public void ShowInorder(); 11 | 12 | public void ShowPostorder(); 13 | // public void ShowLeveloreder(); 14 | 15 | } 16 | -------------------------------------------------------------------------------- /algorithms/java/bst/bst_node.java: -------------------------------------------------------------------------------- 1 | 2 | public class BSTNode { 3 | 4 | public int key; 5 | public String element; 6 | public BSTNode parent; 7 | public BSTNode leftChild; 8 | public BSTNode rigthChild; 9 | 10 | public BSTNode(int key, String element) { 11 | this.key = key; 12 | this.element = element; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /algorithms/java/bubble_sort.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class BubbleSort { 4 | public static void main(String[] args) { 5 | int arr[] = {4, 12, 23, 1, 90, 1243, 98, 24, 1,56, 124}; 6 | bubbleSort(arr); 7 | System.out.println("Array after sorting is: "); 8 | for(int i : arr) { 9 | System.out.print(i + " "); 10 | } 11 | } 12 | 13 | public static void bubbleSort(int arr[]) { 14 | int n = arr.length; 15 | boolean swapped; 16 | for (int i = 0; i < n - 1; i++) { 17 | swapped = false; 18 | for (int j = 0; j < n - i - 1; j++) { 19 | if (arr[j] > arr[j + 1]) { 20 | int temp = arr[j]; 21 | arr[j] = arr[j + 1]; 22 | arr[j + 1] = temp; 23 | swapped = true; 24 | } 25 | } 26 | if (swapped == false) 27 | break; 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /algorithms/java/counting_sort.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class CountingSort { 4 | public static void main(String args[]){ 5 | 6 | Scanner sc = new Scanner(System.in); 7 | System.out.println("Enter the number of elements: "); 8 | int n = sc.nextInt(); 9 | int arr[] = new int[n]; 10 | System.out.println("Enter the Array Elements: "); 11 | for(int i = 0 ; i < n ; i++){ 12 | arr[i] = sc.nextInt(); 13 | } 14 | int max = arr[0]; 15 | for(int i = 0 ; i< arr.length ; i++){ 16 | if(max < arr[i]) 17 | max = arr[i]; 18 | } 19 | int outputarr[] = new int[arr.length+1]; 20 | int countarr[] = new int[max+1]; 21 | for (int i = 0; i < max; ++i) { 22 | countarr[i] = 0; 23 | } 24 | for (int i = 0; i < arr.length; i++) { 25 | countarr[arr[i]]++; 26 | } 27 | for (int i = 1; i <= max; i++) { 28 | countarr[i] += countarr[i - 1]; 29 | } 30 | for (int i = arr.length - 1; i >= 0; i--) { 31 | outputarr[countarr[arr[i]] - 1] = arr[i]; 32 | countarr[arr[i]]--; 33 | } 34 | for (int i = 0; i < arr.length; i++) { 35 | arr[i] = outputarr[i]; 36 | } 37 | System.out.println("Sorted Array in ascending order"); 38 | for(int a : arr){ 39 | System.out.print(a + " "); 40 | } 41 | } 42 | } -------------------------------------------------------------------------------- /algorithms/java/dijkstra's_algorithm.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | import java.io.*; 4 | 5 | class ShortestPath { 6 | 7 | static final int V = 9; //Number of vertices in graph 8 | int minDistance(int dist[], Boolean sptSet[]) 9 | { 10 | // Initialize min value 11 | int min = Integer.MAX_VALUE, min_index = -1; 12 | 13 | for (int v = 0; v < V; v++) 14 | if (sptSet[v] == false && dist[v] <= min) { 15 | min = dist[v]; 16 | min_index = v; 17 | } 18 | 19 | return min_index; 20 | } 21 | 22 | void printSolution(int dist[], int n) 23 | { 24 | System.out.println("Vertex Distance from Source"); 25 | for (int i = 0; i < V; i++) 26 | System.out.println(i + " ======> " + dist[i]); 27 | } 28 | 29 | // Implements Dijkstra's algorithm 30 | void dijkstra(int graph[][], int src) 31 | { 32 | int dist[] = new int[V]; // dist[i] will hold the shortest distance from source to i 33 | 34 | Boolean sptSet[] = new Boolean[V]; 35 | 36 | for (int i = 0; i < V; i++) { 37 | dist[i] = Integer.MAX_VALUE; 38 | sptSet[i] = false; 39 | } 40 | 41 | // Distance of source vertex from itself is 0 42 | dist[src] = 0; 43 | 44 | //Shortest path for all vertices 45 | for (int count = 0; count < V - 1; count++) { 46 | 47 | int u = minDistance(dist, sptSet); 48 | 49 | // Mark the picked vertex 50 | sptSet[u] = true; 51 | 52 | // Update dist value of the adjacent vertices of the picked vertex. 53 | for (int v = 0; v < V; v++) 54 | 55 | if (!sptSet[v] && graph[u][v] != 0 && 56 | dist[u] != Integer.MAX_VALUE && dist[u] + graph[u][v] < dist[v]) 57 | dist[v] = dist[u] + graph[u][v]; 58 | } 59 | 60 | // print the constructed distance array 61 | printSolution(dist, V); 62 | } 63 | 64 | public static void main(String[] args) 65 | { 66 | /* creating the graph */ 67 | int graph[][] = new int[][] { { 0, 4, 3, 0, 0, 0, 0, 6, 0 }, 68 | { 4, 0, 8, 0, 0, 0, 0, 12, 0 }, 69 | { 3, 8, 0, 7, 0, 2, 0, 0, 2 }, 70 | { 0, 0, 7, 0, 9, 12, 0, 0, 0 }, 71 | { 0, 0, 0, 9, 0, 10, 0, 0, 0 }, 72 | { 0, 0, 2, 12, 10, 0, 2, 0, 0 }, 73 | { 0, 0, 0, 0, 0, 2, 0, 1, 6 }, 74 | { 6, 12, 0, 0, 0, 0, 1, 0, 5 }, 75 | { 0, 0, 2, 0, 0, 0, 6, 5, 0 } }; 76 | ShortestPath t = new ShortestPath(); 77 | t.dijkstra(graph, 0); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /algorithms/java/factorial.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | public class factorial { 3 | public static void main(String[] args) { 4 | Scanner sc = new Scanner(System.in); 5 | int factorial = 1; 6 | System.out.println("enter the number you want factorial of"); 7 | int n = sc.nextInt(); 8 | 9 | for(int i = 1;i <= n; i++){ 10 | factorial = i*factorial; 11 | } 12 | 13 | System.out.println(factorial); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /algorithms/java/huffman_coding.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.InputStreamReader; 3 | import java.io.IOException; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | import java.util.PriorityQueue; 7 | 8 | public class HuffmanCoding { 9 | 10 | protected static Map result; 11 | 12 | static class Node implements Comparable { 13 | Node left; 14 | Node right; 15 | char data; 16 | int count; 17 | 18 | public Node(char data, int count, Node left, Node right) { 19 | this.data = data; 20 | this.count = count; 21 | this.left = left; 22 | this.right = right; 23 | } 24 | 25 | @Override 26 | public int compareTo(Node node) { 27 | return this.count < node.count ? -1 : 1; 28 | } 29 | } 30 | 31 | public static void main (String[] args) throws IOException { 32 | BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); 33 | System.out.print("\nEnter the string to be encoded: "); 34 | String message = reader.readLine().trim(); 35 | reader.close(); 36 | 37 | Map frequencies = new HashMap<>(); 38 | for (char character : message.toCharArray()) 39 | frequencies.put(character, frequencies.getOrDefault(character, 0) + 1); 40 | 41 | PriorityQueue queue = new PriorityQueue<>(frequencies.size()); 42 | for (Map.Entry pair : frequencies.entrySet()) 43 | queue.add(new Node(pair.getKey(), pair.getValue(), null, null)); 44 | 45 | while (queue.size() > 1) { 46 | Node left = queue.poll(); 47 | Node right = queue.poll(); 48 | queue.add(new Node('$', left.count + right.count, left, right)); 49 | } 50 | 51 | result = new HashMap<>(); 52 | preOrder(queue.poll(), ""); 53 | 54 | System.out.println("\nEncodings for each character:"); 55 | for (Map.Entry pair : result.entrySet()) 56 | System.out.println(pair.getKey() + ": " + pair.getValue()); 57 | 58 | StringBuilder answer = new StringBuilder(""); 59 | for (char character : message.toCharArray()) 60 | answer.append(result.get(character)); 61 | 62 | System.out.println("\nThe encoded message is: " + answer); 63 | } 64 | 65 | private static void preOrder(Node root, String prefix) { 66 | if (root != null) { 67 | if (root.data != '$') { 68 | result.put(root.data, prefix); 69 | return; 70 | } 71 | preOrder(root.left, prefix + "0"); 72 | preOrder(root.right, prefix + "1"); 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /algorithms/java/insertion_sort.java: -------------------------------------------------------------------------------- 1 | public class InsertionSorting { 2 | 3 | private int[] array; 4 | 5 | public InsertionSorting() { 6 | setArray(); 7 | } 8 | 9 | public static void main(String[] args) { 10 | InsertionSorting is = new InsertionSorting(); 11 | System.out.println("Before Sorting array is"); 12 | is.printTheArray(); 13 | is.sortTheArray(); 14 | System.out.println("After Sorting array is"); 15 | is.printTheArray(); 16 | } 17 | 18 | private void printTheArray() { 19 | for(int i=0; i -1 && array[j] > index) { 33 | array[j + 1] = array[j]; 34 | j--; 35 | } 36 | 37 | array[j + 1] = index; 38 | } 39 | } 40 | 41 | private void setArray() { 42 | int[] a = {72,21,69,38,96,77,30,19,42,55,99}; 43 | array = a; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /algorithms/java/interpolation_sort.java: -------------------------------------------------------------------------------- 1 | public class InterpolationSearch { 2 | 3 | public static int search(int[] numbers, int find) { 4 | int low = 0; 5 | int high = numbers.length - 1; 6 | 7 | while (low <= high && find >= numbers[low] && find <= numbers[high]) { 8 | float result = low + (((float) (find - numbers[low]) / (float) (numbers[high] - numbers[low])) * (float) (high - low)); 9 | int position = (int) result; 10 | 11 | if (find == numbers[position]) 12 | return position; 13 | else if (find < numbers[position]) 14 | high = position - 1; 15 | else 16 | low = position + 1; 17 | } 18 | 19 | return -1; 20 | } 21 | } -------------------------------------------------------------------------------- /algorithms/java/kadane's_algorithm.java: -------------------------------------------------------------------------------- 1 | public class maximum_subarray { 2 | public static int max_contagious_subarray_sum(int[] arr){ 3 | int maximum_so_far=arr[0]; 4 | int maximum_ending_here=arr[0]; 5 | for(int i=1;imaximum_ending_here){ 8 | maximum_ending_here=maximum_so_far; 9 | } 10 | } 11 | return maximum_ending_here; 12 | } 13 | 14 | public static void main(String[] args) { 15 | int[] arr= {-2, -3, 4, -1, -2, 1, 5, -3}; 16 | int max_cont_sub_sum=max_contagious_subarray_sum(arr); 17 | System.out.println(max_cont_sub_sum); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /algorithms/java/krushkal's_algorithm.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | // We use Disjoint Set Union to help us in constructing the MST, and checking cycles in MST 4 | public class KruskalAlgorithm { 5 | static class Edge implements Comparable { 6 | int src, dest, weight; 7 | public Edge(int src, int dest, int weight) { 8 | this.src = src; 9 | this.dest = dest; 10 | this.weight = weight; 11 | } 12 | 13 | @Override 14 | public int compareTo(Edge edge) { 15 | // Function to help sort the edges 16 | return this.weight - edge.weight; 17 | } 18 | } 19 | 20 | public static int findParent(int src, int[] parents) { 21 | // If the parent of any vertex is the vertex itself 22 | // then this is the parent of the vertex of the current edge 23 | if(parents[src] == src) { 24 | return src; 25 | } else { 26 | parents[src] = findParent(parents[src], parents); 27 | return parents[src]; 28 | } 29 | } 30 | 31 | public static void union(int src, int dest, int[] parents, int[] size) { 32 | // Find the parent of both the vertices in the current edge, and merge the disjoint sets 33 | src = findParent(src, parents); 34 | dest = findParent(dest, parents); 35 | if(size[src] > size[dest]) { 36 | parents[dest] = src; 37 | size[src] += size[dest]; 38 | } else { 39 | parents[src] = dest; 40 | size[dest] += size[src]; 41 | } 42 | } 43 | 44 | public static boolean isCyclic(int src, int dest, int[] parents) { 45 | return findParent(src, parents) == findParent(dest, parents); 46 | } 47 | 48 | public static void kruskalAlgo(int nodes, int numEdges, Edge[] edges, int[][] graph) { 49 | // This array is to store the minimum spanning tree formed 50 | int[][] minSpanTree = new int[graph.length][graph.length]; 51 | // Sorting all the edges 52 | Arrays.sort(edges); 53 | 54 | // Parents and size array for creating disjoint sets 55 | int[] parents = new int[nodes+1]; 56 | int[] size = new int[nodes+1]; 57 | for(int i = 1; i < graph.length; i++) { 58 | parents[i] = i; 59 | size[i] = i; 60 | } 61 | 62 | int edgeCounter = 0; 63 | int edgedTaken = 1; 64 | 65 | // For connnecting all nodes, we must have at-least nodes-1 edges 66 | while(edgedTaken <= nodes - 1) { 67 | 68 | Edge e = edges[edgeCounter]; 69 | edgeCounter++; 70 | 71 | // Do not include if, cycle is created 72 | if(isCyclic(e.src, e.dest, parents)) 73 | continue; 74 | 75 | union(findParent(e.src, parents), findParent(e.dest, parents), parents, size); 76 | minSpanTree[e.src][e.dest] = e.weight; 77 | edgedTaken++; 78 | } 79 | 80 | /* Displaying Tree*/ 81 | System.out.println("The minimum spanning tree is as follows:"); 82 | for(int i=1; i { 2 | let start = 0; 3 | let end = arr.length - 1; 4 | let mid = Math.floor((start + end) / 2); 5 | while (arr[mid] !== target && start <= end) { 6 | if (target < arr[mid]) { 7 | end = mid - 1; 8 | } else { 9 | start = mid + 1; 10 | } 11 | mid = Math.floor((start + end) / 2); 12 | } 13 | return arr[mid] === target ? mid : -1; 14 | }; 15 | 16 | const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 17 | console.log(binary_search(arr, 2)); // 1 18 | -------------------------------------------------------------------------------- /algorithms/javascript/bubble_sort.js: -------------------------------------------------------------------------------- 1 | function BubbleSort(arr) { 2 | const sortedArray = Array.from(arr); 3 | let swap; 4 | do { 5 | swap = false; 6 | for (let i = 1; i < sortedArray.length; ++i) { 7 | if (sortedArray[i - 1] > sortedArray[i]) { 8 | [sortedArray[i], sortedArray[i - 1]] = [sortedArray[i - 1], sortedArray[i]]; 9 | swap = true; 10 | } 11 | } 12 | } while (swap) 13 | return sortedArray; 14 | } 15 | -------------------------------------------------------------------------------- /algorithms/javascript/bubble_sort_visualized.js: -------------------------------------------------------------------------------- 1 | var numeros = []; 2 | var x = 0; 3 | var y = 0; 4 | var aux; 5 | var spd; 6 | var slider; 7 | 8 | 9 | function setup() { 10 | createCanvas(800, 600); 11 | for (var i = 0; i < width; i++) { 12 | numeros[i] = new float; 13 | numeros[i] = map(i, 0, width, 0, height); 14 | } 15 | slider = createSlider(0, width, 1, 1); 16 | } 17 | 18 | function draw() { 19 | background(20); 20 | stroke(255); 21 | spd = slider.value(); 22 | 23 | if (keyCode === ENTER) { 24 | for (var i = 0; i < 15; i++) { 25 | var t = floor(random(width)); 26 | var u = floor(random(width)); 27 | var aux = numeros[t]; 28 | numeros[t] = numeros[u]; 29 | numeros[u] = aux; 30 | x = 0; 31 | y = 0; 32 | } 33 | } else { 34 | for (var j = 0; j < spd; j++) { 35 | if (y < width) { 36 | if (x < width - y) { 37 | if (numeros[x] > numeros[x + 1]) { 38 | aux = numeros[x]; 39 | numeros[x] = numeros[x + 1]; 40 | numeros[x + 1] = aux; 41 | } 42 | x++; 43 | } else { 44 | x = 0; 45 | y++; 46 | } 47 | } 48 | } 49 | } 50 | for (var i = 0; i < width; i++) { 51 | line(i, height, i, height - numeros[i]); 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /algorithms/javascript/counting_sort.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Counting Sort Algorithm 3 | * 4 | * Counting sort is a sorting algorithm that sorts the elements of an array by counting 5 | * the number of occurrences of each unique element in the array. 6 | * The count is stored in an auxiliary array and the sorting is done 7 | * by mapping the count as an index of the auxiliary array. 8 | * 9 | * Explanation taken from: https://programiz.com/dsa/counting-sort 10 | * 11 | * @param {Array} list List of integers eg. [3, -12, 7, 2, -9, 1, 0, 14, 9] 12 | */ 13 | 14 | function countingSort(list) { 15 | const min = Math.min(...list); 16 | const max = Math.max(...list); 17 | 18 | let count = []; 19 | let a = min; 20 | let b = 0; 21 | 22 | for (a; a <= max; a++) { 23 | count[a] = 0; 24 | } 25 | 26 | for (a = 0; a < list.length; a++) { 27 | count[list[a]] += 1; 28 | } 29 | 30 | for (a = min; a <= max; a++) { 31 | while (count[a]-- > 0) { 32 | list[b++] = a; 33 | } 34 | } 35 | return list; 36 | } 37 | 38 | /** 39 | * Additional function to create sample array to use counting sort on 40 | * 41 | * @param {Integer} min Minimum Value 42 | * @param {Integer} max Maximum Value 43 | * @param {Integer} length Length of desired array 44 | * @return {Array} List of random integers between min and max 45 | */ 46 | function generateRandomListOfIntegers(min, max, length) { 47 | return Array.from({ length }, () => { 48 | return Math.floor(Math.random() * (max - min + 1)) + min; 49 | }); 50 | } 51 | 52 | let list = generateRandomListOfIntegers(-50, 50, 20); 53 | 54 | console.log("Random list:"); 55 | console.log(list); 56 | 57 | console.log("Sorted list:"); 58 | console.log(countingSort(list)); 59 | -------------------------------------------------------------------------------- /algorithms/javascript/insertion.js: -------------------------------------------------------------------------------- 1 | const array = [100, 5, 60, 3, 1, 2, 7, 9, 10, 4, 6, 8, 11, 12, 13, 14, 15, 16, 17] 2 | 3 | function insertionSort(array) { 4 | let i = 1 5 | 6 | while (i < array.length) { 7 | let j = i 8 | while (j > 0 && array[j - 1] > array[j]) { 9 | let temp = array[j] 10 | array[j] = array[j - 1] 11 | array[j - 1] = temp 12 | j-- 13 | } 14 | i++ 15 | } 16 | 17 | return array 18 | } 19 | 20 | const sortedArray = insertionSort(array) 21 | console.log(sortedArray) // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ..., 100] -------------------------------------------------------------------------------- /algorithms/javascript/linear_search.js: -------------------------------------------------------------------------------- 1 | const linearSearch = (numbers, wanted) => { 2 | for (let number of numbers) 3 | if (number == wanted) return 'I found your number'; 4 | 5 | return 'We didn\'t find your number'; 6 | } 7 | 8 | const numbers = [15, 2, 1, 8, 10, 5, 20, 25]; 9 | const numberSought = 8; 10 | 11 | linearSearch(numbers, numberSought); -------------------------------------------------------------------------------- /algorithms/other/algorithmsInfo.md: -------------------------------------------------------------------------------- 1 | Add any algorithms in this folder you want in any other language language, 2 | which is not mentioned as a folder for more info read the readme in the main repository directory 3 | Thanks... -------------------------------------------------------------------------------- /algorithms/other/kotlin/binary_search.kt: -------------------------------------------------------------------------------- 1 | 2 | package main.algorithms.searching 3 | 4 | fun main(args: Array) { 5 | val input = readLine()!!.trim().split(" ").map { it -> it.toInt() }.toIntArray() // to read an array (from user input) 6 | val eleToSearch = readLine()!!.trim().toInt() // to read the element to be searched (from user input) 7 | val pos = binarySearchIterative(input, eleToSearch) 8 | if(pos >= 0 ) { 9 | println(pos) // to print position at last 10 | } else { 11 | println("Position not found") 12 | } 13 | } 14 | 15 | fun binarySearchIterative(input: IntArray, eleToSearch: Int) : Int{ 16 | var low = 0 17 | var high = input.size-1 18 | var mid:Int 19 | while(low <= high) { 20 | mid = low + ((high - low) / 2) 21 | when { 22 | eleToSearch >input[mid] -> low = mid+1 // element is greater than middle element of array, so it will be in right half of array 23 | eleToSearch == input[mid] -> return mid // found the element 24 | eleToSearch < input[mid] -> high = mid-1 //element is less than middle element of array, so it will be in left half of the array. 25 | } 26 | } 27 | return -1 28 | } -------------------------------------------------------------------------------- /algorithms/other/typescript/binary_search.ts: -------------------------------------------------------------------------------- 1 | const binary_search = (arr: number[], key: number): number => { 2 | let low = 0; 3 | let high = arr.length - 1; 4 | while (low <= high) { 5 | let mid = Math.floor((low + high) / 2); 6 | if (arr[mid] === key) { 7 | return mid; 8 | } 9 | if (arr[mid] < key) { 10 | low = mid + 1; 11 | } else { 12 | high = mid - 1; 13 | } 14 | } 15 | return -1; 16 | }; 17 | 18 | const ar: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 19 | console.log(binary_search(ar, 5)); 20 | -------------------------------------------------------------------------------- /algorithms/other/typescript/bogo_sort.ts: -------------------------------------------------------------------------------- 1 | const checkValues = (arr: number[]) => { 2 | for (let i = arr.length -1; i >= 0; i--) { 3 | if (arr[i - 1] > arr[i]) { 4 | return false; 5 | } 6 | } 7 | return true; 8 | } 9 | 10 | const shuffleValues = (arr: number[]) => { 11 | let temp: number; 12 | let index: number; 13 | for (let i = arr.length; i > 0;) { 14 | index = Math.floor(Math.random() * i); 15 | i--; 16 | temp = arr[i]; 17 | arr[i] = arr[index]; 18 | arr[index] = temp; 19 | } 20 | return arr; 21 | } 22 | 23 | const bogoSortValues = (arr: number[]) => { 24 | let sorted: boolean = checkValues(arr); 25 | while(!sorted) { 26 | arr = shuffleValues(arr); 27 | sorted = checkValues(arr); 28 | } 29 | return arr; 30 | } 31 | 32 | // test case 33 | let testArr: number[]; 34 | testArr = [2, 13 , 1, 4, 5, -1]; 35 | console.log(bogoSortValues(testArr)); -------------------------------------------------------------------------------- /algorithms/other/typescript/counting_sort.ts: -------------------------------------------------------------------------------- 1 | // To be able to use counting sort, the algorithm needs to know the min and max value 2 | const countSort = (arr: number[], min: number, max: number) => { 3 | let i: number; 4 | let z: number = 0; 5 | let count: number[] = []; 6 | 7 | // Find all the instances of each element 8 | for (let i = min; i <= max; i++) { 9 | count[i] = 0; 10 | } 11 | for (let n = 0; n < arr.length; n++) { 12 | count[arr[n]]++; 13 | } 14 | // Modify the entry array and move elements where they should be 15 | for (let m = min; m <= max; m++) { 16 | while (count[m]-- > 0) { 17 | arr[z++] = m; 18 | } 19 | } 20 | return arr; 21 | } 22 | 23 | // test 24 | let test_countSort: number[]; 25 | test_countSort = [2, 13 , 1, 4, 5, -1]; 26 | console.log(countSort(test_countSort, -1, 13)); -------------------------------------------------------------------------------- /algorithms/other/typescript/merge_sort.ts: -------------------------------------------------------------------------------- 1 | const mergeSort = (arr: number[]) => { 2 | if (arr.length < 2) { 3 | return arr; 4 | } 5 | let mid = Math.floor(arr.length / 2); 6 | let left = arr.slice(0, mid); 7 | let right = arr.slice (mid); 8 | return merge(mergeSort(left), mergeSort(right)); 9 | } 10 | 11 | const merge = (l: number[], r: number[]) => { 12 | let result: number[] = []; 13 | while (l.length && r.length) { 14 | if (l[0] <= r[0]) { 15 | result.push(l.shift()); 16 | } 17 | result.push(r.shift()); 18 | } 19 | while (l.length) { 20 | result.push(l.shift()); 21 | } 22 | while (r.length) { 23 | result.push(r.shift()); 24 | } 25 | return result; 26 | } 27 | 28 | // test 29 | let test_mergeSort: number[]; 30 | test_mergeSort = [2, 13 , 1, 4, 5, -1]; 31 | console.log(mergeSort(test_mergeSort)); 32 | -------------------------------------------------------------------------------- /algorithms/python/Dijkstra's_algorithm.py: -------------------------------------------------------------------------------- 1 | global visited_and_distance 2 | 3 | # Function to find out which of the unvisited node 4 | # needs to be visited next 5 | def to_be_visited(number_of_vertices,visited_and_distance): 6 | 7 | v = -10 8 | # Choosing the vertex with the minimum distance 9 | for index in range(number_of_vertices): 10 | if visited_and_distance[index][0] == 0 \ 11 | and (v < 0 or visited_and_distance[index][1] <= \ 12 | visited_and_distance[v][1]): 13 | v = index 14 | return v 15 | 16 | 17 | #Main Function 18 | def Dijkstra(vert,edg): 19 | 20 | import sys 21 | 22 | # Creating the graph as an adjacency matrix 23 | vertices = vert 24 | edges = edg 25 | 26 | number_of_vertices = len(vertices[0]) 27 | 28 | # The first element of the lists inside visited_and_distance 29 | # denotes if the vertex has been visited. 30 | # The second element of the lists inside the visited_and_distance 31 | # denotes the distance from the source. 32 | visited_and_distance = [[0, 0]] 33 | for i in range(number_of_vertices-1): 34 | visited_and_distance.append([0, sys.maxsize]) 35 | 36 | for vertex in range(number_of_vertices): 37 | # Finding the next vertex to be visited. 38 | to_visit = to_be_visited(number_of_vertices,visited_and_distance) 39 | for neighbor_index in range(number_of_vertices): 40 | # Calculating the new distance for all unvisited neighbours 41 | # of the chosen vertex. 42 | if vertices[to_visit][neighbor_index] == 1 and \ 43 | visited_and_distance[neighbor_index][0] == 0: 44 | new_distance = visited_and_distance[to_visit][1] \ 45 | + edges[to_visit][neighbor_index] 46 | # Updating the distance of the neighbor if its current distance 47 | # is greater than the distance that has just been calculated 48 | if visited_and_distance[neighbor_index][1] > new_distance: 49 | visited_and_distance[neighbor_index][1] = new_distance 50 | # Visiting the vertex found earlier 51 | visited_and_distance[to_visit][0] = 1 52 | 53 | i = 0 54 | 55 | # Printing out the shortest distance from the source to each vertex 56 | for distance in visited_and_distance: 57 | print("The shortest distance of ",chr(ord('a') + i),\ 58 | " from the source vertex a is:",distance[1]) 59 | i = i + 1 60 | 61 | print("\nFor graph[(a,b),(a,c),(b,c),(c,d)] where a is the source vertex:\n") 62 | Dijkstra(vert = [[0, 1, 1, 0], 63 | [0, 0, 1, 0], 64 | [0, 0, 0, 1], 65 | [0, 0, 0, 0]], 66 | 67 | edg = [[0, 3, 4, 0], 68 | [0, 0, 0.5, 0], 69 | [0, 0, 0, 1], 70 | [0, 0, 0, 0]]) 71 | 72 | 73 | print("\nFor graph[(a,b),(b,c),(b,d),(c,d),(d,e),(c,e)] where a is the source vertex:\n") 74 | Dijkstra(vert = [[0,1,0,0,0], 75 | [0,0,1,1,0], 76 | [0,0,0,1,1], 77 | [0,0,0,0,1], 78 | [0,0,0,0,0]], 79 | 80 | edg = [[0,4,0,0,0], 81 | [0,0,2,3,0], 82 | [0,0,0,1.5,0.5], 83 | [0,0,0,0,3], 84 | [0,0,0,0,0]]) 85 | -------------------------------------------------------------------------------- /algorithms/python/Kadane's_Algorithm.py: -------------------------------------------------------------------------------- 1 | # KADANE'S ALGORITHM TO FIND MAXIMUM SUBARRAY IN ARRAY 2 | 3 | # Given an integer array nums, we find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. 4 | 5 | def maxSubArray(nums: List[int]) -> int: 6 | if not nums: 7 | return 0 8 | if len(nums)==1: 9 | return nums[0] 10 | if all(x<0 for x in nums): 11 | return max(nums) 12 | max_ending_here = 0 13 | max_so_far = 0 14 | global start 15 | global end 16 | s = 0 17 | for i in range(0,len(nums)): 18 | max_ending_here += nums[i] 19 | if max_ending_here<0: 20 | s = i+1 21 | max_ending_here = 0 22 | if max_so_far= left: 4 | 5 | mid = lelf + (right - left) // 2 6 | 7 | if array[mid] == search: 8 | return mid 9 | 10 | elif array[mid] > search: 11 | return binarySearch(array, lelf, mid-1, search) 12 | 13 | else: 14 | return binarySearch(array, mid + 1, right, search) 15 | 16 | else: 17 | return -1 18 | 19 | array = [ 10, 40, 3, 2, 4, 50] 20 | search = 40 21 | 22 | result = binarySearch(array, 0, len(arr)-1, search) 23 | 24 | if result != -1: 25 | print ("Element is present at index % d" % result) 26 | else: 27 | print ("Element is not present in array") 28 | -------------------------------------------------------------------------------- /algorithms/python/bogo_sort.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | # Sorts array a[0..n-1] using Bogo sort 4 | def bogoSort(a): 5 | n = len(a) 6 | while (is_sorted(a)== False): 7 | shuffle(a) 8 | 9 | # To check if array is sorted or not 10 | def is_sorted(a): 11 | n = len(a) 12 | for i in range(0, n-1): 13 | if (a[i] > a[i+1] ): 14 | return False 15 | return True 16 | 17 | # To generate permutation of the array 18 | def shuffle(a): 19 | n = len(a) 20 | for i in range (0,n): 21 | r = random.randint(0,n-1) 22 | a[i], a[r] = a[r], a[i] 23 | 24 | # Driver code to test above 25 | a = [3, 2, 4, 1, 0, 5] 26 | bogoSort(a) 27 | print("Sorted array :") 28 | for i in range(len(a)): 29 | print ("%d" %a[i]), 30 | -------------------------------------------------------------------------------- /algorithms/python/breadth_first_search.py: -------------------------------------------------------------------------------- 1 | def BFS(graph, s): 2 | # Mark all the vertices as not visited 3 | visited = [False] * len(graph) 4 | 5 | queue = [] 6 | queue.append(s) 7 | visited[s] = True 8 | 9 | while queue: 10 | s = queue.pop(0) 11 | print(s, end=" ") 12 | 13 | for i in graph[s]: 14 | if not visited[i]: 15 | queue.append(i) 16 | visited[i] = True 17 | 18 | 19 | def addEdges(graph, u, v): 20 | graph[u].append(v) 21 | graph[v].append(u) 22 | 23 | 24 | if __name__ == "__main__": 25 | n = int(input("Enter the number of nodes: ")) 26 | m = int(input("Enter the number of edges: ")) 27 | graph = [[] for node in range(n)] 28 | for edge in range(m): 29 | start, end = map(int, input().split()) 30 | addEdges(graph, start, end) 31 | BFS(graph, 0) 32 | -------------------------------------------------------------------------------- /algorithms/python/bubble_sort.py: -------------------------------------------------------------------------------- 1 | def bubbleSort(arr): 2 | n = len(arr) 3 | for i in range(n): 4 | swapped = False 5 | for j in range(0, n-i-1): 6 | if(arr[j+1] < arr[j]): 7 | arr[j+1],arr[j] = arr[j], arr[j+1] 8 | swapped = True 9 | if swapped == False: 10 | break; 11 | 12 | arr = [23, 112, 2, 124, 56, 90, 124, 78, 41, 98] 13 | bubbleSort(arr) 14 | print("Sorted array is: ") 15 | for i in range(len(arr)): 16 | print("%d" %arr[i], end=" ") -------------------------------------------------------------------------------- /algorithms/python/factors.py: -------------------------------------------------------------------------------- 1 | # @author : Pradyumn Rahar 2 | 3 | from math import sqrt 4 | 5 | # Time Complexity: O(sqrt(n)*log(sqrt(n))) | Space Complexity: O(sqrt(n)) 6 | def factors_of_a_number(num: int) -> list: 7 | """ 8 | >>> factors_of_a_number(1) 9 | [1] 10 | >>> factors_of_a_number(5) 11 | [1, 5] 12 | >>> factors_of_a_number(24) 13 | [1, 2, 3, 4, 6, 8, 12, 24] 14 | >>> factors_of_a_number(-24) 15 | [] 16 | """ 17 | facs: list[int] = [] 18 | if num < 1: 19 | return facs 20 | facs.append(1) 21 | if num == 1: 22 | return facs 23 | facs.append(num) 24 | for i in range(2, int(sqrt(num)) + 1): 25 | if num % i == 0: # If i is a factor of num 26 | facs.append(i) 27 | d = num // i # num//i is the other factor of num 28 | if d != i: # If d and i are distinct 29 | facs.append(d) # we have found another factor 30 | facs.sort() 31 | return facs 32 | 33 | 34 | if __name__ == "__main__": 35 | print("Factors of 24:", factors_of_a_number(24)) 36 | -------------------------------------------------------------------------------- /algorithms/python/heap_sort.py: -------------------------------------------------------------------------------- 1 | ########################################################## 2 | #Heap Sort Algorithm in Python - Code by Trusha Talati 3 | ########################################################## 4 | 5 | def heapify(arr, n, i): 6 | largest = i 7 | left_child = 2*i + 1 8 | right_child = 2*i + 2 9 | 10 | if(left_child arr[largest]): 11 | largest = left_child 12 | if(right_child arr[largest]): 13 | largest = right_child 14 | 15 | if largest != i: 16 | arr[largest], arr[i] = arr[i] , arr[largest] 17 | heapify(arr,n,largest) 18 | 19 | def heapsort(arr,n) : 20 | 21 | for i in range(n//2 - 1,-1,-1): #gives max heap 22 | heapify(arr,n,i) 23 | 24 | for i in range(n-1,0,-1): 25 | arr[0] , arr[i] = arr[i] , arr[0] # max element at last ith position 26 | heapify(arr,i,0) # heapify ith elements to have next max at 0th position. 27 | 28 | def main(): 29 | arr = [4, 10, 3, 5, 1] 30 | heapsort(arr,len(arr)) 31 | print("Sorted array -->",arr) 32 | 33 | if __name__ == '__main__': 34 | main() -------------------------------------------------------------------------------- /algorithms/python/insertion_sort.py: -------------------------------------------------------------------------------- 1 | def insertionSort(array): 2 | 3 | for step in range(1, len(array)): 4 | key = array[step] 5 | j = step - 1 6 | 7 | # Compare key with each element on the left of it until an element smaller than it is found 8 | # For descending order, change keyarray[j]. 9 | while j >= 0 and key < array[j]: 10 | array[j + 1] = array[j] 11 | j = j - 1 12 | 13 | # Place key at after the element just smaller than it. 14 | array[j + 1] = key 15 | 16 | 17 | data = [9, 5, 1, 4, 3] 18 | insertionSort(data) 19 | print('Sorted Array in Ascending Order:') 20 | print(data) -------------------------------------------------------------------------------- /algorithms/python/krushal's_minimum_spanning_tree.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | 3 | 4 | class Graph: 5 | def __init__(self, vertices): 6 | self.V = vertices 7 | self.graph = [] 8 | 9 | def addEdge(self, u, v, w): 10 | self.graph.append([u, v, w]) 11 | 12 | def find(self, parent, i): 13 | if(parent[i] == i): 14 | return i 15 | return self.find(parent, parent[i]) 16 | 17 | def union(self, parent, rank, x, y): 18 | xroot = self.find(parent, x) 19 | yroot = self.find(parent, y) 20 | if(rank[xroot] < rank[yroot]): 21 | parent[xroot] = yroot 22 | elif(rank[xroot] > rank[yroot]): 23 | parent[yroot] = xroot 24 | else: 25 | parent[yroot] = xroot 26 | rank[xroot] += 1 27 | 28 | def KruskalMST(self): 29 | result = [] 30 | i = 0 31 | e = 0 32 | self.graph = sorted(self.graph, key=lambda item: item[2]) 33 | parent, rank = [], [] 34 | for node in range(self.V): 35 | parent.append(node) 36 | rank.append(0) 37 | while(e < self.V-1): 38 | u, v, w = self.graph[i] 39 | i += 1 40 | x = self.find(parent, u) 41 | y = self.find(parent, v) 42 | if(x != y): 43 | e += 1 44 | result.append([u, v, w]) 45 | self.union(parent, rank, x, y) 46 | print("Following are the edges in the constructed MST") 47 | for u, v, weight in result: 48 | print("%d -- %d == %d" % (u, v, weight)) 49 | 50 | 51 | g = Graph(4) 52 | g.addEdge(0, 1, 10) 53 | g.addEdge(0, 2, 6) 54 | g.addEdge(0, 3, 5) 55 | g.addEdge(1, 3, 15) 56 | g.addEdge(2, 3, 4) 57 | g.KruskalMST() 58 | -------------------------------------------------------------------------------- /algorithms/python/linear_search.py: -------------------------------------------------------------------------------- 1 | ########################################################## 2 | #Linear Search Algorithm in Python - Code by Kavyapriya R 3 | ########################################################## 4 | def linear_search(alist, key): 5 | """Return index of key in alist. Return -1 if key not present.""" 6 | for i in range(len(alist)): 7 | if alist[i] == key: 8 | return i 9 | return -1 10 | 11 | 12 | alist = input('Enter the list of numbers: ') 13 | alist = alist.split() 14 | alist = [int(x) for x in alist] 15 | key = int(input('The number to search for: ')) 16 | 17 | index = linear_search(alist, key) 18 | if index < 0: 19 | print('{} was not found.'.format(key)) 20 | else: 21 | print('{} was found at index {}.'.format(key, index)) 22 | -------------------------------------------------------------------------------- /algorithms/python/merge_sort.py: -------------------------------------------------------------------------------- 1 | def merge_lists(left, right): 2 | i, j = 0, 0 3 | result = [] 4 | 5 | while i < len(left) and j < len(right): 6 | if left[i] <= right[j]: 7 | result.append(left[i]) 8 | i += 1 9 | else: 10 | result.append(right[j]) 11 | j += 1 12 | 13 | result += left[i:] 14 | result += right[j:] 15 | 16 | return result 17 | 18 | 19 | def merge_sort(list): 20 | if len(list) <= 1: 21 | return list 22 | else: 23 | midpoint = int(len(list) / 2) 24 | left = merge_sort(list[:midpoint]) 25 | right = merge_sort(list[midpoint:]) 26 | return merge_lists(left, right) 27 | 28 | number_list = [5, 12, 31, 7, 234, 7, 1, 9, 3, 4, 634, 1, 0, 65, 234, 9] 29 | print(merge_sort(number_list)) -------------------------------------------------------------------------------- /algorithms/python/quick_sort.py: -------------------------------------------------------------------------------- 1 | def quickSort(arr): 2 | 3 | # Base case 4 | if len(arr) < 2: 5 | return arr 6 | 7 | curr = 0 # Position of the partitioning element 8 | 9 | for i in range(1, len(arr)): # Partitioning loop 10 | if arr[i] <= arr[0]: 11 | curr += 1 12 | temp = arr[i] 13 | arr[i] = arr[curr] 14 | arr[curr] = temp 15 | 16 | temp = arr[0] 17 | arr[0] = arr[curr] 18 | arr[curr] = temp # Brings pivot to it's appropriate position 19 | 20 | left = quickSort(arr[0:curr]) 21 | right = quickSort(arr[curr+1:len(arr)]) 22 | 23 | arr = left + [arr[curr]] + right # Merging everything together 24 | 25 | return arr 26 | 27 | def main(): 28 | arr = [4, 2, 7, 3, 1, 6] 29 | arr = quickSort([4, 2, 7, 3, 1, 6]) 30 | print("Sorted array -->",arr) 31 | 32 | if __name__ == '__main__': 33 | main() -------------------------------------------------------------------------------- /data structures/c-sharp/dsInfo.md: -------------------------------------------------------------------------------- 1 | Add any data structure implementation in this folder you want in c# language. for more info read the readme in the main repository directory 2 | Thanks... -------------------------------------------------------------------------------- /data structures/cpp/BST.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | struct Node { 7 | int data; 8 | Node* left; 9 | Node* right; 10 | }; 11 | 12 | Node* Insert(Node* root, int data) { 13 | if(root == NULL) { 14 | Node* node = new Node(); 15 | node->data = data; 16 | node->left = node->right = NULL; 17 | return node; 18 | }else if(data <= root->data) { 19 | root->left = Insert(root->left, data); 20 | }else { 21 | root->right = Insert(root->right, data); 22 | } 23 | return root; 24 | } 25 | 26 | struct Node* Delete(struct Node *root, int data) { 27 | if(root == NULL) return root; 28 | else if(data < root->data) root->left = Delete(root->left, data); 29 | else if(data > root->data) root->right = Delete(root->right, data); 30 | else { 31 | //now the root may have zero child means its a leaf node. 32 | //may have one child or two child... 33 | //lets handle those cases... 34 | 35 | //Case 1: 0 - child(leaf node). 36 | if(root->left == NULL && root->right == NULL) { 37 | delete root; 38 | root = NULL; 39 | } 40 | //Case 2: 1 - child. 41 | else if(root->left == NULL) { 42 | struct Node *temp = root; 43 | root = root->right; 44 | delete temp; 45 | }else if(root->right == NULL) { 46 | struct Node *temp = root; 47 | root = root->left; 48 | delete temp; 49 | } 50 | //Case 3: 2 - child. 51 | else { 52 | struct Node *temp = root->right; 53 | root->data = temp->data; 54 | root->right = Delete(root->right, temp->data); 55 | } 56 | } 57 | return root; 58 | } 59 | 60 | bool search(Node* root, int data) { 61 | if(root == NULL) return false; 62 | else if(root->data == data) { 63 | return true; 64 | } 65 | else if(data <= root->data){ 66 | cout << "/ "; 67 | return search(root->left, data); 68 | } 69 | else{ 70 | cout << "\\ "; 71 | return search(root->right, data); 72 | } 73 | } 74 | 75 | int height(struct Node *root) { 76 | if(root == NULL) return -1; 77 | return max(height(root->left), height(root->right)) + 1; 78 | } 79 | 80 | void LevelOrderTraversal(Node *root) { 81 | if(root == NULL) return; 82 | queue q; 83 | q.push(root); 84 | while(!q.empty()) { 85 | Node* current = q.front(); 86 | if(current->left != NULL) { 87 | q.push(current->left); 88 | } 89 | if(current->right != NULL) { 90 | q.push(current->right); 91 | } 92 | cout << current->data << " "; 93 | q.pop(); 94 | } 95 | cout << endl; 96 | } 97 | 98 | void PreOrderTraversal(Node *root) { 99 | if(root == NULL) return; 100 | cout << root->data << " "; 101 | PreOrderTraversal(root->left); 102 | PreOrderTraversal(root->right); 103 | } 104 | 105 | //this prints elements in acsending order... 106 | void InOrder(Node *root) { 107 | if(root == NULL) return; 108 | InOrder(root->left); 109 | cout << root->data << " "; 110 | InOrder(root->right); 111 | } 112 | 113 | void PostOrder(Node *root) { 114 | if(root == NULL) return; 115 | PostOrder(root->left); 116 | PostOrder(root->right); 117 | cout << root->data << " "; 118 | } 119 | 120 | int main() { 121 | Node* root = NULL; 122 | 123 | root = Insert(root, 15); 124 | root = Insert(root, 10); 125 | root = Insert(root, 20); 126 | root = Insert(root, 25); 127 | root = Insert(root, 8); 128 | root = Insert(root, 12); 129 | root = Insert(root, 18); 130 | root = Insert(root, 2); 131 | root = Insert(root, 9); 132 | root = Insert(root, 30); 133 | root = Insert(root, 1); 134 | root = Insert(root, 0); 135 | root = Insert(root, 19); 136 | root = Insert(root, 16); 137 | root = Insert(root, 17); 138 | 139 | cout << "LevelOrderTraversal : "; 140 | LevelOrderTraversal(root); 141 | cout << "PreOrderTraversal : "; 142 | PreOrderTraversal(root); 143 | cout << endl; 144 | cout << "InOrder : "; 145 | InOrder(root); 146 | cout << endl; 147 | cout << "PostOrderTraversal : "; 148 | PostOrder(root); 149 | cout << endl; 150 | return 0; 151 | } 152 | -------------------------------------------------------------------------------- /data structures/cpp/Doubly_linked_list.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | struct node *tail = NULL; 4 | //creating node for doubly linked list 5 | class node 6 | { 7 | public: 8 | int data; 9 | struct node *prev; 10 | struct node *next; 11 | }; 12 | //functionto create ll 13 | struct node *create_dll(struct node *head) 14 | { 15 | struct node *newnode = new struct node; 16 | newnode->next = NULL; 17 | newnode->prev = NULL; 18 | cin >> newnode->data; 19 | tail = newnode; 20 | if (head == NULL) 21 | { 22 | return newnode; 23 | } 24 | else 25 | { 26 | struct node *p = head; 27 | while (p->next != NULL) 28 | { 29 | p = p->next; 30 | } 31 | newnode->prev = p; 32 | p->next = newnode; 33 | return head; 34 | } 35 | } 36 | //function to insert node at head 37 | struct node *insert_at_beg_in_dll(struct node *head) 38 | { 39 | struct node *newnode = new struct node; 40 | newnode->next = NULL; 41 | newnode->prev = NULL; 42 | cin >> newnode->data; 43 | if (head == NULL) 44 | { 45 | return newnode; 46 | } 47 | else 48 | { 49 | head->prev = newnode; 50 | newnode->next = head; 51 | head = newnode; 52 | return head; 53 | } 54 | } 55 | //function to to insert element at end 56 | struct node *insert_at_end_in_dll(struct node *head) 57 | { 58 | struct node *newnode = new struct node; 59 | newnode->next = NULL; 60 | newnode->prev = NULL; 61 | cin >> newnode->data; 62 | tail = newnode; 63 | if (head == NULL) 64 | { 65 | return newnode; 66 | } 67 | else 68 | { 69 | struct node *p = head; 70 | while (p->next != NULL) 71 | { 72 | p = p->next; 73 | } 74 | p->next = newnode; 75 | newnode->prev = p; 76 | return head; 77 | } 78 | } 79 | //display in forward direction 80 | void display_forward_dll(struct node *head) 81 | { 82 | while (head != NULL) 83 | { 84 | cout << head->data << " "; 85 | head = head->next; 86 | } 87 | } 88 | //display in reverse order 89 | void display_backward_dll() 90 | { 91 | struct node *end = tail; 92 | while (end != NULL) 93 | { 94 | cout << end->data << " "; 95 | end = end->prev; 96 | } 97 | } 98 | //main function 99 | int main() 100 | { 101 | struct node *head = NULL; 102 | int t = 1, n; 103 | int w; 104 | while (t) 105 | { 106 | cout << "\nSelect choice\n1)create dll\n2)insert at beg\n3)insert at end\n4)display forward\n5)display reverse\nEnter: "; 107 | cin >> w; 108 | switch (w) 109 | { 110 | case 1: 111 | cout << "\nEnter number of data elemenets in the dll: "; 112 | cin >> n; 113 | while (n--) 114 | { 115 | head = create_dll(head); 116 | } 117 | break; 118 | case 2: 119 | head = insert_at_beg_in_dll(head); 120 | cout << "\n"; 121 | break; 122 | case 3: 123 | head = insert_at_end_in_dll(head); 124 | cout << "\n"; 125 | break; 126 | case 4: 127 | cout << "\n"; 128 | display_forward_dll(head); 129 | cout << "\n"; 130 | break; 131 | case 5: 132 | cout << "\n"; 133 | display_backward_dll(); 134 | cout << "\n"; 135 | break; 136 | default: 137 | cout << "\nWrong choice!\n"; 138 | } 139 | cout << "(1/0): "; 140 | cin >> t; 141 | } 142 | return 0; 143 | } -------------------------------------------------------------------------------- /data structures/cpp/LinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | char* readline(); 12 | 13 | // Complete the utopianTree function below. 14 | int utopianTree(int n) 15 | { 16 | int sum=1; 17 | for(int i=1;i<=n;i++) 18 | { 19 | if(i%2==0) 20 | { 21 | sum=sum+1; 22 | } 23 | else 24 | { 25 | sum=sum*2; 26 | } 27 | } 28 | return sum; 29 | } 30 | 31 | int main() 32 | { 33 | FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w"); 34 | 35 | char* t_endptr; 36 | char* t_str = readline(); 37 | int t = strtol(t_str, &t_endptr, 10); 38 | 39 | if (t_endptr == t_str || *t_endptr != '\0') { exit(EXIT_FAILURE); } 40 | 41 | for (int t_itr = 0; t_itr < t; t_itr++) { 42 | char* n_endptr; 43 | char* n_str = readline(); 44 | int n = strtol(n_str, &n_endptr, 10); 45 | 46 | if (n_endptr == n_str || *n_endptr != '\0') { exit(EXIT_FAILURE); } 47 | 48 | int result = utopianTree(n); 49 | 50 | fprintf(fptr, "%d\n", result); 51 | } 52 | 53 | fclose(fptr); 54 | 55 | return 0; 56 | } 57 | 58 | char* readline() { 59 | size_t alloc_length = 1024; 60 | size_t data_length = 0; 61 | char* data = malloc(alloc_length); 62 | 63 | while (true) { 64 | char* cursor = data + data_length; 65 | char* line = fgets(cursor, alloc_length - data_length, stdin); 66 | 67 | if (!line) { break; } 68 | 69 | data_length += strlen(cursor); 70 | 71 | if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { break; } 72 | 73 | size_t new_length = alloc_length << 1; 74 | data = realloc(data, new_length); 75 | 76 | if (!data) { break; } 77 | 78 | alloc_length = new_length; 79 | } 80 | 81 | if (data[data_length - 1] == '\n') { 82 | data[data_length - 1] = '\0'; 83 | } 84 | 85 | data = realloc(data, data_length); 86 | 87 | return data; 88 | } 89 | -------------------------------------------------------------------------------- /data structures/cpp/Queue: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sobhanbera/algorithms/9f2386ec573929177472b8888706fff7bee1f217/data structures/cpp/Queue -------------------------------------------------------------------------------- /data structures/cpp/Queue.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | // Define the default capacity of a queue 6 | #define SIZE 1000 7 | 8 | // A class to store a queue 9 | class Queue 10 | { 11 | int *arr; // array to store queue elements 12 | int capacity; // maximum capacity of the queue 13 | int front; // front points to the front element in the queue (if any) 14 | int rear; // rear points to the last element in the queue 15 | int count; // current size of the queue 16 | 17 | public: 18 | Queue(int size = SIZE); // constructor 19 | ~Queue(); // destructor 20 | 21 | int dequeue(); 22 | void enqueue(int x); 23 | int peek(); 24 | int size(); 25 | bool isEmpty(); 26 | bool isFull(); 27 | }; 28 | 29 | // Constructor to initialize a queue 30 | Queue::Queue(int size) 31 | { 32 | arr = new int[size]; 33 | capacity = size; 34 | front = 0; 35 | rear = -1; 36 | count = 0; 37 | } 38 | 39 | // Destructor to free memory allocated to the queue 40 | Queue::~Queue() { 41 | delete[] arr; 42 | } 43 | 44 | // Utility function to dequeue the front element 45 | int Queue::dequeue() 46 | { 47 | // check for queue underflow 48 | if (isEmpty()) 49 | { 50 | cout << "Underflow\nProgram Terminated\n"; 51 | exit(EXIT_FAILURE); 52 | } 53 | 54 | int x = arr[front]; 55 | cout << "Removing " << x << endl; 56 | 57 | front = (front + 1) % capacity; 58 | count--; 59 | 60 | return x; 61 | } 62 | 63 | // Utility function to add an item to the queue 64 | void Queue::enqueue(int item) 65 | { 66 | // check for queue overflow 67 | if (isFull()) 68 | { 69 | cout << "Overflow\nProgram Terminated\n"; 70 | exit(EXIT_FAILURE); 71 | } 72 | 73 | cout << "Inserting " << item << endl; 74 | 75 | rear = (rear + 1) % capacity; 76 | arr[rear] = item; 77 | count++; 78 | } 79 | 80 | // Utility function to return the front element of the queue 81 | int Queue::peek() 82 | { 83 | if (isEmpty()) 84 | { 85 | cout << "Underflow\nProgram Terminated\n"; 86 | exit(EXIT_FAILURE); 87 | } 88 | return arr[front]; 89 | } 90 | 91 | // Utility function to return the size of the queue 92 | int Queue::size() { 93 | return count; 94 | } 95 | 96 | // Utility function to check if the queue is empty or not 97 | bool Queue::isEmpty() { 98 | return (size() == 0); 99 | } 100 | 101 | // Utility function to check if the queue is full or not 102 | bool Queue::isFull() { 103 | return (size() == capacity); 104 | } 105 | 106 | int main() 107 | { 108 | // create a queue of capacity 5 109 | Queue q(5); 110 | 111 | q.enqueue(1); 112 | q.enqueue(2); 113 | q.enqueue(3); 114 | 115 | cout << "The front element is " << q.peek() << endl; 116 | q.dequeue(); 117 | 118 | q.enqueue(4); 119 | 120 | cout << "The queue size is " << q.size() << endl; 121 | 122 | q.dequeue(); 123 | q.dequeue(); 124 | q.dequeue(); 125 | 126 | if (q.isEmpty()) { 127 | cout << "The queue is empty\n"; 128 | } 129 | else { 130 | cout << "The queue is not empty\n"; 131 | } 132 | 133 | return 0; 134 | } -------------------------------------------------------------------------------- /data structures/cpp/Trie.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | struct Trie 4 | { 5 | Trie *nghbr[26]; 6 | bool end; 7 | Trie() 8 | { 9 | for (int i = 0; i < 26; ++i) 10 | nghbr[i] = NULL; 11 | 12 | end = false; 13 | }; 14 | void insert(string s) 15 | { 16 | Trie *cur = this; 17 | int idx; 18 | for (char X : s) 19 | { 20 | idx = X - 'a'; 21 | if (cur->nghbr[idx] == NULL) 22 | { 23 | cur->nghbr[idx] = new Trie(); 24 | } 25 | cur = cur->nghbr[idx]; 26 | }; 27 | cur->end = true; 28 | } 29 | bool search(string k) 30 | { 31 | Trie *cur = this; 32 | int idx; 33 | 34 | for (char X : k) 35 | { 36 | idx = X - 'a'; 37 | if (cur->nghbr[idx] == NULL) 38 | return false; 39 | cur = cur->nghbr[idx]; 40 | } 41 | 42 | return cur->end; 43 | }; 44 | }; 45 | int main() 46 | { 47 | vector A, toSearch; 48 | A = {"apple", "water", "bat", "app", "ball"}; 49 | toSearch = {"ball", "watch", "water", "watep", "apz", "app"}; 50 | Trie *trie = new Trie(); 51 | for (string s : A) 52 | trie->insert(s); 53 | vector ans; 54 | 55 | for (string s : toSearch) 56 | { 57 | 58 | cout << "\n\t" << s << '\t'; 59 | if (trie->search(s)) 60 | cout << "FOUND"; 61 | else 62 | { 63 | cout << "NOT FOUND"; 64 | } 65 | } 66 | cout<<"\n\n"; 67 | return 0; 68 | } 69 | -------------------------------------------------------------------------------- /data structures/cpp/dsInfo.md: -------------------------------------------------------------------------------- 1 | Add any data structure implementation in this folder you want in C++ language. for more info read the readme in the main repository directory 2 | Thanks... -------------------------------------------------------------------------------- /data structures/cpp/heap.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | //C++ program Heap Implementation (Max-Heap) 4 | 5 | #include 6 | #include 7 | 8 | using namespace std; 9 | 10 | //Swap position of two numbers with eachother 11 | void swapNode(int *firstNumber, int *secondNumber){ 12 | 13 | int temporaryNumber = *secondNumber; 14 | *secondNumber = *firstNumber; 15 | *firstNumber = temporaryNumber; 16 | 17 | } 18 | 19 | //Performs heap operations to make largest number at root(top) position 20 | void heapify( vector &heapArray, int maxNumberIndex){ 21 | 22 | int heapSize = heapArray.size(); //Size of heap 23 | int rootIndex = maxNumberIndex; //Index of parent node 24 | int leftIndex = 2 * rootIndex + 1; //Index of left node 25 | int rightIndex = 2* rootIndex + 2; //Index of right node 26 | 27 | 28 | //If number at left node is greater than parent node 29 | //Change root index to index of left node 30 | if(leftIndex < heapSize && heapArray[leftIndex] > heapArray[rootIndex]){ 31 | rootIndex = leftIndex; 32 | } 33 | 34 | 35 | //If number at right node is greater than parent node 36 | //Change root index to index of right node 37 | if( rightIndex < heapSize && heapArray[rightIndex] > heapArray[rootIndex]){ 38 | rootIndex = rightIndex; 39 | } 40 | 41 | 42 | //If root index is not same as number index 43 | //Swap numbers and perform heapify 44 | if( rootIndex != maxNumberIndex){ 45 | 46 | swapNode( &heapArray[maxNumberIndex], &heapArray[rootIndex] ); 47 | heapify( heapArray, rootIndex); 48 | 49 | } 50 | } 51 | 52 | 53 | //Insert new node in heap array 54 | void insertNode( vector &heapArray, int newNumber ){ 55 | 56 | int heapSize = heapArray.size(); //Size of heap 57 | 58 | //If no element in heap 59 | if(heapSize == 0){ 60 | 61 | heapArray.push_back(newNumber); 62 | } 63 | 64 | else{ 65 | 66 | heapArray.push_back(newNumber); //Insert new node 67 | 68 | //Perform heapify 69 | for(int i= heapSize/2 -1; i>=0; i--){ 70 | 71 | heapify(heapArray, i); 72 | 73 | } 74 | } 75 | } 76 | 77 | //Delete node from heap array 78 | void deleteNode(vector &heapArray, int removeNumber){ 79 | 80 | int heapSize = heapArray.size(); //Size of heap 81 | int nodeIndex; 82 | 83 | //Find index node to be removed 84 | for(int i=0; i=0; i--){ 100 | 101 | heapify(heapArray, i); 102 | } 103 | } 104 | 105 | 106 | //Print heap array 107 | void displayHeap(vector &heapArray){ 108 | 109 | //Visit each node in heap 110 | for(int i=0; i heapTree; //Stores heap array 121 | 122 | int newNumber; 123 | char response; 124 | 125 | x: 126 | cout<<"\nEnter a number to insert: "; 127 | cin>>newNumber; 128 | 129 | insertNode(heapTree, newNumber); //Perform insertion 130 | 131 | cout<<"Want to insert more number (press 'Y' or 'N'): "; 132 | cin>>response; 133 | 134 | //Send controls to x: if user want to insert more number 135 | if(response == 'Y' || response == 'y'){ 136 | 137 | goto x; 138 | } 139 | 140 | //Display heap after insertion 141 | cout<<"\nMax-Heap Array is:"; 142 | displayHeap(heapTree); 143 | 144 | y: 145 | cout<<"\nEnter a number to delete: "; 146 | cin>>newNumber; 147 | 148 | deleteNode(heapTree, newNumber); //Perform deletion 149 | 150 | cout<<"Want to delete more number (press 'Y' or 'N'): "; 151 | cin>>response; 152 | 153 | //Send controls to y: if user want to delete more number 154 | if(response == 'Y' || response == 'y'){ 155 | goto y; 156 | } 157 | 158 | //Display heap after deletion 159 | cout<<"\nMax-Heap Array is:"; 160 | displayHeap(heapTree); 161 | 162 | } -------------------------------------------------------------------------------- /data structures/cpp/reverseStack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | void insertAtBottom(stack &s, int element) { 6 | // base class 7 | if(s.empty()) { 8 | s.push(element); 9 | return; 10 | } 11 | 12 | int num = s.top(); 13 | s.pop(); 14 | 15 | // recursive call 16 | insertAtBottom(s, element); 17 | s.push(num); // push 18 | 19 | } 20 | 21 | void reverseStack(stack &stack) { 22 | // base class 23 | if(stack.empty()) { 24 | return; 25 | } 26 | 27 | int num = stack.top(); 28 | stack.pop(); 29 | // recursive call 30 | reverseStack(stack); 31 | 32 | insertAtBottom(stack, num); 33 | } 34 | -------------------------------------------------------------------------------- /data structures/cpp/union_find_disjoint_sets.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | Maintain a set of elements partitioned into non-overlapping subsets. Each 3 | partition is assigned a unique representative known as the parent, or root. The 4 | following implements two well-known optimizations known as union-by-size and 5 | path compression. This version is simplified to only work on integer elements. 6 | 7 | - find_set(u) returns the unique representative of the partition containing u. 8 | - same_set(u, v) returns whether elements u and v belong to the same partition. 9 | - union_set(u, v) replaces the partitions containing u and v with a single new 10 | partition consisting of the union of elements in the original partitions. 11 | 12 | Time Complexity: 13 | - O(a(n)) per call to find_set(), same_set(), and union_set(), where n is the 14 | number of elements, and a(n) is the extremely slow growing inverse of the Ackermann function 15 | (effectively a very small constant for all practical values of n). 16 | 17 | Space Complexity: 18 | - O(n) for storage of the disjoint set forest elements. 19 | - O(1) auxiliary for all operations. 20 | **/ 21 | 22 | #include 23 | 24 | using namespace std; 25 | 26 | class UnionFind { 27 | vector par; 28 | vector siz; 29 | int num_sets; 30 | size_t sz; 31 | 32 | public: 33 | UnionFind() : par(1, -1), siz(1, 1), num_sets(0), sz(0) {} 34 | UnionFind(int n) : par(n + 1, -1), siz(n + 1, 1), num_sets(n), sz(n) {} 35 | 36 | int find_set(int u) { 37 | assert(u <= sz); 38 | 39 | int leader; 40 | for(leader = u; ~par[leader]; leader = par[leader]); 41 | 42 | for(int next = par[u]; u != leader; next = par[next]) { 43 | par[u] = leader; 44 | u = next; 45 | } 46 | return leader; 47 | } 48 | 49 | bool same_set(int u, int v) { 50 | return find_set(u) == find_set(v); 51 | } 52 | 53 | bool union_set(int u, int v) { 54 | if(same_set(u, v)) return false; 55 | 56 | int x = find_set(u); 57 | int y = find_set(v); 58 | 59 | if(siz[x] < siz[y]) swap(x, y); 60 | 61 | par[y] = x; 62 | siz[x] += siz[y]; 63 | 64 | --num_sets; 65 | return true; 66 | } 67 | 68 | int number_of_sets() { 69 | return num_sets; 70 | } 71 | 72 | int size_of_set(int u) { 73 | return siz[find_set(u)]; 74 | } 75 | 76 | size_t size() { 77 | return sz; 78 | } 79 | 80 | void clear() { 81 | par.clear(); 82 | siz.clear(); 83 | sz = num_sets = 0; 84 | } 85 | 86 | void assign(size_t n) { 87 | par.assign(n + 1, -1); 88 | siz.assign(n + 1, 1); 89 | sz = num_sets = n; 90 | } 91 | 92 | map < int, vector > groups(int st) { 93 | map < int, vector > ret; 94 | 95 | for(size_t i = st; i < sz + st; ++i) 96 | ret[find_set(i)].push_back(i); 97 | 98 | return ret; 99 | } 100 | }; 101 | 102 | int main() { 103 | pair ar[] = {{3, 2}, {6, 7}, {7, 5}, {9, 4}, {8, 1}}; 104 | int sz = sizeof(ar) / sizeof(ar[0]); 105 | // max element in the array 106 | UnionFind uf(9); 107 | 108 | for(int i = 0; i < sz; ++i) 109 | if(!uf.same_set(ar[i].first, ar[i].second)) 110 | uf.union_set(ar[i].first, ar[i].second); 111 | 112 | map > sets = uf.groups(1); 113 | for(auto parent : sets) { 114 | cout << parent.first << ": "; 115 | for(auto i : parent.second) 116 | cout << i << " "; 117 | cout << endl; 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /data structures/java/BST.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | 4 | class Node { 5 | Node left, right; 6 | int data; 7 | Node(int data) { 8 | this.data = data; 9 | left = right = null; 10 | } 11 | } 12 | 13 | class Solution { 14 | /* We define a 1-Node tree to have height of 0 */ 15 | public static int getHeight(Node root) { 16 | if (root == null) { 17 | return -1; 18 | } else { 19 | return 1 + Math.max(getHeight(root.left), getHeight(root.right)); 20 | } 21 | } 22 | 23 | public static Node insert(Node root, int data) { 24 | if (root == null) { 25 | return new Node(data); 26 | } else { 27 | Node cur; 28 | if (data <= root.data) { 29 | cur = insert(root.left, data); 30 | root.left = cur; 31 | } else { 32 | cur = insert(root.right, data); 33 | root.right = cur; 34 | } 35 | return root; 36 | } 37 | } 38 | 39 | public static void main(String args[]) { 40 | Scanner sc = new Scanner(System.in); 41 | int T = sc.nextInt(); 42 | Node root = null; 43 | while (T-- > 0) { 44 | int data = sc.nextInt(); 45 | root = insert(root,data); 46 | } 47 | int height = getHeight(root); 48 | System.out.println(height); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /data structures/java/dsInfo.md: -------------------------------------------------------------------------------- 1 | Add any data structure implementation in this folder you want in java language. for more info read the readme in the main repository directory 2 | Thanks... -------------------------------------------------------------------------------- /data structures/java/dynamic_list.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class DynamicList { 4 | 5 | public static Scanner sc = new Scanner(System.in); 6 | public static void main(String [] args) throws Exception{ 7 | 8 | List list = new List(); 9 | 10 | list.insertEnd(3); 11 | list.insertBegin(0); 12 | list.insert(1, 1); 13 | list.insert(2, 2); 14 | list.insertEnd(5); 15 | 16 | list.print(); 17 | 18 | list.remove(4); 19 | 20 | list.print(); 21 | 22 | } 23 | 24 | } 25 | 26 | class Cell { 27 | 28 | public int element; 29 | public Cell next; 30 | 31 | public Cell(){ 32 | this(0); 33 | } 34 | 35 | public Cell(int element) { 36 | this.element = element; 37 | this.next = null; 38 | } 39 | } 40 | 41 | class List { 42 | 43 | private Cell first; 44 | private Cell last; 45 | 46 | public List() { 47 | first = new Cell(); 48 | last = first; 49 | } 50 | 51 | public void insertBegin(int x) { 52 | Cell tmp = new Cell(x); 53 | tmp.next = first.next; 54 | first.next = tmp; 55 | if (first == last) { 56 | last = tmp; 57 | } 58 | tmp = null; 59 | } 60 | 61 | public void insertEnd(int x) { 62 | last.next = new Cell(x); 63 | last = last.next; 64 | } 65 | 66 | public int removeBegin() throws Exception { 67 | 68 | if (first == last) { 69 | throw new Exception("Error! List is empty!"); 70 | } 71 | 72 | Cell tmp = first; 73 | first = first.next; 74 | int resp = first.element; 75 | tmp.next = null; 76 | tmp = null; 77 | 78 | return resp; 79 | } 80 | 81 | 82 | public int removeEnd() throws Exception { 83 | 84 | if (first == last) { 85 | throw new Exception("Error! List is empty!"); 86 | } 87 | 88 | Cell i; 89 | for(i = first; i.next != last; i = i.next); 90 | 91 | int resp = last.element; 92 | last = i; 93 | i = last.next = null; 94 | 95 | return resp; 96 | } 97 | 98 | public void insert(int x, int pos) throws Exception { 99 | 100 | int size = size(); 101 | 102 | if(pos < 0 || pos > size){ 103 | throw new Exception("Error! Position (" + pos + " / size = " + size + ") invalid!"); 104 | } else if (pos == 0){ 105 | insertBegin(x); 106 | } else if (pos == size){ 107 | insertEnd(x); 108 | } else { 109 | Cell i = first; 110 | for(int j = 0; j < pos; j++, i = i.next); 111 | 112 | Cell tmp = new Cell(x); 113 | tmp.next = i.next; 114 | i.next = tmp; 115 | tmp = i = null; 116 | } 117 | } 118 | 119 | public int remove(int pos) throws Exception { 120 | 121 | int resp; 122 | int size = size(); 123 | 124 | if (first == last){ 125 | throw new Exception("Error! List is empty!"); 126 | 127 | } else if(pos < 0 || pos >= size){ 128 | throw new Exception("Error! Position (" + pos + " / size = " + size + ") invalid!"); 129 | } else if (pos == 0){ 130 | resp = removeBegin(); 131 | } else if (pos == size - 1){ 132 | resp = removeEnd(); 133 | } else { 134 | Cell i = first; 135 | for(int j = 0; j < pos; j++, i = i.next); 136 | 137 | Cell tmp = i.next; 138 | resp = tmp.element; 139 | i.next = tmp.next; 140 | tmp.next = null; 141 | i = tmp = null; 142 | } 143 | 144 | return resp; 145 | } 146 | 147 | public void print() { 148 | 149 | int position = 0; 150 | 151 | for (Cell i = first.next; i != null; i = i.next) { 152 | 153 | System.out.print("[" +position+ "]" + i.element + " "); 154 | position++; 155 | } 156 | 157 | System.out.println(); 158 | } 159 | 160 | public int size() { 161 | int size = 0; 162 | for(Cell i = first; i != last; i = i.next, size++); 163 | return size; 164 | } 165 | 166 | } -------------------------------------------------------------------------------- /data structures/java/queue_using_stack.java: -------------------------------------------------------------------------------- 1 | //Queue using stack 2 | 3 | import java.util.*; 4 | public class QueueUsingTwoStacks { 5 | public static void main(String args[]) 6 | { 7 | //Taking input using class Scanner 8 | Scanner sc = new Scanner(System.in); 9 | 10 | //Taking input the number of testcases 11 | int t = sc.nextInt(); 12 | while(t>0) 13 | { 14 | //Creating a new object of class StackQueue 15 | StackQueue g = new StackQueue(); 16 | 17 | //Taking input the total number of Queries 18 | int q = sc.nextInt(); 19 | while(q>0) 20 | { 21 | int QueryTyoe = sc.nextInt(); 22 | 23 | //If QueryTyoe is 1 then 24 | //we call the Push method 25 | //of class StackQueue 26 | //else we call the Pop method 27 | if(QueryTyoe == 1) 28 | { 29 | int a = sc.nextInt(); 30 | g.Push(a); 31 | }else 32 | if(QueryTyoe == 2) 33 | System.out.print(g.Pop()+" "); 34 | q--; 35 | 36 | } 37 | System.out.println(); 38 | t--; 39 | } 40 | } 41 | } 42 | class StackQueue 43 | { 44 | Stack s1 = new Stack(); 45 | Stack s2 = new Stack(); 46 | 47 | /* The method insert to push element 48 | into the queue */ 49 | void Push(int x) 50 | { 51 | s1.push(x); 52 | } 53 | 54 | 55 | /* The method remove which return the 56 | element popped out of the queue*/ 57 | int Pop() 58 | { 59 | if (s1.isEmpty()) { 60 | return -1; 61 | } 62 | while(!s1.isEmpty()) { 63 | s2.push(s1.pop()); 64 | } 65 | int x = s2.pop(); 66 | while(!s2.isEmpty()) { 67 | s1.push(s2.pop()); 68 | } 69 | return x; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /data structures/javascript/bst.js: -------------------------------------------------------------------------------- 1 | /* BST in js 2 | Copyrigth 2020 Laura Irene Capo Hdz*/ 3 | 4 | 5 | 6 | function Node(data, left, right) { 7 | this.data = data; 8 | this.left = left; 9 | this.right = right; 10 | this.show = show; 11 | } 12 | 13 | var isEmpty = true; 14 | 15 | function show() { 16 | return this.data; 17 | 18 | } 19 | 20 | /*The Node object stores both data and links to other nodes (left and right). There is 21 | also a show() function for displaying the data stored in a node*/ 22 | 23 | function BST() { 24 | this.root = root; 25 | this.insert = insert; 26 | this.inOrder = inOrder; 27 | this.preOrder = preOrder; 28 | this.postOrder = postOrder; 29 | 30 | } 31 | 32 | function NewBST() { 33 | var Nodos = []; 34 | 35 | } 36 | 37 | function NBST() { 38 | return BST(Nodos, isEmpty); 39 | 40 | } 41 | 42 | function insert(data) { 43 | var current = Nodos[0]; 44 | while (current.isEmpty) { 45 | if (data < current) { 46 | current = Nodos[current.left]; 47 | 48 | } else { 49 | current = Nodos[current.right]; 50 | 51 | } 52 | 53 | 54 | } 55 | current.data, current.isEmpty = data, false; 56 | current.left = NewBST.Nodos; 57 | current.left = NewBST.Nodos + 1; 58 | NewBST.Nodos = add(NewBST.Nodos, BST.isEmpty(true), Nodos.isEmpty(true)); 59 | 60 | 61 | } 62 | 63 | 64 | function inOrder(node) { 65 | if (node != null) { 66 | inOrder(node.left); 67 | putstr(node.show() + " "); 68 | inOrder(node.right); 69 | } 70 | } 71 | 72 | function preOrder(node) { 73 | if (!(node == null)) { 74 | putstr(node.show() + " "); 75 | preOrder(node.left); 76 | preOrder(node.right); 77 | } 78 | } 79 | 80 | function postOrder(node) { 81 | if (!(node == null)) { 82 | postOrder(node.left); 83 | postOrder(node.right); 84 | putstr(node.show() + " "); 85 | } 86 | } 87 | 88 | 89 | function getMin() { 90 | var current = this.root; 91 | while (current.left != null) { 92 | current = current.left; 93 | } 94 | return current.data; 95 | } 96 | /*Function get min, finds the minimun value of a BST*/ 97 | 98 | function getMax() { 99 | var current = this.root; 100 | while (!(current.right == null)) { 101 | current = current.right; 102 | } 103 | return current.data; 104 | } 105 | /*Function get max, finds the maximus value of a BST*/ 106 | 107 | 108 | function find(data) { 109 | var current = this.root; 110 | while (current.data != data) { 111 | if (data < current.data) { 112 | current = current.left; 113 | } else { 114 | current = current.right; 115 | } 116 | if (current == null) { 117 | return null; 118 | } 119 | } 120 | return current; 121 | } 122 | /* Function find returns the current node if the value is found in the BST and returns null 123 | if the value is not found.*/ 124 | 125 | function remove(data) { 126 | root = removeNode(this.root, data); 127 | } 128 | 129 | function removeNode(node, data) { 130 | if (node == null) { 131 | return null; 132 | } 133 | if (data == node.data) { 134 | // node has no children 135 | if (node.left == null && node.right == null) { 136 | return null; 137 | } 138 | // node has no left child 139 | if (node.left == null) { 140 | return node.right; 141 | } 142 | // node has no right child 143 | if (node.right == null) { 144 | return node.left; 145 | } 146 | // node has two children 147 | var tempNode = getSmallest(node.right); 148 | node.data = tempNode.data; 149 | node.right = removeNode(node.right, tempNode.data); 150 | return node; 151 | } else if (data < node.data) { 152 | node.left = removeNode(node.left, data); 153 | return node; 154 | } else { 155 | node.right = removeNode(node.right, data); 156 | return node; 157 | } 158 | } 159 | 160 | 161 | function getSize() { 162 | return getSize(root); 163 | } 164 | 165 | function getSize(node) { 166 | if (node == null) { 167 | return 0; 168 | 169 | } else { 170 | var result = 1 + getSize(node.left) + getSize(node.right); 171 | return result; 172 | } 173 | 174 | } 175 | 176 | function getHeight() { 177 | return getHeight(root); 178 | } 179 | 180 | function getHeight(node) { 181 | if (node == null) { 182 | return 0; 183 | } else { 184 | var result = 1 + Math.max(getHeight(node.right), getHeight(node.left)); 185 | return result; 186 | 187 | } 188 | 189 | } 190 | 191 | function getDepth() { 192 | var depth = 0; 193 | node = this.parent; 194 | while (node != null) { 195 | depth++; 196 | node = node.parent; 197 | } 198 | return depth; 199 | } -------------------------------------------------------------------------------- /data structures/javascript/dsInfo.md: -------------------------------------------------------------------------------- 1 | Add any data structure implementation in this folder you want in javascript language. for more info read the readme in the main repository directory 2 | Thanks... -------------------------------------------------------------------------------- /data structures/other/dsInfo.md: -------------------------------------------------------------------------------- 1 | Add any data structures implementation in this folder you want in any other language, which is not mentioned as a folder for more info read the readme in the main repository directory 2 | Thanks... -------------------------------------------------------------------------------- /data structures/python/dsInfo.md: -------------------------------------------------------------------------------- 1 | Add any data structure implementation in this folder you want in python language. for more info read the readme in the main repository directory 2 | Thanks... -------------------------------------------------------------------------------- /docs/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ### WARNING! 2 | - Please don't copy and paste any code from any website or any documentation. 3 | 4 | ## How to contribute an implementation (code)? 5 | 6 | * Have a look at open issues. They contain the list of algorithms/DS we plan to be implemented. Pick an unassigned issue. 7 | * You can also create a new issue for an algorithm that is not in the list. 8 | * Make sure you are assigned for the issue. 9 | * Code the algorithm/DS following the style guide defined below. 10 | * Send a PR. 11 | * Be sure to not include any compiled binaries in the patch. 12 | * While sending a PR make sure you follow one issue per PR rule. 13 | 14 | 15 | 16 | ## Suggesting an algorithm / DataStructure / Question: 17 | 18 | * First make sure you are not suggesting a duplicate. 19 | * If not, proceed and create the issue. Make sure that you specify only one language in an issue. Create multiple 20 | issues for different languages. 21 | * Please include at least one external link for the algorithm/DS in the issue's body for each issue. The link 22 | should explain the algorithm/problem/DS in detail. 23 | * Title of issue should be of the following format - 24 | ``` 25 | Algorithm/DS Name [Language] 26 | ``` 27 | 28 | ## Code Style Guide 29 | 30 | * Code submitted should be modular. 31 | * Don't use global variables. 32 | * Use separate folders for each concept. Folder name should be in full lowercase. If the algorithm/DS name has 33 | multiple words, separate them by underscores. (eg `longest_common_subsequence`) 34 | * Filename should be derived from the folder name. (eg `longest_common_subsequence` becomes 35 | `longestCommonSubsequence.c` or `LongestCommonSubsequence.java`) 36 | * Name of master function of the code should be kept same as filename to the best extent possible. 37 | * Prefer classes instead of multiple helper functions (where applicable). 38 | * Currently, we are accepting contributions in C, C++, C#, Java, Python, Go and JavaScript, Typescript but other languages 39 | may be considered after a discussion. 40 | * Define `tester` code only in `main` routine. 41 | * Use meaningful variable, method and function names and comments. 42 | * No profanity. 43 | * Use external libraries only when no other solution is possible/plausible. 44 | * We have defined [skeleton codes](#samples) for some popular languages below. Please follow them whenever possible. 45 | 46 | 47 | ## Improving an implementation 48 | 49 | * If you feel you can improve upon an implementation, feel free to open an issue discussing the improvements. 50 | 51 | 52 | ## Samples 53 | 54 | **C** 55 | 56 | ```c 57 | bool binarysearch(int *ar, int x) { 58 | /* 59 | Your implementation here... 60 | */ 61 | } 62 | 63 | int main() { 64 | int ar_size = 4; 65 | int a[4] = {2, 3, 4, 9, 15, 23, 52}; 66 | if(binarysearch(a, 15)) { 67 | cout << "present in array\n"; 68 | }else { 69 | cout << "not present in array\n"; 70 | } 71 | return 0; 72 | } 73 | ``` 74 | 75 | **Java** 76 | 77 | ```java 78 | public class BinarySearch { 79 | public static void main(String[] args) { 80 | int[] arr = new int[] {2, 3, 0, 4}; 81 | if(binarySearch(arr, 15)) { 82 | System.out.println("present in array"); 83 | }else { 84 | System.out.println("not present in array"); 85 | } 86 | } 87 | 88 | static boolean binarySearch(int[] a, int x) { 89 | /* 90 | Your implementation here... 91 | */ 92 | } 93 | } 94 | ``` 95 | 96 | **Python** 97 | 98 | ```python 99 | def mergesort(arr): 100 | # 101 | # Your implementation here... 102 | # 103 | 104 | def main(): 105 | arr = [2, 3, 0, 4] 106 | sorted_arr = mergesort(arr) 107 | print(sorted_arr) 108 | 109 | if __name__ == '__main__': 110 | main() 111 | ``` 112 | 113 | 114 | **JavaScript** 115 | 116 | ```JavaScript 117 | function mergeSort (arr) { 118 | /* 119 | Your implementation here 120 | */ 121 | } 122 | 123 | function main () { 124 | let input = [2, 3, 0, 4]; 125 | mergeSort(input); 126 | for (let x in input) { 127 | console.log(input[x] + ' '); 128 | } 129 | } 130 | 131 | main(); 132 | ``` 133 | 134 | **C#** 135 | 136 | ```csharp 137 | using System; 138 | 139 | public class MergeSort { 140 | public static void MergeSort(int[] a) { 141 | /* 142 | Your implementation here... 143 | */ 144 | } 145 | 146 | public static void Main() { 147 | int[] arr = new int[] {2, 3, 0, 4}; 148 | MergeSort(arr); 149 | foreach(int element in arr) { 150 | Console.Write(element + " "); 151 | } 152 | Console.WriteLine(""); 153 | } 154 | } 155 | ``` 156 | 157 | **Golang** 158 | 159 | ```go 160 | package main 161 | 162 | import "fmt" 163 | 164 | // QuickSort sorts an array using QuickSort algorithm 165 | func QuickSort(array []int) []int { 166 | // Your implementation here 167 | return array 168 | } 169 | 170 | // Main method where code starts executing 171 | func main() { 172 | array := []int{2, 3, 0, 4} 173 | sortedArray := QuickSort(array) 174 | fmt.Println(sortedArray) 175 | } 176 | ``` 177 | -------------------------------------------------------------------------------- /hacktoberfest.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sobhanbera/algorithms/9f2386ec573929177472b8888706fff7bee1f217/hacktoberfest.gif -------------------------------------------------------------------------------- /others/PythonSMTP_Skeleton.py: -------------------------------------------------------------------------------- 1 | import smtplib 2 | sender='thesender@gmail.com' 3 | receiver='whicheverreceiver@gmail.com' 4 | password=’' 5 | smtpserver=smtplib.SMTP("smtp.gmail.com",587) 6 | smtpserver.ehlo() 7 | smtpserver.starttls() 8 | smtpserver.ehlo 9 | smtpserver.login(sender,password) 10 | msg='Subject:Demo\nThis is a dem 11 | smtpserver.sendmail(sender,receiver,msg) 12 | print('Sent') 13 | smtpserver.close() 14 | -------------------------------------------------------------------------------- /others/cpp/count_word_map.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | // get rid of characters that are not letters in a word 7 | string GetWord(string inputWord); 8 | 9 | int main(int argc, char const *argv[]) 10 | { 11 | int count = 0; 12 | string word; 13 | unordered_map map1; //count the number of words 14 | unordered_map map2; //count the total words 15 | unordered_map::iterator itr; 16 | 17 | string file = "test_count_word_map.txt"; 18 | fstream myfile; 19 | 20 | myfile.open(file); 21 | 22 | while (!myfile.eof()) 23 | { 24 | myfile >> word; 25 | string str = ""; 26 | if (!word.empty()) 27 | str = GetWord(word); 28 | 29 | if (!str.empty()) 30 | { 31 | itr = map1.find(str); 32 | if (itr != map1.end()) 33 | { 34 | itr = map2.find(str); 35 | if (itr == map2.end()) 36 | map2[str] += 1; 37 | 38 | count++; 39 | } 40 | else 41 | { 42 | map1[str] += 1; 43 | count++; 44 | } 45 | } 46 | } 47 | cout << "There are " << map2.size() << " duplicates in the text" << endl; 48 | cout << "There are " << count << " words in the text" << endl; 49 | 50 | return 0; 51 | } 52 | 53 | string GetWord(string inputWord) 54 | { 55 | int i, j; i = j = 0; 56 | 57 | bool check = false; 58 | 59 | while (i < inputWord.size()) 60 | { 61 | if (!(isalpha(inputWord[i])) && !(isdigit(inputWord[i]))) 62 | { 63 | j = i; 64 | inputWord.erase(inputWord.begin() + i); 65 | check = true; 66 | } 67 | 68 | if (check == true) 69 | { 70 | i = j; 71 | check = false; 72 | } 73 | else 74 | { 75 | i++; 76 | } 77 | } 78 | 79 | return inputWord; 80 | } 81 | -------------------------------------------------------------------------------- /others/cpp/test_count_word_map.txt: -------------------------------------------------------------------------------- 1 | I want to eat ice cream. Ice cream is good and I love it so much. 2 | I need to go to shcool because I need to some coidng skills. 3 | -------------------------------------------------------------------------------- /others/snake_game.py: -------------------------------------------------------------------------------- 1 | ### Open CMD with Adminitration and TYPE----> "pip install windows-curses" 2 | import random 3 | import curses 4 | 5 | s= curses.initscr() 6 | curses.curs_set(0) 7 | sh, sw = s.getmaxyx() 8 | w= curses.newwin(sh, sw, 0, 0) 9 | w.keypad(1) 10 | w.timeout(100) 11 | 12 | snk_x =sw/4 13 | snk_y= sh/2 14 | snake =[ 15 | [snk_y,snk_x], 16 | [snk_y,snk_x-1], 17 | [snk_y,snk_x-2] 18 | ] 19 | 20 | food =[sh/2,sw/2] 21 | w.addch(food[0],food[1], curses.ACS_PI) 22 | 23 | key = curses.KEY_RIGHT 24 | 25 | 26 | while True: 27 | next_key =w.getch() 28 | key = key if next_key == -1 else next_key 29 | 30 | if snake[0][0] in [0,sh] or snake[0][1] in [0, sw] or snake[0] in snake[1:]: 31 | curses.endwin() 32 | quit() 33 | 34 | new_head = [snake[0][0], snake[0][1]] 35 | 36 | if key == curses.KEY_DOWN: 37 | new_head[0]+=1 38 | if key == curses.KEY_UP: 39 | new_head[0]-=1 40 | if key == curses.KEY_LEFT: 41 | new_head[1]-=1 42 | if key == curses.KEY_RIGHT: 43 | new_head[1]+=1 44 | 45 | 46 | snake.insert(0, new_head) 47 | 48 | if snake[0] == food: 49 | food =None 50 | while food is None: 51 | nf = [ 52 | random.randint(1,sh-1), 53 | random.ramdint(1, sw-1) 54 | ] 55 | food = nf if nf not in snake else None 56 | w.addch(food[0],food[1], curses.ACS_PI) 57 | else: 58 | tail =snake.pop() 59 | w.addch(tail[0], tail[1], " ") 60 | 61 | w.addch(snake[0],[0], snake[0][1], curses.ASC_CKBOARD) 62 | 63 | -------------------------------------------------------------------------------- /questions/c-sharp/queInfo.md: -------------------------------------------------------------------------------- 1 | Add any competitive programming question with solution in this folder you want in c# language. for more info read the readme in the main repository directory. 2 | Please add some comments to understand what your code is doing. 3 | Thanks... -------------------------------------------------------------------------------- /questions/cpp/Matrix_chain_mult.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void printParenthesis(int i, int j, int n, int *bracket, char &name) 5 | { 6 | if(i==j) 7 | { 8 | cout<>n; 60 | cout<<"Enter the values\n"; 61 | int arr[++n]; 62 | for(int i=0;i>arr[i]; 64 | matrixChainOrder(arr, n); 65 | return 0; 66 | } 67 | -------------------------------------------------------------------------------- /questions/cpp/all_sol_of_n_queen.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define lld long long int 4 | 5 | int mat[100][100]; 6 | int l_diagonal[20],r_diagonal[20],ro[20]; 7 | 8 | int safe(int a,int b) 9 | { 10 | if(!ro[a]&&!r_diagonal[a+b]&&!l_diagonal[a-b+6]) 11 | return 1; 12 | return 0; 13 | } 14 | int queen(int n,int c) 15 | { 16 | if(c>=n) 17 | { 18 | for(int i=0;i>n; 51 | memset(mat,0,sizeof(mat)); 52 | memset(l_diagonal,0,sizeof(l_diagonal)); 53 | memset(r_diagonal,0,sizeof(r_diagonal)); 54 | memset(ro,0,sizeof(ro)); 55 | if(!queen(n,0)) 56 | cout<<"NO\n"; 57 | } 58 | 59 | 60 | -------------------------------------------------------------------------------- /questions/cpp/edit_distance.cpp: -------------------------------------------------------------------------------- 1 | #include "bits/stdc++.h" 2 | using namespace std; 3 | #define int long long 4 | signed main() 5 | { 6 | int n,i,j,k,m,q,l,r; 7 | string a , b; 8 | cin>>a>>b; 9 | n = a.size() , m = b.size(); 10 | vector> dp(n+1 , vector (m+1 , INT_MAX)); 11 | dp[0][0] = 0; 12 | for(int i=0; i<=n;i++) 13 | { 14 | for(int j=0; j<=m; j++) 15 | { 16 | if(i) 17 | dp[i][j] = min(dp[i][j] , dp[i-1][j] + 1); 18 | if(j) 19 | dp[i][j] = min(dp[i][j] , dp[i][j-1] + 1); 20 | if(i && j) 21 | dp[i][j] = min(dp[i][j] , dp[i-1][j-1] + (a[i-1]!=b[j-1])); 22 | } 23 | } 24 | cout< 2 | using namespace std; 3 | #pragma GCC target ("avx2") 4 | #pragma GCC optimization ("O3") 5 | #pragma GCC optimization ("unroll-loops") 6 | #define lld long long int 7 | 8 | //-4%3=-1 9 | lld n,w; 10 | lld wt[101],val[101],dp[2][10000001]; 11 | 12 | lld fun(lld i,lld w) 13 | { 14 | if(i<=0||w<=0) 15 | return 0; 16 | if(dp[i][w]==-1) 17 | { 18 | if(wt[i]<=w) 19 | return dp[i][w]=max(val[i]+fun(i-1,w-wt[i]),fun(i-1,w)); 20 | else 21 | return dp[i][w]=fun(i-1,w); 22 | } 23 | else 24 | return dp[i][w]; 25 | 26 | } 27 | 28 | 29 | 30 | int main() { 31 | // your code goes here 32 | ios_base::sync_with_stdio(false); 33 | cin.tie(NULL); 34 | lld t; 35 | //cin>>t; 36 | t=1; 37 | while(t--) 38 | { 39 | 40 | cin>>n>>w; 41 | for(int i=1;i<=n;i++) 42 | cin>>wt[i]>>val[i]; 43 | memset(dp,-1,sizeof(dp)); 44 | cout< 2 | using namespace std; 3 | #define lld long long int 4 | 5 | lld n,w; 6 | lld wt[101],val[101],dp[100001][101]; 7 | 8 | lld min(lld a,lld b) 9 | { 10 | if(a>n>>w; 36 | for(int i=1;i<=n;i++) 37 | { 38 | cin>>wt[i]>>val[i]; 39 | sum+=val[i]; 40 | } 41 | memset(dp,-1,sizeof(dp)); 42 | for(r=sum;r>=0;r--) // Iterating through all possible values 43 | { 44 | cout<<"For sum="< 2 | using namespace std; 3 | 4 | #define lld long long int 5 | int mat[8][8]; 6 | int r[]={2, 1, -1, -2, -2, -1, 1, 2}; 7 | int c[]={1, 2, 2, 1, -1, -2, -2, -1}; 8 | //set l_diagonal; 9 | //set r_diagonal; 10 | int knight(int x,int y,int cnt) 11 | { 12 | mat[x][y]=cnt; 13 | if(cnt==64) 14 | return 1; 15 | for(int i=0;i<8;i++) 16 | { 17 | int a=x+r[i]; 18 | int b=y+c[i]; 19 | if(a>=0&&a<8&&b>=0&&b<8&&mat[a][b]==-1) 20 | { 21 | if(knight(a,b,cnt+1)) 22 | return 1; 23 | else 24 | mat[a][b]=-1; 25 | } 26 | } 27 | return 0; 28 | } 29 | int main() { 30 | // your code goes here 31 | ios_base::sync_with_stdio(false); 32 | cin.tie(NULL); 33 | //memset(mat,-1,sizeof(mat)); 34 | for(int i=0;i<8;i++) 35 | for(int j=0;j<8;j++) 36 | mat[i][j]=-1; 37 | if(knight(0,0,1)) 38 | for(int i=0;i<8;i++) 39 | { 40 | for(int j=0;j<8;j++) 41 | cout< 2 | using namespace std; 3 | #define lld long long int 4 | 5 | int mat[100][100]; 6 | int l_diagonal[20],r_diagonal[20],ro[20]; 7 | 8 | int safe(int a,int b) 9 | { 10 | if(!ro[a]&&!r_diagonal[a+b]&&!l_diagonal[a-b+6]) 11 | return 1; 12 | return 0; 13 | } 14 | int queen(int n,int c) 15 | { 16 | if(c>=n) 17 | { 18 | for(int i=0;i>n; 54 | memset(mat,0,sizeof(mat)); 55 | memset(l_diagonal,0,sizeof(l_diagonal)); 56 | memset(r_diagonal,0,sizeof(r_diagonal)); 57 | memset(ro,0,sizeof(ro)); 58 | if(!queen(n,0)) 59 | cout<<"NO\n"; 60 | } 61 | 62 | 63 | -------------------------------------------------------------------------------- /questions/cpp/queInfo.md: -------------------------------------------------------------------------------- 1 | Add any competitive programming question with solution in this folder you want in C++ language. for more info read the readme in the main repository directory. 2 | Please add some comments to understand what your code is doing. 3 | Thanks... -------------------------------------------------------------------------------- /questions/cpp/rod_cutting_prob.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int n; 7 | cout<<"enter the length of rod\n"; 8 | cin>>n; 9 | int price[n]={0},t; 10 | cout<<"Enter the no of prices given\n"; 11 | cin>>t; 12 | while(t--) 13 | { 14 | cout<<"Enter length and price\n"; 15 | int a,b; 16 | cin>>a>>b; 17 | price[a-1]=b; 18 | } 19 | int val[n+1]={0}; 20 | for(int i=1;i<=n;i++) 21 | { 22 | int value=INT_MIN; 23 | for(int j=0;j 2 | using namespace std; 3 | 4 | int fun(int arr[][125],int r,int c) 5 | { 6 | int sum[r][c],mx=0; 7 | for(int i=0;i>r>>c; 34 | int arr[r][125]; 35 | cout<<"enter the elements\n"; 36 | for(int i=0;i>arr[i][j]; 39 | fun(arr,r,c); 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /questions/cpp/two_sum.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to check if given array 2 | // has 2 elements whose sum is equal 3 | // to the given value 4 | 5 | #include 6 | using namespace std; 7 | 8 | // Function to check if array has 2 elements 9 | // whose sum is equal to the given value 10 | bool hasArrayTwoCandidates(int A[], int arr_size, 11 | int sum) 12 | { 13 | int l, r; 14 | 15 | /* Sort the elements */ 16 | sort(A, A + arr_size); 17 | 18 | /* Now look for the two candidates in 19 | the sorted array*/ 20 | l = 0; 21 | r = arr_size - 1; 22 | while (l < r) { 23 | if (A[l] + A[r] == sum) 24 | return 1; 25 | else if (A[l] + A[r] < sum) 26 | l++; 27 | else // A[i] + A[j] > sum 28 | r--; 29 | } 30 | return 0; 31 | } 32 | 33 | /* Driver program to test above function */ 34 | int main() 35 | { 36 | int A[] = { 1, 4, 45, 6, 10, -8 }; 37 | int n = 16; 38 | int arr_size = sizeof(A) / sizeof(A[0]); 39 | 40 | // Function calling 41 | if (hasArrayTwoCandidates(A, arr_size, n)) 42 | cout << "Array has two elements" 43 | " with given sum"; 44 | else 45 | cout << "Array doesn't have two" 46 | " elements with given sum"; 47 | 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /questions/java/coin_change.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.IOException; 3 | import java.io.InputStreamReader; 4 | import java.util.Arrays; 5 | 6 | /** 7 | * PROBLEM STATEMENT : 8 | * 9 | * You are given coins of different denominations and a total amount of money amount. 10 | * Write a function to compute the fewest number of coins that you need to make up that amount. 11 | * If that amount of money cannot be made up by any combination of the coins, return -1. 12 | * You may assume that you have an infinite number of each kind of coin. 13 | * 14 | * EXAMPLES : 15 | * 16 | * Input: coins = [1,2,5], amount = 11 17 | * Output: 3 18 | * Explanation: 11 = 5 + 5 + 1 19 | * 20 | * Input: coins = [2], amount = 3 21 | * Output: -1 22 | * 23 | */ 24 | 25 | public class CoinChange { 26 | public static void main(String[] args) throws IOException { 27 | BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); 28 | 29 | System.out.println("\nEnter the coin denominations separated with spaces:"); 30 | int[] coins = Arrays.stream(reader.readLine().trim().split("\\s+")).mapToInt(Integer::parseInt).toArray(); 31 | 32 | System.out.println("\nEnter the amount:"); 33 | int amount = Integer.parseInt(reader.readLine().trim()); 34 | 35 | reader.close(); 36 | 37 | System.out.println("\nMinimum " + coinChange(coins, amount) + " coins are required to make the amount."); 38 | } 39 | 40 | public static int coinChange(int[] coins, int amount) { 41 | int[] combinations = new int[amount + 1]; 42 | 43 | combinations[0] = 0; 44 | 45 | for (int amt = 1; amt <= amount; ++amt) { 46 | int minCoins = Integer.MAX_VALUE; 47 | combinations[amt] = -1; 48 | for (int c : coins) 49 | if (c <= amt && combinations[amt - c] != -1) { 50 | minCoins = Math.min(minCoins, 1 + combinations[amt - c]); 51 | combinations[amt] = minCoins; 52 | } 53 | } 54 | 55 | return combinations[amount]; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /questions/java/queInfo.md: -------------------------------------------------------------------------------- 1 | Add any competitive programming question with solution in this folder you want in java language. for more info read the readme in the main repository directory. 2 | Please add some comments to understand what your code is doing. 3 | Thanks... -------------------------------------------------------------------------------- /questions/javascript/queInfo.md: -------------------------------------------------------------------------------- 1 | Add any competitive programming question with solution in this folder you want in javascript language. for more info read the readme in the main repository directory. 2 | Please add some comments to understand what your code is doing. 3 | Thanks... -------------------------------------------------------------------------------- /questions/other/queInfo.md: -------------------------------------------------------------------------------- 1 | Add any competitive programming question with solution in this folder you want in any language you like. for more info read the readme in the main repository directory. 2 | Please add some comments to understand what your code is doing. 3 | Thanks... -------------------------------------------------------------------------------- /questions/python/Subset.py: -------------------------------------------------------------------------------- 1 | # Subset Sum 2 | 3 | # Problem statement: 4 | # Given a set of non-negative integers, and a value sum, determine if there is a subset of the given set with sum equal to given sum. 5 | 6 | # sample input array 7 | val = [3, 34, 4, 12, 5, 2] 8 | n = len(val) 9 | 10 | # sample target value 11 | target = 9 12 | 13 | # dp array 14 | ans = [[False]*(target+1) for _ in range(n+1)] 15 | 16 | # initialization of dp array 17 | for i in range(n+1): 18 | ans[i][0] = True 19 | 20 | for i in range(1, n+1): 21 | for j in range(1, target+1): 22 | if val[i-1] <= j: 23 | ans[i][j] = ans[i-1][j-val[i-1]] or ans[i-1][j] 24 | 25 | else: 26 | ans[i][j] = ans[i-1][j] 27 | 28 | # printing the answer 29 | print(ans[-1][-1]) -------------------------------------------------------------------------------- /questions/python/coin_change1.py: -------------------------------------------------------------------------------- 1 | # Coin Change Leetcode (322) 2 | # You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. 3 | 4 | # You may assume that you have an infinite number of each kind of coin. 5 | 6 | def coinChange(coins, amount: int): 7 | 8 | n = len(coins) 9 | 10 | t = [[0]*(amount+1) for _ in range(n+1)] 11 | 12 | for i in range(n+1): 13 | 14 | for j in range(amount+1): 15 | 16 | if j == 0: 17 | 18 | t[i][j] = 0 19 | 20 | # Initializing base conditions i.e. when amount is 0 21 | 22 | if i == 0: 23 | 24 | t[i][j] = float('inf') - 1 25 | 26 | # Initializing base conditions i.e. when length of coins array in consideration is 0 27 | 28 | if i == 1 and j != 0: 29 | 30 | if j % coins[0] == 0: 31 | 32 | t[i][j] = j // coins[0] 33 | 34 | else: 35 | 36 | t[i][j] = float('inf') - 1 37 | 38 | else: 39 | 40 | if coins[i-1] <= j: 41 | 42 | t[i][j] = min(1+t[i][j-coins[i-1]],t[i-1][j]) 43 | else: 44 | 45 | t[i][j] = t[i-1][j] 46 | 47 | if t[n][amount] != float('inf'): 48 | return t[n][amount] 49 | 50 | return -1 51 | 52 | coins = [1,2,5] 53 | amount = 11 54 | print(coinChange(coins,amount)) 55 | -------------------------------------------------------------------------------- /questions/python/coin_change2.py: -------------------------------------------------------------------------------- 1 | # Coin Change 2 Leetcode (518) 2 | # You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that amount. You may assume that you have infinite number of each kind of coin. 3 | 4 | def change(amount, coins): 5 | 6 | t = [[0]*(amount+1) for _ in range(len(coins)+1)] 7 | 8 | # j indicates amount and i indicates len of coins array in consideration 9 | # if j i.e. amount is 0, number of combinations is 1 10 | 11 | for i in range(len(t)): 12 | 13 | t[i][0] = 1 14 | 15 | for i in range(1,len(t)): 16 | 17 | for j in range(1,len(t[0])): 18 | 19 | if coins[i-1] <= j: 20 | 21 | t[i][j] = t[i][j-coins[i-1]] + t[i-1][j] 22 | else: 23 | 24 | t[i][j] = t[i-1][j] 25 | 26 | return t[len(coins)][amount] 27 | 28 | amount = 5 29 | coins = [1, 2, 5] 30 | print(change(amount,coins)) -------------------------------------------------------------------------------- /questions/python/egg_dropping.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem Statement: 3 | You are given K eggs, and you have access to a building with N floors from 1 to N. 4 | 5 | Each egg is identical in function, and if an egg breaks, you cannot drop it again. 6 | 7 | You know that there exists a floor F with 0 <= F <= N such that any egg dropped at a floor higher than F will break, and any egg dropped at or below floor F will not break. 8 | 9 | Each move, you may take an egg (if you have an unbroken one) and drop it from any floor X (with 1 <= X <= N). 10 | 11 | Your goal is to know with certainty what the value of F is. 12 | What is the minimum number of moves that you need to know with certainty what F is, regardless of the initial value of F? 13 | 14 | """ 15 | 16 | def eggDropping(eggs,floors): 17 | if floors==0 or floors==1: 18 | return floors 19 | if eggs==1: 20 | return floors 21 | 22 | #if dp array already has a value return it 23 | if dp[eggs][floors]!=-1: 24 | return dp[eggs][floors] 25 | 26 | minimum=float("inf") 27 | temp=0 28 | 29 | #check for all floors 30 | for k in range(1,floors+1): 31 | #here max is used because we want to find the no of attempts in the WORST CASE 32 | #so which ever case provides more attempts will be the answer 33 | temp=1+max(eggDropping(eggs-1,k-1),eggDropping(eggs,floors-k)) 34 | 35 | #but out of all the worst cases we have to find the minimum therefore min is used here 36 | minimum=min(minimum,temp) 37 | 38 | #store the result in dp array 39 | dp[eggs][floors]=minimum 40 | return minimum 41 | 42 | 43 | e=3 44 | f=14 45 | 46 | #make a dp array of dimensions "e x f" 47 | dp=[[-1 for _ in range(f+1)]for _ in range(e+1)] 48 | 49 | print("Minimum number of moves are: ",eggDropping(e,f)) -------------------------------------------------------------------------------- /questions/python/queInfo.md: -------------------------------------------------------------------------------- 1 | Add any competitive programming question with solution in this folder you want in python language. for more info read the readme in the main repository directory. 2 | Please add some comments to understand what your code is doing. 3 | Thanks... -------------------------------------------------------------------------------- /templates/cpp/templateHelp.md: -------------------------------------------------------------------------------- 1 | add your default template you use in competitive programming in this folder in C++ language. 2 | -------------------------------------------------------------------------------- /templates/java/templateHelp.md: -------------------------------------------------------------------------------- 1 | add your default template you use in competitive programming in this folder in Java language. 2 | -------------------------------------------------------------------------------- /templates/other/templateHelp.md: -------------------------------------------------------------------------------- 1 | add your default template you use in competitive programming in this folder in any other language, which is not mentioned as a folder. 2 | -------------------------------------------------------------------------------- /templates/python/templateHelp.md: -------------------------------------------------------------------------------- 1 | add your default template you use in competitive programming in this folder in Python language. 2 | -------------------------------------------------------------------------------- /templates/templateHelp.md: -------------------------------------------------------------------------------- 1 | ### Add you default competitive programming template in this folder. 2 | #### In any language you can --------------------------------------------------------------------------------