code from chapter 4
This commit is contained in:
7
04_quicksort/python/01_loop_sum.py
Normal file
7
04_quicksort/python/01_loop_sum.py
Normal file
@@ -0,0 +1,7 @@
|
||||
def sum(arr):
|
||||
total = 0
|
||||
for x in arr:
|
||||
total += x
|
||||
return total
|
||||
|
||||
print sum([1, 2, 3, 4])
|
||||
4
04_quicksort/python/02_recursive_sum.py
Normal file
4
04_quicksort/python/02_recursive_sum.py
Normal file
@@ -0,0 +1,4 @@
|
||||
def sum(list):
|
||||
if list == []:
|
||||
return 0
|
||||
return list[0] + sum(list[1:])
|
||||
4
04_quicksort/python/03_recursive_count.py
Normal file
4
04_quicksort/python/03_recursive_count.py
Normal file
@@ -0,0 +1,4 @@
|
||||
def count(list):
|
||||
if list == []:
|
||||
return 0
|
||||
return 1 + count(list[1:])
|
||||
5
04_quicksort/python/04_recursive_max.py
Normal file
5
04_quicksort/python/04_recursive_max.py
Normal file
@@ -0,0 +1,5 @@
|
||||
def max(list):
|
||||
if len(list) == 2:
|
||||
return list[0] if list[0] > list[1] else list[1]
|
||||
sub_max = max(list[1:])
|
||||
return list[0] if list[0] > sub_max else sub_max
|
||||
14
04_quicksort/python/05_quicksort.py
Normal file
14
04_quicksort/python/05_quicksort.py
Normal file
@@ -0,0 +1,14 @@
|
||||
def quicksort(array):
|
||||
if len(array) < 2:
|
||||
# base case, arrays with 0 or 1 element are already "sorted"
|
||||
return array
|
||||
else:
|
||||
# recursive case
|
||||
pivot = array[0]
|
||||
# sub-array of all the elements less than the pivot
|
||||
less = [i for i in array[1:] if i <= pivot]
|
||||
# sub-array of all the elements greater than the pivot
|
||||
greater = [i for i in array[1:] if i > pivot]
|
||||
return quicksort(less) + [pivot] + quicksort(greater)
|
||||
|
||||
print quicksort([10, 5, 2, 3])
|
||||
Reference in New Issue
Block a user