您的位置:首页 > 其它

直接插入排序

2015-05-24 00:26 330 查看
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);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: