I have an algorithm called MinDistance that determines the distance between the two closest elements in an array. I need to make it more efficient.
Here is the algorithm, written in pseudocode:
MinDistance(A[0...n-1]
dmin <-- infinity
for i <--- 0 to n - 1 do
for j <--- 0 to n - 1 do
if i does not equal j and |A|i| - A|j|| < dmin
dmin <--- |A|i| - A|j||
return dmin
To me, this feels like it's in its most efficient form, but I'm wrong. Can you help?
Thank you very much.
This solution takes an n-squared algorithm for finding the two closest elements in an array and shows how that algorithm can be converted to a much faster algorithm.