8

I have a Class called apple which contains 3 values as int x, int y and int weight. Then i created an array of apple type objects. Now i want to sort the the array of objects based on weight meaning the the apple object with the lowest weight should be first and so on.

I know there are quite a few ways to achieve this by using Arrays.sort etc or comparators.

I was wondering what is the fastest way of doing this sort in Java? There can be a case where i have 500,000 objects so i want to know which sort i should use, more importantly which approach will give me best approach. i have even wrote my own quick sort with Hoare partition.

Code for Apple class

public class Apple {
    public int x;
    public int y;
    public int weight;

    public Apple(int a, int b, int w) {
        x = a;
        y = b;
        weight = w;
    }
}

Code for main class

public class main {
    static Apple[] appleArray;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int size = sc.nextInt();
        int totalApples = sc.nextInt();
        appleArray = new Edge[totalApples];
        int x = 10;
        int y = 20;
        int w = 30;

        for (int i = 0; i < size; i++) {
            appleArray[i] = new Apple(x, y, w);
            x++;
            y++;
            w++;
        }
        //Now i want to sort array of apple objects based on weight
    }
}
3
  • 1
    If you want fastest sort, you should know that different algo speeds depends on data nature and distribution. I believe that "write and measure performance" is the only right answer to your question. There is large possibility that Collections.sort will do perfectly well. Commented Apr 21, 2015 at 16:50
  • I suspect that you give this code only as an example, but the fastest way to sort by weight for this specific main method is to do nothing - the weights are already increasing with array index. Commented Apr 21, 2015 at 17:11
  • Yes it is just an example they could be random @AndyTurner , good observation though Commented Apr 21, 2015 at 17:37

6 Answers 6

10

This book has a useful cheat sheet for deciding the optimal sort for your needs: https://www.safaribooksonline.com/library/view/algorithms-in-a/9780596516246/ch04s09.html

The easiest solution

The Arrays.sort command uses a quicksort implementation, which is suitable for many situations. For your example code this might be:

Arrays.sort(appleArray, new Comparator<Apple>(){  
    @Override  
    public int compare(Apple apple1, Apple apple2){  
         return apple1.weight - apple2.weight;  
    }  
}); 

The fastest solution

In your case you have a large array containing repetitions, for example 50,000 apples in your array might all weigh 3 ounces... You might therefore opt to implement a bucket sort to improve performance over a quicksort, which can be wasteful under such conditions. Here is an example implementation.

Perhaps benchmark a few researched choices, using the Java API when it suits, to determine the best solution for your input set.

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

2 Comments

I've added a link to an example bucket sort implementation, For an example using Arrays.sort() perhaps the answer here might be helpful? stackoverflow.com/questions/14863433/…
If you have a lot of objects in your array Arrays.parallelSort() can be faster.
7

I would first use Java API. If this is not fast enough then I would search for a optimized sorting library.

Also consider a database, DB engines are fast and optimized for sorting large data sets.

Comments

3

You can use Arrays.sort passing a custom Comparator or defining your Apple as Comparable

1 Comment

so it would be something like this -> Arrays.sort(appleArray, appleArray.weight) ? Thanks for answer if you can show how you would do this it would be great.
2

We can use Collections.sort with a custom Comparator.

class Apple {
    public final int weight;
    // ...
};

List<Apple> apples = // ...

Collections.sort(apples, new Comparator<Apple>() {
    @Override public int compare(Apple a1, Apple a2) {
        return a1.weight - a2.weight; // Ascending
    }

});

1 Comment

And why is this fastest?
2

If in your object there is any Number or Integer over which you have to sort you can do like this-

List<Object> obj = new ArrayList<Object>();

Collections.sort(obj, new Comparator<Object>() {
    @Override
    public int compare(Object object1, Object object2) {
        return object1.getNumber() > object2.getNumber() ? 1 : -1;
    }
});

And if there is not Number or Integer over which you can sort it and you are just having Strings in your object than assign value to Strings by enum.

enum Code {
    Str1(1), Str2(2), Str3(3), Str4(4), Str5(5));

    int sortNumber;

    Code(int sortNumber) {
        this.sortNumber = sortNumber;
    }

    int returnNumber() {
        return sortNumber;
    }
};

public static void main(String[] args) {
    List<Object> obj = new ArrayList<Object>();

    Collections.sort(obj, new Comparator<Object>() {
        @Override
        public int compare(Object object1, Object object2) {
            return Code.valueOf(object1.getStr()).returnNumber() > Code.valueOf(object2.getStr()).returnNumber() ? 1 : -1;
        }
    });
}

Comments

0

With the help of new lambda expressions which came with Java8, now it's way easier and shorter in code to sort Arrays of custom Objects. Below is the code showing the use of lambda expressions in the current scenario.

Arrays.sort(appleArray, (apple1, apple2) -> apple1.weight - apple2.weight); 

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.