1. Home
  2. Explore
  3. Computer Science
  4. Algorithm Complexity Analysis

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Algorithm Complexity Analysis

Searching, Sorting, and Computational Thinking

1. Algorithmic Complexity and Orders of Growth

Algorithm analysis studies how the cost of an algorithm changes as the input size grows. The input size is commonly represented by nnn.

The goal is not usually to calculate the exact running time. Instead, analysis focuses on the order of growth: how rapidly the cost increases for increasingly large inputs.

Common complexity classes include:

  • Constant time: O(1)O(1)O(1)
    The work remains approximately the same regardless of input size.

  • Logarithmic time: O(log⁡n)O(\log n)O(logn)
    The problem size is repeatedly reduced by a constant factor, often by half.

  • Linear time: O(n)O(n)O(n)
    The work grows proportionally to the input size.

  • Log-linear time: O(nlog⁡n)O(n\log n)O(nlogn)
    Common in efficient sorting algorithms.

  • Quadratic time: O(n2)O(n^2)O(n2)
    Often produced by nested loops that each examine up to nnn elements.

  • Exponential time: such as O(2n)O(2^n)O(2n)
    The cost grows extremely rapidly as nnn increases.

  • Factorial time: O(n!)O(n!)O(n!)
    Even less practical for large inputs than exponential time.

For large inputs, algorithms with slower-growing complexity are generally preferred. The hierarchy is approximately:

O(1)<O(log⁡n)<O(n)<O(nlog⁡n)<O(n2)<O(2n)<O(n!)O(1) < O(\log n) < O(n) < O(n\log n) < O(n^2) < O(2^n) < O(n!)O(1)<O(logn)<O(n)<O(nlogn)<O(n2)<O(2n)<O(n!)

Key principle: Algorithm design involves choosing computational strategies that keep the order of growth as low as possible.


2. Search Algorithms

A search algorithm finds an item or group of items within a collection.

The collection may be:

  • Explicit: The items are stored in a concrete data structure, such as a list of student records.

  • Implicit: The possible values are not stored as a collection but are defined by a range or process, such as searching among possible approximations to a square root.

Examples of implicit search include:

  • Exhaustive enumeration of possible values

  • Bisection search for numerical approximations

  • Newton–Raphson methods for finding roots

The main focus here is searching through an explicit list of elements, particularly lists of numbers.


3. Linear Search

Basic Idea

Linear search examines list elements one at a time, starting from one end and moving toward the other.

The algorithm:

  1. Begin at the first element.

  2. Compare the current element with the target.

  3. If they match, return true.

  4. Otherwise, continue to the next element.

  5. If the end of the list is reached, return false.

The list does not need to be sorted.

Complexity

In the worst case, the target:

  • Is the final element, or

  • Is not present at all.

In either case, every element must be examined.

If the list has length nnn:

  • The loop executes up to nnn times.

  • Each iteration performs constant work, O(1)O(1)O(1).

Therefore:

O(n)⋅O(1)=O(n)O(n)\cdot O(1)=O(n)O(n)⋅O(1)=O(n)

The worst-case complexity is linear.

Early Return

The algorithm can return immediately when the target is found. This improves the average-case behavior, because many searches may finish before reaching the end.

However, it does not improve the worst-case complexity. The target may still be absent or located at the final position.

Linear Search on a Sorted List

If the list is sorted, linear search can stop early:

  • If the current element equals the target, the search succeeds.

  • If the current element is larger than the target, the target cannot appear later, because all later elements are at least as large.

This can improve practical performance and average behavior, but the worst-case complexity remains:

O(n)O(n)O(n)

The target might be larger than nearly every list element, requiring almost the entire list to be examined.


4. Bisection or Binary Search

Basic Idea

Bisection search, also called binary search, uses the fact that the list is sorted.

The algorithm repeatedly examines the middle element of the remaining search range:

  1. Find the middle element.

  2. If it equals the target, return success.

  3. If the target is smaller, continue searching only the lower half.

  4. If the target is larger, continue searching only the upper half.

  5. Repeat until the target is found or no elements remain.

Requirement: A Sorted List

Binary search is only valid when the list is sorted. The ordering allows half of the remaining elements to be discarded after every comparison.

Without sorted data, the algorithm cannot determine which half might contain the target.

Why the Complexity Is Logarithmic

At each step, the remaining problem is reduced by half:

n,n2,n4,n8,…n,\frac{n}{2},\frac{n}{4},\frac{n}{8},\ldotsn,2n​,4n​,8n​,…

After kkk steps, the remaining size is:

n2k\frac{n}{2^k}2kn​

