递归

Recursion(3); // 1,2,3
Recursion2(3);  // 3,2,1


static void Recursion(int num)
{
    if (num > 0)
    {
        Console.WriteLine(num);
        Recursion(num - 1);
    }
}

static void Recursion2(int num)
{
    if (num > 0)
    {
        Recursion2(num - 1);
        Console.WriteLine(num);
    }
}

--汉诺塔

static void Hanoi(int n, string a, string b, string c)
{
    if (n > 0)
    {
        Hanoi(n - 1, a, b, c);
        Console.WriteLine($"moving from {a} to {c}");
        Hanoi(n - 1, b, a, c);
    }
}

--二分查找

List<int> ints = new List<int>() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var searchResult = BinarySearch(ints, 3);// 3
Console.WriteLine(searchResult);

static int BinarySearch(List<int> SourceList,int DestInt) { 
    int start = 0; 
    int end = SourceList.Count - 1;
    int middle = start + ((end - start) >> 1);
    while (start <= end)
    {
        middle = start + ((end - start) >> 1);//这样写可以不用重复建立middle变量,减少内存
        if (middle == DestInt)
        {
            return middle;
        }
        else if (SourceList[middle] > DestInt)
        {
            end = middle - 1;
        }
        else {
            start = middle + 1;
        }
    }
    return 0;
}

 

posted @ 2022-08-27 22:12  vba是最好的语言  阅读(43)  评论(0编辑  收藏  举报