1

For instance, I have the following classes:

public class FooService {

    private String name;
    private int quantity;

    public FooService(String name, int quantity) {
        this.name = name;
        this.quantity = quantity;
    }
    // getters + setters
}

and

public class FooStorage {

    private FooService [] services = new FooService[10];

    public void add(FooService fooService) {

    }
}

I want to sort the services array in an alphabetical order according to each element's name parameter.

I know I can use a comparator in this case but it is very expensive when importing large amount of data. Can anyone help me with the insertion sort here?

EDIT: I am not allowed to use Collections. Also, do not mind about the fixed size of the array. I am allocating initially 5000 slots and then multiplying by 2 if the 5000th slot is reached in my program.

0

3 Answers 3

3

Make FooService implement Comparable. Make the compareTo method compare by alphabetic order. And then use Arrays.sort(services); it will sort your array.

Read more here: http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#sort(java.lang.Object[])

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

Comments

2

If you are periodically adding lots of new items into your array then the Arrays.sort() approach described by @Jakkra is a sound approach.

If you're frequently only adding a few items each time then this approach is a bit heavy-weight, you might want to consider a TreeSet (also requires implementing Comparable).

EDIT: Just seen your update saying you cannot use collections (!), so the second option is no good to you but I'll leave it here for posterity.

Comments

0

If you are really keen on insertion sort try this..

public void sort(){
    for(int i=2;i<services.length;i++){
        int j=i-1;
        FooService key=services[i];
        while((j>-1)&& ((services[j].getName().compareTo(key.getName()))>0)){
            services[j+1]=services[j];
            j--;
        }
        services[j+1]=key;
    }
}

P.S. You ain't using collections... compareTo() is just helping you on string comparisons, to implement your own string comparisons will be reinventing the wheel.

1 Comment

btw, why did you assign i as 2 in the first for loop? Thanks in advance

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.