Search code examples
javaarrayssorting

Inserting an integer into a sorted array


I'm trying to write a method that takes a sorted array and an integer, creates a new array that is 1 size larger, and inserts the new integer and keeps it sorted.

I've tried a few different implementations and had them to work - but for this specific one, I can't grasp where it's going wrong.

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

are the arrays, and the method is

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 prints out 1, 2, 3, 4, 6, 7, 8, 0, instead of 1, 2, 3, 4, 5, 6, 7, 8.


Solution

  • Change

    if(k < s[i]) {
    

    to

    if(k < a[i]) {
    

    in line 4.