Skip to content

It's changed for python3 and comments are added #2

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
31 changes: 20 additions & 11 deletions Programming Assignment 3/QuickSort.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,31 @@
#It's written in python3

with open('QuickSort.txt') as f:
with open('c:/Users/Nabin/Desktop/output.txt') as f:
a = [int(x) for x in f]

def FindMedian(A):

#It's for the 3rd part of the assignment where we are told to use the median of three
def FindMedian(A):
minvalue = min(A)
maxvalue = max(A)
for i in range(3):
if A[i] != minvalue and A[i] != maxvalue:
return A[i]


#It's a function which chooses the pivot either the first elem for flag1, the last for flag2 and the median of three for flag3
def ChoosePivot(A,flag):
n = len(A)
first = A[0]
final = A[n-1]
if n/2*2==n:
k = n/2 - 1
if(n%2==0):
k = n//2 - 1
middle = A[k]
elif n/2*2<n:
k = n/2
elif(n%2!=0):
k = n//2
middle = A[k]
else:
print 'error in ChoosePivot to choose middle element of A'
print('error in ChoosePivot to choose middle element of A')

B = [first,middle,final]
med = FindMedian(B)
Expand All @@ -38,15 +43,17 @@ def ChoosePivot(A,flag):
if flag==3:
return position
else:
print 'wrong flag'
print('wrong flag')

#Just a normal swap function
def Swap(A,first,second):
second_value = A[second]
first_value = A[first]
A[first] = second_value
A[second] = first_value
return A

#It's where the main work is done.Comparing the elements. Here we always use the first element as a pivot than continue our comparison and swap.It places the the pivot value in it's proper position in the list
def Partition(A):
pivot = A[0]
r = len(A)
Expand All @@ -57,17 +64,19 @@ def Partition(A):
i +=1
A = Swap(A,0,i-1)
return A,i-1



#The main function where recursion is called
def QuickSort(A,flag):
n = len(A)

if n>1:
p = ChoosePivot(A,flag)
A = Swap(A,0,p)
A = Swap(A,0,p) #places the pivot element in the first position as our partition function works assuming the first element is the pivot.
A,pivot_position = Partition(A)
A[:pivot_position],left = QuickSort(A[:pivot_position],flag)
A[pivot_position+1:],right = QuickSort(A[pivot_position+1:],flag)

return A,left+right+n-1
return A,left+right+n-1 #for each recursive call atleast n-1 comparison is made and then it works for the left and right sublist.
else:
return A,0