Browse Source

Added file which has two ways for doing quick sort.

pull/2/head
jrtechs 2 years ago
parent
commit
8a7579f2f5
3 changed files with 112 additions and 0 deletions
  1. +49
    -0
      other/hasSum.py
  2. +0
    -0
      recurrences.py
  3. +63
    -0
      sorting/quickSort.py

+ 49
- 0
other/hasSum.py View File

@@ -0,0 +1,49 @@
def sortedHasSum(s, x):
tempSum = 0
for i in range(len(s) -1, -1, -1):
if tempSum + s[i] <= x:
tempSum += s[i]
if(tempSum == x):
return True
return False


def hasSumHelper(s, x):
if len(s) == 1:
if x - s[0] >= 0:
return x - s[0]
else:
return x
elif len(s) == 0:
return x;
lower,equal,upper = partition(s)

leftOver = hasSumHelper(upper, x)

if len(equal) > 1:
leftOver = hasSumHelper([equal[0]], leftOver)
leftOver = hasSumHelper(equal[1::],leftOver)
else:
leftOver = hasSumHelper(upper, leftOver)

return hasSumHelper(lower, leftOver)


def hasSum(s, x):
return hasSumHelper(s, x) == 0


def partition(data):
pivot = len(data) -1
lower, equal, upper = [], [], []

for i in range(0, len(data), 1):
if data[i] > data[pivot]:
upper.append(data[i])
elif data[i] == data[pivot]:
equal.append(data[i])
else:
lower.append(data[i])

return lower, equal, upper


+ 0
- 0
recurrences.py View File


+ 63
- 0
sorting/quickSort.py View File

@@ -0,0 +1,63 @@
"""
Jeffery Russell
10-6-18

File Containing Variations of Quick Sort
"""


def partition(data):
"""
Partitions a list of data into three sections
which are lower, equal, and equal to the pivot
which is selected to be the last element in the
list.
"""
pivot = len(data) -1
lower, equal, upper = [], [], []

for i in range(0, len(data), 1):
if data[i] > data[pivot]:
upper.append(data[i])
elif data[i] == data[pivot]:
equal.append(data[i])
else:
lower.append(data[i])

return lower, equal, upper


def quickSortNormal(data):
"""
This is the traditional implementation of quick sort
where there are two recursive calls.
"""
if len(data) == 0:
return []
else:
less, equal, greater = partition(data)
return quickSortNormal(less) + equal + quickSortNormal(greater)


def quick_sort_accumulation(data, a):
"""
Implementation of quickSort which forces tail recursion
by wrapping the second recursive in the tail positioned
recursive call and added an accumulation variable.
"""
if len(data) == 0:
return a
less, equal, greater = partition(data)
return quick_sort_accumulation(less,
equal + quick_sort_accumulation(greater, a))


def quicksort(data):
"""
Wrapper function for quick sort accumulation.
"""
return quick_sort_accumulation(data, [])



print quicksort([1,3,1,5,7,9,2,3,5,5,6])

Loading…
Cancel
Save