Add initial implementation of hw2

This commit is contained in:
Danila Fedorin 2019-10-07 19:06:14 -07:00
commit bc155dc53c
4 changed files with 104 additions and 0 deletions

39
inversions.py Normal file
View File

@ -0,0 +1,39 @@
def _inversions(xs):
# Can't be unsorted
if len(xs) < 2: return 0, xs
# Divide into two subarrays
leng = len(xs)//2
left = xs[:leng]
right = xs[leng:]
# Perform recursive call
lcount, left = _inversions(left)
rcount, right = _inversions(right)
# Reverse the lists to allow O(1) pop.
# Since we already have an O(n) copy,
# this doesn't increase complexity.
left.reverse()
right.reverse()
# Merge by popping
count = 0
total = []
while left != [] and right != []:
if left[-1] <= right[-1]:
total.append(left.pop())
else:
total.append(right.pop())
count += len(left)
# Add elements from non-empty array,
# if applicable.
left.reverse()
right.reverse()
total += left + right
return (count + lcount + rcount), total
def inversions(xs):
count, _ = _inversions(xs)
return count

13
longest.py Normal file
View File

@ -0,0 +1,13 @@
def _longest(ts):
if ts == []: return 0, 0
ldepth, lpath = _longest(ts[0])
rdepth, rpath = _longest(ts[2])
depth = max(ldepth, rdepth) + 1
cpath = max(lpath, rpath)
return depth, max(ldepth+rdepth, cpath)
def longest(ts):
return _longest(ts)[1]

26
msort.py Normal file
View File

@ -0,0 +1,26 @@
def msort(xs):
if len(xs) < 2: return xs
leng = len(xs) // 2
left = msort(xs[:leng])
right = msort(xs[leng:])
# Reversing is O(n), but so is copying, so
# this does not worsen complexity.
# It does slow us down, but... oh well :)
left.reverse()
right.reverse()
# Since we're reversed, the smallest numbers
# are on the end. We can thus use pop (O(1))
total = []
while left != [] and right != []:
if left[-1] <= right[-1]:
total.append(left.pop())
else:
total.append(right.pop())
left.reverse()
right.reverse()
total += left + right
return total

26
report.txt Normal file
View File

@ -0,0 +1,26 @@
Q0: Which of the following sorting algorithms are (or can be made) stable?
A: mergesort, quicksort with first element as pivot, selection sort with insertion,
and insertion sort are stable.
Debrief:
1. Approximately how many hours did you spend on this assignment?
Less than 1 hour.
2. Would you rate it as easy, moderate, or difficult?
Seemed easy, I didn't have any difficulties.
3. Did you work on it mostly alone, or mostly with other people?
Note you are encouraged to discuss with your classmates,
but each students should submit his/her own code.
Alone.
4. How deeply do you feel you understand the material it covers (0%100%)?
Seems like 100%. Didn't have any difficulties.
5. Any other comments?
In my opinion, it kinda sucks that only 1 code assignment is auto-graded.