插入排序
需求:
排序前:{4,3,2,10,12,1,5,6}
排序后:{1,2,3,4,5,6,10,12}
算法设计:
Insertion类:
package suanfa;
public class Insertion {
public static void sort(Comparable[] a){
for(int i=1;i<a.length;i++){
for(int j=i;j>0;j--){
if(greater(a[j-1],a[j])){
exch(a,j-1,j);
}else{
break;
}
}
}
}
private static boolean greater(Comparable v,Comparable w){
return v.compareTo(w)>0;
}
private static void exch(Comparable[] a,int i,int j){
Comparable temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
InsertionTest类:
package suanfa;
import java.util.Arrays;
public class InsertionTest {
public static void main(String[] args) {
Integer[] a={4,3,2,10,12,1,5,6};
Insertion.sort(a);
System.out.println(Arrays.toString(a));
}
}
录制: untitled2 – Insertion.java
录制文件:https://meeting.tencent.com/crm/KzGGkGE85d