Home > Java > javaTutorial > Examples of binary search method binarySearch in Java data structure

Examples of binary search method binarySearch in Java data structure

黄舟
Release: 2017-10-20 09:38:43
Original
1275 people have browsed it

This article mainly introduces relevant information about the example of binary search method of java data structure. I hope this article can help everyone understand and master this part of the content. Friends in need can refer to it

Java data structure binary search method binarySearch example

Half search method, the premise is that the array has been sorted before it can be searched

Example code:


public class BinarySearch {
 int[] bArr;
 
 public void setArr(int[] bArr){
 this.bArr=bArr;
 }
 public static void main(String[] args) {
 int arrLength=16;
 int[] bArr=new int[arrLength];
 System.out.println("数组:");
 bArr=new int[]{72,31,13,94,85,27,64,71,19,55,49,40,8,70,17,13};
 for(int i=0;i<arrLength;i++){
  //bArr[i]=(int)(Math.random()*100);
  System.out.print(bArr[i]+"  ");
 }
 
 System.out.println();
 System.out.println("排序:");
 
 QuickSort qs=new QuickSort();
 qs.setArr(bArr);
 qs.quickSort(0, bArr.length-1);
 
 for(int i=0;i<arrLength;i++){
  System.out.print(bArr[i]+"  ");
 }
 
 BinarySearch bs=new BinarySearch();
 bs.setArr(bArr);
 
 System.out.println();
 System.out.println("查找:");
 int val=bs.binarySearch(bArr.length-1, 0, 13);
 System.out.println("查找:bArr["+val+"]="+13);
 
 }
 
 int binarySearch(int max,int min,int val){//有重复的取的是第一个出现的位置
 int mid=(max+min)/2;
 if(val==bArr[mid]){
  return mid;
 }
 else if(val>bArr[mid]){
  return binarySearch(max,mid,val);
 }
 else if(val<bArr[mid]){
  return binarySearch(mid,min,val);
 }
 return -1;//查找失败
 }
}
Copy after login

The above is the detailed content of Examples of binary search method binarySearch in Java data structure. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template