Insert an integer into a sorted array

I am trying to write a method that takes a sorted array and an integer, creates a new array of size 1 size and inserts a new integer and keeps it sorted.

I tried several different implementations and made them work, but for this particular I can not understand where this is happening.

    int[] array1 = new int[]{1, 2, 3, 4, 6, 7, 8};
    int[] printArray = insert(array1, 5);

are arrays, and the method

public static int[] insert(int[] a, int k) {
    int[] s = new int[a.length + 1];
    for(int i = 0; i < a.length; i++) {
        if(k < s[i]) {
            s[i] = k;
            for(int j = i + 1; j < s.length; j++) {
                s[j] = a[i];
                i++;
            }
            return s;
        } else {
            s[i] = a[i];
        }
    }
    return s;
} 

This method returns 1, 2, 3, 4, 6, 7, 8, 0 instead of 1, 2, 3, 4, 5, 6, 7, 8.

+4
source share
3 answers

Edit

if(k < s[i]) {

to

if(k < a[i]) {

in line 4.

+4
source

Actually in the next line you create an array with all the elements of zero:

int[] s = new int[a.length + 1];

s[0]to s[7]be 0.

i 0 a.length, - s . k s[i], , ( ).

, .

  • s a[0].
  • .

:

public static int[] insert(int[] a, int k) {
        int[] s = new int[a.length + 1];
        s[0] = a[0];
        for(int i = 1; i < a.length; i++) {
            if(k < s[i-1]) {
                s[i] = k;
                for(int j = i + 1; j < s.length; j++) {
                    s[j] = a[i];
                    i++;
                }
                return s;
            } else {
                s[i] = a[i];
            }
        }
        return s;
    }

: [1, 2, 3, 4, 6, 5, 7, 8]

0

Arrays.copyOf(int[], int), , , . , , . System.arraycopy(Object,int,Object,int,int), . :

public static int[] insert(int[] a, int k) {
    int[] s = Arrays.copyOf(a, a.length + 1);
    for (int i = 0; i < s.length; i++) {
        if (a[i] < k) {
            continue;
        }
        System.arraycopy(a, i, s, i + 1, s.length - i - 1);
        s[i] = k;
        break;
    }
    return s;
}

Arrays.toString(int[]),

public static void main(String s[]) throws IOException {
    int[] array1 = new int[] { 1, 2, 3, 4, 6, 7, 8 };
    int[] printArray = insert(array1, 5);
    System.out.println(Arrays.toString(printArray));
}

()

[1, 2, 3, 4, 5, 6, 7, 8]
0
source

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


All Articles