The search ends when the remaining size reaches 111:

n2k=1\frac{n}{2^k}=12kn​=1

Solving for kkk gives:

2k=n2^k=n2k=n

and therefore:

k=log⁡2nk=\log_2 nk=log2​n

Thus, binary search has worst-case complexity:

O(log⁡n)O(\log n)O(logn)

Recursive Structure

A recursive implementation typically has:

  • A base case for an empty list or a search range containing one element.

  • A recursive call on either the lower half or the upper half.

  • Only one recursive call per step, because the comparison determines which half can contain the target.

The implementation can pass index boundaries rather than copying sublists. Passing these indices requires constant work at each level, so the total cost remains O(log⁡n)O(\log n)O(logn).

Key distinction: Linear search examines elements one by one, while binary search repeatedly eliminates half of the remaining possibilities.


5. When Should a List Be Sorted Before Searching?

Binary search is much faster than linear search, but it requires sorting first. This creates a trade-off.

Let:

  • S(n)S(n)S(n) be the cost of sorting a list of length nnn.

  • kkk be the number of searches.

  • A linear search cost approximately O(n)O(n)O(n) per search.

  • A binary search cost approximately O(log⁡n)O(\log n)O(logn) per search.

One Search

For a single search, sorting first would require:

S(n)+O(log⁡n)S(n)+O(\log n)S(n)+O(logn)

A direct linear search requires:

O(n)O(n)O(n)

Sorting cannot have a worst-case cost lower than linear time because every element must be examined at least once. Therefore:

S(n)≥O(n)S(n)\geq O(n)S(n)≥O(n)

Sorting once merely to perform one search generally does not provide a worst-case advantage.

Multiple Searches

If the same list will be searched repeatedly, the sorting cost can be amortized across many searches.

For kkk binary searches, the total cost is:

S(n)+O(klog⁡n)S(n)+O(k\log n)S(n)+O(klogn)

Performing kkk linear searches costs:

O(kn)O(kn)O(kn)

The sorted approach becomes attractive when:

S(n)+O(klog⁡n)<O(kn)S(n)+O(k\log n)<O(kn)S(n)+O(klogn)<O(kn)

For sufficiently large kkk, the initial sorting cost becomes relatively unimportant, while each subsequent search benefits from logarithmic complexity.

Amortization spreads a one-time cost across many operations, making an initially expensive preparation step worthwhile.


Sorting Algorithms

Sorting arranges elements into an order, such as increasing numerical order.

Sorting is important because ordered data supports efficient operations, especially binary search.


6. Bogo Sort or Permutation Sort

Basic Idea

Bogo sort repeatedly rearranges the list randomly until the list happens to be sorted.

A deterministic variation, called permutation sort, could examine every possible permutation until it finds a sorted one.

Complexity

The number of possible permutations of nnn elements is:

n!n!n!

Therefore:

  • Best case: O(n)O(n)O(n)
    The first arrangement happens to be sorted, but the algorithm still needs to check it.

  • Average case: Approximately O(n!)O(n!)O(n!)

  • Worst case: Unbounded or effectively unpredictable for random rearrangement, because the algorithm could continue indefinitely.

Factorial growth is extremely rapid. Even modest input sizes make this algorithm impractical.

Bogo sort is useful primarily as a humorous illustration of how poor algorithmic design can produce disastrous complexity.


7. Bubble Sort

Basic Idea

Bubble sort repeatedly compares adjacent elements and swaps them when they are in the wrong order.

For increasing order:

  1. Compare the first two elements.

  2. Swap them if the left element is larger.

  3. Move one position to the right.

  4. Continue comparing adjacent pairs until reaching the end.

  5. Repeat complete passes until a pass occurs with no swaps.

The larger elements gradually move toward the end of the list, as though they are “bubbling” upward.

Example of a Pass

For an adjacent pair:

  • If ai≤ai+1a_i\leq a_{i+1}ai​≤ai+1​, leave them unchanged.

  • If ai>ai+1a_i>a_{i+1}ai​>ai+1​, swap them.

At the end of the first complete pass, the largest element is guaranteed to be at the final position.

At the end of the second pass, the second-largest element is guaranteed to be in the second-to-last position, and so on.

Termination Condition

A Boolean flag can record whether any swap occurred during a pass:

  • Set swap to false before beginning a pass.

  • Set it to true whenever an inversion is found and corrected.

  • If the entire pass finishes without a swap, the list is sorted.

This early stopping condition can make bubble sort faster on already sorted or nearly sorted lists.

Complexity

A pass examines up to nnn elements. In the worst case, up to nnn passes may be necessary.

