Posted in Programs

Program to Delete Duplicates from Array…

Here is an program to delete duplicates from an array. Program will work fine for Sorted as well as Unsorted data array. Here are steps and code(C++) for program.

Algorithm:

i=0 , N=Size of array, arr[N] ;

Step 1: Traverse array from i=0 to N-1 (0 to N-1 programmatically)

Step 2: Check for i+1th to N-1

if same element found, then move all elements upward upto i+1

Code:


#include "stdafx.h"
#include "iostream"

using namespace std;
void delete_duplicate(int a[], int *size);
int _tmain(int argc, _TCHAR* argv[])
{
int a[10],n,i;
cout << “Enter Number of elements: “; cin >> n;
cout << “Enter Elements: “;
for (int i = 0; i < n; i++) { cin >> a[i];
}

cout << “\n\nAfter Deleting Duplicates: \n\n”;
delete_duplicate(a,&n);

system(“pause”);
return 0;

}

void delete_duplicate(int a[], int *size)
{
int i, j, k,n=*size;
for (i = 0; i < n; i++)
{
for (int j = i + 1; j < n;)
{
if (a[i] == a[j])
{
for (int k = j; k < n – 1; k++)
{
a[k] = a[k + 1];
}
n–;
}
else
j++;
}
cout << “\n”<<a[i];
}

}

 

Output:-

Output1

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s