<p>I have an array (<code>arr</code>) of elements, and a function (<code>f</code>) that takes 2 elements and returns a number.</p>

<p>I need a permutation of the array, such that <code>f(arr[i], arr[i+1])</code> is as little as possible for each <code>i</code> in <code>arr</code>. (and it should loop, ie. it should also minimize <code>f(arr[arr.length - 1], arr[0])</code>)</p>

<p>Also, <code>f</code> works sort of like a distance, so <code>f(a,b) == f(b,a)</code></p>

<p>I don't need the optimum solution if it's too inefficient, but one that works reasonable well and is fast since I need to calculate them pretty much in realtime (I don't know what to length of <code>arr</code> is, but I think it could be something around 30)</p>

What does "such that f(arr[i], arr[i+1]) is as little as possible for each i in arr" mean? Do you want minimize the
sum
? Do you want to minimize the largest of those? Do you want to minimize f(arr[0],arr[1]) first, then among all solutions that minimize this, pick the one that minimizes f(arr[1],arr[2]), etc., and so on?
If you want to minimize the
sum
, this is
exactly
the Traveling Salesman Problem in its full generality (well, "metric TSP", maybe, if your f's indeed form a metric). There are clever optimizations to the naive solution that will give you the exact optimum and run in reasonable time for about n=30; you could use one of those, or one of the heuristics that give you approximations.
If you want to minimize the
maximum
, it is a simpler problem although still NP-hard: you can do binary search on the answer; for a particular value d, draw edges for pairs which have f(x,y)
If you want to minimize it
lexiocographically
, it's trivial: pick the pair with the shortest distance and put it as arr[0],arr[1], then pick arr[2] that is closest to arr[1], and so on.
Depending on where your f(,)s are coming from, this might be a much easier problem than TSP; it would be useful for you to mention that as well.