JAVA插入排序实现

实现方法一:
class InsertSort{

ArrayList al;

public InsertSort(int num,int mod){
al=new ArrayList(num);
Random rand=new Random();
System.out.println("需要排序的数组为:");
for(int i=0;i<num;i++){
al.add(i,new Integer((Math.abs(rand.nextInt()))%mod+1));
System.out.println("al["+i+"]="+al.get(i));
}
}

public void SortArray(){
int maxSize=1;
Integer temp;
for(int i=1;i<=al.size()-1;i++){
temp=(Integer)al.remove(i);
if(temp.intValue()>=((Integer)(al.get(maxSize-1))).intValue()){
al.add(i, temp);
maxSize++;
}else{
for(int j=0;j<al.size();j++){
if(temp.intValue()<=((Integer)(al.get(j))).intValue()){
al.add(j, temp);
maxSize++;
break;
}
}
}
}
System.out.println("排序后的数组为:");
for(int i=0;i<al.size();i++){
System.out.println("al["+i+"]="+al.get(i));
}
}

public static void main(String[] args){
InsertSort insertSort= new InsertSort(6,100);
insertSort.SortArray();
}
}


实现方法二:
class InsertSort2{
public static void main(String[] args){
int[] a={20,11,42,56,38,77};
int n=a.length;
int i,j;
int temp;
for(i=0;i<n;i++){
temp=a[i];
for(j=i;j>0 && temp<a[j-1];j--){
a[j] = a[j-1];
}
a[j]=temp;
}

for(i=0;i<n;i++){
System.out.println("a["+i+"]="+a[i]);
}
}
}

猜你喜欢

转载自wang2832840-163-com.iteye.com/blog/2301567