Thus, the nested structure gives:

O(n)⋅O(n)=O(n2)O(n)\cdot O(n)=O(n^2)O(n)⋅O(n)=O(n2)

The worst-case complexity is:

O(n2)O(n^2)O(n2)

The actual number of passes may be smaller than nnn, but the worst-case order remains quadratic.

Important Property

After each pass:

  • The largest remaining unsorted element is placed in its final position.

  • The sorted region grows from the end of the list.


8. Selection Sort

Basic Idea

Selection sort repeatedly finds the smallest element in the unsorted portion of the list and places it at the beginning of that portion.

The algorithm:

  1. Search the entire list for the smallest element.

  2. Place it in the first position.

  3. Search the remaining unsorted portion for the next-smallest element.

  4. Place it in the second position.

  5. Continue until the entire list is sorted.

Unlike bubble sort, which builds a sorted region at the end, selection sort builds a sorted region at the beginning.

Loop Invariant

A loop invariant is a property that remains true at the beginning of every iteration of a loop.

For selection sort, after the first iii positions have been processed:

  • The prefix containing positions 000 through i−1i-1i−1 is sorted.

  • Every element in the sorted prefix is less than or equal to every element in the remaining suffix.

  • The suffix contains exactly the elements that have not yet been placed.

Proving Correctness

The invariant can be established through induction.

Base Case

Initially, the sorted prefix is empty. An empty list is trivially sorted, and no element in the suffix can violate the condition.

Inductive Step

Assume the invariant is true at the beginning of an iteration.

  1. Find the smallest element in the unsorted suffix.

  2. Move it to the first position of that suffix.

  3. The existing prefix was already sorted.

  4. The newly selected element is no larger than any remaining suffix element.

Therefore, the sorted prefix becomes one element longer while preserving the invariant.

Conclusion

When the suffix is empty, the entire list is sorted.

Complexity

Selection sort makes approximately:

  • nnn comparisons during the first pass,

  • n−1n-1n−1 during the second,

  • n−2n-2n−2 during the third,

  • and so on.

The total number of comparisons is proportional to:

n+(n−1)+(n−2)+⋯+1n+(n-1)+(n-2)+\cdots+1n+(n−1)+(n−2)+⋯+1

This sum grows as:

O(n2)O(n^2)O(n2)

The worst-case complexity is therefore:

O(n2)O(n^2)O(n2)

Selection sort performs a predictable number of passes regardless of whether the list is already nearly sorted.

Comparison with Bubble Sort

  • Bubble sort: Moves large elements toward the end through repeated adjacent swaps.

  • Selection sort: Searches for the smallest remaining element and places it directly into its final position.

  • Both: Have quadratic worst-case complexity, O(n2)O(n^2)O(n2).

  • Selection sort: Builds the sorted region at the front.

  • Bubble sort: Builds the sorted region at the end.


9. Merge Sort

Divide-and-Conquer Strategy

Merge sort uses the divide-and-conquer approach:

  1. Divide a large problem into smaller subproblems.

  2. Solve the smaller subproblems recursively.

  3. Combine their solutions into the solution to the original problem.

For merge sort:

  • The division step splits the list into two smaller lists.

  • The recursive calls sort the two lists.

  • The merge step combines the two sorted lists.

Base Case

A list with zero or one element is already sorted.

Therefore:

  • An empty list is returned unchanged or copied.

  • A one-element list is returned unchanged or copied.

Recursive Process

For a list with more than one element:

  1. Find the midpoint.

  2. Split the list into left and right halves.

  3. Recursively sort the left half.

  4. Recursively sort the right half.

  5. Merge the two sorted halves.

The list continues to split until every sublist contains at most one element.


10. The Merge Operation

Basic Idea

The merge operation combines two already sorted lists into one sorted list.

Suppose the two lists are:

  • left

  • right

The algorithm:

  1. Look at the first remaining element of each list.

  2. Compare them.

  3. Copy the smaller element into the result.

  4. Advance the position in the list from which the element was taken.

  5. Repeat while both lists still contain elements.

  6. Copy the remainder of whichever list is not empty.

Why Merging Is Efficient

Because both input lists are already sorted, the smallest remaining element must be at the front of one of the two lists. There is no need to search through the interior of either list.

Each element is copied into the result once. If the two lists together contain nnn elements:

  • The copying work is O(n)O(n)O(n).

  • The number of comparisons is also O(n)O(n)O(n).

Thus, merging two sorted lists takes linear time:

O(n)O(n)O(n)

Index-Based Implementation

A typical implementation maintains:

  • A result list

  • Index iii for the left list

  • Index jjj for the right list

The comparison continues while:

i<length(left)i<\text{length(left)}i<length(left)

and

j<length(right)j<\text{length(right)}j<length(right)

When one list is exhausted, the remaining elements of the other list are appended directly.

The merge step is efficient because each list is scanned only once from beginning to end.


11. Merge Sort Complexity

Work at Each Level

At the top level, the original list has nnn elements. Merging the two sorted halves requires:

O(n)O(n)O(n)

At the next level, there are four sublists, each of size approximately n4\frac{n}{4}4n​. The total number of elements processed across all merges is still nnn, so the work at that level is also:

O(n)O(n)O(n)

This remains true at every level:

  • More subproblems appear.

  • Each subproblem becomes smaller.

  • The total number of elements processed at one level remains proportional to nnn.

Number of Levels

The list is repeatedly divided by two:

n,n2,n4,…,1n,\frac{n}{2},\frac{n}{4},\ldots,1n,2n​,4n​,…,1

The number of division levels is:

O(log⁡n)O(\log n)O(logn)

Total Complexity

There are O(log⁡n)O(\log n)O(logn) levels, each requiring O(n)O(n)O(n) work:

O(n)⋅O(log⁡n)=O(nlog⁡n)O(n)\cdot O(\log n)=O(n\log n)O(n)⋅O(logn)=O(nlogn)

Therefore, merge sort has worst-case complexity:

O(nlog⁡n)O(n\log n)O(nlogn)

This is substantially better than the quadratic complexity of bubble sort and selection sort for large lists.

Why It Is Called Log-Linear

Merge sort combines:

  • A linear amount of work at each level, O(n)O(n)O(n).

  • A logarithmic number of levels, O(log⁡n)O(\log n)O(logn).

Their product gives the log-linear complexity:

O(nlog⁡n)O(n\log n)O(nlogn)

12. Comparing the Sorting Algorithms

Bogo Sort

  • Approach: Randomly rearrange elements until sorted.

  • Best case: O(n)O(n)O(n).

  • Average case: Approximately O(n!)O(n!)O(n!).

  • Worst case: Unbounded or unpredictable.

  • Practicality: Not practical.

Bubble Sort

  • Approach: Repeatedly swap adjacent elements that are out of order.

  • Worst-case complexity: O(n2)O(n^2)O(n2).

  • Strength: Simple and may stop early when the list is already sorted.

  • Weakness: Performs poorly on large lists.

Selection Sort

  • Approach: Repeatedly select the smallest remaining element.

  • Worst-case complexity: O(n2)O(n^2)O(n2).

  • Strength: Simple and predictable.

  • Weakness: Must repeatedly scan the unsorted suffix.

Merge Sort

  • Approach: Divide the list recursively, then merge sorted sublists.

  • Worst-case complexity: O(nlog⁡n)O(n\log n)O(nlogn).

  • Strength: Efficient worst-case performance.

  • Weakness: Requires additional work and structure for merging sublists.

For sufficiently large inputs, merge sort is substantially more efficient than quadratic sorting methods.


13. Why O(nlog⁡n)O(n\log n)O(nlogn) Sorting Matters for Searching

Sorting cannot generally be performed in less than linear time because every element must be examined at least once.

However, merge sort performs the sort in:

O(nlog⁡n)O(n\log n)O(nlogn)

This cost is low enough to be worthwhile when the list will be searched many times.

For kkk searches:

  • Sorting once and using binary search:

O(nlog⁡n)+O(klog⁡n)O(n\log n)+O(k\log n)O(nlogn)+O(klogn)
  • Using linear search every time:

O(kn)O(kn)O(kn)

As kkk becomes large, the repeated linear searches dominate the second expression. Sorting once and then using binary search becomes more efficient.

The overall strategy is therefore:

  1. Sort the collection once.

  2. Perform many fast binary searches.

  3. Amortize the initial sorting cost across all searches.


14. Broader Computational Ideas

The study of searching and sorting illustrates several general approaches to computational problem solving.

Data Structures as Knowledge Representations

Data structures provide ways to represent information so that it can be processed effectively.

Examples include:

  • Tuples

  • Lists

  • Dictionaries

  • Classes

  • More complex structures built from simpler components

The choice of data structure affects which operations are easy or expensive.

Iteration and Loops

Iteration expresses repeated computation.

Examples include:

  • Scanning a list during linear search

  • Repeatedly comparing adjacent elements in bubble sort

  • Examining the unsorted suffix in selection sort

  • Repeatedly merging sublists in merge sort

Understanding how many times a loop executes is essential for determining complexity.

