一次。每个数组元素只能访问一次,设计一个算法,将它找出来;不用辅助存储空
间,能否设计一个算法实现?
class Program
{
static void Main(string[] args)
{
int[] list = new int[101];
Random r = new Random();
int a= r.Next(1, 100);
bool b = false;
for (int i = 0; i < 101; i++)
{
if (!b)
list[i] = i + 1;
else
list[i] = i;
if (a == i + 1)
{
list[i + 1] = a;
b = true;
}
}
Console.WriteLine("The Random number : "+a.ToString());
int left = 0, right = 100;
int posion;
posion = (left + right) / 2;
int count = 0;
while (right - left > 1)
{
if (list[posion] == posion)
{
right = posion;
}
else
{
left = posion;
}
posion = (left + right) / 2;
++count;
}
Console.WriteLine("At the " + count.ToString() + "th time found out the Random number : " + list[posion].ToString() + " ; And his posion is " + posion.ToString());
Console.Read();
}
}