Archive for the ‘array’ Category

remove the duplicated no. from a sorted array..

September 4, 2007

//1st method This function just prints the array without duplicates.
//  It does not modify the original array!

#include <stdio.h>
#include<iostream>
using namespace std;

void remove(int a[], int n);
int main()
{

int a[100],n;
cout<<“\n enter the size of array :”;
cin>>n;
for(int i=0; i<n; i++)
cin>>a[i];
remove(a,n);
system(“pause”);
return(0);
}

void remove(int a[], int n)
{
int i,last_seen_unique;
if(n<= 1){return;}
last_seen_unique = a[0];

cout<<a[0]<<” “;
for(i=1;i<n;i++)
{
if(a[i]!=last_seen_unique)
{
cout<<a[i];
last_seen_unique = a[i];
}
}
}
 //2nd method Changes the original array and resets the size of the array if //duplicates have been removed.

#include <stdio.h>
#include<iostream>
using namespace std;

void remove(int a[], int n) ;
int main()
{
int a[100],n;
cout<<“\n enter the size of array :”;
cin>>n;
for(int i=0; i<n; i++)
cin>>a[i];
remove(a,n);
cout<<endl<<endl;
system(“pause”);
return(0);
}

void remove(int a[], int n)
{
int i, j, k, l;
int current_pos;
int dup_start;
int dup_end;
if(n<= 1){return;}
for (i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]!=a[j])
break;
else
{
current_pos = i;
dup_start = j;
j++;
while((a[i]==a[j])&& j<n)
j++;
dup_end = j-1;
// Now remove elements of the array from “dup_start” to “dup_end”
// and shrink the size of the array.
for(k = (dup_end + 1), l = dup_start ; k <n;)
a[l++]=a[k++];
// Reduce the array size by the number of elements removed.
n=n-(dup_end – dup_start + 1);
}
}
}
cout<<“\n\n final array with size <“<<n<<” >”<<” is :”;
for(i=0;i<n;i++)
cout<<a[i]<<” “;
}

//3rd method  modify the array
void remove1(int a[], int n)
{     int i,j=0;
for(i=1;i<n;i++)
{
for(j=i+1; j<n; j++)
if(a[i]!=a[j])
{ j++;  a[j]=a[i]; }
n=j-1;
}
for(int i=0;i<n;i++)
cout<<a[i]<<” “;
}