i was thinking about finding a $x$ that minimize the function $f(x)=\sum_{i=0}^{n}|x-a_i|$. I plot this function in geogebra (here is the url) and i saw that the function have an x that minimize it when n is odd, we can see that the minimum turn into a range when we add another absolute difference.
How can we we find the a x that minimize the function givin a odd $n$ and how can we prove that it only exists for odd $n$, ?? And if n is even, can we find the range for x such that for all x in this range f(x) = min f(x)
This was trickier than i expected this to be:
As you probably noticed from your plot, this function is piecewise linear, the nonlinearity points being the points $a_i$. This directly implies that the minimum will be attained at one of the points $a_i$.
From intuition i would say, that, if the $a_i$ were sorted, the minimum would be attained at the median of the points.
Without loss of generality we may assume that all the $a_i$s are sorted in ascending order and $> 0$. Since the minimum is attained at one of the $a_i$, we only have to consider $f(a_k)$ for $k = 1, .., n$. We have: \begin{align} f(a_k) &= \sum_{i = 1}^{k - 1} a_k - a_i + \sum_{i = k + 1}^n a_i - a_k \\ &= \sum_{i = 1}^{k - 1} - a_i + \sum_{i = k+ 1}^n a_i + ((k-1) - (n - k)) a_k \\ &= \sum_{i = 1}^{k - 1} - a_i + \sum_{i = k+ 1}^n a_i + (2k - n - 1) a_k \end{align} Consider the difference $d_k = f(x_k) - f(x_{k + 1})$. We have \begin{align} d_k &= \sum_{i = 1}^{k - 1} - a_i + \sum_{i = k+ 1}^n a_i + (2k - n - 1) a_k\\ &\ - \left(\sum_{i = 1}^{k} - a_i + \sum_{i = k+ 2}^n a_i + (2(k + 1) - n - 1) a_{k+1}\right) \\ &= a_k + a_{k + 1} + (2k - n - 1) a_k - (2k - n + 1) a_{k+1} \\ &= (2k - n)a_k - (2k - n)a_{k + 1}. \end{align} Since $f$ is convex and the $a_i$ are ordered, the minimum will be attained at $a_k$, where $k$ is the smallest integer, such that $d_k \le 0$. This is equivalent to $(2k - n) a_k \le (2k - n) a_{k + 1}$. As the $a_k$ are ordered and $> 0$, this is only possible if $2k - n \ge 0$. Therefore the minimum is attained at $a_k$ for $k$ being the smallest integer $k$, such that $2k \ge n$, this is $k = \lceil \frac n 2 \rceil$.
Note that if $n$ is odd, we always have $d_k < 0$ or $d_k > 0$. For even $n$ we have with $k = \frac n 2$: $d_k = 0$. This explains your observation for even $n$.