直接插入排序?
public class InsertSort {
public static void insert(int[] a){
if(a == null){
throw new RuntimeException("输入数组");
}
if(a.length <= 1){
return;
}
for(int j = 1;j<a.length;j++){
int temp = a[j];
int i;
for(i = j-1;i>=0 && a[i]>temp;i--){
a[i+1] = a[i];
}
//不满足上面for循环的话,元素不动
a[i+1] = temp;
}
}
public static void main(String[] args){
int[] a = {4,2,2,2,1,5,7,6};
InsertSort.insert(a);
System.out.println(Arrays.toString(a));
}
}
近期评论