简体   繁体   中英

radix sort (java implementation) complexity

this is my first question so I hope I haven't broken any rules. I have finally just managed to write code for the Radix Sort algorithm but I am wondering if I have done it wrong. What makes me think that is that my algorithm looks of complexity O(n^3) but Radix Sort is notoriously a O(kn) algorithm. Am I calculating the complexity of my algorithm wrong or did I just write really bad code?

private static void radixSort(int[] A){
    ArrayList<Integer>[] bucket = new ArrayList[10];
    int maxNumberOfDigits = 0;
    for(int number : A){
        if(numberOfDigitsIn(number) > maxNumberOfDigits) maxNumberOfDigits = numberOfDigitsIn(number);
    }
    for(int c=0; c<bucket.length; c++){
        bucket[c] = new ArrayList<Integer>();
    }
    int i = 0;
    int digit;
    int j;
    while(i < maxNumberOfDigits){
        for(j = 0; j<A.length; j++){
            digit = getDigit(A[j], i);
            bucket[digit].add(A[j]);
        }

        int index = 0;
        for(int z = 0; z<bucket.length; z++){
            for (int k=0; k<bucket[z].size(); k++){
                A[index] = bucket[z].get(k);
                index += 1;

            }
            bucket[z].clear();
        }
        i += 1;
    }
}

The methods getDigit() and numberOfDigitsIn() are of constant time.

  for(int z = 0; z<bucket.length; z++){ for (int k=0; k<bucket[z].size(); k++){ 

The crucial thing here is that the sum total of all the bucket sizes will equal n, so these loops combined only take O(n). The loop over j takes O(n), and the while loop on i will run for maxNumberOfDigits iterations, and that number represents k in the O(kn) runtime you described. So the total is, in fact, O(kn).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM