Bravo Bravo - 1 year ago 84
Java Question

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) { = name;
this.quantity = quantity;
// getters + setters


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.

Answer Source

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

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download