美文网首页
基数排序

基数排序

作者: Lemon_Home | 来源:发表于2018-01-04 10:46 被阅读21次

    基数排序并不需要直接对元素进行相互比较,也不需要将元素相互交换,需要做的就是对元素进行“分类”。根据关键字中各位的值,通过对排序的N个元素进行若干趟“分配”与“收集”来实现排序的。

    • java
    public class Ridex {
        public static void sort(int[] array) {
            int max = array[0];
            for (int i = 1; i < array.length; i++) {
                if (array[i] > max) {
                    max = array[i];
                }
            }
            int time = 0;
            while (max > 0) {
                max /= 10;
                time++;
            }
            List<ArrayList> queue = new ArrayList<ArrayList>();
            for (int i = 0; i < 10; i++) {
                ArrayList<Integer> queue1 = new ArrayList<Integer>();
                queue.add(queue1);
            }
            for (int i = 0; i < time; i++) {
                for (int j = 0; j < array.length; j++) {
                    int x = array[j] % (int) Math.pow(10, i + 1) / (int) Math.pow(10, i);
                    ArrayList<Integer> queue2 = queue.get(x);
                    queue2.add(array[j]);
                    queue.set(x, queue2);
                }
                int count = 0;
                for (int k = 0; k < 10; k++) {
                    while (queue.get(k).size() > 0) {
                        ArrayList<Integer> queue3 = queue.get(k);
                        array[count] = queue3.get(0);
                        queue3.remove(0);
                        count++;
                    }
                }
            }
        }
    
        public static void show(int[] a) {
            for (int i = 0; i < a.length; i++) {
                System.out.print(a[i] + " ");
            }
            System.out.println();
        }
    
        public static void main(String[] args) {
            int[] a = {80, 30, 11160, 40, 20, 10, 2250, 170};
            sort(a);
            show(a);
        }
    }
    
    • python
    import math
    
    
    class Radix:
        def radix_sort(self, data, radix=10):
            k = int(math.ceil(math.log(max(data), radix)))
            bucket = [[] for i in range(radix)]
            for i in range(1, k + 1):
                for j in data:
                    bucket[j // (radix ** (i - 1)) % radix].append(j)
                del data[:]
                for z in bucket:
                    data += z
                    del z[:]
            return data
    
    
    if __name__ == "__main__":
        s = [80, 30, 11160, 40, 20, 10, 2250, 170]
        radix = Radix()
        print(radix.radix_sort(s))
    

    相关文章

      网友评论

          本文标题:基数排序

          本文链接:https://www.haomeiwen.com/subject/rcmvbxtx.html