




























































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





























































Competencies and Topics Explains Algorithms - 29% of assessment Characteristics of Algorithms Finiteness An algorithm must always have a finite number of steps before it ends. When the operation is finished, it must have a defined endpoint or output and not enter an endless loop. Definiteness An algorithm needs to have exact definitions for each step. Clear and straightforward directions ensure that every step is understood and can be taken easily. Input An algorithm requires one or more inputs. The values that are first supplied to the algorithm before its processing are known as inputs. These inputs come from a predetermined range of acceptable values. Output One or more outputs must be produced by an algorithm. The output is the outcome of the algorithm after every step has been completed. The relationship between the input and the result should be clear. Effectiveness An algorithm's stages must be sufficiently straightforward to be carried out in a finite time utilizing fundamental operations. With the resources at hand, every operation in the algorithm should be doable and practicable.
Generality Rather than being limited to a single particular case, an algorithm should be able to solve a group of issues. It should offer a generic fix that manages a variety of inputs inside a predetermined range or domain. Factors of an Algorithm Modularity: This feature was perfectly designed for the algorithm if you are given a problem and break it down into small-small modules or small-small steps, which is a basic definition of an algorithm. Correctness: An algorithm's correctness is defined as when the given inputs produce the desired output, indicating that the algorithm was designed correctly. An algorithm's analysis has been completed correctly. Maintainability: It means that the algorithm should be designed in a straightforward, structured way so that when you redefine the algorithm, no significant changes are made to the algorithm. Functionality: It takes into account various logical steps to solve a real-world problem. Robustness: Robustness refers to an algorithm's ability to define your problem clearly. User-friendly: If the algorithm is difficult to understand, the designer will not explain it to the programmer. Simplicity: If an algorithm is simple, it is simple to understand. Extensibility: Your algorithm should be extensible if another algorithm designer or programmer wants to use it. Types of Algorithms Brute Force Algorithm : A straightforward approach that exhaustively tries all possible solutions, suitable for small problem instances but may become impractical for larger ones due to its high time complexity. Recursive Algorithm : A method that breaks a problem into smaller, similar subproblems and repeatedly applies itself to solve them until reaching a base case, making it effective for tasks with recursive structures.
How It Works: Base Case : When n is 0, the function returns 1. Recursive Case : For any other value of n, the function calls itself with n−1 and multiplies the result by n. For example, calling factorial(3) would work as follows: factorial(3) calls factorial(2) factorial(2) calls factorial(1) factorial(1) calls factorial(0) factorial(0) returns 1, then: factorial(1) returns 1 * 1 = 1 factorial(2) returns 2 * 1 = 2 factorial(3) returns 3 * 2 = 6 Advantages of Recursion
Simplicity : Recursive solutions are often more elegant and easier to understand than their iterative counterparts. Direct Translation : Some problems are naturally recursive, like tree traversals, making recursion the most straightforward approach. Disadvantages of Recursion Performance : Recursive algorithms can be less efficient due to the overhead of multiple function calls and potential stack overflow issues for deep recursion. Memory Usage : Recursion can consume more memory because each function call adds a new frame to the call stack. When to Use Recursion When a problem can naturally be divided into similar sub-problems (e.g., tree traversal, searching algorithms like binary search). When the recursive solution is significantly simpler or more intuitive than an iterative one. Linear & Binary Search Linear search and binary search are two fundamental algorithms used to search for an element in a collection, like an array or a list. However, they differ significantly in how they approach the search and their efficiency. Linear Search Concept : Linear search is the simplest search algorithm. It works by sequentially checking each element of the array or list until the target element is found or the end of the collection is reached. Algorithm :
Time Complexity : O(log n), where n is the number of elements in the array. This logarithmic time complexity makes binary search significantly faster than linear search for large datasets. When to Use : When the array or list is sorted. When the array is large and efficiency is crucial. Example: def binary_search(arr, target): low = 0 high = len(arr) - 1 while low <= high: mid = (low + high) // 2 if arr[mid] == target: return mid elif arr[mid] < target: low = mid + 1 else: high = mid - 1 return -1 # Return -1 if the element is not found Comparison Efficiency : Binary search is faster than linear search, especially for large datasets, but it requires the array to be sorted. Simplicity : Linear search is simpler to implement and doesn't require the array to be sorted, making it more versatile for smaller or unsorted datasets. Use Cases : o Linear Search : Suitable for small or unsorted collections where the simplicity of the algorithm outweighs the need for speed. o Binary Search : Ideal for large, sorted collections where performance is a priority.
Step-By-Step Guide To Figuring Out The Array Elements Corresponding To The Mid-Values In The First And Second Iterations Of A Binary Search arr = {45, 77, 89, 90, 94, 99, 100} and key = 100 Initial Setup : The array arr is {45, 77, 89, 90, 94, 99, 100}. The key to find is 100. Initialize two pointers: low (start of the array) and high (end of the array). First Iteration : Calculate the middle index mid using the formula: mid = (low + high) / 2 Check the value at arr[mid]. Compare arr[mid] with the key: o If arr[mid] is less than key, update low to mid + 1. o If arr[mid] is greater than key, update high to mid - 1. o If arr[mid] is equal to key, you have found the key (though you won't need a second iteration in this case). Second Iteration : Repeat the calculation for mid with the updated low and high values. Again, compare arr[mid] with the key and update low or high accordingly. Searching & Sorting Algorithms Searching Algorithms Linear Search Concept : As discussed earlier, linear search involves checking each element in a list or array sequentially until the target element is found or the end of the collection is reached. Time Complexity : O(n), where n is the number of elements. Use Case : Best used when the list is small or unsorted. Distinct Characteristics :
Interpolation Search Worst, Average and Best o Best Case : O(1) — The target element is exactly where the interpolation suggests. o Average Case : O(log log n) — Uniformly distributed data. o Worst Case : O(n) — Highly skewed data distribution or worst interpolation. Depth-First Search (DFS) and Breadth-First Search (BFS) Concept : Used primarily in graph and tree data structures. DFS explores as far as possible along one branch before backtracking, while BFS explores all neighbors at the present depth before moving on to nodes at the next depth level. Time Complexity : O(V+E), where V is the number of vertices and E is the number of edges. Use Case : Useful for searching nodes in graphs and trees. Depth-First Search (DFS) Worst, Average and Best o Best Case : O(1) — The target node is found immediately. o Average Case : O(V+E)— Typically when all nodes and edges must be explored. o Worst Case : O(V+E) — The target node is the last one discovered. Breadth-First Search (BFS) Worst, Average and Best o Best Case : O(1) — The target node is the root or the first node checked. o Average Case : O(V+E) — All nodes and edges need to be explored. o Worst Case : O(V+E) — The target node is the last one explored. Sorting Algorithms Sorting algorithms organize data in a particular order (usually ascending or descending). This makes searching and other operations more efficient. Bubble Sort Use Case : Simple but inefficient for large datasets. Best used for educational purposes or small lists. Distinct Characteristics : Repeatedly swaps adjacent elements if they are in the wrong order. Simple, but inefficient for large datasets.
“Bubbles” the largest element to the end of the list. Bubble Sort Worst, Average and Best o Best Case : O(n) — The array is already sorted (with an optimized version that stops early). o Average Case : O(n^2 ) — Average case with random elements. o Worst Case : O(n^2 ) — The array is sorted in reverse order. Bubble : Look for something that swaps so the result can “bubble” to the top. (Swap, Exchange) Selection Sort Use Case : Inefficient for large lists, but useful when memory writes are more expensive than comparisons. Distinct Characteristics : Finds the minimum element and swaps it with the first unsorted element. Reduces the problem size by one in each iteration. Always performs O(n^2 ) comparisons, regardless of input. Selection Sort Worst, Average and Best o Best Case : O(n^2 ) — Selection sort does not improve with better input, always O(n^2 ). o Average Case : O(n^2 ) — Average case with random elements. o Worst Case : O(n^2 ) — Selection sort is insensitive to input order. Selection: Look for code that repeatedly finds the minimum (or maximum) element and moves it to the beginning (or end) of the list. (Select minimum, Swap with start) Insertion Sort Use Case : Good for small or nearly sorted lists. Distinct Characteristics : Builds a sorted list one element at a time. Efficient for small or nearly sorted datasets. Shifts elements to make space for the current element. Insertion Sort Worst, Average and Best
o Worst Case : O(n^2 ) — The pivot is always the smallest or largest element, leading to unbalanced partitions. Quicksort : Look for the keywords “pivot” and/or “split”. (Pivot, Split) Heap Sort Use Case : Useful when memory usage is a concern as it’s an in-place algorithm. Distinct Characteristics : Utilizes a binary heap data structure. Builds a max-heap and repeatedly extracts the maximum element. Efficient and in-place, but not stable. Heap Sort Worst, Average and Best o Best Case : O(n log n) — Heap sort’s time complexity is the same in all cases. o Average Case : O(n log n). o Worst Case : O(n log n). Heap Sort: Look for code that uses a heap data structure to repeatedly extract the maximum (or minimum) element and rebuilds the heap. (Heapify, Extract Max, Build Heap) Counting Sort Use Case : Efficient for sorting integers or other items with a small range of possible values. Distinct Characteristics : Non-comparative sorting. Counts occurrences of each element and uses this information to place elements. Efficient for small ranges of integers. Counting Sort Worst, Average and Best o Best Case : O(n+k)— k is the range of the input. o Average Case : O(n+k). o Worst Case : O(n+k). Radix Sort
Use Case : Effective for sorting large numbers or strings with a fixed length. Distinct Characteristics : Sorts numbers by processing individual digits. Non-comparative, stable, and efficient for specific data types. Often combined with counting sort. Radix Sort Worst, Average and Best o Best Case : O(nk) — k is the number of digits in the largest number. o Average Case : O(nk). o Worst Case : O(n*k). Radix Sort: Look for code that sorts numbers based on their individual digits, starting from the least significant digit (LSD) or the most significant digit (MSD). (Count, Frequency, Sum) Bucket Sort Use Case : Good for uniformly distributed data. Distinct Characteristics : Distributes elements into buckets and sorts each bucket individually. Efficient when the input is uniformly distributed. Often combined with another sorting algorithm like insertion sort. Bucket Sort Worst, Average and Best o Best Case : O(n+k) — k is the number of buckets; assumes uniform distribution. o Average Case : O(n+k). o Worst Case : O(n^2 ) — All elements end up in one bucket (degenerate case). Bucket : Look for something that distributes the values into “buckets” where they are individually sorted. (Bucket) Shell Sort Distinct Characteristics : o Generalization of insertion sort with a gap sequence.
Bubble Sort, Selection Sort, and Insertion Sort : These are simple but inefficient for large datasets, especially in the worst case. Merge Sort and Heap Sort : Stable and consistent in performance, regardless of the input. Quick Sort : Very efficient on average but can degrade to O(n^2 ) in the worst case without proper pivot selection. Counting Sort, Radix Sort, and Bucket Sort : Efficient for specific types of data (e.g., integers within a fixed range) but less versatile. Choosing the Right Algorithm Small datasets : Simpler algorithms like bubble sort, selection sort, or insertion sort might suffice. Large datasets : More efficient algorithms like merge sort, quick sort, or heap sort are preferred. Sorted data : Algorithms like insertion sort can be very efficient. Special conditions : Use counting sort, radix sort, or bucket sort if the data is within a certain range or has other specific properties. Big O Notation What is Big O Notation? Big O Notation : It provides an upper bound on the time or space complexity of an algorithm, representing the worst-case scenario. It’s a way to describe the efficiency of an algorithm as the input size grows towards infinity. Why Use Big O Notation? Comparing Algorithms : It allows us to compare the efficiency of different algorithms independently of hardware or other environmental factors. Scalability : It helps us understand how an algorithm will perform as the size of the input data grows. Common Big O Notations
o Efficiency : Excellent.
Rule : Lower-order terms are ignored because they become insignificant as n grows. Why : Similar to focusing on the dominant term, lower-order terms have a negligible impact on large inputs. Example : O(n^2 + n + log n) simplifies to O(n^2 ) Multiplicative Constants Can Be Ignored: Rule : Coefficients that multiply variables (e.g., 2n, 3n^2) are ignored. Why : Like constants, they don't change the growth rate. Example : O(3n^2 ) simplifies to O(n^2 ) Additive Constants Can Be Ignored: Rule : Constant terms that don't depend on n are ignored. Why : They don't affect the overall growth rate as n increases. Example : O(n+10) simplifies to O(n) Logarithms with Different Bases: Rule : Logarithms with different bases can be considered equivalent in Big O notation. Why : Changing the base of a logarithm only introduces a constant factor, which is ignored in Big O notation. Example : O(log 2 n) simplifies to O(log n) Non-Dominant Polynomial Terms: Rule : In polynomials, only the highest degree term is considered. Why : As n grows large, the highest degree term will dominate. Example : O(5n^3 + 2n^2 + 7) simplifies to O(n^3 ) Exponential Growth: Rule : Exponential growth functions dominate polynomial functions. Why : Exponential functions grow much faster than polynomial functions as n increases. Example : O(2n^ + n^3 ) simplifies to O(2n) Nested Loops:
Rule : The time complexity of nested loops is the product of the complexities of each loop. Why : Each loop iterates based on the input size, so their combined effect is multiplicative. Example : A loop inside another loop both running n times results in O(n * n) = O(n^2 ) Sequential Statements: Rule : If two independent statements (or loops) are executed sequentially, their time complexities are added. Why : Sequential operations don't multiply time complexity, but rather add up. Example : Two loops each running n times sequentially result in O(n + n) = O(n) Determines Data Structure Impact - 31% of assessment Implementation of Data Structures Data Types What is a Data Type? Definition : A data type is a classification that specifies the type of data that a variable can hold in programming. It defines the operations that can be performed on the data and the way the data is stored in memory. Examples : o Primitive Data Types : These are the basic building blocks of data in a programming language. Integer (e.g., int in C, Java): Holds whole numbers. Floating Point (e.g., float, double): Holds numbers with fractional parts. Character (e.g., char): Holds a single character. Boolean (e.g., bool): Holds a true or false value. o Composite Data Types : These are constructed from primitive types. Arrays : A collection of elements of the same data type. Structures (e.g., struct in C): A collection of different data types. o User-Defined Data Types : Created by the user, typically by combining primitive data types.