Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the fastest algorithm to find the minimum difference between pairs of numbers in an array? [duplicate]

Possible Duplicate:
Is it possible to find two numbers whose difference is minimum in O(n) time

For example, in [4, 2, 7, 11, 8], the algorithm should return abs(7-8) = 1.

The brute force way will be O(n2) and sorting will give O(nlogn). Is there more efficient way?

Thanks

like image 453
javaMan Avatar asked Sep 24 '11 20:09

javaMan


People also ask

How do you find the min diff of an array?

sort((a,b) => { return a-b; }); let min = arr[1]-arr[0]; let n = arr. length; for (var i=0;i<n;i++) { let m = arr[i+1] - arr[i]; if(m < min){ m = min; } } return m; // minimum difference. } Show activity on this post. The given problem can easily be solved in O(n) time.

How do you find the smallest interval?

Subtract the smallest number from the largest number in the pair, this will generate the interval. Store in a variable the difference generated by every operation and update it only if the result is lower than the previous one, once it ends, the variable will store the smallest interval, which in this case is 2.

What is array in simple language?

Overview. An array is a data structure consisting of a collection of elements (values or variables), each identified by at least one array index or key. Depending on the language, array types may overlap (or be identified with) other data types that describe aggregates of values, such as lists and strings.


2 Answers

I think sorting and comparing is going to be your best bet. Something like:

function minDiff( arr ) {
    var min,
        temp,
        initDiff = false,
        arr = arr.sort( function(a, b){return a-b} ),
        last = arr.length - 1,
        i;

    for ( i = 0; i < last; i++ ) {

        if ( !initDiff ) {            
            min = arr[i + 1] - arr[i];
            initDiff = true;
        } else {            
            temp = arr[i + 1] - arr[i];

            if ( temp < min ) {            
                min = temp;            
            }            
        }
    }

    return min; 
}

var myArr = [ 1, 8, 5, 96, 20, 47 ],
    min = minDiff( myArr );

console.log( min ); // 3
like image 198
jbyrd Avatar answered Sep 22 '22 19:09

jbyrd


A similar question here - Is it possible to find two numbers whose difference is minimum in O(n) time . It appears to be O(nlogn).

This page may give useful background info too.

like image 31
Caffeinated Avatar answered Sep 19 '22 19:09

Caffeinated