I come here with a solution I just wrote but I definitely can't find a better way to sort my array as fast as possible.
I actually need the algorithm to give me the answer in less than 1 sec, on an array containing 100'000 integers.
Here's the code :
read N
for (( i=0; i<N; i++ )); do
read arr[i]
done
sorted=($(printf '%s\n' "${arr[@]}"|sort -n))
min=$(( sorted[1]-sorted[0] ))
for (( i=1; i<N-1; i++ )); do
diff=$(( sorted[i+1] - sorted[i] ))
if [ "$diff" -lt "$min" ]; then
min=$diff
fi
done
echo $min
N is the number of elements, in our case 100'000 as I said.
The thing is, after my array is sorted, I need to loop through it and calculate the minimum distance between two integers :
For example, with (3, 5, 8, 9), the minimum distance is 1 (between 8 and 9).
I'm such a newbie in Bash, so I don't even know if this is an efficient way;
In fact, the gain of speed could come from the second part of the code, and not from the sorting part...
Any ideas ?
Thanks in advance,