Python sorting algorithm-bucket sorting and base sorting

Source: Internet
Author: User

1. Sort buckets

Sort buckets in the range of 1-m in 1.1

If an array A contains N integers ranging from 1 to M, we can get A very fast sort by bucket sort ). Hold an array S, which contains M buckets and is initialized to 0. Then traverse array A and add one to S [Ai] When Reading Ai. After all the inputs are read, scan the array S to get the sorted table. This algorithm takes O (M + N) time, and space cannot be sorted in situ.

Initialization sequence S

Traverse A and modify S in sequence

For example, sort an array [5, 3, 6, 1, 2, 7, 5, 10]

The values are between 1 and 10, and 10 buckets are created:

[0 0 0 0 0 0 0 0 0] Bucket

[1 2 3 4 5 6 7 8 9 10] The value of the bucket

Traverse the array. The first number is 5, and the fifth bucket is added with 1.

[0 0 0 0 1 0 0 0 0]

The second digit 3, the third bucket plus 1

[0 0 1 0 1 0 0 0 0 0]

After Traversal

[1 1 0 2 1 0 0 1]

Output

[1 2 3 5 5 6 7 10]

Code

import randomclass bucketSort(object):    def _max(self,oldlist):        _max=oldlist[0]        for i in oldlist:            if i>_max:                _max=i        return _max    def _min(self,oldlist):        _min=oldlist[0]        for i in oldlist:            if i<_min:                _min=i        return _min    def sort(self,oldlist):        _max=self._max(oldlist)        _min=self._min(oldlist)        s=[0 for i in xrange(_min,_max+1)]        for i in oldlist:            s[i-_min]+=1        current=_min        n=0        for i in s:            while i>0:                oldlist[n]=current                i-=1                n+=1            current+=1    def __call__(self,oldlist):        self.sort(oldlist)        return oldlistif __name__=='__main__':    a=[random.randint(0,100) for i in xrange(10)]    bucketSort()(a)    print a

Sorting of evenly distributed buckets in the 1.2 interval [)

When the input is evenly distributed, for example, the elements are evenly distributed in the interval [0, 1), you can combine the bucket sorting method with other sorting methods.

If the sequence size is n, [0, 1) is divided into n sub-intervals (buckets) of the same size, and n input numbers are distributed to each bucket. Sort the number in each bucket first, and then list the elements in each bucket in order.

Description of algorithm:

Code:

class bucketSort(object):    def insertSort(self,a):        n=len(a)        if n<=1:            pass        for i in range(1,n):            key=a[i]            j=i-1            while key<a[j] and j>=0:                a[j+1]=a[j]                j-=1            a[j+1]=key    def sort(self,a):        n=len(a)        s=[[] for i in xrange(n)]        for i in a:            s[int(i*n)].append(i)        for i in s:            self.insertSort(i)        return [i for j in s for i in j]    def __call__(self,a):        return self.sort(a)                      if __name__=='__main__':    from random import random    from timeit import Timer    a=[random() for i in xrange(10000)]    def test_bucket_sort():        bucketSort()(a)    def test_builtin_sort():        sorted(a)    tests=[test_bucket_sort,test_builtin_sort]    for test in tests:                name=test.__name__        t=Timer(name+'()','from __main__ import '+name)        print t.timeit(1)
2. Base sorting

Base sorting is generally used as an array composed of elements with the same length. First, sort by the lowest valid number, and then proceed from low to high.

329 72 70 29

457 35 39 55

657 43 46 36

839 ==== 45 ==== 89 === 57

436 65 35 57

720 32 47 20

355 83 67 39

The base sorting can be seen as sorting Multiple Buckets. Each valid number is between 0-9, which is suitable for sorting buckets. It is convenient to create 10 buckets.

Sort arrays 64, 8, 216,512, 27,729, 343,125

First sort:

51 34 6 12 21 2 72

0 1 2 3 4 5 6 7 8 9

Second sort:

8 79

1 26 7

0 52 15 33 4

0 1 2 3 4 5 6 7 8 9

Third sort:

64

27

8

1

0 25 16 43 12 29

0 1 2 3 4 5 6 7 8 9

Output: 1 8 27 64 125 216 343 512

Code:

Import randomdef radixSort (): A = [random. randint (10000) for I in xrange ()] for k in xrange (4): #4 round sorting s = [[] for I in xrange (10)] for I in A: s [I/(10 ** k) % 10]. append (I) A = [a for B in s for a in B] return

  

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.