有一无符号整型数组,大小为10, 初始的数值随机,但在[0, 99]之间。请用C/C++语言写一个过滤程序,令数组内的数据互不相等。
说明:
1.若数组内有相等的数据,可令某一数值加1或减1作出偏移,直至不等为止。
2.数组内的数据只能在[0, 99]之间。
3.保持数组内的数据位置不变,即对应下标不变。
说明:
1.若数组内有相等的数据,可令某一数值加1或减1作出偏移,直至不等为止。
2.数组内的数据只能在[0, 99]之间。
3.保持数组内的数据位置不变,即对应下标不变。
C++实现代码:
#include
#include
#include
using namespace std;
#define N 100
void filter(int *A,int n)//利用计数排序思路
{
int Array[N];
bool suc=true;
int i,j;
while(suc)
{
suc=false;
for(i=0;i
Array[i]=0;
for(j=0;j
Array[A[j]]=Array[A[j]]+1;
for(j=0;j
{
if(Array[A[j]]>1)//大于1有相同元素
{
Array[A[j]]=Array[A[j]]-1;
A[j]=A[j]-1;
suc=true;
}
}
}
}
int main()
{
srand(time(0));//设置随机数种子,可确保每次运行生成不同的随机数
int A[10];
int i;
for(i=0;i<10;i++)
A[i]=rand()0;//生成0-99的随机数
for(i=0;i<10;i++)
cout<<A[i]<<' ';
cout<<endl;
filter(A,10);
for(i=0;i<10;i++)
cout<<A[i]<<' ';
cout<<endl;
return 0;
}