Python algorithm learning-counting sorting instance

Source: Internet
Author: User
This code introduces the counting sorting instance in python algorithm learning. for details about the code, refer to the example of using python algorithm learning for counting sorting.

The code is as follows:


#-*-Coding: UTF-8 -*-

Def _ counting_sort (A, B, k ):
"Counts are sorted. the pseudo code is as follows:
COUNTING-SORT (A, B, k)
1 for I defaults 0 to k // initialize the value of the bucket
2 do C [I] defaults 0
3 for j every 1 to length [A] // count each value
4 do C [A [j] ← C [A [j] + 1
5. Objective C [I] contains the number of elements equal to I
6 for I limit 1 to k // calculate the sum of counts and determine the number of elements <= each value
7 do C [I] ← C [I] + C [i-1]
8. Objective C [I] contains the number of elements smaller than or equal to I
9 for j segment length [A] downto 1
10 do B [C [A [j] then A [j] // place the [j] value in the corresponding position
11 C [A [j] ← C [A [j]-1 // avoid element overwriting at the same time

T (n) = θ (n)

Args:
A (Sequence): Original array
B (Sequence): result array
K (int): the maximum value. it is assumed that all elements are between [0, k].
"""
Len_c = k + 1
C = [0] * len_c
For a in:
C [a] = C [a] + 1
For I in range (1, len_c ):
C [I] = C [I] + C [i-1]
For a in A [:-1]:
B [C [a]-1] =
C [a] = C [a]-1

Def counting_sort ():
"Assuming that all elements in array A are between [0, len (A)-1]"
B = [0] * len ()
_ Counting_sort (A, B, len (A)-1)
Return B

If _ name _ = '_ main __':
Import random, timeit

Items = range (1, 10000)
Random. shuffle (items)

Def test_sorted ():
Print (items)
Sorted_items = sorted (items)
Print (sorted_items)

Def test_counting_sort ():
Print (items)
Sorted_items = counting_sort (items)
Print (sorted_items)

Test_methods = [test_sorted, test_counting_sort]
For test in test_methods:
Name = test. _ name _ # test. func_name
T = timeit. Timer (name + '()', 'from _ main _ import '+ name)
Print (name + 'takes time: % f' % t. timeit (1 ))

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.