The function
$$f(b)=|b-a|$$ is piecewise linear with a slope $-1$ for $b<a$ and $+1$ for $b>a$.
So a sum like
$$\sum_{k=1}^n|b-a_k|$$ is piecewise linear, with changes of slope at every $a_k$. And the slope at a given point $b$ is the difference of the number of $a_k$ values to its right and the number of $a_k$ values to its left.
(In fact the derivative rule works, with
$$f'(b)=\sum_{k=1}^n\text{sgn}(b-a_k),$$
though as it is not defined at the $a_k$, you need to find the global change of sign instead.)
Hence, the minimum is achieved "in the middle". Depending on the parity of $n$, the minimum is a single point or an interval. (Check the slopes $-3,-1,1,3$ and $-4,-2,0,2,4$.)

The quadratic case is somewhat easier, as the quadratic trinomials add up.
$$\sum_{k=1}^n(b-a_k)^2=nb^2-2\sum_{k=1}^na_k\,b+\sum_{k=1}^na_k^2.$$
You can find the minimum by differentiating.
$$2nb-2\sum_{k=1}^na_k=0\implies b=\dfrac1n\sum_{k=1}^na_k.$$
Or by completing the square.