1

I am currently working on a delete method on a fixed array. Here is the implementation of the delete method below. What it does in the first for-loop is it gets the index if the data has a match on the array. For the next if and for-loop, its supposed to move the contents of the index if for example, the element deleted is at the 2nd or 3rd index of an array of length 5. It returns true, if the element has been successfully deleted in the array and false if not.

public boolean delete(E data) {
    int index = -1;
    int size = list.length;

    for (int i = 0; i < list.length; i++) { // for getting what index in the array
        if (data == list[i]) {              // is the element in if there is a match
            index = i;
        }
    }

    if (index > -1) {                               // for swapping the index when
        final int newArraySize;                     // the element is deleted in the 
        if ((newArraySize = size - 1) > index) {    // between first-2nd to the last
            for (int x = 0; x < list.length; x++) { // index in the array.
                    if (list[x] == null) {
                        for (int y = 0; y < x; y++) {
                            // move items
                            list[y] = list[y+1];
                        }
                    }
            }
        }
        list[size = newArraySize] = null;
        return true;
    }

    return false;
}

When I try running it, it doesn't delete the element. I'm having problems with the implementation of the swapping index part. I need help.

1 Answers1

0

Your solution has time complexity of O(nxn). Instead you can start from the index of element being removed and swap all elements from index of element being removed.

for (int i = index; i < list.length - 1; i++) {
    list[i] = list[i + 1];
}

But above solution might retain same size of the array and have repeat elements.

I will suggest using two array solutions, it adds bit of space complexity but effectively removes element and reduces the array size. Also you need to return this updated array.

int[] copy = new int[list.length - 1];

for (int i = 0, j = 0; i < list.length; i++) {
    if (i != index) {
        copy[j++] = list[i];
    }
}
SRJ
  • 2,092
  • 3
  • 17
  • 36
  • 1
    Thanks for this. I was looking at a lot of forums about this problem. Your explanation made it clearer for me. –  Sep 03 '21 at 05:45