# java – Can I make this type of insert faster?

I am trying to order a matrix in the initial insertion of a value.
I tried to think of "binary search", except with the classification, where I am looking for the correct insertion point. I guess you can call it a binary type, but it's not that. It works well, but I would like it to be faster. The slowest part of the algorithm is to reposition the previously inserted values.

I understand that there are already things in place that do what I am trying to do. This was completely for mental exercise. That said, here's the code …

``````empty public insert (insert int) {
int topEnd = nElem - 1;
int bottomEnd = 0;
halfway
if (nElem == 0) {
training = insertion;
} another thing
while (true) {
midway = (topEnd + bottomEnd) / 2;

// The following is a case of loop output If topEnd and bottomEnd point to the same position,
// or if topEnd minus bottomEnd is equal to -1, then it is ready to insert.

if (topEnd == bottomEnd || topEnd - bottomEnd == -1) {

/ * For the following, if the number that is inserted is larger, insert in front * /

yes (insertion> matrix[halfway]) {
displacement (lower part, insertion);
training[halfway + 1] = insertion;
break;

/ * For the following, if the number that is inserted is smaller, insert after * /

} else if (insertion < array[halfway]) {
shift(bottomEnd, insertion);
array[halfway] = insertion;
break;

/* For the following, if the number being inserted is equal, its a duplicate, insert in behind */

} else if (insertion == array[halfway]) {
shift(bottomEnd, insertion);
array[halfway] = insertion;
break;
}

/* If we're not ready to insert, then we need to shorten our range.
If greater, shorten range by moving the bottom to halfway + 1.
If lesser, shorten the range by moving the top down to halfway - 1. */

} else if (insertion > training[halfway]) {
bottomEnd = halfway + 1;
} else if (insert <array[halfway]) {
topEnd = halfway - 1;

/ * The following is another case of looping output that is meant to help handle duplicates.
* If this case is not here when there are duplicates of more than two, or when topEnd is equal to 3, 7, 11,
* The algorithm enters an infinite loop. When testing this, it happened about 35% of the time.
* * /

} else if si (insertion == matrix[halfway]) {
displacement (lower part, insertion);
training[halfway] = insertion;
break;
}
}
nElem ++;
}
``````

The following is the code for the slowest part of the algorithm. It is the method of change.

``````Change of private vacuum (int position, int value) {
for (int i = nElem; i> position; i--)
training[i] = matrix[i - 1];
}
``````