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?