diff --git a/Arrays/P05_CheckForPairSum.py b/Arrays/P05_CheckForPairSum.py index 45b42e5..d71e6db 100644 --- a/Arrays/P05_CheckForPairSum.py +++ b/Arrays/P05_CheckForPairSum.py @@ -4,8 +4,10 @@ # in S whose sum is exactly x. def checkSum(array, sum): - # sort the array in descending order - array = quickSort(array) + # sort the array in ascending order + # new changes : made use of Python's inbuilt Merge Sort method + # Reason for such change : Worst case Time complexity of Quick Sort is O(n^2) whereas Worst Case Complexity of Merge Sort is O(nlog(n)) + array = sorted(array) leftIndex = 0 rightIndex = len(array) - 1 @@ -20,14 +22,14 @@ def checkSum(array, sum): return False, False -def quickSort(array): - if len(array) <= 1: - return array - pivot = array[len(array) // 2] - left = [x for x in array if x < pivot] - middle = [x for x in array if x == pivot] - right = [x for x in array if x > pivot] - return quickSort(left) + middle + quickSort(right) +##def quickSort(array): +## if len(array) <= 1: +## return array +## pivot = array[len(array) // 2] +## left = [x for x in array if x < pivot] +## middle = [x for x in array if x == pivot] +## right = [x for x in array if x > pivot] +## return quickSort(left) + middle + quickSort(right) if __name__ == '__main__': myArray = [10, 20, 30, 40, 50] @@ -37,4 +39,4 @@ def quickSort(array): if(number1 and number2): print('Array has elements:', number1, 'and', number2, 'with sum:', sum) else: - print('Array doesn\'t has elements with the sum:', sum) + print('Array doesn\'t have elements with the sum:', sum) diff --git a/Dynamic Programming/P04_SieveOfEratosthenes.py b/Dynamic Programming/P04_SieveOfEratosthenes.py new file mode 100644 index 0000000..4c980fd --- /dev/null +++ b/Dynamic Programming/P04_SieveOfEratosthenes.py @@ -0,0 +1,32 @@ + +# Python program to print all primes smaller than or equal to +# n using Sieve of Eratosthenes + +def sieve_of_eratosthenes(n): + + # Create a boolean array "prime[0..n]" and initialize + # all entries it as true. A value in prime[i] will + # finally be false if i is Not a prime, else true. + prime = [True for i in range(n+1)] + p = 2 + while (p * p <= n): + + # If prime[p] is not changed, then it is a prime + if (prime[p] == True): + + # Update all multiples of p + for i in range(p * 2, n+1, p): + prime[i] = False + p += 1 + + # Print all prime numbers + for p in range(2, n): + if prime[p]: + print (p), + +# driver program +if __name__=='__main__': + n = 30 + print ("Following are the prime numbers smaller"), + print ("than or equal to", n ) + sieve_of_eratosthenes(n)