0

I have tried to remove the duplicate elements from an array using c language, here I'am using 3 for loop to remove the duplicate elements.

How can this optimize the code?

any other simple method to remove the duplicate elements?

Thanks.

#include <stdio.h>

#define MAX_SIZE 100 // Maximum size of the array

int main()
{
    int arr[MAX_SIZE]; 
    int size;        
    int i, j, k;     


    printf("Enter size of the array : ");
    scanf("%d", &size);


    printf("Enter elements in array : ");
    for(i=0; i<size; i++)
    {
        scanf("%d", &arr[i]);
    }



    for(i=0; i<size; i++)
    {
        for(j=i+1; j<size; j++)
        {
   
            if(arr[i] == arr[j])
            {
             
                for(k=j; k<size; k++)
                {
                    arr[k] = arr[k + 1];
                }

         
                size--;

                j--;
            }
        }
    }

    printf("\nArray elements after deleting duplicates : ");
    for(i=0; i<size; i++)
    {
        printf("%d\t", arr[i]);
    }

    return 0;
}
hivert
  • 10,579
  • 3
  • 31
  • 56
Wounder
  • 9
  • 3
  • 3
    If you have working code that you want peer reviewed for improvements, you should ask on [codereview.se] instead. It was created specifically for that purpose. – Ken White Feb 20 '21 at 03:32
  • 2
    Hint: sort the array first. Even faster hint: Use a hash table. – selbie Feb 20 '21 at 03:50
  • You are removing from an array list, but array lists are not fast at removing elements, they are fast to find and edit, you can use a linked list, it is much faster to add and remove. I don't think there is any improvement to be made using your approach. – Matheus Rossi Saciotto Feb 20 '21 at 03:53
  • Sort would take more time than remove duplicates. Hashing random integers doesn't make sense. – Matheus Rossi Saciotto Feb 20 '21 at 03:58
  • 3
    @MatheusRossiSaciotto - quicksort is `O(N lg N)` compared to the code above which is `O(N²)`. So on a large enough array, the sorting will beat the brute force method. Also the cost of hashing an integer is near 0, the number is the hash. – selbie Feb 20 '21 at 06:58
  • Of course, the STL implementation of `sort` and `unique` is faster than the one presented. But sorting and then removing adjacent duplicates doesn't seem like a faster way, see this discussion : https://stackoverflow.com/questions/1041620/whats-the-most-efficient-way-to-erase-duplicates-and-sort-a-vector – Matheus Rossi Saciotto Feb 20 '21 at 23:14

0 Answers0