Searching for duplicates in array
Simple algorithm
int yes = 1, i, j;
for (i = 0; i < n; ++i)
{
for (j = i + 1; j < n; ++j) if (arr[i] == arr[j])
{
printf("Found a duplicate of %d\n", arr[i]);
yes = 0;
break;
}
if (!yes) break;
}
if (yes) printf("No duplicates");
Efficient Algorithim
void rmdup(int *array, int length)
{
int *current , *end = array + length - 1;
for ( current = array + 1; array < end; array++, current = array + 1 )
{
while ( current <= end )
{
if ( *current == *array )
{
*current = *end--;
}
else
{
current++;
}
}
}
}
Comments