Half-lookup,

Source: Internet
Author: User

Half-lookup,

Small knowledge points, easy to understand for beginners, clear remarks, simple and clear. Requirements: 1. in order, ascending and descending order. 2. Locate an element in the array. If no element exists, return-1.
// Package name package test1111; public class Demo2 {public static void main (String [] args) {// The first is an sorted array (ascending or descending) int [] arr = {11, 23, 40, 45, 59,65, 99}; // search for the number 45int index = getIndex (arr, 65); // obtain the value System. out. println ("index =" + index); // index = 5} public static int getIndex (int [] arr, int key) {int minIndex = 0; // minimum subscript int maxIndex = arr. length-1; // maximum subscript int midIndex = (maxIndex + minIndex)/2; // intermediate subscript while (key! = Arr [midIndex]) {// when the median and key are different, enter the loop to obtain a new set of numbers. if (key> arr [midIndex]) {// The key is greater than the median value, the minimum subscript of the new value is equal to the intermediate subscript + 1 minIndex = midIndex + 1;} else {// key is smaller than the intermediate value, and the obtained maximum subscript is equal to the intermediate subscript-1 maxIndex = midIndex-1 ;} if (maxIndex <minIndex) {// The maximum subscript is smaller than the minimum subscript to prove that the value does not exist return-1; // If no result is returned,-1} // The intermediate subscript midIndex = (maxIndex + minIndex)/2;} return midIndex; // always return the subscript of the number in the middle of the array }}

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.