首页 > 代码库 > 插入排序
插入排序
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | public class InsertSort { public static void sort( int [] a) { int N = a.length; int count = 0 ; for ( int i = 1 ; i < N; i++) // 如果只有一个元素, i < N 就不会成立,for循环就不执行 { for ( int j = i; j > 0 ; j--) { if (a[j] < a[j- 1 ]) { int temp = 0 ; temp = a[j]; a[j] = a[j- 1 ]; a[j- 1 ] = temp; count++; } } } for ( int i = 0 ; i < N; i++) { System.out.print(a[i] + " " ); } System.out.println( "count = " + count); } public static void main(String[] args) { int [] a = { 6 , 2 , 5 , 3 , 1 , 4 }; InsertSort.sort(a); } } |
运算过程:
{6, 2, 5, 3, 1, 4} ----------------------------- i = 1; j = 1; {2, 6, 5, 3, 1, 4} ----------------------------- i = 2; j = 2; {2, 5, 6, 3, 1, 4} j = 1; ----------------------------- i = 3; j = 3; {2, 5, 3, 6, 1, 4} j = 2; {2, 3, 5, 6, 1, 4} j = 1; ----------------------------- i = 4; j = 4; {2, 3, 5, 1, 6, 4} j = 3; {2, 3, 1, 5, 6, 4} j = 2; {2, 1, 3, 5, 6, 4} j = 1; ------------------------------ i = 5; j = 5; {1, 2, 3, 5, 4, 6} j = 4; {1, 2, 3, 4, 5, 6} j = 3; j = 2; j = 1;
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。