Example of the bucket sorting algorithm implemented by Python and the python Sorting Algorithm

Source: Internet
Author: User

Example of the bucket sorting algorithm implemented by Python and the python Sorting Algorithm

This example describes the bucket sorting algorithm implemented by Python. We will share this with you for your reference. The details are as follows:

Bucket sorting is also called counting sorting. Simply put, all the elements in the dataset are listed in order, and then the number of times the elements appear is counted. Finally, the elements in the dataset are output in sequence.

However, bucket sorting is a waste of space. For example, the sorting range is 0 ~ Between 2000, the number to be sorted is [2001,], and spaces are also required

Note:The bucket sorting cannot sort decimal places.

The following is code implementation from small to large:

#! /Usr/bin/env python # coding: utf-8def bucketSort (nums): # select a maximum number of max_num = max (nums) # create a list of elements all 0, as bucket = [0] * (max_num + 1) # Put all elements into the bucket, that is, add the number of corresponding elements to one for I in nums: bucket [I] + = 1 # store sort_nums = [] # retrieve the elements in the bucket for j in range (len (bucket): if bucket [j]! = 0: for y in range (bucket [j]): sort_nums.append (j) return sort_numsnums = [,] print "helper's house test result: "print bucketSort (nums)" "[0, 0, 1, 2, 2, 3, 5, 6, 8, 65]"

Running result:

In general, the advantage of Bucket sorting is that it is very fast and really fast! Very fast! Special Block! The disadvantage is resource consumption. If the data value range is 0---1010, you need to apply for an array with a size of 1010. Fear! The sorting of buckets can only be an integer greater than zero.

PS: For more information about sorting algorithms, see online tools on this site:

Online animation demo insert/select/bubble/merge/hill/Quick Sort Algorithm process Tool
Http://tools.jb51.net/aideddesign/paixu_ys

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.