package dataStructure;
/**
* 面向对象方式的对数组封装, 模拟ArrayList
* @author wangtao
* @date 2016-10-19 上午9:39:43
* @version v1.0
* @TODO 描述
*/
public class MyArray {
private long[] arr;
private int elements;
public MyArray(){
arr = new long[50];
}
/**
* 添加数据
*/
public void insert(long value){
arr[elements] = value;
elements++;
/*针对有序数据的插入
* 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 void display(){
System.out.println("{");
for(int i = 0; i < elements; i++){
System.out.println(arr[i] + " ");
}
System.out.println("}");
}
/**
* 线性查找数据
*/
public int search(long value){
int i ;
for(i = 0; i < elements; i++){
if(value == arr[i]){
break;
}
}
if(i == elements){
return -1;
}
return i;
}
/**
* 二分法查找, 前提是数据是有顺序的
* @return
*/
public int binarySearch(long value){
int middle = 0;
int low = 0;
int pow = elements;
while(true){
middle = (pow + low)/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;
}
}
}
}
/**
* 查找数据,根据索引来查
* @return
*/
public long get(int index){
if(index >= elements || index < 0){
throw new ArrayIndexOutOfBoundsException();
}
return arr[index];
}
/**
* 删除数据
* @param index
*/
public void delete(int index){
if(index >= elements || index < 0){
throw new ArrayIndexOutOfBoundsException();
} else{
for(int i = index; i < elements; i++){
arr[index] = arr[index+1];
}
elements--;
}
}
/**
* 更新数据
*/
public void change(int index, long newvalue){
if(index >= elements || index < 0){
throw new ArrayIndexOutOfBoundsException();
}else{
arr[index] = newvalue;
}
}
}
数组(一)------模拟ArrayList
最新推荐文章于 2024-01-15 23:38:55 发布