Python implements a fast sorting algorithm

Source: Internet
Author: User

Fast sequencing is a sort of algorithm developed by Donny Holl. On average, sort n items to 0(n log n) comparisons. In the worst case scenario, a 0(n2) comparison is required, but this is not a common situation. In fact, fast sequencing is usually much faster than the other 0(n log n) algorithms because its internal loop (inner Loop) can be implemented efficiently on most architectures.

Quick sort uses the divide-and-conquer (Divide and conquer) strategy to divide a serial (list) into two sub-serial (sub-lists).

Algorithm steps:

1 Select an element from the series, called the "Datum" (pivot),

2 Reorder the columns, where all elements are placed in front of the datum in a smaller position than the base value, and all elements are larger than the base value behind the datum (the same number can be on either side). After the partition exits, the datum is in the middle of the sequence. This is called partition (partition) operation.

3 recursively (recursive) sorts sub-columns that are less than the base value element and that are larger than the base value element.

At the bottom of the recursive scenario, the size of the sequence is 0 or one, which is always sorted. Although it is always recursive, the algorithm always exits, because in each iteration (iteration), it will at least put an element to its last position.

#!/usr/bin/env python#-*-coding:utf-8-*-def func (L):    if not L or len (l) = = 1:        return l    base = l[0]    lef t_l, right_l = [], [] for    I in L[1:]:        If I >= base:            right_l.append (i)        else:            left_l.append (i)    left_l = func (left_l)    right_l = func (right_l)    return left_l + [base] + right_l        if __name__ = = "__main__": 
   l = [1, 3, 4, 8, $,, +, +]    print func (l)


Python implements a fast sorting algorithm

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.