-9

I want some logic which will insert numbers in the array, and at the same time it will check that the current number is already not present in the array. Please help me with the logic.

6

2 Answers 2

0

Code to Remove duplicate Element in an Array

    #include<stdio.h>
    #include<conio.h>
    void main()
    {
       int a[20], i, j, k, n;
       clrscr();

       printf("\nEnter array size : ");
       scanf("%d",&n);

       printf("\nEnter %d array element : ", n);
       for(i = 0; i < n; i++) 
       {
          scanf("%d",&a[i]);
       }

       printf("\nOriginal array is : ");
       for(i=0;i< n;i++)
       {
          printf(" %d",a[i]);
       }

       printf("\nNew array is  : ");
       for(i=0; i < n; i++) 
       {
          for(j=i+1; j < n; )
          {
             if(a[j] == a[i])
             {
                for(k=j; k < n;k++) 
                {
                   a[k] = a[k+1];
                }
                n--;
             }
             else {
                j++;
             }
          }
       }

       for(i=0; i < n; i++)
       {
          printf("%d ", a[i]);
       }
    getch();
    }

Output

Enter array size : 5

Enter 5 array element : 11 13 11 12 13

Original array is : 11 13 11 12 13

New array is : 11 13 12

Sign up to request clarification or add additional context in comments.

Comments

0

Possible solution:

  1. O(n^2) algorithm, where you do a linear search O(n) to check if the number is present in the array or not for all the n elements.

For each element (n elements):

O(n): Search

O(1): Insertion

  1. O(n^2) algorithm, when you insert in sorted array.

For each element (n elements):

O(log n): Binary search

O(n): Shift and Insertion

Though there are advanced data structures (more in C++ STL) but you will need more than just a array. Because insertion is costly in array(Insertion in a specific position).

Other data structures which might help: BST (AVL-BST, Splay Trees, ... other balanced Trees structures).

In C++: sets is exactly what you want. sets is implemented as tree in STL.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.