一开始不理解为什么无序数组插入比有序数组快,因为无序没有顺序,随便插入,自然是插在末尾,不需要移动其他元素最快了,而有序数组插入需要移动插入之后的元素。
以下是有序数组插入和二分法查找。
如有错误,感谢指正
import java.util.Scanner;
public class disorder_Array {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
selfArray a = new selfArray();
for(int i=0;i<n;i++) {
a.insert(sc.nextInt());
}
a.show();
System.out.println(a.find(3));
}
}
class selfArray{
private int array[];
private int len;
public selfArray() {
array = new int[10];
this.len = 0;
// TODO Auto-generated constructor stub
}
public void insert(int num) {
if(len==0) {
array[0] = num;
this.len++;
return;
}
for(int i=0;i<len;i++) {
if(num<array[i]) {
this.len++;
for(int j=len-1;j>i;j--) {
array[j]=array[j-1];
}
array[i]=num;
return;
}
}
array[len] = num;
this.len++;
}
public int find(int num) {
int lastPos=this.len-1;
int firstPos=0;
int curr;
if(lastPos<0) {
return -1;
}
while(true) {
curr = (lastPos+firstPos)/2;
if(array[curr]==num) {
return curr;
}
else if(curr==firstPos) {
if(array[lastPos]==num) {
return lastPos;
}
else {
return -1;
}
}
else {
if(array[curr]>num) {
lastPos = curr;
}
else {
firstPos = curr;
}
}
}
}
public void show() {
for(int i=0;i<this.len;i++) {
System.out.println(array[i]);
}
}
}