If you need many calls to this function, pre-sorting the vector is the best option:
a = [9, 7, 3, 5, 2, 8, 1, 0, 11];
p = vecsort(a,, 1); \\ permutation sorting a
A = vecextract(a, p); \\ A = vecsort(a)
position2(n) = p[vecsearch(A,n)];
? position2(8)
%1 = 6
For simplicity, I used global variables and I didn't cater for missing entries (need to check whether vecsearch
returns 0). And I also assume the inputs are real numbers (if not, use the universal vecsort(a, cmp, 1)
instead of the default comparison function).
Using Piotr's benchmark:
position = (elt, array) -> select((x) -> x == elt, array, 1);
position1 = (elt, array) -> for(i = 1, #array, if(array[i] == el, return(i)));
a = vector(100, i, random(200));
position2(n) = p[vecsearch(A,n)];
? for(i = 1, 10^5, position(8, a));
time = 586 ms.
? for(i = 1, 10^5, position1(8, a));
time = 1,644 ms.
? for(i = 1, 10^5, position2(8));
time = 29 ms.