顺序加入数组,是我自己想出来的。
而二分法这么简单的算法,我自己没有实践出来,还是看了一下书上代码之后,凭记忆写出来的。
可能有稍许不同,但不影响结果。
加油呀。要
class HighArray { private long[] a; private int nElems; public HighArray(int max) { a = new long[max]; nElems = 0; } public int size() { return nElems; } public int find(long searchKey) { int lowerBound = 0; int upperBound = nElems - 1; int curIn; while(true) { curIn = (lowerBound + upperBound) / 2; if(a[curIn] == searchKey){ return curIn; } else if(lowerBound > upperBound){ return nElems; } else{ if(a[curIn] < searchKey) lowerBound = curIn + 1; else upperBound = curIn -1; } } } public void insert(long value) { int j; int i; long temp; a[nElems] = value; nElems++; for(j = 0; j < nElems; j++){ for(i = j; i < nElems; i++){ if (a[j] > a[i]){ temp = a[i]; a[i] = a[j]; a[j] = temp; } } } System.out.print("Insert value: " + value); System.out.println(""); } public boolean delete(long value) { int j; for(j = 0; j < nElems; j++) if(value == a[j]) break; if(j == nElems){ System.out.println("Can't delete value: " + value); return false; } else { for(int k = j; k < nElems; k++) a[k] = a[k + 1]; nElems--; System.out.println("Delete value: " + value); return true; } } public void display() { for(int j = 0; j < nElems; j++) System.out.print(a[j] + " "); System.out.println(" "); } } public class HighArrayApp { /** * @param args */ public static void main(String[] args) { int maxSize = 100; int searchKey; HighArray arr; arr = new HighArray(maxSize); arr.insert(345); arr.insert(24); arr.insert(4); arr.insert(213); arr.insert(987); arr.insert(43); arr.insert(435); arr.insert(17); arr.insert(323); arr.insert(98); arr.display(); System.out.println("Array size is : " + arr.size()); searchKey = 35; if(arr.find(searchKey) != arr.size()) System.out.println("Found searchKey : " + searchKey); else System.out.println("Can't find searchKey : " + searchKey); searchKey = 323; if(arr.find(searchKey) != arr.size()) System.out.println("Found searchKey : " + searchKey); else System.out.println("Can't find searchKey : " + searchKey); arr.delete(00); arr.delete(55); arr.delete(99); arr.display(); arr.insert(62); arr.insert(34); arr.display(); } }
时间: 2024-09-02 15:09:51