Sunday 12 January 2014

Python: Minimum absolute sum of two integers in an Array

So I was given this problem and figured I would share my solution for others. I believe the Time Complexity to be O(n log n) due to Quicksort being O(n log n). I could be wrong though!
'''
Created on 10/01/2014

# My first foray in python
# min_abs_sum_of_two takes an Integer Array and returns the lowest absolute sum of two integers
# I did not include checking for the following: array length, non integer characters.
@author: BeauR
'''

import time
import sys

def min_abs_sum_of_two(listOfNums):
    #init y as last array place
    y = len(listOfNums)-1
    #init x as first array place
    x = 0
    #set current min to arbitrary max possible integer
    currentMin = sys.maxsize
    #quicksort array into ascending order
    quicksort(listOfNums, x, y)
    #while x is less than y to ensure they never overlap array places
    while (x < y):
        #if the current calculation is less than currentMin
        if abs(listOfNums[x]+listOfNums[y]) < currentMin:
            #store new minimum
            currentMin = abs(listOfNums[x]+listOfNums[y])
        #if the sum of arr[x] & arr[y] is greater than zero
        #x no longer need to be increased as its at optimum minimum value
        if listOfNums[x]+listOfNums[y] < 0:
            #increment search pointer x
            x = x + 1
        else:
            #decrement search pointer y
            y = y -1
    return(currentMin)
   

def quicksort(list, start, end):
    if start < end:                            # If there are two or more elements...
        split = partition(list, start, end)    # ... partition the sublist...
        quicksort(list, start, split-1)        # ... and sort both halves.
        quicksort(list, split+1, end)
    else:
        return

def partition(myList, start, end):
    pivot = myList[start]
    left = start+1
    right = end
    done = False
    while not done:
        while left <= right and myList[left] <= pivot:
            left = left + 1
        while myList[right] >= pivot and right >=left:
            right = right -1
        if right < left:
            done= True
        else:
            # swap places
            temp=myList[left]
            myList[left]=myList[right]
            myList[right]=temp
    # swap start with myList[right]
    temp=myList[start]
    myList[start]=myList[right]
    myList[right]=temp
    return right

start_time = time.clock()
print(min_abs_sum_of_two(listOfNums = [-6, -5, -4, -3, 1]))
print(time.clock() - start_time, "seconds")

No comments:

Post a Comment