To obtain the first and third quartiles in Ada, sort the sample in ascending order, then compute the position of each quartile in the sorted array. The lower quartile (Q1) sits at index (n−1)/4 and the upper quartile (Q3) at 3(n−1)/4, using zero-based positions. When a position lands between two elements, interpolate linearly between them. Ada has no built-in statistics library in its standard library, so you write these steps yourself on top of Ada.Containers.Vectors or a plain array. The two details that decide whether your answer matches other tools are the position formula and the handling of zeros, both covered below.
This guide walks through one complete, compilable implementation, then examines the choices that make quartile code disagree across libraries: which position definition you use, how interpolation works, and how integer arithmetic can quietly wreck your results. The reference date is November 13, 2026; the language constructs described are stable across Ada 2012 and Ada 2022, so nothing here depends on a compiler release you may not have.
Defining the quartile and the position formula
A quartile is a value that divides an ordered data set into four parts with roughly equal counts. The median (Q2) splits the data in half; Q1 is the median of the lower half and Q3 the median of the upper half. That textbook phrasing hides a real ambiguity: when the count is odd, does the median belong to both halves, one half, or neither? Different conventions answer that question differently, which is why the same ten numbers can yield two different Q1 values in two different programs.
The cleanest way to remove the ambiguity is to express each quartile as a fractional position in the sorted array and then interpolate. With n observations sorted ascending and indexed 0 through n−1, define:
position_low = (n − 1) × 0.25 position_high = (n − 1) × 0.75
The quartile value is then the value at that fractional index: take the whole part as an index i, the fractional part as f, and return value(i) + f × (value(i+1) − value(i)). When f is zero you simply return value(i). This is the method most statistical software calls the "linear interpolation" or type-7 definition, and it is the one R, NumPy, and Excel's QUARTILE.INC function produce. It is also the method the implementation below follows.
For n = 10, position_low = 2.25 and position_high = 6.75, so Q1 interpolates a quarter of the way from the third to the fourth sorted value, and Q3 three-quarters of the way from the seventh to the eighth. For n = 4, position_low = 0.75 and position_high = 2.25. For n = 5, the positions are 1.0 and 3.0, so no interpolation happens and the quartiles are the second and fourth sorted values. That last case is worth remembering as a sanity check: with an odd count the middle value always falls exactly on an integer position for Q2, and for n = 5 the quartiles happen to land on integers too.
Keep the definition in one named function or constant so the rest of your code cannot drift from it. If you later must match a system that uses a different convention, you change one place, not every call site.
Prerequisites before you write the quartile code
You need three things in place before the quartile routine makes sense.
First, a container for the sample. Your options are a constrained array indexed by a subtype whose bounds you know at compile time, an unconstrained array parameter, or Ada.Containers.Vectors if the count is unknown until runtime. Vectors are the usual choice for data read from a file or produced by another computation.
Second, a numeric element type with enough precision. Float (roughly six decimal digits) is often too coarse for data with large magnitudes or fine gradations; Long_Float or a decimal fixed-point type is safer. The interpolation multiplies a small fraction by a difference of two values, so precision loss shows up mainly in that subtraction and multiplication, not in the division by four.
Third, a sorting routine. Ada's standard library does not sort containers, but Ada.Containers.Generic_Array_Sort and Ada.Containers.Generic_Constrained_Array_Sort are generic procedures in the language standard that sort any array of a discrete-indexed type given a comparison. For a vector, the practical route is to copy its elements into an array, sort the array, and run the quartile computation over it. That keeps the code simple and avoids writing your own sort for a task that recurs constantly.
One prerequisite deserves emphasis: decide, before writing code, whether your sample is the whole population or a sample drawn from a larger one. The quartile values are the same either way—the positions depend only on n—but if you ever extend this code to variance or standard deviation, the divisor differs (n versus n−1). Mixing the two conventions inside one program is a common source of numbers that "look wrong" but are arithmetically consistent with a different choice.
The quartile algorithm, step by step
The procedure below is the whole answer to the query. Read it as a sequence you can test in pieces.
1: Collect the sample into an array. Every value participates; do not pre-filter or round before computing positions, because dropping points changes n and therefore changes both positions. Decide up front how to handle missing values—either remove them and document that n is the count of valid observations, or substitute a defined value—and never silently treat a missing value as zero.
2: Sort ascending. Use the generic sort on the array. Sorting is the only step whose cost dominates: O(n log n) comparisons. If the data is already sorted, skip this step, but only if you can prove it; a wrongly assumed sorted input produces nonsense quartiles that look plausible.
3: Compute the two fractional positions. With n as the element count, low = (n − 1) × 0.25 and high = (n − 1) × 0.75. In Ada, perform this in floating point or fixed point, not by integer division, for reasons explained in the next section.
4: Split each position into an integer index and a fraction. For position p, index i = floor(p) and fraction f = p − i. Because the largest position is 3(n−1)/4 < n−1 for n ≥ 1, i is always a valid index and i+1 is either valid or exactly n−1, the last element. Guard n = 1 separately because (n−1) is zero and both positions are zero.
5: Interpolate. Return value(i) + f × (value(i+1) − value(i)). Cast the fraction to the element type before multiplying if the element type is not itself floating point; mixing a Float fraction with a Long_Float difference forces an unwanted conversion.
6: Check the result. The invariants are simple and catch most mistakes: Q1 ≤ Q2 ≤ Q3, all three lie between the sample minimum and maximum, and for an odd n with the middle value pinned, Q2 equals the sorted middle value exactly. For n = 4 the result should be the 0.75 and 2.25 interpolations; test that case by hand once.
Success looks like a function that returns two values (typically as a record or as two out parameters) and passes your hand-checked cases. Failure shows up as Q1 above Q3, as a result outside the sample range, or as an index check failure—each points to a different step, which is why the invariants are worth asserting in a debug build.
A complete Ada implementation
The following package specification and body compile under Ada 2012 and Ada 2022 with a typical GNAT toolchain. It uses a vector of Long_Float values, sorts a copy, and returns a record holding both quartiles.
A few notes on the choices in that listing, because they matter more than they look.
Copying the vector into a constrained array lets you reuse the generic sort without writing a comparator-based vector sort. The copy costs O(n) memory and time, negligible beside the O(n log n) sort. The array is indexed from 1 to N, which makes the position arithmetic in Interpolate straightforward, but it means the integer floor must be clamped to at least 1 so a zero position (n = 1 or n = 2) does not index out of range; the Natural'Max handles that. The Natural'Min on Next guards the other end, where a position equal to n−1 would otherwise demand index n, which does not exist.
The Ascending function uses < rather than <=. For quartile work the difference only matters when the sample contains duplicates, and even then the sorted order and the interpolated values are identical; stability is irrelevant. Using < is slightly cheaper and avoids a comparison in the exchange.
A caller might look like this, feeding four hard-coded values whose Q1 and Q3 can be verified by hand:
With n = 4, positions are 0.75 and 2.25, so Q1 = 1 + 0.75×(2−1) = 1.75 and Q3 = 3 + 0.25×(4−3) = 3.25. Run that case first whenever you change the interpolation code; it exercises the fractional path, which is where bugs live. The exact assignment above would fail a style check that forbids use clauses, and in real code you would call Data.Append (1.0) with the indexed form or a loop, but the arithmetic is the point.
Why integer division breaks quartiles
The most common failure in home-grown quartile code is computing the position with integer arithmetic and silently truncating. Suppose n = 10. Integer division (n − 1)/4 gives 9/4 = 2, and the code then reports the third sorted value as Q1—ignoring the 0.25 fractional part entirely. For n = 6, (n − 1)/4 = 5/4 = 1, and the code reports the second value instead of interpolating 25 percent of the way between the second and third. The reported numbers are always actual sample values, which makes them look trustworthy; they are simply the wrong definition.
There is a second, subtler trap in the same area. If you multiply first and divide later to keep precision—for example (3 × (N − 1)) / 4 in integer arithmetic—you get an integer index for Q3, again discarding the interpolation. The fix is not to reorder the integer operations but to leave integer arithmetic behind: convert n to Long_Float once, multiply by 0.25 or 0.75, and keep the result as a real number until you split it. The split itself is where floor and fraction are separated deliberately, not accidentally.
A third variant bites people who compute the quartile index as n/4 or (n+1)/4. Those formulas belong to other conventions and, combined with integer truncation, produce values that match neither the interpolation method nor the nearest-rank method consistently. If you are porting code from another language, port the formula first and test it against known inputs before trusting any output.
Fixed-point arithmetic is a legitimate alternative if your data is decimal fixed point, but remember that the fraction 0.25 is exact in both binary floating point and decimal fixed point, while 0.1 and 0.75 times certain differences may round. For quartiles specifically, the fractions are always k/4 with k in {0,1,2,3}, so the multiplication is exact in binary floating point as long as the difference itself is exact. That is a small comfort: the subtraction of two nearby large values can still lose digits, which is why Long_Float is the safer default for mixed-magnitude data.
Alternative quartile conventions and how to match another tool
The interpolation method above is not the only defensible definition, and knowing the alternatives prevents a long afternoon of debugging when your Ada output must match a report produced elsewhere.
The nearest-rank method treats Q1 as the value at the smallest index whose cumulative count reaches 25 percent of n, with no interpolation at all. It is simple and always returns an observed value, which is desirable when the data is categorical or when reported quartiles must be actual measurements. It differs from interpolation on almost every sample whose positions are not integers.
The median-of-halves method splits the sorted data at the median, includes or excludes the median according to a stated rule, and takes the median of each half. For even n it agrees with interpolation in many cases; for odd n the inclusion rule creates the disagreement mentioned earlier. The textbook version that excludes the median from both halves and the version that includes it in both produce different Q1 and Q3 for the same odd-sized sample.
Excel exposes the distinction directly: QUARTILE.INC uses the inclusive interpolation method described here, while QUARTILE.EXC uses a variant based on (n+1) positions that cannot return a value below the minimum for small samples and differs from INC except at certain sizes. If your Ada code must reproduce a spreadsheet, identify which function the spreadsheet used and encode that formula, not the one in this article, in the single position function.
The practical advice is to treat the position formula as configuration. Name it (Interpolated_Positions, Nearest_Rank, Median_Of_Halves), implement each as a small function returning the two fractional positions or directly the two values, and select one at the call site. Tests then pin each variant against hand-computed cases, and the rest of the program never needs to know which convention is active.
Worked examples and hand checks
Three examples cover the cases that matter and give you regression tests.
For the sample 4, 7, 13, 16 (n = 4), positions are 0.75 and 2.25. Sorted, the values are 4, 7, 13, 16. Q1 = 4 + 0.75×(7−4) = 6.25. Q3 = 13 + 0.25×(16−13) = 13.75. The median is 10. Any implementation that returns 4 and 13 is using nearest-rank; one that returns 5.5 and 14.5 is doing something else again.
For the sample 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 (n = 10), positions are 2.25 and 6.75. Q1 = 3 + 0.25×(4−3) = 3.25. Q3 = 7 + 0.75×(8−7) = 7.75. These are the values R and NumPy report for this vector under their default quantile type, which makes the example a cross-check rather than only a self-check.
For the sample 2, 4, 4, 4, 5, 5, 7, 9 (n = 8), positions are 1.75 and 5.25. Q1 = 4 + 0.75×(4−4) = 4. Q3 = 5 + 0.25×(7−5) = 5.5. The duplicate values make the interpolation trivially exact on the lower side, which is exactly the case where a buggy fraction would be invisible; include a duplicate-heavy sample in your tests precisely because it hides errors elsewhere.
A quick arithmetic check you can do mentally: the median of an even-sized sorted sample under this convention is (value at (n−1)/2 plus value at (n+1)/2) ÷ 2, which for n = 4 is (7+13)/2 = 10, matching. If your Q2 disagrees with that formula, Q1 and Q3 are suspect too.
Edge cases, performance, and where to stop
Small samples need explicit handling. n = 0 is an error: there is no quartile of nothing, and the routine should raise rather than return a sentinel. n = 1 returns the single value for all three quartiles. n = 2 gives positions 0.25 and 0.75, so Q1 and Q3 interpolate toward the two values; Q1 = v0 + 0.25×(v1−v0) and Q3 = v0 + 0.75×(v1−v0). n = 3 gives positions 0.5 and 1.5, so Q2 is exactly the middle value and Q1 and Q3 are midpoints between adjacent values.
Samples containing NaN or infinity are a separate problem: sorting comparisons involving NaN are unordered, so a NaN can land anywhere in the array and corrupt every position after it. Filter non-finite values before sorting, and document that n counts only the remaining observations. Negative zero compares equal to positive zero in Ada, so it causes no trouble.
Performance is dominated by the sort. For a million values, expect the generic sort to take on the order of tens of millions of comparisons—well under a second on a modern desktop—and the quartile computation itself to be effectively free. If you call Compute repeatedly on overlapping windows of one large data set, the sort is what to optimize: sort once, then compute positions over index ranges rather than re-sorting each window. Do not bother optimizing the interpolation; it is a handful of operations.
Where should you stop and hand off? If the data requires weighted observations, stratified groups, or frequency tables where each value stands for many cases, the simple position formula no longer applies, and the correct approach is an expanded or weighted quantile computation that a statistics package documents in detail. Likewise, if the numbers feed into a regulatory report or a published statistic, confirm the required convention with the body that defines it before choosing a formula; the difference between conventions can exceed the precision your report promises. That is a question for the statistician or the reporting authority, not something to settle by trying formulas until one looks right.
A final safeguard: expose the sorted sample and the computed positions from your function in a debug mode, so that when a number looks odd you can see whether the position or the interpolation is responsible. It costs a few lines and turns a mysterious wrong answer into an obvious one.
Frequently asked questions
Can I compute quartiles without sorting in Ada? Not correctly for the general case. Selection algorithms can find the k-th smallest element in linear time, which is faster than sorting when you need only a few order statistics, but the interpolation needs the neighbors of the fractional position, so you would select several ranks, and the complexity of getting the bookkeeping right usually exceeds the savings. Sort, or use a partial sort if your vendor's container library offers one.
Does Ada 2022 change anything here? The generic array sorts, containers, and floating-point facilities used above all exist in Ada 2012 and carry into Ada 2022. Ada 2022 adds container aggregates and more expressive iterator syntax, which can shorten the copy loop, but the quartile arithmetic and the formula are unchanged. Nothing in this guide depends on a feature added after Ada 2012.
How do I handle missing values? Remove them before the computation and set n to the number of remaining valid observations, or define a documented substitution. Do not let a missing marker such as a sentinel like −9999 enter the sort, because it will sort to the bottom and shift both positions; and do not pad with zeros, because zeros are real observations that change quartiles. Record the excluded count alongside the result so readers know the denominator.
Why does my Q1 match Excel's QUARTILE.INC but not QUARTILE.EXC? Because the two functions use different position formulas. INC uses the (n−1) interpolation described in this article; EXC places positions differently and is designed so the result never falls outside the observed range for small samples. Pick the one your audience uses, encode it in the position function, and state the choice in your documentation—matching the spreadsheet is a specification, not a bug fix.