Hi everyone
I am writing a program to sort an array, but I have a problem removing the duplicates ... so can someone please point me to the right direction or show me a sample program based on my code.
for example, the user gives in a row the following values:
1 3 2 7 5 9 7 -1 5 7 3 -1
Then the output should be:
1
1 3
1 2 3
1 2 3 7
1 2 3 5 7
1 2 3 5 7 9
1 2 3 5 7 7 9
1 2 3 5 6 7 7 9
1 2 3 6 7 7 9
1 2 3 6 7 9
1 2 6 7 9
2 6 7 9
best regards, alsz.
My code is below
#include <iostream>
using namespace std;
const int sizeofarray = 16;
class SortedArray
{
public:
SortedArray();
void insert(int);
void remove(int);
void print();
private:
int *sortedArray;
int size;
int totalSize;
};
SortedArray::SortedArray()
{
size = 0;
totalSize = sizeofarray;
sortedArray = new int[totalSize];
}
void SortedArray::insert(int inp)
{
int i;
size++;
if (size == totalSize)
{
totalSize += sizeofarray;
int *temp = new int[totalSize];
if (sortedArray != '\0')
{
for (i=0; i<(size-1) && inp > sortedArray[i]; i++)
{
temp[i] = sortedArray[i];
}
if (i < (size - 1))
{
temp[i] = inp;
for ( i++; i < size; i++)
{
temp[i] = sortedArray[i - 1];
}
}
else
{
temp[size - 1] = inp;
}
delete[] sortedArray;
}
sortedArray = temp;
}
else
{
for ( i = size - 1; i > 0 && inp < sortedArray[i - 1]; i--)
{
sortedArray[i] = sortedArray[i-1];
}
sortedArray[i] = inp;
}
}
void SortedArray::remove(int inp)
{
int i;
size;
if (size == totalSize)
{
totalSize += sizeofarray;
int *temp = new int[totalSize];
if (sortedArray != '\0')
{
for (i=0; i<(size-1) && inp > sortedArray[i]; i++)
{
temp[i] = sortedArray[i];
}
if (i < (size - 1))
{
temp[i] = sortedArray[i - 1];
}
}
}
}
void SortedArray::print()
{
for(int i=0; i<size; i++)
{
cout << sortedArray[i] << " ";
}
cout << endl;
}
int main()
{
SortedArray x;
int inp;
cin >> inp;
do
{
x.insert(inp);
x.print();
cin >> inp;
}while(inp>=0);
do
{
cin >> inp;
x.remove(inp);
x.print();
}while(inp>=0);
system("PAUSE");
return 0;
}