本次主题内容为数组。
在Java中,数组是作为对象来处理,所以在创建数组的时候需要使用new。
int[] array = new int[20];
int array[] = new int[20];
以上两种方式效果相同,但是第一方式更直观的说明是在定义一个int[] 类型对象,一般的书都建议这种方式。
有序数组的简单实现
public class OrderArray {
private final int INIT_SIZE = 20;
private long[] ary;
private int length;
public OrderArray() {
init(INIT_SIZE);
}
public OrderArray(int size) {
init(size);
}
private void init(int size) {
ary = new long[size];
length = 0;
}
public int size() {
return length;
}
public void insert(long key) {
if (ary.length <= length) {
return;
}
int j;
for (j = length - 1; j >= 0; j--) {
if (ary[j] < key) {
break;
}
ary[j + 1] = ary[j];
}
ary[j + 1] = key;
length++;
}
public void delete(long key) {
int j;
// 线性查找,也可以通过二分查找
// for (j = 0; j < length; j++) {
// if (ary[j] == key) {
// break;
// }
// }
// 二分查找
j = find(key);
// 未找到
if (j == length) {
return;
}
for (int i = j; i < length; i++) {
ary[i] = ary[i + 1];
}
length--;
}
public int find(long key) {
int leftscope = 0;
int rightscope = length;
int midscope;
while (leftscope != rightscope) {
midscope = (leftscope + rightscope) / 2;
if (ary[midscope] > key) {
rightscope = midscope - 1;
} else if (ary[midscope] < key) {
leftscope = midscope + 1;
} else {
return midscope;
}
}
if (ary[leftscope] == key) {
return leftscope;
}
return length;
}
public void display() {
System.out.print("the array is: {");
for (int i = 0; i < length; i++) {
System.out.print("" + ary[i] + ",");
}
System.out.print("}");
}
public long getvalue(int index) {
if (index <= 0 || index > length) {
return Long.MIN_VALUE;
}
return ary[index - 1];
}
public void merge(OrderArray oa) {
int newSize = this.length + oa.length;
long[] newary = new long[newSize];
int i = 0, j = 0, k = 0;
while (i < length && j < oa.length) {
if (ary[i] < oa.getvalue(j)) {
newary[k] = ary[i];
i++;
} else {
newary[k] = oa.getvalue(j);
j++;
}
k++;
}
if (i < length) {
for (; i < length; i++, k++) {
newary[k] = ary[i];
}
} else {
for (; j < oa.length; j++, k++) {
newary[k] = oa.getvalue(j);
}
}
ary = newary;
}
public void noDou() {
long temp = ary[0];
int k = 0;
for (int i = 0; i < length; i++) {
if (temp == ary[i + 1]) {
ary[i + 1] = -1;
continue;
} else {
temp = ary[i + 1];
k++;
ary[k] = temp;
}
}
length = k;
}
}
根据循环次数,大致可以看出,有序数组在查找效率更高,因为可以使用二分查找,既是使用的是简单线性查找,虽然不会更快找到元素,但是可以更快的结束找不到元素的情况。
典型适用情况:频繁查找,数据变化频率低
数组的效率的不均衡性(查找快,增删慢),而且数组的固定尺寸问题,导致灵活性下降,既是有Vector这样的类其实也是简化处理。
以上两种情况导致了必须还要其他更适合的数据结构来解决问题。