├── .DS_Store ├── .github ├── ISSUE_TEMPLATE └── PULL_REQUEST_TEMPLATE ├── Arrays ├── Buy And Sell Stocks 1.cpp ├── Buy And Sell Stocks 2.cpp ├── Buy And Sell Stocks 3.cpp ├── First&LastPositionElementSortedArray.cpp ├── FourSum.cpp ├── LargestRectangleInHistogram.cpp ├── MaxSubarraySum.cpp ├── QueueArray.py ├── SearchRotatedSortedArray.cpp ├── StackArray.py ├── TrappingRainwater.cpp ├── TwoSum.cpp └── sum.java ├── Bit manipulation ├── CheckPowerOfTwo.c ├── CheckPowerOfTwo.kt ├── IsPowerOfTwo.py ├── NumberSwapper.java ├── powerOfTwo.cpp └── powerOfTwo.js ├── CONTRIBUTING.md ├── Dijkstra └── Dijkstra.cpp.cpp ├── Elemental algorithms └── exponentiation.cpp ├── Graphs ├── BFS.cpp ├── DFS.cpp ├── DSU.cpp ├── DepthFirstTraversal.java ├── Dijkstra.py ├── FloydWarshall.cpp ├── Kruskal.cpp ├── Prim.cpp └── TopologicalSort.cpp ├── Interview prep └── README.md ├── LICENSE.md ├── README.md ├── Searching ├── Binary-Search.c ├── Binary-Search.cpp ├── BinarySearch.java ├── BinarySearch.js ├── BinarySearch.py ├── LinearSearch.java ├── LinearSearch.js ├── LinearSearch.py ├── Ternary-Search.cpp └── TernarySearch.py ├── Segment Tree └── SegmentTree.cpp ├── Sorting ├── BubbleSort.java ├── Bubble_Sort.py ├── Bubblesort.js ├── CountingSort.cpp ├── Heapsort.cpp ├── Insertion_Sort.cpp ├── Insertion_sort.py ├── Insertionsort.cpp ├── MergeSort.java ├── MergeSort.js ├── QuickSort.java ├── Quick_sort.py ├── Radix Sort.cpp ├── SelectionSort.java ├── SelectionSort.js ├── SelectionSortAlt.cpp ├── Selectionsort.cpp ├── bubblesort.cpp ├── bubblesort.go ├── bucketsort.c ├── insertionsort.java ├── mergesort.c ├── mergesort.cpp ├── quicksort.cpp ├── quicksort.go └── selection sort.py ├── String Matching └── KMP.cpp ├── Structures ├── .DS_Store ├── CircularLinkedList.java ├── DoublyLinkedList.java ├── LinkedList.cpp ├── LinkedList.java ├── LinkedLists │ ├── DNode.java │ ├── QueueDLinked.java │ └── StackDLinked.java ├── Queue.h ├── Stack.java └── infixtopostfix.c++ └── Trees ├── Bfs.py ├── Child Sum Java ├── Left view binary tree ├── MinMax tree ├── Mirror Tree ├── Right View Binary Tree └── Suffix Tree /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CodersForLife/Data-Structures-Algorithms/cf08f47de8c999857cb87b5be08b6fe225ff3389/.DS_Store -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE: -------------------------------------------------------------------------------- 1 | **Would you like to work on the issue?** 2 | 3 | Let us know if this issue should be assigned to you or tell us who you think could help to solve this issue. 4 | 5 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE: -------------------------------------------------------------------------------- 1 | ### Submission Checklist 2 | 3 | 4 | 5 | - [ ] Your pull request targets the `master` branch of the repository. 6 | - [ ] You have only one commit (if not, [squash](http://forum.freecodecamp.org/t/how-to-squash-multiple-commits-into-one-with-git/13231) them into one commit). 7 | - [ ] You have read the [Contributing guidelines](https://github.com/CodersForLife/Data-Structures-Algorithms/blob/master/CONTRIBUTING.md) and your changes follow them. 8 | 9 | #### Type of Change 10 | 11 | - [ ] Bug fix 12 | - [ ] New implementation 13 | 14 | ### PR Description 15 | 16 | 17 | 18 | 19 | Issue #[Add issue number here.] 20 | -------------------------------------------------------------------------------- /Arrays/Buy And Sell Stocks 1.cpp: -------------------------------------------------------------------------------- 1 | int maxProfit(vector& prices) { 2 | int n = prices.size(); 3 | if(n == 0 || n == 1) 4 | return 0; 5 | int mini = prices[0]; 6 | int ans = 0; 7 | for(int i = 1;i& prices) { 2 | int ans = 0; 3 | for(int i = 1; i& prices) { 2 | int n = prices.size(); 3 | if(n <= 1) 4 | return 0; 5 | if(n == 2) { 6 | return max((prices[1] - prices[0]), 0); 7 | } 8 | 9 | vector secondMax(n,0); 10 | 11 | int maxPrice = prices[n-1]; 12 | int maxProfit = 0; 13 | for(int i=n-2;i>=0;i--) { 14 | maxProfit = max(maxProfit, maxPrice - prices[i]); 15 | secondMax[i] = maxProfit; 16 | maxPrice = max(maxPrice, prices[i]); 17 | } 18 | 19 | int minPrice = prices[0]; 20 | int ans = 0; 21 | for(int i=1;i& nums, int target) 5 | { 6 | int ans = -1; 7 | int s = 0, e = nums.size() - 1; 8 | 9 | while(s<=e) 10 | { 11 | int mid = s + (e-s)/2; 12 | if(nums[mid] == target) 13 | { 14 | ans = mid; 15 | e = mid - 1; 16 | } 17 | else if(nums[mid] > target) 18 | e = mid -1; 19 | else 20 | s = mid + 1; 21 | } 22 | return ans; 23 | } 24 | 25 | int upperBound(vector& nums, int target) 26 | { 27 | int ans = -1; 28 | int s = 0, e = nums.size() - 1; 29 | 30 | while(s<=e) 31 | { 32 | int mid = s + (e-s)/2; 33 | if(nums[mid] == target) 34 | { 35 | ans = mid; 36 | s = mid + 1; 37 | } 38 | else if(nums[mid] > target) 39 | e = mid -1; 40 | else 41 | s = mid + 1; 42 | } 43 | return ans; 44 | } 45 | 46 | vector searchRange(vector& nums, int target) { 47 | int lower = lowerBound(nums, target); 48 | int upper = upperBound(nums, target); 49 | vector ans; 50 | ans.push_back(lower); 51 | ans.push_back(upper); 52 | return ans; 53 | } 54 | }; -------------------------------------------------------------------------------- /Arrays/FourSum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | vector > fourSum(vector& nums, int target) 7 | { 8 | sort(nums.begin(), nums.end()); 9 | int n = nums.size(); 10 | vector > ans; 11 | int i = 0; 12 | while (i < n) { 13 | int j = i + 1; 14 | while (j < n) { 15 | int s = j + 1, e = n - 1; 16 | while (s < e) { 17 | int cSum = nums[i] + nums[j] + nums[s] + nums[e]; 18 | if (cSum == target) { 19 | vector temp = { nums[i], nums[j], nums[s], nums[e] }; 20 | ans.push_back(temp); 21 | s += 1; 22 | e -= 1; 23 | while (s < n && nums[s] == nums[s - 1]) 24 | s += 1; 25 | 26 | while (e >= 0 && nums[e] == nums[e + 1]) 27 | e -= 1; 28 | } 29 | else if (cSum > target) 30 | e -= 1; 31 | else 32 | s += 1; 33 | } 34 | j += 1; 35 | while (j < n && nums[j] == nums[j - 1]) 36 | j += 1; 37 | } 38 | i += 1; 39 | while (i < n && nums[i] == nums[i - 1]) 40 | i += 1; 41 | } 42 | return ans; 43 | } 44 | 45 | int main() { 46 | vector array; 47 | 48 | int number, target; 49 | cin>>target; 50 | 51 | while (cin >> number) { 52 | array.push_back(number); 53 | } 54 | 55 | cout << fourSum(array, target) << endl; 56 | 57 | return 0; 58 | } 59 | -------------------------------------------------------------------------------- /Arrays/LargestRectangleInHistogram.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int largestRectangleArea(vector& heights) 7 | { 8 | heights.push_back(0); 9 | int n = heights.size(); 10 | stack stk; 11 | int ans = 0; 12 | for (int i = 0; i < n; i++) { 13 | if (stk.empty() || heights[stk.top()] <= heights[i]) 14 | stk.push(i); 15 | else { 16 | while (!stk.empty() && heights[stk.top()] > heights[i]) { 17 | int barHeight = heights[stk.top()]; 18 | stk.pop(); 19 | int area = 0; 20 | if (stk.empty()) 21 | area = i * barHeight; 22 | else 23 | area = (i - 1 - (stk.top() + 1) + 1) * barHeight; 24 | ans = max(ans, area); 25 | } 26 | stk.push(i); 27 | } 28 | } 29 | return ans; 30 | } 31 | 32 | int main() { 33 | vector array; 34 | 35 | int number; 36 | 37 | while (cin >> number) { 38 | array.push_back(number); 39 | } 40 | 41 | cout << largestRectangleArea(array) << endl; 42 | 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /Arrays/MaxSubarraySum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int maxSubarraySum(const vector &array) { 7 | int maxSum = *array.begin(); 8 | 9 | int sum = 0; 10 | for (vector::const_iterator i = array.begin(); i != array.end(); ++i) { 11 | sum += *i; 12 | maxSum = max(maxSum, sum); 13 | 14 | if (sum < 0) { 15 | sum = 0; 16 | } 17 | } 18 | 19 | return maxSum; 20 | } 21 | 22 | int main() { 23 | vector array; 24 | 25 | int number; 26 | while (cin >> number) { 27 | array.push_back(number); 28 | } 29 | 30 | cout << maxSubarraySum(array) << endl; 31 | 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /Arrays/QueueArray.py: -------------------------------------------------------------------------------- 1 | # Implementation of a queue using an array 2 | # Python 3 3 | # Aitor Alonso (https://github.com/tairosonloa) 4 | 5 | class QueueArray: 6 | def __init__(self): 7 | self.items = [] 8 | 9 | def isEmpty(self): 10 | return self.items == [] 11 | 12 | def enqueue(self, item): 13 | # We always enqueue into last position 14 | self.items.append(item) 15 | 16 | def dequeue(self): 17 | if not self.isEmpty(): 18 | # We always dequeue from first position 19 | return self.items.pop(0) 20 | else: 21 | print("The queue is empty. Can't dequeue.") 22 | return None 23 | 24 | def size(self): 25 | return len(self.items) 26 | 27 | def printQueue(self): 28 | print ("FIRST>", end=" ") 29 | for item in self.items: 30 | print(item, end=" ") 31 | print (" 2 | #include 3 | 4 | using namespace std; 5 | 6 | int search(vector& nums, int target) 7 | { 8 | int n = nums.size(); 9 | 10 | int s = 0, e = n - 1; 11 | while (s <= e) { 12 | int mid = s + (e - s) / 2; 13 | if (nums[mid] == target) 14 | return mid; 15 | if (nums[mid] > target) { 16 | if (nums[mid] <= nums[e]) 17 | e = mid - 1; 18 | else { 19 | if (target > nums[e]) 20 | e = mid - 1; 21 | else 22 | s = mid + 1; 23 | } 24 | } 25 | else { 26 | if (nums[mid] >= nums[s]) 27 | s = mid + 1; 28 | else { 29 | if (target > nums[e]) 30 | e = mid - 1; 31 | else 32 | s = mid + 1; 33 | } 34 | } 35 | } 36 | return -1; 37 | } 38 | 39 | int main() { 40 | vector array; 41 | 42 | int number, target; 43 | cin>>target; 44 | 45 | while (cin >> number) { 46 | array.push_back(number); 47 | } 48 | 49 | cout << search(array, target) << endl; 50 | 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /Arrays/StackArray.py: -------------------------------------------------------------------------------- 1 | # Implementation of a stack using an array 2 | # Python 3 3 | # Aitor Alonso (https://github.com/tairosonloa) 4 | 5 | class StackArray: 6 | def __init__(self): 7 | self.items = [] 8 | 9 | def isEmpty(self): 10 | return self.items == [] 11 | 12 | def push(self, item): 13 | # We always push into last position 14 | self.items.append(item) 15 | 16 | def pop(self): 17 | if not self.isEmpty(): 18 | # We always pop from last position 19 | return self.items.pop() 20 | else: 21 | print("The stack is empty. Can't pop") 22 | return None 23 | 24 | def size(self): 25 | return len(self.items) 26 | 27 | def printStack(self): 28 | for item in self.items: 29 | print(item, end=" ") 30 | print(" 2 | #include 3 | 4 | using namespace std; 5 | 6 | int trap(vector& height) 7 | { 8 | int n = height.size(); 9 | if (n == 0 || n == 1 || n == 2) 10 | return 0; 11 | 12 | vector leftMax(n, 0); 13 | vector rightMax(n, 0); 14 | 15 | leftMax[0] = height[0]; 16 | rightMax[n - 1] = height[n - 1]; 17 | 18 | for (int i = 1; i < n; i++) 19 | leftMax[i] = max(leftMax[i - 1], height[i]); 20 | 21 | for (int i = n - 2; i >= 0; i--) 22 | rightMax[i] = max(rightMax[i + 1], height[i]); 23 | 24 | int ans = 0; 25 | for (int i = 1; i <= n - 2; i++) { 26 | ans += max((min(leftMax[i - 1], rightMax[i + 1]) - height[i]), 0); 27 | } 28 | return ans; 29 | } 30 | 31 | int main() { 32 | vector array; 33 | 34 | int number; 35 | 36 | while (cin >> number) { 37 | array.push_back(number); 38 | } 39 | 40 | cout << trap(array) << endl; 41 | 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /Arrays/TwoSum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | vector twoSum(vector& nums, int target) { 7 | vector ans; 8 | int n = nums.size(); 9 | if(n == 0 || n == 1) 10 | return ans; 11 | 12 | unordered_map um; 13 | um[nums[0]] = 0; 14 | for(int i=1;i array; 30 | 31 | int number, target; 32 | cin>>target; 33 | 34 | while (cin >> number) { 35 | array.push_back(number); 36 | } 37 | 38 | cout << twoSum(array, target) << endl; 39 | 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /Arrays/sum.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.math.*; 3 | 4 | public class sum { 5 | static void printMaxSum(int[] arr){ 6 | 7 | //1) For max continuous sub array 8 | int max_ending_here = 0; 9 | int max_so_far = Integer.MIN_VALUE; 10 | /*OR int max_so_far = arr[0];*/ 11 | 12 | for(int x : arr){ 13 | max_ending_here = Math.max(x, max_ending_here + x); 14 | max_so_far = Math.max(max_so_far, max_ending_here); 15 | } 16 | 17 | System.out.print(max_so_far); 18 | 19 | //2) For max non-continuous sub array, order doesn't matter 20 | Arrays.sort(arr); 21 | int sum = 0; 22 | 23 | //if there is none positive value in entire array 24 | if(arr[arr.length-1] <= 0) 25 | sum = arr[arr.length - 1]; 26 | //accumulate all positive values in entire array 27 | else{ 28 | for(int x : arr){ 29 | if(x > 0) 30 | sum += x; 31 | } 32 | } 33 | System.out.println(" " + sum); 34 | } 35 | 36 | public static void main(String args[] ) throws Exception { 37 | Scanner sc = new Scanner(System.in); 38 | int t = sc.nextInt(); 39 | for(int i=0; i 2 | 3 | int main() 4 | { 5 | int number,check; 6 | scanf("%d",&number); 7 | check= number & (number-1); 8 | if(check==0) 9 | printf("YES"); 10 | else 11 | printf("NO"); 12 | } -------------------------------------------------------------------------------- /Bit manipulation/CheckPowerOfTwo.kt: -------------------------------------------------------------------------------- 1 | fun main(args: Array){ 2 | var number = readLine()!!.toInt() 3 | var check = number and (number - 1) 4 | if(check == 0){ 5 | print("Yes") 6 | } 7 | else{ 8 | print("No") 9 | } 10 | } -------------------------------------------------------------------------------- /Bit manipulation/IsPowerOfTwo.py: -------------------------------------------------------------------------------- 1 | number = int(input()) 2 | 3 | isPowerOf2 = number & (number - 1) 4 | 5 | if isPowerOf2 == 0: 6 | print('Yes') 7 | else: 8 | print('No') -------------------------------------------------------------------------------- /Bit manipulation/NumberSwapper.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Demonstrates swapping of two number using bit manipulation. 3 | */ 4 | public class NumberSwapper { 5 | 6 | private Integer x; 7 | private Integer y; 8 | 9 | public NumberSwapper(Integer x, Integer y) { 10 | this.x = x; 11 | this.y = y; 12 | } 13 | 14 | public Integer getX() { 15 | return x; 16 | } 17 | 18 | public Integer getY() { 19 | return y; 20 | } 21 | 22 | @Override 23 | public String toString() { 24 | return "NumberSwapper{" + 25 | "x=" + x + 26 | ", y=" + y + 27 | '}'; 28 | } 29 | 30 | /** 31 | * Swaps the values of fields x and y in class. 32 | */ 33 | public void swap() { 34 | x = x ^ y; 35 | y = x ^ y; 36 | x = x ^ y; 37 | } 38 | 39 | /** 40 | * Swaps integers in array. Expects array to be not null and elements in array must be 2. 41 | * @param arr 42 | */ 43 | public static void swapArray(int[] arr) { 44 | checkNotNull(arr); 45 | checkState(arr); 46 | arr[0] = arr[0] ^ arr[1]; 47 | arr[1] = arr[0] ^ arr[1]; 48 | arr[0] = arr[0] ^ arr[1]; 49 | } 50 | 51 | private static void checkNotNull(int[] arr) { 52 | if(arr == null) { 53 | throw new NullPointerException("Array can not be null."); 54 | } 55 | } 56 | 57 | private static void checkState(int[] arr) { 58 | if(arr.length != 2) { 59 | throw new IllegalStateException("Array size must be 2."); 60 | } 61 | } 62 | } -------------------------------------------------------------------------------- /Bit manipulation/powerOfTwo.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | int number; 3 | int isPowerOfTwo(int number) { 4 | if ((number - 1) & number) { 5 | return 0; 6 | } else { 7 | return 1; 8 | } 9 | } 10 | int main() { 11 | scanf("%d", &number); 12 | printf("%d", isPowerOfTwo(number)); 13 | } -------------------------------------------------------------------------------- /Bit manipulation/powerOfTwo.js: -------------------------------------------------------------------------------- 1 | const isPowerOfTwo = number => { 2 | if (number === 0) { 3 | return 1; 4 | } 5 | number & (number - 1) === 0; 6 | } 7 | 8 | const readline = require('readline'); 9 | 10 | const rl = readline.createInterface({ 11 | input: process.stdin, 12 | output: process.stdout 13 | }); 14 | 15 | rl.question('Please input a number: ', (answer) => { 16 | console.log(isPowerOfTwo(answer) === 0); 17 | rl.close(); 18 | }); 19 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | 1. Find an issue that needs assistance by searching in our [Issue Tracker](https://github.com/CodersForLife/Data-Structures-Algorithms/issues). 4 | 2. Let us know you are working on it by posting a comment on the issue. 5 | 3. Follow these Contribution Guidelines to start working on the issue. 6 | 7 | ## Forking the Project 8 | 9 | 1. Fork it by clicking the "Fork" button in [the top level of the repository](https://github.com/CodersForLife/Data-Structures-Algorithms). 10 | 2. Clone your fork of _Data-Structures-Algorithms_. 11 | ``` 12 | $ git clone https://github.com/yourUsername/Data-Structures-Algorithms 13 | ``` 14 | 3. Create your feature branch: `git checkout -b my-new-feature` 15 | 4. Add your changes to the project. 16 | 5. Commit your changes: `git commit -m 'Add some feature'` 17 | 6. Push to the branch: `git push origin my-new-feature` 18 | 7. Submit your pull request! 19 | 20 | ## Submitting a Pull Request 21 | 22 | **When you make a Pull Request, all of your changes need to be in one commit.** 23 | 24 | If you have more than one commit in your feature branch you should [_squash_](https://forum.freecodecamp.org/t/how-to-squash-multiple-commits-into-one-with-git/13231) your commits. 25 | 26 | * Your PR title should follow the `category: algorithm (language)` model. 27 | * Ex1: `Sorting: Bubble Sort (C)` 28 | * Ex2: `Searching: Binary Search (Java)` 29 | * After creating your PR, you must fill the checkboxes that define our contribution guidelines. 30 | * Your changes will be reviewed and added to the main repository! 31 | 32 | **After your pull request is merged**, you can safely delete your branch. 33 | 34 | ## Coding Guidelines 35 | 36 | * All the codes should be modular. 37 | * All the codes should be indented. 38 | * Name of the file should be algorithm's name and first letter of file should be capital. 39 | * Code written should be readable. 40 | * Variable names should be logical and understandable. Like `int x; // This is not allowed` 41 | * Same algorithm can be submitted in different languages. 42 | -------------------------------------------------------------------------------- /Dijkstra/Dijkstra.cpp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | using namespace std; 9 | class Graph{ 10 | int V; 11 | int *key; 12 | int *index; 13 | vector heap; 14 | list< pair > *adj; 15 | public: 16 | Graph(int v) 17 | { 18 | V=v; 19 | adj=new list< pair >[v+1]; 20 | key=new int[v+1]; 21 | index=new int[v+1]; 22 | } 23 | void addEdge(int u,int v,int w) 24 | { 25 | adj[u].push_back(make_pair(v,w)); 26 | adj[v].push_back(make_pair(u,w)); 27 | } 28 | int Display(); 29 | int Dijkstra(int s); 30 | int Minheapify(int s); 31 | int insert(int ,int); 32 | int extract_min(); 33 | int parent(int i) 34 | { 35 | return (i-1)/2; 36 | } 37 | }; 38 | int Graph::Display() 39 | { 40 | for(int i=1;i<=V;i++) 41 | { 42 | list< pair >::iterator k=adj[i].begin(); 43 | cout< "; 44 | while(k!=adj[i].end()) 45 | { 46 | cout<first<<" "; 47 | k++; 48 | } 49 | cout< >::iterator k=adj[s].begin(); 65 | while(k!=adj[s].end()) 66 | { 67 | insert(k->first,k->second+key[s]); 68 | k++; 69 | } 70 | while(!heap.empty()) 71 | { 72 | int num=extract_min(); 73 | visited[num]=true; 74 | list >::iterator k=adj[num].begin(); 75 | while(k!=adj[num].end()) 76 | { 77 | if(visited[k->first]==false) 78 | insert(k->first,k->second+key[num]); 79 | k++; 80 | } 81 | } 82 | for(int i=1;i<=V;i++) 83 | { 84 | if(s!=i) 85 | printf("%d ",key[i]); 86 | } 87 | printf("\n"); 88 | return 0; 89 | } 90 | int Graph::Minheapify(int i) 91 | { 92 | int l=2*i+1; 93 | int r=2*i+2; 94 | int min; 95 | if(lkey[heap[l]]) 96 | min=l; 97 | else 98 | min=i; 99 | if(rdis) 128 | { 129 | key[n]=dis; 130 | for(int j=0;j>source; 168 | g.Dijkstra(source); 169 | return 0; 170 | } 171 | -------------------------------------------------------------------------------- /Elemental algorithms/exponentiation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // Exponentiation by squaring 4 | // base ^ power can be written as: 5 | // if power is even: 6 | // base ^ power = base ^ (power / 2) * base ^ (power / 2) 7 | // if power is odd: 8 | // base ^ power = base ^ (power / 2) * base ^ (power / 2) * base 9 | long long exp_by_squaring(int base, int power) { 10 | if (power == 0) { 11 | return 1; 12 | } 13 | long long squaring = exp_by_squaring(base, power / 2); 14 | if (power % 2 == 0) { 15 | return squaring * squaring; 16 | } else { 17 | return base * squaring * squaring; 18 | } 19 | } 20 | 21 | int main() { 22 | int base, power; 23 | scanf("%d%d", &base, &power); 24 | long long result = exp_by_squaring(base, power); 25 | printf("%lld", result); 26 | return 0; 27 | } -------------------------------------------------------------------------------- /Graphs/BFS.cpp: -------------------------------------------------------------------------------- 1 | //written by hg398 2 | 3 | #include 4 | using namespace std; 5 | vector adj[100000]; //vector to implement graph using adjacency lists (size can vary a/c to need) 6 | bool mark[100000]; //array to keep record of visited nodes 7 | void bfs(int s) 8 | { 9 | queue q; // Create a queue for BFS 10 | mark[s] = true; // Mark the current node as visited and enqueue it 11 | q.push(s); 12 | 13 | while(!q.empty()) 14 | { 15 | s = q.front(); // Dequeue a vertex from queue and print it 16 | cout << s+1 << " "; 17 | q.pop(); 18 | 19 | // Get all adjacent vertices of the dequeued vertex s 20 | // If a adjacent has not been visited, then mark it visited 21 | // and enqueue it 22 | for(int i = 0; i < adj[s].size(); ++i) 23 | { 24 | if(!mark[adj[s][i]]) 25 | { 26 | mark[adj[s][i]] = true; 27 | q.push(adj[s][i]); 28 | } 29 | } 30 | } 31 | } 32 | 33 | int main() { 34 | int nodes,edges; //no. of nodes and edges in graph 35 | cin>>nodes>>edges; 36 | while(edges--) 37 | { 38 | int a,b; //vertices between which an edge exist 39 | cin>>a>>b; 40 | a--;b--; //0-based indexing 41 | adj[a].push_back(b); //adding b to adjacency list of a to which it is directly connected 42 | adj[b].push_back(a); //adding a to adjacency list of b to which it is directly connected 43 | } 44 | memset(mark,false,sizeof(mark)); //marking all vertices unvisited 45 | int source; //source node 46 | cin>>source; 47 | bfs(source); 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /Graphs/DFS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define N 100 4 | 5 | int visited[N]; 6 | 7 | void dfs_iterative(vector graph[], int node){ 8 | stack stack_dfs; 9 | stack_dfs.push(node); 10 | visited[node] = 1; 11 | 12 | int cur_node; 13 | while(!stack_dfs.empty()){ 14 | cur_node = stack_dfs.top(); 15 | stack_dfs.pop(); 16 | cout< graph[], int node) { 27 | if(visited[node] == 1) 28 | return; 29 | 30 | // Else 31 | visited[node]=1; 32 | cout< graph[6]; 47 | graph[1].push_back(2); 48 | graph[1].push_back(4); 49 | graph[2].push_back(1); 50 | graph[2].push_back(3); 51 | graph[2].push_back(5); 52 | graph[3].push_back(2); 53 | graph[3].push_back(5); 54 | graph[4].push_back(1); 55 | graph[5].push_back(2); 56 | graph[5].push_back(3); 57 | 58 | // Initially no node is visited 59 | initialize(); 60 | 61 | dfs(graph,1); 62 | 63 | return 0; 64 | } 65 | -------------------------------------------------------------------------------- /Graphs/DSU.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int find(int* parent,int val) { 5 | if(parent[val]!=val) 6 | parent[val]=find(parent,parent[val]);//find the leader of the group of this node 7 | return parent[val]; 8 | } 9 | 10 | void unionSet(int* parent,int a,int b) { 11 | int ap = find(parent,a); 12 | int bp = find(parent,b); 13 | if(ap!=bp) 14 | parent[bp]=ap; //make 'a's parent as the leader of b's group as well. 15 | } 16 | int countNumberOfComponents(vector>& M) { 17 | int n = M.size(); 18 | int parent[n]; //stores parent for each node 19 | for(int i=0;i > adjacencyMatrix(vertices, vector(vertices,0)); 40 | for(int i=0;i adj[]; 13 | 14 | // Constructor 15 | Graph(int v) 16 | { 17 | V = v; 18 | adj = new LinkedList[v]; 19 | for (int i=0; i i = adj[v].listIterator(); 38 | while (i.hasNext()) 39 | { 40 | int n = i.next(); 41 | if (!visited[n]) 42 | DFSUtil(n, visited); 43 | } 44 | } 45 | 46 | // The function to do DFS traversal. It uses recursive DFSUtil() 47 | void DFS(int v) 48 | { 49 | // Mark all the vertices as not visited(set as 50 | // false by default in java) 51 | boolean visited[] = new boolean[V]; 52 | 53 | // Call the recursive helper function to print DFS traversal 54 | DFSUtil(v, visited); 55 | } 56 | 57 | public static void main(String args[]) 58 | { 59 | Graph g = new Graph(4); 60 | 61 | g.addEdge(0, 1); 62 | g.addEdge(0, 2); 63 | g.addEdge(1, 2); 64 | g.addEdge(2, 0); 65 | g.addEdge(2, 3); 66 | g.addEdge(3, 3); 67 | 68 | System.out.println("Following is Depth First Traversal "+ 69 | "(starting from vertex 2)"); 70 | 71 | g.DFS(2); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /Graphs/Dijkstra.py: -------------------------------------------------------------------------------- 1 | # Dijkstra v1.0 2 | """ Dijkstra take a graph and source and returns the minimum distance of each vertex to that source. 3 | Pre-Conditions - Graph is a list of Connection to that vertex and Weight to that vertex in same order. 4 | - Source is an integer value between 0 to n 5 | - Connections should have n lists inside it similarly for Weights. ! Can be empty also. 6 | 7 | Dijkstra(Graph, Source) --> Standard Function Call 8 | 9 | 10 | Example: 11 | 12 | Graph --> [ [[1, 2], [3], [1, 3, 4], [], [3]] , [[ 5, 3], [3], [2, 5, 6], [], [1]] ] 13 | 14 | |__________Connections_________| |___________Weights______________| 15 | 16 | Here 0 vertex is connected to 1 and 2 with weights 5 and 3 resp. 17 | Here 3 vertex is connected to no other vertex. 18 | Here 4 vertex is connected to 3 with weight of 1. 19 | 20 | Source --> Source can be any integer value between [0,4]. 21 | 22 | Output --> For this Graph, and source = 0 will be: [0, 5, 3, 8, 9]. ! If a vertex is not accessible returns distance as inf i.e. Infinity. 23 | 24 | """ 25 | 26 | def Dijkstra(Graph, Source): 27 | 28 | # Shortest distances to each node 29 | Short_Distances = [] 30 | 31 | # Vertex to be visited are stored here 32 | Queue_Vertex = [] 33 | 34 | # Connections stores connnections to each Vertex and Weights store corresponding Weight 35 | Connections = Graph[0] 36 | Weights = Graph[1] 37 | Queue_Vertex = list(range(len(Connections))) 38 | 39 | # Setting all distances except source to infinity and source distance to 0 40 | for Vertex in Queue_Vertex: 41 | if Vertex == Source: 42 | Short_Distances.append(0) 43 | else: 44 | Short_Distances.append(float('inf')) 45 | 46 | # To visit all Vertices 47 | while (len(Queue_Vertex) != 0): 48 | Min_Dist = float('inf') 49 | 50 | #Pick Node with minimum distance currently 51 | for i in Queue_Vertex: 52 | if Short_Distances[i] <= Min_Dist: 53 | Min_Dist = Short_Distances[i] 54 | Node = i 55 | 56 | # Remove Vertex from Queue as visited 57 | Queue_Vertex.remove(Node) 58 | 59 | # Set distances of vertices connected to node as minimum 60 | for Con_Node in Connections[Node]: 61 | Try_Dist = Short_Distances[Node] + Weights[Node][Connections[Node].index(Con_Node)] 62 | if Try_Dist <= Short_Distances[Con_Node]: 63 | Short_Distances[Con_Node] = Try_Dist 64 | 65 | return Short_Distances 66 | 67 | #Sample Run for Example Graph 68 | if __name__ == '__main__': 69 | Test_Graph = [ [[1, 2], [3], [1, 3, 4], [], [3]] , [[ 5, 3], [3], [2, 5, 6], [], [1]] ] 70 | print(Dijkstra(Test_Graph,0)) 71 | print(Dijkstra(Test_Graph,1)) 72 | print(Dijkstra(Test_Graph,2)) 73 | print(Dijkstra(Test_Graph,3)) 74 | print(Dijkstra(Test_Graph,4)) -------------------------------------------------------------------------------- /Graphs/FloydWarshall.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | #define INF 1e9 7 | 8 | int main(){ 9 | 10 | int n,m,x,y,z; 11 | 12 | cin >> n >> m; // n: number of vertex , m: number of edges 13 | 14 | vector > distances(n,vector(n,INF)); 15 | 16 | for(int i=0;i> x >> y >> z; 18 | x--; y--; 19 | distances[x][y]=min(distances[x][y],z); 20 | distances[y][x]=min(distances[y][x],z); 21 | } 22 | 23 | for(int k=0;k 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | int sort(int*,int*,int*,int,int); 10 | int merge(int*,int*,int*,int,int,int); 11 | 12 | int make_set(int p[],int r[],int i) 13 | { 14 | p[i]=i; 15 | r[i]=0; 16 | return 0; 17 | } 18 | int find(int p[],int i) 19 | { 20 | if(p[i]!=i) 21 | { 22 | p[i]=find(p,p[i]); 23 | } 24 | return p[i]; 25 | } 26 | int Union(int p[],int r[],int i,int j) 27 | { 28 | int x=find(p,i); 29 | int y=find(p,j); 30 | if(x!=y) 31 | { 32 | if(r[x]>r[y]) 33 | { 34 | p[y]=x; 35 | } 36 | else 37 | { 38 | p[x]=y; 39 | if(r[x]==r[y]) 40 | { 41 | r[j]+=1; 42 | } 43 | } 44 | return 1; 45 | } 46 | return 0; 47 | } 48 | int main() 49 | { 50 | int n,m; 51 | cin>>n>>m; 52 | int U[m],V[m],W[m]; 53 | int p[n+1]; 54 | int r[n+1]; 55 | for(int i=0;i>U[i]>>V[i]>>W[i]; 58 | } 59 | int s; 60 | cin>>s; 61 | sort(U,V,W,0,m-1); 62 | for(int i=1;i<=n;i++) 63 | { 64 | make_set(p,r,i); 65 | } 66 | int sum=0; 67 | for(int i=0;i 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | class Minheap{ 9 | public: 10 | vector heap; 11 | int *key; 12 | int intialise(int v) 13 | { 14 | key=new int[v+1]; 15 | for(int i=0;i<=v;i++) 16 | { 17 | key[i]=-1; 18 | } 19 | return 0; 20 | } 21 | int Minheapify(int); 22 | int parent(int i) 23 | { 24 | return (i-1)/2; 25 | } 26 | int extract_min(); 27 | int insert(int n,int dis); 28 | }; 29 | int Minheap::extract_min() 30 | { 31 | int root=heap[0]; 32 | heap[0]=heap[heap.size()-1]; 33 | heap.resize(heap.size()-1); 34 | Minheapify(0); 35 | return root; 36 | } 37 | int Minheap::insert(int n,int dis) 38 | { 39 | int i; 40 | if(key[n]==-1) 41 | { 42 | key[n]=dis; 43 | heap.push_back(n); 44 | i=heap.size()-1; 45 | } 46 | else if(key[n]>dis) 47 | { 48 | key[n]=dis; 49 | for(int j=0;jkey[heap[l]]) 77 | min=l; 78 | else 79 | min=i; 80 | if(r > *adj; 94 | public: 95 | Graph(int v) 96 | { 97 | V=v; 98 | adj=new list< pair >[v+1]; 99 | intialise(v); 100 | } 101 | void addEdge(int u,int v,int w) 102 | { 103 | adj[u].push_back(make_pair(v,w)); 104 | adj[v].push_back(make_pair(u,w)); 105 | } 106 | void Display(); 107 | int MST(int ); 108 | }; 109 | void Graph::Display() 110 | { 111 | for(int i=1;i<=V;i++) 112 | { 113 | cout< "; 114 | list< pair >::iterator k=adj[i].begin(); 115 | while(k!=adj[i].end()) 116 | { 117 | cout<first<<" "<second<<" "; 118 | k++; 119 | } 120 | cout< >::iterator k=adj[s].begin(); 134 | while(k!=adj[s].end()) 135 | { 136 | insert(k->first,k->second+key[s]); 137 | k++; 138 | } 139 | /*for(int i=0;i >::iterator k=adj[num].begin(); 150 | while(k!=adj[num].end()) 151 | { 152 | if(visited[k->first]==false) 153 | { 154 | insert(k->first,k->second); 155 | } 156 | k++; 157 | } 158 | } 159 | return sum; 160 | } 161 | int main() { 162 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 163 | int n,m; 164 | scanf("%d %d",&n,&m); 165 | Graph g(n); 166 | while(m--) 167 | { 168 | int u,v,w; 169 | scanf("%d %d %d",&u,&v,&w); 170 | g.addEdge(u,v,w); 171 | } 172 | //g.Display(); 173 | int s; 174 | cin>>s; 175 | cout< 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Graph 7 | { 8 | int V; 9 | list *adj; 10 | 11 | void topologicalSortUtil(int v, bool visited[], stack &Stack); 12 | public: 13 | Graph(int V); // Constructor 14 | 15 | void addEdge(int v, int w); 16 | void topologicalSort(); 17 | }; 18 | 19 | Graph::Graph(int V) 20 | { 21 | this->V = V; 22 | adj = new list[V]; 23 | } 24 | 25 | void Graph::addEdge(int v, int w) 26 | { 27 | adj[v].push_back(w); // Add w to v’s list. 28 | } 29 | 30 | void Graph::topologicalSortUtil(int v, bool visited[],stack &Stack) 31 | { 32 | 33 | visited[v] = true; 34 | 35 | // Recur for all the vertices adjacent to this vertex 36 | list::iterator i; 37 | for (i = adj[v].begin(); i != adj[v].end(); ++i) 38 | if (!visited[*i]) 39 | topologicalSortUtil(*i, visited, Stack); 40 | 41 | // Push current vertex to stack which stores result 42 | Stack.push(v); 43 | } 44 | 45 | void Graph::topologicalSort() 46 | { 47 | stack Stack; 48 | 49 | bool *visited = new bool[V]; 50 | for (int i = 0; i < V; i++) 51 | visited[i] = false; 52 | 53 | for (int i = 0; i < V; i++) 54 | if (visited[i] == false) 55 | topologicalSortUtil(i, visited, Stack); 56 | 57 | while (Stack.empty() == false) 58 | { 59 | cout << Stack.top() << " "; 60 | Stack.pop(); 61 | } 62 | } 63 | int main() 64 | { 65 | 66 | Graph g(6); 67 | g.addEdge(5, 2); 68 | g.addEdge(5, 0); 69 | g.addEdge(4, 0); 70 | g.addEdge(4, 1); 71 | g.addEdge(2, 3); 72 | g.addEdge(3, 1); 73 | 74 | cout << "Following is a Topological Sort of the given graph n"; 75 | g.topologicalSort(); 76 | 77 | return 0; 78 | } -------------------------------------------------------------------------------- /Interview prep/README.md: -------------------------------------------------------------------------------- 1 | # Interview Prep resources 2 | 3 | 4 | ### Website Links 5 | 6 | * [https://leetcode.com/](https://leetcode.com/) 7 | 8 | * [https://www.interviewbit.com/](https://www.interviewbit.com/) 9 | 10 | ### Must do Coding Questions 11 | 12 | * [FAANG](https://www.geeksforgeeks.org/must-do-coding-questions-for-companies-like-amazon-microsoft-adobe/) 13 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2017 Nimit Aggarwal and Piyush Gupta 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | this software and associated documentation files (the "Software"), to deal in 7 | the Software without restriction, including without limitation the rights to 8 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software is furnished to do so, 10 | 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, FITNESS 17 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Data Structures And Algorithms 2 | 3 | ### Please star the repository 4 | 5 | ## Contributing 6 | 7 | Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on our coding guidelines and the process for submitting pull requests to us. 8 | 9 | ## Coding Guidelines 10 | 11 | * All the codes should be modular. 12 | * All the codes should be indented. 13 | * Name of the file should be algorithm's name and first letter of file should be capital. 14 | * Code written should be readable. 15 | * Variable names should be logical and understandable. 16 | Like int x; //This is not allowed 17 | * Same algorithm can be submitted in different languages. 18 | * Please Fix only one issue in one pull request 19 | 20 | ## Authors 21 | 22 | See the list of [contributors](https://github.com/CodersForLife/Data-Structures-Algorithms/contributors) who participated in this project. 23 | 24 | ## License 25 | 26 | This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details 27 | -------------------------------------------------------------------------------- /Searching/Binary-Search.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int binarySearch(int arr[], int beg, int last, int element) // returns the position of the element if the search is successfull, otherwise returns -1. 4 | { 5 | if (beg<=last) 6 | { 7 | int mid = (beg+last)/2; 8 | if (arr[mid] == x) 9 | return mid; 10 | else if (arr[mid] > x) 11 | return binarySearch(arr,beg, mid-1, x); 12 | else 13 | return binarySearch(arr, mid+1, last, x); 14 | } 15 | return -1; 16 | } 17 | 18 | int main() 19 | { 20 | int arr[] = {10, 34, 22, 4, 5}; 21 | int n = sizeof(arr)/ sizeof(arr[0]); 22 | int x = 10; 23 | int result = binarySearch(arr, 0, n-1, x); 24 | (result == -1)? printf("Element is not present in array") 25 | : printf("Element is present at index %d", result); 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /Searching/Binary-Search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int binarySearch(int *arr,int low,int high,int x){ 5 | if(high >= low){ 6 | int mid = (low+high)/2; 7 | if(arr[mid] == x) return mid; 8 | if(arr[mid] > x) return binarySearch(arr,low,mid-1,x); 9 | if(arr[mid] < x) return binarySearch(arr,mid+1,high,x); 10 | } 11 | return -1; 12 | } 13 | 14 | int main(){ 15 | int n; // number of elemmets of array 16 | cin>>n; 17 | int a[n+1]; 18 | for(int i=0;i>a[i]; 20 | } 21 | cout<<"\n Enter element to be searched\n"; 22 | int x; 23 | cin>>x; 24 | int ret = binarySearch(a,0,n,x); 25 | (ret==-1) ? (cout<<"Element not present") : (cout<<"Element found at index "< endIndex) { 9 | return -1; 10 | } 11 | int mid = startIndex + (endIndex - startIndex) / 2; 12 | if (num == arr[mid]) { 13 | return mid; 14 | } else if (num > arr[mid]) { 15 | return binarySearch(arr, num, mid + 1, endIndex); 16 | } else { 17 | return binarySearch(arr, num, startIndex, mid - 1); 18 | } 19 | } 20 | 21 | public static void main(String[] args) { 22 | Scanner s = new Scanner(System.in); 23 | int size = s.nextInt(); 24 | int[] arr = new int[size]; 25 | for (int i = 0; i < arr.length; i++) { 26 | arr[i] = s.nextInt(); 27 | } 28 | int num = s.nextInt(); 29 | int position = binarySearch(arr, num, 0, size - 1); 30 | if (position == -1) { 31 | System.out.println("The number is not present in the array"); 32 | } else { 33 | System.out.println("The position of number in array is : " 34 | + position); 35 | } 36 | s.close(); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /Searching/BinarySearch.js: -------------------------------------------------------------------------------- 1 | function binarySearch(array, targetValue) { 2 | var high = array.length - 1; 3 | var low = 0; 4 | var mid; 5 | 6 | while (low <= high) { 7 | // Getting the mid index of the array, using Math.floor to cancel out decimals 8 | mid = Math.floor((high + low) / 2); 9 | 10 | if (targetValue === array[mid]) { 11 | return mid; 12 | } else if (targetValue > array[mid]) { 13 | // Setting low as mid + 1 because target can only be above mid 14 | low = mid + 1; 15 | } else { 16 | // Setting high as mid - 1 because target can only be below mid 17 | high = mid - 1; 18 | } 19 | } 20 | 21 | return "Not Found"; 22 | } 23 | 24 | function main() { 25 | 26 | // Example 27 | var exampleArray = [1, 2, 3, 4, 4, 7, 8, 11, 13, 20]; 28 | var exampleTarget = 13; 29 | result = binarySearch(exampleArray, exampleTarget); 30 | if (result === "Not Found") { 31 | console.log("Your value " + exampleTarget + " was " + result); 32 | } else { 33 | console.log("Your value " + exampleTarget + " was found at array index " + result); 34 | } 35 | } 36 | 37 | main(); -------------------------------------------------------------------------------- /Searching/BinarySearch.py: -------------------------------------------------------------------------------- 1 | Returns index of x in arr if present, else -1 2 | def binarySearch (arr, l, r, x): 3 | 4 | # Check base case 5 | if r >= l: 6 | 7 | mid = l + (r - l)/2 8 | 9 | # If element is present at the middle itself 10 | if arr[mid] == x: 11 | return mid 12 | 13 | # If element is smaller than mid, then it can only 14 | # be present in left subarray 15 | elif arr[mid] > x: 16 | return binarySearch(arr, l, mid-1, x) 17 | 18 | # Else the element can only be present in right subarray 19 | else: 20 | return binarySearch(arr, mid+1, r, x) 21 | 22 | else: 23 | # Element is not present in the array 24 | return -1 25 | 26 | # Test array 27 | arr = [ 2, 3, 4, 10, 40 ] 28 | x = 10 29 | 30 | # Function call 31 | result = binarySearch(arr, 0, len(arr)-1, x) 32 | 33 | if result != -1: 34 | print "Element is present at index %d" % result 35 | else: 36 | print "Element is not present in array" 37 | 38 | -------------------------------------------------------------------------------- /Searching/LinearSearch.java: -------------------------------------------------------------------------------- 1 | public class MyLinearSearch { 2 | 3 | public static int linerSearch(int[] arr, int key){ 4 | 5 | int size = arr.length; 6 | for(int i=0;i 2 | using namespace std; 3 | 4 | int ternary_search(int array[],int l,int r, int x) 5 | { 6 | if(r>=l) 7 | { 8 | int mid1 = l + (r-l)/3; 9 | int mid2 = r - (r-l)/3; 10 | if(array[mid1] == x) 11 | return mid1; 12 | if(array[mid2] == x) 13 | return mid2; 14 | if(xarray[mid2]) 17 | return ternary_search(array,mid2+1,r,x); 18 | else 19 | return ternary_search(array,mid1+1,mid2-1,x); 20 | 21 | } 22 | return -1; 23 | } 24 | int main() { 25 | 26 | int size; 27 | cin>>size; 28 | int array[size]; 29 | for(int i=0;i>array[i]; 32 | } 33 | int val; 34 | cin>>val; 35 | cout< arr[mid1]: 45 | lo = mid2 + 1 46 | else: 47 | lo = mid1 + 1 48 | hi = mid2 - 1 49 | 50 | if flag == False: 51 | print("Value Not Found") -------------------------------------------------------------------------------- /Segment Tree/SegmentTree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int query(int x,int tree[],int start,int end,int a[],int l, int r); 4 | int update(int x,int tree[],int start,int end,int a[],int idx,int val); 5 | int build(int x,int tree[],int start,int end,int a[]); 6 | int main() 7 | { 8 | int n,q; 9 | cin>>n>>q; 10 | int l=1; 11 | while(l>a[i]; 23 | } 24 | else 25 | { 26 | a[i]=INT_MAX; 27 | } 28 | //cout<>c; 41 | if(c=='q') 42 | { 43 | int x,y; 44 | cin>>x>>y; 45 | x--; 46 | y--; 47 | cout<>x>>y; 53 | x--; 54 | update(0,tree,0,l-1,a,x,y); 55 | } 56 | } 57 | return 0; 58 | } 59 | int build(int x,int tree[],int start,int end,int a[]) 60 | { 61 | if(start==end) 62 | { 63 | tree[x]=a[start]; 64 | } 65 | else 66 | { 67 | int mid=(start+end)/2; 68 | build(2*x+1,tree,start,mid,a); 69 | build(2*x+2,tree,mid+1,end,a); 70 | tree[x]=min(tree[2*x+1],tree[2*x+2]); 71 | } 72 | return 0; 73 | } 74 | int query(int x,int tree[],int start,int end,int a[],int l, int r) 75 | { 76 | if(r=start&&mid>=idx) 101 | update(2*x+1,tree,start,mid,a,idx,val); 102 | else 103 | update(2*x+2,tree,mid+1,end,a,idx,val); 104 | 105 | tree[x]=min(tree[2*x+1],tree[2*x+2]); 106 | } 107 | return 0; 108 | } -------------------------------------------------------------------------------- /Sorting/BubbleSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class BubbleSort { 4 | 5 | public static void bubbleSort(int[] arr) { 6 | int temp = 0; 7 | for (int i = 0; i < arr.length - 1; i++) { 8 | for (int j = 0; j < arr.length - (i + 1); j++) { 9 | if (arr[j] > arr[j + 1]) { 10 | temp = arr[j]; 11 | arr[j] = arr[j + 1]; 12 | arr[j + 1] = temp; 13 | } 14 | } 15 | } 16 | } 17 | 18 | public static void main(String[] args) { 19 | Scanner s = new Scanner(System.in); 20 | int size = s.nextInt(); 21 | int arr[] = new int[size]; 22 | for (int i = 0; i < arr.length; i++) { 23 | arr[i] = s.nextInt(); 24 | } 25 | bubbleSort(arr); 26 | for (int i = 0; i < arr.length; i++) { 27 | System.out.print(arr[i] + " "); 28 | } 29 | s.close(); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /Sorting/Bubble_Sort.py: -------------------------------------------------------------------------------- 1 | # Bubble Sort Program 2 | """ Bubble Sort takes an array as an input and returns the sorted array by default in ascending order without changing the orignal array. 3 | Pre-Conditions - Array must contain elements of integer type only. 4 | - By default ascending order is given for reverse order set Reverse = True. 5 | 6 | Bubble_Sort(Array_Orig, Reverse = False) --> Standard Function Call 7 | 8 | Example: 9 | 10 | List = [1, 3, 5, 3, 2, 8, 2, 4] 11 | 12 | Bubble_Sort(List) returns --> [1, 2, 2, 3, 3, 4, 5, 8] 13 | Bubble_Sort(List, Reverse = False) returns --> [1, 2, 2, 3, 3, 4, 5, 8] 14 | Bubble_Sort(List, Reverse = True) returns --> [8, 5, 4, 3, 3, 2, 2, 1] 15 | 16 | """ 17 | 18 | def Bubble_Sort(Array_Orig, Reverse = False): 19 | 20 | # Copy of Array so that changes made are not reflected 21 | Array = list(Array_Orig) 22 | 23 | for i in range(len(Array)): 24 | Max = Array[i] 25 | Pos = i 26 | for j in range(i, len(Array)): 27 | if not Reverse: 28 | if Max > Array[j]: 29 | Max = Array[j] 30 | Pos = j 31 | elif Reverse: 32 | if Max < Array[j]: 33 | Max = Array[j] 34 | Pos = j 35 | 36 | # Swapping the positions 37 | Array[i],Array[Pos] = Array[Pos],Array[i] 38 | return Array -------------------------------------------------------------------------------- /Sorting/Bubblesort.js: -------------------------------------------------------------------------------- 1 | // Swap function which can easily swap two indices of any array. 2 | 3 | Array.prototype.swap = function (first,second) { 4 | var temp = this[first]; 5 | this[first] = this[second]; 6 | this[second] = temp; 7 | return this; 8 | } 9 | 10 | // Main bubble sort logic. 11 | 12 | function bubbleSort(array) { 13 | for(let i = 1; i < array.length; ++i) { 14 | sorted = true; 15 | 16 | for(let j = 0 ; j < array.length - i ; ++j) { 17 | if(array[j] > array[j+1]) { 18 | array.swap(j, j+1); 19 | sorted = false; 20 | } 21 | } 22 | 23 | if(sorted) { 24 | break; 25 | } 26 | } 27 | return array; 28 | } 29 | 30 | // Sample array 31 | 32 | let array = [-1, 0, -100, 11, 10, 19, 1 , 50, 11, 7]; 33 | 34 | // Calling bubble sort function 35 | 36 | console.log(bubbleSort(array)); 37 | -------------------------------------------------------------------------------- /Sorting/CountingSort.cpp: -------------------------------------------------------------------------------- 1 | #include //including all the libraries of cpp 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int N; 7 | cout<<"Enter the number of elements to sort"<>N; //to enter the number of elements to sort 9 | int a[N]; //array to store all the elements 10 | cout<<"Start entering the numbers"<>a[i]; 14 | } 15 | int min,max; //variables to store the max and min values 16 | min=max=a[0]; 17 | for(int i=0;imax) 22 | max=a[i]; 23 | } 24 | int sort[max-min+1]; //array to count the frequency of all elements 25 | for(int i=min;i<=max;i++) //initialising all frequencies to zero 26 | { 27 | sort[i]=0; 28 | } 29 | for(int i=0;i 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; //Not the best tactic, used for cleaner code and better understanding 8 | 9 | class Heap { 10 | private: 11 | std::vector heap; 12 | int hpsz; 13 | public: 14 | 15 | Heap(){ 16 | hpsz=0; //At first the Heap is Empty 17 | heap.push_back(0); //Index 0 must be initialized because we start indexing from 1 18 | } 19 | 20 | Heap(std::vector& array){ 21 | int n = array.size(); 22 | heap.push_back(100); //The first index of heap array is 1 so we must fill 0 index with dummy content let it be 0 23 | heap.insert(heap.end(),array.begin(),array.end()); //προσθέτω το 0 24 | hpsz=n; //Heap size = Heap Array size 25 | for (int i = n / 2; i > 0; i--) combine(i); 26 | } 27 | 28 | void insert(int elmnt) { 29 | heap.push_back(elmnt); 30 | hpsz++; 31 | int i = hpsz, parent = i / 2; 32 | while ((i > 1) && (heap[parent] < heap[i])) 33 | { 34 | iter_swap(heap.begin() + parent, heap.begin() + i); 35 | i = parent; parent = i / 2; 36 | } 37 | } 38 | 39 | //Get max without deleting from heap 40 | int peek_max(){ 41 | return heap[1]; 42 | } 43 | 44 | void combine (int i){ 45 | int mp=i,left=2*i,right=(2*i)+1; 46 | if((left<=hpsz) && (heap[left]>heap[mp])) { 47 | mp = left; 48 | } 49 | if((right<=hpsz) && (heap[right]>heap[mp])) { 50 | mp = right; 51 | } 52 | if(mp!=i) { 53 | iter_swap(heap.begin() + i, heap.begin() + mp); 54 | combine(mp); 55 | } 56 | } 57 | 58 | int deletemax(){ 59 | if(isEmpty()) return -1; 60 | int max = heap[1]; 61 | 62 | heap[1] = heap[hpsz--]; 63 | combine(1); 64 | return max; 65 | } 66 | 67 | bool isEmpty(){ 68 | return (hpsz==0); 69 | } 70 | 71 | int getHeapSize(){ 72 | return (hpsz); 73 | } 74 | 75 | void heapSort(){ 76 | int temp = hpsz; 77 | for (int i = hpsz; i > 1; i--) { 78 | iter_swap(heap.begin() + 1, heap.begin() + i); 79 | hpsz--; 80 | combine(1); 81 | } 82 | hpsz = temp; 83 | } 84 | 85 | void printHeap(){ 86 | for (int i = 1; i <= hpsz; i++) { 87 | printf("%d ", heap[i] ); 88 | } 89 | printf("\n"); 90 | } 91 | }; 92 | 93 | int main(){ 94 | /* 95 | Heap can be constructed using vector as input 96 | */ 97 | int a[] = {3,4,10,8,15,16,17,12,11,20}; 98 | vector heapin (a, a + sizeof(a) / sizeof(a[0]) ); //C++2003 99 | //std::vector heapin ({3,4,10,8,15,16,17,12,11,20}); //C++2011 100 | // std::vector heapin(std::begin(a), std::end(a)); //C++2003 101 | Heap test(heapin); 102 | /* 103 | Heap can be constructed using one by one insertion of elements 104 | <--------------------------------------------------------------> 105 | Heap test; 106 | int num_elements; 107 | printf("Enter number of elements\n"); 108 | scanf("%d\n",&num_elements); 109 | int elem; 110 | 111 | while(num_elements!=0) { 112 | num_elements--; 113 | scanf("%dendl",&elem ); 114 | test.insert(elem); 115 | } 116 | */ 117 | 118 | test.printHeap(); //Heap array 119 | test.heapSort(); //after heap sorting the array does not include a list 120 | test.printHeap(); //Sorted array 121 | 122 | /* 123 | * Use the following loop to extract all the elements from head of max heap 124 | while (!test.isEmpty()) { 125 | printf("Max after delete: %d\n", test.deletemax()); 126 | } 127 | */ 128 | 129 | 130 | 131 | } 132 | -------------------------------------------------------------------------------- /Sorting/Insertion_Sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | /* Function to sort an array using insertion sort*/ 6 | void insertionSort(int arr[], int n) 7 | { 8 | int i, key, j; 9 | for (i = 1; i < n; i++) 10 | { 11 | key = arr[i]; 12 | j = i-1; 13 | 14 | /* Move elements of arr[0..i-1], that are 15 | greater than key, to one position ahead 16 | of their current position */ 17 | while (j >= 0 && arr[j] > key) 18 | { 19 | arr[j+1] = arr[j]; 20 | j = j-1; 21 | } 22 | arr[j+1] = key; 23 | } 24 | } 25 | 26 | // A utility function ot print an array of size n 27 | void printArray(int arr[], int n) 28 | { 29 | int i; 30 | for (i=0; i < n; i++) 31 | cout< curNum: 9 | Arr[j+1] = Arr[j] 10 | else: 11 | break 12 | Arr[pos+1] = curNum 13 | return Arr 14 | 15 | if __name__=="__main__": 16 | test = [10,67,2,998,23,56,32,21,91,21,22] 17 | print(insertion_sort(test)) 18 | 19 | -------------------------------------------------------------------------------- /Sorting/Insertionsort.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Created by Tay on 10/11/17. 3 | // 4 | 5 | void insertionSort(int table[], int size) { 6 | int key, j; 7 | for (int i = 1; i < size; i++) { 8 | key = table[i]; 9 | j = i - 1; 10 | while (j >= 0 && table[j] > key) { 11 | table[j + 1] = table[j]; 12 | j--; 13 | } 14 | table[j + 1] = key; 15 | } 16 | } 17 | 18 | int main() { 19 | int table[] = {13, 32, 43, 14, 25}; 20 | insertionSort(table, 5); 21 | return 0; 22 | } 23 | 24 | -------------------------------------------------------------------------------- /Sorting/MergeSort.java: -------------------------------------------------------------------------------- 1 | public class MergeSort { 2 | 3 | public static void mergeSort(int[] arr) { 4 | mergeSort(arr, 0, arr.length-1); 5 | } 6 | 7 | public static void mergeSort(int[] arr, int leftIndex, int rightIndex) { 8 | int arrLen = rightIndex + 1 - leftIndex; 9 | 10 | if (arrLen > 1) { 11 | int midIndex = (leftIndex + rightIndex) / 2; 12 | 13 | mergeSort(arr, leftIndex, midIndex); 14 | mergeSort(arr, midIndex+1, rightIndex); 15 | merge(arr, leftIndex, midIndex, rightIndex); 16 | } 17 | } 18 | 19 | public static void merge(int[] arr, int leftIndex, int midIndex, int rightIndex) { 20 | int leftLen = midIndex + 1 - leftIndex; 21 | int rightLen = rightIndex - midIndex; 22 | 23 | int[] leftArr = new int[leftLen]; 24 | int[] rightArr = new int[rightLen]; 25 | 26 | for (int i = 0; i < leftLen; i++) { 27 | leftArr[i] = arr[i+leftIndex]; 28 | } 29 | 30 | for (int j = 0; j < rightLen; j++) { 31 | rightArr[j] = arr[j+midIndex+1]; 32 | } 33 | 34 | int i = 0; 35 | int j = 0; 36 | int k = leftIndex; 37 | 38 | while (i < leftLen && j < rightLen) { 39 | if (leftArr[i] < rightArr[j]) { 40 | arr[k] = leftArr[i]; 41 | i++; 42 | } else { 43 | arr[k] = rightArr[j]; 44 | j++; 45 | } 46 | k++; 47 | } 48 | 49 | while (i < leftLen) { 50 | arr[k] = leftArr[i]; 51 | i++; 52 | k++; 53 | } 54 | 55 | while (j < rightLen) { 56 | arr[k] = rightArr[j]; 57 | j++; 58 | k++; 59 | } 60 | } 61 | } -------------------------------------------------------------------------------- /Sorting/MergeSort.js: -------------------------------------------------------------------------------- 1 | var a = [149, 520, 50, 76, 270, 684, 128, 584, 290]; 2 | 3 | function merge(left, right) 4 | { 5 | var result = []; 6 | 7 | while (left.length && right.length) { 8 | if (left[0] <= right[0]) { 9 | result.push(left.shift()); 10 | } else { 11 | result.push(right.shift()); 12 | } 13 | } 14 | 15 | while (left.length) 16 | result.push(left.shift()); 17 | 18 | while (right.length) 19 | result.push(right.shift()); 20 | 21 | return result; 22 | } 23 | 24 | function mergeSort(arr) 25 | { 26 | if (arr.length < 2) 27 | return arr; 28 | 29 | var middle = parseInt(arr.length / 2); 30 | var left = arr.slice(0, middle); 31 | var right = arr.slice(middle, arr.length); 32 | 33 | return merge(mergeSort(left), mergeSort(right)); 34 | } 35 | 36 | console.log(mergeSort(a)); 37 | -------------------------------------------------------------------------------- /Sorting/QuickSort.java: -------------------------------------------------------------------------------- 1 | public class QuickSort { 2 | 3 | public static void quickSort(int[] arr) { 4 | quickSort(arr, 0, arr.length-1); 5 | } 6 | 7 | public static void quickSort(int[] arr, int leftIndex, int rightIndex) { 8 | int arrLength = rightIndex + 1 - leftIndex; 9 | 10 | if (arrLength > 1) { 11 | int partitionIndex = partition(arr, leftIndex, rightIndex); 12 | 13 | quickSort(arr, leftIndex, partitionIndex-1); 14 | quickSort(arr, partitionIndex+1, rightIndex); 15 | } 16 | } 17 | 18 | public static int partition(int[] arr, int leftIndex, int rightIndex) { 19 | int pivot = arr[rightIndex]; 20 | int partitionIndex = leftIndex; 21 | 22 | for (int i = leftIndex; i < rightIndex; i++) { 23 | if (arr[i] < pivot) { 24 | swap(arr, i, partitionIndex); 25 | partitionIndex++; 26 | } 27 | } 28 | swap(arr, partitionIndex, rightIndex); 29 | 30 | return partitionIndex; 31 | } 32 | 33 | public static void swap(int[] arr, int i, int j) { 34 | int temp = arr[i]; 35 | arr[i] = arr[j]; 36 | arr[j] = temp; 37 | } 38 | } -------------------------------------------------------------------------------- /Sorting/Quick_sort.py: -------------------------------------------------------------------------------- 1 | def quick_sort(arr, left_index, right_index): 2 | if left_index < right_index: 3 | partition_index = partition(arr, left_index, right_index) 4 | 5 | quick_sort(arr, left_index, partition_index-1) 6 | quick_sort(arr, partition_index+1, right_index) 7 | 8 | def partition(arr, left_index, right_index): 9 | pivot = arr[right_index] 10 | partition_index = left_index 11 | 12 | for i in range(left_index, right_index): 13 | if arr[i] < pivot: 14 | arr[i], arr[partition_index] = arr[partition_index], arr[i] 15 | partition_index += 1 16 | arr[partition_index], arr[right_index] = arr[right_index], arr[partition_index] 17 | 18 | return partition_index 19 | 20 | if __name__ == "__main__": 21 | arr = [1,3,5,4,2,6,8,9,7,10,13,12,14,16,15,17,19,18] 22 | 23 | quick_sort(arr, 0, len(arr)-1) 24 | print(arr) 25 | -------------------------------------------------------------------------------- /Sorting/Radix Sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | void radixSort(int *arr, int &no_of_elmnts){ 6 | int min = INT_MAX; 7 | int max = INT_MIN; 8 | 9 | for(int i=0;imax){ 11 | max = arr[i]; 12 | continue; 13 | } 14 | if(arr[i] > buckets; 33 | int place_value=1; 34 | for(int i=0;i::iterator it; 45 | for(it=buckets[j].begin(); it!=buckets[j].end();it++){ 46 | arr[arr_index++]=*it; 47 | } 48 | } 49 | place_value*=10; 50 | } 51 | 52 | if(min<0){ 53 | for(int i=0;i>no_of_elmnts; 63 | 64 | int *arr = new int[no_of_elmnts]; 65 | 66 | for(int i=0;i>arr[i]; 68 | } 69 | radixSort(arr, no_of_elmnts); 70 | 71 | return 0; 72 | } -------------------------------------------------------------------------------- /Sorting/SelectionSort.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Utility class for sorting an array using Selection Sort algorithm. Selection 3 | * Sort is a basic algorithm for sorting with O(n^2) time complexity. Basic idea 4 | * of this algorithm is to find a local minimum, which is the minimum value from 5 | * (i+1) to length of the array [i+1, arr.length), and swap it with the current 6 | * working index (i). 7 | * 8 | * @author Kongpon Charanwattanakit 9 | * 10 | */ 11 | public class SelectionSort { 12 | 13 | /** 14 | * Sort an array using Selection Sort algorithm. 15 | * 16 | * @param arr 17 | * is an array to be sorted 18 | */ 19 | public static void sort(int[] arr) { 20 | for (int i = 0; i < arr.length; i++) { 21 | int min = i; 22 | for (int j = i + 1; j < arr.length; j++) { 23 | /* find local min */ 24 | if (arr[j] < arr[min]) { 25 | min = j; 26 | } 27 | } 28 | swap(arr, i, min); 29 | } 30 | } 31 | 32 | /** 33 | * Utility method for swapping elements in an array. 34 | * 35 | * @param arr 36 | * is an array to be swapped 37 | * @param i 38 | * is index of first element 39 | * @param j 40 | * is index of second element 41 | */ 42 | private static void swap(int[] arr, int i, int j) { 43 | int temp = arr[i]; 44 | arr[i] = arr[j]; 45 | arr[j] = temp; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Sorting/SelectionSort.js: -------------------------------------------------------------------------------- 1 | var selectionSort = function(arr) { 2 | for(var i = 0; i < arr.length; i++){ 3 | //set low to the current value of i 4 | var low = i; 5 | for(var j = i+1; j < arr.length; j++){ 6 | if(arr[j] < arr[low]){ 7 | low = j; 8 | } 9 | } 10 | var temp = arr[i]; 11 | arr[i] = arr[low]; 12 | arr[low] = temp; 13 | } 14 | return arr; 15 | }; 16 | -------------------------------------------------------------------------------- /Sorting/SelectionSortAlt.cpp: -------------------------------------------------------------------------------- 1 | // A fairly verbose implementation of selection sort 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | inline bool ascending(int x, int y) 8 | { 9 | return x > y; 10 | } 11 | 12 | inline bool descending(int x, int y) 13 | { 14 | return x < y; 15 | } 16 | 17 | void selection_sort(int *array, std::size_t size, std::function direction) 18 | { 19 | for (std::size_t current_index = 0; current_index < size; ++current_index) 20 | { 21 | // The element we want to swap 22 | int preferred_index = current_index; 23 | 24 | for (std::size_t next_index = current_index + 1; next_index < size; ++next_index) 25 | { 26 | if (direction(array[preferred_index], array[next_index])) 27 | preferred_index = next_index; 28 | } 29 | 30 | std::swap(array[current_index], array[preferred_index]); 31 | 32 | } 33 | } 34 | 35 | int main() 36 | { 37 | 38 | const std::size_t size = 5; 39 | int array[size] = { 8, 5, 4, 2, 1 }; 40 | selection_sort(array, size, ascending); 41 | 42 | for (std::size_t i = 0; i < size; ++i) 43 | std::cout << array[i] << '\n'; 44 | 45 | return 0; 46 | } 47 | 48 | -------------------------------------------------------------------------------- /Sorting/Selectionsort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | void main() 4 | { 5 | clrscr(); 6 | int size, arr[50], i, j, temp; 7 | cout<<"Enter Array Size : "; 8 | cin>>size; 9 | cout<<"Enter Array Elements : "; 10 | for(i=0; i>arr[i]; 13 | } 14 | cout<<"Sorting array using selection sort...\n"; 15 | for(i=0; iarr[j]) 20 | { 21 | temp=arr[i]; 22 | arr[i]=arr[j]; 23 | arr[j]=temp; 24 | } 25 | } 26 | } 27 | cout<<"Now the Array after sorting is :\n"; 28 | for(i=0; i 2 | 3 | int main() 4 | { 5 | int array[100], n, c, d, swap; 6 | 7 | printf("Enter number of elements\n"); 8 | scanf("%d", &n); 9 | 10 | printf("Enter %d integers\n", n); 11 | 12 | for (c = 0; c < n; c++) 13 | scanf("%d", &array[c]); 14 | 15 | for (c = 0 ; c < ( n - 1 ); c++) 16 | { 17 | for (d = 0 ; d < n - c - 1; d++) 18 | { 19 | if (array[d] > array[d+1]) /* For decreasing order use < */ 20 | { 21 | swap = array[d]; 22 | array[d] = array[d+1]; 23 | array[d+1] = swap; 24 | } 25 | } 26 | } 27 | 28 | printf("Sorted list in ascending order:\n"); 29 | 30 | for ( c = 0 ; c < n ; c++ ) 31 | printf("%d\n", array[c]); 32 | 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /Sorting/bubblesort.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | func bubbleSort(arrayItem []int) { 8 | 9 | for i := 0; i < len(arrayItem)-1; i++ { 10 | for j := 0; j < len(arrayItem)-i-1; j++ { 11 | if arrayItem[j] > arrayItem[j+1] { 12 | temp := arrayItem[j] 13 | arrayItem[j] = arrayItem[j+1] 14 | arrayItem[j+1] = temp 15 | } 16 | } 17 | } 18 | 19 | } 20 | 21 | func main() { 22 | 23 | arrayItem := []int{2, 4, 1, 8, 3, 5, 9} 24 | fmt.Println("Original: ", arrayItem) 25 | bubbleSort(arrayItem) 26 | fmt.Println("Sorted: ", arrayItem) 27 | 28 | } 29 | -------------------------------------------------------------------------------- /Sorting/bucketsort.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define MAX 1000000 6 | 7 | 8 | void ler(int arr[], int n) 9 | { 10 | int i; 11 | for(i = 0; i < n; i++) 12 | { 13 | arr[i] = rand() % n; 14 | } 15 | } 16 | 17 | void print(int arr[], int n, char mens[]) 18 | { 19 | int i; 20 | printf("%s\n",mens); 21 | for(i = 0; i < n; i++) 22 | { 23 | printf("%d ", arr[i]); 24 | if(i % 50 == 0 && i > 0) printf("\n"); 25 | } 26 | printf("\n"); 27 | } 28 | typedef struct no 29 | { 30 | int valor; 31 | struct no* prox; 32 | }No; 33 | 34 | void inserir(No** r, int valor) 35 | { 36 | No* p; 37 | No* aux = NULL; 38 | No* atual = (*r); 39 | int cond = 1; 40 | 41 | p = (No*)malloc(sizeof(No)); 42 | 43 | p->valor = valor; 44 | p->prox = NULL; 45 | 46 | while(atual != NULL && cond) 47 | { 48 | if(valor < atual->valor) cond = 0; 49 | else 50 | { 51 | aux = atual; 52 | atual = atual->prox; 53 | } 54 | } 55 | p->prox = atual; 56 | if(aux == NULL) (*r) = p; 57 | else aux->prox = p; 58 | } 59 | 60 | void bucketSort(int arr[], int n) 61 | { 62 | No** bucket = (No**)malloc(n * sizeof(No*)); 63 | printf("------------------BUCKETSORT------------------\n"); 64 | int i,j; 65 | for(i = 0; i < n; i++) 66 | { 67 | bucket[i] = NULL; 68 | } 69 | for(i = 0; i < n; i++) 70 | { 71 | int indice = n * ((double) arr[i]/(n + 1)); 72 | inserir(bucket+indice, arr[i]); 73 | 74 | } 75 | int ind = 0; 76 | No* b; 77 | for(i = 0; i < n; i++) 78 | { 79 | b = bucket[i]; 80 | while(b != NULL) 81 | { 82 | arr[ind++] = (b)->valor; 83 | bucket[i] = (b)->prox; 84 | free(b); 85 | b = bucket[i]; 86 | } 87 | free(b); 88 | } 89 | } 90 | /*------------------------------------------*/ 91 | int main() 92 | { 93 | srand(time(NULL)); 94 | int n; 95 | printf("Input the array size\n"); 96 | scanf("%d",&n); 97 | int *arr = malloc(sizeof(int)*n); 98 | 99 | 100 | 101 | ler(arr, n); 102 | print(arr, n, "Antes"); 103 | printf("\n"); 104 | bucketSort(arr, n); 105 | printf("\n"); 106 | print(arr, n, "Depois"); 107 | printf("\n\n"); 108 | 109 | return 0; 110 | } 111 | -------------------------------------------------------------------------------- /Sorting/insertionsort.java: -------------------------------------------------------------------------------- 1 | /* Created by Jacob Rodgers 2 | 10/11/17 3 | */ 4 | 5 | public class insertionSort { 6 | 7 | public void iSort(int userArray[]){ 8 | for (int i = 1; i < userArray.length; i++){ 9 | //create an index variable for tracking current number 10 | int index = userArray[i]; 11 | //and a second counting variable, j 12 | int j = i - 1; 13 | 14 | //Iterate through entire Array comparing each variable to the index assigned above 15 | while ((j >= 0) && (userArray[j] > index)) { 16 | //If there is a number out of order then we will switch them 17 | userArray[j+1] = userArray[j]; 18 | j = j - 1; 19 | } 20 | userArray[j+1] = index; 21 | } 22 | } 23 | } 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /Sorting/mergesort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define NX 500010 4 | 5 | int N, A[NX], B[NX]; 6 | 7 | void mergeSort(int left, int right) { 8 | int middle = (left + right) >> 1, i, j, k; 9 | 10 | if (left == right) { 11 | return; 12 | } 13 | 14 | mergeSort(left, middle); 15 | mergeSort(middle + 1, right); 16 | 17 | for (i = left, j = middle + 1, k = left; i <= middle || j <= right;) { 18 | if (j > right || (i <= middle && A[i] < A[j])) { 19 | B[k++] = A[i++]; 20 | } else { 21 | B[k++] = A[j++]; 22 | } 23 | } 24 | for (k = left; k <= right; k++) { 25 | A[k] = B[k]; 26 | } 27 | } 28 | 29 | int main() { 30 | int i; 31 | 32 | scanf("%d", &N); 33 | for (i = 1; i <= N; i++) 34 | scanf("%d", A + i); 35 | 36 | mergeSort(1, N); 37 | 38 | for (i = 1; i <= N; i++) 39 | printf("%d ", A[i]); 40 | 41 | return 0; 42 | } -------------------------------------------------------------------------------- /Sorting/mergesort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | void merge(int A[],int p,int q,int r) 5 | { 6 | int i,j,x,y; 7 | int n1=q-p+1;int n2=r-q; 8 | int B[n1],C[n2]; 9 | for(i=0;i=r) 55 | { 56 | return; 57 | } 58 | else 59 | { 60 | q=(p+r)/2; 61 | mergesort(A,p,q); 62 | mergesort(A,q+1,r); 63 | merge(A,p,q,r); 64 | } 65 | } 66 | 67 | int main() 68 | { 69 | int A[5],a; 70 | for(a=0;a<5;a++) 71 | cin>>A[a]; 72 | mergesort(A,0,4); 73 | for(a=0;a<5;a++) 74 | cout< 2 | using namespace std; 3 | int comp=0; 4 | int Partition(int a[],int p,int q) 5 | { 6 | 7 | int x=a[p]; 8 | int i=p,temp; 9 | for(int j=p+1;j<=q;j++) 10 | { 11 | if(a[j]<=x) 12 | { 13 | i++; 14 | temp=a[i]; 15 | a[i]=a[j]; 16 | a[j]=temp; 17 | } 18 | } 19 | temp=a[i]; 20 | a[i]=x; 21 | a[p]=temp; 22 | for(int c=0;c<6;c++) 23 | cout<>n; 43 | for(int i=0;i>a[i]; 45 | Quicksort(a,0,n-1); 46 | for(int i=0;i 2 | 3 | using namespace std; 4 | void make_lps(int *lps, string &pattern){ 5 | int j=0, i=1; 6 | lps[0]=0; 7 | while(i0){ 12 | j=lps[j-1]; 13 | } 14 | else{ 15 | lps[i++]=0; 16 | } 17 | } 18 | } 19 | 20 | int match(string &orig, string &pattern, int *lps){ 21 | int patt_index=0; 22 | int orig_index=0; 23 | while(orig_index>orig; 46 | 47 | string pattern; 48 | cin>>pattern; 49 | int lps[pattern.length()]; 50 | make_lps(lps, pattern); 51 | 52 | 53 | cout< 2 | #include 3 | #include 4 | 5 | void append(int element); 6 | void clear(void); 7 | int max(void); 8 | int get(unsigned int position); 9 | void remove_element(unsigned int position); 10 | 11 | struct Node 12 | { 13 | int value; 14 | struct Node* next; 15 | }; 16 | 17 | static struct Node* head = 0; 18 | 19 | void append(int element) 20 | { 21 | if (!head) 22 | { 23 | head = (struct Node*)malloc(sizeof(struct Node)); 24 | head->value = element; 25 | head->next = 0; 26 | } 27 | else 28 | { 29 | struct Node* iterator = head; 30 | while (iterator->next != 0) 31 | iterator = iterator->next; 32 | 33 | iterator->next = (struct Node*)malloc(sizeof(struct Node)); 34 | iterator->next->value = element; 35 | iterator->next->next = 0; 36 | } 37 | } 38 | 39 | void clear(void) 40 | { 41 | if (head == 0) 42 | return; 43 | 44 | struct Node* iterator = head; 45 | struct Node* iterator2; 46 | while (iterator != 0) 47 | { 48 | iterator2 = iterator->next; 49 | free(iterator); 50 | iterator = iterator2; 51 | } 52 | head = 0; 53 | } 54 | 55 | int max(void) 56 | { 57 | int max = 0; 58 | for (struct Node* iterator = head; iterator; iterator = iterator->next) 59 | if (iterator->value > max) 60 | max = iterator->value; 61 | 62 | return max; 63 | } 64 | 65 | 66 | int get(unsigned int position) 67 | { 68 | struct Node* iterator = head; 69 | for (int i = 0; i < position; i++) 70 | { 71 | if (!iterator || !iterator->next) 72 | return 0; 73 | 74 | iterator = iterator->next; 75 | } 76 | 77 | return iterator->value; 78 | } 79 | 80 | void remove_element(unsigned int position) 81 | { 82 | struct Node* iterator = head; 83 | struct Node* prev_iterator = head; 84 | for (int i = 0; i < position; i++) 85 | { 86 | if (!iterator || !iterator->next) 87 | return; 88 | 89 | prev_iterator = iterator; 90 | iterator = iterator->next; 91 | } 92 | 93 | if(position == 0) 94 | { 95 | head = iterator->next; 96 | free(iterator); 97 | } 98 | else 99 | { 100 | iterator = iterator->next; 101 | free(prev_iterator->next); 102 | prev_iterator->next = iterator; 103 | } 104 | } 105 | 106 | ///////// 107 | //TESTS// 108 | ///////// 109 | 110 | void max_of_one_element_is_same_element(void) 111 | { 112 | append(5); 113 | assert(max() == 5); 114 | clear(); 115 | } 116 | 117 | void max_of_three_elements(void) 118 | { 119 | append(3); 120 | append(5); 121 | append(2); 122 | assert(max() == 5); 123 | clear(); 124 | } 125 | 126 | void get_returns_element_in_position(void) 127 | { 128 | append(3); 129 | append(5); 130 | append(7); 131 | assert(get(2) == 7); 132 | assert(get(0) == 3); 133 | assert(get(500) == 0); 134 | clear(); 135 | } 136 | 137 | void erasing_elements(void) 138 | { 139 | append(3); 140 | append(5); 141 | append(7); 142 | remove_element(1); 143 | assert(get(0) == 3); 144 | assert(get(1) == 7); 145 | assert(get(2) == 0); 146 | clear(); 147 | } 148 | 149 | 150 | int main (void) 151 | { 152 | max_of_one_element_is_same_element(); 153 | max_of_three_elements(); 154 | get_returns_element_in_position(); 155 | erasing_elements(); 156 | printf("All tests passed!\r\n"); 157 | } -------------------------------------------------------------------------------- /Structures/LinkedList.java: -------------------------------------------------------------------------------- 1 | 2 | public class LinkedList { 3 | public Node head = null; 4 | 5 | public int length(){ //returns length of linkedlist 6 | int cnt = 0; 7 | Node temp = this.head; 8 | while(temp != null){ 9 | temp = temp.next; 10 | cnt++; 11 | } 12 | return cnt; 13 | } 14 | 15 | public int sumOfElements(){ //returns the sum of elements in linkedlist 16 | int sum = 0; 17 | Node temp = this.head; 18 | while(temp != null){ 19 | sum += temp.data; 20 | temp = temp.next; 21 | } 22 | return sum; 23 | } 24 | 25 | 26 | public void searchNode(Node n){ 27 | Node temp = this.head; 28 | int cnt = 0; 29 | while(temp != null){ 30 | if(temp == n){ 31 | System.out.println("Node found at pos: " + cnt); 32 | return; 33 | } 34 | temp=temp.next; 35 | cnt++; 36 | } 37 | System.out.println("Node does not exist"); 38 | } 39 | 40 | // Deletes Nodes at even position 41 | public void deleteEven(){ 42 | Node temp = this.head; 43 | int cnt = 0; 44 | while(cnt != this.length()){ 45 | if(cnt%2 == 0){ 46 | this.deleteAtPos(cnt); 47 | } 48 | cnt++; 49 | } 50 | } 51 | 52 | public void insertAtHead(int value){ 53 | Node newNode = new Node(value); 54 | Node temp = this.head; 55 | if(temp == null){ 56 | this.head = newNode; 57 | } 58 | else{ 59 | newNode.next = this.head; 60 | this.head = newNode; 61 | } 62 | 63 | } 64 | 65 | 66 | public void insertAtTail(int value){ 67 | Node newNode = new Node(value); 68 | Node temp = this.head; 69 | if(temp == null){ 70 | this.head = newNode; 71 | } 72 | else{ 73 | while(temp.next != null){ 74 | temp = temp.next; 75 | } 76 | temp.next = newNode; 77 | } 78 | } 79 | 80 | public void insertAtPos(int value, int k){ 81 | Node temp = this.head; 82 | if(k == 0){ 83 | this.insertAtHead(value); 84 | } 85 | else{ 86 | int cnt = 0; 87 | Node newNode = new Node(value); 88 | Node prev = temp; 89 | while(temp!=null && k!=cnt){ 90 | prev = temp; 91 | temp = temp.next; 92 | cnt++; 93 | } 94 | if(temp == null){ 95 | System.out.println("Invalid position"); 96 | } 97 | else{ 98 | prev.next = newNode; 99 | newNode.next = temp; 100 | } 101 | } 102 | } 103 | 104 | public void deleteAtPos(int k){ 105 | Node temp = this.head; 106 | if(k == 0){ 107 | temp = temp.next; 108 | this.head.next = null; 109 | this.head = temp; 110 | } 111 | else{ 112 | Node prev = temp; 113 | int cnt = 0; 114 | while(temp.next != null && k!=cnt){ 115 | prev = temp; 116 | temp = temp.next; 117 | cnt++; 118 | } 119 | if(k == this.length() - 1){ 120 | temp.next = null; 121 | } 122 | else if(k == cnt){ 123 | prev.next = temp.next; 124 | temp.next = null; 125 | } 126 | else{ 127 | System.out.println("Invalid Position"); 128 | } 129 | 130 | } 131 | } 132 | 133 | public void deleteValue(int value){ 134 | Node temp = this.head; 135 | Node prev = temp; 136 | while(temp.data != value && temp != null){ 137 | prev = temp; 138 | temp = temp.next; 139 | } 140 | if(temp == null){ 141 | System.out.println("Value is not present"); 142 | } 143 | else{ 144 | prev.next = temp.next; 145 | temp.next = null; 146 | } 147 | } 148 | 149 | public void print(){ 150 | if(this.head == null){ 151 | System.out.println("Empty list"); 152 | } 153 | else{ 154 | Node temp = this.head; 155 | while(temp != null){ 156 | System.out.print(temp.data + " "); 157 | temp = temp.next; 158 | } 159 | } 160 | } 161 | 162 | public static LinkedList Concat(LinkedList L1, LinkedList L2){ 163 | LinkedList L = new LinkedList(); 164 | L.head = L1.head; 165 | Node temp = L.head; 166 | while(temp.next != null){ 167 | temp = temp.next; 168 | } 169 | temp.next = L2.head; 170 | 171 | return L; 172 | } 173 | 174 | private void reverse(Node temp, Node prev){ 175 | if(temp == null){ 176 | this.head = prev; 177 | return; 178 | } 179 | else{ 180 | reverse(temp.next,temp); 181 | temp.next = prev; 182 | return; 183 | } 184 | } 185 | 186 | public void reverseList(){ 187 | this.reverse(this.head,null); 188 | } 189 | 190 | public void split(LinkedList l1,LinkedList l2){ 191 | Node temp = this.head; 192 | int cnt = 1; 193 | l1.head = this.head; 194 | while(temp != null){ 195 | if(cnt%2 == 0){ 196 | l1.insertAtTail(temp.data); 197 | } 198 | else{ 199 | l2.insertAtTail(temp.data); 200 | } 201 | } 202 | } 203 | } 204 | 205 | 206 | class Node { 207 | int data; 208 | Node next; 209 | Node prev; 210 | 211 | Node(){ 212 | data = 0; 213 | next = null; 214 | prev = null; 215 | } 216 | 217 | Node(int data){ 218 | this.data = data; 219 | this.next = null; 220 | this.prev = null; 221 | } 222 | } 223 | -------------------------------------------------------------------------------- /Structures/LinkedLists/DNode.java: -------------------------------------------------------------------------------- 1 | package LinkedLists; 2 | 3 | // Implementation of a double linked node from a double linked list 4 | // Java 8 5 | // Aitor Alonso (https://github.com/tairosonloa) 6 | 7 | public class DNode { 8 | 9 | public Object elem; 10 | public DNode prev; 11 | public DNode next; 12 | 13 | public DNode(Object elem) { 14 | this.elem = elem; 15 | } 16 | } -------------------------------------------------------------------------------- /Structures/LinkedLists/QueueDLinked.java: -------------------------------------------------------------------------------- 1 | package LinkedLists; 2 | 3 | // Implementation of a queue using double linked list 4 | // Java 8 5 | // Aitor Alonso (https://github.com/tairosonloa) 6 | 7 | public class QueueDLinked { 8 | 9 | private DNode header; 10 | private DNode trailer; 11 | 12 | public QueueDLinked() { 13 | header = new DNode(null); 14 | trailer = new DNode(null); 15 | header.next = trailer; 16 | trailer.prev= header; 17 | } 18 | 19 | 20 | /** 21 | * Checks if queue is empty 22 | * @return true if queue is empty, false in other case 23 | */ 24 | public boolean isEmpty() { 25 | return (header.next == trailer); 26 | } 27 | 28 | 29 | /** 30 | * Enqueue an element 31 | * @param elem The element to be enqueued 32 | */ 33 | public void enqueue(Object elem) { 34 | DNode newNode = new DNode(elem); 35 | newNode.next = trailer; 36 | newNode.prev= trailer.prev; 37 | trailer.prev.next = newNode; 38 | trailer.prev= newNode; 39 | } 40 | 41 | 42 | /** 43 | * Dequeue an element 44 | * @return elem dequeued, null if queue is empty 45 | */ 46 | public Object dequeue() { 47 | if (!isEmpty()) { 48 | Object elem = header.next.elem; 49 | header.next = header.next.next; 50 | header.next.prev = header; 51 | return elem; 52 | } 53 | else System.out.println("The queue is empty. Cannot dequeue."); 54 | return null; 55 | } 56 | 57 | 58 | /** 59 | * Gets the queue size 60 | * @return int with the queue size 61 | */ 62 | public int getSize() { 63 | int size = 0; 64 | if (!isEmpty()) { 65 | for (DNode nodeIt = header.next; nodeIt != trailer; nodeIt = nodeIt.next) 66 | size++; 67 | } 68 | return size; 69 | } 70 | 71 | 72 | /** 73 | * Prints the queue on standard output 74 | */ 75 | public void printQueue() { 76 | if (!isEmpty()) { 77 | for (DNode nodeIt = header.next; nodeIt != trailer; nodeIt = nodeIt.next) { 78 | System.out.print(nodeIt.elem + " "); 79 | } 80 | System.out.println(); 81 | } 82 | else System.out.println("The queue is empty."); 83 | } 84 | 85 | 86 | /** 87 | * Just to check the class QueueDLinked works 88 | * @param args 89 | */ 90 | public static void main(String[] args) { 91 | 92 | // Just to check it works 93 | System.out.println("Testing class QueueDLinked"); 94 | QueueDLinked queue = new QueueDLinked(); 95 | System.out.println("Calling method isEmpty()"); 96 | System.out.println("queue.isEmpty(): " + queue.isEmpty()); 97 | System.out.println("Calling method getSize()"); 98 | System.out.println("queue.getSize(): " + queue.getSize()); 99 | System.out.println("Trying to dequeue with empty queue:"); 100 | queue.dequeue(); 101 | System.out.println("Calling method enqueue(). Enqueue element 1."); 102 | queue.enqueue(1); 103 | System.out.println("Calling method enqueue(). Enqueue element 2."); 104 | queue.enqueue(2); 105 | System.out.println("Calling method enqueue(). Enqueue element 3."); 106 | queue.enqueue(3); 107 | System.out.println("Printing the queue:"); 108 | queue.printQueue(); 109 | System.out.println("Calling method isEmpty()"); 110 | System.out.println("queue.isEmpty(): " + queue.isEmpty()); 111 | System.out.println("Calling method getSize()"); 112 | System.out.println("queue.getSize(): " + queue.getSize()); 113 | System.out.println("Calling method dequeue()"); 114 | System.out.println("Dequeued: " + queue.dequeue()); 115 | System.out.println("Calling method isEmpty()"); 116 | System.out.println("queue.isEmpty(): " + queue.isEmpty()); 117 | System.out.println("Calling method getSize()"); 118 | System.out.println("queue.getSize(): " + queue.getSize()); 119 | System.out.println("Printing the queue:"); 120 | queue.printQueue(); 121 | System.out.println("Test finished. Bye!"); 122 | } 123 | } -------------------------------------------------------------------------------- /Structures/LinkedLists/StackDLinked.java: -------------------------------------------------------------------------------- 1 | package LinkedLists; 2 | 3 | // Implementation of a queue using double linked list 4 | // Java 8 5 | // Aitor Alonso (https://github.com/tairosonloa) 6 | 7 | public class StackDLinked 8 | { 9 | 10 | private DNode header; 11 | private DNode trailer; 12 | 13 | public StackDLinked() { 14 | header = new DNode(null); 15 | trailer = new DNode(null); 16 | header.next = trailer; 17 | trailer.prev= header; 18 | } 19 | 20 | 21 | /** 22 | * Checks if stack is empty 23 | * @return true if stack is empty, false in other case 24 | */ 25 | public boolean isEmpty() { 26 | return (header.next == trailer); 27 | } 28 | 29 | 30 | /** 31 | * Pushes an element 32 | * @param elem The element to be pushed 33 | */ 34 | public void push(Object elem) { 35 | DNode newNode = new DNode(elem); 36 | newNode.next = trailer; 37 | newNode.prev= trailer.prev; 38 | trailer.prev.next = newNode; 39 | trailer.prev= newNode; 40 | } 41 | 42 | 43 | /** 44 | * Pops an element 45 | * @return elem popped, null if stack is empty 46 | */ 47 | public Object pop() { 48 | if (!isEmpty()) { 49 | Object elem = trailer.prev.elem; 50 | trailer.prev=trailer.prev.prev; 51 | trailer.prev.next=trailer; 52 | return elem; 53 | } 54 | else System.out.println("The stack is empty. Cannot pop."); 55 | return null; 56 | } 57 | 58 | 59 | /** 60 | * Gets the stack size 61 | * @return int with the stack size 62 | */ 63 | public int getSize() { 64 | int size = 0; 65 | if (!isEmpty()) { 66 | for (DNode nodeIt = header.next; nodeIt != trailer; nodeIt = nodeIt.next) 67 | size++; 68 | } 69 | return size; 70 | } 71 | 72 | 73 | /** 74 | * Prints the stack on standard output 75 | */ 76 | public void printStack() { 77 | if (!isEmpty()) { 78 | for (DNode nodeIt = header.next; nodeIt != trailer; nodeIt = nodeIt.next) { 79 | System.out.print(nodeIt.elem + " "); 80 | } 81 | System.out.println(" 5 | 6 | using namespace std; 7 | 8 | template 9 | class Queue { 10 | private: 11 | T *data; 12 | int first, last; 13 | int length; 14 | 15 | public: 16 | Queue() { 17 | data = new T[100]; 18 | first = last = 0; 19 | length = 100; 20 | } 21 | 22 | Queue(int _length): length(_length) { 23 | data = new T[_length]; 24 | first = last = 0; 25 | } 26 | 27 | ~Queue() { 28 | if (data) { 29 | delete[] data; 30 | } 31 | } 32 | 33 | void push(T _data) { 34 | if (last < length) { 35 | if (first != last) { 36 | data[last] = _data; 37 | } else { 38 | data[first] = _data; 39 | } 40 | last++; 41 | } else { 42 | cout<<"Queue is full"< { 5 | private int max; 6 | private int top; 7 | private Object[] list; 8 | 9 | public Stack() { 10 | max = 512; 11 | top = 0; 12 | list = new Object[max]; 13 | } 14 | 15 | public Stack(int size) { 16 | max = size; 17 | top = 0; 18 | list = new Object[max]; 19 | } 20 | 21 | @SuppressWarnings("unchecked") 22 | public boolean isEmpty() { 23 | for(E t : (E[]) list) { 24 | if(t != null) { 25 | return false; 26 | } 27 | } 28 | 29 | return true; 30 | } 31 | 32 | @SuppressWarnings("unchecked") 33 | public E peek() { 34 | return (E) list[top]; 35 | } 36 | 37 | @SuppressWarnings("unchecked") 38 | public int size() { 39 | if(top == 0) { 40 | return 0; 41 | } 42 | 43 | int count = 0; 44 | for(E t : (E[]) list) { 45 | if(t != null) { 46 | count++; 47 | } 48 | } 49 | 50 | return count; 51 | } 52 | 53 | @SuppressWarnings("unchecked") 54 | public E pop() { 55 | if(isEmpty()) { 56 | throw new IndexOutOfBoundsException("This stack is empty; nothing to pop."); 57 | } 58 | 59 | E data = (E) list[top]; 60 | 61 | top = (top == 0 ? 0 : top - 1); 62 | return data; 63 | } 64 | 65 | public void push(E data) { 66 | if(top == max - 1) { 67 | list = Arrays.copyOf(list, list.length * 2); 68 | } 69 | 70 | top++; 71 | list[top] = data; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /Structures/infixtopostfix.c++: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int precedence(char c) 7 | { 8 | if(c=='^') 9 | return 3; 10 | else if(c=='*' || c=='/') 11 | return 2; 12 | else if(c=='+' || c=='-')infixtopostfix.c++ 13 | return 1; 14 | else 15 | return -1; 16 | } 17 | 18 | void converttopostfix(string s) 19 | { 20 | stack st; 21 | st.push('N'); 22 | int l=s.length(); 23 | string ns; 24 | for(int i=0;i= 'a' && s[i] <= 'z') || (s[i] >= 'A' && s[i] <= 'Z')) 27 | ns=ns+s[i]; 28 | else if(s[i] == '(') 29 | st.push('('); 30 | else if(s[i] == ')') 31 | { 32 | while(st.top() != 'N' && st.top() != '(') 33 | { 34 | char c=st.top(); 35 | st.pop(); 36 | ns=ns+c; 37 | } 38 | if(st.top() == '(') 39 | { 40 | char c=st.top(); 41 | st.pop(); 42 | } 43 | } 44 | else 45 | { 46 | while(st.top() != 'N' && (precedence(s[i])<=precedence(st.top()))) 47 | { 48 | char c=st.top(); 49 | st.pop(); 50 | ns=ns+c; 51 | } 52 | st.push(s[i]); 53 | } 54 | } 55 | while(st.top() != 'N') 56 | { 57 | char c=st.top(); 58 | st.pop(); 59 | ns=ns+c; 60 | } 61 | 62 | cout<>s; 68 | converttopostfix(s); 69 | return 0; 70 | } -------------------------------------------------------------------------------- /Trees/Bfs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | #title :Bfs.py 4 | #description :Breadth first search implementation in python 5 | #reference :http://eddmann.com/posts/depth-first-search-and-breadth-first-search-in-python/ 6 | #date :10102017 7 | #version :0.1 8 | #============================================================================== 9 | 10 | # Implementation 11 | class Bfs(): 12 | # Initializer for the class 13 | def __init__(self,graphAdjList): 14 | self.graphAdjList = graphAdjList 15 | # Check for the graph 16 | if not len(self.graphAdjList)>=1: 17 | raise ValueError('please pass a valid graph') 18 | 19 | # Function to traverse in a bfs manner 20 | # BFS algorithm: 21 | # 1. Start with the head node in queue 22 | # 2. repeat while queue is not empty 23 | # 1. Pop queue 24 | # 2. add neighbors if already not visited to list 25 | # 3. remove from queue 26 | # 3. return list 27 | def traverse(self,start): 28 | visited, queue = set(), [start] 29 | while queue and start and start in self.graphAdjList: 30 | vertex = queue.pop(0) 31 | if vertex not in visited: 32 | visited.add(vertex) 33 | queue.extend(self.graphAdjList[vertex] - visited) 34 | return visited 35 | 36 | 37 | # Main method to trigger the execution 38 | if __name__ == '__main__': 39 | # Variables 40 | # Define the adjacency list for the graph (undirected) 41 | graphAdjList = {'A': set(['B', 'C']), 42 | 'B': set(['A', 'D', 'E']), 43 | 'C': set(['A']), 44 | 'D': set(['B']), 45 | 'E': set(['B', 'F']), 46 | 'F': set(['E'])} 47 | 48 | thisBfs = Bfs(graphAdjList) 49 | print "BFS traversal is: "+str(thisBfs.traverse('A')) 50 | -------------------------------------------------------------------------------- /Trees/Child Sum Java: -------------------------------------------------------------------------------- 1 | // Java program to check children sum property 2 | 3 | /* A binary tree node has data, pointer to left child 4 | and a pointer to right child */ 5 | class Node 6 | { 7 | int data; 8 | Node left, right; 9 | 10 | public Node(int d) 11 | { 12 | data = d; 13 | left = right = null; 14 | } 15 | } 16 | 17 | class BinaryTree 18 | { 19 | Node root; 20 | 21 | /* returns 1 if children sum property holds for the given 22 | node and both of its children*/ 23 | int isSumProperty(Node node) 24 | { 25 | 26 | /* left_data is left child data and right_data is for right 27 | child data*/ 28 | int left_data = 0, right_data = 0; 29 | 30 | /* If node is NULL or it's a leaf node then 31 | return true */ 32 | if (node == null 33 | || (node.left == null && node.right == null)) 34 | return 1; 35 | else 36 | { 37 | 38 | /* If left child is not present then 0 is used 39 | as data of left child */ 40 | if (node.left != null) 41 | left_data = node.left.data; 42 | 43 | /* If right child is not present then 0 is used 44 | as data of right child */ 45 | if (node.right != null) 46 | right_data = node.right.data; 47 | 48 | /* if the node and both of its children satisfy the 49 | property return 1 else 0*/ 50 | if ((node.data == left_data + right_data) 51 | && (isSumProperty(node.left)!=0) 52 | && isSumProperty(node.right)!=0) 53 | return 1; 54 | else 55 | return 0; 56 | } 57 | } 58 | 59 | /* driver program to test the above functions */ 60 | public static void main(String[] args) 61 | { 62 | BinaryTree tree = new BinaryTree(); 63 | 64 | tree.root = new Node(10); 65 | tree.root.left = new Node(8); 66 | tree.root.right = new Node(2); 67 | tree.root.left.left = new Node(3); 68 | tree.root.left.right = new Node(5); 69 | tree.root.right.right = new Node(2); 70 | if (tree.isSumProperty(tree.root) != 0) 71 | System.out.println("The given tree satisfies children" 72 | + " sum property"); 73 | else 74 | System.out.println("The given tree does not satisfy children" 75 | + " sum property"); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /Trees/Left view binary tree: -------------------------------------------------------------------------------- 1 | // C program to print left view of Binary Tree 2 | #include 3 | #include 4 | 5 | struct node 6 | { 7 | int data; 8 | struct node *left, *right; 9 | }; 10 | 11 | // A utility function to create a new Binary Tree node 12 | struct node *newNode(int item) 13 | { 14 | struct node *temp = (struct node *)malloc(sizeof(struct node)); 15 | temp->data = item; 16 | temp->left = temp->right = NULL; 17 | return temp; 18 | } 19 | 20 | // Recursive function to print left view of a binary tree. 21 | void leftViewUtil(struct node *root, int level, int *max_level) 22 | { 23 | // Base Case 24 | if (root==NULL) return; 25 | 26 | // If this is the first node of its level 27 | if (*max_level < level) 28 | { 29 | printf("%d\t", root->data); 30 | *max_level = level; 31 | } 32 | 33 | // Recur for left and right subtrees 34 | leftViewUtil(root->left, level+1, max_level); 35 | leftViewUtil(root->right, level+1, max_level); 36 | } 37 | 38 | // A wrapper over leftViewUtil() 39 | void leftView(struct node *root) 40 | { 41 | int max_level = 0; 42 | leftViewUtil(root, 1, &max_level); 43 | } 44 | 45 | // Driver Program to test above functions 46 | int main() 47 | { 48 | struct node *root = newNode(12); 49 | root->left = newNode(10); 50 | root->right = newNode(30); 51 | root->right->left = newNode(25); 52 | root->right->right = newNode(40); 53 | 54 | leftView(root); 55 | 56 | return 0; 57 | } 58 | -------------------------------------------------------------------------------- /Trees/MinMax tree: -------------------------------------------------------------------------------- 1 | // A simple C++ program to find 2 | // maximum score that 3 | // maximizing player can get. 4 | #include 5 | using namespace std; 6 | 7 | // Returns the optimal value a maximizer can obtain. 8 | // depth is current depth in game tree. 9 | // nodeIndex is index of current node in scores[]. 10 | // isMax is true if current move is 11 | // of maximizer, else false 12 | // scores[] stores leaves of Game tree. 13 | // h is maximum height of Game tree 14 | int minimax(int depth, int nodeIndex, bool isMax, 15 | int scores[], int h) 16 | { 17 | // Terminating condition. i.e 18 | // leaf node is reached 19 | if (depth == h) 20 | return scores[nodeIndex]; 21 | 22 | // If current move is maximizer, 23 | // find the maximum attainable 24 | // value 25 | if (isMax) 26 | return max(minimax(depth+1, nodeIndex*2, false, scores, h), 27 | minimax(depth+1, nodeIndex*2 + 1, false, scores, h)); 28 | 29 | // Else (If current move is Minimizer), find the minimum 30 | // attainable value 31 | else 32 | return min(minimax(depth+1, nodeIndex*2, true, scores, h), 33 | minimax(depth+1, nodeIndex*2 + 1, true, scores, h)); 34 | } 35 | 36 | // A utility function to find Log n in base 2 37 | int log2(int n) 38 | { 39 | return (n==1)? 0 : 1 + log2(n/2); 40 | } 41 | 42 | // Driver code 43 | int main() 44 | { 45 | // The number of elements in scores must be 46 | // a power of 2. 47 | int scores[] = {3, 5, 2, 9, 12, 5, 23, 23}; 48 | int n = sizeof(scores)/sizeof(scores[0]); 49 | int h = log2(n); 50 | int res = minimax(0, 0, true, scores, h); 51 | cout << "The optimal value is : " << res << endl; 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /Trees/Mirror Tree: -------------------------------------------------------------------------------- 1 | // Java program to convert binary tree into its mirror 2 | 3 | /* Class containing left and right child of current 4 | node and key value*/ 5 | class Node 6 | { 7 | int data; 8 | Node left, right; 9 | 10 | public Node(int item) 11 | { 12 | data = item; 13 | left = right = null; 14 | } 15 | } 16 | 17 | class BinaryTree 18 | { 19 | Node root; 20 | 21 | void mirror() 22 | { 23 | root = mirror(root); 24 | } 25 | 26 | Node mirror(Node node) 27 | { 28 | if (node == null) 29 | return node; 30 | 31 | /* do the subtrees */ 32 | Node left = mirror(node.left); 33 | Node right = mirror(node.right); 34 | 35 | /* swap the left and right pointers */ 36 | node.left = right; 37 | node.right = left; 38 | 39 | return node; 40 | } 41 | 42 | void inOrder() 43 | { 44 | inOrder(root); 45 | } 46 | 47 | /* Helper function to test mirror(). Given a binary 48 | search tree, print out its data elements in 49 | increasing sorted order.*/ 50 | void inOrder(Node node) 51 | { 52 | if (node == null) 53 | return; 54 | 55 | inOrder(node.left); 56 | System.out.print(node.data + " "); 57 | 58 | inOrder(node.right); 59 | } 60 | 61 | /* testing for example nodes */ 62 | public static void main(String args[]) 63 | { 64 | /* creating a binary tree and entering the nodes */ 65 | BinaryTree tree = new BinaryTree(); 66 | tree.root = new Node(1); 67 | tree.root.left = new Node(2); 68 | tree.root.right = new Node(3); 69 | tree.root.left.left = new Node(4); 70 | tree.root.left.right = new Node(5); 71 | 72 | /* print inorder traversal of the input tree */ 73 | System.out.println("Inorder traversal of input tree is :"); 74 | tree.inOrder(); 75 | System.out.println(""); 76 | 77 | /* convert tree to its mirror */ 78 | tree.mirror(); 79 | 80 | /* print inorder traversal of the minor tree */ 81 | System.out.println("Inorder traversal of binary tree is : "); 82 | tree.inOrder(); 83 | 84 | } 85 | } 86 | 87 | 88 | -------------------------------------------------------------------------------- /Trees/Right View Binary Tree: -------------------------------------------------------------------------------- 1 | // C program to print right view of Binary Tree 2 | #include 3 | #include 4 | 5 | struct Node 6 | { 7 | int data; 8 | struct Node *left, *right; 9 | }; 10 | 11 | // A utility function to create a new Binary Tree Node 12 | struct Node *newNode(int item) 13 | { 14 | struct Node *temp = (struct Node *)malloc(sizeof(struct Node)); 15 | temp->data = item; 16 | temp->left = temp->right = NULL; 17 | return temp; 18 | } 19 | 20 | // Recursive function to print right view of a binary tree. 21 | void rightViewUtil(struct Node *root, int level, int *max_level) 22 | { 23 | // Base Case 24 | if (root==NULL) return; 25 | 26 | // If this is the last Node of its level 27 | if (*max_level < level) 28 | { 29 | printf("%d\t", root->data); 30 | *max_level = level; 31 | } 32 | 33 | // Recur for right subtree first, then left subtree 34 | rightViewUtil(root->right, level+1, max_level); 35 | rightViewUtil(root->left, level+1, max_level); 36 | } 37 | 38 | // A wrapper over rightViewUtil() 39 | void rightView(struct Node *root) 40 | { 41 | int max_level = 0; 42 | rightViewUtil(root, 1, &max_level); 43 | } 44 | 45 | // Driver Program to test above functions 46 | int main() 47 | { 48 | struct Node *root = newNode(1); 49 | root->left = newNode(2); 50 | root->right = newNode(3); 51 | root->left->left = newNode(4); 52 | root->left->right = newNode(5); 53 | root->right->left = newNode(6); 54 | root->right->right = newNode(7); 55 | root->right->left->right = newNode(8); 56 | 57 | rightView(root); 58 | 59 | return 0; 60 | } 61 | -------------------------------------------------------------------------------- /Trees/Suffix Tree: -------------------------------------------------------------------------------- 1 | string s; 2 | int n; 3 | 4 | struct node { 5 | int l, r, par, link; 6 | map next; 7 | 8 | node (int l=0, int r=0, int par=-1) 9 | : l(l), r(r), par(par), link(-1) {} 10 | int len() { return r - l; } 11 | int &get (char c) { 12 | if (!next.count(c)) next[c] = -1; 13 | return next[c]; 14 | } 15 | }; 16 | node t[MAXN]; 17 | int sz; 18 | 19 | struct state { 20 | int v, pos; 21 | state (int v, int pos) : v(v), pos(pos) {} 22 | }; 23 | state ptr (0, 0); 24 | 25 | state go (state st, int l, int r) { 26 | while (l < r) 27 | if (st.pos == t[st.v].len()) { 28 | st = state (t[st.v].get( s[l] ), 0); 29 | if (st.v == -1) return st; 30 | } 31 | else { 32 | if (s[ t[st.v].l + st.pos ] != s[l]) 33 | return state (-1, -1); 34 | if (r-l < t[st.v].len() - st.pos) 35 | return state (st.v, st.pos + r-l); 36 | l += t[st.v].len() - st.pos; 37 | st.pos = t[st.v].len(); 38 | } 39 | return st; 40 | } 41 | 42 | int split (state st) { 43 | if (st.pos == t[st.v].len()) 44 | return st.v; 45 | if (st.pos == 0) 46 | return t[st.v].par; 47 | node v = t[st.v]; 48 | int id = sz++; 49 | t[id] = node (v.l, v.l+st.pos, v.par); 50 | t[v.par].get( s[v.l] ) = id; 51 | t[id].get( s[v.l+st.pos] ) = st.v; 52 | t[st.v].par = id; 53 | t[st.v].l += st.pos; 54 | return id; 55 | } 56 | 57 | int get_link (int v) { 58 | if (t[v].link != -1) return t[v].link; 59 | if (t[v].par == -1) return 0; 60 | int to = get_link (t[v].par); 61 | return t[v].link = split (go (state(to,t[to].len()), t[v].l + (t[v].par==0), t[v].r)); 62 | } 63 | 64 | void tree_extend (int pos) { 65 | for(;;) { 66 | state nptr = go (ptr, pos, pos+1); 67 | if (nptr.v != -1) { 68 | ptr = nptr; 69 | return; 70 | } 71 | 72 | int mid = split (ptr); 73 | int leaf = sz++; 74 | t[leaf] = node (pos, n, mid); 75 | t[mid].get( s[pos] ) = leaf; 76 | 77 | ptr.v = get_link (mid); 78 | ptr.pos = t[ptr.v].len(); 79 | if (!mid) break; 80 | } 81 | } 82 | 83 | void build_tree() { 84 | sz = 1; 85 | for (int i=0; i