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.
Asked
Active
Viewed 4,065 times
-9
-
1Show your effort. – msc Jul 06 '17 at 05:31
-
2What have you tried so far? How have your attempt worked, or not worked? Please take some time to read [the help pages](http://stackoverflow.com/help), especially the sections named ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](http://stackoverflow.com/help/dont-ask). Also [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask). Lastly please learn how to create a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve). – Some programmer dude Jul 06 '17 at 05:31
-
http://www.studytonight.com/c/remove-duplicate-element-program.php – msc Jul 06 '17 at 05:32
-
It seems you need the OrderedSet rather than Array. – ShenLei Jul 06 '17 at 05:32
-
@ShenLei Why not an *unordered* set? – Some programmer dude Jul 06 '17 at 05:33
-
have you tried Google – Vishwajeet Vishu Jul 06 '17 at 05:48
2 Answers
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

code passionate
- 98
- 5
0
Possible solution:
O(n^2)
algorithm, where you do a linear searchO(n)
to check if the number is present in the array or not for all then
elements.
For each element (n elements):
O(n)
: Search
O(1)
: Insertion
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.

NVS Abhilash
- 574
- 7
- 24