重新整理数据结构与算法—— 二分查找法[十二]

前言

什么是二分查找呢?

直接给一个地址哈,避免误解。

https://baike.baidu.com/item/二分法查找/9751511#1

根据我发的这个链接呢?我们知道通过二分查找一定有一个硬性要求,那就是说一定要按照某种顺序排列,不一定是大小。

比如说有一个数组为:{1,2,5,10,11,16,18,20,100},如果如果你要查找100,如果按照遍历的话,那么要到最后一个。

如果通过二分法,那么第一个比较的就是11了,比11大,那么右边是不用再去查找了的。

同意我们要判断什么时候找到,且要分析好如果没有这个数该怎么办?

好的,那么按照这个思路就可以来写一写了。

正文

代码如下:

static void Main(string[] args)
{
	int[] arr = new int[]{1,2,5,10,11,16,18,20,100 };
	Console.WriteLine(binarySearch(arr,0,arr.Length-1,100));
	Console.ReadKey();
}


public static int binarySearch(int[] arr,int left,int right,int findValue)
{
	//表示没有找到
	if (left>right)
	{
		return -1;
	}
	int mid = (left + right)/2;
	if (findValue > arr[mid])
	{
		return binarySearch(arr, mid + 1, right, findValue);
	}
	else if (findValue < arr[mid])
	{
		return binarySearch(arr, left, mid- 1, findValue);
	}
	else
	{
		return mid;
	}
}

代码非常简单哈。

可能呢,我们需要找到的有几个,其实这也非常简单,是这样的。

我们找到了这个后,可以向前扫描或者向后扫描,然后得出结果。

static void Main(string[] args)
{
	int[] arr = new int[]{1,1,1,1,2,5,10,11,16,18,20,100 };
	List<int> list= binaryListSearch(arr, 0, arr.Length - 1, 1);
	foreach (var u in list)
	{
		Console.WriteLine(u);
	}
	Console.ReadKey();
}

public static List<int> binaryListSearch(int[] arr, int left, int right, int findValue)
{
	List<int> result = new List<int>();
	int temp = binarySearch(arr, 0, arr.Length - 1, findValue);
	if (temp != -1)
	{
		for (int i =0 ; i <= temp - 1; i++)
		{
			if (arr[i] == arr[temp])
			{
				result.Add(i);
			}
		}
		result.Add(temp);
		for (int i = temp + 1; i < arr.Length; i++)
		{
			if (arr[i] == arr[temp])
			{
				result.Add(i);
			}
		}
	}
	return result;
}

public static int binarySearch(int[] arr,int left,int right,int findValue)
{
	//表示没有找到
	if (left>right)
	{
		return -1;
	}
	int mid = (left + right)/2;
	if (findValue > arr[mid])
	{
		return binarySearch(arr, mid + 1, right, findValue);
	}
	else if (findValue < arr[mid])
	{
		return binarySearch(arr, left, mid- 1, findValue);
	}
	else
	{
		return mid;
	}
}
posted @ 2020-06-29 18:31  敖毛毛  阅读(125)  评论(0编辑  收藏  举报