├── Dynamic Programming └── Knapsack │ ├── knapsack_1.jpg │ ├── knapsack_2.png │ └── algorithm.md ├── Searching ├── Interpolation Search │ ├── C++ │ │ ├── InterpolationSearch.exe │ │ └── InterpolationSearch.cpp │ └── Python │ │ └── InterpolationSearch.py ├── Linear Search │ ├── C++ │ │ └── LinearSearch.cpp │ ├── C# │ │ └── LinearSearch.cs │ ├── Java │ │ └── LinearSearch.java │ ├── Python │ │ └── LinearSearch.py │ └── algorithm.md ├── Binary Search │ ├── algorithm.md │ ├── Python │ │ └── BinarySearch.py │ ├── Java │ │ ├── BinarySearch.java │ │ └── InfiniteArray.java │ └── C++ │ │ └── binarySearch.cpp └── Ternary Search │ ├── Python │ └── TernarySearch.py │ ├── Java │ └── TernarySearch.java │ ├── algorithm.md │ └── C++ │ └── TernarySearch.c++ ├── Traversal Algorithms ├── Tree Traversals │ ├── Level Order Traversal - Binary Tree │ │ ├── Algorithm.md │ │ └── C++ │ │ │ ├── LeftViewBinaryTree.cpp.cpp │ │ │ └── HeightOfTree.cpp │ ├── Postorder Traversal-Binary Tree │ │ └── C │ │ │ └── Postorder Traversal.C │ ├── Postorder Traversal - Binary Tree │ │ └── C++ │ │ │ └── PostorderTraversal.cpp │ └── Inorder Traversal - Binary Tree │ │ └── C++ │ │ └── InorderTraversal.cpp └── Graph Traversals │ ├── DFS │ ├── C++ │ │ └── DFS.cpp │ ├── Algorithm.md │ └── Python │ │ └── DFS.py │ └── BFS │ ├── C++ │ ├── Algorithm.md │ └── BFS.cpp │ └── JAVA │ └── BFS.java ├── Sorting ├── Bubble Sort │ ├── Python │ │ └── BubbleSort.py │ ├── C++ │ │ └── BubbleSort.cpp │ └── Algorithm.md ├── Insertion Sort │ ├── Python │ │ └── InsertionSort.py │ ├── C++ │ │ └── InsertionSort.cpp │ ├── Java │ │ └── InsertionSort.java │ ├── algorithm.md │ └── C# │ │ └── InsertionSort.cs ├── Merge Sort │ ├── algorithm.md │ ├── Python │ │ └── MergeSort.py │ ├── C++ │ │ └── MergeSort.cpp │ └── C# │ │ └── mergesort.cs ├── Selection Sort │ ├── algorithm.md │ ├── C++ │ │ └── SelectionSort.c++ │ ├── Java │ │ └── SelectionSort.java │ └── C# │ │ └── SelectionSort.cs ├── Heap Sort │ └── algorithm.md ├── Quick Sort │ ├── Python │ │ └── QuickSort.py │ ├── C++ │ │ └── QuickSort.cpp │ └── Algorithm.md └── Radix Sort │ └── C++ │ └── RadixSort.cpp ├── Graph Algorithms ├── Dijkstra │ ├── C++ │ │ └── Dijkstra.cpp │ ├── Algorithm.md │ ├── Java │ │ └── Dijkstra.java │ └── Python │ │ └── Dijkstra.py ├── Topological Sort │ ├── C++ │ │ └── TopologicalSort.cpp │ ├── Python │ │ └── TopologicalSort.py │ └── Algorithm.md └── Bellman Ford │ ├── Algorithm.md │ ├── C++ │ └── BellmanFord.cpp │ └── java │ └── BellmanFord.java ├── LICENSE ├── Contribution guidelines.md ├── README.md └── How to create a pull request.md /Dynamic Programming/Knapsack/knapsack_1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CodeChefMUST/Algorithms/HEAD/Dynamic Programming/Knapsack/knapsack_1.jpg -------------------------------------------------------------------------------- /Dynamic Programming/Knapsack/knapsack_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CodeChefMUST/Algorithms/HEAD/Dynamic Programming/Knapsack/knapsack_2.png -------------------------------------------------------------------------------- /Searching/Interpolation Search/C++/InterpolationSearch.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CodeChefMUST/Algorithms/HEAD/Searching/Interpolation Search/C++/InterpolationSearch.exe -------------------------------------------------------------------------------- /Searching/Linear Search/C++/LinearSearch.cpp: -------------------------------------------------------------------------------- 1 | int linear_search(vector nums, int target){ 2 | int n = nums.size(); 3 | for (int i = 0; i < n; i++) { 4 | if (nums[i] == target) 5 | return i; 6 | } 7 | return -1; 8 | } 9 | 10 | int main(){ 11 | 12 | } -------------------------------------------------------------------------------- /Traversal Algorithms/Tree Traversals/Level Order Traversal - Binary Tree/Algorithm.md: -------------------------------------------------------------------------------- 1 | # Problem Statement - 2 | # Given a Binary Tree, print left view of it. Left view of a Binary Tree is set of nodes visible when tree is visited from left side. 3 | #Given a Binary Tree, find the Maximum Depth or Height of the tree. -------------------------------------------------------------------------------- /Searching/Binary Search/algorithm.md: -------------------------------------------------------------------------------- 1 | Binary Serach Questions 2 | 3 | 1)https://leetcode.com/problems/longest-increasing-subsequence 4 | 5 | 2)https://codeforces.com/problemset/problem/1575/B 6 | 7 | 3)https://codeforces.com/problemset/problem/177/E2 8 | 9 | 4)https://leetcode.com/problems/median-of-two-sorted-arrays 10 | 11 | 5)https://www.geeksforgeeks.org/find-position-element-sorted-array-infinite-numbers/ 12 | -------------------------------------------------------------------------------- /Searching/Linear Search/C#/LinearSearch.cs: -------------------------------------------------------------------------------- 1 | class LinearSearch { 2 | public static int linearSearch(int[] array, int num) 3 | { 4 | for (int i = 0; i < array.Length; i++){ 5 | if (array[i] == num) //This loop searches the index of the given number in the array 6 | return i; 7 | } 8 | return -1; //If the loop can not find the number in the array, then method will return -1 9 | } 10 | } -------------------------------------------------------------------------------- /Searching/Linear Search/Java/LinearSearch.java: -------------------------------------------------------------------------------- 1 | public class LinearSearch 2 | { 3 | /* 4 | Linear search function: 5 | 6 | -Takes in two arguments 7 | 1. int array[] 8 | 2. int target 9 | 10 | -The function returns the index of a target element if found else returns -1 11 | */ 12 | public static int linear_search(int[] arr, int target) 13 | { 14 | for(int i = 0; i < arr.length; i++) 15 | { 16 | if(arr[i] == target) 17 | return i; 18 | } 19 | return -1; 20 | } 21 | } -------------------------------------------------------------------------------- /Traversal Algorithms/Tree Traversals/Postorder Traversal-Binary Tree/C/Postorder Traversal.C: -------------------------------------------------------------------------------- 1 | /* 2 | Author : Tanya Bansal 3 | Date : 18/10/2021 4 | Description : This Program is on Postorder Traversal 5 | */ 6 | 7 | #include 8 | #include 9 | 10 | struct node { 11 | int data; 12 | struct node * left; 13 | struct node * right; 14 | }; 15 | 16 | void postorderTraversal(struct node * tree) { 17 | if (tree != NULL) { 18 | postorderTraversal(tree -> left); 19 | postorderTraversal(tree -> right); 20 | printf("%d\t", tree -> data); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Sorting/Bubble Sort/Python/BubbleSort.py: -------------------------------------------------------------------------------- 1 | # Creating a bubble sort function 2 | # contributed by ankit 3 | def bubble_sort(list1): 4 | # Outer loop for traverse the entire list 5 | for i in range(0,len(list1)-1): 6 | for j in range(len(list1)-1): 7 | if(list1[j]>list1[j+1]): 8 | temp = list1[j] 9 | list1[j] = list1[j+1] 10 | list1[j+1] = temp 11 | return list1 12 | 13 | list1 = [5, 3, 8, 6, 7, 2] 14 | print("The unsorted list is: ", list1) 15 | # Calling the bubble sort function 16 | print("The sorted list is: ", bubble_sort(list1)) -------------------------------------------------------------------------------- /Searching/Binary Search/Python/BinarySearch.py: -------------------------------------------------------------------------------- 1 | def binarySearch(arr, n, key): 2 | low = 0 3 | high = n-1 4 | while low <= high: 5 | mid = (low + high) // 2 6 | if arr[mid] == key: 7 | return mid 8 | elif arr[mid] > key: 9 | high = mid - 1 10 | elif arr[mid] < key: 11 | low = mid + 1 12 | 13 | return -1 14 | 15 | arr = [1, 4, 6, 10, 20, 39, 50, 66] 16 | n = len(arr) 17 | key = 39 18 | # calling function binary search 19 | result = binarySearch(arr, n, key) 20 | if result == -1: 21 | print("Element is not present in the array.") 22 | else: 23 | print("Element is found at index: ", result) -------------------------------------------------------------------------------- /Sorting/Insertion Sort/Python/InsertionSort.py: -------------------------------------------------------------------------------- 1 | def insertionSort(array): 2 | if array == None or len(array) == 0: 3 | return None 4 | for i in range(1,len(array)): 5 | currentElement = array[i] 6 | j = i - 1 7 | while j >= 0: 8 | if array[j] > currentElement: 9 | array[j+1] = array[j] 10 | else: 11 | break 12 | j-=1 13 | array[j+1] = currentElement 14 | return array 15 | # 16 | # Sample Input: [4,3,2,1] 17 | # Sample Output: [1,2,3,4] 18 | # 19 | # Time Complexity in Best Case: O(n) 20 | # Time Complexity in Average Case: O(n^2) 21 | # Time Complexity in Worst Case: O(n^2) 22 | # Space Complexity in Worst Case: O(1) 23 | # -------------------------------------------------------------------------------- /Searching/Linear Search/Python/LinearSearch.py: -------------------------------------------------------------------------------- 1 | def LinearSearch(array , key): 2 | 3 | for i in range(0, len(array)): 4 | 5 | if (array[i] == key): 6 | 7 | print("Key present at index:",i) 8 | return 0; 9 | 10 | print("Key not present!"); 11 | 12 | 13 | # Sample Input 1 : 14 | # array = [21 , 90 , -32 , 78 , 52] 15 | # key = 78 16 | 17 | # Output 1 : 18 | # Key present at index: 3 19 | 20 | # Sample Input 2 : 21 | # array = [86 , 67 , 21 , 91 , -39 , 11] 22 | # key = 99 23 | 24 | # Output 2: 25 | # Key not present! 26 | 27 | # TIME COMPLEXITY : 28 | # Best case : O(1) 29 | # Average case : O(n) 30 | # Worst case : O(n) 31 | 32 | # SPACE COMPLEXITY : O(n) 33 | 34 | -------------------------------------------------------------------------------- /Sorting/Merge Sort/algorithm.md: -------------------------------------------------------------------------------- 1 | ## Merge Sort 2 | ### Merge Sort is a very efficient sorting algorithm. It uses Divide and Conquer principle to sort the elements. It divides the list into two equal halves. The sub-lists are divided again and again until each sublist consists of a single element.Then merge sublists in a way that results in a sorted list. 3 | ![This is an image](https://media.geeksforgeeks.org/wp-content/cdn-uploads/Merge-Sort-Tutorial.png) 4 | 5 | ## Algorithm 6 | ``` 7 | Merge_sort(array,start,end) 8 | Step 1: if start key: 11 | high = pos - 1 12 | else: 13 | low = pos + 1 14 | 15 | return -1 16 | 17 | 18 | # arr = [1, 3, 5, 7, 9, 11, 13, 15, 17] 19 | # fairly uniform sorted array 20 | # n = len(arr) 21 | # key = 11 22 | 23 | # output: 5 24 | # time complexity best case: O(1) 25 | # time complexity average case: O(log2(log2N)) 26 | # time complexity worst case: O(N) 27 | # space complexity: O(1) -------------------------------------------------------------------------------- /Sorting/Selection Sort/algorithm.md: -------------------------------------------------------------------------------- 1 | ## SELECTION SORT ALGORITHM 2 | In selection sort, the smallest value among the unsorted elements of the array is selected in every pass and inserted to its appropriate position into the array. The array with n elements is sorted by using n-1 pass of selection sort algorithm. It is one of the simplest algorithm. Selection sort is the best algorithm when swapping is a costly operation and it is a comparision based algorithm. 3 | ``` 4 | Step 1: for i = 1 to n-1 5 | step 2: Let minimum = a[i] 6 | step 3: Let position = i 7 | step 4: For j = i+1 to n-1 (loop) 8 | if (minimun > a[j]) 9 | Set minimum = a[j] 10 | Set position = j 11 | (end of if) 12 | (end of loop) 13 | 14 | step 5: swapping a[position] with a[i] 15 | (end of loop) 16 | step 6: END 17 | ``` 18 | 19 | 20 | -------------------------------------------------------------------------------- /Searching/Linear Search/algorithm.md: -------------------------------------------------------------------------------- 1 | ## Linear Search 2 | ### Linear search is a very simple search algorithm. In this type of searching, a sequential search is made over all items one by one. Every item is checked and if a match is found then that particular item is returned, otherwise the search continues till the end of the data collection. 3 | ![This is an image](https://miro.medium.com/max/1140/1*QlhHM_8r-AUnY6I2nyKHnA.gif) 4 | > Image link [here](https://medium.com/karuna-sehgal/an-simplified-explanation-of-linear-search-5056942ba965). 5 | 6 | ## Algorithm 7 | ``` 8 | Linear Search ( Array A, Value x) 9 | Step 1: Set i to 1 10 | Step 2: if i > n then go to step 7 11 | Step 3: if A[i] = x then go to step 6 12 | Step 4: Set i to i + 1 13 | Step 5: Go to Step 2 14 | Step 6: Print Element x Found at index i and go to step 8 15 | Step 7: Print element not found 16 | Step 8: Exit 17 | ``` 18 | -------------------------------------------------------------------------------- /Sorting/Insertion Sort/C++/InsertionSort.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @file InsertionSort.cpp 3 | * 4 | * @brief Implementation of Insertion Sort in C++ 5 | * 6 | * @author ashishlamsal 7 | * 8 | */ 9 | 10 | #include 11 | 12 | void insertion_sort(int arr[], int n) { 13 | for (int i = 1; i < n; i++) { 14 | int current = arr[i]; 15 | 16 | // prev of currrent 17 | int j = i - 1; 18 | while (j >= 0 && arr[j] > current) { 19 | 20 | // shift j to right 21 | arr[j + 1] = arr[j]; 22 | j--; 23 | } 24 | arr[j + 1] = current; 25 | } 26 | } 27 | 28 | 29 | // Sample Input: [ 8 6 10 5 9 3 20 26 4 ] 30 | // Sample Output: [ 3 4 5 6 8 9 10 20 26 ] 31 | 32 | // Best Time Complexity (when array is already sorted): O(n) 33 | // Worst Time Complexity (when array is not sorted): O(n^2) 34 | // SPACE COMPLEXITY: O(1) 35 | -------------------------------------------------------------------------------- /Sorting/Selection Sort/C++/SelectionSort.c++: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | // taking vector array as input, along with it's size n 6 | vector selectionsort(vector a, int n) 7 | { 8 | int i, position, minimum, j, temp; 9 | for (i = 0 ; i < n - 1 ; i++){ 10 | minimum = a[i]; 11 | position = i; 12 | for (j= i + 1; j < n; j++) { 13 | if (minimum > a[j]) { 14 | minimum = a[j]; 15 | position = j; 16 | } 17 | } 18 | temp = a[i]; 19 | a[i] = a[position]; 20 | a[position] = temp; 21 | } 22 | return a; 23 | } 24 | 25 | 26 | /* 27 | Sample Input: 28 | 12 -78 99 -23 55 36 91 29 | */ 30 | 31 | /* 32 | Output for above input 33 | -78 -23 12 36 55 91 99 34 | */ 35 | 36 | /* 37 | TIME COMPLEXITY: O(n^2) 38 | SPACE COMPLEXITY: O(1) 39 | */ 40 | 41 | -------------------------------------------------------------------------------- /Sorting/Insertion Sort/Java/InsertionSort.java: -------------------------------------------------------------------------------- 1 | 2 | public class InsertionSort { 3 | 4 | public static int[] insertionSort(int[] array) { 5 | if (array == null || array.length == 0) //if array is not sortable, then return null 6 | return null; 7 | 8 | for (int i = 1; i < array.length; i++) { 9 | int currentElement = array[i]; 10 | int j = i-1; 11 | for (;j >= 0; j--) //we move the current element to the correct position at the left of the array in this step 12 | if (array[j] > currentElement) 13 | array[j+1] = array[j]; 14 | else 15 | break; 16 | 17 | array[j+1] = currentElement; //we placed the current element in correct position 18 | } 19 | return array; 20 | } 21 | 22 | } 23 | 24 | /* 25 | * Sample Input: [4,3,2,1] 26 | * Sample Output: [1,2,3,4] 27 | * 28 | * Time Complexity in Worst Case: O(n^2) 29 | * Space Complexity in Worst Case: O(1) 30 | * 31 | */ 32 | 33 | 34 | -------------------------------------------------------------------------------- /Searching/Binary Search/Java/BinarySearch.java: -------------------------------------------------------------------------------- 1 | class BinarySearchExample{ 2 | public static void binarySearch(int arr[], int first, int last, int key){ 3 | int mid = (first + last)/2; 4 | while( first <= last ){ 5 | if ( arr[mid] < key ){ 6 | first = mid + 1; 7 | }else if ( arr[mid] == key ){ 8 | System.out.println("Element is found at index: " + mid); 9 | break; 10 | }else{ 11 | last = mid - 1; 12 | } 13 | mid = (first + last)/2; 14 | } 15 | if ( first > last ){ 16 | System.out.println("Element is not found!"); 17 | } 18 | } 19 | public static void main(String args[]){ 20 | int arr[] = {10,20,30,40,50}; 21 | int key = 30; 22 | int last=arr.length-1; 23 | binarySearch(arr,0,last,key); 24 | } 25 | } -------------------------------------------------------------------------------- /Searching/Interpolation Search/C++/InterpolationSearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int InterpolationSearch(int arr[], int low, int high, int key){ 5 | int pos; 6 | while(low<=high){ 7 | //pos = low + int(((key - arr[low])/(arr[high] - arr[low])))*(high - low); 8 | pos = low + (((double)(high - low) / (arr[high] - arr[low])) * (key - arr[low])); 9 | if(arr[pos] == key){ 10 | return pos; 11 | } 12 | if(arr[pos] < key){ 13 | low = pos + 1; 14 | } 15 | if(arr[pos] > key){ 16 | high = pos - 1; 17 | } 18 | } 19 | return -1; 20 | } 21 | 22 | /* 23 | Sample Input arr = {16, 18, 19, 20, 21, 22, 23, 24, 33, 35, 42, 47} 24 | key = 23 25 | 26 | output: 6 27 | 28 | time complexity best case: O(1) 29 | time complexity average case: O(log2(log2N)) 30 | time complexity worst case: O(N) 31 | space complexity: O(1) 32 | 33 | */ -------------------------------------------------------------------------------- /Sorting/Heap Sort/algorithm.md: -------------------------------------------------------------------------------- 1 | ## HEAP SORT 2 | 3 | # Heap sort is one of the sorting algorithms used to arrange a list of elements in order. 4 | 5 | # Heapsort algorithm uses one of the tree concepts called Heap Tree. 6 | 7 | #### In this sorting algorithm, we use Max Heap to arrange list of elements in Descending order and Min Heap to arrange list elements in Ascending order. 8 | 9 | • Step 1 - Make a Binary Tree with given list of Elements. 10 | 11 | • Step 2 - Convert the Binary Tree into Min Heap. 12 | 13 | • Step 3 - Delete the root element from Min Heap using Heapify method. 14 | 15 | • Step 4 - Put the deleted element into the Sorted list. 16 | 17 | • Step 5 - Repeat the same until Min Heap becomes empty. 18 | 19 | • Step 6 - Display the sorted list. 20 | 21 | Complexity of the Heap Sort Algorithm 22 | 23 | To sort an unsorted list with 'n' number of elements, following are the complexities. 24 | 25 | Worst Case: O(n log n) 26 | 27 | Best Case : O(n log n) 28 | -------------------------------------------------------------------------------- /Sorting/Selection Sort/Java/SelectionSort.java: -------------------------------------------------------------------------------- 1 | public class SelectionSort { 2 | public static int[] selectionSort(int[] array) { 3 | if (array == null || array.length == 0) //if array is not sortable, then return null 4 | return null; 5 | for (int i = 0; i < array.length-1; i++) { 6 | int minIndex = i; 7 | for (int j = i + 1; j < array.length;j++) //we find the index of smallest element at the rest of the array in this for loop 8 | if (array[j] < array[minIndex]) 9 | minIndex = j; 10 | int temp = array[i]; //we swap the smallest element with current index element 11 | array[i] = array[minIndex]; 12 | array[minIndex] = temp; 13 | } 14 | return array; 15 | } 16 | } 17 | 18 | /* 19 | * Sample Input: [4,3,2,1] 20 | * Sample Output: [1,2,3,4] 21 | * 22 | * Time Complexity in Best Case: O(n^2) 23 | * Time Complexity in Average Case: O(n^2) 24 | * Time Complexity in Worst Case: O(n^2) 25 | * Space Complexity in Worst Case: O(1) 26 | */ -------------------------------------------------------------------------------- /Sorting/Insertion Sort/algorithm.md: -------------------------------------------------------------------------------- 1 | INSERTION SORT ALGORITHM 2 | 3 | In insertion sort algorithm, we sort the elements in ascending order just like sorting a deck of cards. 4 | First of all, we assume the first element of the array as sorted and start with the second element. 5 | If the second element is smaller than the first element then we swap them. In this case, first two 6 | elements will be sorted. After that, we iterate this step with other elements of the array and we place 7 | them on the correct position on the left-side of the array one by one. In the end, we get a sorted array 8 | with ascending order. 9 | 10 | Step 1: for i = 2 to array.length-1 11 | Step 2: Let currentElement = array[i] 12 | Step 3: for j = i-1 to 0 13 | Step 4: if (array[j] > currentElement) 14 | Set array[j+1] = array[j]; 15 | else 16 | break; 17 | end_for 18 | Step 5:Set array[j+1] = currentElement 19 | end_for 20 | Step 6: return array 21 | Step 7: END 22 | -------------------------------------------------------------------------------- /Sorting/Quick Sort/Python/QuickSort.py: -------------------------------------------------------------------------------- 1 | # This will sort array in place 2 | 3 | def partitionArray(array, lowIndex, highIndex): 4 | index = lowIndex - 1 5 | # pivot is the last elemet 6 | pivot = array[highIndex] 7 | 8 | for k in range(lowIndex, highIndex): 9 | # Move to the left elements that are less than or equal to pivot 10 | if array[k] <= pivot: 11 | index += 1 12 | array[index], array[k] = array[k], array[index] 13 | 14 | # Move pivot to end of the array 15 | array[index + 1], array[highIndex] = array[highIndex], array[index + 1] 16 | 17 | # Return pivot position 18 | return index + 1 19 | 20 | def quickSort(array, lowIndex, highIndex): 21 | if len(array) == 1: 22 | return array 23 | 24 | if lowIndex < highIndex: 25 | pivotPosition = partitionArray(array, lowIndex, highIndex) 26 | quickSort(array, lowIndex, pivotPosition - 1) 27 | quickSort(array, pivotPosition + 1, highIndex) -------------------------------------------------------------------------------- /Sorting/Merge Sort/Python/MergeSort.py: -------------------------------------------------------------------------------- 1 | def merge(array: [int], beg: int, m: int, end: int): 2 | temp = [0]* (end - beg + 1) 3 | i,j,k = beg, m + 1, 0 4 | 5 | while i <= m and j <= end: 6 | if array[i] <= array[j]: 7 | temp[k] = array[i] 8 | k += 1 9 | i += 1 10 | else: 11 | temp[k] = array[j] 12 | k += 1 13 | j += 1 14 | 15 | while i <= m: 16 | temp[k] = array[i] 17 | i += 1 18 | k += 1 19 | 20 | while j <= end: 21 | temp[k] = array[j] 22 | j += 1 23 | k += 1 24 | 25 | for i in range(beg,end+1): 26 | array[i] = temp[i - beg] 27 | 28 | def Merge_sort(array: [int], beg: int, end: int): 29 | if beg < end: 30 | m = (beg + end)/2 31 | Merge_sort(array,beg,m) 32 | Merge_sort(array,m+1,end) 33 | merge(array,beg,m,end) 34 | 35 | #Sample Input: 5 14 35 20 7 2 36 | #Sample Output: 2 5 7 14 20 35 37 | #Time Complexity: θ(nLogn) in all cases(worst, average and best) 38 | #Space Complexity: O(n) 39 | -------------------------------------------------------------------------------- /Graph Algorithms/Dijkstra/C++/Dijkstra.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @brief priyanshi2808 3 | * find the shortest paths from the source to all vertices in the given graph. 4 | * vectoradj[] push{node , weight } 5 | * Time Complexity : O ( V^2 ) ,with min-priority queue : O ( V + E l o g V ) 6 | * 7 | */ 8 | 9 | vector dijkstra(vector < pair adj[], int src) 10 | { 11 | 12 | priority_queue, vector>, greater>> pq; 13 | vector dist(n + 1, 1e6); // n is the no of edges from 1 to n+1 14 | pq.push({0, src}) // distance 0 for node src to stc 15 | while (!pq.empty()) 16 | { 17 | int currNode = pq.top().second; 18 | int currDist = pq.top().first; 19 | pq.pop(); 20 | for (pair edge : adj[currNode]) 21 | { 22 | if (edge.second + currDist < dist[edge.first]) 23 | { 24 | dist[edge.first] = currDist + edge.second; 25 | pq.push({dist[edge.first], edge.first}); 26 | } 27 | } 28 | } 29 | return dist; 30 | } 31 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 CodeChefMUST 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 | -------------------------------------------------------------------------------- /Graph Algorithms/Topological Sort/C++/TopologicalSort.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @file TopologicalSort.cpp 3 | * @author Priyanshi Dixit 4 | * @brief 5 | * @version 0.1 6 | * @date 2021-10-25 7 | * 8 | * @copyright Copyright (c) 2021 9 | * 10 | */ 11 | /** 12 | * note :- 13 | * there are no unique topological sort for a graph 14 | * can be used for cycle detection 15 | * Valid for acyclic directed graphs 16 | * Here we have used Kahn's Algorithm 17 | * 18 | */ 19 | // adj represents the graph , indegree is for each node and n is the no of nodes 20 | 21 | vector kahns(vector &adj[], vector &indegree, int n) 22 | { 23 | queue q; 24 | for (int i = 1; i <= n; i++) 25 | { 26 | if (indegree[i] == 0) 27 | { 28 | q.push(i); 29 | } 30 | } 31 | vector res; 32 | while (!q.empty()) 33 | { 34 | int curr = q.front(); 35 | q.pop(); 36 | res.push_back(curr); 37 | for (auto i : adj[curr]) 38 | { 39 | indegree[i]--; 40 | if (indegree[i] == 0) 41 | q.psuh(i); 42 | } 43 | } 44 | return res; 45 | } -------------------------------------------------------------------------------- /Sorting/Bubble Sort/C++/BubbleSort.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @file BubbleSort.cpp 3 | * 4 | * @brief Implementation of Bubble Sort in C++ 5 | * 6 | * @author ashishlamsal 7 | * 8 | */ 9 | 10 | #include 11 | 12 | void swap(int& a, int& b) { 13 | int temp = a; 14 | a = b; 15 | b = temp; 16 | } 17 | 18 | void bubble_sort(int arr[], int n) { 19 | bool isSorted; 20 | for (int i = 0; i < n - 1; i++) { 21 | 22 | // isSorted flag to monitor swapping 23 | isSorted = true; 24 | for (int j = 0; j < (n - 1 - i); j++) { 25 | if (arr[j] > arr[j + 1]) { 26 | 27 | // swap elements and set isSorted flag to false 28 | swap(arr[j], arr[j + 1]); 29 | isSorted = false; 30 | } 31 | } 32 | 33 | // returns if arr is sorted 34 | if (isSorted) 35 | return; 36 | } 37 | } 38 | 39 | 40 | // Sample Input: [ 8 16 10 5 9 3 2 6 4 ] 41 | // Sample Output: [ 2 3 4 5 6 8 9 10 16 ] 42 | 43 | // Best Time Complexity (when array is already sorted): O(n) 44 | // Worst Time Complexity (when array is not sorted): O(n^2) 45 | // SPACE COMPLEXITY: O(1) 46 | -------------------------------------------------------------------------------- /Searching/Ternary Search/Python/TernarySearch.py: -------------------------------------------------------------------------------- 1 | # Here, left = 0 and right = length of array - 1 2 | 3 | def ternarySearch(ar , key , left , right): 4 | 5 | if left < right: 6 | 7 | inter = (right - left ) // 3 8 | rightmid = right - inter 9 | leftmid = left +inter 10 | 11 | if (ar[rightmid] == key ): 12 | 13 | print( "Element found!Index:",rightmid ) 14 | return 0; 15 | 16 | elif ( ar[leftmid] == key ): 17 | 18 | print( "Element found!Index:",leftmid ) 19 | return 0; 20 | 21 | elif ( key < ar[rightmid] and key > ar[leftmid] ) : 22 | return ternarySearch( ar , key , leftmid , rightmid) 23 | 24 | elif ( key > ar[rightmid] ) : 25 | return ternarySearch( ar , key , rightmid , right) 26 | 27 | else: 28 | return ternarySearch( a , key , left , leftmid ) 29 | 30 | print( "Key not found!" ) 31 | 32 | return 0 33 | 34 | 35 | 36 | # Sample Input : 37 | # Ar = [12 , 90 , 67 , 19 , 18] 38 | # Key = 19 39 | 40 | # Output: 41 | # Element found!Index: 3 42 | -------------------------------------------------------------------------------- /Sorting/Selection Sort/C#/SelectionSort.cs: -------------------------------------------------------------------------------- 1 | public class SelectionSort { 2 | public static void selectionSort(int[] array) 3 | { 4 | for (int i = 0; i < array.Length - 1; i++) 5 | { 6 | int min_index = i; 7 | for (int j = i + 1; j < array.Length; j++) 8 | if (array[j] < array[min_index]) 9 | min_index = j; //Initial minimum index is updated 10 | 11 | 12 | int temp = array[min_index]; //Then it swapped the smallest element with current index element 13 | array[min_index] = array[i]; 14 | array[i] = temp; 15 | } 16 | } 17 | 18 | //MAIN METHOD 19 | /* 20 | public static void Main() 21 | { 22 | int[] a = { 23, 25, 22, 21, 27 }; 23 | selectionSort(a); 24 | 25 | //After sorted 26 | for (int i = 0; i < a.Length; i++) 27 | { 28 | if(i != a.Length-1) 29 | Console.Write(a[i] + ", "); 30 | else 31 | Console.Write(a[i]); 32 | } 33 | } 34 | */ 35 | 36 | 37 | /* 38 | Time complexity in the worst case: O(N^2) 39 | Space complexity: O(1) 40 | */ 41 | } -------------------------------------------------------------------------------- /Searching/Ternary Search/Java/TernarySearch.java: -------------------------------------------------------------------------------- 1 | public class TernarySearch { 2 | public static int ternarySearch(int leftIndex, int rightIndex, int number, int[] array) { // if array is not sorted, then it may return a wrong result 3 | if (rightIndex>=leftIndex) { 4 | int middleFirst = leftIndex + (rightIndex-leftIndex)/3; 5 | int middleSecond = rightIndex - (rightIndex-leftIndex)/3; 6 | if(array[middleFirst] == number) 7 | return middleFirst; 8 | if(array[middleSecond] == number) 9 | return middleSecond; 10 | if(number < array[middleFirst]) 11 | return ternarySearch(leftIndex, middleFirst-1, number, array); 12 | if(number > array[middleFirst] && number < array[middleSecond]) 13 | return ternarySearch(middleFirst+1, middleSecond-1, number, array); 14 | if(number > array[middleSecond]) 15 | return ternarySearch(middleSecond+1, rightIndex, number, array); 16 | } 17 | return -1;//if number is not found in the array, then it returns -1 18 | } 19 | } 20 | 21 | /* 22 | * Sample Input: (0,3,1,{0,1,2,3}) 23 | * Sample Output: 1 24 | * 25 | * Time Complexity in Best Case : O(1) 26 | * Time Complexity in Worst Case : O(log(3)n) 27 | * Space Complexity in Worst Case: O(1) 28 | */ 29 | 30 | -------------------------------------------------------------------------------- /Traversal Algorithms/Graph Traversals/DFS/C++/DFS.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @file DFS.cpp 3 | * @author Priyanshi Dixit 4 | * @brief 5 | * dfs traversal in a graph : 6 | * input 1: 7 | * 1--> 2--| 8 | * ^ | | 9 | * | \/ | 10 | * | 3 | 11 | * 0<------| 12 | * output : starting from node 1: 1 , 2 , 3, 0 13 | * 14 | * @version 0.1 15 | * @date 2021-10-20 16 | * 17 | * @copyright Copyright (c) 2021 18 | * 19 | */ 20 | 21 | /* node is referd to the current node we are processing 22 | adj represents the graphical relationship of nodes 23 | vis takes the record of node that are visited at any time of traversal 24 | 25 | */ 26 | 27 | void dfsUtil(int node, vector &adj[], vector &vis, vector &ans) 28 | { 29 | vis[node] = true; 30 | ans.push_back(node); 31 | for (auto i : adj[node]) 32 | { 33 | if (vis[i] == false) 34 | dfsUtil(i); 35 | } 36 | } 37 | vector dfs(int startingNode, vector &adj[]) 38 | { 39 | vector vis(n + 1, false) // n is the no of nodes 40 | vector 41 | ans; 42 | dfsUtil(startingNode, adj, vis, ans); 43 | return ans; 44 | } -------------------------------------------------------------------------------- /Graph Algorithms/Topological Sort/Python/TopologicalSort.py: -------------------------------------------------------------------------------- 1 | # Takes graph in the form of adjacency list in input, and gives sorted list as output 2 | def topological_sort(graph: defaultdict(list)): 3 | v = len(graph) # getting the number of vertices 4 | sorted = [] 5 | indegrees = [0] * v # array that stores the indegrees of each node 6 | zero_incoming = [] # queue that stores all the nodes that have no incoming edges 7 | for node in graph: 8 | for neighbour in graph[node]: 9 | indegree[neighbour] += 1 # populating the indegree array with indegrees 10 | for node in range(v): 11 | if indegrees[node] == 0: 12 | zero_incoming.append(i) # adding nodes with zero indegree to queue 13 | visited_nodes = 0 # to check the number of nodes visited 14 | while zero_incoming: # while the queue has nodes with 0 indegrees 15 | node = zero_incoming.pop(0) 16 | sorted.append(node) # add node to topological order 17 | for neighbour in graph[node]: 18 | indegrees[neighbour] -= 1 # removing the outgoing edges 19 | if indegrees[neighbour] == 0: 20 | zero_incoming.append(neighbour) # adding new nodes with 0 indegree to queue 21 | visited_nodes += 1 22 | 23 | assert visited_nodes == v, "The graph is cyclic!" # if graph is cyclic, raise error 24 | return sorted -------------------------------------------------------------------------------- /Traversal Algorithms/Tree Traversals/Level Order Traversal - Binary Tree/C++/LeftViewBinaryTree.cpp.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Input Tree - 3 | 36 4 | / \ 5 | 5 23 6 | / \ / \ 7 | 9 12 45 56 8 | / 9 | 20 10 | Output - 11 | 36 5 9 20 12 | Time Complexity - O(n) -- Traversal of at-most n elements of the tree 13 | Space Complexity - O(n) -- size of queue = number of elements in the tree // since no element will be enqueued twice. 14 | */ 15 | 16 | void LeftViewBinaryTree(Node* root) 17 | { 18 | if (!root) 19 | return; 20 | 21 | queue lv; 22 | lv.push(root); 23 | 24 | while (!lv.empty()) 25 | { 26 | // number of nodes at current level 27 | int s = lv.size(); 28 | 29 | // Traverse all nodes of current level 30 | for(int i = 1; i <= s; i++) 31 | { 32 | Node* temp = lv.front(); 33 | lv.pop(); 34 | 35 | // Print the left most element at the current level 36 | if (i == 1) 37 | cout<data<<" "; 38 | 39 | // Add left node to lv 40 | if (temp->left != NULL) 41 | lv.push(temp->left); 42 | 43 | // Add right node to lv 44 | if (temp->right != NULL) 45 | lv.push(temp->right); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Searching/Binary Search/C++/binarySearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int binarySearch(vectornums, int target){ 6 | int right = (nums.size())-1; 7 | int left = 0; 8 | int middle; 9 | while(right >= left) 10 | { 11 | middle = left + (right - left) / 2; 12 | if(nums[middle] == target){ 13 | return middle; 14 | } 15 | else if(nums[middle] > target){ 16 | right = (middle-1); 17 | } 18 | else{ 19 | left = (middle+1); 20 | } 21 | } 22 | return -1; 23 | } 24 | 25 | int main() 26 | { 27 | unsigned int i; 28 | int n; 29 | vectornums; 30 | cout << "Enter the amount of numbers to be evaluated: "; 31 | cin >> i; 32 | cout << "Enter the numbers to be evaluated: " << endl; 33 | while (nums.size() < i && cin >> n){ 34 | nums.push_back(n); 35 | } 36 | int target; 37 | cout << "Enter the target you want to search\n"; 38 | cin >> target; 39 | int result = binarySearch(nums,target); 40 | if (result == -1){ 41 | cout << "The target is not found ! "; 42 | } 43 | else{ 44 | cout << "The target is present at index: " << result; 45 | } 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /Traversal Algorithms/Tree Traversals/Level Order Traversal - Binary Tree/C++/HeightOfTree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Sample Input:: 3 | 4 | Input Tree 1: 5 | 1 6 | / \ 7 | 6 5 8 | / 9 | 2 10 | output 1: 3 11 | 12 | Input Tree 2: 13 | 36 14 | / \ 15 | 5 23 16 | / \ / \ 17 | 9 12 45 56 18 | / 19 | 20 20 | output 2: 4 21 | 22 | Time Complexity - O(n) -- Traversal of all n elements of the tree 23 | Space Complexity - O(n) -- size of queue = number of elements in the tree // since no element will be enqueued twice. 24 | */ 25 | 26 | int HeightOfTree(Node* root) 27 | { 28 | int height=0; 29 | 30 | queue q; 31 | 32 | q.push(root); 33 | q.push(NULL); 34 | while (!q.empty()) 35 | { 36 | Node* curr=q.front(); 37 | q.pop() 38 | 39 | if(curr==NULL)//NULL means that a level has been traversed hence increment height 40 | height++; 41 | 42 | if(curr!=NULL)//Push the right and lift child of current Node 43 | { 44 | if(curr->left) 45 | q.push(curr->left); 46 | if(curr->right) 47 | q.push(curr->right); 48 | } 49 | else if(!q.empty())//If queue still have elements then push NULL 50 | q.push(NULL); 51 | } 52 | 53 | return height; 54 | } -------------------------------------------------------------------------------- /Sorting/Insertion Sort/C#/InsertionSort.cs: -------------------------------------------------------------------------------- 1 | public class InsertionSort { 2 | public static void insertionSort(int[] array) 3 | { 4 | for (int i = 1; i < array.Length; ++i)//It starts from index 1 to compare the current element with remained left side elements of the array 5 | { 6 | int current = array[i]; 7 | int j = i - 1; 8 | 9 | while (j >= 0 && array[j] > current) //This loop allows the element to be compared with the elements before it 10 | { 11 | array[j + 1] = array[j]; 12 | j-=1; 13 | } 14 | array[j + 1] = current; //After while loop, current element placed in the correct position 15 | } 16 | } 17 | 18 | //MAIN METHOD 19 | /* 20 | public static void Main() 21 | { 22 | int[] a = { 23, 25, 22, 21, 27 }; 23 | insertionSort(a); 24 | 25 | //After sorted 26 | for (int i = 0; i < a.Length; i++) 27 | { 28 | if(i != a.Length-1) 29 | Console.Write(a[i] + ", "); 30 | else 31 | Console.Write(a[i]); 32 | } 33 | } 34 | */ 35 | 36 | 37 | /* 38 | Time complexity in the worst case: O(N^2) 39 | Space complexity: O(1) 40 | */ 41 | } -------------------------------------------------------------------------------- /Sorting/Merge Sort/C++/MergeSort.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @file MergeSort.cpp 3 | * 4 | * @brief Implementation of Merge Sort in C++ 5 | * 6 | * @author ashishlamsal 7 | * 8 | */ 9 | 10 | #include 11 | 12 | void merge(int left[], int right[], int result[], int l1, int l2) { 13 | int i = 0, j = 0, k = 0; 14 | 15 | while (i < l1 && j < l2) { 16 | if (left[i] <= right[j]) 17 | result[k++] = left[i++]; 18 | else 19 | result[k++] = right[j++]; 20 | } 21 | 22 | while (i < l1) 23 | result[k++] = left[i++]; 24 | 25 | while (j < l2) 26 | result[k++] = right[j++]; 27 | } 28 | 29 | void merge_sort(int arr[], int n) { 30 | if (n < 2) return; 31 | 32 | // divide 33 | int middle = n / 2; 34 | int* left = new int[middle]; 35 | for (int i = 0; i < middle; i++) 36 | left[i] = arr[i]; 37 | 38 | int* right = new int[n - middle]; 39 | for (int i = middle; i < n; i++) 40 | right[i - middle] = arr[i]; 41 | 42 | // sort 43 | merge_sort(left, middle); 44 | merge_sort(right, n - middle); 45 | 46 | // conquer 47 | merge(left, right, arr, middle, n - middle); 48 | 49 | delete[] left; 50 | delete[] right; 51 | } 52 | 53 | // Sample Input: [ 8 6 10 5 9 3 2 6 4 ] 54 | // Sample Output: [ 2 3 4 5 6 6 8 9 10 ] 55 | 56 | // TIME COMPLEXITY: O(nlog(n)) 57 | // SPACE COMPLEXITY: O(n) -------------------------------------------------------------------------------- /Traversal Algorithms/Graph Traversals/DFS/Algorithm.md: -------------------------------------------------------------------------------- 1 | # Graph Depth-first search (DFS) 2 | 3 | ## Definition 4 | ``` 5 | "Depth-first search (DFS) is an algorithm for traversing 6 | or searching tree or graph data structures. The algorithm 7 | starts at the root node (selecting some arbitrary node as 8 | the root node in the case of a graph) and explores as far 9 | as possible along each branch before backtracking." 10 | 11 | https://en.wikipedia.org/wiki/Depth-first_search 12 | ``` 13 | 14 | ## Steps 15 | 1. Start a stack with starting node (root node) 16 | 2. Check if node at top of the stack (actual node) has been visited before. If true, remove the node from the stack. 17 | 3. Otherwise, check if actual node has target value. If true, return actual node. 18 | 4. If false, push all adjacent nodes of actual node into the stack. 19 | 5. Repeat step 2 until find the desired node at step 3 or exhaust the stack 20 | 21 | ## Example 22 | 23 | ![Simple DFS](https://upload.wikimedia.org/wikipedia/commons/7/7f/Depth-First-Search.gif) 24 | 25 | This first example shows the DFS in a ~~tree~~ uni-direcional graph. 26 | 27 | ![Complex DFS](https://codeforces.com/predownloaded/8d/be/8dbe5d89e58b67f3d8e4d8e0e8eb3358ba921b28.png) 28 | 29 | This second example shows the DFS in a (actual) bidirectional graph. The white circles are the not visited nodes, the gray circles are the visited node and the red circle is the actual node. -------------------------------------------------------------------------------- /Searching/Ternary Search/algorithm.md: -------------------------------------------------------------------------------- 1 | ### TERNARY SEARCH 2 | Ternary Search is a searching algorithm which works like binary search. It is based on divide and conqure. Difference between Binary Search and Ternary Search: In Binary search, sorted array is divided into two equal parts while in Ternary Search, sorted array is divided into three equal parts. 3 | **Main condition for Ternary Search :** Array must be sorted. 4 | ``` 5 | int ternary_search(int a[] , int element , int right , int left) 6 | Step 1: The array is divided into three equal parts. 7 | Step 2: Check if right is greater than left. 8 | Step 3: Calculate interval, followed by left middle index and then right middle index. 9 | Step 4: if right middle element = element 10 | exit 11 | if left middle element = element 12 | exit 13 | Step 5: If both of these conditions are not true, we will recursively call ternary_search function by following below conditions : 14 | if element is less than right middle element and element is greater than left middle element 15 | return ternary_search (a, element, rmid, lmid) 16 | if element is less than left middle element 17 | return ternary_search (a, element, lmid , left) 18 | else ( Both of the above conditions are not true) 19 | return ternary_search (a, element, right, rmid) 20 | 21 | (end of if loop) 22 | Step 6: exit 23 | 24 | ``` 25 | -------------------------------------------------------------------------------- /Graph Algorithms/Topological Sort/Algorithm.md: -------------------------------------------------------------------------------- 1 | ## Abstract 2 | Topological Sorting or Kahn's algorithm is an algorithm that orders a directed acylic graph in a way such that each node appears before all the nodes it points to in the returned order, i.e. if we have a --> b, a must appear before b in the topological order. 3 | It's main usage is to detect cycles in directed graphs, since no topological order is possible for a graph that contains a cycle. Some of it's uses are: deadlock detection in OS, Course schedule problem etc. 4 | 5 | Here's the algorithm step by step: 6 | 1. Find a vertex that has indegree = 0 (no incoming edges) 7 | 2. Remove all the edges from that vertex that go outward (make it's outdegree = 0, remove outgoing edges) 8 | 3. Add that vertex to the array representing topological sorting of the graph 9 | 4. Repeat till there are no more vertices left. 10 | 11 | ## Pseudocode: 12 | ``` 13 | sorted <-- Empty list initially, of the topologically sorted elements 14 | zero_incoming <-- set of nodes with indegree = 0 15 | 16 | while zero_incoming is not empty do: 17 | remove a node n from zero_incoming 18 | add n to the sorted list 19 | for each node out with an edge from n to out do: 20 | remove edge from graph 21 | if out has no other incoming edges then: 22 | insert out in zero_incoming 23 | 24 | if graph has edges then: 25 | return Error {graph has at least 1 cycle} 26 | else 27 | return sorted {our final array} 28 | ``` -------------------------------------------------------------------------------- /Traversal Algorithms/Tree Traversals/Postorder Traversal - Binary Tree/C++/PostorderTraversal.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Sample Input:: 3 | Input Tree 1: 4 | 1 5 | / \ 6 | 6 5 7 | / 8 | 2 9 | output 1: [6, 2, 5, 1] 10 | Input Tree 2: 11 | 1 12 | / \ 13 | 2 3 14 | / \ 15 | 4 5 16 | 17 | Output 2: [4, 5, 2, 3, 1] 18 | */ 19 | 20 | /** Binary Tree Defination : 21 | struct Node { 22 | int data; 23 | Node *left; 24 | Node *right; 25 | Node(int x) : val(x), left(NULL), right(NULL) {} 26 | }; 27 | */ 28 | 29 | 30 | // Recursive code 31 | void recurPostorderTraversal(Node *a, vector &ans) 32 | { 33 | if (a == NULL) 34 | return; 35 | recurPostorderTraversal(a->left, ans); 36 | recurPostorderTraversal(a->right, ans); 37 | ans.push_back(a->data); 38 | } 39 | vector PostorderTraversal(Node *a) 40 | { 41 | vector ans; 42 | recurPostorderTraversal(a, ans); 43 | return ans; 44 | } 45 | 46 | // Iterative code 47 | vector iterpostordertraversal(Node *a) 48 | { 49 | stack s; 50 | s.push(a); 51 | vector ans; 52 | 53 | while(!s.empty) 54 | { 55 | Node * curr=s.top(); 56 | s.pop(); 57 | 58 | ans.push_back(curr->data); 59 | 60 | if(curr->left) 61 | s.push(curr->left); 62 | 63 | if(curr->right) 64 | s.push(curr->right); 65 | } 66 | reverse(ans.begin(),ans.end()); 67 | 68 | return ans; 69 | 70 | } 71 | 72 | //Time complexity : O(n) 73 | -------------------------------------------------------------------------------- /Searching/Ternary Search/C++/TernarySearch.c++: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // right = number of elements of array - 1 5 | // left = 0 6 | 7 | int ternary_search (int a[], int element, int right, int left); 8 | 9 | int ternary_search (int a[], int element, int right, int left) 10 | { 11 | if (right > left) 12 | { 13 | int rmid , lmid , interval; 14 | interval = (right - left) / 3; 15 | lmid = left + interval; 16 | rmid = right - interval; 17 | if (a[rmid] == element) 18 | { 19 | cout << "Element found at index value: " << rmid; 20 | exit(0); 21 | } 22 | if (a[lmid] == element) 23 | { 24 | cout << "Element found at index value: " << lmid; 25 | exit(0); 26 | } 27 | else if (element < a[rmid] && element > a[lmid]) 28 | { 29 | return ternary_search (a, element, rmid, lmid); 30 | } 31 | else if (element < a[lmid]) 32 | { 33 | return ternary_search (a, element, lmid, left); 34 | } 35 | else 36 | { 37 | return ternary_search (a, element, right, rmid); 38 | } 39 | } 40 | printf("Element not found!"); 41 | return 0; 42 | } 43 | 44 | /* 45 | Sample Input 1 : 46 | 47 | a= [-99 , 21 , 33 , 46] 48 | element = 89 49 | 50 | Output : Element not found! 51 | 52 | Sample Input 2 : 53 | 54 | a= [-99 , 21 , 33 , 46] 55 | element = 33 56 | 57 | Output : Element found at index value: 2 58 | */ 59 | 60 | /* 61 | TIME COMPLEXITY : O(log N) {base 3} 62 | 63 | SPACE COMPLEXITY : O(1) 64 | */ 65 | 66 | 67 | 68 | 69 | 70 | 71 | -------------------------------------------------------------------------------- /Traversal Algorithms/Tree Traversals/Inorder Traversal - Binary Tree/C++/InorderTraversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @brief priyanshi2808 3 | * 4 | */ 5 | 6 | /* 7 | ## example : 8 | Input Tree 1: 9 | 1 10 | / \ 11 | 12 4 12 | / 13 | 2 14 | output 1: [12, 1, 2, 4] 15 | Input Tree 2: 16 | 1 17 | / \ 18 | 2 3 19 | / \ 20 | 4 5 21 | 22 | Output 2: [4, 2, 5, 1, 3] 23 | */ 24 | 25 | /** Binary Tree Defination : 26 | struct Node { 27 | int val; 28 | Node *left; 29 | Node *right; 30 | Node(int x) : val(x), left(NULL), right(NULL) {} 31 | }; 32 | */ 33 | 34 | // Recursive code 35 | void UtilInorderTraversal(Node *A, vector &ans) 36 | { 37 | if (A == NULL) 38 | return; 39 | UtilInorderTraversal(A->left, ans); 40 | ans.push_back(A->val); 41 | UtilInorderTraversal(A->right, ans); 42 | } 43 | vector InorderTraversal(Node *A) 44 | { 45 | vector ans; 46 | UtilInorderTraversal(A, ans); 47 | return ans; 48 | } 49 | 50 | // Iterative code 51 | vector inorderTraversal(Node *A) 52 | { 53 | stack s; 54 | vector ans; 55 | Node *root = A; 56 | while (true) 57 | { 58 | while (root) 59 | { 60 | s.push(root); 61 | root = root->left; 62 | } 63 | 64 | if (s.empty()) 65 | { 66 | break; 67 | } 68 | 69 | root = s.top(); 70 | s.pop(); 71 | ans.push_back(root->val); 72 | root = root->right; 73 | } 74 | return ans; 75 | } 76 | 77 | //Time complexity : O(n) 78 | -------------------------------------------------------------------------------- /Dynamic Programming/Knapsack/algorithm.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 0-1 Knapsack Dynamic Programming 3 | author: Vishal Ambavade (@VishalAmbavade) 4 | date: 2021-10-13 5 | --- 6 | 7 | ![Knapsack Visual Representation](knapsack_1.jpg) 8 | 9 |

