Bravo
Bravo

Reputation: 1139

insertion sort for an object-array?

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.

Upvotes: 1

Views: 1280

Answers (3)

SandeepGodara
SandeepGodara

Reputation: 1528

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.

Upvotes: 0

stridecolossus
stridecolossus

Reputation: 1561

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.

Upvotes: 2

Jakkra
Jakkra

Reputation: 651

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[])

Upvotes: 3

Related Questions