Python algorithm sorting for fast sorting

Source: Internet
Author: User
QUICKSORT (A, p, R) is a subroutine that quickly sorts, calls the partitioning program to divide the array, and then recursively calls QUICKSORT (A, p, R) to complete the process of fast sorting. The worst time complexity for fast sorting is O (N2), and the time complexity is O (NLGN). The worst-case-time complexity is when the average time complexity of an array is more than the average when the number of times is fairly uniform. In peacetime, the time complexity of fast sorting and heap sorting is O (NLGN), but the fast sort constant is smaller, so it is better than heap sorting.
PARTITION (A, p, R)
Copy CodeThe code is 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 CodeThe code is as follows:


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


Realize:
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"% 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.