Accoridng to Wikipedia,

10 | 11 | > Given a set of items, each with a weight and a value, determine the number of each item to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large as possible. 12 | 13 |
14 |

There are a few variations of Knapsack problem:

15 | 16 | - 0-1 Knapsack 17 | - Bounded knapsack 18 | - Unbounded Knapsack 19 | 20 |
21 | 22 | Here, we'll see the algorithm of 0-1 Knapsack problem. 23 | 24 | ## Problem Details 25 | 26 |

Suppose we have a knapsack which can hold int w = 10 weight units. We have a total of int n = 4 items to choose from, whose values are represented by an array int[] val = {10, 40, 30, 50} and weights represented by an array int[] wt = {5, 4, 6, 3}. 27 | Since this is the 0–1 knapsack problem, we can either include an item in our knapsack or exclude it, but not include a fraction of it, or include it multiple times. 28 | 29 | ## Algorithm 30 | 31 | ```Dynamic-0-1-knapsack (v, w, n, W) 32 | for w = 0 to W do 33 | c[0, w] = 0 34 | for i = 1 to n do 35 | c[i, 0] = 0 36 | for w = 1 to W do 37 | if wi ≤ w then 38 | if vi + c[i-1, w-wi] then 39 | c[i, w] = vi + c[i-1, w-wi] 40 | else c[i, w] = c[i-1, w] 41 | else 42 | c[i, w] = c[i-1, w] 43 | ``` 44 | 45 | ![Knapsack solution](knapsack_2.png) 46 | -------------------------------------------------------------------------------- /Sorting/Quick Sort/C++/QuickSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void swap(int* a, int* b) 5 | { 6 | int t = *a; 7 | *a = *b; 8 | *b = t; 9 | } 10 | 11 | //Partition function takes last element of the array as pivot, 12 | //Places the pivot element at its correct position in sorted array 13 | //Places all other elements to either left or right of the pivot element 14 | //Elements smaller than pivot element is palced left of pivot and all greater elements to right of pivot. 15 | int partition (vector& arr, int l, int r) 16 | { 17 | int pivot = arr[r]; // pivot 18 | int i = (l - 1); 19 | 20 | for (int j = l; j <= r - 1; j++) 21 | { 22 | 23 | if (arr[j] < pivot) 24 | { 25 | i++; 26 | swap(&arr[i], &arr[j]); 27 | } 28 | } 29 | swap(&arr[i + 1], &arr[r]); 30 | return (i + 1); 31 | } 32 | 33 | //The main function that implements QuickSort 34 | //arr --> Vector array to be sorted, 35 | //l is the Starting index, 36 | //r is the final index 37 | 38 | 39 | vector quickSort(vector& arr, int l, int r)// taking vector array as input, along with first and last index 40 | { 41 | if (l < r) 42 | { 43 | /* pi is partitioning index, arr[p] is now 44 | at right place */ 45 | int pi = partition(arr, l, r); 46 | 47 | // Separately sort elements before 48 | // partition and after partition 49 | quickSort(arr, l, pi - 1); 50 | quickSort(arr, pi + 1, r); 51 | 52 | return arr; 53 | } 54 | } 55 | 56 | 57 | /* 58 | 59 | # Sample Input: 60 | 61 | Enter the number of elements: 62 | 7 63 | Enter the elements of array: 64 | 12 78 10 53 55 26 91 65 | ``` 66 | Array elements after applying Quick Sort: 67 | 10 12 26 53 55 78 91 68 | ``` 69 | 70 | **TIME COMPLEXITY:** O(nlogn) 71 | **SPACE COMPLEXITY:** O(1) 72 | 73 | */ 74 | -------------------------------------------------------------------------------- /Traversal Algorithms/Graph Traversals/BFS/C++/Algorithm.md: -------------------------------------------------------------------------------- 1 | Breadth First Search (BFS) 2 | 3 | Breadth first search is a graph traversal algorithm that starts traversing the graph from root node and explores all the neighbouring nodes. Then, it selects the nearest node and explore all the unexplored nodes. The algorithm follows the same process for each of the nearest node until it finds the goal. 4 | 5 | In the various levels of the data, you can mark any node as the starting or initial node to begin traversing. The BFS will visit the node and mark it as visited and places it in the queue. 6 | Now the BFS will visit the nearest and un-visited nodes and marks them. These values are also added to the queue. The queue works on the FIFO model. 7 | In a similar manner, the remaining nearest and un-visited nodes on the graph are analyzed marked and added to the queue. These items are deleted from the queue as receive and printed as the result. 8 | 9 | 10 | Algorithm 11 | 12 | Step 1: Start by putting any one of the graph's vertices at the back of a queue. 13 | 14 | Step 2: Take the front item of the queue and add it to the visited list. 15 | 16 | Step 3: Create a list of that vertex's adjacent nodes. Add the ones which aren't in the visited list to the back of the queue. 17 | 18 | Step 4: Keep repeating steps 2 and 3 until the queue is empty. 19 | 20 | Step 5: Print all the elements from the visited list. 21 | 22 | Step 6: Exit. 23 | 24 | 25 | 26 | Sample input graph: 27 | ┌──A──┐ 28 | │ │ 29 | B ┌──C──┐ 30 | │ │ 31 | ┌──D──┐ E 32 | │ │ 33 | F G 34 | Sample Output: 35 | A 36 | B 37 | C 38 | D 39 | E 40 | F 41 | G 42 | -------------------------------------------------------------------------------- /Searching/Binary Search/Java/InfiniteArray.java: -------------------------------------------------------------------------------- 1 | package com.company; 2 | 3 | /* 4 | 5 | Input Array - arr = {3,5,7,9,10,90,100,130,140,160,170} 6 | 7 | Target Element - 10 8 | 9 | Output - 4 10 | 11 | Time Complexity - O(log N) 12 | Space Complexity - O(log N) // Search Space is also reduced to chunks of the Infinite Array 13 | 14 | */ 15 | 16 | public class InfiniteArray { 17 | public static void main(String[] args) { 18 | int[] arr = {3,5,7,9,10,90,100,130,140,160,170}; 19 | int target = 10; 20 | System.out.println(ans(arr,target)); 21 | } 22 | 23 | /* 24 | 1. This function will divide the infinite array into chunks / Subarrays. 25 | 2. Will check if the target element lies in the chunk / subarray range. 26 | 3. If yes, binary search is applied on the chunk / subarray , returns -1 if not found. 27 | 4. Else, Chunk / Subarray range is changed. 28 | 5. -1 is return in case element does not exist. 29 | */ 30 | static int ans(int[] arr, int target) 31 | { 32 | int start = 0; 33 | int end = 1; 34 | while(target > arr[end]) 35 | { 36 | int newStart = end + 1; 37 | end = end + 2 * (end - start + 1); 38 | start = newStart; 39 | } 40 | return binarySearch(arr, target, start, end); 41 | } 42 | static int binarySearch(int[] arr, int target, int start, int end) 43 | { 44 | while(start <= end) 45 | { 46 | int mid = start + (end - start) / 2; 47 | if(target < arr[mid]) 48 | { 49 | end = mid - 1; 50 | } 51 | else if(target > arr[mid]) 52 | { 53 | start = mid + 1; 54 | } 55 | else 56 | return mid; 57 | 58 | } 59 | return -1; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /Graph Algorithms/Bellman Ford/Algorithm.md: -------------------------------------------------------------------------------- 1 | # Bellman Ford algorithm 2 | It helps us find the shortest path from a vertex to all other vertices of a weighted graph. 3 | It is very similar to the Dijkstra Algorithm. However, unlike the Dijkstra Algorithm, the Bellman-Ford algorithm can work on graphs with negative-weighted edges. This capability makes the Bellman-Ford algorithm a popular choice. 4 | 5 | ## Step by Step Algorithm 6 | 7 | - Start with the weighted graph. 8 | - Choose a starting vertex and assign infinity path values to all other vertices. 9 | - Visit each edge and relax the path distances if they are inaccurate. 10 | - We need to do this V times because in the worst case, a vertex's path length might need to be readjusted V times. 11 | - Notice how the vertex at the top right corner had its path length adjusted. 12 | - After all the vertices have their path lengths, we check if a negative cycle is present. 13 | 14 | 15 | ## Time Complexity 16 | 17 | **Best Case Complexity :** O(E) 18 | **Average Case Complexity :** O(VE) 19 | **Worst Case Complexity :** O(VE) 20 | 21 | ## Space Complexity 22 | O(V) 23 | 24 | ## INPUT 25 | V = 5 26 | E = 10 27 | S = 0 28 | 29 | Edge1: Source, Destination, Weight 30 | 0,1,6 31 | 32 | Edge2: Source, Destination, Weight 33 | 0,2,7 34 | 35 | Edge3: Source, Destination, Weight 36 | 1,2,8 37 | 38 | Edge4: Source, Destination, Weight 39 | 1,4,-4 40 | 41 | Edge5: Source, Destination, Weight 42 | 1,3,5 43 | 44 | Edge6: Source, Destination, Weight 45 | 3,1,-2 46 | 47 | Edge7: Source, Destination, Weight 48 | 2,3,-3 49 | 50 | Edge8: Source, Destination, Weight 51 | 2,4,9 52 | 53 | Edge9: Source, Destination, Weight 54 | 4,0,2 55 | 56 | Edge10: Source, Destination, Weight 57 | 4,3,7 58 | 59 | ##OUTPUT 60 | 61 | Vertex Distance from Source Distance 62 | 0 0 63 | 1 2 64 | 2 7 65 | 3 4 66 | 4 -2 67 | ======= 68 | 69 | 70 | -------------------------------------------------------------------------------- /Graph Algorithms/Bellman Ford/C++/BellmanFord.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * author: adityawithdoublea 3 | * Problem statement: Given a weighted, directed and connected graph of V vertices and E edges, we have to find the shortest distance of all the vertex's from the source vertex S. 4 | 5 | */ 6 | 7 | /* 8 | * adj: vector of vectors which represents the graph 9 | * S: source vertex 10 | */ 11 | vector BellmanFord(int V, vector> adj, int S) { 12 | 13 | //initialize distance of all vertices as infinite. 14 | vector dis(V); 15 | for (int i = 0; i < V; i++) 16 | dis[i] = 1e8; 17 | 18 | //initialize distance of source as 0 19 | dis[S] = 0; 20 | 21 | //relax all edges |V| - 1 times 22 | //a simple shortest path from src to any other vertex can have at-most |V| - 1 edges 23 | for (int i = 0; i < V - 1; i++) { 24 | 25 | for (int j = 0; j < adj.size(); j++) { 26 | if (dis[adj[j][0]] != 1e8 && dis[adj[j][0]] + adj[j][2] < 27 | dis[adj[j][1]]) 28 | dis[adj[j][1]] = 29 | dis[adj[j][0]] + adj[j][2]; 30 | } 31 | } 32 | 33 | return dis; 34 | } 35 | 36 | 37 | /* 38 | * Time Complexity : O(V*E); where V = number of vertices, E = number of edges 39 | * Space Complexity : O(V) 40 | * Sample Input : 0 41 | (3)/ \(1) 42 | / \ 43 | 1 ------ 2 (Source) 44 | (-1) 45 | 46 | V = 3, E = 3 47 | weight between edges = 3, 1, -1 48 | S = 2 49 | * Sample Output : For nodes 2 to 0, we can follow the path 2-0. This has a distance of 1. 50 | For nodes 2 to 1, we cam follow the path 2-0-1, which has a distance of 1+5 = 6 51 | So, our output will be: 1 6 0 52 | */ 53 | -------------------------------------------------------------------------------- /Sorting/Quick Sort/Algorithm.md: -------------------------------------------------------------------------------- 1 | # Quick Sort 2 | 3 | ![Quick Sort](https://upload.wikimedia.org/wikipedia/commons/f/fe/Quicksort.gif) 4 | 5 | Quicksort is an in-place sorting algorithm. Quicksort is a divide-and-conquer algorithm. It works by selecting a 'pivot' element from the array and partitioning the other elements into two sub-arrays, according to whether they are less than or greater than the pivot. The sub-arrays are then sorted recursively. This can be done in-place, requiring small additional amounts of memory to perform the sorting. 6 | 7 | Mathematical analysis of quicksort shows that, on average, the algorithm takes O(nlogn) comparisons to sort n items. In the worst case, it makes O(n^2) comparisons. 8 | 9 | ## Algorithm 10 | 11 | Quicksort applies the three-step divide-and-conquer process for sorting a typical subarray `A[p..r]`: 12 | 13 | - **Divide**: Partition the array `A[p..r]` into two subarrays `A[p .. q - 1]` and `A[q + 1 .. r]` such that each element of `A[p .. q - 1]` is less than or equal to `A[q]`, which is, in turn, less than or equal to each element of `A[q + 1 .. r]`. Compute the index q as part of this partitioning procedure. 14 | 15 | - **Conquer**: Sort the two subarrays `A[p .. q - 1]` and `A[q + 1 .. r]` by recursive calls to quicksort. 16 | 17 | - **Combine**: Because the subarrays are already sorted, no work is needed to combine them: the entire array `A[p..r]` is now sorted. 18 | 19 | ## PseudoCode 20 | 21 | PROCEDURE QUICKSORT(A, p, r) 22 | if p < r 23 | q = PARTITION(A, p, r) 24 | QUICKSORT(A, p, q - 1) 25 | QUICKSORT(A, q + 1, r) 26 | END PROCEDURE 27 | 28 | 29 | PROCEDURE PARTITION(A, p, r) 30 | x = A[r] 31 | i = p - 1 32 | for j = p to r - 1 33 | if A[j] <= x 34 | i = i + 1 35 | exchange A[i] with A[j] 36 | exchange A[i + 1] with A[r] 37 | return i + 1 38 | END PROCEDURE 39 | -------------------------------------------------------------------------------- /Traversal Algorithms/Graph Traversals/BFS/JAVA/BFS.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class BFS{ 4 | 5 | private static int V; // No. of vertices 6 | private static LinkedList adj[]; //Adjacency Lists 7 | 8 | // Constructor 9 | BFS(int v) 10 | { 11 | V = v; 12 | adj = new LinkedList[v]; 13 | for (int i = 0; i < v; ++i){ 14 | adj[i] = new LinkedList(); 15 | } 16 | } 17 | 18 | // Function to add an edge into the graph 19 | void addEdge(int v,int w) 20 | { 21 | adj[v].add(w); 22 | } 23 | 24 | // prints BFS traversal from a given source s 25 | public static void BFS(int s) 26 | { 27 | boolean visited[] = new boolean[V]; // Mark all the vertices as not visited 28 | 29 | LinkedList queue = new LinkedList(); 30 | 31 | visited[s]=true; // Mark the current node as visited and enqueue it 32 | queue.add(s); 33 | 34 | while (queue.size() != 0) 35 | { 36 | s = queue.poll(); 37 | System.out.print(s+" "); // Dequeue a vertex from queue and print it 38 | 39 | Iterator i = adj[s].listIterator(); // Get all adjacent vertices of the dequeued vertex s 40 | while (i.hasNext()) 41 | { 42 | int n = i.next(); 43 | if (!visited[n]) 44 | { 45 | visited[n] = true; // If a adjacent has not been visited, then mark it visited and enqueue it 46 | queue.add(n); 47 | } 48 | } 49 | } 50 | } 51 | 52 | } 53 | 54 | /* 55 | * Sample Input: (0,1) (0,2) (1,2) (2,0) (2,3) (3,3) 56 | * Sample Output: 2 0 3 1 57 | * Time Complexity in Best Case: O(V+E) 58 | * Time Complexity in Average Case: O(V+E) 59 | * Time Complexity in Worst Case: O(V+E) 60 | * Space Complexity in Worst Case: O(V) 61 | */ -------------------------------------------------------------------------------- /Sorting/Bubble Sort/Algorithm.md: -------------------------------------------------------------------------------- 1 | # Bubble Sort Algorithm 2 | **Bubble sorting** is a sorting algorithm that starts from left end of the array and ends at the last element in the right. It checks first and second element and compares it,if the element in the right is greater than the element on the left then they are left the way they are however the element in the left is greater than the element in the right then they are swapped so that the greater element bubbles up to the end of array and the smaller element remains at the left end of the array. 3 | 4 | **Obejective:** 5 | To sort the elements of the array in ascending order. 6 | 7 | **For Example:** 8 | The array that we need to sort (30, 10, 20, 15, 25, 5, 90) 9 | 10 | **Expected result:** (5, 10, 15, 20, 25, 30, 90) 11 | 12 | **Steps for Bubble Sorting** 13 | 14 | 1) Compare the elements on the place index i=0 and (i+1)=1 ,i.e 30 and 10. As the right element is larger, it will get swapped with i=0 position; so we get 10 at i=10 and for i+1=1 position we get 30. 15 | Now our array becomes (10, 30, 20, 15, 25, 5, 90). 16 | 17 | 2) Now, it will compare for position i=1 and i+1=2, which in our current array is 30,20 respectively. 18 | 19 | 3) Similarly, it will keep on comparing and swapping till the (i+1)th element becomes larger than ith element. 20 | 21 | 3) By this method the the smallest element in the array will attain leftmost position and the largest element in the array will attain the rightmost position. 22 | 23 | 4) Now the resultant array is sorted in ascending order. 24 | 25 | 5) Finally the expected sorted array is achived as: (5, 10, 15, 20, 25, 30, 90) 26 | 27 | **Time Complexity:** 28 | Best case time complexity is O(n). 29 | 30 | **NOTE** 31 | The algorithm checks if the element on the right, with position i + 1 is lesser than the current element at position i, then it swaps the elements if they are not in the correct order as required, the highest number will bubble it's way to the right with each iteration, a sorted partition will form at the end of array. 32 | -------------------------------------------------------------------------------- /Graph Algorithms/Dijkstra/Algorithm.md: -------------------------------------------------------------------------------- 1 | # Dijkstra is a Greedy algorithm 2 | # The code finds the shortest distances from the source to all vertices. 3 | # The function dijkstra() calculates the shortest path. 4 | # The mindistance() function constructs the shortest path starting from the target using predecessors. 5 | 6 | 7 | # Dijkstra Algotithm 8 | 9 | 1) Mark all vertex as unvisited vertex. 10 | 11 | 2) Mark source vertex as 0 and all other vertices as infinity. 12 | 13 | 3) Consider source vertex as current vertex. 14 | 15 | 4) Calculate the path length of all the neighboring vertex from the current vertex by adding the weight of the edge in the current vertex 16 | 17 | 5) If the new path length is smaller than the previous path length then replace it otherwise ignore it. 18 | 19 | 6) Mark the current vertex as visited after visiting the neighbor vertex of the current vertex 20 | 21 | 7) Select the vertex with the smallest path length as the new current vertex and go back to step 4. 22 | 23 | 8) Repeat this process until all the vertex are marked as visited 24 | 25 | 26 | # psudo code for Dijkstra algo/ Shortest distance 27 | 28 | Declare the visited list 29 | Declare the unvisited list 30 | For each node in graph: 31 | Add node to the unvisited list with distance of infinity and previous node of null 32 | Set the start node's distance to 0 in the unvisited list 33 | 34 | While the unvisited list is not empty: 35 | Set current node to the node with the lowest cost from the unvisited list 36 | Copy cost and previous values for current node from the unvisited list to the visited list 37 | Remove the current node from the unvisited list 38 | 39 | For each neighbour of current node: 40 | If neighbour is not in the visited list 41 | Calculate new cost = weight of edge + cost of current node 42 | If new cost is less than neighbour's cost in unvisited list 43 | Update the neighbour's cost to become the new cost 44 | Update the neighbour's previous node to become the current node 45 | 46 | Return the visited list 47 | -------------------------------------------------------------------------------- /Sorting/Merge Sort/C#/mergesort.cs: -------------------------------------------------------------------------------- 1 | // Program for merge sort in C# 2 | 3 | // Merges two subarrays of []arr. 4 | // First subarray is arr[l..m] 5 | // Second subarray is arr[m+1..r] 6 | void merge(int[] arr, int o, int m, int r) 7 | { 8 | // Find sizes of two 9 | // subarrays to be merged 10 | int n1 = m - o + 1; 11 | int n2 = r - m; 12 | 13 | // Create temp arrays 14 | int[] L = new int[n1]; 15 | int[] R = new int[n2]; 16 | int i, j; 17 | 18 | // Copy data to temp arrays 19 | for (i = 0; i < n1; ++i) 20 | L[i] = arr[o + i]; 21 | for (j = 0; j < n2; ++j) 22 | R[j] = arr[m + 1 + j]; 23 | 24 | // Merge the temp arrays 25 | 26 | // Initial indexes of first 27 | // and second subarrays 28 | i = 0; 29 | j = 0; 30 | 31 | // Initial index of merged 32 | // subarray array 33 | int k = o; 34 | while (i < n1 && j < n2) { 35 | if (L[i] <= R[j]) { 36 | arr[k] = L[i]; 37 | i++; 38 | } 39 | else { 40 | arr[k] = R[j]; 41 | j++; 42 | } 43 | k++; 44 | } 45 | 46 | // Copy remaining elements 47 | // of L[] if any 48 | while (i < n1) { 49 | arr[k] = L[i]; 50 | i++; 51 | k++; 52 | } 53 | 54 | // Copy remaining elements 55 | // of R[] if any 56 | while (j < n2) { 57 | arr[k] = R[j]; 58 | j++; 59 | k++; 60 | } 61 | } 62 | 63 | // Main function that 64 | // sorts arr[l..r] using 65 | // merge() 66 | void sort(int[] arr, int o, int r) 67 | { 68 | if (o < r) { 69 | // Find the middle 70 | // point 71 | int m = o+ (r-l)/2; 72 | 73 | // Sort first and 74 | // second halves 75 | sort(arr, o, m); 76 | sort(arr, m + 1, r); 77 | 78 | // Merge the sorted halves 79 | merge(arr, o, m, r); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /Traversal Algorithms/Graph Traversals/DFS/Python/DFS.py: -------------------------------------------------------------------------------- 1 | ''' 2 | These implementations, recursive and interative have a time 3 | complexity of O(V + E), being V the quantity of vertices 4 | and E the quantity of edges. The space complexity if O(V). 5 | 6 | Author: LiuSeeker 7 | ''' 8 | 9 | # Node class 10 | class GraphNode: 11 | def __init__(self, value=None): 12 | self.value = value 13 | self.adjacent = [] 14 | 15 | 16 | def recursive_depth_first_search(node: GraphNode, target_value, visited=None) -> None: 17 | ''' 18 | This function check if this node has the target value. 19 | If True, return this node. If False, call this function 20 | for each adjacent node, if not already visited. If one 21 | recursive call returns a node, return the returned node; 22 | otherwise return None. 23 | ''' 24 | if visited is None: 25 | visited = set() 26 | visited.add(node) 27 | 28 | return_node = None 29 | 30 | if node.value == target_value: 31 | return_node = node 32 | else: 33 | for adj in node.adjacent: 34 | if adj not in visited: 35 | ret = recursive_depth_first_search(adj, target_value, visited) 36 | if ret is not None: 37 | return_node = ret 38 | break 39 | 40 | 41 | return return_node 42 | 43 | def iterative_depth_first_search(node: GraphNode, target_value) -> None: 44 | ''' 45 | This function uses a stack to check the value of the 46 | nodes, starting with the root node. If the node on top 47 | of the stack has the target value, return the node. 48 | Otherwise, remove the node from the stack and push the 49 | adjacent nodes to the stack. Repeat until find the 50 | targe value or empty the stack. 51 | ''' 52 | visited = set() 53 | stack = [] 54 | stack.append(node) 55 | visited.add(node) 56 | 57 | while stack: 58 | actual_node = stack.pop() 59 | if actual_node.value == target_value: 60 | return actual_node 61 | for adj in actual_node.adjacent: 62 | if adj not in visited: 63 | visited.add(adj) 64 | stack.append(adj) 65 | 66 | return None 67 | -------------------------------------------------------------------------------- /Graph Algorithms/Dijkstra/Java/Dijkstra.java: -------------------------------------------------------------------------------- 1 | /* 2 | Dijkstra's Algorithm is an algo used to compute distances of nodes from a single source in an undirected graph. 3 | Hence, this is part of the SSSP (Single Source Shortest Path) algorithms. 4 | In this, we will see how Dijkstra's is implemented for Adjacency Matrix representation of graphs. 5 | 6 | Time Complexity of the algorithm : O(V^2), here V is the number of nodes 7 | Space Complexity of the algorithm : O(V^2), as we are making a 2D array to store the distances of every node from every node 8 | 9 | */ 10 | 11 | import java.io.*; 12 | import java.util.*; 13 | 14 | public class Dijkstra { 15 | public static int[] Dijkstra_Matrix(int[][] graph, int source, int nodes){ 16 | 17 | // Everything is one based indexing. 18 | // source variable stands for the source node, from which we have to calculate the minimum distances. 19 | // nodes variable is the number of nodes in the graph. 20 | 21 | int[] distances = new int[nodes + 1]; 22 | Boolean[] visited = new Boolean[nodes + 1]; 23 | 24 | for (int i = 1; i <= nodes; i++) { 25 | distances[i] = Integer.MAX_VALUE; 26 | visited[i] = false; 27 | } 28 | distances[source] = 0; 29 | for (int i = 0; i < nodes - 1; i++) { 30 | 31 | int min_value = Integer.MAX_VALUE; 32 | int min_index = -1; 33 | 34 | for (int j = 1; j <= nodes; j++) { 35 | if(!visited[j] && distances[j]<=min_value){ 36 | min_value = distances[j]; 37 | min_index = j; 38 | } 39 | } 40 | visited[min_index] = true; 41 | for (int j = 1; j <= nodes ; j++) { 42 | if(!visited[j] && graph[min_index][j] != 0){ 43 | if(distances[min_index] + graph[min_index][j] < distances[j]){ 44 | distances[j] = distances[min_index] + graph[min_index][j]; 45 | } 46 | } 47 | } 48 | } 49 | int[] ans = new int[nodes]; 50 | for (int i = 0; i < nodes; i++) { 51 | ans[i] = distances[i+1]; 52 | } 53 | return ans; 54 | } 55 | } 56 | 57 | 58 | /* 59 | Code contributed by Akshat Wadhwa (github.com/akshat19231) 60 | */ -------------------------------------------------------------------------------- /Contribution guidelines.md: -------------------------------------------------------------------------------- 1 | # Contribution Guidelines 2 | 3 | ### **Steps** 4 | 5 | 1. Browse code and issue list, find some existing issue or create a new one. 6 | 2. Comment on the issue that you want to work on. Don't forget to mention the language you are planning to use. 7 | 3. Wait for issue to be assigned to you. 8 | 4. Create a new branch in your forked repo and start working on your code. 9 | 5. Along with the code add following contents - 10 | 11 | * Relevant comments for easier understanding 12 | * A block comment with 13 | * Sample Inputs 14 | * Sample Outputs 15 | * Time Complexity 16 | * Space Complexity 17 | * You need not write any `main` function 18 | * Don't forget to mention your username as the author 19 | * Make sure to name your files according to these guidelines: 20 | * Name your file in camel case. For example, if your contribution involves the source code for binary search in c++, then your file name must be BinarySearch.cpp. The same way, LinearSearch.py or BubbleSort.java. 21 | * Pay close attention to the file structure, and if new folders are required to be created by you, then make sure that the spellings are correct and the naming convention follows camel case if required. For creating a new folder, every word must start with a capitalized letter. 22 | 23 | 6. Update algo.md file in present in the language folder for every algorithm, if required. 24 | 7. Create a pull request and mention the issue number, also, give edit access to collaborators and maintainers. 25 | 8. Wait for it to be get reviewed and approved by maintainers. 26 | 27 | ### **Note** 28 | 29 | * Issues will be assigned on a first come, first serve basis. The person who creates the issue gets the first priority. And then, issues are assigned based on who commented first. You just have to comment on the issue, asking to be assigned and the programming language you are going to use, and it will be done if found fit. 30 | * You cannot work on any issue that is not assigned to you. 31 | * If you have anything else in mind, **FEEL FREE TO CREATE AN ISSUE** and please wait for it to be assigned to you. If assigned to you, then you can start working on it and create a PR. 32 | * All PRs must be made from a Branch. Create a separate branch for every Issue you are working upon and then create a PR. 33 | * In your code file, add (Inside a multiline comment) Sample Input and Output at the end of the file along with Time and Space Complexity. 34 | * Every time you add a file via a Pull Request also update the algo.md file for that particular language in the same PR. You'll find a algo.md file in each language folder for every algorithm. 35 | * Plagiarism is highly discouraged and a plagiarized PR won't be accepted at all and will be marked as spam. 36 | * PR should be created within a week of you being assigned to it. 37 | * At no point of time, you can claim more than 4 issues i.e. you can have at max 4 working issues, for this repository. 38 | 39 | If you're wondering how to create a pull request, then take a look at [this](https://docs.github.com/en/github/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request). 40 | -------------------------------------------------------------------------------- /Traversal Algorithms/Graph Traversals/BFS/C++/BFS.cpp: -------------------------------------------------------------------------------- 1 | // Directed Graph 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | class Graph { 11 | private: 12 | class Node { 13 | public: 14 | std::string label; 15 | Node(const std::string& label) : label(label) {} 16 | }; 17 | 18 | // use map for fast lookup 19 | std::unordered_map nodes; 20 | 21 | // list of lists of adjacent node 22 | // eg. Node A = [B,C,D] where, B,C,D are adjacent to A 23 | std::unordered_map> adjacencyList; 24 | 25 | public: 26 | void addNode(const std::string&); 27 | void addEdge(const std::string&, const std::string&); 28 | 29 | // Breadth First Traversal 30 | void breadthFirstTraversal(const std::string&); 31 | }; 32 | 33 | void Graph::addNode(const std::string& label) { 34 | Node* new_node = new Node(label); 35 | nodes.emplace(label, new_node); 36 | } 37 | 38 | void Graph::addEdge(const std::string& from, const std::string& to) { 39 | if (nodes.find(from) == nodes.end()) 40 | throw std::runtime_error("Error: " + from + " node not found"); 41 | if (nodes.find(to) == nodes.end()) 42 | throw std::runtime_error("Error: " + to + " node not found"); 43 | 44 | // add "to node" to "from node" list as its adjacent node 45 | adjacencyList[nodes[from]].push_back(nodes[to]); 46 | } 47 | 48 | void Graph::breadthFirstTraversal(const std::string& root) { 49 | // validate the root node 50 | if (nodes.find(root) == nodes.end()) 51 | throw std::runtime_error("Error: " + root + " node not found"); 52 | 53 | // set of visited nodes 54 | std::set visited; 55 | 56 | // create a queue frontier and push root node 57 | std::queue frontier; 58 | frontier.push(nodes[root]); 59 | 60 | while (!frontier.empty()) { 61 | // pop one node from the front of the queue 62 | Node* current = frontier.front(); 63 | frontier.pop(); 64 | 65 | // continue if the current node is already visited 66 | if (visited.find(current) != visited.end()) 67 | continue; 68 | 69 | // visit the current node and add it to the set of visited node 70 | std::cout << current->label << std::endl; 71 | visited.insert(current); 72 | 73 | // push all of current's unvisited neighbour into the queue 74 | for (auto&& neighbour : adjacencyList[current]) { 75 | if (visited.find(neighbour) == visited.end()) 76 | frontier.push(neighbour); 77 | } 78 | } 79 | } 80 | 81 | /* 82 | To add a node : graph.addNode("A"); 83 | To add an edge : graph.addEdge("A", "B"); 84 | 85 | Sample input graph: 86 | 87 | ┌──A──┐ 88 | │ │ 89 | B ┌──C──┐ 90 | │ │ 91 | ┌──D──┐ E 92 | │ │ 93 | F G 94 | 95 | Sample Output: 96 | A 97 | B 98 | C 99 | D 100 | E 101 | F 102 | G 103 | 104 | */ 105 | -------------------------------------------------------------------------------- /Graph Algorithms/Dijkstra/Python/Dijkstra.py: -------------------------------------------------------------------------------- 1 | # Python program for Dijkstra's single 2 | # source shortest path algorithm. The program is 3 | # for adjacency matrix representation of the graph 4 | 5 | # Library for INT_MAX 6 | 7 | import sys 8 | 9 | class Graph(): 10 | 11 | def __init__(self, vertices): 12 | self.V = vertices 13 | self.graph = [[0 for column in range(vertices)] 14 | for row in range(vertices)] 15 | 16 | def printSolution(self, dist): 17 | print ("Vertex \tDistance from Source") 18 | for node in range(self.V): 19 | print(node, "\t", dist[node]) 20 | 21 | # A utility function to find the vertex with 22 | # minimum distance value, from the set of vertices 23 | # not yet included in shortest path tree 24 | 25 | def minDistance(self, dist, sptSet): 26 | 27 | # Initialize minimum distance for next node 28 | min = sys.maxint 29 | 30 | # Search not nearest vertex not in the 31 | # shortest path tree 32 | for u in range(self.V): 33 | if dist[u] < min and sptSet[u] == False: 34 | min = dist[u] 35 | min_index = u 36 | 37 | return min_index 38 | 39 | # Function that implements Dijkstra's single source 40 | # shortest path algorithm for a graph represented 41 | # using adjacency matrix representation 42 | def dijkstra(self, src): 43 | 44 | dist = [sys.maxint] * self.V 45 | dist[src] = 0 46 | shortest_path = [False] * self.V 47 | 48 | for cout in range(self.V): 49 | 50 | # Pick the minimum distance vertex from 51 | # the set of vertices not yet processed. 52 | # x is always equal to src in first iteration 53 | x = self.minDistance(dist, shortest_path) 54 | 55 | # Put the minimum distance vertex in the 56 | # shortest path tree 57 | shortest_path[x] = True 58 | 59 | # Update dist value of the adjacent vertices 60 | # of the picked vertex only if the current 61 | # distance is greater than new distance and 62 | # the vertex in not in the shortest path tree 63 | for y in range(self.V): 64 | if self.graph[x][y] > 0 and shortest_path[y] == False and \ 65 | dist[y] > dist[x] + self.graph[x][y]: 66 | dist[y] = dist[x] + self.graph[x][y] 67 | 68 | self.printSolution(dist) 69 | 70 | 71 | """ 72 | Sample Input 73 | 74 | g = Graph(9) # defines no of vertices 75 | 76 | #sample graph 77 | [0, 4, 0, 0, 0, 0, 0, 8, 0], 78 | [4, 0, 8, 0, 0, 0, 0, 11, 0], 79 | [0, 8, 0, 7, 0, 4, 0, 0, 2], 80 | [0, 0, 7, 0, 9, 14, 0, 0, 0], 81 | [0, 0, 0, 9, 0, 10, 0, 0, 0], 82 | [0, 0, 4, 14, 10, 0, 2, 0, 0], 83 | [0, 0, 0, 0, 0, 2, 0, 1, 6], 84 | [8, 11, 0, 0, 0, 0, 1, 0, 7], 85 | [0, 0, 2, 0, 0, 0, 6, 7, 0] 86 | 87 | 88 | """ 89 | 90 | 91 | #Time Complexity of the algorithm : O(V^2), 92 | # here V is the number of nodes 93 | #Space Complexity of the algorithm : O(V^2), 94 | # as we are making a 2D array to store the distances of every node from every node 95 | 96 | """ 97 | O/P 98 | 99 | Vertex Distance from Source 100 | 0 0 101 | 1 4 102 | 2 12 103 | 3 19 104 | 4 21 105 | 5 11 106 | 6 9 107 | 7 8 108 | 8 14 109 | """ 110 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Codechef Logo](https://user-images.githubusercontent.com/77433608/136649361-89697879-7105-44d2-83cc-5af4eb1e6f40.png) 2 | # DSA 3 | 4 | # Overview 5 | * The main goal of this project is to promote open-source, allowing anyone who wants to contribute. 6 | * This repository would be focused on various algorithms in different languages. 7 | * You can contribute to a description, code of that algorithm, and submit solutions to the questions related to that algorithm in any language you prefer. 8 | * Make sure to follow the contribution guidelines listed below. 9 | 10 | # RULES: 11 | 12 | **YOU CANNOT CREATE A PR DIRECTLY. YOU NEED TO BE ASSIGNED AN ISSUE. IF THE ISSUE DOES NOT EXIST, CREATE ONE, ASK FOR IT IN YOUR PREFERRED PROGRAMMING LANGUAGE AND WAIT FOR IT TO BE ASSIGNED TO YOU. NOT FOLLOWING THIS WILL BE CONSIDERED A VIOLATION AND YOUR PR WILL BE MARKED INVALID. WHILE CREATING AN ISSUE, PLEASE FOLLOW THE FORMAT, ELSE, THE ISSUE WILL BE CLOSED.** 13 | 14 | # Repository structure: 15 | Please note that while creating a pull request, you must adhere to the structure of the repository. You can create a pull request for any of the following - explaination of an algorithm in an Algorithm.md markdown file, a code of that algorithm in your preferred language, or your solutions to some questions based on that particular algorithm in a language of your choice. 16 | - Algorithm Type Folders (eg - Searching, Sorting, Dynamic Programming etc) 17 | - Algorithm Folder 18 | - Algorithm.md (markdown file explaining algorithm) 19 | - Language Folder (eg. C++, Python, Java, Ruby, C# etc.) 20 | - Algorithm source code file (named as Algorithm.cpp / .py etc in CamelCase. Eg - HeapSort.cpp, BinarySearch.py) 21 | - Question based on the algorithm 22 | 23 | 24 | # Contribution Guidelines: 25 | If you want a more detailed explanation, please visit [here](https://github.com/CodeChefMUST/DSA/blob/main/Contribution%20guidelines.md). 26 | 27 | * Issues will be assigned on a ***first come, first serve basis***. The person who creates the issue gets the first priority. And then, issues are assigned based on who commented first. You just have to comment on the issue, asking to be assigned and the programming language you should be assigned in, and it will be done if found fit. 28 | * You cannot work on any issue that is not assigned to you. 29 | * If you have anything else in mind, **FEEL FREE TO CREATE AN ISSUE** and please wait for it to be assigned to you. If assigned to you, then you can start working on it and create a PR. 30 | * All PRs must be made from a Branch. Create a separate branch for every Issue you are working upon and then create a PR. 31 | * In your code file, add (Inside a multiline comment) Sample Input and Output at the end of the file along with Time and Space Complexity. 32 | * Every time you add a file via a Pull Request also update the algo.md file for that particular language in the same PR. You'll find a algo.md file in each language folder for every algorithm. 33 | * Plagiarism is highly discouraged and a plagiarized PR won't be accepted at all and will be marked as spam. 34 | * PR should be created within a week of you being assigned to it. 35 | * At no point of time, you can claim more than 3 issues i.e. you can have at max 3 working issues, for this repository. 36 | 37 | # Maintainers / Collaborators: 38 | 1. @Taneesha-creates 39 | 2. @deepansha-singh 40 | 41 | For all the spectators of this repository, if you like the content, please ⭐ it! 42 | -------------------------------------------------------------------------------- /Sorting/Radix Sort/C++/RadixSort.cpp: -------------------------------------------------------------------------------- 1 | //Radix Sort 2 | vector Radix_Sort(vector &arr, int n) { 3 | //first of all we take the largest element from the array 4 | //why do we need maximum element or largest elements ? 5 | //since largest element would have maximum number of digits 6 | //why do we find maximum number of digits 7 | //Radix sort is using count sort for sorting but if numbers differ huge in range then conting sort would not be good in overall complexity right ? 8 | //so in radix sort we are sorting the elements of the array on the basis of digits on ones place, hundereds place ,thousands place upto the last place of digit in largest element 9 | int maximum_element = *max_element(arr.begin(), arr.end()); 10 | 11 | //finding the number of digits in largest element we've found 12 | //Below is one of the method to find number of digits in a number 13 | int number_of_digits = floor(log10(maximum_element)) + 1; //It's a formula 14 | 15 | 16 | //for finding the ones place digit what we do generally ? 17 | //lets take a number "123", now if we want to find what digit on it's ones place we will take its mod with 10 and whatever number we will get will be ones place digit of number "123" right ? 18 | //To find digit on hunderds place what we can do ? 19 | //one thing we can do, if we divide number "123" by 10 we will get the quotient = 12 since now 2 comes at ones place then we can get the 2 by just taking mod wih 10 20 | //Similarly to find last digit we need largest number in power of 10 such that last digit comes to ones place 21 | //that's what below line does 22 | int largest_divisor = pow(10, number_of_digits); 23 | 24 | //In below code we have for loop 25 | //and d whose values are 1,10,100,100,1000.... 26 | //and each time counting sort function is being called with the value d as argument 27 | // when d = 1 we are calling counting sort and count sort the elements by comparing the digits on the ones place 28 | //similary when d = 2 we are calling counting sort and coun sort the elements by comparing the digits on the hunders place 29 | for (int d = 1; d <= largest_divisor ; d *= 10) 30 | Counting_sort(arr, n, d); //lets see this counting sort function 31 | 32 | return arr; //sorted array 33 | } 34 | 35 | void Counting_sort(vector &arr, int n, int d) { 36 | //How many one digit numbers in number system ? 37 | //obviously 10 ? 38 | //what are they ? 39 | //0 1 2 3 4 5 6 7 8 9 40 | //since we are comparing and sorting based on one digit numbers 41 | //I have taken a vector (array) having 10 capacity and initialized each number with 0 42 | //below code is counting sort with little modification 43 | vector count(10, 0); 44 | 45 | 46 | vector helper_array(n); //why this ? // we need this 47 | 48 | //for the below explaination assume d = 1 49 | 50 | 51 | for (auto element : arr) 52 | count[(element / d) % 10]++; 53 | //here we are counting the number of digit that are at ones place in each element of array 54 | //and storing in the count array 55 | 56 | for (int i = 1; i < 10; i++) 57 | count[i] += count[i - 1]; //filling all the postions 58 | 59 | for (int i = n - 1; i >= 0; i--) { 60 | helper_array[count[(arr[i] / d) % 10] - 1] = arr[i]; //since we can't use "arr" on LHS. we've used "helper_array" 61 | //here we are sorting according to value of d 62 | //arr[i] is the elemenent and we are taking it's mod to get digit and finding its count from count array 63 | //-1 is used here because we are using 0 based indexing for helper_array 64 | 65 | count[(arr[i] / d) % 10]--; 66 | //after that we are decreasing the count of the (arr[i] / d) % 10) in count array 67 | } 68 | 69 | for (int i = 0; i < n; i++) 70 | arr[i] = helper_array[i]; //storing the elments fro helper array to original array 71 | 72 | 73 | //for each iteration we are doing this till we get our array sorted 74 | 75 | } 76 | -------------------------------------------------------------------------------- /Graph Algorithms/Bellman Ford/java/BellmanFord.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | import java.io.*; 4 | 5 | class Graph 6 | { 7 | class Edge 8 | { 9 | int src, dest, weight; 10 | Edge() 11 | { 12 | src = dest = weight = 0; 13 | } 14 | }; 15 | 16 | int V, E; //V: vertices, E: edges 17 | Edge edge[]; 18 | 19 | Graph(int v, int e) 20 | { 21 | V = v; 22 | E = e; 23 | edge = new Edge[e]; 24 | for (int i=0; i` 43 | 44 | Now that our new branch is created, we can switch to make sure that we are working on that branch by using the git checkout command: 45 | 46 | ##### `git checkout ` 47 | 48 | Once you enter the git `checkout` command, you will receive the following output: 49 | 50 | ###### `Output:` 51 | 52 | ##### `Switched to branch '' ` 53 | 54 | ##### `code .` 55 | 56 | Once you enter this command, the whole code will automatically open in your code editor 57 | 58 | At this point, you can now modify existing files or add new files to the project on your own branch. 59 | 60 | #### Make Changes Locally 61 | 62 | Once you have modified existing files or added new files to the project, you can add them to your local repository, which you can do with the git add command. Let’s add the -A flag to add all changes that we have made: 63 | 64 | ##### `git add -A` or `git add .` 65 | 66 | Next, we’ll want to record the changes that we made to the repository with the git commit command. 67 | 68 | _The commit message is an important aspect of your code contribution; it helps the other contributors fully understand the change you have made, why you made it, and how significant it is. Additionally, commit messages provide a historical record of the changes for the project at large, helping future contributors along the way._ 69 | 70 | If you have a very short message, you can record that with the -m flag and the message in quotes: 71 | 72 | ###### `Example:` 73 | 74 | ##### `git commit -m "Updated Readme.md"` 75 | 76 | ###### At this point you can use the git push command to push the changes to the current branch of your forked repository: 77 | 78 | ###### ` Example:` 79 | 80 | ##### `git push --set-upstream origin new-branch` 81 | 82 | ### 4. Update Local Repository 83 | 84 | _While working on a project alongside other contributors, it is important for you to keep your local repository up-to-date with the project as you don’t want to make a pull request for code that will cause conflicts. To keep your local copy of the code base updated, you’ll need to sync changes._ 85 | 86 | We’ll first go over configuring a remote for the fork, then syncing the fork. 87 | 88 | ### 5. Configure a Remote for the Fork 89 | 90 | Next up, you’ll have to specify a new remote upstream repository for us to sync with the fork. This will be the original repository that you forked from. you’ll have to do this with the git remote add command. 91 | 92 | ##### `git remote add upstream https://github.com/CodeChefMust/DSA.git` 93 | 94 | In this example, // upstream // is the shortname we have supplied for the remote repository since in terms of Git, “upstream” refers to the repository that you cloned from. If you want to add a remote pointer to the repository of a collaborator, you may want to provide that collaborator’s username or a shortened nickname for the shortname. 95 | 96 | ### 6. Sync the Fork 97 | 98 | Once you have configured a remote that references the upstream and original repository on GitHub, you are ready to sync your fork of the repository to keep it up-to-date. 99 | To sync your fork, from the directory of your local repository in a terminal window, you’ll have to use the // git fetch // command to fetch the branches along with their respective commits from the upstream repository. Since you used the shortname “upstream” to refer to the upstream repository, you’ll have to pass that to the command: 100 | 101 | ##### `git fetch upstream` 102 | 103 | Switch to the local master branch of our repository: 104 | 105 | ##### `git checkout master` 106 | 107 | Now merge any changes that were made in the original repository’s master branch, that you will access through your local upstream/master branch, with your local master branch: 108 | 109 | ##### `git merge upstream/master` 110 | 111 | ### 7. Create Pull Request 112 | 113 | At this point, you are ready to make a pull request to the original repository. 114 | 115 | Navigate to your forked repository, and press the “New pull request” button on your left-hand side of your Repo page. 116 | 117 | **ALWAYS**, give your PR a meaningful name. 118 | 119 | # Yay! You have created your First Pull Request. 120 | --------------------------------------------------------------------------------