参加Grapecity的一道笔试题

上周去听 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);

        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值