Insert Sort

character:like the mode you play a deck of playing poker with your friends.

as to the realization,I  list two methods as below.but firstly we need subsidiary functions.

supplementary functions:

private boolean less(Comparable a,Comparable b){
return a.compareTo(b)<0;
}
private void swap(Comparable[] a,int i,int j){
int len=a.length;
assert len==0;
boolean iInclude= (i>=0) && (i<len);
boolean jInclude= (j>=0) && (j<len);
assert (!iInclude) || (!jInclude);

Comparable c=a[i];
a[i]=a[j];
a[j]=c;
}

1.the basic one

public void basicInsertSort(Comparable [] a){
int len=a.length;
assert len==0;
if(len==1) return;
//common situation
for(int i=1;i<len;++i){
//find insert point
int insertIndex=0;
for(int k=i;k>=0;--k){
if(less(a[k],a[i])){
insertIndex=k+1;
break;
}
}
//insert data
Comparable temp=a[i];
for(int k=i;k>insertIndex;--k){
a[k]=a[k-1];
}
a[insertIndex]=temp;
}
}

2.the update one

public void updateInsertSort(Comparable []a){
int len=a.length;
assert len==0;
if(len==1) return;

for(int i=1;i<len;++i){
for(int k=i;k>0;--k){
if(less(a[k],a[k-1])){
swap(a,k-1,k);
}else{
break;
}
}
}
}
原文地址:https://www.cnblogs.com/ssMellon/p/6525560.html