Question
In Java. modify the radix sort method to allow strings of various lengths to be properly sorted WITHOUT any additional data structures used to store
In Java. modify the radix sort method to allow strings of various lengths to be properly sorted WITHOUT any additional data structures used to store data
i.e. array.sort or Compareto()
For example:
abdef
abd
abde
Would be sorted to..
abd
abde
abdef
Method:
public static void radixSortStrings(String[] arr, int strLen)
{
//number of buckets = 256 (characters in the character set)
int buckets = 256;
//if you were doing a case insensitive sort, and you knew everything was single words, you could use 26 as your size
//Buckets need to be lists instead of counters
ArrayList
//create array of lists and initialize each object
for(int i = 0; i < buckets; i++)
{
bucket[i] = new ArrayList<>();
}
//pointer for position in original list
int index = 0;
//loop from end of string to beginning
for(int i = strLen-1; i >= 0; i--)
{
index = 0;
//loop through each string
for(int j = 0; j < arr.length; j++)
{
//add to appropriate bucket
bucket[(int)arr[j].charAt(i)].add(arr[j]);
}
System.out.println("Sorted on character "+i);
//loop through buckets
for(int j = 0; j < bucket.length; j++)
{
if(bucket[j].size() > 0)
System.out.println(j+":"+bucket[j].toString());
//add each string back to original array in new order
for(String s : bucket[j])
{
arr[index] = s;
index++;
}
//clear the bucket
bucket[j].clear();
}
}
}
:
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started