一.数组
1.构造简单的数组的包装类;具有插入、删除、查找功能;
package com.lcq.array;
//create HighArray as tool class
public class HighArray {
private long[] array;
private int items;//number of data items
//constructor function
public HighArray(int max){
array = new long[max];
items = 0;
}
//create find method to find searchKey
public boolean find(long searchKey){
boolean b = false;
for(int i = 0;i < items;i++){
if(searchKey == array[i]){
b = true;
break;
}
}
return b;
}
//create insert method to put item into array
public void insert(long value){
array[items] = value;
items++;
}
//create delete method to delete item from array
public boolean delete(long value){
boolean b = false;
for(int i = 0;i < array.length;i++){
if(value == array[i]){
for(;i < array.length-1;i++){
array[i] = array[i+1];
}
b = true;
items--;
break;
}
}
return b;
}
//show items
public void display(){
for(int i = 0;i < items;i++){
System.out.println("array[" + i + "]=" + array[i]);
}
}
}
测试类:
package com.lcq.array;
/**
* function : test HighArray class
* @author lcq
* write test class first maybe better
*/
public class HighArrayApp {
public static void main(String[] args) {
HighArray a = new HighArray(5);
a.insert(1);
a.insert(2);
a.insert(3);
a.display();
System.out.println(a.find(5));
a.delete(2);
a.delete(4);
a.display();
}
}
2.构造有序的数组的包装类;该类能够进行二分查找和进行有序的插入数据;
package com.lcq.array;
/**
* focus on find and insert methods
* @author lcq
*
*/
public class OrdArray {
private long[] array;
private int items;
public OrdArray(int max) {
array = new long[max];
items = 0;
}
public boolean find(long value) {
boolean b = false;
int lowerBound = 0;
int upperBound = items - 1;
int curIn;
while (true) {
curIn = (lowerBound + upperBound) / 2;
if (array[curIn] == value) {
b = true;
return b;
} else if (array[curIn] < value) {
lowerBound = curIn + 1;
} else {
upperBound = curIn - 1;
}
if (lowerBound > upperBound) {
return b;
}
}
}
public void insert(long value) {
int i;
for (i = 0; i < items; i++) {
if (value < array[i]) {
break;
}
}
for (int k = items; k > i; k--) {
array[k] = array[k - 1];
}
array[i] = value;
items++;
}
public boolean delete(long value) {
boolean b = false;
for (int i = 0; i < array.length; i++) {
if (value == array[i]) {
for (; i < array.length - 1; i++) {
array[i] = array[i + 1];
}
b = true;
items--;
break;
}
}
return b;
}
public void display() {
for (int i = 0; i < items; i++) {
System.out.println("array[" + i + "]=" + array[i]);
}
}
}
测试类:
package com.lcq.array;
public class OrdArrayApp {
public static void main(String[] args) {
OrdArray ordArray = new OrdArray(5);
ordArray.insert(1);
ordArray.insert(2);
ordArray.insert(3);
ordArray.insert(5);
ordArray.insert(4);
ordArray.display();
System.out.println(ordArray.find(2));
ordArray.delete(2);
ordArray.display();
System.out.println(ordArray.find(2));
}
}