Skip to content

Commit f0786d3

Browse files
committed
实现一个大小固定的有序数组,支持动态增删改操作
1 parent 10fc519 commit f0786d3

File tree

1 file changed

+124
-0
lines changed

1 file changed

+124
-0
lines changed

Array/JAVA/FixedOrderArray.md

+124
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
```java
2+
package com.test.xiaolu;
3+
import java.util.concurrent.CountDownLatch;
4+
5+
/**
6+
* 实现一个大小固定的有序数组,支持动态增删改操作
7+
* @author 小鹿
8+
*
9+
*/
10+
public class FixedOrderArray {
11+
private int[] data;
12+
private int n;
13+
private int count;
14+
15+
public FixedOrderArray(int n) {
16+
this.n = n;
17+
count = 0;
18+
data = new int[n];
19+
}
20+
21+
public static void main(String[] args) {
22+
FixedOrderArray array02 = new FixedOrderArray(5);
23+
//插入
24+
array02.insert(1);//0
25+
array02.insert(3);//1
26+
array02.insert(2);//2
27+
array02.insert(1);//3
28+
array02.insert(0);//4
29+
//删除
30+
array02.delete(0);
31+
array02.print();
32+
//查找数据
33+
System.out.println();
34+
System.out.print("查找该数据的下标为:"+array02.find(2));
35+
}
36+
37+
/**
38+
* 功能:插入
39+
* @param value 插入的元素
40+
* @return 返回 Boolean 值
41+
*/
42+
public Boolean insert(int value) {
43+
//判断数组是否为空
44+
if(data == null && data.length==0) {
45+
return false;
46+
}else {
47+
//第一个数据直接插入数组
48+
if(count == 0) {
49+
data[count] = value;
50+
count++;
51+
return true;
52+
}
53+
//优化:先判断是否大于最后一个数据
54+
if(value>=data[count-1]) {
55+
data[count] = value;
56+
count++;
57+
return true;
58+
}
59+
//其他数据比较搬移
60+
for (int i = 0; i < data.length; i++) {
61+
if(value >= data[i]) {
62+
for (int j = count-1; j >= i+1; j--) {
63+
data[j+1] = data[j];
64+
}
65+
data[i+1] = value;
66+
count++;
67+
return true;
68+
}else {
69+
//插入数组第一个位置
70+
for (int j = count-1; j >=0; j--) {
71+
data[j+1] = data[j];
72+
}
73+
data[0] = value;
74+
count++;
75+
return true;
76+
}
77+
}
78+
}
79+
return false;
80+
}
81+
82+
83+
/**
84+
* 功能:删除下标指定数据
85+
* @param index 指定下标
86+
* @return 返回删除的数据
87+
*/
88+
public int delete(int index) {
89+
//判断删除元素的下标是否合理
90+
if(index < 0 || index >= data.length) {
91+
return -1;
92+
}else {
93+
for (int i = index; i < count-1; i++) {
94+
data[i] = data[i+1];
95+
}
96+
}
97+
count--;
98+
return 0;
99+
}
100+
101+
/**
102+
* 功能: 查找
103+
* @param value 要查找的元素
104+
* @return 返回该下标
105+
*/
106+
public int find(int value) {
107+
108+
for (int i = 0; i <= count-1; i++) {
109+
if(data[i]==value) {
110+
return i;
111+
}
112+
}
113+
return -1;
114+
}
115+
116+
//打印数组内容
117+
public void print() {
118+
for(int i=0;i<count;i++) {
119+
System.out.print(data[i]+" ");
120+
}
121+
}
122+
}
123+
```
124+

0 commit comments

Comments
 (0)