Remove duplicate elements from unsorted array

Simple C program to remove duplicates from array.

C Program:

#include<stdio.h>
 
int RemoveDuplicates(int arr[], int size)
{
 int i,j,k=0;
 arr[k]=arr[0];
 
 for(i=1;i<size;i++)
 {
  for(j=i+1;j<size;j++)
  {
   if(arr[j]==arr[i])
   arr[j]=arr[0];
  }
  if(arr[i]!=arr[0])
  {
  k++;
  arr[k]=arr[i];
 
 }
}
 
 //size = k+1;
 return k+1;
}
int main()
{
 int i,arr[]={12,65,12,65,20,12,20,17,17,28,85};
 
 int size = sizeof(arr)/sizeof(arr[0]);
 
 size = RemoveDuplicates(arr,size);
 
 printf("Array is \n");
 for(i=0;i<size;i++)
 {
  printf("%d ",arr[i]);
 }
 
 return 0;
}

Time Complexity of this program is O(n^2).

You can do this in O(nlogn) by sorting array using merge sort.

Related: Remove duplicate from sorted array

Popular posts from this blog