1、主方法当然实现的方式还有递归等)
/**
* 二分法查找
*/
public int binarySearch(long value){
int middle = 0; //中间的值为0
int low = 0; //最左边
int pow = elements; //最右的
if(value<arr[low] || value>arr[pow-1]) return -1;
while(true){
middle = (low + pow) / 2;
if(arr[middle] == value)
return middle;
else if(low > pow)
return -1;
else {
if(arr[middle] > value){ //往左查找
pow = middle - 1;
}else{ //向右查询
low = middle + 1;
}
}
}
}
2、整体代码:
package org.gzw.arr;
public class MyOrderArray {
private long[] arr;
/* 有效数据的长度 */
private int elements;
public MyOrderArray() {
arr = new long[50];
}
public MyOrderArray(int maxSize) {
arr = new long[maxSize];
}
/**
* 添加数据(在此排序:从小到大)
*/
public void insert(long value){
int i;
for(i=0;i<elements;i++){
if(arr[i] > value)
break;
}
//从后向前
for(int j=elements;j>i;j--){
arr[j] = arr[j-1];
}
arr[i] = value;
elements++;
}
/**
* 显示数据
*/
public String display(){
StringBuffer strbuf = new StringBuffer();
strbuf.append("[ ");
/*for(long l : arr){
strbuf.append(l + ", ");
}*/
for(int i =0; i<elements;i++){
strbuf.append(arr[i] + ", ");
}
strbuf.delete(strbuf.length()-1, strbuf.length());
strbuf.append("]");
return strbuf.toString();
}
/**
* 二分法查找
*/
public int binarySearch(long value){
int middle = 0; //中间的值为0
int low = 0; //最左边
int pow = elements; //最右的
if(value<arr[low] || value>arr[pow-1]) return -1;
while(true){
middle = (low + pow) / 2;
if(arr[middle] == value)
return middle;
else if(low > pow)
return -1;
else {
if(arr[middle] > value){ //往左查找
pow = middle - 1;
}else{ //向右查询
low = middle + 1;
}
}
}
}
/**
* 查询数据,并返回位置索引
*/
public int search(long value){
int i;
for(i=0;i<elements;i++){
if(arr[i] == value) break;
}
if(i==elements){
return -1;
}else{
return i;
}
}
/**
* 查找数据,更具索引来查
*/
public long get(int index){
if(0<=index && index<elements){
return arr[index];
}else{
throw new ArrayIndexOutOfBoundsException();
}
}
/**
* 删除数据
*/
public void delete(int index){
if(0<=index && index<elements){
for(int i=index;i<elements;i++){
if(i<elements-1){
arr[i] = arr[i+1];
}else break;
}
elements--;
}else{
throw new ArrayIndexOutOfBoundsException();
}
}
/**
* 更新数据
*/
public void change(int index, long value){
if(0<=index && index<elements){
arr[index] = value;
}else{
throw new ArrayIndexOutOfBoundsException();
}
}
}
3、测试
package org.gzw.arr;
public class TestMyOrderArray {
public static void main(String[] args) {
MyOrderArray myOrderArr = new MyOrderArray(6);
myOrderArr.insert(1);
myOrderArr.insert(139);
myOrderArr.insert(229);
myOrderArr.insert(9);
myOrderArr.insert(19);
myOrderArr.insert(39);
System.out.println(myOrderArr.display());
System.out.println(myOrderArr.binarySearch(139));
}
}
4、运行结果:
[ 1, 9, 19, 39, 139, 229,]
4