《算法导论》插入排序算法(JAVA实现)
伪代码(算法导论【原书第三版】,第10页)
数组 A
A.length 数组元素个数
// 注释
and &&
A[j] 根据下标取数组单个元素
for,while 循环语句
INSERTION-SORT(A)
for j=2 to A.length
key=A[j]
//Insert A[j] into the sorted sequence A[1..j-1]
i=j-1
while i>0 and A[i]>key
A[i+1]=A[i]
i=i-1
A[i+1]=key
JAVA代码实现
public class Sort {
public static void main(String[] args) {
int[] a=sort(new int[]{5,2,4,6,1,3});
for(int i= 0;i<a.length;i++){
System.out.println(a[i]);
}
}
public static int[] sort(int[] arr){
for(int j=1;j<arr.length;j++){
int key=arr[j];
int i=j-1;
while(i>=0 && arr[i]>key){
arr[i+1]=arr[i];
i=i-1;
arr[i+1]=key;
}
}
return arr;
}
}