Skip to content

Latest commit

 

History

History
60 lines (39 loc) · 1.21 KB

ch04-02.md

File metadata and controls

60 lines (39 loc) · 1.21 KB

4.2 Quicksort

# quicksort

def quicksort(array):
    if len(array) < 2:
        return array
    else:
        pivot = array[0]  # the first item as a pivot
        less, greater = [], []
        for item in array[1:]:
            if item <= pivot:
                less.append(item)
            else:
                greater.append(item)
        return quicksort(less) + [pivot] + quicksort(greater)

# test quicksort
my_array = [10, 5, 2, 3]
print(quicksort(my_array))
  • 🐍 python practice
# quicksort (using Python List Comprehension)

def quicksort(array):
    if len(array) < 2:
        return array
    else:
        pivot = array[0]  # the first item as a pivot
        less = [item for item in array[1:] if item <= pivot]    # List Comprehension
        greater = [item for item in array[1:] if item > pivot]
        return quicksort(less) + [pivot] + quicksort(greater)

# test quicksort
my_array = [10, 5, 2, 3]
print(quicksort(my_array))