Reputation: 117
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.
Upvotes: 4
Views: 187
Reputation: 503
You might want the loop so that it does the following:
for (int i = count; i > index; i--) {
arr[i] = arr[i - 1]; // shifts the elements to the one place right
}
arr[index] = key; // add the key to the given index
Note: The count is the current number of elements in the array and it is less than arr.length
Upvotes: 2
Reputation: 140457
You can go for something like this:
First of all, you need
Then it is really simple:
Upvotes: 1
Reputation: 15684
It looks like you're attempting to shift your array elements in the wrong direction.
Given index = 0
and i = 0
, you'd end up with:
arr[0] = arr[1];
When you probably want the other way around.
Upvotes: 0