Finding out the minimum difference between elements in an array

前端 未结 8 644
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-08 01:02

I have an integer array with some finite number of values. My job is to find the minimum difference between any two elements in the array.

Consider that the array co

8条回答
  •  遥遥无期
    2020-12-08 01:18

    While all the answers are correct, I wanted to show the underlying algorithm responsible for n log n run time. The divide and conquer way of finding the minimum distance between the two points or finding the closest points in a 1-D plane.

    The general algorithm:

    • Let m = median(S).
    • Divide S into S1, S2 at m.
    • δ1 = Closest-Pair(S1).
    • δ2 = Closest-Pair(S2).
    • δ12 is minimum distance across the cut.
    • Return δ = min(δ1, δ2, δ12).

    Here is a sample I created in Javascript:

    // Points in 1-D
    var points = [4, 9, 1, 32, 13];
    
    var smallestDiff;
    
    function mergeSort(arr) {
      if (arr.length == 1)
        return arr;
    
      if (arr.length > 1) {
        let breakpoint = Math.ceil((arr.length / 2));
        // Left list starts with 0, breakpoint-1
        let leftList = arr.slice(0, breakpoint);
        // Right list starts with breakpoint, length-1
        let rightList = arr.slice(breakpoint, arr.length);
    
        // Make a recursive call
        leftList = mergeSort(leftList);
        rightList = mergeSort(rightList);
    
        var a = merge(leftList, rightList);
        return a;
      }
    }
    
    function merge(leftList, rightList) {
      let result = [];
      while (leftList.length && rightList.length) {
        // Sorting the x coordinates
        if (leftList[0] <= rightList[0]) {
          result.push(leftList.shift());
        } else {
          result.push(rightList.shift());
        }
      }
    
      while (leftList.length)
        result.push(leftList.shift());
    
      while (rightList.length)
        result.push(rightList.shift());
    
      let diff;
      if (result.length > 1) {
        diff = result[1] - result[0];
      } else {
        diff = result[0];
      }
    
      if (smallestDiff) {
        if (diff < smallestDiff)
          smallestDiff = diff;
      } else {
        smallestDiff = diff;
      }
      return result;
    }
    
    mergeSort(points);
    
    console.log(`Smallest difference: ${smallestDiff}`);

提交回复
热议问题