diff --git a/04_quicksort/python/01_loop_sum.py b/04_quicksort/python/01_loop_sum.py new file mode 100644 index 0000000..b43c5e3 --- /dev/null +++ b/04_quicksort/python/01_loop_sum.py @@ -0,0 +1,7 @@ +def sum(arr): + total = 0 + for x in arr: + total += x + return total + +print sum([1, 2, 3, 4]) diff --git a/04_quicksort/python/02_recursive_sum.py b/04_quicksort/python/02_recursive_sum.py new file mode 100644 index 0000000..bf3a358 --- /dev/null +++ b/04_quicksort/python/02_recursive_sum.py @@ -0,0 +1,4 @@ +def sum(list): + if list == []: + return 0 + return list[0] + sum(list[1:]) diff --git a/04_quicksort/python/03_recursive_count.py b/04_quicksort/python/03_recursive_count.py new file mode 100644 index 0000000..c83630a --- /dev/null +++ b/04_quicksort/python/03_recursive_count.py @@ -0,0 +1,4 @@ +def count(list): + if list == []: + return 0 + return 1 + count(list[1:]) diff --git a/04_quicksort/python/04_recursive_max.py b/04_quicksort/python/04_recursive_max.py new file mode 100644 index 0000000..c32fb54 --- /dev/null +++ b/04_quicksort/python/04_recursive_max.py @@ -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 diff --git a/04_quicksort/python/05_quicksort.py b/04_quicksort/python/05_quicksort.py new file mode 100644 index 0000000..bb98746 --- /dev/null +++ b/04_quicksort/python/05_quicksort.py @@ -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])