简体   繁体   中英

How does my Quick Sort algorithm work exactly?

I know how the Quick Sort algorithm works in theroy:

Concept of Divide and Conquer. Dividing the list into three main parts:

Elements less than the Pivot element,

Pivot element(Central element),

Elements greater than the pivot element

Repeat this until everything is sorted and put it back together.

I have implemented a quick sort algorithm in my python code, and it works fine. But I do not understand exactly how it works:

def quickSort(list, compare_fn):

if not list:
    return list
pivot = list[0]
lesser = quickSort([x for x in list[1:] if compare_fn(x, pivot)], compare_fn)
greater = quickSort([x for x in list[1:] if not compare_fn(x, pivot)], compare_fn)
return lesser + [pivot] + greater

product_list = quickSort(product_list, lambda x,y: x[z] < y[z])

"z" is the variable by which column the list should be sorted.

I would be very happy if someone could explain to me exactly how the function works. I am also not sure what lambda does in this context

I would really appreciate help

It's quite simple really... let's start with the invocation:

product_list = quickSort(product_list, lambda x,y: x[z] < y[z])

The lambda defines an anonymous function (a "lambda") that takes two values, x and y, and checks to see if x[z] is less than y[z] . In your quicksort, this is the compare_fn - a function that takes two values and returns True if the first value is less than the second and False otherwise.

Why bother? Well... doing it this way means quicksort can be written without knowing how you decide what "less" means in your context. But also, what if the elements are objects? Easy: Just pass in a lambda that compares the fields.

Next: The quicksort itself.

  • pivot - your code just takes the first element of the list. It doesn't really matter which element you use to pivot on ( unless you have more knowledge of the list, but you don't in the general case)

  • inside the two (recursive) calls to quickSort , you have [x for x in list[1:] if compare_fn(x, pivot)] (and the opposite for greater ).

this [x for x in list[1:]...] construct is a list comprehension . list[1:] is a copy of your list, except the first element (the pivot). For lesser we only use the elements that are less than pivot, for greater only those that are not less than pivot.

This algorithm employs something called recursion . Basically, quickSort uses quickSort to calculate it's result. Look it up, other's can explain this much better than I.

In the end, you just append all the lists ( lesser , a list with just the pivot , and greater ) and return that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM