Java Array 2 (2015-8-27)

Source: Internet
Author: User

1, two-part search method to explain: if the use of binary search method to do the operation, the array must be ordered. So when you start out with an unordered array, you sort the ordered array first.

public class test2{

public static void Main (string[] args) {

--Find the location of a data

int number = 8;

--Define the number of groups

int[] arr = new int[]{7,2,10,9,45,3,4};

Sorting and dichotomy are used simultaneously.

int[] arr = new int[]{2,3,4,7,9,10,45};

--Start subscript

int start = 0;

--Termination of subscript

int end = Arr.length-1;

--the intermediate subscript to be obtained

int middle;

--Stores the container where the array is located (if the last printed index is 1, the data that is found does not exist)

int index =-1;

while (Start<=end) {

Middle = (start+end)/2;

if (Number==arr[middle]) {

index = middle+1;

Break

}else if (Number<arr[middle]) {

end = Middle-1;

}else if (Number>arr[middle]) {

start = Middle +1;

}

}

if (index==-1) {

System.out.println ("Didn't find the data needed!!! ");

}else{

System.out.println ("The location of the data is:" +index);

}

} }

2, import Java.util.Scanner;

public class binarysearch{

public static void Main (String [] args) {

int [] array={10,20,30,40,50,60,70,80};

System.out.println ("Please enter the number to find:");

Scanner input=new Scanner (system.in);

int Number=input.nextint ();

int index=-1;

int start=0;

int end=array.length-1;

int middle;

while (Start<=end) {

Middle= (Start+end)/2;

if (Number==array[middle]) {

index=middle+1;

Break

}

if (Number>array[middle]) {

start=middle+1;

}

if (Number<array[middle]) {

end=middle-1;

}

}

if (index==-1) {

System.out.println ("not Found");

}else{

System.out.println ("found" +index);

} }}

Java Array 2 (2015-8-27)

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.