Arthur
Arthur

Reputation: 3962

Inserting integer into array using 1 for loop

I am trying to write a method that takes a sorted array and an integer, and returns a new sorted array with the integer in the correct place.

I am trying to do this without using dynamic arrays, as well as only using 1 for loop - I have this working using a different method.

This is the method :

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

My test input is

int[] array1 = new int[]{1, 2, 3, 4, 6, 7, 8};

and I am trying to insert a 5.

The issue I am having with this particular method is that it will always set the index after the inserted integer to 0. In this case it would store and print

1, 2, 3, 4, 5, 0, 7, 8

rather than

1, 2, 3, 4, 5, 6, 7, 8

Thanks

Upvotes: 1

Views: 1040

Answers (3)

Ankit Deshpande
Ankit Deshpande

Reputation: 3604

   public static int[] insertIntoSortedArray(int[] array, int k) {
    int[] newArray = new int[array.length + 1];
    int i = 0;// for array
    int j = 0;// for new array
    boolean inserted = false;
    while (i < array.length) {
        if (!inserted && k < array[i]) {
            newArray[j] = k;
            inserted = true;
        } else {
            newArray[j] = array[i++];
        }
        j++;
    }
    return newArray;
}

Upvotes: 0

Louie11
Louie11

Reputation: 86

You may want to use an alternative. Instead of using a loop, use the Arrays object to add and sort your array.

Example:

public int[] insert(int[] a, int k) {
    // create a copy of int array parameter and add one to the length
    int[] s = Arrays.copyOf(a, a.length + 1);

    // add the second parameter at the end of the new array
    s[s.length - 1] = k;

    // sort the array
    Arrays.sort(s);

    return s;
}

Upvotes: 0

sprinter
sprinter

Reputation: 27976

It's not setting the index to zero, it's just jumping over one index. When k < a[i] is true it's incrementing i (in the for loop) and j (in j++ statement). So when you next do s[i + j] = a[i] it will have skipped two positions rather than one.

The solution is to ensure that in every iteration of the loop a value from the original array is copied. In other words, once you've assigned k to s[i] you then need to assign a[i] to s[i + 1]. The simplest way to achieve this is to remove your else clause and execute s[i + j] every iteration.

Upvotes: 2

Related Questions