排序-插入排序-java
阿新 • • 發佈:2018-11-23
不知道為什麼,標題為“charu排序”被csdn給刪除了。。。。
插入排序:
思想類比打撲克摸牌的時候,摸一張插入手中的牌排順序
程式碼:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("please enter the size:");
int size = in.nextInt();
System.out.println("please enter the anrry:" );
List<Integer> list = new ArrayList<>();
for(int i=0;i<size;i++){
int value = in.nextInt();
list.add(value);
}
List<Integer> result = new ArrayList<>();
result.add(list.get(0));
size = result.size();
for (int i=1;i<list.size();i++){
inner:for(int j=0;j<size;j++){
int a = list.get(i);
if(a<=result.get(0)) {
result.add(0, a);
size = result.size();
break inner;
}
if (a>=result.get(size-1)) {
result.add(size, a);
size = result.size();
break inner;
}
if(a>=result.get(j)&&a<result.get(j+1)&&size>1) {
result.add(j+1, a);
size = result.size();
break inner;
}
}
}
System.out.println("out put:");
for(int i=0;i<result.size();i++){
System.out.printf(result.get(i)+" ");
}
}