/**
* 插入排序
**/
#include<stdio.h>
// 对数组A进行插入排序 (升序)
void insertSort(int A[],int n){
int temp;
// 从第二个元素开始执行(n-1)次
for(int i=1;i<n;i++){
// A[i] < A[i-1] 临时存起来 temp = A[i]
if(A[i] < A[i-1]){
temp = A[i];
// 逆序遍历j=i-1,temp > A[j],j-- 每次向后移动1位
for(int j=i-1;j>=0 && temp<A[j];j--){
// 每次向后移动1位
A[j+1] = A[j];
}
//最后得到j的位置插入 A[j] = temp
A[j+1] = temp;
}
}
}
// 折半插入排序
void insertSortHalf(int A[],int n){
int temp;
int low,hight,mid;
// 从第二个元素开始执行(n-1)次
for(int i=1;i<n;i++){
// A[i] < A[i-1] 临时存起来 temp = A[i]
if(A[i] < A[i-1]){
temp = A[i];
low = 0;
hight = i-1;
// 二分查找位置
while(low <= hight){
mid = (low+hight)/2;
if(A[mid] > A[i]){
hight = mid-1;
}else{
low = mid+1;
}
}
// 找到位置low 大的向后移动
for(int j=i-1;j>=hight+1;--j){
A[j+1]=A[j];
}
A[hight+1] = temp;
}
}
}
/**
* 希尔排序
**/
void shellSort(int A[],int n){
int temp ;
// 求步长d(执行n/2次)
for(int d = n/2 ;d>=1;d=d/2){
// 进行插入排序
for(int i=d+1;i<n;i++){
// 小于前子列表最大值才插入
if(A[i] < A[i-d]){
temp = A[i];
// 对前子列表进行插入排序
for(int j=i-d;j>0&&A[j]>temp;j--){
// 向后移动
A[j+d]=A[j];
}
A[j+d] = temp;
}
}
}
}
void main(){
int A[5] = {1,5,2};
shellSort(A,3);
for(int i=0;i<3;i++){
printf("%d\t", A[i]);
}
}
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交