-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOrderedArray.java
More file actions
122 lines (107 loc) · 2.48 KB
/
OrderedArray.java
File metadata and controls
122 lines (107 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package com.fantasy.datastructure.array;
/**
* 大小固定的有序数组
*
* <pre>
* author : Fantasy
* version : 1.0, 2020-07-01
* since : 1.0, 2020-07-01
* </pre>
*/
public class OrderedArray {
/**
* 默认容量
*/
private static final int DEFAULT_CAPACITY = 20;
/**
* 当前容量
*/
private int mCapacity;
/**
* 当前元素个数
*/
private int mSize;
/**
* 数组容器
*/
private int[] mData;
public OrderedArray() {
this(DEFAULT_CAPACITY);
}
public OrderedArray(int capacity) {
mCapacity = capacity;
mData = new int[mCapacity];
}
/**
* 添加元素
*
* @param element 元素
*/
public void add(int element) {
if (mSize == mCapacity) {
throw new IllegalArgumentException("add fail. array is full.");
}
int i = mSize - 1;
for (; i >= 0; i--) {
if (element < mData[i]) {
mData[i + 1] = mData[i];
} else {
break;
}
}
mData[i + 1] = element;
mSize++;
}
/**
* 删除指定索引的元素
*
* @param index 索引
* @return 被删除的元素
*/
public int remove(int index) {
if (index < 0 || index > mSize - 1) {
throw new IllegalArgumentException("remove fail. index out of range.");
}
int element = mData[index];
for (int i = index; i < mSize - 1; i++) {
mData[i] = mData[i + 1];
}
mData[mSize - 1] = 0;
mSize--;
return element;
}
/**
* 获取指定索引的元素
*
* @param index 索引
* @return 元素
*/
public int get(int index) {
if (index < 0 || index > mSize - 1) {
throw new IllegalArgumentException("get fail. index out of range.");
}
return mData[index];
}
public boolean isEmpty() {
return mSize == 0;
}
public int getSize() {
return mSize;
}
public String toString() {
if (isEmpty()) {
return "[]";
}
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < mSize; i++) {
sb.append(get(i));
if (i == mSize - 1) {
sb.append("]");
} else {
sb.append(',').append(' ');
}
}
return sb.toString();
}
}