# “万里挑一”算法

//初始化
int N = 10;

int[] a = new int[N];
Random rand
= new Random();

//赋值
for (int i = 1; i < a.Length; i++)
{
a[i]
= i;
}

int idx1 = 0;

int idx2 = 0;

//打乱顺序
for (int i = 0; i < a.Length * 10; i++)
{
idx1
= rand.Next(N);
idx2
= rand.Next(N);

if (idx1 == idx2)
{
i
--;

continue;
}
a[idx1]
= a[idx1] ^ a[idx2];
a[idx2]
= a[idx1] ^ a[idx2];
a[idx1]
= a[idx1] ^ a[idx2];
}

//创建重复元素一个
idx1 = rand.Next(N);

while (a[idx1] == 0)
idx1
= rand.Next(N);

for (int i = 0; i < a.Length; i++)
{

if (a[i] == 0)
{
a[i]
= a[idx1];

break;
}
}

//查找
unsafe
{

fixed (int* p = a)
{

int* p1 = p;

//if a[0]==a[1]
if (*p1 == *(p1 + 1))
{

//Find!
return;
}

//loop array
while (p1 < p + N)
{

short* pBigEndian = (short*)(p + *(short*)p1) + 1;

short* pLittleEndian = (short*)p1;

*pBigEndian = *pLittleEndian;
p1
++;
pBigEndian
= (short*)(p + *(short*)p1) + 1;
pLittleEndian
= (short*)p1;

if (*pBigEndian == *pLittleEndian)
{

//Find!
break;
}
}
}
}

-        a    {Dimensions:[0x0000000a]}    int[]
[0x00000000]    0x00000003
int
[0x00000001]    0x00000008
int
[0x00000002]    0x00000001
int
[0x00000003]    0x00000009
int
[0x00000004]    0x00000007
int
[0x00000005]    0x00000002
int
[0x00000006]    0x00000006
int
[0x00000007]    0x00000005
int
[0x00000008]    0x00000007
int
[0x00000009]    0x00000004
int

-        a    {Dimensions:[0x0000000a]}    int[]
[0x00000000]    0x00000003
int
[0x00000001]    0x00000008
int
[0x00000002]    0x00000001
int
[0x00000003]    0x00030009
int
[0x00000004]    0x00000007
int
[0x00000005]    0x00000002
int
[0x00000006]    0x00000006
int
[0x00000007]    0x00000005
int
[0x00000008]    0x00000007
int
[0x00000009]    0x00000004
int

-        a    {Dimensions:[0x0000000a]}    int[]
[0x00000000]    0x00000003
int
[0x00000001]    0x00010008
int
[0x00000002]    0x00020001
int
[0x00000003]    0x00030009
int
[0x00000004]    0x00000007
int
[0x00000005]    0x00050002
int
[0x00000006]    0x00060006
int
[0x00000007]    0x00070005
int
[0x00000008]    0x00080007
int
[0x00000009]    0x00090004
int

posted @ 2009-07-22 15:51 DiggingDeeply 阅读(...) 评论(...) 编辑 收藏