Finding the two closest numbers in a list using sorting

前端 未结 3 1103
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-27 09:20

If I am given a list of integers/floats, how would I find the two closest numbers using sorting?

3条回答
  •  灰色年华
    2021-01-27 09:26

    Jose has a valid point. However, you could just consider these cases equal and not care about returning one or the other.

    I don't think you need a sorting algorithm, per say, but maybe just a sort of 'champion' algorithm like this one:

    def smallestDistance(self, arr):
        championI = -1
        championJ = -1
        champDistance = sys.maxint
        i = 0
        while i < arr.length:
            j = i + 1
            while j < arr.length:
                if math.fabs(arr[i] - arr[j]) < champDistance:
                    championI = i
                    championJ = j
                    champDistance = math.fabs(arr[i] - arr[j])
                j += 1
            i += 1
        r = [arr[championI], arr[championJ]]
        return r
    

    This function will return a sub array with the two values that are closest together. Note that this will only work given an array of at least two long. Otherwise, you will throw some error.

    I think the popular sorting algorithm known as bubble sort would do this quite well. Though running at possible O(n^2) time if that kind of thing matters to you...

    Here is standard bubble sort based on the sorting of arrays by integer size.

     def bubblesort( A ):
      for i in range( len( A ) ):
        for k in range( len( A ) - 1, i, -1 ):
          if ( A[k] < A[k - 1] ):
            swap( A, k, k - 1 )
    
    def swap( A, x, y ):
      tmp = A[x]
      A[x] = A[y]
      A[y] = tmp
    

    You can just modify the algorithm slightly to fit your purposes if you insist on doing this using a sorting algorithm. However, I think the initial function works as well...

    hope that helps.

提交回复
热议问题