0

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.

5
  • What do you mean "cast the array"? Also, is it correct to assume that you want to sort in order of numerical value represented by the strings, and not lexically? And do you need the original string values sorted, or the array of numerical values sorted? Commented Jul 13, 2011 at 21:44
  • The numerical values, cast to float type first. I was hoping to get the float values then back into a String[] once they have been ordered. Commented Jul 13, 2011 at 21:53
  • 1
    I'm not sure 'android order prices` is the best way of describing your problem. It's unlikely that your problem depends on whether the elements in the array are actually prices. And if they are prices, 230.08 seems terrible expensive. Commented Jul 13, 2011 at 21:59
  • 1
    lol. 230.08 is a bargain I'm selling cigars rolled on the thighs of a virgin. Commented Jul 13, 2011 at 22:02
  • Is there a reason you can't refactor in order that you're storing all of your price data in an int/long array? Commented Jul 14, 2011 at 0:17

6 Answers 6

3

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.)

Sign up to request clarification or add additional context in comments.

Comments

2

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.

2 Comments

However, I don't know the backend of the ArrayList class very well, and they could have it functioning with an array copy anyway :)
thanks for the help I am looking into the most effective data type to use
1

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.

Comments

1

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.

3 Comments

Thank you this looks like a good solution, will mark the answer soon just testing all the solutions I can first :)
could you add to your code a method of getting the List<Float> back into a String[] please :)
It will be better to create ArrayList with capacity: List<Float> newlist = new ArrayList<Float>(vars.length);
1

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);

1 Comment

This will not work because "230.00" will sort as coming before "34.11".
0

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]);
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.