Java二分法
贴段代码,有少许注释:
package ibees;
import java.util.Arrays;
public class BinarySearch {
/**
* @param args
*/
public static void main(String[] args) {
double[] src = new double[]{1.3,9.9,10.89,12.89,89.0};
System.out.println(new BinarySearch().binarySearch(src, 89.0));
}
/**
* 二分法查找
* */
public int binarySearch(double[] src, double des){
Arrays.sort(src);
int beginIndex = 0;
int endIndex = src.length-1;
int middle = (endIndex+beginIndex)/2;
while(src[middle] != des && beginIndex != endIndex){
//最后两项
if(beginIndex+1 == endIndex){
if(src[beginIndex] == des){
return beginIndex;
}else if(src[endIndex] == des){
return endIndex;
}else{
return -1;
}
}
//判断中间的数与给定数之间的关系
if(des > src[middle]){
beginIndex = middle+1;
}else if(des < src[middle]){
endIndex = middle-1;
}else{
return middle;
}
middle = (endIndex + beginIndex)/2;
}
return middle;
}
}
想想返回的数组索引是不对的。
相关文档:
JAVA相关基础知识
1、面向对象的特征有哪些方面
1.抽象:
抽象就是忽略一个主题中与当前目标无关的那些方面,以便更充分地注意与当前目标有关的方面。抽象并不打算了解全部问题,而只是选择其中的一部分,暂时不用部分细节。抽象包括两个方面,一是过程抽象,二是数据抽象。
2.继承:
继承是一种联结类的层次模型,并 ......
鉴于网上对Java的堆栈区分,众说纷纭,有的把C++的堆栈也混进来,有的没有分清Stack,Heap的中文翻译,搞得我把Stack当作堆,Heap当作栈,混乱了!昨天参加一外企的笔试,选择英文答案时,选错了,知道答案是堆,却选择了Stack!今天,决定把两者区分清楚!
&nbs ......
Java 语言是一种具有动态性的解释型编程语言,当指定程序运行的时候, Java 虚拟机就将编译生成的 . class 文件按照需求和一定的规则加载进内存,并组织成为一个完整的 Java 应用程序。 Java 语言把每个单独的类 Class 和接口 Implements 编译成单独的一个 . class 文件,这些文件对于 Java 运行环境来说就是一个个可以动态 ......
package com.xiaobian;
public class BubbleSort {
//冒泡排序
public static void bubbleSort(int[] data){
&n ......