插入排序具体算法过程:
假设有10个元素,首先排序前两个元素,然后继续扫描下一个元素,依次与已排序的元素进行比较,然后插入到已排序的队列的合理位置中,继续扫描下一个元素,知道所有元素都被扫描完。
很明显,插入排序也是稳定的排序。
具体代码如下:
/**
* @author yangshunfan
* 插入排序具体代码
*/
public class test06 {
public static void selectSort(int[] source) {
/*
* 这层循环用于来扫描全部元素
*/
for (int i = 1; i < source.length; i++) {
//排序主要算法
for (int j = i; (j > 0) && (source[j] > source[j - 1]); j--) {
swap(source , j , j - 1);
}
}
}
/*
* 创建方法,由于交换数的位置
*/
private static void swap(int[] source, int x, int y) {
int temp = source[x];
source[x] = source[y];
source[y] = temp;
}
/*
* 主方法
*/
public static void main(String[] args) {
int[] a = {1,2,3,7,3,4,12,-23,54,76};
selectSort(a);
for (int i = 0; i < 10; i++) {
System.out.print(a[i] +" ");
}
}
}