Data Science
Percentiles & Quartiles
Sorting the data dominates the cost — O(n log n) time. Once sorted, computing any single percentile takes O(1) time.
The idea, in plain English
Imagine every runner in a marathon lined up from slowest to fastest, and someone tells you 'you finished in the 90th percentile.' That means 90% of runners were slower than you. You beat 90 out of every 100 people. A percentile just tells you where one value sits compared to everyone else, once everything is sorted. Quartiles are just percentiles cut into quarters. Q1 is the 25th percentile (a quarter of the way through). Q2 is the 50th percentile (the median, halfway through). Q3 is the 75th percentile (three-quarters of the way through).
How it works
- 1Sort all the values from smallest to largest.
- 2To find the value at percentile p, work out its 'rank' first. The rank is the position that is p percent of the way through the sorted list, counting from the first item.
- 3If that rank falls exactly on an item, that item is your answer. If it falls between two items, blend them proportionally (this is called interpolation) to get a value in between.
- 4Q1, Q2 (the median), and Q3 are just this same percentile calculation run at p = 25, 50, and 75.
When you'd use it
Use percentiles whenever 'average' does not tell the whole story. For example, when reporting website load times, the 95th percentile shows how bad the worst experiences get, which the mean would hide. Percentiles are also useful for grading on a curve. Quartiles specifically are the backbone of the box plot and the interquartile range (IQR), a robust way to measure spread that ignores extreme outliers.
Common beginner mistakes
- Do not forget to sort first. Percentiles and quartiles are meaningless on unsorted data.
- Do not assume every percentile lands exactly on a data point. It often falls between two values, and you need to interpolate rather than just round to the nearest one.
Try it — edit and run
Click the code to edit · press ⌘/Ctrl+↵ to run
Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.
Data: 8 21 5 14 7 18 3 13 12
Sorted: 3 5 7 8 12 13 14 18 21
Q1 (25th pct): 7.00
Q2 / Median (50th pct): 12.00
Q3 (75th pct): 14.00
IQR (Q3 - Q1): 7.00
90th percentile: 18.60Not sure this is the right topic? See the learning paths → or where this leads →