Python algorithm sorting for fast sorting

Source: Internet
Author: User

QUICKSORT (A, p, r) is A subroutine for fast sorting. It calls the division program to divide the array, and then recursively calls QUICKSORT (A, p, r ), to complete the quick sorting process. The worst time complexity of quick sorting is O (n2), and the usual time complexity is O (nlgn ). The worst time complexity is when the array is basically ordered, and the average time complexity is when the value distribution of the array is relatively average. In normal cases, the time complexity of fast sorting and heap sorting is O (nlgn), but the constant term of quick sorting is small, so it is better than heap sorting.
PARTITION (A, p, r) Copy codeThe Code is as follows: x using A [r]
I branch p-1
For j then p to r-1
Do if A [j] ≤ x
Then I have I + 1
Swap (A [I], A [j])
Swap (A [I + 1], A [r])
Return I + 1

QUICKSORT (A, p, r)Copy codeThe Code is as follows: if p <r
Then q PARTITION (A, p, r)
QUICKSORT (A, p, q-1)
QUICKSORT (A, q + 1, r)

Implementation:Copy codeThe Code is as follows :#! /Usr/bin/python
Import sys
Def partion (array, p, r ):
X = array [r]
I = p-1
For j in range (p, r ):
If (array [j] <x ):
I + = 1
Array [j], array [I] = array [I], array [j]
I + = 1
Array [I], array [r] = array [r], array [I]
Return I
Def quick_sort (array, p, r ):
If p <r:
Q = partion (array, p, r)
Quick_sort (array, p, q-1)
Quick_sort (array, q + 1, r)
If _ name _ = "_ main __":
Array = [1, 3, 5, 23, 64, 7, 23, 6, 34, 98,100, 9]
Quick_sort (array, 0, len (array)-1)
For a in array:
Sys. stdout. write ("% d" %)

Related Article

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.