package demo01;import java.util.Arrays;public class MyArray { private int[] elements; public MyArray() { elements = new int[0]; } //获取长度 public int size() { return elements.length; } //添加元素 public void add(int element){ int[] newArr = new int[elements.length+1]; for(int i = 0;i < elements.length;i++) { newArr[i] = elements[i]; } newArr[elements.length] = element; elements = newArr;//新数组替换旧数组 } //打印元素 public void printArray() { System.out.println(Arrays.toString(elements)); } //删除元素 public void delete(int index) { if(index < 0 || index > elements.length-1) { throw new RuntimeException("下标越界"); } int[] newArr = new int[elements.length-1]; for(int i = 0;i < newArr.length;i++) { if(i < index) { newArr[i] = elements[i]; } else{ newArr[i] = elements[i+1]; } elements = newArr; } } //获取指定位置的元素 public int get(int index){ return elements[index]; } //在某个位置插入一个元素 public void insert(int pos,int value) { if(pos < 1 || pos > elements.length+1) { System.out.println("插入位置不合法"); return; } int[] newArr = new int[elements.length+1]; for(int i = 0;i <= elements.length;i++) { if(i < pos-1) { newArr[i] = elements[i]; } else if(i == pos-1) { newArr[i] = value; } else { newArr[i] = elements[i-1]; } } elements = newArr; } //替换指定位置的元素 public void set(int pos,int value) { if(pos < 1 || pos > elements.length) { System.out.println("替换位置有误"); return; } elements[pos-1] = value; } //线性查找 public int search(int target) { int index = -1; for(int i = 0;i < elements.length;i++) { if(elements[i] == target){ index = i; break; } } return index; } //二分查找找--查找的目标数组必须是有序的 public int binarySearch(int target) { int index = -1; int begin = 0; int end = elements.length-1; int middle; //循环查找 while(true) { middle = (begin+end)/2; if(begin >= end)//出现这种情况,说明目标元素不存在 { break; } if(elements[middle] == target)//判断中间的元素是不是要查找的元素 { index = middle; break; } else if(elements[middle] > target) { end = middle-1; } else { begin = middle+1; } } return index; }}
来源:https://www.cnblogs.com/baoyingying/p/11792783.html