Plz let me know the algorithm for searching and deleting an element in a array(C++)
Four answers:
James Bond
2012-03-18 02:49:06 UTC
Sequential search
traverse the array element
by element and compare with the required value. If found remove the same.
Binary search is little more efficient than sequential search. Read the following
PC
2012-03-18 02:40:59 UTC
Unless the array is sorted in some way, there is no efficient way to search it. If it is sorted, then a binary search will be reasonably efficient.
As far as I'm aware, there's no really good way to delete an element in an array. The best way I can think of is to memcpy all elements from position i+1 back one space (if order needs to be maintained). If order does not need to be maintained, copy the last element to the element being deleted. In either case, reduce a size counter by one.
It would be much better to use a more complex data structure, like a binary tree or hash table, depending on the usage.