Ticker

6/recent/ticker-posts

Radix Sort - Java

Radix Sort - Java



In this sorting algo, we use radix method to solve sorting.

we use counting sort as a base sorting algo in radix sorting. we are using stable counting algorithm.
package com.company;

public class Main {

public static void main(String[] args) {
int[] intArray = {4725, 4586, 1330, 8792, 1594, 5729};

radixSort(intArray, 10, 4);

for(int num: intArray) {
System.out.println(num);
}
}

public static void radixSort(int[] input, int radix, int width) {
for(int i=0 ; i<width ; i++) {
radixSingleSort(input, i, radix);
}
}

public static void radixSingleSort(int[] input, int pos, int radix){

int numItems = input.length;
int[] countArray = new int[radix];

for(int value: input) {
countArray[getDigit(pos, value, radix)]++;
}

// adjust the count array
for(int j=1 ; j<radix ; j++){
countArray[j] += countArray[j-1];
}

int[] temp = new int[numItems];
for(int tempIndex = numItems-1 ; tempIndex >= 0 ; tempIndex--) {
temp[--countArray[getDigit(pos, input[tempIndex], radix)]] = input[tempIndex];
}

System.arraycopy(temp,0, input, 0, numItems);
}

public static int getDigit(int position, int value, int radix){
return value / (int) Math.pow(radix, position) % radix;
}
}

Post a Comment

0 Comments