"Java" Array binary lookup element __java

Source: Internet
Author: User

Find premises: array elements ordered

requirements: Finding the index of an element



Code implementation:

public class Test_erfenfa {public

	static void Main (string[] args) {
		int[] arr = {11,22,33,44,55,66,77};
		int i = GetIndex (arr,33);
		System.out.println (i);
	}
	
	public static int GetIndex (int[] arr, int value) {
		int min = 0;
		int max = arr.length-1;
		int mid = (min + max)/2;
		
		while (Arr[mid]!= value) {/					/when the median value is not equal to the value to be found, start the loop lookup
			if (Arr[mid] < value) {					//when the median value is less than the value to be found
				min = mid + 1;					The smallest index changes
			}else if (Arr[mid] > value) {			//when the median value is greater than the value to be found
				max = mid-1;					Maximum index change
			}
			
			mid = (min + max)/2;					Regardless of the maximum or minimum change, the intermediate index will change with the
			
			if (min > Max) {						//If the minimum index is greater than the maximum index, there is no possibility of a lookup
				return-1;					Returns-1
			}
		} return
		mid;
	}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.