Java顺序表(一)解决排序问题
import java.util.Scanner;
class SeqList {
private Object[] obj;
private int length;
public SeqList(){}
public SeqList(int num){
obj = new Object[num];
length = 0;
}
//清空数组
public void clean(){
length = 0;
}
//插入数组
public void inster(int position,Object i) throws Exception {
if(position>length||position<0){
throw new Exception("ArrayIndexOutOfBoundsException");
}else{
for(int p = length;p!=position;p--){
obj[p] = obj[p-1];
}
obj[position] = i;
length++;
}
}
//查找数组中的元素是否存在
public int indexOf(Object foundnum) {
for(int i = 0;i <= length;i++) {
if(foundnum.equals(obj[i])) {
return i+1;
}
}
return -1;
}
//返回数组的长度
public int length() {
return length;
}
//输出
public void display() {
for(int i = 0;i<length;i++) {
System.out.print(obj[i]+" ");
}
System.out.println();
}
//逆序输出
public void reverse() {
Object temp;
for(int i = 0;i < length/2;i++){
temp = obj[i];
obj[i] = obj[length-1-i];
obj[length-1-i] = temp;
}
}
}
public class Main {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
SeqList s = new SeqList(10);
Scanner sc = new Scanner(System.in);
Object input = sc.next();
while(!input.equals("0")) {
s.inster(0,input);
input = sc.next();
}
int indexOf = s.indexOf(sc.next());
System.out.println("The length:"+s.length());
System.out.println("The elements:");
s.display();
if(indexOf==-1) {
System.out.println("No found");
}else {
System.out.println("Found position:"+indexOf);
}
s.reverse();
System.out.println("The length:"+s.length());
System.out.println("The elements:");
s.display();
}
}