class OrderlyAndBinarySearch {
private long[] a;
private int nElems;
public OrderlyAndBinarySearch(int maxSize){
a = new long[maxSize];
nElems = 0;
}
//查看大小元素个数
public int size(){
return nElems;
}
//插入(线性查找方式插入)
public void insert(int value){
int i;
for(i=0;i<nElems;i++){
if(a[i] > value){
break;
}
}
for(int k=nElems; k>i; k--){
a[k] = a[k-1];
}
a[i] = value;
nElems ++;
}
//二分法查找 时间复杂度O(log n)
public int find(int value){
int low = 0;
int high = nElems - 1;
int mid;
while (low <= high){
mid = (low + high)/2;
if(a[mid] == value){
return mid;
}else if(a[mid] > value){
high = mid - 1;
}else {
low = mid + 1;
}
}
return -1;
}
//删除
public boolean delete(int value){
int i = find(value);
if(i == nElems){
return false;
}else {
for(int k = i; k<nElems; k++){
a[k] = a[k+1];
}
nElems --;
return true;
}
}
//显示所有
public void display(){
for(int i=0; i<nElems; i++){
System.out.print(a[i] + " ");
}
System.out.println();
}
public static void main(String[] args){
OrderlyAndBinarySearch arr = new OrderlyAndBinarySearch(50);
arr.insert(77);
arr.insert(43);
arr.insert(23);
arr.insert(1);
arr.insert(87);
arr.insert(54);
arr.insert(98);
arr.insert(45);
arr.insert(3);
arr.insert(878);
arr.insert(56);
arr.insert(65);
arr.insert(4334);
arr.insert(545);
arr.insert(33);
arr.insert(90);
int searchValue = 56;
if(arr.find(searchValue) != arr.size()){
System.out.println("found:" + searchValue);
}else {
System.out.println("Can't find" + searchValue);
}
arr.display();
arr.delete(1);
arr.delete(545);
arr.display();
}
}
java版数据结构与算法—有序数组和二分法查找
最新推荐文章于 2023-01-07 23:40:19 发布