简体   繁体   English

理解quicksort python实现

[英]Understading a quicksort python implementation

I found this code online. 我在网上找到了此代码。

def quick_sort(items):
""" Implementation of quick sort """
if len(items) > 1:
    pivot_index = len(items) / 2
    smaller_items = []
    larger_items = []
    for i, val in enumerate(items):
        if i != pivot_index:
            if val < items[pivot_index]:
                smaller_items.append(val)
            else:
                larger_items.append(val)

    quick_sort(smaller_items)
    quick_sort(larger_items)
    items[:] = smaller_items + [items[pivot_index]] + larger_items

The one line that gives me trouble is the last one. 给我麻烦的那一条线是最后一条。 I believe it's basic concatenation, however, when I change "items[:]" to "items", the algorithm fails. 我相信这是基本的串联,但是,当我将“ items [:]”更改为“ items”时,算法将失败。 What is special about the [:] at the end of the list? 列表末尾的[:]有什么特别之处?

If anyone one can help, I would really appreciate. 如果有人可以提供帮助,我将不胜感激。 Thank you in advance! 先感谢您!

This is in-place assignment, without replacing the list object with a new object. 这是就地分配,而不用新对象替换列表对象。 This way, the output is placed in the original list and can be read by the caller. 这样,输出将放置在原始列表中,并可由调用方读取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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