Recursion

Recursion solves a problem by applying the same procedure to smaller versions of the problem.

Merge sort is a central example:

  • A list is divided into smaller lists.

  • Each smaller list is sorted using the same algorithm.

  • The sorted solutions are merged.

A recursive algorithm requires:

  • A clearly defined base case.

  • A recursive step that makes progress toward that base case.

Without a base case, recursion can continue indefinitely.

Abstraction

Abstraction hides implementation details behind a usable interface.

A procedure or method can be treated as a contract:

  • The caller provides specified inputs.

  • The procedure performs its internal computation.

  • The caller relies on the promised output without needing to know every implementation detail.

This allows complex programs to be divided into manageable components.

Classes and Methods

Classes combine:

  • Data

  • Operations that act on that data

They provide a way to modularize systems and organize related behavior. This supports the construction of larger programs from reusable components.


15. Computational Thinking

Computational thinking is a way of approaching problems using ideas from computer science. It is not limited to programming; it can be applied to biology, chemistry, mathematics, physics, engineering, and many other fields.

Three central components are:

Abstraction

Abstraction identifies the essential structure of a problem while setting aside unnecessary details.

Questions include:

  • What information matters?

  • Which details can be ignored?

  • How can the problem be represented in a simpler form?

  • Can the problem be decomposed into meaningful components?

For example, a sorting algorithm does not need to know what a number represents. It only needs a rule for comparing two elements.

Automation

Automation converts an abstract solution into a sequence of operations that a machine can execute.

This involves:

  • Expressing the process precisely.

  • Defining each required step.

  • Translating the steps into a programming language.

  • Ensuring that the computer can carry them out consistently.

Algorithms

An algorithm is a precise procedure for solving a problem.

Writing an algorithm forces the problem solver to clarify:

  • What the inputs are.

  • What the output should be.

  • Which operations are needed.

  • How the process terminates.

  • How efficiently the process runs.

Algorithms are therefore both computational tools and methods for organizing thought.

Computational thinking combines abstraction, automation, and algorithmic reasoning.


16. Decomposition and Divide-and-Conquer Thinking

A difficult problem can often be made manageable by breaking it into smaller versions of itself.

The divide-and-conquer pattern consists of:

  1. Divide: Break the original problem into smaller subproblems.

  2. Conquer: Solve each subproblem, often recursively.

  3. Combine: Construct the complete solution from the smaller solutions.

Merge sort demonstrates this pattern directly:

  • Divide the list into halves.

  • Recursively sort each half.

  • Combine the sorted halves through merging.

This approach is powerful because smaller instances may be easier to solve, and the solutions can often be combined efficiently.


17. Problem Difficulty and Algorithm Choice

Different problems and different solutions have different inherent computational costs.

A problem-solving process should therefore include:

  1. Identifying the problem structure.

  2. Choosing an appropriate representation.

  3. Selecting an algorithmic strategy.

  4. Analyzing the algorithm’s complexity.

  5. Comparing possible approaches.

  6. Choosing an algorithm that remains practical as input size grows.

The main goal is not merely to find an algorithm that works, but to find one that works efficiently.

For example:

  • Linear search is appropriate when the list is unsorted or only searched once.

  • Binary search is preferable for repeated searches on sorted data.

  • Bubble sort or selection sort may be acceptable for small lists or instructional purposes.

  • Merge sort is preferable when reliable O(nlog⁡n)O(n\log n)O(nlogn) worst-case sorting performance is needed.

Effective computational problem solving requires both correctness and efficiency.


18. Central Takeaways

  • Linear search works on unsorted lists but has worst-case complexity O(n)O(n)O(n).

  • Binary search requires a sorted list and has complexity O(log⁡n)O(\log n)O(logn).

  • Sorting is worthwhile when a collection will be searched repeatedly.

  • Bogo sort demonstrates factorial or unbounded behavior and is not practical.

  • Bubble sort repeatedly swaps adjacent out-of-order elements and has worst-case complexity O(n2)O(n^2)O(n2).

  • Selection sort repeatedly places the smallest remaining element and has complexity O(n2)O(n^2)O(n2).

  • Merge sort uses divide and conquer and has complexity O(nlog⁡n)O(n\log n)O(nlogn).

  • Merging two sorted lists takes linear time because each element is processed in order.

  • Loop invariants and induction can be used to prove that an algorithm is correct.

  • Abstraction, recursion, decomposition, and complexity analysis are fundamental computational thinking tools.

  • Good algorithms are evaluated not only by whether they produce the correct answer, but also by how their costs grow as the input becomes larger.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent