I have to do an algorithm, aprop, using divide and conquer to calculate the couple of points that are closer to each other in a list and also I have to calculate the complexity.
def aprop(a):
longitudlista = len(a)
if longitudlista <= 2:
return a
else:
mig = longitudlista / 2
pivot = (a[mig])
a= [1.2,2.9,3.1,4.0,5.7]
aprop(a)
Now I want that the algorithm return the couple of points that having the minimum difference of all the differences of all elements of the list using the pivot. How can i write this idea in code?
Sort your array and check pairwise for the smallest distance.
The sort can be done using a divide and conquer algorithm, like merge_sort in
O(nlog(n))
time.For instance you could piggyback on merge sort like this :
For your array
[1.2,2.9,3.1,4.0,5.7]
Side Note:
If you don't care about the divide and conquer implementation, you could simply use
min
using a key anditertools.combinations
( Like implemented above for the combine step / the base case oflen(array)
equal to 3. )Check this to learn more about :
itertools.combinations
min
with akey
parameter - Has been explained formax
but the same applies formin
too.Hope this helps...