Write a function named "eliminate_duplicates" that takes an array of integers in random order and eliminates all the duplicate integers in the array.
The function should take two arguments:
(1) an array of integers;
(2) an integer that tells the number of cells in the array.
The function should not return a value, but if any duplicate integers are eliminated, then the function should change the value of the argument that was passed to it so that the new value tells the number of distinct integers in the array.Â
#include<iostream>
#include<algorithm>
using namespace std;
int eliminate_duplicates(int arr[], int n)
{
if (n == 0 || n == 1)
return n;
sort(&arr[0], &arr[n - 1]);
int *temp = new int[n];
int j = 0;
for (int i = 0; i < n - 1; i++)
{
if (arr[i] != arr[i + 1])
temp[j++] = arr[i];
}
if(arr[n - 1]>temp[j-1])
temp[j++] = arr[n - 1];
for (int i = 0; i < j; i++)
arr[i] = temp[i];
return j;
}
int main()
{
int arr[] = {4,5,7,4,1,2,3,7,6,2};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Primary array: ";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << "\nn = " << n << endl;
n = eliminate_duplicates(arr, n);
for (int i = 0; i < n; i++)
cout<<arr[i]<<" ";
cout << "\nn = " << n;
}
Comments
Leave a comment