I need help with a loop that will move the elements of an array if the new value added is less than the existing value, so the array is sorted as you enter new values.
The array is empty to begin with.
I tried several loops, but they don't seem to work in my case, since they are loops used for arrays that have already been filled.
Here is the code I have.
if(index < 0)
index = -(index + 1);
if(arr[index] > key)
for(int i = 0; i < count -1; i++) {
arr[index + i] = arr[index + i + 1];
}
arr[index] = key;
Index from binary search.
So, for example, if I first have input 80, it will take up a slot arr[0]. Then I enter 45, which will also occupy the slot arr[0].
Since the key 45 is smaller than the existing arr [0] (80), then 80 should move up the index.