| 
 | 1 | +# Author: OMKAR PATHAK  | 
 | 2 | + | 
 | 3 | +# Given an array A[] of n numbers and another number x, determines whether or not there exist two elements  | 
 | 4 | +# in S whose sum is exactly x.  | 
 | 5 | + | 
 | 6 | +def checkSum(array, sum):  | 
 | 7 | +    # sort the array in descending order  | 
 | 8 | +    array = quickSort(array)  | 
 | 9 | + | 
 | 10 | +    leftIndex = 0  | 
 | 11 | +    rightIndex = len(array) - 1  | 
 | 12 | + | 
 | 13 | +    while leftIndex < rightIndex:  | 
 | 14 | +        if (array[leftIndex] + array[rightIndex] ==  sum):  | 
 | 15 | +            return array[leftIndex], array[rightIndex]  | 
 | 16 | +        elif(array[leftIndex] + array[rightIndex] < sum):  | 
 | 17 | +            leftIndex += 1  | 
 | 18 | +        else:  | 
 | 19 | +            rightIndex += 1  | 
 | 20 | + | 
 | 21 | +    return False, False  | 
 | 22 | + | 
 | 23 | +def quickSort(array):  | 
 | 24 | +    if len(array) <= 1:  | 
 | 25 | +        return array  | 
 | 26 | +    pivot = array[len(array) // 2]  | 
 | 27 | +    left = [x for x in array if x < pivot]  | 
 | 28 | +    middle = [x for x in array if x == pivot]  | 
 | 29 | +    right = [x for x in array if x > pivot]  | 
 | 30 | +    return quickSort(left) + middle + quickSort(right)  | 
 | 31 | + | 
 | 32 | +if __name__ == '__main__':  | 
 | 33 | +    myArray = [10, 20, 30, 40, 50]  | 
 | 34 | +    sum = 80  | 
 | 35 | + | 
 | 36 | +    number1, number2 = checkSum(myArray, sum)  | 
 | 37 | +    if(number1 and number2):  | 
 | 38 | +        print('Array has elements:', number1, 'and', number2, 'with sum:', sum)  | 
 | 39 | +    else:  | 
 | 40 | +        print('Array doesn\'t has elements with the sum:', sum)  | 
0 commit comments