用数组实现插入排序

来源:互联网 发布:淘宝开店计划书 编辑:程序博客网 时间:2024/06/05 02:09

package com.algorithm.sort;public class InsertSort {public static void main(String[] args) {int a[] = { 3, 7, 4, 9, 5, 2, 6, 1 };printArray(a);Insert(a);printArray(a);}public static void Insert(int[] x) {int temp = 0;for (int i = 1; i < x.length; i++) {for (int j = 0; j < i; j++) {if (x[i] < x[j]) {temp = x[i];x[i] = x[j];x[j] = temp;}}printArray(x);}}public static void printArray(int[] x) {for (int a : x)System.out.print(a + " ");System.out.println();}}

执行后结果:

3 7 4 9 5 2 6 1
3 7 4 9 5 2 6 1
3 4 7 9 5 2 6 1
3 4 7 9 5 2 6 1
3 4 5 7 9 2 6 1
2 3 4 5 7 9 6 1
2 3 4 5 6 7 9 1
1 2 3 4 5 6 7 9
1 2 3 4 5 6 7 9

插入排序 的原理 :第i个数之前都是有序序列,将第i+1个数插入到有序序列里面,先以第一个数为一个有序序列,然后将后面所有的数依次插入其中



0 0
原创粉丝点击