Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Java > Using Java Classes to Sort a Small Array Quickly

Reply
Thread Tools

Using Java Classes to Sort a Small Array Quickly

 
 
KevinSimonson
Guest
Posts: n/a
 
      09-01-2011
I have an <enum> named <ProjectEnum> that has twelve values. Today I
added an instance variable to it, a <String> named <collectionTitle>.
The engineer I'm working with asked me to write a static method in
class <ProjectEnum> that returns an array of <ProjectEnum>s sorted
alphabetically by this value <collectionTitle>.

I wrote a little program that compares the performance of
SelectionSort and InsertionSort on comparable arrays of <String>s, and
discovered that InsertionSort sorts in about half the amount of time
that InsertionSort does, at least on our machines. Therefore I
implemented my static method, <alphaSort()>, using InsertionSort.

On the way home from work my fellow carpooler told me that there are
Java classes that can do sorts in O(N) time. That would be an
improvement, since although InsertionSort is faster than
SelectionSort, it's still an O(N^2) algorithm. So I went looking, but
all I could find was the <sort()> method from the <Collections>
class. I replaced my code for SelectionSort with a loop that reads
the input array into an <ArrayList< String>> object, calls <sort()> on
the <ArrayList< String>> object, and then reads the values back into
the array; and then ran my test code again. This method was
significantly faster than SelectionSort, but my InsertionSort code
still beat it.

So I guess my question is, <b><i>is</i></b> there a way in Java to
sort an array of <String>s (or perhaps more to the point to sort an
array of <ProjectEnum>s) that runs in O(N) time? Or even that runs in
O(N^2) time but faster than InsertionSort? I'd appreciate any
information anyone can give me on this.

Kevin Simonson
 
Reply With Quote
 
 
 
 
markspace
Guest
Posts: n/a
 
      09-01-2011
On 8/31/2011 7:48 PM, KevinSimonson wrote:
> On the way home from work my fellow carpooler told me that there are
> Java classes that can do sorts in O(N) time.



Pfft. No. Theoretical maximum speed of a sort is something like n log
n. The only data you can sort in n time is data that's already sorted.


> my InsertionSort code
> still beat it.



How many projects can you have? For small arrays anything is fast and
even a bubble sort should work fine. If you have many projects... how
do you code that up as an enum anyway?

Sorry but there's a little red flashing light labeled "warning!" that's
going off in my mind right now.



 
Reply With Quote
 
 
 
 
Eric Sosman
Guest
Posts: n/a
 
      09-01-2011
On 8/31/2011 10:48 PM, KevinSimonson wrote:
> I have an<enum> named<ProjectEnum> that has twelve values. Today I
> added an instance variable to it, a<String> named<collectionTitle>.
> The engineer I'm working with asked me to write a static method in
> class<ProjectEnum> that returns an array of<ProjectEnum>s sorted
> alphabetically by this value<collectionTitle>.
>
> I wrote a little program that compares the performance of
> SelectionSort and InsertionSort on comparable arrays of<String>s, and
> discovered that InsertionSort sorts in about half the amount of time
> that InsertionSort does, at least on our machines. Therefore I
> implemented my static method,<alphaSort()>, using InsertionSort.


Failed to find Arrays.sort, did you?

> On the way home from work my fellow carpooler told me that there are
> Java classes that can do sorts in O(N) time.


