Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Completed PreCourse_2 #1655

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 23 additions & 6 deletions Exercise_1.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,28 @@

# It returns location of x in given array arr
# if present, else returns -1
"""
Space Complexity : O(1) we are using only variables like start, mid, end
Time Complexity: Best O(1), Worst: O(log n)
"""
def binarySearch(arr, l, r, x):

#write your code here


start = l
end = r
target = x
#If len(arr) is 0 it wont enter into while loop and directly prints -1
#if len > 1 we enter into the while loop to find the index of the target
while(start<=end):
mid = (start + end) //2
#if arr[mid] == target we return the index
if arr[mid] == target:
return mid
#if arr[mid] < target that means the target may present after the midpoint. so we need to search in those indexes.
elif arr[mid] < target:
start = mid + 1
#if arr[mid] > target that means the target may present after the midpoint. so we need to search in those indexes.
else:
end = mid - 1
return -1

# Test array
arr = [ 2, 3, 4, 10, 40 ]
Expand All @@ -17,6 +34,6 @@ def binarySearch(arr, l, r, x):
result = binarySearch(arr, 0, len(arr)-1, x)

if result != -1:
print "Element is present at index % d" % result
print ("Element is present at index % d" % result)
else:
print "Element is not present in array"
print ("Element is not present in array")
30 changes: 18 additions & 12 deletions Exercise_2.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,29 @@
# Python program for implementation of Quicksort Sort

#Time complexity:Best -> O(n logn) Worst -> O(n2)
#Space complexity:Best -> O(logn) Worst -> O(n)
# give you explanation for the approach
def partition(arr,low,high):


#write your code here

pivot = arr[high] # choosing last elemrnt as pivot
i = low - 1 # pointer for smaller elements
for j in range(low,high): #traverse from low to high
if arr[j] <= pivot: #if elements smaller or equal to pivot
i += 1 #increment low pointer
arr[i],arr[j] = arr[j],arr[i] #swapping lower element to the left
arr[i+1],arr[high] = arr[high],arr[i+1] #swapping pivot element to the correct position
return i+1 #returning partition index

# Function to do Quick sort
def quickSort(arr,low,high):

#write your code here

if low < high:
pivot_index = partition(arr, low, high) # Find pivot position
quickSort(arr, low, pivot_index - 1) # Recursively sort left half
quickSort(arr, pivot_index + 1, high) #recursively sort right

# Driver code to test above
arr = [10, 7, 8, 9, 1, 5]
n = len(arr)
print("Before Sorting: ",arr)
n = len(arr)
quickSort(arr,0,n-1)
print ("Sorted array is:")
for i in range(n):
print ("%d" %arr[i]),
print("After Sorting: ",arr)


31 changes: 25 additions & 6 deletions Exercise_3.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,39 @@
# Node class
class Node:

# Function to initialise the node object
def __init__(self, data):
self.data = data
self.next = None

class LinkedList:

def __init__(self):

def __init__(self):
self.head = None

def push(self, new_data):
#Inserts new node at the beggining
#Space complexity: O(1)
#Time complexity : O(1)
newnode = Node(new_data)
newnode.next = self.head
self.head = newnode


# Function to get the middle of
# the linked list
#Space complexity: O(1)
#Time complexity : O(n)
def printMiddle(self):
#If empty list
if self.head is None:
return None
current = self.head
#slow pointer moves one step while fast pointer moves 2 steps at a time
slow = current
fast = current
#we iterate till fast reaches the end
while fast is not None and fast.next is not None:
slow = slow.next
fast = fast.next.next
return slow.data # since slow now points to middle node

# Driver code
list1 = LinkedList()
Expand All @@ -23,4 +42,4 @@ def printMiddle(self):
list1.push(2)
list1.push(3)
list1.push(1)
list1.printMiddle()
print(list1.printMiddle())
37 changes: 37 additions & 0 deletions Exercise_4.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,49 @@
# Python program for implementation of MergeSort
#Time complexity:Best -> O(n logn) Worst -> O(n logn)
#Space complexity:Best -> O(n) Worst -> O(n)
def mergeSort(arr):

#write your code here
#we recursively divides the array into halves, sorts each half,and then merges them back together in sorted order.
if len(arr) > 1: #afterc finding middle index, we divided the arrays
midpoint = len(arr)//2
leftarr = arr[:midpoint]
rightarr = arr[midpoint:]

#sorting both halves recursively
mergeSort(leftarr)
mergeSort(rightarr)
#pointer for lrft, right and original array
i = 0
j = 0
k = 0

while (i < len(leftarr)) and (j < len(rightarr)):
#if left element is smaller
if leftarr[i] <= rightarr[j]:
arr[k] = leftarr[i]
i += 1
else:
#if left element is smaller
arr[k] = rightarr[j]
j += 1
k += 1

while i < len(leftarr): # Copy remaining elements of leftarr if present
arr[k] = leftarr[i]
i += 1
k += 1

while j < len(rightarr): # Copy remaining elements of rightarr if present
arr[k] = rightarr[j]
j += 1
k += 1

# Code to print the list
def printList(arr):

#write your code here
print(arr)

# driver code to test the above code
if __name__ == '__main__':
Expand Down
28 changes: 28 additions & 0 deletions Exercise_5.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,38 @@
# Python program for implementation of Quicksort
#Time complexity:Best -> O(n logn) Worst -> O(n2)
#Space complexity:Best -> O(logn) Worst -> O(n)

# This function is same in both iterative and recursive
def partition(arr, l, h):
#write your code here
pivot = arr[h] # choosing last elemrnt as pivot
i = l - 1 # pointer for smaller elements
for j in range(l,h): #traverse from low to high
if arr[j] <= pivot: #if elements smaller or equal to pivot
i += 1 #increment low pointer
arr[i],arr[j] = arr[j],arr[i] #swapping lower element to the left
arr[i+1],arr[h] = arr[h],arr[i+1] #swapping pivot element to the correct position
return i+1 #returning partition index


def quickSortIterative(arr, l, h):
#write your code here
stack = []
stack.append((l,h))
while stack:
l,h = stack.pop()
if l < h:
pivotIndex = partition(arr,l,h)
# Push left part onto stack if it has more than 1 element
if pivotIndex - 1 > l:
stack.append((l, pivotIndex - 1))

# Push right part onto stack if it has more than 1 element
if pivotIndex + 1 < h:
stack.append((pivotIndex + 1, h))

arr = [10, 7, 8, 9, 1, 5]
print("Before Sorting: ",arr)
n = len(arr)
quickSortIterative(arr,0,n-1)
print("After Sorting: ",arr)