(二)Java数组的使用
Java数组
无序数组插入删除查询操作:
public class ArrayList { private static int[] intArray; private int nElems; public ArrayList(int max){ intArray=new int[max]; nElems=0; } public boolean find(long searchKey){ int j; for(j=0;j<nElems;j++){ if(intArray[j]==searchKey){ break; } } if(j==nElems){ return false; }else{ return true; } } public void insert(int value){ intArray[nElems]=value; nElems++; } public boolean delete(int value){ int j; for(j=0;j<nElems;j++){ if(value==intArray[j]){ break; } } if(j==nElems){ return false; }else{ for(int k=j;k<nElems;k++){ intArray[k]=intArray[k+1]; } nElems--; return true; } } public void display(){ for(int j=0;j<nElems;j++){ System.out.print(intArray[j]+" "); } System.out.println(); } public static void main(String[] args) { int maxSize=100; ArrayList arr=new ArrayList(maxSize); arr.insert(77); arr.insert(99); arr.insert(44); arr.insert(55); arr.insert(22); arr.insert(88); arr.insert(11); arr.insert(00); arr.insert(66); arr.insert(33); arr.display(); int searchKey=11; if(arr.find(searchKey)){ System.out.println("found "+searchKey); }else{ System.out.println("can't found "+searchKey); } arr.delete(55); arr.display(); } }
二分查找,按序插入
//线性查找,二分查找 public class OrderList { private static int[] intArray; private int nElems; public OrderList(int max) { intArray = new int[max]; nElems = 0; } public int size() { return nElems; } // 猜数游戏 // 二分查找 public int find(int searchKey) { int lowerBound = 0; int upperBound = nElems - 1; int curIn; while (true) { curIn = (lowerBound + upperBound) / 2; if (intArray[curIn] == searchKey) { return curIn; } else if (lowerBound > upperBound) { return nElems; } else { if (intArray[curIn] < searchKey) { lowerBound = curIn + 1; } else { upperBound = curIn - 1; } } } } //按顺序插入 public void insert(int value) { int j; for (j = 0; j < nElems; j++) { if (intArray[j] > value) { break; } } for (int k = nElems; k > j; k--) { intArray[k] = intArray[k - 1]; } intArray[j] = value; nElems++; } public boolean delete(int value){ int j=find(value); if(j==nElems){ return false; }else{ for(int k=j;k<nElems;k++){ intArray[k]=intArray[k+1]; } nElems--; return true; } } public void display(){ for(int j=0;j<nElems;j++){ System.out.print(intArray[j]+" "); } System.out.println(); } public static void main(String[] args) { int maxSize=100; OrderList arr=new OrderList(maxSize); arr.insert(77); arr.insert(99); arr.insert(44); arr.insert(55); arr.insert(22); arr.insert(88); arr.insert(11); arr.insert(00); arr.insert(66); arr.insert(33); arr.display(); int searchKey=11; if(arr.find(searchKey)!=arr.size()){ System.out.println("found "+searchKey+":"+arr.find(searchKey)); }else{ System.out.println("can't found "+searchKey); } arr.delete(55); arr.display(); } }
效率
线性查找 | O(N) |
二分查找 | O(log N) |
无序数组插入 | O(1) |
有序数组插入 | O(N) |
无序数组删除 | O(N) |
有序数组删除 | O(N) |