Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
12-04-2011, 06:08 AM #1
- Join Date
- Dec 2011
- Thanked 0 Times in 0 Posts
Help sorting an array of strings that contain letter, dashes, and numbers?
I am a student and cannot use one of java's built in sort methods. The strings are in the format LDD-DDDDD, where L can be a letter B,M or P.
D represents a digit. i.e. B09-00002. Our teacher has specified that we must use the "selection sort" method for sorting integers and modify it to work in this situation. There are several other parts to the program that I have already done, but I can't think my way through this one. Please help me, I have to take my final in 2 days (well one now), and I haven't been able to study because I am so busy trying to finish this last assignment. Please try to go in depth, as I really need to understand how to do this.
12-04-2011, 03:31 PM #2
- Join Date
- Sep 2002
- Saskatoon, Saskatchewan
- Thanked 2,662 Times in 2,631 Posts
All sorting algorithms essentially come down to 1 common feature. They compare. Custom object collections are easiest done by implementing Comparable<?> onto the custom object, which then performs the comparison. Dealing directly with strings, you can still use a built in sort by using the Comparator<T> instead.
If you are mandated to use a custom selection sort, its simply a matter of creating an overload that accepts a comparator. The wiki has a pretty good article for a selection sort: http://en.wikipedia.org/wiki/Selection_sort
The key to change would be this line (granted this appears to be in C, but it is basic enough that it appears that it would compile in java as well):
if (a[i] < a[iMin]). At this step, you cannot check a direct comparison between the two, but if you are given a comparator you can use
if (comparatorGiven.compare(a[i], a[iMin]) < 0)to indicate that the second argument is less than the first.
As for the comparator itself, I'm not sure exactly what you are trying to sort by. Given the look of it, I'd say you want to treat it fully as a string (only as a number on a per digit basis), and start from the end of each string working back to the beginning comparing character by character. This way the one with the highest leader will prevail. The end result of something like: B09-00002 compared to A09-00002 would result in +1 since the 'A' is greater than the 'B'.