直接插入排序-是一种最简单的排序方法,它的基本操作是将一个记录插入到已排好序的有序表中,从而得到一个新的、记录数增1的有序表。
初始序列:
i=1 [46] 58 15 45 90 18 10 62
↓
i=2 [46 58] 15 45 90 18 10 62
┌——┘
↓
i=3 [15 46 58] 45 90 18 10 62
┌——┘
↓
i=4 [15 45 46 58] 90 18 10 62
↓
i=5 [15 45 46 58 90] 18 10 62
┌—————┘
↓
i=6 [15 18 45 46 58 90] 10 62
┌————————┘
↓
i=7 [10 15 18 45 46 58 90] 62
┌—┘
↓
i=8 [10 15 18 45 46 58 62 90]
实例代码:
public class InsertSortSample {
public static void main(String[] args) {
int[] des = {46,58, 15, 45 ,90 ,18, 10, 62 };
//ASC
int[] sorted = {des[0]};
for (int i = 1; i < des.length; i++) {
int[] temp = sorted;
sorted = new int[i+1];
System.arraycopy(temp, 0, sorted, 0, i);
//计算第i次插入目标的位置
int pos = 0;
for (int j = 0; j < i; j++) {
if(des[i]>sorted[j]){
pos++;
}
}
int temp1 = sorted[pos];
sorted[pos] = des[i];
for (int j = pos+1; j < sorted.length-1; j++) {
sorted[j+1] = temp[j];
}
if(pos<sorted.length-1){
sorted[pos+1] = temp1;
}
}
for (int i = 0; i < sorted.length; i++) {
System.out.println(sorted[i]);
}
}
}
6861

被折叠的 条评论
为什么被折叠?



