插入排序:平均时间复杂度:O(n2)
public static void insert_sort(int array[],int lenth){
int temp;
for(int i=0;i<lenth-1;i++){
for(int j=i+1;j>0;j--){
if(array[j] < array[j-1]){
temp = array[j-1];
array[j-1] = array[j];
array[j] = temp;
}else{ //不需要交换
break;
}
}
}
}
希尔排序:希尔排序是插入排序的改进,我们知道插入排序在数据基本有序的情况性能最好,所以我们通过缩小增量的方法依次进行插入排序,直至数列有序。
public static void shell_sort(int array[],int lenth){
int temp = 0;
int incre = lenth;
while(true){
incre = incre/2;
for(int k = 0;k<incre;k++){ //根据增量分为若干子序列
for(int i=k+incre;i<lenth;i+=incre){
for(int j=i;j>k;j-=incre){
if(array[j]<array[j-incre]){
temp = array[j-incre];
array[j-incre] = array[j];
array[j] = temp;
}else{
break;
}
}
}
}
if(incre == 1){
break;
}
}
}
评论区