basically you just need an algorithm that takes a position and compares it to the previous position. If they are different, store the new one, if they are the same, discard the new one.
1223
1) 12 - Good
2) 22 - Discard second two
3) 23 - Good
I had to do something similar to this when writing a SoundEx function.
what you need to do when you find a repeated number is move all the positions above it down one. That will eliminate the duplicate as well as move things into correct position.
so your first iteration will compare 1 and 2. thats ok
i++;
compare 2 and 2. Remove second 2 by moving 2,4,4,5,5,5,5 all down one and setting last pos to 0
updated array looks like {1,2,3,4,4,5,5,5,5,0}
i++;
compare 2 and 3, thats ok.
i++;
compare 3 and 4, thats ok.
i++;
compare 4 and 4. Remove second 4 by moving 5,5,5,5 down one and setting last pos to 0
updated array looks like {1,2,3,4,5,5,5,5,0,0}
i++;
repeat above steps.
#include <iostream>
usingnamespace std;
//no need to assume increasing order
int main()
{
// no need to assume no more than 10, any number can be work
int array_size;//the length of preset array
do
{
cout << "Input array_size(<=10): ";
cin >> array_size;
}while(array_size > 10);
int *arr = newint[array_size];
int i, j;
for(i = 0; i < array_size; i++)
{
cout<<"Input arr[" << i << "]: ";
cin>>arr[i];
}
cout << "the original array output: " << endl;
for(i = 0; i < array_size; i++)
cout << arr[i] << " ";
cout << endl;
cout << "the single element output: " << endl;
cout << arr[0] << " "; //first element
for(i = 1; i < array_size; i++) //the critical codes
{
for(j = 0; j < i; j++)
{
if(arr[j] == arr[i])
break;
if(j == i-1)
cout << arr[i] << " ";
}
}
delete [] arr;
cout << endl;
return 0;
}
such as: int arr[10]={1,2,2,3,4,4,5,5,5,5} can be work well.
such as: int arr[10]={5,2,1,3,4,4,5,4,5,5} can be work well too.