A fast sort _python based on Python algorithm

Source: Internet
Author: User
QUICKSORT (A, p, R) is a fast-sequencing subroutine that calls the partitioning program to partition the array, and then recursively calls QUICKSORT (A, p, R) to complete the quick sort process. The worst time complexity for fast sorting is O (N2), and the time complexity is O (NLGN). When the worst time complexity is in an orderly array, the average time complexity is more evenly distributed than the numerical distribution of the group. In peacetime, the time complexity of sorting and stacking is O (NLGN), but the fast-sorted constants are smaller, so they are better than heap sorting.
PARTITION (A, p, R)
Copy Code code as follows:

X←A[R]
I←p-1
For J←p to R-1
Do if a[j]≤x
Then i←i + 1
Swap (A[i], a[j])
Swap (A[i + 1], A[r])
return i + 1

QUICKSORT (A, p, R)
Copy Code code as follows:

If P < r
Then Q←partition (A, p, R)
QUICKSORT (A, p, q-1)
QUICKSORT (A, q + 1, R)

Realize:
Copy Code code 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"% a)

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.