├── .gitignore ├── Computer_Algorithms.md ├── LICENSE ├── README.md ├── code ├── 01_linear_search.cpp ├── 01_linear_search.py ├── 02_binary_search.cpp ├── 02_binary_search.py ├── PrefixtoPostFix.java ├── bubble_sort.py ├── circular_queue.py ├── heap_sort.py ├── insertion_sort.py ├── merge_sort.py ├── quick_sort.py └── selection_sort.py ├── final-project ├── README.md └── Source.cpp ├── images ├── .DS_Store ├── 01.png ├── 02.png ├── 03.png ├── 04.png ├── 05.png ├── 06.gif ├── 06a.png ├── 07.png ├── 08.png ├── 09.png ├── 09a.png ├── 10.png ├── 11.png ├── 12.png ├── 13.png ├── 14.png ├── 15.png ├── 16.png ├── 17.png ├── 18.png ├── 19.png ├── 20.png ├── 21.png ├── 22.png ├── 23.png ├── 24.png ├── 25.png ├── 26.png ├── 27.png ├── 28.png ├── 29.png ├── 30.png ├── 31.png ├── 32.png ├── 33.png ├── 34.png ├── 35.png ├── 36.png ├── 37.png ├── 38.png ├── 39.png ├── 40.png ├── 41.png ├── 42.png ├── 43.png ├── 44.png ├── 45.png ├── 46.png ├── 47.png ├── 48.png ├── 49.png ├── 50.png ├── 51.png ├── 52.png ├── 53.png ├── 54.png ├── 55.png ├── 56.png ├── 57.png ├── 58.png ├── 59.png ├── 60.png ├── CA │ ├── .DS_Store │ ├── asymp_notat │ │ ├── 1.jpg │ │ ├── 10.jpg │ │ ├── 2.jpg │ │ ├── 3.jpg │ │ ├── 4.jpg │ │ ├── 5.jpg │ │ ├── 6.jpg │ │ ├── 7.jpg │ │ ├── 8.jpg │ │ └── 9.jpg │ ├── back.jpg │ ├── masters.jpg │ ├── masters_decr.png │ ├── masters_div.png │ ├── quick.png │ ├── radix.png │ ├── radix2.png │ ├── sort_complexity.png │ └── tree.jpg ├── complexity.png ├── max_heap.png ├── max_heap2.png ├── merge_sort.png ├── merge_step.png ├── quicksort1.png ├── quicksort2.png ├── quicksort3.png ├── time_complexity1.png └── time_complexity2.png ├── lecture notes ├── .DS_Store ├── 01_Data_Structures.pptx ├── 02_Serching_Techniques.pptx ├── 03_DS_Sorting.pptx ├── 04_Linked_List-_Insert_&_delete_operations.pptx ├── 05_Linked_List-Circular_and_Doubly_Linked_List.pptx ├── 06_Stacks.pptx ├── 07_Infix_to_prefix.pptx ├── 08_Queues.pptx ├── 09_Tree.pptx ├── 10_Traversing_a_tree+_BST.pptx ├── 11_Graphs.pptx ├── 12_BFS_and_DFS.pptx ├── 13_Threaded_Binary-_TREES.ppt ├── 14_AVL_slides.pptx ├── 15_Deletion_-_AVL_tree.pptx ├── 16_Huffman_Coding_Algorithm.pptx ├── 17_M-way_Search_Trees.pptx ├── 18_B_Tree.pptx └── CA │ ├── .DS_Store │ ├── CA_1_Analyzing Running Times of recursive Programs.pptx │ ├── CA_HW2_masters.pdf │ └── CA_HW3_heapsort_quicksort.pdf └── linked_list └── linked_list_java.md /.gitignore: -------------------------------------------------------------------------------- 1 | .* 2 | .idea 3 | .DS_Store -------------------------------------------------------------------------------- /Computer_Algorithms.md: -------------------------------------------------------------------------------- 1 | # Computer Algorithms 2 | 3 | Rustam Zokirov • Sep 19, 2021 4 | 5 | ## Table of contents 6 | - [Introduction](#introduction) 7 | - [Data Abstraction](#data-abstraction) 8 | - [Asymptotic Notations](#asymptotic-notations) 9 | - [Practice 1](#practice-1) 10 | - [Analyzing Recurrences](#analyzing-recurrences) - running time of **recursive program** code 11 | - [Master's Theorem](#masters-theorem) 12 | - Insertion sort 13 | - Merge sort 14 | - [Heap sort](#heap-sort) 15 | - [Quick sort](#quick-sort) 16 | - [Radix sort](#radix-sort) 17 | - Bucket sort 18 | - [RedBlack Tree](#redblack-tree) 19 | 20 | ## Introduction 21 | - A **computer algorithm** is 22 | - a detailed step-by-step method 23 | - for solving a problem 24 | - by using a computer 25 | - **Properties** 26 | - Finiteness (should be terminated) 27 | - Unambiguous (must be clear) 28 | - Definiteness of sequence (by order) 29 | - Input /Output defined 30 | - Feasibility (must be possible to implement) 31 | - **Problem solving strategies** 32 | - Divide & Conquer 33 | - Greedy Method (making the most possible solution) 34 | - Branch & Bound 35 | - Backtracking 36 | - Dynamic Programming 37 | - Brute Force (checking all possibilities) 38 | - Randomized 39 | 40 | 41 | ## Data Abstraction 42 | - Abstact Data Type - each ADT has set of *values* and *operations* 43 | - Encapsulation: hide implementation details 44 | - A data structure is the physical implementation of an ADT 45 | - **Data items have both *logical* and *physical* form** 46 | - Logical form: definition of the data item within an ADT. 47 | - Physical form: implementation of the data item within a data structure 48 | - Abstract Data Types 49 | - Lists, Trees 50 | - Stacks, Queues 51 | - Priority Queue, Union-Find 52 | - Dictionary 53 | - **ADT Specification** 54 | - Specification formally define the behavior of a software system or a module (*in terms of Inputs and Outputs*) 55 | - A specification of an operation consists of: 56 | - Calling prototype 57 | - Preconditions 58 | - Postconditions 59 | - The calling prototype includes 60 | - name of the operation 61 | - parameters and their types 62 | - return value and its types 63 | - The preconditions are statements 64 | - assumed to be true when the operation is called 65 | - The postconditions are statements 66 | - assumed to be true when the operation returns. 67 | 68 | 69 | ## Asymptotic Notations 70 | - Running time of an algorithm as a function of input size **n for large n** 71 | - O (worst, upper bound), Ω (best, lower bound), Θ (average, tight bound) 72 | - “Running time is O(f(n))” -> Worst case is O(f(n)) 73 | - “Running time is Ω(f(n))” -> Best case is Ω(f(n)) 74 | 75 | ### Practice 1 76 | ``` 77 | Big O 78 | __________________________________________________________________ 79 | a. f(n) = 5n^3 + n^2 + 6n + 2 80 | 5n^3 + n^2 + 6n + 2 <= 5n^3 + n^2 + 6n + n n >= 2 81 | <= 5n^3 + n^2 + 7n 82 | <= 5n^3 + n^2 + n^2 n^2 >= 7n, n >= 7 83 | <= 5n^3 + 2n^2 84 | <= 5n^3 + n^3 n^3 >= 2n^2, n >= 2 85 | <= 6n^3 86 | = O(n^3) 87 | [c=6, n>=7] 88 | 89 | b. f(n) = 6n^2 + 3n + 2^n 90 | 2^n + 6n^2 + 3n <= 2^n + 6n^2 + n^2 n^2 >= 6n, n >= 6 91 | <= 2^n + 7n^2 92 | <= 2^n + 2^n 2^n >= n^2, n >= 4 93 | <= 2*2^n 94 | = O(2^n) 95 | [c=2, n=6] 96 | 97 | Big Ω 98 | __________________________________________________________________ 99 | a. 5n^3 + n^2 + 3n + 2 100 | 5n^3+ n^2 + 3n + 2 >= 5n^3 n0 >= 1 101 | = Ω(n^3) 102 | [c=5, n0>=1] 103 | 104 | b. 4*2^n + 3n 105 | 4*2^n + 3n >= 4*2^n n0 >= 1 106 | = Ω(2^n) 107 | [c=4, n0 >= 1] 108 | 109 | Big Θ (average) 110 | __________________________________________________________________ 111 | a. f(n) = 27*n^2 + 16n 112 | 27*n^2+16n <= 27*n^2+n^2 n^2 >= 16n, n >= 16 113 | <= 28*n^2 114 | = O(n^2) 115 | [c1=28, n0=16] 116 | 117 | 27*n^2+16n >= 27*n^2 n0 >= 1 118 | = Ω(n^2) 119 | [c2=27, n0>=1] 120 | 121 | Overall, [c1=28, c2=27, n0>=16] 122 | 123 | b. f(n) = 3*2^n + 4n^2 + 5n + 2 124 | 3*2^n+4n^2+5n+2 <= 3*2^n+4n^2+5n+n n >= 2 125 | <= 3*2^n+4n^2+6n 126 | <= 3*2^n+4n^2+n^2 n^2 >= 6n, n >= 6 127 | <= 3*2^n+5n^2 128 | <= 3*2^n+2^n 2^n >= n^2, n >= 4 129 | <= 4*2^n 130 | = O(2^n) 131 | [c1=4, n0>=6] 132 | 133 | 3*2^n + 4n^2 + 5n + 2 >= 3*2^n n0 >= 1 134 | = Ω(2^n) 135 | [c2=3, n0>=1] 136 | 137 | Overall, [c1=4, c2=3, n0>=6] 138 | 139 | Extra 140 | __________________________________________________________________ 141 | f(n) = 5n^3 + 2 and g(n)= n^2 142 | 143 | a. g(n) = o f(n) 144 | n^2 = o(5n^3 + 2) 145 | n^2 = o(n^3) TRUE 146 | 147 | b. f(n) = O g(n) 148 | 5n^3 + 2 = O(n^2) FALSE, it should be at least O(n^3), O(n^4) 149 | ``` 150 | 151 | ## Analyzing Recurrences 152 | - Back substitution 153 | - Recursive tree method 154 | - Master's theorem 155 | 156 | ``` 157 | // T(n) = n + T(n-1) => O(n^2) 158 | demo(int n){ 159 | if(n>0){ 160 | for(i=1; i<=n; i++) // this 161 | print (“message”); 162 | demo(n-1); // and this 163 | } 164 | else 165 | return 1; 166 | } 167 | 168 | // T(n) = logn + T(n-1) => 0(nlogn) 169 | demo(int n){ 170 | if(n>0){ 171 | for(i=1; i<=n; i=i*2) // logn because of i*2 172 | print (“message”); 173 | demo(n-1); // and this 174 | } 175 | else 176 | return 1; 177 | } 178 | 179 | // T(n) = 2T(n-1) + c => 0(2^n) 180 | demo(int n){ 181 | if(n>0){ 182 | print (“message”); // we don't have for loop 183 | demo(n-1); // 2T(n-1) comes from two recursive funcs 184 | demo(n-1); 185 | } 186 | else 187 | return 1; 188 | } 189 | 190 | // T(n) = T(n/2) + c => 0(logn) 191 | demo(int n){ 192 | if(n>1){ 193 | print (“message”); 194 | demo(n/2); 195 | } 196 | else 197 | return 1; 198 | } 199 | 200 | // O(n) because [n + T(n/2) = n] 201 | demo(int n){ 202 | if(n>1){ 203 | for(i=1; i<=n; i=i+1) 204 | print (“message”); 205 | demo(n/2); 206 | } 207 | else 208 | return 1; 209 | } 210 | // 2T(n/2)+n which is nlogn, when there are 2 times demo(n/2) 211 | 212 | 213 | T(n) = c + T(n-1) => 0(n) 214 | = 1 + T(n-1) => 0(n) 215 | = n + T(n-1) => 0(n^2) 216 | = n^2 + T(n-1) => 0(n^3) 217 | = logn + T(n-1) => 0(nlogn) 218 | 219 | T(n) = 2T(n-1) + c => 0(2^n) 220 | = 3T(n-1) + 1 => 0(3^n) 221 | = 2T(n-1) + n => 0(n2^n) 222 | = 2T(n-1) + logn => 0(logn * 2^n) 223 | ``` 224 | 225 | - Back substitution
226 | 227 | - Recursive tree method (use geometric progression sum formula a(1-r^n)/(1-r) )
228 | 229 | - Master's Theorem
230 | 231 | 232 | 233 | ## Master's Theorem 234 | 235 | 236 | 237 | 238 | ## Heap Sort 239 | - `build_max_heap()` - build max heap from unsorted array 240 | - `max_heapify()` 241 | - `extract_max_heap()` 242 | - How to do: take the max number put it about, then do heapify for both children. Take the root node, and swap with the rightmost leaf child. Then delete root node after swap which is now in the leaf. Then again apply heapify, and extract max heap for whole array. 243 | 244 | ## Quick sort 245 | 246 | 247 | ## Radix sort 248 | https://www.youtube.com/watch?v=XiuSW_mEn7g 249 | 250 | How it works? 251 | 252 | We take the last digit of an element, then sort by it, then we move to another digit, and again sort by them. 253 | 254 | 255 | 256 | 257 | ## Bucket sort 258 | https://www.youtube.com/watch?v=NvZG0dZ60RQ 259 | 260 | We have an array, just put the same values into one bucket. Then place back again. Only in range of 0-999, and these values already created for us. 261 | 262 | 263 | 264 | ## RedBlack Tree 265 | - https://www.youtube.com/watch?v=A3JZinzkMpk&list=PL9xmBV_5YoZNqDI8qfOZgzbqahCUmUEin&index=4 266 | - Case 1: Z.uncle = red --> recolor(all) 267 | - Case 2: Z.uncle = black(triangle) --> rotate Z.parent # just put child(z) above its parent, this will bring case 3 268 | - Case 3: Z.uncle = black(line) --> rotate(Z.grandparent) # parent will be root, + recolor(parent, grandparent) 269 | - O(logn) 270 | 271 | ### Complexity 272 | 273 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Rustam_Z 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Data Structures and Computer Algorithms 2 | Lecture notes on Data Structures `SOC-2010` and Computer Algorithms `SOC-3030` 3 | 4 | By Rustam Zokirov • Fall Semester 2020 • Fall Semester 2021 5 | 6 | > *NOTES ON COMPUTER ALGORITHMS - [HERE](Computer_Algorithms.md)* 7 | 8 | ## Learning roadmap 9 | - [ ] START HERE: [Naso Academy DS playlist](https://www.youtube.com/playlist?list=PLBlnK6fEyqRj9lld8sWIUNwlKfdUoPd1Y) 10 | - [ ] [The Last Algorithms Course You'll Need](https://frontendmasters.com/courses/algorithms/introduction/) 11 | - [ ] ALGORITHMS VIDEO: [Jenny's DSA playlist](https://www.youtube.com/playlist?list=PLdo5W4Nhv31bbKJzrsKfMpo_grxuLl8LU) 12 | - [ ] READING: [programiz.com/dsa](https://www.programiz.com/dsa) 13 | - [ ] SHORT VIDEOS: [Data Structures by Google Software Engineer](https://www.youtube.com/playlist?list=PLDV1Zeh2NRsB6SWUrDFW2RmDotAfPbeHu) 14 | 15 | ## Practicing roadmap 16 | - [ ] [interviewbit.com](https://www.interviewbit.com/courses/programming/) 17 | - [ ] [LeetCode Explore](https://leetcode.com/explore/) 18 | - [ ] [LeetCode study plan](https://leetcode.com/study-plan/) — Data Structure 1, Algorithm 1, Programming Skills 1 19 | - [ ] "Cracking the coding interview" + [CTCI problems in LeetCode](https://leetcode.com/discuss/general-discussion/1152824/cracking-the-coding-interview-6th-edition-in-leetcode) 20 | - [ ] [LeetCode study plan](https://leetcode.com/study-plan/) — Data Structure 2, Algorithm 2, Programming Skills 2 21 | - [ ] AlgoExpert 22 | - [ ] [neetcode.io](https://neetcode.io/) & [NeetCode playlist](https://www.youtube.com/c/NeetCode/playlists) 23 | 24 | ## Contents 25 | - [Introduction to Data Structures](#introduction-to-data-structures) 26 | - [Introduction](#introduction) 27 | - [Abstract Data Type](#abstract-data-type) 28 | - [Asymptotic Notations (O, Ω, Θ)](#asymptotic-notations) 29 | - [Searching techniques](#searching-techniques) 30 | - [Linear Search](#linear-search) 31 | - [Binary Search](#binary-search) 32 | - [Sorting techniques](#sorting-techniques) 33 | - [Merge sort](#merge-sort) 34 | - [Quick sort](#quick-sort) 35 | - [Heap sort](#heap-sort) 36 | - [Linked list](#linked-list) 37 | - [Insertion at the beginning](#insertion-at-beginning-in-linked-list) 38 | - [Insertion at the end](#insertion-at-the-end-in-linked-list) 39 | - [Insertion at particular position](#insertion-at-particular-position) 40 | - [Deleting the first Node](#deleting-the-first-node-from-a-linked-list) 41 | - [Deleting the last Node](#deleting-the-last-node-from-a-linked-list) 42 | - [Deleting the specific node in a Linked List](#deleting-the-specific-node-in-a-linked-list) 43 | - [Circular linked list](#circular-linked-list) 44 | - [Insertion at the beginning](#insertion-at-beginning-in-circular-linked-list) 45 | - [Insertion at the end](#insertion-at-the-end-in-circular-linked-list) 46 | - [Insertion at particular position](#insertion-at-particular-position-in-circular-linked-list) 47 | - [Deletion a node](#deletion-a-node-in-circular-linked-list) 48 | - [Doubly linked list](#doubly-linked-list) 49 | - [Stacks](#stacks) 50 | - [Array representation of stacks](#array-representation-of-stacks) 51 | - [Linked representation of stack](#linked-representation-of-stack) 52 | - [Infix to Postfix](#infix-to-postfix) 53 | - [Evaluation of Postfix expression](#evaluation-of-postfix-expression) 54 | - [Infix to Prefix](#infix-to-prefix) 55 | - [Evaluation of Prefix expression](#evaluation-of-prefix-expression) 56 | - [Queue](#queue) 57 | - [Linear Queue](#linear-queue) 58 | - [Circular Queue](#circular-queue) 59 | - [Double-Ended Queue](#double-ended-queue) 60 | - [Priority Queue](#priority-queue) 61 | - [Tree](#tree) 62 | - [Binary Tree](#binary-tree) 63 | - [Traversing a Binary Tree](#traversing-a-binary-tree) 64 | - [Binary Search Tree](#binary-search-tree) 65 | - [Search & Insert Operation in Binary Search Tree](#search-insert-operation-in-binary-search-tree) 66 | - [Deletion Operation in Binary Search Tree](#deletion-operation-in-binary-search-tree) 67 | - [Graphs](#graphs) 68 | - [Breadth First Search Traversal](#breadth-first-search-traversal) 69 | - [Depth First Search](#depth-first-search) 70 | - [Threaded Binary Tree](#threaded-binary-tree) 71 | - [Inorder Traversal in TBT](#inorder-traversal-in-tbt) 72 | - [Threaded Binary Tree One-Way](#threaded-binary-tree-one-way) 73 | - [Threaded Binary Tree Two-Way](#threaded-binary-tree-two-way) 74 | - [Inserting Node in TBT](#inserting-node-in-tbt) 75 | - [AVL Trees](#avl-trees) 76 | - [Insertion in AVL Tree](#insertion-in-avl-tree) 77 | - [Deletion in AVL Tree](#deletion-in-avl-tree) 78 | - [Huffman Encoding](#huffman-encoding) 79 | - [M-way trees](#m-way-trees) 80 | - [B-Trees](#b-trees) 81 | 82 | ## Introduction to Data Structures 83 | ### Introduction 84 | - Data structure usually refers to a *data organization*, *management*, and *storage* in main memory that enables efficiently access and modification. 85 | - If **data** is arranged systematically then it gets the structure and becomes meaningful. This meaningful and processed data is the **information**. 86 | - The **cost** of a solution is the amount of resources that the solution needs. 87 | - A data structure requires: 88 | - Space for each data item it stores 89 | - Time to perform each basic operation 90 | - Programming effort 91 | - How to select a data structure? 92 | - Identify the problem 93 | - Analyze the problem 94 | - Quantify the resources 95 | - Select the data structure 96 |
97 | 98 |
Data structures hierarchy
99 |
100 | 101 | - Operations on data structures: 102 | - Traversing, Searching, Inserting, Deleting, Sorting, Merging. 103 | - **Algorithm** properties: 104 | - It must be correct (must produce the desired output). 105 | - It is composed of a series of concrete steps. 106 | - There can be no ambiguity. 107 | - It must be composed of a finite number of steps. 108 | - It must terminate. 109 | - To summarize: 110 | - **Problem** - a function of inputs and mapping them to outputs. 111 | - **Algorithm** - a step-by-step set of operations to solve a specific problem or a set of problems. 112 | - **Program** - a specific sequence of instructions in a prog. lang., and it may contain the implementation of many algorithms. 113 | 114 | ### Abstract data type 115 | - https://youtu.be/ZniDyolzrBw, https://youtu.be/n0e27Cpc88E 116 | - Two important things about data types: 117 | - Defines a certain **domain** of values 118 | - Defines **operations** allowed on those values 119 | - Example: `int` takes 120 | - Takes only integer values 121 | - Operations: addition, subtraction, multiplication, division, bitwise operations. 122 | - ADT describes a set of objects sharing the same properties and behaviors. 123 | - The *properties* of an ADT are its data. 124 | - The *behaviors* of an ADT are its operations or functions. 125 | - ADT example: stack (can be implemented with array or linked list) 126 | - **Abstraction** is the method of hiding unwanted information. 127 | - **Encapsulation** is a method to hide the data in a single entity or unit along with a method to protect information from outside. Encapsulation can be implemented using an access modifier i.e. private, protected, and public. 128 | 129 | ### What is the data structure 130 | - A **data structure** is the organization of the data in a way so that it can be used efficiently. 131 | - It is used to implement an ADT. 132 | - ADT tells us *what* is to be done and data structures tell use *how* to do it. 133 | - Types: 134 | - **linear** (stack, array, linked list) 135 | - **non-linear** (tree, graph) 136 | - **static** (compile time memory allocation), array 137 | - Advantage: fast access 138 | - Disadvantage: slow insertion and deletion 139 | - **dynamic** (run-time memory allocation), linked list 140 | - Advantage: faster insertion and deletion 141 | - Disadvantage: slow access 142 | 143 | ### Asymptotic notations 144 | - Efficiency measured in terms of **TIME** and **SPACE**. In terms of number of operations. 145 | - Asymptotic complexity 146 | - The running time depends on the *size of the input* 147 | - `f(n)` = running time of an algorithm, where `n`= input size. We are interested in the growth of `n` to calculate the `f(n)` 148 | - "Functions do more work for bigger input" 149 | - Drop all constants: `3n, 5n, 100n => n`, [why?](https://www.youtube.com/watch?v=MgyLGVUn8LQ) 150 | - Ignore lower order terms: n3 + n2 + n + 5 => n3 151 | - Ignore the base of logs: `log(2) => ln(2)` 152 | - f(n) = O(n2) => describes how f(n) grows in comparison to n2 153 | - Big-O notation, Ω (Omega) notation, Θ (Big-Theta) notation 154 | - Big-O notation is used to measure the performance of any algorithm by providing the order of growth of the function. 155 | - 156 | - 157 | - 158 | - **O (Big-O) notation** (worst time, upper bound, maximum complexity), `0 <= f(n) <= c*g(n) for all n >= n0`, `f(n) = O(g(n))` 159 | ``` 160 | f(n) = 3n + 2, g(n) = n, f(n) = Og(n) 161 | 162 | 3n + 2 <= Cn 163 | 3n + 2 <= 4n 164 | n >= 2 165 | 166 | c = 4, n >= 2 167 | ``` 168 | - n3 = O(n2) False 169 | - n2 = O(n3) True 170 | - **Ω (Omega) notation** (best amount of time, lower bound), `0 <= c*g(n) <= f(n) for all n >=n0` 171 | ``` 172 | f(n) = 3n + 2, g(n) = n, f(n) = Ωg(n) 173 | 174 | 3n + 2 <= Cn 175 | 3n + 2 <= n 176 | 2n >= -2 177 | n >= -1 178 | 179 | c = 1, n >= 1 180 | ``` 181 | - **Θ (Big-theta) notation** (average case, lower & upper sandwich), `0 <= c1*g(n) <= f(n) <= c2*g(n)` 182 | ``` 183 | f(n) = 3n + 2, g(n) = n, f(n) = Θg(n) 184 | 185 | C1*n <= 3n + 2 <= C2*n 186 | 187 | 3n + 2 <= C2*n c1*n <= 3n + 2 188 | 3n + 2 <= 4n 3n + 2 >= n 189 | n >= 2 n >= -1 190 | 191 | c2 = 4, n >= 2 c1 = 1, n >= 1 192 | n >=2 // We must take a greater number, which is true for both 193 | ``` 194 | - [Loops, if-else asymptotic analysis](https://www.youtube.com/watch?v=BpiMRyWoDu0) 195 | 196 | 197 | 198 | 199 | ## Searching Techniques 200 | - **Searching** is an operation that finds the location of a given element in a list. 201 | - The search is said to be **successful** or **unsuccessful** depending on whether the element that is to be searched is found or not. 202 | 203 | ### Linear Search 204 | - **Problem**: Given an array `arr[]` of `n` elements, write a function to search a given element `x` in `arr[]`. 205 | - In this type of search, a sequential search is made over all items one by one. Every item is checked and if a match is found then that particular item is returned, otherwise the search continues till the end of the data collection. 206 |
207 | - Pseudocode: 208 | ``` 209 | procedure linear_search(list, value) 210 | for each item in the list 211 | if item == value 212 | return the item's location 213 | end if 214 | end for 215 | end procedure 216 | ``` 217 | - Linear search in C++ | Linear search in Python 218 | - Analysis: 219 | - Best case `O(1)` 220 | - Average `O(n)` 221 | - Worst `O(n)` 222 | 223 | ### Binary Search 224 | - Binary Search is a searching algorithm for finding an element's position in a **sorted array**. 225 | - It's fast and efficient, time complexity of binary search: `O(log n)` 226 | - In this method: 227 | - To search an element we compare it with the element present at the center of the list. If it matches then the search is successful. 228 | - Otherwise, the list is divided into two halves: 229 | - One from the 0th element to the center element (first half) 230 | - Another from the center element to the last element (second half) 231 | - The search will now proceed in either of the two halves depending upon whether the element is greater or smaller than the center element. 232 | - If the element is smaller than the center element then the searching will be done in the first half, otherwise in the second half. 233 | - It can be done recursively or iteratively. 234 | - Pseudocode: 235 | ``` 236 | procedure binary_search 237 | A ← sorted array 238 | n ← size of array 239 | x ← value to be searched 240 | 241 | set lowerBound = 1 242 | set upperBound = n 243 | 244 | while x not found 245 | if upperBound < lowerBound 246 | EXIT: x does not exists. 247 | 248 | set midPoint = lowerBound + (upperBound - lowerBound) / 2 249 | 250 | if A[midPoint] < x 251 | set lowerBound = midPoint + 1 252 | 253 | if A[midPoint] > x 254 | set upperBound = midPoint - 1 255 | 256 | if A[midPoint] = x 257 | EXIT: x found at location midPoint 258 | end while 259 | 260 | end procedure 261 | ``` 262 | - Binary search in C++ | Binary search in Python 263 | - Analysis: 264 | - Best-case `O(1)` 265 | - Average `O(log n)` 266 | - Worst-case `O(log n)` 267 | 268 | ## Sorting techniques 269 | - **Sorting** - a process of arranging a set of data in a certain order. 270 | - **Internal sorting** - deals with data in the memory of the computer. 271 | - **External sorting** - deals with data stored in data files when data is in large volume. 272 | - Types of sorts: 273 | - [Selection sort](https://www.programiz.com/dsa/selection-sort) - O(n2). Selects the smallest element from an unsorted list and places that element in front. [Python code](code/selection_sort.py). 274 | - [Bubble sort](https://www.programiz.com/dsa/bubble-sort) - best O(n) else O(n2). Compares adjacent elements, and swaps elements bringing large elements to the end. [Python code](code/bubble_sort.py). 275 | - **[Insertion sort](https://www.programiz.com/dsa/insertion-sort) - best O(n) else O(n2). Places unsorted element at its suitable place in each iteration. [Python code](code/insertion_sort.py). 276 | - **[Merge sort](https://www.programiz.com/dsa/merge-sort) - O(n\*logn). It is based on *Divide and Conquer Algorithm* divides in the middle, sorts, then combines. 277 | - [Quick sort](https://www.programiz.com/dsa/quick-sort) - **PIVOT**, worst O(n2) else O(n\*logn). Based on *Divide and Conquer Algorithm*, larger and smaller elements are placed after and before pivot element. 278 | - [Heap sort](https://www.programiz.com/dsa/heap-sort) - O(n\*logn). 279 | - Radix sort 280 | - Bucket sort 281 | - 282 | 283 | ### [Merge sort](https://www.programiz.com/dsa/merge-sort) 284 | - [Python code](code/merge_sort.py) 285 | The problem is divided into two sub-problems. Each problem is solved individually. Finally, sub-problems are combined to the final solution. 286 | - Divide: we split `A[p..r]` into two arrays `A[p..q]` and `A[q+1, r]` 287 | - Conquer: we sort both sub-arrays `A[p..q]` and `A[q+1, r]`, so this part is recursive. We use merge sort to sort both sub-arrays. 288 | - Combine: we combine the results by creating a sorted array `A[p..r]` from two sorted sub-arrays `A[p..q]` and `A[q+1, r]` 289 |
290 | - How do we merge (combine)? We need two pointers i, j to track the current position in sub-arrays. Basically, we are placing the mim value to the final array. 291 |
292 | 293 | ### [Quick sort](https://www.programiz.com/dsa/quick-sort) 294 | - [Python code](code/quick_sort.py) 295 | - Based on the divide and conquer approach. 296 | - Algorithm: 297 | - An array is divided into sub-arrays by selecting a **pivot element** (element selected from the array). 298 | - While dividing the array, the pivot element should be positioned in such a way that elements less than the pivot are kept on the left side and elements greater than pivot are on the right side of the pivot. 299 | - The left and right sub-arrays are also divided using the same approach. This process continues until each subarray contains a single element. 300 | - At this point, elements are already sorted. Finally, elements are combined to form a sorted array 301 | - Working with Quicksort algorithm: 302 | 1. Select the pivot element. We select the rightmost element of the array as the pivot element. 303 |
304 | 2. Rearrange the array. We rearrange smaller and larger elements to the right and left side of the pivot. 305 |
306 | 3. How do we rearrange the array? 307 | 1. We need PIVOT which is last element, "i" the first largest element from left side, and "j" which is the iterator (next element in array). 308 | 2. We compare "j" with pivot. If "j" is smaller than pivot we swap "j" with "i", and make "++i". 309 | 3. If "j" reaches the pivot, we just swap pivot with "i". 310 | 4. Now we have two sub-arrays, we repeat the same algo. 311 | 312 | ### [Heap sort](https://www.programiz.com/dsa/heap-sort) 313 | - [Python code](code/heap_sort.py) 314 | - Left child of element `i` is `2i + 1`, right child is `2i + 2`. Indexing starts from 0 315 | - Parent of element `i` can be found with `(i-1) / 2` 316 | - Heap data structure: 317 | - It is a complete binary tree (nodes are formed from left to right) 318 | - All nodes are greater than children (max-heap) 319 | - 320 | - To create a Max-Heap from a complete binary tree, we must use a `heapify` function. 321 | - 322 | - `n/2 - 1` is the first index of a non-leaf node. 323 | - Heapify function, which bring larger element in top. Used just for one sub-tree recursively. 324 | ```c 325 | void heapify(int arr[], int n, int i) { 326 | // Find largest among root, left child and right child 327 | int largest = i; 328 | int left = 2 * i + 1; 329 | int right = 2 * i + 2; 330 | 331 | if(left < n && arr[left] > arr[largest]) 332 | largest = left; 333 | 334 | if(right < n && arr[right] > arr[largest]) 335 | largest = right; 336 | 337 | // Swap and continue heapifying if root is not largest 338 | if (largest != i) { 339 | swap(&arr[i], &arr[largest]); 340 | heapify(arr, n, largest); 341 | } 342 | } 343 | ``` 344 | 345 | - Firstly, it is a kind of pre-condition for swapping, we must bring our tree to MAX-HEAP, so that the largest element is in top. It is needed so that we start sorting the array. 346 | ```c 347 | // Max-heap creation 348 | for(int i = n/2 - 1; i >= 0; i--) 349 | heapify(arr, n, i); 350 | ``` 351 | - After that we swap elements, and apply heapify again. 352 | ```c 353 | // Build heap (rearrange array) 354 | for (int i = n/2 - 1; i >= 0; i--) 355 | swap(arr[i], arr[0]); 356 | heapify(arr, n, i); 357 | ``` 358 | 359 | ## Linked List 360 | - Array limitations: 361 | - Fixed-size 362 | - Physically stored in consecutive memory locations 363 | - To insert or delete items, may need to shift data 364 | - Variations of linked list: linear linked list, circular linked list, double linked list 365 | - **head** pointer "defines" the linked list (it is not a node)
366 | - Advantages of **Linked Lists** 367 | - The items do NOT have to be stored in consecutive memory locations. 368 | - So, can insert and delete items without shifting data. 369 | - Can increase the size of the data structure easily. 370 | - Linked lists can grow dynamically (i.e. at run time) – the amount of memory space allocated can grow and shrink as needed. 371 | - Disadvantages of **Linked Lists** 372 | - A linked list will use more memory storage than arrays. It has more memory for an additional linked field or next pointer field. 373 | - Linked list elements cannot randomly be accessed. 374 | - Binary search cannot be applied in a linked list. 375 | - A linked list takes more time to traverse of elements. 376 | - **Node** 377 | - A linked list is an ordered sequence of items called **nodes** 378 | - A node is the basic unit of representation in a linked list 379 | - A node in a singly linked list consists of two fields: 380 | - A *data* portion 381 | - A *link (pointer)* to the *next* node in the structure 382 | - The first item (node) in the linked list is accessed via a front or head pointer 383 | - The linked list is defined by its head (this is its starting point) 384 | - We will use `ListNode` and `LinkedList` classes (https://youtu.be/Dfu7PeZ3v2Q) 385 | ```cpp 386 | class Node { 387 | public: 388 | int info; // data 389 | Node* next; // pointer to next node in the list 390 | /*Node(int val) {info = val; next=NULL;}*/ 391 | }; 392 | 393 | class List { 394 | public: 395 | // head: a pointer to the first node in the list. 396 | // Since the list is empty initially, head is set to NULL 397 | List(void) {head = NULL;} // constructor 398 | ~List(void); // destructor 399 | 400 | private: 401 | Node* head; 402 | }; 403 | // isEmpty, insertNode, findNode, deleteNode, displayList 404 | ``` 405 | - Boundary condition 406 | - Empty data structure 407 | - Single element in the data structure 408 | - Adding/removing beginning of the data structure 409 | - Adding/removing end of the data structure 410 | - Working in the middle 411 | 412 | ### Insertion at the beginning in Linked List 413 | - https://youtu.be/yMoHuOZzMpk 414 | - It is just a 2-step algorithm: 415 | - `New node` should be connected to the `first node`, which means the head. This can be achieved by assigning the address of the node to the head. 416 | - `New node` should be considered as a `head`. It can be achieved by declaring head equal to a new node. 417 | ```cpp 418 | void insertStart(int val) { 419 | Node *node = new Node; // create a new node (node=node) 420 | node->info=val; // put value 421 | 422 | if(head == NULL) { // check if the list is empty 423 | head = node; 424 | node->next = NULL 425 | } 426 | else { // if list is not empty 427 | node->next = head; 428 | head = node; 429 | } 430 | } 431 | ``` 432 | 433 | ### Insertion at the end in Linked List 434 | ```cpp 435 | void insertEnd(int val) { 436 | Node *node = new Node; // create a new node 437 | node->info = val; // put value 438 | node->next = NULL; // pointer of last node is NULL 439 | 440 | if(head == NULL) { // if empty 441 | node->next = NULL 442 | head = node; 443 | } 444 | else { 445 | Node *cur = new Node(); 446 | cur = head; 447 | while(cur->next != NULL) { 448 | cur = cur->next; 449 | } 450 | cur->next = node; 451 | } 452 | } 453 | ``` 454 | ### Insertion at a particular position 455 | - In this case, we don’t disturb the `head` and `tail` nodes. Rather, a new node is inserted between two consecutive nodes. 456 | - We call one node `current` and the other `previous`, and the new node is placed between them. 457 | - Two steps we need to insert between `previous` and `current`: 458 | - Pass the address of the new node in the next field of the previous node. 459 | - Pass the address of the current node in the next field of the new node. 460 | ```cpp 461 | void insertPosition(int pos, int val) { 462 | Node *pre; 463 | Node *cur; 464 | Node *node = new Node; 465 | 466 | node->data = val; 467 | cur = head; 468 | 469 | for(int i=1; inext; 472 | } 473 | pre->next = node; 474 | node->next = cur; 475 | } 476 | ``` 477 | ```cpp 478 | void insertSpecificValue(int sp_val, int data) { 479 | Node *pre; 480 | Node *cur; 481 | Node *node = new Node; 482 | 483 | node->info = data; 484 | cur = head; // "current" in the beginning points to head, and "previous" points to NULL 485 | 486 | while(cur->data != sp_val) { 487 | pre = cur; 488 | cur = cur->next; 489 | } 490 | node->next = cur; 491 | cur->next = node; 492 | } 493 | ``` 494 | 495 | ### Deleting the first node from a Linked List 496 | - Following steps, we need to remove the first node: 497 | - Check if the linked list exists or not `if(head == NULL)`. 498 | - Check if it is an element list. 499 | - However, if there are nodes in the linked list, then we use a pointer variable `PTR` that is set to point to the first node of the list. For this, we initialize `PTR` with Head that stores the address of the first node of the list. 500 | - Head is made to point to the next node in sequence and finally, the memory occupied by the node pointed by PTR is freed and returned to the free pool. 501 | ```cpp 502 | void deleteFirst() { 503 | if(head == NULL) { // if empty 504 | cout << "Underflow" << endl; 505 | } 506 | else if(head.next == NULL) { // if only one element 507 | Node *ptr; 508 | ptr = head; 509 | head = NULL; 510 | delete ptr; 511 | } 512 | else { // otherwise 513 | Node *ptr; 514 | ptr = head; 515 | head = head->next; 516 | delete ptr; 517 | } 518 | } 519 | ``` 520 | 521 | ### Deleting the last node from a Linked List 522 | - Following steps we need to remove the first node: 523 | - Check if the linked list exists or not `if(head == NULL)`. 524 | - Check if it is an element list. 525 | - Take a pointer variable `PTR` and initialize it with `head`. That is, `PTR` now points to the first node of the linked list. In the while loop, we take another pointer variable `PREPTR` such that it always points to one node before the PTR. Once we reach the last node and the second last node, we set the NEXT pointer of the second last node to NULL, so that it now becomes the (new) last node of the linked list. The memory of the previous last node is freed and returned back to the free pool. 526 | ``` 527 | STEP 1: IF START = NULL 528 | WRITE UNDERFLOW 529 | Go to STEP 8 530 | [END OF IF] 531 | STEP 2: SET PTR = START 532 | STEP 3: REPEAT Steps 4 and 5 while PTR->NEXT != NULL 533 | STEP 4: SET PREPTR = PTR 534 | STEP 5: SET PTR = PTR->NEXT 535 | [END OF LOOP] 536 | STEP 6: SET PREPTR->NEXT = NULL 537 | STEP 7: FREE PTR 538 | STEP 8: EXIT 539 | ``` 540 | 541 | ### Deleting the Specific Node in a Linked List 542 | ``` 543 | Step 1: IF START = NULL 544 | Write UNDERFLOW Go to Step 10 545 | [END OF IF] 546 | Step 2: SET PTR = START 547 | Step 3: SET PREPTR = PTR 548 | Step 4: Repeat Steps 5 and 6 while PREPTR-> DATA I = NUM 549 | Step 5: SET PREPTR = PTR 550 | Step 6: SET PTR = PTR -> NEXT 551 | [END OF LOOP) 552 | Step 7: SET TEMP = PTR 553 | Step 8: SET PREPTR -> NEXT - PTR-> NEXT 554 | Step 9: FREE TEMP 555 | Step 10: EXIT 556 | ``` 557 | 558 | ## Circular Linked List 559 | - https://youtu.be/7ELt4-z4YeI 560 | - In a circular linked list, the last node contains a pointer to the first node. 561 | - No node points to NULL! 562 | - Start at `head`, and iterate until you find `head` again: `t == head, t.next == head` 563 | - Complexity for all operations is `O(n)` 564 | - ```cpp 565 | class Node { 566 | int info; 567 | Node *next; 568 | }; 569 | 570 | class CircularLList { 571 | public: 572 | Node *last; 573 | 574 | CircularLList() { 575 | last = NULL; 576 | } 577 | }; 578 | ``` 579 | 580 | ### Insertion at Beginning in Circular Linked List 581 | ```cpp 582 | void addBegin(int val) { 583 | Node *temp = new Node(); 584 | temp->info=val; 585 | 586 | if (last == NULL) { // if empty 587 | last = temp; 588 | temp->next = last; // points next to itself // in simple LL it pointed to NULL 589 | } 590 | else { 591 | temp->next = last; 592 | last = temp; 593 | } 594 | 595 | ``` 596 | 597 | ### Insertion at the End in Circular Linked List 598 | ```cpp 599 | while cur->next != last) { 600 | cur = cur->next; 601 | } 602 | cur->next = New; 603 | New->next = last; 604 | ``` 605 | 606 | ### Insertion at Particular Position in Circular Linked List 607 | ```cpp 608 | void insertNode(int item,int pos) { 609 | Node *New = new Node(); 610 | Node *prev; 611 | Node *cur; 612 | New->data = item; 613 | 614 | if(last == NULL){ // insert into empty list 615 | last = New; 616 | last->next = last; 617 | } 618 | 619 | prev = last; 620 | cur = last->next; 621 | 622 | for (int i=1; inext; 625 | } 626 | 627 | New->next = cur; 628 | prev->next = New; 629 | } 630 | ``` 631 | 632 | ### Deletion of a Node in Circular Linked List 633 | - From a single-node circular linked list (node points to itself): 634 | ```cpp 635 | last = NULL; 636 | delete cur; 637 | ``` 638 | - Delete the head node: 639 | ```cpp 640 | while(prev->next != last) { 641 | prev = cur; 642 | cur = cur->next; 643 | } 644 | prev->next = cur->next; 645 | delete cur; 646 | ``` 647 | - Delete a middle node Cur: 648 | ```cpp 649 | for(i=1; i<=pos; i++) { 650 | prev = cur; 651 | cur = cur->next; 652 | } 653 | prev->next = cur->next; 654 | delete cur; 655 | ``` 656 | - Delete the end node: 657 | ```cpp 658 | while(cur->next != last) { 659 | prev = cur; 660 | cur = cur->next; 661 | } 662 | prev->next = cur->next; 663 | delete cur; 664 | ``` 665 | ## Doubly Linked List 666 | - https://youtu.be/v8xyoI11PsU 667 | - DLL contains a pointer to the next as well as the previous node in the sequence. Therefore, it consists of three parts: 668 | - data 669 | - a pointer to the next node 670 | - a pointer to the previous node 671 | - ```cpp 672 | class Node { 673 | int info; 674 | Node *next; 675 | Node *pre; 676 | } 677 | ``` 678 | 679 | ## Stacks 680 | - Last in, first out (LIFO) 681 | - Elements are added to and removed from the top of the stack (the most recently added items are at the top of the stack). 682 | - 683 | - Operations on Stack: 684 | - `push(i)` to insert the element `i` on the top of the stack. 685 | - `pop()` to remove the top element of the stack and to return the removed element as a function value. 686 | - `top()` to return the top element of stack(s) 687 | - `empty()` to check whether the stack is empty or not. It returns true if stack is empty and returns false otherwise. 688 | 689 | ### Array Representation of Stacks 690 | - In the computer’s memory, stacks can be represented as a linear array. 691 | - Every stack has a variable called TOP associated with it, which is used to store the address of the topmost element of the stack. 692 | - TOP is the position where the element will be added to or deleted from 693 | - There is another variable called MAX, which is used to store the maximum number of elements that the stack can hold. 694 | - Underflow and Overflow: 695 | - if `TOP = NULL` (underflow) it indicates that the stack is empty and 696 | - if `TOP = MAX–1` (overflow) then the stack is full. 697 | - Pseudocode for PUSH, POP, PEEK: 698 | ``` 699 | PUSH operation 700 | Step 1: IF TOP = MAX - 1 701 | PRINT "OVERFLOW" 702 | Goto Step 4 703 | [END OF IF] 704 | Step 2: SET TOP = TOP + 1 705 | Step 3: SET STACK[TOP] = VALUE 706 | Step 4: END 707 | 708 | POP operation 709 | Step 1: IF TOP = NULL 710 | PRINT "UNDERFLOW" 711 | Goto Step 4 712 | [END OF IF] 713 | Step 2: SET VALUE STACK(TOP) 714 | Step 3: SET TOP = TOP - 1 715 | Step 4: END 716 | 717 | PEEK operation 718 | Step 1: IF TOP = NULL 719 | PRINT "STACK IS EMPTY" 720 | Goto Step 3 721 | Step 2: RETURN STACK[TOP] 722 | Step 3: END 723 | ``` 724 | 725 | ### Linked Representation of Stack 726 | - Stack may be created using an array. This technique of creating a stack is easy, but the drawback is that the array must be declared to have some fixed size. 727 | - In a linked stack, every node has two parts—one that stores data and another that stores the address of the next node. The START pointer of the linked list is used as TOP. 728 | - **PUSH** is adding a node at beginning, **POP** deleting front node. 729 | 730 | ### Infix to Postfix 731 | - Algorithm used (Postfix): 732 | - Step 1: Add `)` to the end of the infix expression 733 | - Step 2: Push `(` onto the STACK 734 | - Step 3: Repeat until each character in the infix notation is scanned 735 | - IF a `(` is encountered, `push` it on the STACK. 736 | - IF an `operand` (whether a digit or a character) is encountered, `add` it postfix expression. 737 | - IF a `)` is encountered, then 738 | - a. Repeatedly `pop` from STACK and `add` it to the postfix expression until a `(` is encountered. 739 | - b. Discard the `(`. That is, remove the `(` from STACK and do not add it to the postfix expression 740 | - IF an operator `O` is encountered, then 741 | - a. Repeatedly `pop` from STACK and `add` each operator (popped from the STACK) to the postfix expression which has the **same precedence or a higher precedence than O** 742 | - b. `Push` the operator to the STACK 743 | [END OF IF] 744 | - Step 4: Repeatedly `pop` from the STACK and `add` it to the postfix expression until the STACK is empty 745 | - Step 5: EXIT 746 | - If `/` adds to `((-*` we will take only `*`, then it will be `((-/` 747 | ``` 748 | Example: (A * B) + (C / D) – (D + E) 749 | 750 | (A * B) + (C / D) – (D + E)) [put extra ")" at last] 751 | 752 | Char Stack Expression 753 | ( (( Push at beginning "(" 754 | A (( A 755 | * ((* A 756 | B ((* AB 757 | ) ( AB* 758 | + (+ AB* 759 | ( (+( AB* 760 | C (+( AB*C 761 | / (+(/ AB*C 762 | D (+(/ AB*CD 763 | ) (+ AB*CD/ 764 | - (- AB*CD/+ 765 | ( (-( AB*CD/+ 766 | D (-( AB*CD/+D 767 | + (-(+ AB*CD/+D 768 | E (-(+ AB*CD/+DE 769 | ) (- AB*CD/+DE+ 770 | ) AB*CD/+DE+- 771 | ``` 772 | 773 | ### Evaluation of Postfix expression 774 | - ``` 775 | [AB*CD/+DE+-] ==> 2 3 * 2 4 / + 4 3 + - 776 | 777 | Char Stack Operation 778 | 2 2 779 | 3 2, 3 780 | * 6 2*3 781 | 2 6, 2 782 | 4 6, 2, 4 783 | / 6, 0 2/4 784 | + 0 6+0 785 | 4 6, 4 786 | 3 6, 4, 3 787 | + 6, 7 4+3 788 | - -1 6-7 789 | ``` 790 | 791 | ### Infix to Prefix 792 | 793 | #### First method 794 | - Algorithm used (Prefix): 795 | - Step 1. `Push` `)` onto STACK, and `add` `(` to start of the A. 796 | - Step 2. Scan A from right to left and repeat step 3 to 6 for each element of A until the STACK is empty or contains only `)` 797 | - Step 3. If an **operand** is encountered add it to B 798 | - Step 4. If a **right parenthesis** is encountered push it onto STACK 799 | - Step 5. If an **operator** is encountered then: 800 | - a. Repeatedly pop from STACK and add to B each operator (on the top of STACK) which has **only higher precedence than the operator**. 801 | - b. Add operator to STACK 802 | - Step 6. If **left parenthesis** is encountered then 803 | - a. Repeatedly pop from the STACK and add to B (each operator on top of stack until a right parenthesis is encountered) 804 | - b. Remove the left parenthesis 805 | - Step 7. **Reverse** B to get prefix form 806 | 807 | - ``` 808 | Example: 14 / 7 * 3 - 4 + 9 / 2 809 | 810 | (14 / 7 * 3 - 4 + 9 / 2 [Put extra "(" to start] 811 | 812 | Char Stack Expression 813 | 2 ) Push at the beginning ")" 814 | / )/ 2 815 | 9 )/ 2 9 816 | + )+ 2 9 / 817 | 4 )+ 2 9 / 4 818 | - )+- 2 9 / 4 819 | 3 )+- 2 9 / 4 3 820 | * )+-* 2 9 / 4 3 821 | 7 )+-* 2 9 / 4 3 7 822 | / )+-*/ 2 9 / 4 3 7 823 | 14 )+-*/ 2 9 / 4 3 7 14 824 | ( 2 9 / 4 3 7 14 / * - + 825 | 826 | DON'T FORGET TO REVERSE: + - * / 14 7 3 4 / 9 2 827 | ``` 828 | 829 | #### Second method 830 | - Algorithm used (Prefix): 831 | - Step 1: Reverse the infix string. Note that while reversing the string you must interchange left and right parentheses. Eg. `(3+2)` will be `(2+3)` but not `)2+3(` 832 | - Step 2: Obtain the postfix expression of the infix expression obtained in Step 1. 833 | - Step 3: Reverse the postfix expression to get the prefix expression 834 | 835 | - ``` 836 | Example: 14 / 7 * 3 - 4 + 9 / 2 837 | 838 | Reversed: 2 / 9 + 4 - 3 * 7 / 14 839 | 840 | Char Stack Expression 841 | 2 ( Push at beginning "(" 842 | / (/ 2 843 | 9 (/ 2 9 844 | + (+ 2 9 / 845 | 4 (+ 2 9 / 4 846 | - (+- 2 9 / 4 847 | 3 (+- 2 9 / 4 3 848 | * (+-* 2 9 / 4 3 849 | 7 (+-* 2 9 / 4 3 7 850 | / (+-*/ 2 9 / 4 3 7 851 | 14 (+-*/ 2 9 / 4 3 7 14 852 | ) 2 9 / 4 3 7 14 / * - + 853 | 854 | DON'T FORGET TO REVERSE: + - * / 14 7 3 4 / 9 2 855 | 856 | NOTE: Operator with the same precedence must not be popped from stack 857 | ``` 858 | 859 | ### Evaluation of Prefix Expression 860 | - For postfix we evaluated `a+b` but in prefix we will do `b+a` 861 | 862 | - ``` 863 | Example: 14 / 7 * 3 - 4 + 9 / 2 ==> + - * / 14 7 3 4 / 9 2 864 | 865 | Char Stack Operation 866 | 2 2 867 | 9 2, 9 868 | / 4 9/2 [but in postfix we did 2/9] 869 | 4 4, 4 870 | 3 4, 4, 3 871 | 7 4, 4, 3, 7 872 | 14 4, 4, 3, 7, 14 873 | / 4, 4, 3, 2 14/2 874 | * 4, 4, 6 2*2 875 | - 4, 2 6-4 876 | + 6 2+4 877 | ``` 878 | 879 | ## Queue 880 | - First in, first out (FIFO) 881 | - The queue has a **front** and a **rear** 882 | - 883 | - Items can be removed only at the **front** 884 | - Items can be added only at the other end, the **rear** 885 | - Types of queues: 886 | - Linear queue 887 | - Circular queue 888 | - Double-ended queue (Deque) 889 | - Priority queue 890 | 891 | ### Linear Queue 892 | - A queue is a sequence of data elements 893 | - **Enqueue** (add an element to back) When an item is `inserted` into the queue, it always goes `at the end` (rear). 894 | - **Dequeue** (`remove` element from the front), when an item is taken from the queue, it always comes `from the front`. 895 | - Implemented using either an array or a linear linked list. 896 | - Array implementation: 897 | - **ENQUEUE** 898 | ``` 899 | Step 1: IF REAR = MAX-1 900 | Write "OVERFLOW" 901 | Goto step 4 902 | [END OF IF] 903 | Step 2: IF FRONT = -1 and REAR = -1 904 | SET FRONT = REAR = 0 905 | ELSE 906 | SET REAR = REAR + 1 907 | [END OF IF] 908 | Step 3: SET QUEUE [REAR] = NUM 909 | Step 4: EXIT 910 | ``` 911 | - **DEQUEUE** 912 | ``` 913 | Step 1: IF FRONT = -1 OR FRONT > REAR 914 | Write "UNDERFLOW" 915 | ELSE 916 | SET VAL = QUEUE[FRONT] 917 | SET FRONT = FRONT + 1 918 | [END OF IF] 919 | Step 2: EXIT 920 | ``` 921 | 922 | - Linked list implementation: 923 | - **ENQUEUE** the same as adding a node at the end 924 | ``` 925 | Step 1: Allocate memory for the new node and name it as PTR 926 | Step 2: SET PTR -> DATA = VAL 927 | Step 3: 928 | IF FRONT = NULL 929 | SET FRONT = REAR = PTR 930 | SET FRONT -> NEXT = REAR -> NEXT = NULL 931 | ELSE 932 | SET REAR -> NEXT = PTR 933 | SET REAR = PTR 934 | SET REAR -> NEXT = NULL 935 | [END OF IF] 936 | Step 4: END 937 | 938 | ``` 939 | - **DEQUEUE** the same as deleting a node from the beginning 940 | ``` 941 | Step 1: IF FRONT = NULL 942 | Write "Underflow" 943 | Go to Step 5 944 | [END OF IF] 945 | 946 | Step 2: SET PTR = FRONT 947 | Step 3: SET FRONT = FRONT -> NEXT 948 | Step 4: FREE PTR 949 | Step 5: END 950 | ``` 951 | 952 | ### Circular Queue 953 | - https://youtu.be/ihEmEcO2Hx8 954 | - **Drawbacks of linear queue** Once the queue is full, even though few elements from the front are deleted and some occupied space is relieved, it is not possible to add anymore new elements, as the rear has already reached the Queue’s rear most position. 955 | - In the circular queue, once the Queue is full the "First" index of the Queue becomes the "Rear" most index, if and only if the "Front" element has moved forward. Otherwise, it will be a "Queue overflow" state.
956 | - **ENQUEUE** algorithm: 957 | ``` 958 | Insert-Circular-Q(CQueue, Rear, Front, N, Item) 959 | 960 | 1. If Front = -1 and Rear = -1: 961 | then Set Front :=0 and go to step 4 962 | 963 | 2. If Front = 0 and Rear = N-1 or Front = Rear + 1: 964 | then Print: “Circular Queue Overflow” and Return 965 | 966 | 3. If Rear = N -1: 967 | then Set Rear := 0 and go to step 4 968 | 969 | 4. Set CQueue [Rear] := Item and Rear := Rear + 1 970 | 971 | 5. Return 972 | ``` 973 | - Here, `CQueue` is a circular queue. 974 | - `Rear` represents the location in which the data element is to be inserted. 975 | - `Front` represents the location from which the data element is to be removed. 976 | - `N` is the maximum size of CQueue 977 | - `Item` is the new item to be added. 978 | - Initailly `Rear = -1` and `Front = -1`. 979 | 980 | - **DEQUEUE** algorithm: 981 | ``` 982 | Delete-Circular-Q(CQueue, Front, Rear, Item) 983 | 984 | 1. If Front = -1: 985 | then Print: “Circular Queue Underflow” and Return 986 | 987 | 2. Set Item := CQueue [Front] 988 | 989 | 3. If Front = N – 1: 990 | then Set Front = 0 and Return 991 | 992 | 4. If Front = Rear: 993 | then Set Front = Rear = -1 and Return 994 | 995 | 5. Set Front := Front + 1 996 | 997 | 6. Return 998 | ``` 999 | - `CQueue` is the place where data are stored. 1000 | - `Rear` represents the location in which the data element is to be inserted. 1001 | - `Front` represents the location from which the data element is to be removed. 1002 | - `Front` element is assigned to `Item`. 1003 | - Initially, `Front = -1`. 1004 | 1005 | - While inserting `REAR++`, `FRONT` 1006 | - While deleting `REAR`, `FRONT++` 1007 | - If `FRONT = REAR + 1` then the queue is full! Overflow will occur. 1008 | 1009 | ### Double Ended Queue 1010 | - It is exactly like a queue except that elements can be added to or removed from the **head** or the **tail**. 1011 | - No element can be added and deleted from the middle. 1012 | - Implemented using either a circular array or a circular doubly linked list. 1013 | - In a deque, two pointers are maintained, `LEFT` and `RIGHT`, which point to either end of the deque. 1014 | - The elements in a deque extend from the `LEFT` end to the `RIGHT` end and since it is circular, `Deque[N–1]` is followed by `Deque[0]`. 1015 | - Two types: 1016 | - **Input restricted deque** In this, insertions can be done only at one of the ends, while deletions can be done from both ends. 1017 | - **Output restricted deque** In this deletions can be done only at one of the ends, while insertions can be done on both ends. 1018 | - 1019 | 1020 | ### Priority Queue 1021 | - A priority queue is a data structure in which each element is assigned a priority. 1022 | - The priority of the element will be used to determine the order in which the elements will be processed. 1023 | - An element with *higher priority* is processed before an element with a *lower priority*. 1024 | - Two elements with the same priority are processed on a first-come-first-served (FCFS) basis. 1025 | 1026 | ## Tree 1027 | - **Root**: node without a parent (A) 1028 | - **Siblings**: nodes share the same parent 1029 | - **Internal node**: node with at least one child (A, B, C, F) 1030 | - **External node** (leaf): node without children (E, I, J, K, G, H, D) 1031 | - **Ancestors** of a node: parent, grandparent, grand-grandparent, etc. 1032 | - **Descendant** of a node: child, grandchild, grand-grandchild, etc. 1033 | - **Depth** of a node: number of ancestors 1034 | - **Height** of a tree: maximum depth of any node (3) 1035 | - **Degree of a node**: the number of its children. The leaf of the tree does not have any child so its degree is zero 1036 | - **Degree of a tree**: the maximum degree of a node in the tree. 1037 | - **Subtree**: tree consisting of a node and its descendants 1038 | - **Empty (Null)-tree**: a tree without any node 1039 | - **Root-tree**: a tree with only one node 1040 | - 1041 | 1042 | ## Binary Tree 1043 | - https://youtu.be/0k1gZ7m8WUk 1044 | - It is a data structure that is defined as a collection of elements called nodes. 1045 | - In a binary tree, 1046 | - The topmost element is called the root node. 1047 | - Each node has 0, 1, or at the most 2 children. 1048 | - A node that has zero children is called a leaf node or a terminal node. 1049 | - Every node contains a data element, a left pointer that points to the left child, and a right pointer that points to the right child 1050 | - **Complete binary tree** - every level except possibly the last is completely filled. All nodes must appear as far left as possible. 1051 | - 1052 | 1053 | - Linked list implementation of binary tree: 1054 | - Every node will have three parts: the **data element**, **a pointer to the left node**, and **a pointer to the right node**. 1055 | 1056 | ```cpp 1057 | class Node { 1058 | public: 1059 | Node *left; 1060 | int data; 1061 | Node *right; 1062 | }; 1063 | ``` 1064 | - Every binary tree has a pointer `ROOT`, which points to the root element (topmost element) of the tree. If `ROOT = NULL`, then the tree is **empty**. 1065 | 1066 | - Array implementation of binary tree: 1067 | - If `TREE[1] = ROOT` then 1068 | - the left child of a node `K` ==> `2*K` 1069 | - the right child of a node `K` ==> `2*K+1` 1070 | - parent of any node `K` ==> `floor(K/2)` 1071 | - max size of tree is 2h+1-1, where h = height 1072 | - P.S. floor(3/2) = 2 1073 | 1074 | - If `TREE[0] = ROOT` then 1075 | - the left child of a node `K` ==> `2*K+1` 1076 | - the right child of a node `K` ==> `2*K+2` 1077 | - parent of any node `K` ==> `floor(K/2)-1` 1078 | 1079 | - Algebraic expressions with binary tree 1080 | - `((a + b) – (c * d)) % ((f ^ g) / (h – i))` 1081 | 1082 | - 1083 | 1084 | ### Traversing a Binary Tree 1085 | - https://youtu.be/H0exHo7KAhQ 1086 | - PREORDER (NLR), POSTORDER (LRN) & INORDER TRAVERSAL (LNR) 1087 | - Preorder traversal can be used to extract a prefix notation 1088 | - 1089 | - **PREORDER TRAVERSAL** (NLR) 1090 | 1. Visiting the root node, 1091 | 2. Traversing the left sub-tree, and finally 1092 | 3. Traversing the right sub-tree. 1093 | 1094 | ``` 1095 | Example outputs with preorder: 1096 | (a) A, B, D, G, H, L, E, C, F, I, J, K 1097 | (b) A, B, D, C, E, F, G, H, I 1098 | ``` 1099 | - **POSTORDER TRAVERSAL** (LRN) 1100 | 1. Traversing the left sub-tree, 1101 | 2. Visiting the root node, and finally 1102 | 3. Traversing the right sub-tree. 1103 | 1104 | ``` 1105 | Example outputs with postorder: 1106 | (a) G, L, H, D, E, B, I, K, J, F, C, A 1107 | (b) D, B, H, I, G, F, E, C, A 1108 | ``` 1109 | - **INORDER TRAVERSAL** (LNR) 1110 | 1. Traversing the left sub-tree, 1111 | 2. Traversing the right sub-tree, and finally 1112 | 3. Visiting the root node. 1113 | 1114 | ``` 1115 | Example outputs with inorder: 1116 | (a) G, D, H, L, B, E, A, C, I, F, K, J 1117 | (b) B, D, A, E, H, G, I, F, C 1118 | ``` 1119 | 1120 | ## Binary Search Tree 1121 | - **A binary search tree**, also known as an ordered binary tree, is a variant of binary trees in which the nodes are arranged in an order. 1122 | - Left sub-tree nodes must have a value less than that of the root node. 1123 | - Right sub-tree must have a value either equal to or greater than the root node. 1124 | - `O(n)` worst case for searching in BST 1125 | 1126 | ### Search & Insert Operation in Binary Search Tree 1127 | - 1128 | - 1129 | - Insert `39,27,45,18,29,40,9,21,10,19,54,59,65,60` in binary search tree 1130 |
1131 | 1132 | ### Deletion Operation in Binary Search Tree 1133 | - Deleting a `Node` that has no children, `delete 78`
1134 | - Deleting a `Node` with One Child, `delete 54`
1135 | - Deleting a `Node` with Two Children, `delete 56`
1136 | - Main algorithm:
1137 | 1138 | ## Graphs 1139 | - **Vertices** (nodes), **edges** (lines between vertices), undirected graph, directed graph 1140 | - Adjacent nodes and neighbors: 1141 | ``` 1142 | O----O adjacent nodes 1143 | ``` 1144 | - **Degree of a node** - Total number of edges containing the node. If deg(u)=0 then **isolated node**. 1145 | - **Size of a graph** - The size of a graph is the total number of edges in it. 1146 | 1147 | - **Regular graph** - It is a graph where each vertex has the same number of neighbors. That is, every node has the same degree.
1148 | - **Connected graph** - A graph is said to be connected if for any two vertices (u, v) in V there is a path from u to v. That is to say that there are `no isolated nodes` in a connected graph.
1149 | - **Complete graph** - Fully connected. That is, there is a `path from one node to every other node` in the graph. A complete graph has `n(n–1)/2` edges, where n is the number of nodes in G.
1150 | - **Weighted graph** - In a weighted graph, the edges of the graph are assigned some weight or length.
1151 | - **Multi-graph** - A graph with multiple edges and/or loops is called a multi-graph.
1152 | 1153 | - **Directed Graphs** - *digraph*, a graph in which every edge has a direction assigned to it.
1154 | - Terminology of a Directed graph: 1155 | - *Out-degree of a node* - The out-degree of a node u, written as outdeg(u), is the number of edges that **originate** at u. 1156 | - *In-degree of a node* - The in-degree of a node u, written as indeg(u), is the number of edges that **terminate** at u. 1157 | - *Degree of a node* - The degree of a node, written as deg(u), is equal to the sum of the in-degree and out-degree of that node. 1158 | Therefore, `deg(u) = indeg(u) + outdeg(u)`. 1159 | - *Isolated vertex* - A vertex with degree zero. Such a vertex is not an end-point of any edge. 1160 | - *Pendant vertex* - (also known as leaf vertex) A vertex with degree one. 1161 | 1162 | - **REPRESENTATION OF GRAPHS**. Sequential (adjacency matrix) & linked rep-s. 1163 | - 1164 | - 1165 | - 1166 | 1167 | ### Breadth First Search Traversal 1168 | - There are two standard methods of graph traversal: 1169 | 1. Breadth-first search (uses queue) 1170 | 2. Depth-first search (uses stack) 1171 | - https://youtu.be/oDqjPvD54Ss 1172 | - Breadth-first search. Complexity = `O(vertices + edges)`, finding the shortest path on unweighted graphs. 1173 | - BFS starts at some arbitrary node of a graph and explores the neighbor nodes first, before moving to the next level neighbors. 1174 | - 1175 | 1176 | ### Depth First Search 1177 | - https://youtu.be/7fujbpJ0LB4 1178 | - Complexity = `O(vertices + edges)` 1179 | - Make sure you don't re-visit visited nodes! Continue on the previous node! 1180 | - Backtrack when a dead end is reached! Means don't take the node that has no other neighbors. 1181 | - 1182 | - Choose any arbitrary node and PUSH (STATUS 2) it into the stack. Then only we will POP. When you POP (STATUS 3) and PUSH neighbors. 1183 | 1184 | ## Threaded Binary Tree 1185 | - According to this idea we are going to replace all the null pointers by the appropriate pointer values called threads. 1186 | - The maximum number of nodes with height `h` of a binary tree is 2h+1-1 1187 | - `n0` is the number of leaf nodes and `n2` the number of nodes of degree 2, then `n0=n2+1` 1188 | 1189 | ### Inorder Traversal in TBT 1190 | - `A / B * C * D + E` 1191 |
1192 | - `n`: number of nodes 1193 | - number of non-null links: `n-1` 1194 | - total links: `2n` 1195 | - null links: 2n-(n-1)=`n+1` 1196 | - Replace these null pointers with some useful “threads”. 1197 | - A one-way threading and a two-way threading exist. 1198 | 1199 | ### Threaded Binary Tree One-Way 1200 | - In the one-way threading of T, 1201 | a thread will appear in the **right field** of a node and will point to the next node in the in-order traversal of T. 1202 | - 1203 | 1204 | ### Threaded Binary Tree Two-Way 1205 | - If `ptr->left_child` is `null`, replace it with a pointer to the node that would be *visited before ptr* in an inorder traversal (**inorder predecessor**) 1206 | - If `ptr->right_child` is `null`, replace it with a pointer to the node that would be *visited after ptr* in an inorder traversal (**inorder successor**) 1207 | - 1208 | - ```cpp 1209 | class Node { 1210 | int data; 1211 | Node *left_child, *right_child; 1212 | boolean leftThread, rightThread; 1213 | } 1214 | ``` 1215 | - 1216 | 1217 | ### Inserting Node in TBT 1218 | - Inserting in the right side
1219 | - Inserting in the left side
1220 | 1221 | ## AVL Trees 1222 | - https://youtu.be/1QSYxIKXXP4 1223 | - Adelson-Velsky-Landis - one of many types of Balanced Binary Search Tree. `O(log(n))` 1224 | - **Balanced Factor (BF)**: `BF(node) = HEIGHT(node.right) - HEIGH(node.left)` 1225 | - Where `HEIGHT(x)` is the hight of node `x`. Which is the **number of edges** between `x` and the **furthest leaf**. 1226 | - -1, 0, +1 balanced factor values. 1227 | 1228 | ### Insertion in AVL Tree 1229 | - 1230 | - 1231 | - 1232 | - 1233 | - 1234 | - 1235 | - 1236 | - **Examples**: 1237 | - 1238 | - 1239 | - 1240 | 1241 | ### Deletion in AVL Tree 1242 | - We need rebalancing if needed after deletion: **L rotation** & **R rotation** 1243 | - R rotations 1244 | - R0 -> LL Case 1245 | - R1 -> LL case 1246 | - R-1 -> LR case 1247 | - L rotations 1248 | - L0 -> RR Case 1249 | - L1 -> RL Case 1250 | - L-1 -> RR Case 1251 | - Example R0:
1252 | - Example R1:
1253 | - Example R-1:
1254 | 1255 | ## Huffman Encoding 1256 | - Fixed-Length encoding 1257 | - Variable-Length encoding 1258 | - **Prefix rule** - used to prevent ambiguities during decoding which states that no binary code should be a prefix of another code. 1259 | - ``` 1260 | Bad Good 1261 | a 0 a 0 1262 | b 011 b 11 1263 | c 111 c 101 1264 | d 11 d 100 1265 | ``` 1266 | - **Algorithm for creating the Huffman Tree**: 1267 | - Step 1 - Create a leaf node for each character and build a min heap using all the nodes (The frequency value is used to compare two nodes in the min heap). 1268 | - Step 2 - Repeat Steps 3 to 5 while the heap has more than one node. 1269 | - Step 3 - Extract two nodes, say x and y, with minimum frequency from the heap. 1270 | - Step 4 - Create a new internal node z with x as its left child and y as its right child. Also `frequency(z)= frequency(x)+frequency(y)`. 1271 | - Step 5 - Add z to min heap. 1272 | - Step 6 - The last node in a heap is the root of the Huffman tree. 1273 | 1274 | - 1275 | 1276 | ## M-way trees 1277 | - http://faculty.cs.niu.edu/~freedman/340/340notes/340multi.htm 1278 | - The binary search tree is the binary tree. 1279 | - Each node has `m` children and `m-1` key fields. The keys in each node are in ascending order. 1280 | - A binary search tree has *one value* in each node and *two subtrees*. This notion easily generalizes to an **M-way search tree**, which has `(M-1)` values per node and `M` subtrees. 1281 | - M is called the **degree** of the tree. A binary search tree, therefore, has degree 2. 1282 | - M is thus a *fixed upper limit* on how much data can be stored in a node. 1283 | 1284 | ## B-Trees 1285 | - http://faculty.cs.niu.edu/~freedman/340/340notes/340multi.htm 1286 | - Every node in a B-Tree contains at most m children. (other nodes beside root & leaf must have at least m/2 children) 1287 | - All leaf nodes must be at the same level. 1288 | - **Inserting** 1289 | - Find the appropriate leaf node 1290 | - If the leaf node contains less than m-1 keys then insert the element in the increasing order. 1291 | - Else if the leaf contains m-1: 1292 | - Insert the new element in the increasing order of elements. 1293 | - Split the node into the two nodes at the median. 1294 | - Push the median element up to its parent node. 1295 | - If the parent node also contains an m-1 number of keys, then split it too by following the same steps. 1296 | -------------------------------------------------------------------------------- /code/01_linear_search.cpp: -------------------------------------------------------------------------------- 1 | // C++ code to linearly search x in arr[]. If x 2 | // is present then return its location, otherwise 3 | // return -1 4 | 5 | #include 6 | using namespace std; 7 | 8 | int search(int arr[], int n, int x) 9 | { 10 | int i; 11 | for (i = 0; i < n; i++) 12 | if (arr[i] == x) 13 | return i; 14 | return -1; 15 | } 16 | 17 | // Driver code 18 | int main(void) 19 | { 20 | int arr[] = { 2, 3, 4, 10, 40 }; 21 | int x = 10; 22 | int n = sizeof(arr) / sizeof(arr[0]); 23 | 24 | // Function call 25 | int result = search(arr, n, x); 26 | (result == -1) 27 | ? cout << "Element is not present in array" 28 | : cout << "Element is present at index " << result; 29 | return 0; 30 | } -------------------------------------------------------------------------------- /code/01_linear_search.py: -------------------------------------------------------------------------------- 1 | # Python3 code to linearly search x in arr[]. 2 | # If x is present then return its location, 3 | # otherwise return -1 4 | 5 | def search(arr, n, x): 6 | for i in range(0, n): 7 | if arr[i] == x: 8 | return i 9 | return -1 10 | 11 | 12 | if __name__ == '__main__': 13 | array = [2, 3, 4, 10, 40] 14 | x = 10 15 | n = len(array) 16 | 17 | result = search(array, n, x) 18 | if result == -1: 19 | print("Element is not present in array") 20 | else: 21 | print("Element is present at index", result) 22 | -------------------------------------------------------------------------------- /code/02_binary_search.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to implement recursive Binary Search 2 | #include 3 | using namespace std; 4 | 5 | // A recursive binary search function. It returns 6 | // location of x in given array arr[l..r] is present, 7 | // otherwise -1 8 | int binarySearch(int arr[], int l, int r, int x) 9 | { 10 | if (r >= l) { 11 | int mid = l + (r - l) / 2; 12 | 13 | // If the element is present at the middle 14 | // itself 15 | if (arr[mid] == x) 16 | return mid; 17 | 18 | // If element is smaller than mid, then 19 | // it can only be present in left subarray 20 | if (arr[mid] > x) 21 | return binarySearch(arr, l, mid - 1, x); 22 | 23 | // Else the element can only be present 24 | // in right subarray 25 | return binarySearch(arr, mid + 1, r, x); 26 | } 27 | 28 | // We reach here when element is not 29 | // present in array 30 | return -1; 31 | } 32 | 33 | int main(void) 34 | { 35 | int arr[] = { 2, 3, 4, 10, 40 }; 36 | int x = 10; 37 | int n = sizeof(arr) / sizeof(arr[0]); 38 | int result = binarySearch(arr, 0, n - 1, x); 39 | (result == -1) ? cout << "Element is not present in array" 40 | : cout << "Element is present at index " << result; 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /code/02_binary_search.py: -------------------------------------------------------------------------------- 1 | def binary_search(self, nums, target: int) -> int: 2 | left, right = 0, len(nums) - 1 3 | 4 | while left <= right: 5 | mid = (right + left) // 2 6 | 7 | if nums[mid] == target: 8 | return mid 9 | elif nums[mid] < target: 10 | left = mid + 1 11 | elif nums[mid] > target: 12 | right = mid - 1 13 | 14 | return -1 15 | 16 | 17 | # Returns index of x in arr if present, else -1 18 | def binary_search_recursive(arr, l, r, x): 19 | # Check base case 20 | if r >= l: 21 | mid = l + (r - l) // 2 22 | if arr[mid] == x: 23 | return mid 24 | 25 | # If element is smaller than mid, then it 26 | # can only be present in left subarray 27 | elif arr[mid] > x: 28 | return binary_search_recursive(arr, l, mid - 1, x) 29 | 30 | # Else the element can only be present 31 | # in right subarray 32 | else: 33 | return binary_search_recursive(arr, mid + 1, r, x) 34 | 35 | else: 36 | # Element is not present in the array 37 | return -1 38 | 39 | 40 | if __name__ == "__main__": 41 | arr = [2, 3, 4, 10, 40] 42 | x = 10 43 | result = binary_search_recursive(arr, 0, len(arr) - 1, x) 44 | if result != -1: 45 | print("Element is present at index % d" % result) 46 | else: 47 | print("Element is not present in array") 48 | -------------------------------------------------------------------------------- /code/PrefixtoPostFix.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | public class PrefixtoPostFix { 3 | 4 | boolean isOperator(char x){ 5 | switch (x){ 6 | case '-': 7 | case '+': 8 | case '/': 9 | case '*': 10 | case '^': 11 | return true; 12 | } 13 | return false; 14 | } 15 | 16 | public String convert(String expression){ 17 | 18 | Stack stack = new Stack(); 19 | for (int i = expression.length()-1; i >=0 ; i--) { 20 | 21 | char c = expression.charAt(i); 22 | 23 | if(isOperator(c)){ 24 | String s1 = stack.pop(); 25 | String s2 = stack.pop(); 26 | String temp = s1 + s2 + c; 27 | stack.push(temp); 28 | }else{ 29 | stack.push(c+""); 30 | } 31 | } 32 | 33 | String result = stack.pop(); 34 | return result; 35 | } 36 | 37 | public static void main(String[] args) { 38 | String prefix = "*/93+*24-76"; 39 | System.out.println("Prefix Expression: " + prefix); 40 | System.out.println("Postfix Expression: " + new PrefixtoPostFix().convert(prefix)); 41 | } 42 | } -------------------------------------------------------------------------------- /code/bubble_sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | Optimized Bubble sort algorithm implementation. 3 | Time Complexity: O(n^2) 4 | Best O(n) 5 | Worst O(n^2) 6 | Average O(n^2) 7 | Space Complexity: O(1) 8 | """ 9 | 10 | 11 | def bubble_sort(array): 12 | for i in range(len(array)): 13 | swapped = False 14 | for j in range(0, len(array) - i - 1): 15 | # change > to < to sort in descending order 16 | if array[j] > array[j + 1]: 17 | array[j], array[j + 1] = array[j + 1], array[j] 18 | swapped = True 19 | 20 | # no swapping means the array is already sorted 21 | # so no need for further comparison 22 | if not swapped: 23 | break 24 | 25 | return array 26 | 27 | 28 | if __name__ == "__main__": 29 | data = [-2, 45, 0, 11, -9, 32, 43, 0, 92] 30 | bubble_sort(data) 31 | print(data) 32 | -------------------------------------------------------------------------------- /code/circular_queue.py: -------------------------------------------------------------------------------- 1 | # This is the CircularQueue class 2 | class CircularQueue: 3 | 4 | # constructor for the class 5 | # taking input for the size of the Circular queue 6 | # from user 7 | def __init__(self, maxSize): 8 | self.queue = list() 9 | # user input value for maxSize 10 | self.maxSize = maxSize 11 | self.head = 0 12 | self.tail = 0 13 | 14 | # add element to the queue 15 | def enqueue(self, data): 16 | # if queue is full 17 | if self.size() == (self.maxSize - 1): 18 | return ("Queue is full!") 19 | else: 20 | # add element to the queue 21 | self.queue.append(data) 22 | # increment the tail pointer 23 | self.tail = (self.tail + 1) % self.maxSize 24 | return True 25 | 26 | # remove element from the queue 27 | def dequeue(self): 28 | # if queue is empty 29 | if self.size() == 0: 30 | return ("Queue is empty!") 31 | else: 32 | # fetch data 33 | data = self.queue[self.head] 34 | # increment head 35 | self.head = (self.head + 1) % self.maxSize 36 | return data 37 | 38 | # find the size of the queue 39 | def size(self): 40 | if self.tail >= self.head: 41 | qSize = self.tail - self.head 42 | else: 43 | qSize = self.maxSize - (self.head - self.tail) 44 | # return the size of the queue 45 | return qSize 46 | 47 | 48 | # input 7 for the size or anything else 49 | size = input("Enter the size of the Circular Queue: ") 50 | q = CircularQueue(int(size)) 51 | 52 | # change the enqueue and dequeue statements as you want 53 | print(q.dequeue(10)) 54 | print(q.head) 55 | print(q.tail) 56 | print() 57 | print() 58 | -------------------------------------------------------------------------------- /code/heap_sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | Heap sort algorithm implementation. 3 | Time complexity: best, worst, average = O(n log n) 4 | Space complexity: O(1) 5 | """ 6 | 7 | 8 | def heapify(arr, n, i): 9 | largest = i 10 | l = 2*i + 1 11 | r = 2*i + 2 12 | 13 | if l < n and arr[l] > arr[largest]: 14 | largest = l 15 | 16 | if r < n and arr[r] > arr[largest]: 17 | largest = r 18 | 19 | if largest != i: 20 | arr[i], arr[largest] = arr[largest], arr[i] 21 | 22 | # Recursively heapify the affected sub-tree 23 | heapify(arr, n, largest) 24 | 25 | 26 | def heap_sort(arr): 27 | n = len(arr) 28 | 29 | # Max heap 30 | for i in range(n//2 - 1, -1, -1): 31 | heapify(arr, n, i) 32 | 33 | # One by one extract elements 34 | for i in range(n - 1, 0, -1): 35 | # Swap 36 | arr[i], arr[0] = arr[0], arr[i] 37 | 38 | # heapify root element 39 | heapify(arr, i, 0) 40 | 41 | 42 | if __name__ == "__main__": 43 | unsorted_array = [12, 11, 13, 5, 6, 7] 44 | heap_sort(unsorted_array) 45 | print(unsorted_array) 46 | -------------------------------------------------------------------------------- /code/insertion_sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | Insertion sort algorithm implementation. 3 | Time complexity: 4 | Best O(n) 5 | Worst O(n^2) 6 | Average O(n^2) 7 | Space complexity: O(1) 8 | """ 9 | 10 | 11 | def insertion_sort(array): 12 | for i in range(1, len(array)): 13 | key = array[i] 14 | j = i - 1 15 | while j >= 0 and key < array[j]: 16 | array[j + 1] = array[j] 17 | j -= 1 18 | array[j + 1] = key 19 | return array 20 | 21 | 22 | if __name__ == '__main__': 23 | unsorted_array = [5, 2, 4, 6, 1, 3] 24 | sorted_array = insertion_sort(unsorted_array) 25 | print(sorted_array) 26 | -------------------------------------------------------------------------------- /code/merge_sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | Merge sort algorithm implementation. 3 | Time complexity: best, worst, average = O(n log n) 4 | Space complexity: O(n) 5 | 6 | How it works: 7 | 1. Divide the array in half 8 | 2. Sort each half 9 | 3. Merge the two halves 10 | """ 11 | 12 | 13 | def merge_sort(array): 14 | if len(array) <= 1: 15 | return None 16 | 17 | # r is the point where the array is divided into two sub-arrays 18 | r = len(array) // 2 19 | L = array[:r] 20 | M = array[r:] 21 | 22 | # Sort the two halves 23 | merge_sort(L) 24 | merge_sort(M) 25 | 26 | i = j = k = 0 27 | 28 | # Until we reach either end of either L or M, pick smaller among 29 | # elements L and M and place them in the correct position at A[p..r] 30 | while i < len(L) and j < len(M): 31 | if L[i] < M[j]: 32 | array[k] = L[i] 33 | i += 1 34 | else: 35 | array[k] = M[j] 36 | j += 1 37 | k += 1 38 | 39 | # When we run out of elements in either L or M, 40 | # pick up the remaining elements and put in A[p..r] 41 | while i < len(L): 42 | array[k] = L[i] 43 | i += 1 44 | k += 1 45 | 46 | while j < len(M): 47 | array[k] = M[j] 48 | j += 1 49 | k += 1 50 | 51 | 52 | if __name__ == '__main__': 53 | unsorted_array = [6, 5, 12, 10, 9, 1] 54 | merge_sort(unsorted_array) 55 | print(unsorted_array) 56 | -------------------------------------------------------------------------------- /code/quick_sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | Quick sort algorithm implementation. 3 | Time complexity: 4 | Best case: O(n log n) 5 | Average case: O(n log n) 6 | Worst case: O(n^2) 7 | Space complexity: O(log n), because recursive stack can max uses half of array 8 | """ 9 | 10 | 11 | # function to find the partition position 12 | def partition(array, low, high): 13 | # choose the rightmost element as pivot 14 | pivot = array[high] 15 | 16 | # pointer for greater element 17 | i = low - 1 18 | 19 | # traverse through all elements 20 | # compare each element with pivot 21 | for j in range(low, high): 22 | if array[j] <= pivot: 23 | # if element smaller than pivot is found 24 | # swap it with the greater element pointed by i 25 | i = i + 1 26 | 27 | # swapping element at i with element at j 28 | array[i], array[j] = array[j], array[i] 29 | 30 | # swap the pivot element with the greater element specified by i 31 | array[i + 1], array[high] = array[high], array[i + 1] 32 | 33 | # return the position from where partition is done 34 | return i + 1 35 | 36 | 37 | # function to perform quicksort 38 | def quick_sort(array, low, high): 39 | if low < high: 40 | # find pivot element such that 41 | # element smaller than pivot are on the left 42 | # element greater than pivot are on the right 43 | pi = partition(array, low, high) 44 | 45 | # recursive call on the left of pivot 46 | quick_sort(array, low, pi - 1) 47 | 48 | # recursive call on the right of pivot 49 | quick_sort(array, pi + 1, high) 50 | 51 | 52 | if __name__ == '__main__': 53 | unsorted_array = [-5, 10, 7, 8, 9, 1, 5, -2] 54 | quick_sort(unsorted_array, 0, len(unsorted_array) - 1) 55 | print(unsorted_array) 56 | -------------------------------------------------------------------------------- /code/selection_sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | Selection sort algorithm implementation. 3 | Time Complexity: 4 | Best O(n^2) 5 | Worst O(n^2) 6 | Average O(n^2) 7 | Space Complexity: O(1) 8 | """ 9 | 10 | 11 | def selection_sort(array): 12 | for i in range(len(array)): 13 | min_index = i 14 | for j in range(i + 1, len(array)): 15 | if array[j] < array[min_index]: 16 | min_index = j 17 | array[i], array[min_index] = array[min_index], array[i] 18 | return array 19 | 20 | 21 | if __name__ == '__main__': 22 | unsorted_array = [5, 3, 6, 2, 10, -23, 0] 23 | selected_array = selection_sort(unsorted_array) 24 | print(selected_array) 25 | -------------------------------------------------------------------------------- /final-project/README.md: -------------------------------------------------------------------------------- 1 | # DS Student Practice Project 2 | **@Alimov-8** & **@Rustam-Z** 3 | 4 | Covid-Free Transport Place Allocation ✈️🚉 5 | Using Linked List and Stacks (C++, binary files and other features) 6 | 7 | ### Description: 8 | Because of COVID-19, social distancing plays a vital role in real life. 9 | Therefore we want to help transportation systems to overhead this problem. 10 | We will allocate all booked places of passengers so that each of them will be on the safe distance seats from each other. 11 | -------------------------------------------------------------------------------- /final-project/Source.cpp: -------------------------------------------------------------------------------- 1 | #include // need to use getch() 2 | #include // file handling 3 | #include // input/output handling 4 | #define Line "------------------------------------------ " // macros 5 | 6 | using namespace std; 7 | 8 | class Carriage { 9 | protected: 10 | // identifires 11 | string carriageType, carriageID; 12 | int carriagePlaces; 13 | public: 14 | // setting data (name and tell) 15 | void setData(string carriageType, string carriageID, int carriagePlaces) { 16 | this->carriageType = carriageType; 17 | this->carriageID = carriageID; 18 | this->carriagePlaces = carriagePlaces; 19 | } 20 | 21 | // get name and tell 22 | string getCarriageType() { return carriageType; } 23 | string getCarriageID() { return carriageID; } 24 | int getCarriagePlace() { return carriagePlaces; } 25 | 26 | // displaying name and tell 27 | void Display() { 28 | cout << Line << endl; 29 | cout << " Carriage: " << carriageID << " " << carriageType << " " << carriagePlaces << endl; 30 | } 31 | }; 32 | 33 | class Passenger { 34 | protected: 35 | // identifires 36 | string firstName, lastName, ticketType; 37 | public: 38 | // setting data 39 | void setData(string firstName, string lastName, string ticketType) { 40 | this->firstName = firstName; 41 | this->lastName = lastName; 42 | this->ticketType = ticketType; 43 | } 44 | 45 | // get name and tell 46 | string getFirstName() { return firstName; } 47 | string getFamilyName() { return lastName; } 48 | string getTicketType() { return ticketType; } 49 | 50 | // displaying name and tell 51 | void Display() { 52 | cout << Line << endl; 53 | cout << " Passenger: " << firstName << " " << lastName << " " << ticketType << endl; 54 | } 55 | }; 56 | 57 | // Node needed to implement linked list 58 | class Node { 59 | public: 60 | int data; 61 | Node* next; 62 | }; 63 | 64 | // Linked list implementation 65 | class LinkedList { 66 | public: 67 | LinkedList() { // constructor 68 | head = NULL; 69 | } 70 | 71 | ~LinkedList() {}; // destructor 72 | void addNode(int val); 73 | void deleteFirst(); 74 | int getFirstElement(); 75 | void display(); 76 | 77 | private: 78 | Node* head; 79 | }; 80 | 81 | int LinkedList::getFirstElement() { 82 | return head->data; 83 | } 84 | 85 | // Add a node in linked list 86 | void LinkedList::addNode(int val) { 87 | // function to add node to a list 88 | Node* newnode = new Node(); 89 | newnode->data = val; 90 | newnode->next = NULL; 91 | if (head == NULL) { 92 | head = newnode; 93 | } 94 | else { 95 | Node* temp = head; // head is not NULL 96 | while (temp->next != NULL) { 97 | temp = temp->next; // go to end of list 98 | } 99 | temp->next = newnode; // linking to newnode 100 | } 101 | } 102 | 103 | // Displays the linked list 104 | void LinkedList::display() { 105 | if (head == NULL) { 106 | cout << "Passengers list is empty!" << endl; 107 | } 108 | else { 109 | Node* temp = head; 110 | while (temp != NULL) { 111 | cout << temp->data << " --> "; 112 | temp = temp->next; 113 | } 114 | cout << endl; 115 | } 116 | } 117 | 118 | // Removing element from Linked list 119 | void LinkedList::deleteFirst() { 120 | // if empty 121 | if (head == NULL) 122 | cout << "Passengers list is empty!" << endl; 123 | 124 | // delete the first element 125 | else { 126 | Node* temp = head; 127 | head = head->next; 128 | delete(temp); 129 | } 130 | } 131 | 132 | // Stack implementation 133 | class Stack { 134 | Node* front; // points to the head of list 135 | public: 136 | Stack() { 137 | front = NULL; 138 | } 139 | 140 | void push(int); // push method to add data element 141 | void pop(); // pop method to remove data element 142 | void printStack(); 143 | }; 144 | 145 | // Inserting Data in Stack (Linked List) 146 | void Stack::push(int d) { 147 | // creating a new node 148 | Node* temp; 149 | temp = new Node(); 150 | 151 | temp->data = d; // setting data to it 152 | 153 | // add the node in front of list 154 | if (front == NULL) 155 | temp->next = NULL; 156 | else 157 | temp->next = front; 158 | front = temp; 159 | } 160 | 161 | // Removing Element from Stack (Linked List) 162 | void Stack::pop() { 163 | // if empty 164 | if (front == NULL) 165 | cout << "UNDERFLOW"; 166 | 167 | // delete the first element 168 | else { 169 | Node* temp = front; 170 | front = front->next; 171 | delete(temp); 172 | } 173 | } 174 | 175 | // Displays the linked list 176 | void Stack::printStack() { 177 | if (front == NULL) { 178 | cout << "UNDERFLOW!"; 179 | } 180 | else { 181 | Node* temp = front; 182 | while (temp != NULL) { 183 | cout << temp->data << " <--> "; 184 | temp = temp->next; 185 | } 186 | cout << endl; 187 | } 188 | } 189 | 190 | int main() { 191 | // identifires 192 | string firstName, lastName, ticketType, carriageType, carriageID; int carriagePlaces; 193 | int Num = 1; 194 | int numOfBusiness = 0, numOfFirst = 0; 195 | double businessSpace = 0, firstSpace = 0; 196 | 197 | // objects 198 | Passenger Psg; 199 | Carriage Crg; 200 | 201 | // start 202 | for (int i = 0; i < 1000; i++) { // loop for Menu 203 | system("cls"); 204 | 205 | cout << "\t*** MENU *** " << endl; 206 | cout << "1. Add passenger to file" << endl; 207 | cout << "2. Read passengers info from file" << endl; 208 | cout << "3. Add carriage to file" << endl; 209 | cout << "4. Read carriage info from file" << endl; 210 | cout << "5. Show linked lists" << endl; // Sort and Divide Info which comes from File and will add to linked list 211 | cout << "Your choice:"; 212 | 213 | switch (_getch()) { 214 | case 49: { // write to file a passenger 215 | cout << "\n" << Line << endl; 216 | ofstream out; 217 | out.open("Passengers", ios::binary | ios::app); 218 | 219 | cout << "\t*** Add Passenger ***" << endl; 220 | cout << "Enter first name: "; cin >> firstName; 221 | cout << "Enter last name: "; cin >> lastName; 222 | cout << "Enter ticket type (Business/First): "; cin >> ticketType; 223 | 224 | Psg.setData(firstName, lastName, ticketType); 225 | out.write((char*)&Psg, sizeof(Passenger)); 226 | out.close(); 227 | 228 | cout << endl; 229 | system("pause"); 230 | } 231 | break; 232 | 233 | case 50: { // read from file passengers 234 | cout << "\n\t*** Passenger File *** " << endl; 235 | 236 | ifstream in; 237 | in.open("Passengers", ios::binary); 238 | while (in.read((char*)&Psg, sizeof(Passenger))) { 239 | cout << Num << "." << endl; 240 | Psg.Display(); 241 | Num++; 242 | } 243 | cout << Line << endl; 244 | Num = 1; 245 | in.close(); 246 | 247 | cout << endl; 248 | system("pause"); 249 | } 250 | break; 251 | 252 | case 51: { // write to file carriages 253 | cout << "\n" << Line << endl; 254 | ofstream out; 255 | out.open("Carriages", ios::binary | ios::app); 256 | 257 | cout << "\t*** Add Carriages ***" << endl; 258 | cout << "Enter ID: "; cin >> carriageID; 259 | cout << "Enter type (Business/First): "; cin >> carriageType; 260 | cout << "Enter number of seets: "; cin >> carriagePlaces; 261 | 262 | Crg.setData(carriageType, carriageID, carriagePlaces); 263 | out.write((char*)&Crg, sizeof(Carriage)); 264 | out.close(); 265 | 266 | cout << endl; 267 | system("pause"); 268 | } 269 | break; 270 | 271 | case 52: { // read from file carriages 272 | cout << endl; 273 | cout << "\n\t*** Carriage File ***" << endl; 274 | ifstream in; 275 | in.open("Carriages", ios::binary); 276 | while (in.read((char*)&Crg, sizeof(Carriage))) { 277 | cout << Num << "." << endl; 278 | Crg.Display(); 279 | Num++; 280 | } 281 | cout << Line << endl; 282 | Num = 1; 283 | in.close(); 284 | 285 | cout << endl; 286 | system("pause"); 287 | } 288 | break; 289 | 290 | case 53: { 291 | // Sort Passengers into Linked Lists 292 | LinkedList* listBusiness = new LinkedList(); 293 | LinkedList* listFirst = new LinkedList(); 294 | numOfBusiness = 0; 295 | numOfFirst = 0; 296 | ifstream in; 297 | in.open("Passengers", ios::binary); 298 | while (in.read((char*)&Psg, sizeof(Passenger))) { 299 | if (Psg.getTicketType() == "Business") { 300 | listBusiness->addNode(Num); 301 | numOfBusiness++; 302 | } 303 | else { 304 | listFirst->addNode(Num); 305 | numOfFirst++; 306 | } 307 | Num++; 308 | } 309 | cout << endl << Line << endl; 310 | Num = 1; 311 | in.close(); 312 | // --------------------------------------- 313 | cout << "Linked List - 'Business class'" << endl; 314 | listBusiness->display(); 315 | cout << "Overall 'Business': " << numOfBusiness << endl << endl; 316 | 317 | cout << "Linked List - 'First class'" << endl; 318 | listFirst->display(); 319 | cout << "Overall 'First': " << numOfFirst << endl; 320 | // --------------------------------------- 321 | 322 | for (int j = 0; j < 100; j++) { 323 | cout << "\n\t*** INNER MENU *** " << endl; 324 | cout << "1. Distribute 'Business class'" << endl; 325 | cout << "2. Distribute 'First class'" << endl; 326 | cout << "0. Go back " << endl; 327 | cout << "Your choice:"; 328 | 329 | businessSpace = 0; 330 | firstSpace = 0; 331 | 332 | ifstream in; 333 | in.open("Carriages", ios::binary); 334 | while (in.read((char*)&Crg, sizeof(Carriage))) { 335 | if (Crg.getCarriageType() == "Business") { 336 | businessSpace = businessSpace + Crg.getCarriagePlace(); 337 | } 338 | else { 339 | firstSpace = firstSpace + Crg.getCarriagePlace(); 340 | } 341 | } 342 | businessSpace = round(businessSpace / 2.0); 343 | firstSpace = round(firstSpace / 2.0); 344 | in.close(); 345 | 346 | switch (_getch()) { 347 | case 49: { 348 | // Distribute 'Business class' 349 | Stack* stackBusiness = new Stack(); 350 | 351 | // Free spaces we have in business class 352 | cout << endl << Line << endl; 353 | cout << "Number of free spaces (Business): " << businessSpace << endl; 354 | 355 | if (numOfBusiness <= businessSpace) { 356 | // take the first element from list, PUSH() it to stack, delete that element 357 | for (int i = numOfBusiness; i > 0; i--) { 358 | int distributedPerson = listBusiness->getFirstElement(); 359 | stackBusiness->push(distributedPerson); 360 | listBusiness->deleteFirst(); 361 | businessSpace--; 362 | } 363 | // shows the number of free spaces 364 | cout << "Free spaces left: " << businessSpace << endl; 365 | } 366 | else if (numOfBusiness > businessSpace) { 367 | for (int i = businessSpace; i > 0; i--) { 368 | int distributedPerson = listBusiness->getFirstElement(); 369 | stackBusiness->push(distributedPerson); 370 | listBusiness->deleteFirst(); 371 | } 372 | cout << "You need " << numOfBusiness - businessSpace << " more spaces!" << endl; 373 | } 374 | else { 375 | // Overflow case 376 | cout << "You need " << numOfBusiness - businessSpace << " free spaces!"<< endl; 377 | } 378 | 379 | cout << "Business class passengers list: "; 380 | // listBusiness->display(); // displays old linked list 381 | stackBusiness->printStack(); // displays new stack 382 | 383 | cout << endl; 384 | system("pause"); 385 | } 386 | break; 387 | case 50: { // Distribute 'First class' 388 | Stack* stackFirst = new Stack(); 389 | 390 | // Free spaces we have in first class 391 | cout << endl << Line << endl; 392 | cout << "Number of free spaces (Fist): " << firstSpace << endl; 393 | 394 | if (numOfFirst <= firstSpace) { 395 | // take the first element from list, PUSH() it to stack, delete that element 396 | for (int i = numOfFirst; i > 0; i--) { 397 | int distributedPerson = listFirst->getFirstElement(); 398 | stackFirst->push(distributedPerson); 399 | listFirst->deleteFirst(); 400 | firstSpace--; 401 | } 402 | // shows the number of free spaces 403 | cout << "Free spaces left: " << firstSpace << endl; 404 | } 405 | else if (numOfFirst > firstSpace) { 406 | for (int i = firstSpace; i > 0; i--) { 407 | int distributedPerson = listFirst->getFirstElement(); 408 | stackFirst->push(distributedPerson); 409 | listFirst->deleteFirst(); 410 | } 411 | cout << "You need " << numOfFirst - firstSpace << " more spaces!" << endl; 412 | } 413 | else { 414 | // Overflow case 415 | cout << "You need " << numOfFirst - firstSpace << " spaces!" << endl; 416 | } 417 | 418 | cout << "First class passengers list: "; 419 | stackFirst->printStack(); // displays new stack 420 | 421 | cout << endl; 422 | system("pause"); 423 | } 424 | break; 425 | case 48: { // go back 426 | j = 101; 427 | } 428 | break; 429 | } 430 | 431 | } // inner menu 432 | 433 | cout << endl; 434 | // system("pause"); 435 | } 436 | break; 437 | 438 | default: { 439 | cout << "\n\nYour choice is not available in the menu!" << endl; 440 | cout << endl; 441 | system("pause"); 442 | } 443 | break; 444 | } // end of switch 445 | } // end of loop 446 | system("pause"); 447 | return 0; 448 | } -------------------------------------------------------------------------------- /images/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/.DS_Store -------------------------------------------------------------------------------- /images/01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/01.png -------------------------------------------------------------------------------- /images/02.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/02.png -------------------------------------------------------------------------------- /images/03.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/03.png -------------------------------------------------------------------------------- /images/04.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/04.png -------------------------------------------------------------------------------- /images/05.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/05.png -------------------------------------------------------------------------------- /images/06.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/06.gif -------------------------------------------------------------------------------- /images/06a.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/06a.png -------------------------------------------------------------------------------- /images/07.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/07.png -------------------------------------------------------------------------------- /images/08.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/08.png -------------------------------------------------------------------------------- /images/09.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/09.png -------------------------------------------------------------------------------- /images/09a.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/09a.png -------------------------------------------------------------------------------- /images/10.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/10.png -------------------------------------------------------------------------------- /images/11.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/11.png -------------------------------------------------------------------------------- /images/12.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/12.png -------------------------------------------------------------------------------- /images/13.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/13.png -------------------------------------------------------------------------------- /images/14.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/14.png -------------------------------------------------------------------------------- /images/15.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/15.png -------------------------------------------------------------------------------- /images/16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/16.png -------------------------------------------------------------------------------- /images/17.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/17.png -------------------------------------------------------------------------------- /images/18.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/18.png -------------------------------------------------------------------------------- /images/19.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/19.png -------------------------------------------------------------------------------- /images/20.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/20.png -------------------------------------------------------------------------------- /images/21.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/21.png -------------------------------------------------------------------------------- /images/22.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/22.png -------------------------------------------------------------------------------- /images/23.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/23.png -------------------------------------------------------------------------------- /images/24.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/24.png -------------------------------------------------------------------------------- /images/25.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/25.png -------------------------------------------------------------------------------- /images/26.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/26.png -------------------------------------------------------------------------------- /images/27.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/27.png -------------------------------------------------------------------------------- /images/28.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/28.png -------------------------------------------------------------------------------- /images/29.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/29.png -------------------------------------------------------------------------------- /images/30.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/30.png -------------------------------------------------------------------------------- /images/31.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/31.png -------------------------------------------------------------------------------- /images/32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/32.png -------------------------------------------------------------------------------- /images/33.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/33.png -------------------------------------------------------------------------------- /images/34.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/34.png -------------------------------------------------------------------------------- /images/35.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/35.png -------------------------------------------------------------------------------- /images/36.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/36.png -------------------------------------------------------------------------------- /images/37.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/37.png -------------------------------------------------------------------------------- /images/38.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/38.png -------------------------------------------------------------------------------- /images/39.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/39.png -------------------------------------------------------------------------------- /images/40.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/40.png -------------------------------------------------------------------------------- /images/41.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/41.png -------------------------------------------------------------------------------- /images/42.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/42.png -------------------------------------------------------------------------------- /images/43.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/43.png -------------------------------------------------------------------------------- /images/44.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/44.png -------------------------------------------------------------------------------- /images/45.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/45.png -------------------------------------------------------------------------------- /images/46.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/46.png -------------------------------------------------------------------------------- /images/47.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/47.png -------------------------------------------------------------------------------- /images/48.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/48.png -------------------------------------------------------------------------------- /images/49.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/49.png -------------------------------------------------------------------------------- /images/50.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/50.png -------------------------------------------------------------------------------- /images/51.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/51.png -------------------------------------------------------------------------------- /images/52.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/52.png -------------------------------------------------------------------------------- /images/53.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/53.png -------------------------------------------------------------------------------- /images/54.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/54.png -------------------------------------------------------------------------------- /images/55.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/55.png -------------------------------------------------------------------------------- /images/56.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/56.png -------------------------------------------------------------------------------- /images/57.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/57.png -------------------------------------------------------------------------------- /images/58.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/58.png -------------------------------------------------------------------------------- /images/59.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/59.png -------------------------------------------------------------------------------- /images/60.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/60.png -------------------------------------------------------------------------------- /images/CA/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/CA/.DS_Store -------------------------------------------------------------------------------- /images/CA/asymp_notat/1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/CA/asymp_notat/1.jpg -------------------------------------------------------------------------------- /images/CA/asymp_notat/10.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/CA/asymp_notat/10.jpg -------------------------------------------------------------------------------- /images/CA/asymp_notat/2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/CA/asymp_notat/2.jpg -------------------------------------------------------------------------------- /images/CA/asymp_notat/3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/CA/asymp_notat/3.jpg -------------------------------------------------------------------------------- /images/CA/asymp_notat/4.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/CA/asymp_notat/4.jpg -------------------------------------------------------------------------------- /images/CA/asymp_notat/5.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/CA/asymp_notat/5.jpg -------------------------------------------------------------------------------- /images/CA/asymp_notat/6.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/CA/asymp_notat/6.jpg -------------------------------------------------------------------------------- /images/CA/asymp_notat/7.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/CA/asymp_notat/7.jpg -------------------------------------------------------------------------------- /images/CA/asymp_notat/8.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/CA/asymp_notat/8.jpg -------------------------------------------------------------------------------- /images/CA/asymp_notat/9.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/CA/asymp_notat/9.jpg -------------------------------------------------------------------------------- /images/CA/back.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/CA/back.jpg -------------------------------------------------------------------------------- /images/CA/masters.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/CA/masters.jpg -------------------------------------------------------------------------------- /images/CA/masters_decr.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/CA/masters_decr.png -------------------------------------------------------------------------------- /images/CA/masters_div.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/CA/masters_div.png -------------------------------------------------------------------------------- /images/CA/quick.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/CA/quick.png -------------------------------------------------------------------------------- /images/CA/radix.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/CA/radix.png -------------------------------------------------------------------------------- /images/CA/radix2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/CA/radix2.png -------------------------------------------------------------------------------- /images/CA/sort_complexity.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/CA/sort_complexity.png -------------------------------------------------------------------------------- /images/CA/tree.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/CA/tree.jpg -------------------------------------------------------------------------------- /images/complexity.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/complexity.png -------------------------------------------------------------------------------- /images/max_heap.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/max_heap.png -------------------------------------------------------------------------------- /images/max_heap2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/max_heap2.png -------------------------------------------------------------------------------- /images/merge_sort.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/merge_sort.png -------------------------------------------------------------------------------- /images/merge_step.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/merge_step.png -------------------------------------------------------------------------------- /images/quicksort1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/quicksort1.png -------------------------------------------------------------------------------- /images/quicksort2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/quicksort2.png -------------------------------------------------------------------------------- /images/quicksort3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/quicksort3.png -------------------------------------------------------------------------------- /images/time_complexity1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/time_complexity1.png -------------------------------------------------------------------------------- /images/time_complexity2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/images/time_complexity2.png -------------------------------------------------------------------------------- /lecture notes/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/lecture notes/.DS_Store -------------------------------------------------------------------------------- /lecture notes/01_Data_Structures.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/lecture notes/01_Data_Structures.pptx -------------------------------------------------------------------------------- /lecture notes/02_Serching_Techniques.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/lecture notes/02_Serching_Techniques.pptx -------------------------------------------------------------------------------- /lecture notes/03_DS_Sorting.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/lecture notes/03_DS_Sorting.pptx -------------------------------------------------------------------------------- /lecture notes/04_Linked_List-_Insert_&_delete_operations.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/lecture notes/04_Linked_List-_Insert_&_delete_operations.pptx -------------------------------------------------------------------------------- /lecture notes/05_Linked_List-Circular_and_Doubly_Linked_List.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/lecture notes/05_Linked_List-Circular_and_Doubly_Linked_List.pptx -------------------------------------------------------------------------------- /lecture notes/06_Stacks.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/lecture notes/06_Stacks.pptx -------------------------------------------------------------------------------- /lecture notes/07_Infix_to_prefix.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/lecture notes/07_Infix_to_prefix.pptx -------------------------------------------------------------------------------- /lecture notes/08_Queues.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/lecture notes/08_Queues.pptx -------------------------------------------------------------------------------- /lecture notes/09_Tree.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/lecture notes/09_Tree.pptx -------------------------------------------------------------------------------- /lecture notes/10_Traversing_a_tree+_BST.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/lecture notes/10_Traversing_a_tree+_BST.pptx -------------------------------------------------------------------------------- /lecture notes/11_Graphs.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/lecture notes/11_Graphs.pptx -------------------------------------------------------------------------------- /lecture notes/12_BFS_and_DFS.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/lecture notes/12_BFS_and_DFS.pptx -------------------------------------------------------------------------------- /lecture notes/13_Threaded_Binary-_TREES.ppt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/lecture notes/13_Threaded_Binary-_TREES.ppt -------------------------------------------------------------------------------- /lecture notes/14_AVL_slides.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/lecture notes/14_AVL_slides.pptx -------------------------------------------------------------------------------- /lecture notes/15_Deletion_-_AVL_tree.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/lecture notes/15_Deletion_-_AVL_tree.pptx -------------------------------------------------------------------------------- /lecture notes/16_Huffman_Coding_Algorithm.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/lecture notes/16_Huffman_Coding_Algorithm.pptx -------------------------------------------------------------------------------- /lecture notes/17_M-way_Search_Trees.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/lecture notes/17_M-way_Search_Trees.pptx -------------------------------------------------------------------------------- /lecture notes/18_B_Tree.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/lecture notes/18_B_Tree.pptx -------------------------------------------------------------------------------- /lecture notes/CA/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/lecture notes/CA/.DS_Store -------------------------------------------------------------------------------- /lecture notes/CA/CA_1_Analyzing Running Times of recursive Programs.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/lecture notes/CA/CA_1_Analyzing Running Times of recursive Programs.pptx -------------------------------------------------------------------------------- /lecture notes/CA/CA_HW2_masters.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/lecture notes/CA/CA_HW2_masters.pdf -------------------------------------------------------------------------------- /lecture notes/CA/CA_HW3_heapsort_quicksort.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rustam-Z/data-structures-and-algorithms/6810c39eb75f5c2b3686b2be7629917742908187/lecture notes/CA/CA_HW3_heapsort_quicksort.pdf -------------------------------------------------------------------------------- /linked_list/linked_list_java.md: -------------------------------------------------------------------------------- 1 | # Linked List in Java 2 | - [Nodes and Size](#nodes-and-size) 3 | - [Boundary condition](#boundary-condition) 4 | - [addFirst()](#addFirst()) 5 | - [addLast()](#addLast()) 6 | - [removeFirst()](#removeFirst()) 7 | - [removeLast()](#removeLast()) 8 | 9 | ## Nodes and Size 10 | ```java 11 | public class LinkedList implements ListI { 12 | class Node { 13 | E data; 14 | Node next; 15 | public Node(E obj) { 16 | data = obj; 17 | next = null; 18 | } 19 | } // Node 20 | 21 | private Node head; // head 22 | private int currentSize; // get current size of list 23 | public LinkedList() { 24 | head = null; 25 | currentSize = 0; 26 | } 27 | // addFirst(), addLast() 28 | } // LinkedList 29 | ``` 30 | 31 | ## Boundary Condition 32 | - Empty data structure 33 | - Single element in the data structure 34 | - Adding / removing beginning of data structure 35 | - Adding / removing end of data structure 36 | - Working in the middle 37 | 38 | ## addFirst() 39 | ```java 40 | // complexity = O(1) 41 | public void addFirst(E obj) { 42 | Node node = new Node(obj); // create a node 43 | 44 | node.next = head; // new node points to head 45 | head = node; // change head to new node 46 | 47 | currentSize++; // increment size when add, decrement when delete 48 | } 49 | ``` 50 | 51 | ## addLast() 52 | 53 | ```java 54 | // complexity = O(n) 55 | public void addLast(E obj) { 56 | Node node = new Node(obj); // create a node 57 | 58 | if(head == null) { // if empty 59 | head = node; 60 | currentSize++; 61 | return 62 | } 63 | 64 | Node tmp = head; // temporary pointer 'head' 65 | 66 | while(tmp.next != null) { // seek last node (it points to "null") 67 | tmp = tmp.next; 68 | } 69 | tmp.next = node; 70 | currentSize++; 71 | } 72 | ``` 73 | 74 | ```java 75 | // complexity = O(1), because of the glogal "tail" pointer 76 | // "tail" same as "head", it should be declared in LinkedList class 77 | public void addLast(E obj) { 78 | Node node = new Node(obj); // create a node 79 | 80 | if(head == null) { // if empty 81 | head = tail = node; 82 | currentSize++; 83 | return 84 | } 85 | // tail = хвост 86 | tail.next = node; 87 | tail = node; 88 | currentSize++; 89 | return 90 | } 91 | ``` 92 | 93 | ## removeFirst() 94 | ```java 95 | public E removeFirst() { 96 | if(head == null) // if list is empty 97 | return null; 98 | 99 | E tmp = head.data; // temp which points to head 100 | 101 | if(head.next == null) // if we have just one element // same as "head == tail" 102 | head = tail = null; 103 | else 104 | head = head.next; // after removing change head 105 | 106 | currentSize--; // decrement size 107 | return tmp; 108 | } 109 | ``` 110 | 111 | ## removeLast() 112 | ```java 113 | public E removeLast() { 114 | if(head == null) // if list is empty 115 | return null; 116 | 117 | if(head.next == null) { // if we have just one element // same as "head == tail" 118 | return removeFirst(); 119 | } 120 | 121 | Node current = head, previous = null; // "current" in the beginning points to head, and "previous" points to null 122 | while(current != tail) { 123 | previous = current; 124 | current = current.next; 125 | } 126 | previous.next = null; // after deleting the last element, the previous must point to null 127 | tail = previous; // update tail pointer, if you will not do it you will have two linked lists 128 | 129 | currentSize--; 130 | return current.data; 131 | } 132 | ``` --------------------------------------------------------------------------------