插入排序
- 作者: 李广46656
- 来源: 51数据库
- 2021-11-12
插入排序
从第二个数起,与前面的数依次比较如果比前面的数小就交换,直到第二个数前面的数字顺序为从小到大为止,然后从第三个数重复以上过程,第四个、第五个…
模拟过程
例:对3 8 1 5 4 6 2 9 排序过程
3 8 1 5 4 6 2 9
3 8 1 5 4 6 2 9
3 1 8 5 4 6 2 9
1 3 8 5 4 6 2 9
1 3 5 8 4 6 2 9
1 3 5 8 4 6 2 9
1 3 5 8 4 6 2 9
1 3 5 4 8 6 2 9
1 3 4 5 8 6 2 9
1 3 4 5 8 6 2 9
1 3 4 5 8 6 2 9
1 3 4 5 6 8 2 9
1 3 4 5 6 8 2 9
1 3 4 5 6 8 2 9
1 3 4 5 6 8 2 9
1 3 4 5 6 8 2 9
1 3 4 5 6 2 8 9
1 3 4 5 2 6 8 9
1 3 4 2 5 6 8 9
1 3 2 4 5 6 8 9
1 2 3 4 5 6 8 9
1 2 3 4 5 6 8 9
1 2 3 4 5 6 8 9
1 2 3 4 5 6 8 9
1 2 3 4 5 6 8 9
1 2 3 4 5 6 8 9
1 2 3 4 5 6 8 9
1 2 3 4 5 6 8 9
1 2 3 4 5 6 8 9
1 2 3 4 5 6 8 9
代码实现
public class InsertSort {
private int []arr;
private int num;
public static void main(String[] args) {
InsertSort op=new InsertSort();
op.arr=new int[8];
op.insert(3);
op.insert(8);
op.insert(1);
op.insert(5);
op.insert(4);
op.insert(6);
op.insert(2);
op.insert(9);
op.sort();
op.display();
}
public void insert(int a) {
arr[num]=a;
num++;
}
public void sort() {
for(int i=1;i<num;i++) {
int in=i;
for(int j=i-1;j>=0;j--) {
if(arr[in]<arr[j]) {
swap(in,j);
in=j;
}
}
}
}
public void swap(int a,int b) {
int temp;
temp=arr[a];
arr[a]=arr[b];
arr[b]=temp;
}
public void display() {
for(int i=0;i<num;i++) {
System.out.println(arr[i]);
}
}
}
推荐阅读