Hi there! The problem for today required me to find the quartiles of set of data values. The concept is actually new to me but, once I learned it, it resembled a lot the median of a data set. Actually, the second quartile $Q_2$ is the median itself, while the other two quartiles, $Q_1$ and $Q_2$, are basically medians of sub datasets divided around the second quartile. The three quartiles divide the data in four regions instead of two regions using only the median.

The input for the program is n, the size of the data set, and then n integers are fed from the standard input. The input is always given such that the output quartiles are integers as well. My solution included a getMedian function that I used to get the quartiles for a subset of the data. Initially I tried to just use some if-else logic without calling this external function, but it was not working and was clumsy. My solution is given below.

package main

import (

// assumes `a` is already sorted
func getMedian(a []int) int {
  n := len(a)
  if n%2 == 0 {
    return (a[n/2] + a[n/2-1]) / 2
  return a[n/2]

func main() {

  N := 0
  fmt.Scanf("%d", &N)

  // allocate memory
  a := make([]int, N)

  // read numbers from stdin
  for i := 0; i < N; i++ {
    fmt.Scanf("%d", &a[i])

  // sort

  var Q1, Q2, Q3 int

  // get quartiles
  Q2 = getMedian(a)
  if N%2 == 0 {
    Q1 = getMedian(a[0 : N/2])
    Q3 = getMedian(a[N/2:])
  } else {
    Q1 = getMedian(a[0 : N/2])
    Q3 = getMedian(a[N/2+1:])
  fmt.Printf("%d\n%d\n%d\n", Q1, Q2, Q3)

That’s all for this post! Thanks for reading!