Skip to main content

Searching for duplicates in array

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

Popular posts from this blog

CAN INTERVIEW QUESTIONS

Qualifiers and Modifier in C

RTOS Real time operating system interview questions

CAN INTERVIEW QUESTIONS 2

What is UDS protocol

Memory mapping in c

TOP IOT PLATFORMS