Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Array is sorted. I'm asking more about algorithm related stuff. I know that by naming conventions is not good here. Also error handling is not exists yet.

public class OrdArray {

    private long[] a;

    private int nElems;

    public OrdArray(int size) {
        this.a = new long[size];
    }

public void binaryInsert(long value) {
    int lowerBound = 0;
    int upperBound = this.nElems - 1;

    int currIndex;

    while(true) {
        currIndex = (lowerBound + upperBound) / 2;

        if (lowerBound == upperBound) {
            break;
        } else {
            if (a[currIndex] < value) {
                lowerBound = currIndex + 1;
            } else {
                upperBound = currIndex - 1;
            }
        }
    }

    int targetIndex;

    if (a[currIndex] > value) {
        targetIndex = currIndex;
    } else {
        targetIndex = ++currIndex;
    }

    int i = nElems;

    while(i > currIndex) {
            a[i] = a[--i];
    }

    a[targetIndex] = value;
    nElems++;
}   


    public void linearInsert(long value) {
        int i;
        for (i = 0; i < this.nElems; i++) {
            if (this.a[i] > value) {
                break;
            }
        }

        for (int k = this.nElems; k > i; k--) {
            this.a[k] = a[k - 1];
        }
        this.a[i] = value
        this.nElems++;
    }
}

Sample class usage:

    OrdArray array = new OrdArray(25);
    array.linearInsert(11);
    array.linearInsert(22);
    array.linearInsert(45);
    //etc

    array.binaryInsert(28);

Code is working properly. Can someone provide me some improvement suggestions?

share|improve this question

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.