Heres a little program I whipped together for you check it out hope it will help you.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void Sort(int numbers[], int size)
{
int i, j;
int min, temp;
//selection sort
for (i = 0; i < size-1; i++)
{
min = i;
for (j = i+1; j < size; j++)
{
if (numbers[j] < numbers[min])
{
min = j;
}
}
temp = numbers[i];
numbers[i] = numbers[min];
numbers[min] = temp;
}
}
void checkForDuplicate(int numbers[], int size)
{
int i, j;
//probably someway to make this more efficent but you get the idea
for(i = 0; i < size; i++)
{
for(j = i + 1; j < size; j++)
{
if(numbers[i] == numbers[j])
{
numbers[j] = rand() % 10;
}
}
}
}
int main(void)
{
int i;
const int size = 3;
int array[size];
srand((unsigned int)time(NULL));//makes the numbers based on time
for(i = 0; i < size; i++)
{
array[i] = rand() % 10;
}
checkForDuplicate(array,size);//call check for duplicate before you sort them
//so you don't have to sort twice
Sort(array,size);
for(i = 0; i < size; i++)
{
cout<<array[i]<<endl;
}
cin.get();
return 0;
}
One issue with your code, one that I am currently facing in a similar problem; the problem lies in your CheckForDuplicate().
This is my pseudocode interpretation of that function, correct me if I am wrong:
n=ordinal location of a number in a 5 number sequence (1 through length)
If int n equals int n+1, assign a new random value to n+1.
---------------
The issue with this is as follows:
say you have the number sequence generated: 5 3 7 7 9
The loop first encounters the number 5. the number following is 3. 5 != 3, so it continues. Next, 3 and 7. 3 != 7, so the loop continues. Next, 7 and 7. 7 == 7, so now the program proceeds to assign a new random value to the second 7. Say the new value is 5. OK for now, so it seems....So now having "fixed" the duplicate, it continues. we now have this sequence: 5 3 7 5 9 and we are currently on the fourth number (5). So the loop has 5 and 9. 5 != 9, so the loop continues. The LCV has now reached the termination condition, so the loop terminates, with a final sequence of 5 3 7 5 9. Unfortunately, we now have two 5's. And the loop failed to address this problem.
I am working on this same problem now more or less, and can't solve it. My wily old professor caught this error, and I can't seem to fix it. The only solution I have come up with is instead of generating a new val for the number n+1, when number n and n+1 equal each other, I restart the loop by setting i=0. This works, however as my professor says, is terribly inefficient. On today's machine's, it doesn't matter, but on the machines HE used to work on, that would mean a huge difference in processing power -_-