上周去听 Grapecity的宣讲会,并顺带参加了他的笔试,其中最后一道题,大概是这样的:
50个数,连续存储,现要选出其中最大的数和最小的数,用顺序选择最少也要97次比较,试设计一种算法,使其比较次数肯定小于97次.
当时直接就想到了归并的思想(应该还有更快的),说了具体的算法思想,并画了一个选择示意图,没写具体程序,刚刚用c#把算法实现了一遍,比较次数为(85-2=3)次:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication5
{
class Program
{
static int c = 0;
public static int[] D = new int[50];
static void Main(string[] args)
{
Random r = new Random();
for (int i = 0; i < D.Length; i++)
{
D[i] = r.Next(1000);
}
F();
F1(0, 2);
Console.WriteLine(D[D.Length - 1] > D[0] ? D[D.Length - 1] : D[0]);
F1(1, 2);
Console.WriteLine(D[D.Length - 1] < D[0] ? D[D.Length - 1] : D[0]);
c += 2;
Console.WriteLine(c);
Console.ReadLine();
}
static void F()
{
for (int j = 0; j + 1 < D.Length; j += 2)
{
if (D[j] < D[j + 1])
{
int t = D[j];
D[j] = D[j + 1];
D[j + 1] = t;
}
c++;
}
}
static void F1(int s, int n)
{
if (s + n >= D.Length)
{
return;
}
c++;
for (int j = s; j + n < D.Length; j += (n * 2))
{
c++;
if (D[j] < D[j + n] && s == 0)
{
int t = D[j];
D[j] = D[j + n];
D[j + n] = t;
}
else if (D[j] > D[j + n] && s == 1)
{
int t = D[j];
D[j] = D[j + n];
D[j + n] = t;
}
}
F1(s, n * 2);
}
}
}