I need help with a loop that will shift the elements of an array if a newly added value is lower than an existing value, so the array is being sorted as new values are inputted.
The array is empty to start with.
I had tried several loops but they don't seem to work in my case as they were loops used for arrays that were already full.
Here is the code I currently 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;
The index is from a binary search.
So for example, if I have input 80 first, it would take the slot of arr[0]. Then I input 45, which will also take the slot of arr[0].
Since 45, key, is smaller than the existing arr[0] (80), 80 is to move up an index.