brux
brux

Reputation: 3230

how to sort array of strings in numerical order?

I have a String[] of prices that might look like this:

String[0] = 1.22
String[1] = 230.08
String[2] = 34.11

I need to cast the array and order it in ascending order. What is the best way to do this? The Array may be very large so performance important. Thank you in advance.

Upvotes: 0

Views: 4761

Answers (6)

Pranav
Pranav

Reputation: 4250

Now no need to Boxing (i.e no need to Creating OBJECT using new Operator use valueOf insted with compareTo of Collections.Sort..)

First convert your String array using below code:

String[] floats={"0.1","0.2","0.3"};
for(int i=0;i<floats.length;i++) 
{
    List<Float> temp = Collections.singletonList(Float.parseFloat(floats[i]));
} 

1)For Ascending order

Collections.sort(temp, new Comparator<XYZBean>() 
{
     @Override
     public int compare(XYZBean lhs, XYZBean rhs) {

       return Integer.valueOf(lhs.getDistance()).compareTo(rhs.getDistance());
      }
 });

1)For Deascending order

Collections.sort(temp, new Comparator<XYZBean>() 
{
     @Override
     public int compare(XYZBean lhs, XYZBean rhs) {

       return Integer.valueOf(rhs.getDistance()).compareTo(lhs.getDistance());
      }
 });

later on if you want your String arrays back then use below code:

Float xyz[] = temp.toArray( new Float[temp.size()]);
String floats[]=new String[temp.size()];

for (int i = 0; i < xyz.length; i++) {
     floats[i] = String.valueOf(xyz[i]);
 }

Upvotes: 0

A. Abiri
A. Abiri

Reputation: 10810

This is an efficent way to sort an array:

// Creates a list from the prices array and the list is sorted
List<String> list = new ArrayList<String>(list);
Collections.sort(list);

Upvotes: 1

dustmachine
dustmachine

Reputation: 10824

A simple solution like this should work for you:

    String[] vars = {"1.22","230.08","34.11"};

    List<Float> newlist = new ArrayList<Float>();
    for (String s : vars) {
        newlist.add(Float.valueOf(s));  // converts your string to float
    }
    Collections.sort(newlist);

The Collections.sort() will sort your list in place (returns void, so don't try to assign it to a new variable there). At this point the newlist contains Floats. With the new information from your comment below, you'd like them changed back into Strings. You can do that with another loop:

    List<String> numsAsStrings = new ArrayList<String>();
    for (Float f : newlist) {
        numsAsStrings.add(f.toString());
    }

If you want to then turn the List back into an array like the one you started with you can use the toArray method from the Collection interface:

    vars = numsAsStrings.toArray(new String[0]);

I would suggest trying this "default" search and seeing if it's fast enough for your needs. It's often surprising how fast it can sort things. Only after trying the built-in and getting an idea for speed would I look to another algorithm. To do otherwise is premature optimization.

As you can see by all of the new additions, what started as a simple solution turned into a lot of code (looping through it twice in addition to whatever the sort() method is doing internally). And while this solution is pretty easy to follow even for beginners, I'd have to recommend using the Comparator approach that Ted Hopp suggested, and choosing his answer as the correct one. It will be less code to read for the next person that has to look at your code (my only suggestion would be to name the Comparator for what it does like "stringAsFloatComparator")

Comparators are useful, powerful, elegant things. I would recommend reading up the Comparator section of the Java tutorial if you are unfamiliar with them.

Upvotes: 1

Aly
Aly

Reputation: 16275

If you will be adding to this array after sorting then you might want to consider a different data structure such as a self balancing binary tree (like the Red-Black Tree).

However, if this is a one time sort then using Arrays.sort and defining your own Comparator as Ted Hopp suggested. However, this is a comparison sort and therefore will have a lower bound if O(nlg(n)). If this is not fast enough, you may want to try a radix sort with counting sort as the backing stable sort for O(n) time - not this will make the code more complex and therefore could be error prone and less maintainable.

Upvotes: 1

Ted Hopp
Ted Hopp

Reputation: 234847

You can define a specialized string comparator:

class MyComparator implements Comparator<String> {
    public int compare(Object a, Object b) {
        return Float.valueOf(a.toString()).compareTo(Float.valueOf(b.toString());
    }
}

and then sort your String array using:

Arrays.sort(aStringArray, new MyComparator());

(N.B. There may be more efficient ways of comparing two strings representing float values.)

Upvotes: 3

RedLeader
RedLeader

Reputation: 657

Sorting arrays is a classic problem. The question here is when you are sorting and adding to the array.

Do you need to sort every addition? Will you be adding after a sort?... etc.

If you will be adding after you sort, one by one, I recommend using an ArrayList instead of an array. This way you can find your insertion point by tracing down the ArrayList, and put it in that index in quicker time.

Also, for sorting, you should look here: http://en.wikipedia.org/wiki/Sorting_algorithm, Quicksort is the most famous.

Upvotes: 2

Related Questions