/**
* 插入排序很简单,就是把待排序的元素的前面的元素顺序都排好,然后把待排序的元素跟前面已经排好的元素进行比较、交换,直到插入到正确的位置。
*
* @author 王嘉锐
*
*/
public class ChaRuSort {
public static void sort(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);
}
}
}
public 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,6,3,5,2,8,12};
sort(a);
for(int i = 0; i < a.length; i++){
System.out.println(a[i]);
}
}
}
插入排序
最新推荐文章于 2023-09-23 17:47:53 发布