The distance from a point to a line segment [duplicate]
Let the line segment be described by two points $s_1,s_2$, and you wish to find the nearest point on the segment to the point $p$.
We find the nearest point to the line through $s_1,s_2$, then 'project' back to the segment, then compute the distance.
A point on the line can be parameterized by $s(t) = s_1+t(s_2-s_1)$, note that $s(t)$ is on the line segment iff $t \in [0,1]$. The distance from $p$ to the point $s(t)$ given by the function $\phi(t)= \|s(t)-p\|$. It is easier to deal with $\phi^2$, which is a convex quadratic in $t$.
To find the minimizing '$t$', we set the derivative of $\phi^2$ to zero giving $\hat{t} = \frac{\langle p-s_1, s_2-s_1\rangle}{\|s_2-s_1\|^2}$. To find the $t$ that minimizes the distance on the segment, we 'project' back to $[0,1]$ using $t^* = \min(\max(\hat{t},0),1)$. Then the minimum distance is given by $\|s(t^*)-p\|$.
Addendum:
Note that $\phi(t)^2 = \phi(\hat{t})^2+(t-\hat{t})^2 \|s_2-s_1\|^2$.
Hence the minimum distance will correspond to the value of $t \in [0,1]$ that results in the smallest $(t-\hat{t})^2$. It is straightforward to see that this is given by $t^*$ above.
Edit: this is indeed a duplicate, I had not read the question carefully enough. Below is how you compute the distance from a point to a line, which is the major bulk when computing the distance from a point to a line segment.
Let us assume we are in $\mathbb{R}^n$ ($n\geq 2$) equipped with its usual Euclidean inner product $(x,y)=\sum_{k=1}^nx_ky_k$.
Let $L$ be a line parameterized by $$ t\longmapsto P+t\vec{u} $$ where $P$ is a point belonging to this line and $\vec{u}$ is a vector giving the direction of $L$. If you know two points $P,P'$ on the line, it suffices to take $P$ and $\vec{u}=\vec{PP'}$.
Now let $Q$ be any point. The distance $Q$ to $L$ is the distance between $Q$ and $Q_L$ its orthogonal projection on $L$. Now $Q_L$ is characterized by the vector projection formula: $$ \vec{PQ_L}=\frac{(\vec{PQ_L},\vec{u})}{\|\vec{u}\|^2}\vec{u}. $$ So $$ \vec{QQ_L}=\vec{QP}+\vec{PQ_L}=\vec{QP}+\frac{(\vec{PQ_L},\vec{u})}{\|\vec{u}\|^2}\vec{u}. $$ It only remains to compute the norm of the latter to get the distance from $Q$ to $L$.
Note: when $n=2$ and $L$ is given by a cartesian equation $ax+by+c=0$, this yields the formula $$ d(P,L)=\frac{|ax+by+c|}{\sqrt{a^2+b^2}} $$ for every $P=(x,y)$.
Algorithm to compute the distance from $Q$ to the line segment $[P,P']$: Take an arbitrary point $Q$. Compute the coordinates of the projection $Q_L$ on the line (which does not necessarily belong to the segment). Compute $d(Q,Q_L)=\|\vec{QQ_L}\|$ the distance between $Q$ and $Q_L$. Also compute the distances $d(Q,P)$ and $d(Q,P')$ to the endpoints. Then the number you are looking for (the distance from $Q$ to $[P,P']$) is the minimum of these three numbers: $d(Q,Q_L)$, $d(Q,P)$ and $d(Q,P')$.