您需要检查所有以前的项目,然后才能知道该项目是否已经发生。
#include <stdio.h>
#include <stdlib.h>
int compareFunc(const void *op1, const void *op2 )
{
int *a, *b;
a = (int*)op1;
b = (int*)op2;
return *a - *b;
}
void printUnique(int *array, int numElems)
{
int curPrintIndex, curCompareIndex;
char alreadySeen;
for (curPrintIndex=0; curPrintIndex<numElems; curPrintIndex++)
{
alreadySeen = 0;
for (curCompareIndex=0; curCompareIndex<curPrintIndex; curCompareIndex++)
{
if (array[curCompareIndex] == array[curPrintIndex])
{
alreadySeen = 1;
break;
}
}
if (alreadySeen == 0)
printf("%d\n", array[curPrintIndex]);
}
}
int main()
{
const int numItems = 100;
int *array, i, lastVal;
array = calloc(numItems, sizeof(int) );
for (i=0; i<numItems; i++)
array[i] = rand()%numItems;
printUnique(array, numItems);
free(array);
return 0;
/*
qsort(array, numItems, sizeof(int), compareFunc);
printf("%d\n", array[0]);
lastVal = array[0];
for (i=1; i<numItems; i++)
{
if (array[i] != lastVal)
{
lastVal = array[i];
printf("%d\n", array[i]);
}
}
*/
}