[PYTHON] Quicksort 2 | Easy list comprehension

Python's strengths

Quicksort with list comprehension

quickSortSimple.py


data = [26,13,32,65,76,22,43,87,14,59]

def QuickSort(data):
    if len(data) <= 1: #No need to sort if there is only one data
        return data

    #Use the first value in the list as the reference data (pivot)
    pivot = data[0]
    #Create a list with data above the pivot
    left = [ii for ii in data[1:] if ii >= pivot]
    #List with less than pivot data
    right = [ii for ii in data[1:] if ii < pivot]

    left  = QuickSort(left)  #Sort on the left
    right = QuickSort(right) #Sort on the right
    #Return sorted data and pivot together
    return left + [pivot] + right

print(QuickSort(data))

#result
# [87, 76, 65, 59, 43, 32, 26, 22, 14, 13]

This time, the value at the top of the list is used as the pivot, but there are various options such as the first value, the last value, and the median of the three appropriately selected values, and it is a quick process to select a good value. It's like the key to.

・ Other articles about sorting

Quicksort | Largest order [Merge sort | Sorting in descending order] (https://qiita.com/ProOJI/items/c34441886a9d60fc9664) [Selection sort | Memorandum] (https://qiita.com/ProOJI/items/a7fc63c943f51a4e2e92)

Recommended Posts

Quicksort 2 | Easy list comprehension
List comprehension
List comprehension
Python> Comprehension / Comprehension> List comprehension
Note: List comprehension
Python Exercise 2 --List Comprehension
Python list comprehension speed
Not just list comprehension
Judgment of if by list comprehension
QuickSort
Python basic operation 1st: List comprehension notation
Python comprehension (list and generator expressions) [additional]