码迷,mamicode.com
首页 > 其他好文 > 详细

radix sort

时间:2014-08-28 04:17:08      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:blog   http   for   ar   div   代码   log   sp   line   

(radix sort)

Problem Statement
Given an integer array of length N, containing values in the range 1,2,3…N^2. Sort the array in O(N) time.

 

bubuko.com,布布扣
//http://www.geeksforgeeks.org/sort-n-numbers-range-0-n2-1-linear-time/

public class RadixSort {
 
    public void radixSort(int arr[], int maxDigits){
        int exp = 1;//10^0;
        for(int i =0; i < maxDigits; i++){
            ArrayList bucketList[] = new ArrayList[10];
            for(int k=0; k < 10; k++){
                bucketList[k] = new ArrayList();
            }
            for(int j =0; j < arr.length; j++){
                int number = (arr[j]/exp)%10;
                bucketList[number].add(arr[j]);
            }
            exp *= 10;
            int index =0;
            for(int k=0; k < 10; k++){
                for(int num: bucketList[k]){
                    arr[index] = num;
                    index++;
                }
            }
        }
 
        System.out.println("Sorted numbers");
        for(int i =0; i < arr.length; i++){
            System.out.print(arr[i] +", ");
        }
    }
 
    public static void main(String[] argv){
        int n = 5;
        int arr[] = {1,4,2,3,5,10,8};
        new RadixSort().radixSort(arr, 2);
    }
}






quicksort to find the nth in liner time.

radix sort

标签:blog   http   for   ar   div   代码   log   sp   line   

原文地址:http://www.cnblogs.com/leetcode/p/3940711.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!