直接插入排序

import java.util.Scanner;

public class InsertSort{
public static void directSort(double n[]){//从数组下标为1的开始的元素进行直接插入排序
int i,j;
for(i=2;i<n.length;i++){
n[0]=n[i];
for(j=i-1;j>0 && n[j]>n[0];j--){
n[j+1]=n[j];
}
n[j+1]=n[0];
}
}
public static void showSort(double[] num){
System.out.println("sorted:");
for(int i=1;i<num.length;i++) {
System.out.print(num[i] + " ");
}
}
public static void main(String args[]){
double[] num={0};
Scanner in=new Scanner(System.in);
double newNumber;
System.out.println("enter 0 represents stop");
System.out.println("Please enter the proper numbers");
while(true){

newNumber=in.nextDouble();
if(newNumber==0f){
System.out.println("User stop the sort");
break;
}
double[] tmp=new double[num.length+1];//临时数组
System.arraycopy(num,0,tmp,0,num.length);//复制数组
tmp[num.length]=newNumber;
num=tmp;
directSort(num);
showSort(num);
}
}
}

posted @ 2015-05-24 00:26  sunshinewxz  阅读(98)  评论(0编辑  收藏  举报