zoukankan      html  css  js  c++  java
  • 【程序员笔试面试必会——排序②】Python实现 计数排序、基数排序

    一、计数排序

    概要:  

      时间复杂度O(n),空间复杂度O(k),k是输入序列的值的范围(最大值-最小值),是稳定的。计数排序一般用于已知输入值的范围相对较小,比如给公司员工的身高体重信息排序。

    思路:

       输入数组A为{3,5,1,2,4,3},值的范围是1~5,所以创建5个桶,序号1,2,3,4,5。装桶时遍历一遍输入数组,A[0]=3,把它放到3号桶;A[1]=5,放到5号桶;1放到1号桶……最后3放到3号桶。现在三号桶的值为2,其他桶的值为1,再遍历一遍桶数组,按顺序把桶倒出,元素被倒出的顺序就是排序的顺序了。

    Python实现:

    # coding:utf-8
    class CountingSort:
        def countingSort(self, A, m):
            result = []
            A_min = min(A)
            A_max = max(A)
            buckets_len = A_max - A_min + 1
            buckets = [0] * buckets_len  # 创建桶
            # 装桶
            for n in A:
                buckets[n-A_min] += 1
            # 桶倒出
            for i in xrange(buckets_len):
                value = i + A_min
                n = buckets[i]
                result += [value] * n
            return result
    
    l = [54, 35, 48, 36, 27, 12, 44, 44, 8, 14, 26, 17, 28]
    print CountingSort().countingSort(l, len(l))

    二、基数排序

    思路:

      首先准备0号桶~9号桶:

        

      根据个位上的数值选择几号桶,后再将数字依次倒出桶:

          

      根据序列的顺序十位上的数值选择几号桶,后再将数字依次倒出桶:

          

      根据序列的顺序百位上的数值选择几号桶,后再将数字依次倒出桶,最后一次倒出桶的顺序就是排序的顺序:

          

     Python实现:

    # -*- coding:utf-8 -*-
    
    class RadixSort:
        def radixSort(self, A, n):
            order_array = A
            buckets = [[] for i in xrange(10)]  # 生成桶
            radix = 1  # 基数为1代表个位
            max_radix = 10 ** len(str(max(order_array)))  # 这些数的最大位
            while radix < max_radix:
                for n in order_array:
                    digit = (n / radix) % 10  # 个位、十位、百位...
                    buckets[digit].insert(0, n)  # 将数字添加到桶中
    
                i = 0
                for pour_nums in buckets:
                    while pour_nums:
                        order_array[i] = pour_nums.pop()
                        i += 1
                radix *= 10
            return order_array
    
    l = [54, 35, 48, 36, 27, 12, 44, 44, 8, 14, 26, 17, 28]
    print RadixSort().radixSort(l, len(l))
  • 相关阅读:
    Eclipse配置方法注释模板
    彻底清除Github上某个文件以及历史
    eclipse快捷键
    Hibernate执行原生SQL
    API接口规范
    eclipse配置google代码风格
    eclipse format xml
    git撤销commit
    使用postman测试文件上传
    centos7下部署elasticSearch集群
  • 原文地址:https://www.cnblogs.com/wangchaowei/p/8302183.html
Copyright © 2011-2022 走看看