Intro to Algorithms
Intro to Algorithms
Introduction to Algorithms
3. O(n): Linear Time ● Description: The runtime is a combination of linear and logarithmic
factors. Algorithms with this complexity are typically more efficient
● Description: The runtime grows linearly with than O(n²) but less efficient than O(n).
the input size, meaning that the time taken ● Example: Merge Sort, Quick Sort (in average case).
increases directly in proportion to the number ● Merge sort divides the array into halves (log n splits) and then
of elements. merges the results (n operations), resulting in a time complexity of
● Example: Iterating over an array to find the O(n log n).
maximum element.
● The algorithm must examine each element in
the array, so the runtime is proportional to
the number of elements (n).
●
Time Complexity Classes
6. O(2ⁿ): Exponential Time
5. O(n²): Quadratic Time ● Description: The runtime doubles with each additional element in
the input. These algorithms are extremely inefficient for large inputs.
● Description: The runtime grows ● Example: Solving the Tower of Hanoi problem or calculating the nth
quadratically with the input size, meaning Fibonacci number using a naive recursive approach.
that the time taken is proportional to the
square of the number of elements. This is The recursive Fibonacci algorithm recalculates values repeatedly, leading
typical for algorithms that involve nested to exponential growth in the number of recursive calls as n increases.
loops.
● Example: Selection Sort or Bubble Sort.
● For every element, the algorithm compares it
to every other element, resulting in O(n²)
comparisons.
Space-Time Tradeoff
● Balancing memory usage and execution time
● Sometimes faster algorithms require more memory
● Example: Hash tables vs. Arrays for data lookup
● Can you think of a situation where you'd prioritize space over
time?
Algorithm Correctness
● BEGIN
● Input numbers A, B, C
● IF A > B AND A > C THEN
● max = A
● ELSE IF B > A AND B > C THEN
● max = B
● ELSE
● max = C
● END IF
● Output max
● END
● Can you modify this pseudocode to find the minimum number?
Combining Flowcharts and Pseudocode