J
josh
Hi all:
I am trying to find out the most efficient way to remove an element
from an array, and have the array size shrink by one.
pop, push, and splice won't work too well for me, I am trying to
remove an element that could be in any position.
Here is my current implementation (may not actually compile, just a
example)
<psuedo perl code>
# this array is purposely unsorted
@array = ['bob', 'alice', 'david', 'christy', 'edward', 'henry',
'frank'];
@array = removeFromArray ( @array, "edward" );
sub removeFromArray {
@array = $_[0];
$name = $_[1];
for ( $i = 0; $i < @$array; $i++ ) {
if ( $array[$i] eq $name ) {
unset $array[$i];
}
}
}
</psuedo perl code>
As you can see, this is not exactly the most efficient way of removing
an element as the size of my array grows. And especially when I run
this in a nested loop, say, when I want to compare two arrays and
remove the differences, it will result in a close to BigO(n^2)
efficiency.
Is there a faster, more efficient way to remove an element from an
array (and preferrably not BigO(n) )?
Will it help if I am performinig this on an already sorted array? Then
I can perhaps use some sort of binary search function to find the item
I am looking for?
I am trying to find out the most efficient way to remove an element
from an array, and have the array size shrink by one.
pop, push, and splice won't work too well for me, I am trying to
remove an element that could be in any position.
Here is my current implementation (may not actually compile, just a
example)
<psuedo perl code>
# this array is purposely unsorted
@array = ['bob', 'alice', 'david', 'christy', 'edward', 'henry',
'frank'];
@array = removeFromArray ( @array, "edward" );
sub removeFromArray {
@array = $_[0];
$name = $_[1];
for ( $i = 0; $i < @$array; $i++ ) {
if ( $array[$i] eq $name ) {
unset $array[$i];
}
}
}
</psuedo perl code>
As you can see, this is not exactly the most efficient way of removing
an element as the size of my array grows. And especially when I run
this in a nested loop, say, when I want to compare two arrays and
remove the differences, it will result in a close to BigO(n^2)
efficiency.
Is there a faster, more efficient way to remove an element from an
array (and preferrably not BigO(n) )?
Will it help if I am performinig this on an already sorted array? Then
I can perhaps use some sort of binary search function to find the item
I am looking for?