Possible, perhaps, for restricted key types and given some
assumptions about the possible values: For instance, it's easy to
sort an array of `boolean' in O(N) time. But quite clearly *not*
possible for sorts based on pairwise comparisons, since log(N!)
grows faster than O(N).

> That would be an
> improvement, since although InsertionSort is faster than
> SelectionSort, it's still an O(N^2) algorithm.


So? N in your case is twelve. There's no point in studying the
behavior "as twelve approaches infinity," becase it doesn't.

Besides, you're misusing O. Suppose I offer you two algorithms,
one whose running time is O(N^2) and the other O(N). Which is faster?
Before you say "O(N), nitwit," let me show you the actual timing
formulae:

T1(N) = N * N (nanoseconds)
T2(N) = N (gigayears)

T1(N) is clearly O(N^2), while T2(N) is O(N). Which do you choose
for sorting N=12 items?

> So I went looking, but
> all I could find was the<sort()> method from the<Collections>
> class.


Either your looking was extremely cursory, or you haven't learned
how to look. I'm not sure how you found Collections.sort, but *if*
you had opened the Javadoc, gone to the "S" index page, and hunted for
the word "sort," you'd have found Arrays.sort right next door to it.

> I replaced my code for SelectionSort with a loop that reads
> the input array into an<ArrayList< String>> object, calls<sort()> on
> the<ArrayList< String>> object, and then reads the values back into
> the array; and then ran my test code again. This method was
> significantly faster than SelectionSort, but my InsertionSort code
> still beat it.


Your improved Javadoc searching skills would have found Arrays.sort,
which might have directed your attention to the Arrays class as a whole
and led you to discover Arrays.asList. Or possibly not, because you
have no need of a List anyhow. Meanwhile you've run "seven times around
the seven hills of Rome," and it's no surprise that the unnecessary trip
has made your task take longer than it needed to.

> So I guess my question is,<b><i>is</i></b> there a way in Java to
> sort an array of<String>s (or perhaps more to the point to sort an
> array of<ProjectEnum>s) that runs in O(N) time? Or even that runs in
> O(N^2) time but faster than InsertionSort? I'd appreciate any
> information anyone can give me on this.


Probably nothing of O(N); see remarks above. Also probably
nothing as bad as O(N^2), but you can always do the hills of Rome
thing to slow down a better method if you want.

BUT, BUT, BUT! Your N is a constant, a small constant! Even if
your hand-crafted sort runs at ten times the speed of Arrays.sort,
I posit that you have already expended more time than your speedy
method will ever recoup: If Arrays.sort takes a microsecond while
yours takes 100 nanoseconds, and if all your investigation and
implementation (and writing to Usenet) took just ten minutes, you
need more than six hundred billion fast sorts merely to break even.
Modify the arithmetic as needed in light of your actual measurements,
then turn your talents elsewhere instead of wasting them on a non-
problem.

--
Eric Sosman
http://www.velocityreviews.com/forums/(E-Mail Removed)d
 
Reply With Quote
 
Eric Sosman
Guest
Posts: n/a
 
      09-01-2011
On 9/1/2011 12:25 AM, Eric Sosman wrote:
>[...] If Arrays.sort takes a microsecond while
> yours takes 100 nanoseconds, and if all your investigation and
> implementation (and writing to Usenet) took just ten minutes, you
> need more than six hundred billion fast sorts merely to break even.


"For suitable values of a billion," like those that begin
with an "M" instead of a "B."

<FX: dope slap>

--
Eric Sosman
(E-Mail Removed)d
 
Reply With Quote
 
Robert Klemme
Guest
Posts: n/a
 
      09-01-2011
On 01.09.2011 04:48, KevinSimonson wrote:
> I have an<enum> named<ProjectEnum> that has twelve values. Today I
> added an instance variable to it, a<String> named<collectionTitle>.
> The engineer I'm working with asked me to write a static method in
> class<ProjectEnum> that returns an array of<ProjectEnum>s sorted
> alphabetically by this value<collectionTitle>.


Since we're talking about an enum and I am sure you made field "name"
final (i.e. to make instances immutable) you can completely ignore sort
performance. You just need to sort once. For example:

package en;

import java.util.Arrays;
import java.util.Comparator;

public enum ProjectEnum {

P1("xyz"), P2("abc"), P3("def");

private final String collectionTitle;

private ProjectEnum(String name) {
if (name == null) {
throw new NullPointerException();
}

this.collectionTitle = name;
}

public String getCollectionTitle() {
return collectionTitle;
}

private static final ProjectEnum[] sortedValues;

static {
sortedValues = ProjectEnum.values();

Arrays.sort(sortedValues, new Comparator<ProjectEnum>() {
@Override
public int compare(ProjectEnum o1, ProjectEnum o2) {
return o1.getCollectionTitle().compareTo(o2.getCollection Title());
}
});
}

public static ProjectEnum[] sorted() {
return Arrays.copyOf(sortedValues, sortedValues.length);
}
}

Kind regards

robert

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
 
Reply With Quote
 
RedGrittyBrick
Guest
Posts: n/a
 
      09-01-2011
On 01/09/2011 03:48, KevinSimonson wrote:
> I have an<enum> named<ProjectEnum> that has twelve values. Today I
> added an instance variable to it, a<String> named<collectionTitle>.
> The engineer I'm working with asked me to write a static method in
> class<ProjectEnum> that returns an array of<ProjectEnum>s sorted
> alphabetically by this value<collectionTitle>.
>
>
> is there a way in Java to
> sort an array of<String>s (or perhaps more to the point to sort an
> array of<ProjectEnum>s) that runs in O(N) time? Or even that runs in
> O(N^2) time but faster than InsertionSort? I'd appreciate any
> information anyone can give me on this.



If I was sorting twelve elements, I would consider myself utterly
deranged if I found myself worrying about the sort algorithm.



If the static method will be called millions of times per second, you
might want to cache the sort results rather than pointlessly repeating
the sort, but only after measuring a performance problem and working out
if this method really needs to be called that often.

--
RGB
 
Reply With Quote
 
Roedy Green
Guest
Posts: n/a
 
      09-01-2011
On Wed, 31 Aug 2011 19:48:02 -0700 (PDT), KevinSimonson
<(E-Mail Removed)> wrote, quoted or indirectly quoted someone who
said :

>
>I wrote a little program that compares the performance of
>SelectionSort and InsertionSort on comparable arrays of <String>s, and
>discovered that InsertionSort sorts in about half the amount of time
>that InsertionSort does, at least on our machines. Therefore I
>implemented my static method, <alphaSort()>, using InsertionSort.


The bulit-in sort in Java beats everything I have thrown at it except
a RadixSort for some cases. I have posted the code for a number of
different algorithms, including RadixSort, HeapSort, BubbleSort,
ShellSort, QuickSort. InsertionSort and SelectionSort are too
disgusting to code.

See http://mindprod.com/jgloss/sort.html

I have also written an applet that generates Comparator/Comparable
classes.
See http://mindprod.com/applet/comparator.html

Java has a built-in sort mechanism with Comparator and Comparable
interfaces. Even if you experiment with your own sorts, they should
use the standard interface.
--
Roedy Green Canadian Mind Products
http://mindprod.com
The modern conservative is engaged in one of man's oldest exercises in moral philosophy; that is,
the search for a superior moral justification for selfishness.
~ John Kenneth Galbraith (born: 1908-10-15 died: 2006-04-29 at age: 97)
 
Reply With Quote
 
Roedy Green
Guest
Posts: n/a
 
      09-01-2011
On Wed, 31 Aug 2011 20:39:09 -0700, markspace <-@.> wrote, quoted or
indirectly quoted someone who said :

>
>Pfft. No. Theoretical maximum speed of a sort is something like n log
>n. The only data you can sort in n time is data that's already sorted.


see http://mindprod.com/jgloss/radixsort.html

Surely you remember mechanical card sorters. They did precisely that.
--
Roedy Green Canadian Mind Products
http://mindprod.com
The modern conservative is engaged in one of man's oldest exercises in moral philosophy; that is,
the search for a superior moral justification for selfishness.
~ John Kenneth Galbraith (born: 1908-10-15 died: 2006-04-29 at age: 97)
 
Reply With Quote
 
Roedy Green
Guest
Posts: n/a
 
      09-01-2011
On Thu, 01 Sep 2011 00:25:04 -0400, Eric Sosman
<(E-Mail Removed)> wrote, quoted or indirectly quoted
someone who said :

> Either your looking was extremely cursory, or you haven't learned
>how to look. I'm not sure how you found Collections.sort, but *if*
>you had opened the Javadoc, gone to the "S" index page, and hunted for
>the word "sort," you'd have found Arrays.sort right next door to it.


Here are three techniques to see if Java has some built-in capability.

You need an indexing tool like Copernic to find plausible method names
in the JavaDoc that you can download and insert in the JDK.

Alternatively you can use a tool like Funduc Search and replace or
Extract http://mindprod/products1.html#EXTRACT to linearly search for
regular expressions.

The other technique is to Google something like [sort Java array] and
see what code pops up. Look for the relevant classes and consult the
Javadoc.
--
Roedy Green Canadian Mind Products
http://mindprod.com
The modern conservative is engaged in one of man's oldest exercises in moral philosophy; that is,
the search for a superior moral justification for selfishness.
~ John Kenneth Galbraith (born: 1908-10-15 died: 2006-04-29 at age: 97)
 
Reply With Quote
 
Roedy Green
Guest
Posts: n/a
 
      09-01-2011
On Wed, 31 Aug 2011 19:48:02 -0700 (PDT), KevinSimonson
<(E-Mail Removed)> wrote, quoted or indirectly quoted someone who
said :

>I have an <enum> named <ProjectEnum> that has twelve values


have a look at the sample code at
http://mindprod.com/jgloss/enum.html#SORTING

It sorts an array of enums both by the default ordinal and using a
custom Comparator.


You can generate Comparators with
http://mindprod.com/applet/comparatorcutter.html
--
Roedy Green Canadian Mind Products
http://mindprod.com
The modern conservative is engaged in one of man's oldest exercises in moral philosophy; that is,
the search for a superior moral justification for selfishness.
~ John Kenneth Galbraith (born: 1908-10-15 died: 2006-04-29 at age: 97)
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Merge Sort in C - array output is same as input after sort routine completes rkk C Programming 9 09-24-2006 08:30 PM
How to sort a bitset vector quickly? halfsearch2@gmail.com C++ 10 05-28-2005 02:16 PM
Sony Mavica internal small CR2025 battery dies quickly. Fred Digital Photography 0 11-22-2004 12:37 AM
multi-field array sort using Sort::Fields method Domenico Discepola Perl Misc 6 04-28-2004 04:28 AM
Ado sort error-Ado Sort -Relate, Compute By, or Sort operations cannot be done on column(s) whose key length is unknown or exceeds 10 KB. Navin ASP General 1 09-09-2003 07:16 AM



Advertisments