Explore BrainMass

Explanation of how to make an algorithm more efficient

This content was COPIED from BrainMass.com - View the original, and get the already-completed solution here!

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:

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.

© BrainMass Inc. brainmass.com March 21, 2019, 4:57 pm ad1c9bdddf

Solution Preview

There are a couple things that can make this algorithm more efficient. First, calculating the distance between the two elements can be done in one place and stored in a variable. Then that variable can be used for ...

Solution Summary

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.