Here is the C program to delete duplicate elements from an unsorted array. Given an array of length N, which may contain some duplicate elements. We have to remove all duplicate elements and print only unique elements in array. If an element is present more than once in input array then output array should contain only one one instance of that element.
For Example
Input Array: 6 3 3 5 8 6Output Array: 6 3 5 8
Algorithm to delete duplicate elements from an array
Let inputArray is an array of length N, and readIndex and writeIndex are two integer variables to store index references.
Time Complexity : O(n2)
Let inputArray is an array of length N, and readIndex and writeIndex are two integer variables to store index references.
- readIndex scan elements from left to write.
- At any instant of time all the elements before writeIndex are unique.
- We initialize readIndex and writeIndex with zero and start traversing the array.
- For any element A at index i, we scan remaining elements of array from index i+1 to N-1. If we found one more A then we skip A at index i, otherwise A is unique and we copy it in out unique element list(inputArray[writeIndex]).
- At the end of traversal, we will get all unique elements between index 0 to writeIndex.
C program to delete duplicate elements from an array
Below program defines three integer variables(readIndex, writeIndex and scanIndex) to store indexes of input array. Let the number of elements in array is N.
- All the elements before writeIndex are unique.
- readIndex traverse the array from index 0 to N-1 and for every element it checks whether it is unique or not
- scanIndex traverse the array from readIndex+1 to N-1. It tries to find the duplicate element of array[readIndex]
#include <stdio.h> int main(){ int inputArray[500], elementCount, counter; int readIndex, writeIndex = 0, scanIndex; printf("Enter number of elements in array: "); scanf("%d", &elementCount); printf("Enter %d numbers \n", elementCount); for(counter = 0; counter < elementCount; counter++){ scanf("%d", &inputArray[counter]); } for(readIndex=0; readIndex < elementCount; readIndex++){ for(scanIndex=readIndex+1;scanIndex<elementCount;scanIndex++){ if(inputArray[scanIndex] == inputArray[readIndex]){ /* We found a duplicate element*/ break; } } if(scanIndex == elementCount){ inputArray[writeIndex] = inputArray[readIndex]; writeIndex++; } } printf("Unique Elements\n"); for(counter = 0; counter < writeIndex; counter++){ printf("%d ", inputArray[counter]); } return 0; }Output
Enter number of elements in array: 7 1 6 2 4 1 6 3 Unique Elements 2 4 1 6 3
Related Topics