Coding/잡동사니

quick sort

linguana 2021. 4. 29. 17:13

sorting - quick sort python recursion - Stack Overflow

def quicksort_recursive(a):
    if len(a) == 0:
        return a
    p = len(a) // 2
    l = [i for i in a if i < a[p]]
    m = [i for i in a if i == a[p]]
    r = [i for i in a if i > a[p]]
    return quicksort_recursive(l) + m + quicksort_recursive(r)

Algorithms and Data Structures - Full Course for Beginners from Treehouse - YouTube

4:43:27 to 4:47:12 Quick sort explained with animated presentation

import sys
from load import load_numbers

numbers = load_numbers(sys.argv[1])

def quicksort(values):
    # base case
    if len(values) <= 1:
        return values
    
    less_than_pivot = []
    greater_than_pivot = []
    pivot = values[0]
    for value in values[1:]:
    	if value <= pivot:
        	less_than_pivot.append(value)
        else:
        	greater_than_pivot.append(value)
    print("%15s %1s %-15s" % (less_than_pivot, pivot, greater_than_pivot))
    return quicksort(less_than_pivot) + [pivot] + quicksort(greater_than_pivot)

print(numbers)
sorted_numbers = quicksort(numbers)
print(sorted_numbers)