FiftySentos
FiftySentos

Reputation: 117

Sort an array as values are inputted into the array

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

Answers (3)

Moonstruck
Moonstruck

Reputation: 503

You might want the loop so that it does the following:

  1. Shift the elements with indices > index so that you make space for the new element, and
  2. then add the element to given index.
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

GhostCat
GhostCat

Reputation: 140457

You can go for something like this:

First of all, you need

  1. A counter that tells you how many "unused" array elements are left; there is no point in swapping index 1 to 2, 2 to 3, ... if you find in the end that your array is "full"
  2. Keep an eye on the index, to avoid going beyond the length of your array

Then it is really simple:

  • You iterate your current array to find the first index (lets call it n here) that is bigger than key
  • Then you turn to the last array index that is "in use" ... and start moving values to the right from there
  • Finally, after you moved arr[n] to arr[n+1]; you assign arr[n] = key

Upvotes: 1

Joe C
Joe C

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

Related Questions