插入排序方式

来源:互联网 发布:软件家园 编辑:程序博客网 时间:2024/05/17 16:13
package vincent.sort;public class InsertSort {/** * @param args */static  int[] a = new int[10];public static void main(String[] args) {// TODO Auto-generated method stuba[0] = 4;a[1] = 1;a[2] = 8;a[3] = 9;a[4] = 10;a[5] = 6;a[6] = 2;a[7] = 0;a[8] = 5;a[9] = 14;insertionSort();}public static void insertionSort(){int in , out;for(out = 1; out < 10; out ++ ){int temp = a[out];in = out;while(in > 0 && a[in-1] >= temp){a[in] = a[in -1];-- in;}a[in] = temp;print();}}public static void print(){for(int i : a){System.out.print(i + "  ");}System.out.println();}}


附加上控制台输出

 

1  4  8  9  10  6  2  0  5  14 
1  4  8  9  10  6  2  0  5  14 
1  4  8  9  10  6  2  0  5  14 
1  4  8  9  10  6  2  0  5  14 
1  4  6  8  9  10  2  0  5  14 
1  2  4  6  8  9  10  0  5  14 
0  1  2  4  6  8  9  10  5  14 
0  1  2  4  5  6  8  9  10  14 
0  1  2  4  5  6  8  9  10  14 

 

插入排序逻辑:

外层for循环中, out 变量从1 开始,向右移动, 他标记了为排序的部分的最左端的数据。 而在内层的while循环中,in变量从out变量开始,向左移动,直到temp变量小于in所指向的数据项,或者他已经不能够再往左移动为止,while循环的每躺都是向右移动一个已经排序的数据项,并且注意  完毕之后需要将 已经找到位置的a[in] = temp。

原创粉丝点击