Sorting an array as you enter values ​​into an array

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.

+4
3

, :

  • > 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

. - , arr.length

+2

- :

,

  • , , "" ; 1 2, 2 3,... , ""
  • , .

:

  • , ( ), ,
  • , ""...
  • , , arr [n] arr [n + 1]; arr [n] = key
+1

It looks like you are trying to move the elements of an array in the wrong direction.

Given index = 0and i = 0, you will receive:

arr[0] = arr[1];

When you probably want a different way.

0
source

Source: https://habr.com/ru/post/1656528/


All Articles