Ranking charts in Matplotlib - Time & Space Complexity
When creating ranking charts, we want to know how the time to draw the chart changes as the data grows.
We ask: How does the chart drawing time grow when we add more items to rank?
Analyze the time complexity of the following code snippet.
import matplotlib.pyplot as plt
values = [5, 3, 9, 1, 7]
labels = ['A', 'B', 'C', 'D', 'E']
sorted_pairs = sorted(zip(values, labels), reverse=True)
sorted_values, sorted_labels = zip(*sorted_pairs)
plt.bar(sorted_labels, sorted_values)
plt.show()
This code sorts data by value and then draws a bar chart showing the ranking.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Sorting the list of values and labels.
- How many times: Sorting compares elements multiple times, depending on the number of items.
As the number of items to rank grows, the sorting work grows faster than just counting items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 30 comparisons |
| 100 | About 700 comparisons |
| 1000 | About 10,000 comparisons |
Pattern observation: The number of operations grows faster than the number of items, roughly multiplying by n log n.
Time Complexity: O(n log n)
This means the time to create the ranking chart grows a bit faster than the number of items, because sorting takes more work as data grows.
[X] Wrong: "Sorting the data takes the same time no matter how many items there are."
[OK] Correct: Sorting compares many pairs of items, so more items mean more comparisons and longer time.
Understanding how sorting affects chart drawing helps you explain performance in real projects and shows you can think about efficiency clearly.
"What if we already had the data sorted? How would the time complexity change when creating the ranking chart?"