一、定义数组
-
long[] arr = new long[]{2,3,4};
-
long[] arr = new long[10];
arr[0]=1;
...
二、自定义类封装数组
public class MyArray1 {
private long[] arr;
private int element;
public MyArray1(){
arr=new long[50];
}
public MyArray1(int maxsize){
arr=new long[maxsize];
}
/**
* 插入数据
*/
public void insert(long value){
arr[element]=value;
element++;
}
/**
* 显示数据
*/
public void display(){
System.out.print("[");
for (int i = 0; i < element; i++) {
System.out.print(arr[i]+" ");
}
System.out.print("]");
}
/**
* 查找数据,根据value进行查找,返回索引
*/
public int search(long value){
int i;
for (i = 0; i < element; i++) {
if(value==arr[i]){
break;
}
}
if(i == element){
return -1;
}else {
return i;
}
}
/**
* 查找数据,根据index进行查找,返回值
*/
public long get(int index){
if(index < 0 || index >= element){
throw new ArrayIndexOutOfBoundsException();
}else{
return arr[index];
}
}
/**
* 删除数据,根据index进行删除
*/
public void delete(int index){
if(index < 0 || index >= element){
throw new ArrayIndexOutOfBoundsException();
}else{
for (int i = index; i < element; i++) {
arr[index]=arr[index+1];
}
element--;
}
}
/**
* 更新数据
*/
public void change(int index,long newvalue){
if (index < 0 || index >= element) {
throw new ArrayIndexOutOfBoundsException();
}else{
arr[index]=newvalue;
}
}
}
三、有序数组
/**
* 插入数据
*/
public void insert(long value){
int i;
for (i = 0; i < element; i++) {
if (arr[i] > value) {
break;
}
}
for (int j = element; j > i; j--) {
arr[j]=arr[j-1];
}
arr[i]=value;
element++;
}
四、查找算法
-
线性查找
2.二分法查找(建立在该数组是有序数组的基础上)
/**
* 二分法查找有序数组
*/
public int binarySearch(long value){
int middle=0;
int left=0;
int right=element;
while (true) {
middle=(left + right)/2;
if (arr[middle]==value) {
return middle;
}else if(right < left){
return -1;
}else {
if (arr[middle]>value) {
right=middle-1;
}else {
left=middle+1;
}
}
}
}