Rahul
Rahul

Reputation: 5834

How to re-arrange elements of Array after Deleting

Recently I was reading a Programming book and found this question:

I have an array :

  array = [2,3,6,7,8,9,33,22];

Now, Suppose I have deleted the element at 4th position i.e. 8 .

Now I have to rearrange the array as:

  Newarray = [2,3,6,7,9,33,22];

How Can I do this. And I have to also minimize the complexity.

Edit I have no choice to make another copy of it.I have to only modify it.

Upvotes: 0

Views: 2489

Answers (3)

thepace
thepace

Reputation: 2221

You can simply displace each element from the delIdx(deletion index) one step forward.

for(int i=delIdx; i<(arr_size-1);i++)
{
    arr[i]= arr[i+1];
}

If required you can either set the last element to a non-attainable value or decrease the size of the array.

Upvotes: 1

sameera sy
sameera sy

Reputation: 1718

Do this, just use these two functions and it will work fine

index=4;//You wanted to delete it from the array.
memcpy(newarray,array,sizeof(array));
memmove(&newarray[index], &newarray[index + 1], sizeof(newarray)-1);

now the newarray contains your exact replica without the character that you wished to remove

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409166

You can "remove" a value from an array by simply copy over the element by the next elements, that's easy to do with memmove:

int array[8] = {2,3,6,7,8,9,33,22};
memmove(&array[4], &array[5], sizeof(int) * 3);

The resulting array will be {2,3,6,7,9,33,22,22}.

And from that you can see the big problem with attempting to "remove" an element from a compile-time array: You can't!

You can overwrite the element, but the size of the array is fixed at time of compilation and can't actually be changed at run-time.

One common solution is to keep track of the actual number of valid elements in the array manually, and make sure you update that size as you add or remove elements. Either that or set unused elements to a value that's not going to be used otherwise (for example if your array can only contain positive numbers, then you could set unused elements to -1 and check for that).


If you don't want to use a library function (why not?) then loop and set e.g.

array[4] = array[5];
array[5] = array[6];

and so on.

Upvotes: 2

Related Questions