Question

In Java, Write a function to perform bucket sort on a list of strings.Test the function...

In Java,

Write a function to perform bucket sort on a list of strings.Test the function to see if it really works in linear time on average. Finally, compare the performance of the function with Java sort method for lists.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Bucket sort on list of Strings

public void sort(String[] array)

{

if(array.length == 0)

return ;

//find the max length

int max=0;

for(int i=1; i<array.length; i++)

{

//update max length

if(max < array[i].length())

max=array[i].length();

}

//initialize the buckets

int bucketCount=26; //alphabets

//buckets in maps

HashMap<Character, Vector<String>> buckets=new HashMap<Character, Vector<String>>(bucketCount);

//create the buckets

char a='a';

for(int i=0; i<=bucketCount; i++; a++)

{

buckets.put(a, new Vector<String>());

}

//assign String array values into the buckets

for(int i=0; i<array.length; i++)

{

//get the first letter of the String word

String current=array[i];

char letter=current.toLowerCase().charAt(0);

buckets.get(letter).add(array[i]);

}

//sort the buckets and put them into input array

int index=0;

for(char key='a'; key<='z'; key++)

{

//retrieve the bucket

Vector<String> bucket=buckets.get(key);

//perform sort on bucket

for(int i=1; i<bucket.size(); i++)

{

String temp=bucket.get(i);

bucket.remove(i);

int j;

for(j=i-1; j>=0 && bucket.get(j).compareToIgnoreCase(temp) > 0; j--)

{

bucket.add(j+1, bucket.get(j));

bucket.remove(j);

}

bucket.add(j+1, temp);

}

//pile the current bucket back into array

for(int j=0; j<bucket.size(); j++)

array[index++]=bucket.get(j);

  }

}

Add a comment
Know the answer?
Add Answer to:
In Java, Write a function to perform bucket sort on a list of strings.Test the function...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT