语言基础——Java_binarySearch(折半查找)

本文深入讲解了折半查找算法的实现原理与应用,包括不同版本的折半查找代码示例,以及如何在有序数组中插入元素保持数组有序性的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//折半查找实现
class BinarySearch
{
	public static void main(String[] args)
	{
		int[] arr = {6,9,12,26,55,67,69,80};
		sop(arr);
		int index = btseatch(arr,12);
		System.out.println("index = "+index);
	}
	public static void sop(int[] arr)
	{
		for(int i=0;i<arr.length;i++)
		{
			System.out.println("arr["+i+"] ="+ arr[i]);
		}
	}
	public static int btseatch(int[] arr,int key)
	{
		int min = 0;
		int max = arr.length-1;
		int mid = (min + max)/2;
		
		while(key != arr[mid])//待查元素与arr[mid]比较,进而确定下一步查找范围。
		{
			if(key<arr[mid])  //于arr[mid]左侧范围内查找。
				max = mid - 1;
			else
				min = mid + 1; //于arr[mid]右侧范围内查找。			
			if(max <  min) //说明不存在待查元素。
				return -1;
			mid = (min + max)/2; //不能忘记,在获得新的min和max之后要重新计算出新的mid。
		}
		return mid;
	}
}

         当然,上述代码在折半查找方法中while的判断条件是依据:待查元素key和arr[mid]值得关系。即,key和arr[mid]不相等时就一直循环下去,直到两者相等,返回角标mid。或者出现角标max<min的情况,返回-1(即,没找到待查元素,查找失败。)

         鉴于角标max<min。我们不妨利用角标max和min的关系来作为while的判断依据。代码如下:

public static int btseatch(int[] arr,int key)
	{
		int min = 0;
		int max = arr.length-1;
		//int mid = (min + max)>>1; 
		
		while(min <= max)
		{
			int mid = (min + max)>>1;//位运算>>,<<.左移乘,右移除。
			if(key < arr[mid])
				max = mid - 1;
			else if(key > arr[mid])
				min = mid + 1;
			else 
				return mid;
		}
		return -1;
	}

注意:折半查找一定是针对有序数组,无序数组不行。千万不要拿个无序数组,自己先排序,使之成为有序数组,然后再折半查找,这是不行的。因为在你自行排序的时候数组的角标已经发生了变化,所以后续的查找是无意义的。针对无序数组,查找某个元素可以直接查找,实现如下:

public static int getIndex(int[] arr,int key)
	{
		for(int i=0;i<arr.length;i++)
		{
			if(key==arr[i])
				return i;
		}
		return -1;
	}
锤炼·精技术_JeremyDC

关于这个折半查找的一个应用。

【需求:在一个有序数组中插入一个元素,使得新数组还是一个有序数组。】

import java.util.*;
class BinarySearch
{
	public static void main(String[] args)
	{
		int[] arr = {6,9,12,26,55,67,69,80};
		sop(arr);
		int index = btseatch(arr,800);
		System.out.println("index = "+index);
		int index1 = Arrays.binarySearch(arr,800);//Java再带功能。如果元素存在则返回具体角标位置,如果元素不存在则返回:-插入点-1.
		System.out.println("index1 = "+ index1);
	}
	public static void sop(int[] arr)
	{
		for(int i=0;i<arr.length;i++)
		{
			System.out.println("arr["+i+"] ="+ arr[i]);
		}
	}
	public static int btseatch(int[] arr,int key)
	{
		int min = 0;
		int max = arr.length-1;
		//int mid = (min + max)>>1; 
		
		while(min <= max)
		{
			int mid = (min + max)>>1;
			if(key < arr[mid])
				max = mid - 1;
			else if(key > arr[mid])
				min = mid + 1;
			else  
				return mid;
		}
		return min;//此处 出现返回min的意思就是待查元素不在该数组中,因为出现了max<min的情况。 
	} //注意:此处不再是return -1 了;另外为了达到和Java自身带有的功能一致此处实际返回值因该是:-min-1
}

上述实现重点在于插入点的问题。但是针对【需求:在一个有序数组中插入一个元素,使得新数组还是一个有序数组。】而言,具体讲新元素如何插入,如何将新数组打印出来,以后我再来补充……


锤炼·精技术_JeremyDc





                
A binary search algorithm (or binary chop) is a technique for finding a particular value in a sorted list. It makes progressively better guesses, and closes in on the sought value, by comparing an element halfway with what has been determined to be an element too low in the list and one too high in the list. A binary search finds the median element in a list, compares its value to the one you are searching for, and determines if it’s greater than, less than, or equal to the one you want. A guess that turns out to be too high becomes the new top of the list, and one too low the new bottom of the list. The binary search's next guess is halfway between the new list's top and bottom. Pursuing this strategy iteratively, it narrows the search by a factor 2 each time, and finds your value. A binary search is an example of a divide and conquer algorithm (more specifically a decrease and conquer algorithm) and a dichotomic search (more at Search algorithm). The most common application of binary search is to find a specific value in a sorted list. To cast this in the frame of the guessing game (see Example below), realize that we are now guessing the index, or numbered place, of the value in the list. This is useful because, given the index, other data structures will contain associated information. Suppose a data structure containing the classic collection of name, address, telephone number and so forth has been accumulated, and an array is prepared containing the names, numbered from one to N. A query might be: what is the telephone number for a given name X. To answer this the array would be searched and the index (if any) corresponding to that name determined, whereupon it would be used to report the associated telephone number and so forth. Appropriate provision must be made for the name not being in the list (typically by returning an index value of zero), indeed the question of interest might be only whether X is in the list or not. If the list of names is in sorted order, a binary search will find a given name with far fewer probes than the simple procedure of probing each name in the list, one after the other in a linear search, and the procedure is much simpler than organising a hash table though that would be faster still, typically averaging just over one probe. This applies for a uniform distribution of search items but if it is known that some few items are much more likely to be sought for than the majority then a linear search with the list ordered so that the most popular items are first may do better. The binary search begins by comparing the sought value X to the value in the middle of the list; because the values are sorted, it is clear whether the sought value would belong before or after that middle value, and the search then continues through the correct half in the same way. Only the sign of the difference is inspected: there is no attempt at an interpolation search based on the size of the differences. Your task is to write a program that, given a set numbers of ascending and a key, finding a particular postion in a sorted list.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值