Removing duplicates in a sorted array

Write the code to remove duplicates in a sorted array.

Answer:

Method 1[1]


int removeDuplicates(int a[], int array_size)
{
int i, j;

j = 0;


// Print old array...
printf("\n\nOLD : ");
for(i = 0; i < array_size; i++)
{
printf("[%d] ", a[i]);
}


// Remove the duplicates ...
for (i = 1; i < array_size; i++)
{
if (a[i] != a[j])
{
j++;
a[j] = a[i]; // Move it to the front
}
}

// The new array size..
array_size = (j + 1);


// Print new array...
printf("\n\nNEW : ");
for(i = 0; i< array_size; i++)
{
printf("[%d] ", a[i]);
}
printf("\n\n");



// Return the new size...
return(j + 1);
}



Method 2:
Use the algorithm unique.[2]

No comments: