/*
*四种插入排序(直接插入排序,折半插入排序,希尔排序)
*/
#include<stdio.h>
#define N 8
#define M 3
void sort1(int a[N]);
void sort2(int a[N]);
void print(int a[N]);
void sort3(int a[N]);
void sort3two(int a[N],int delph);
void sort4(int a[N]);
void sort5(int a[N],int low ,int high);
int sort5two(int a[N],int low,int high);
void main()
{
int a[N]={5,6,3,9,1,7,2,4};
sort1(a); //折半插入排序
sort2(a); //直接插入排序
sort3(a); //希尔排序
sort4(a); //冒泡排序
sort5(a,0,N-1); //快速排序
print(a); //打印
}
//快速排序//
void sort5(int a[N],int low ,int high)//递归调用sort5Two()方法
{
int pos;
while(low<high)
{
pos=sort5two(a,low,high);
sort5two(a,low,pos-1);
sort5two(a,pos+1,high);
}
}
int sort5two(int a[N],int low,int high)//排序核心
{
int temp;
temp=a[low];
while (low<high)
{
while(low<high&&a[high]>temp) high--;//左端查找小于temp的数,high停在此值上
if(low<high){a[low]=a[high];low++;}//将high指向的值赋给low,并将low后移
while(low<high&&a[low]<temp) low++;
if(low<high){a[high]=a[low];high--;}
}
a[low]=temp;
return low;
}
//冒泡排序//
void sort4(int a[N])
{
int i,j,temp;
for(j=N-1;j>0;j--)
for(i=0;i<j;i++)
if(a[i]>a[i+1])
{
temp=a[i];a[i]=a[i+1];a[i+1]=temp;
}
}
//直接插入排序//
void sort1(int a[N])
{
int temp,i,j;
for(i=1;i<N;i++)
{
temp=a[i];
j=i-1;
while(j>0)//找出需要插入的位置
{
if(a[j]>temp)
{
a[j+1]=a[j];//移动元素
j--;
}
else break;
}
//此时j指向小于temp的最后一个数
a[j+1]=temp;
}
}
//折半插入排序//
void sort2(int a[N])
{
//int a[N]={1,4,5,6,3,9,5};
int low,high,mid,temp;
for(int i=1;i<N;i++)
{
low=0; high=i-1;mid=(low+high)/2;
while(low<=high)//查找插入点,mid正好为插入点
{
if(a[i]<a[mid]) high=mid-1;
else low=mid+1;
mid=(low+high)/2;
}
temp=a[i];
for(int j=i-1;j>mid;j--)//移动mid后面的元素
a[j+1]=a[j];
a[mid+1]=temp;//将元素a[i]插到(mid+1)位置
}
}
//希尔排序//
void sort3(int a[N])
{
int delph[M]={1,2,4};
for(int i=(M-1);i>=0;i++)//增量数组delph[M]的长度
{
sort3two(a,delph[i]);
}
}
void sort3two(int a[N],int delph)//delph是增量
{
int i,temp;
for(i=0;i<(N-delph);i++) //经计算,当增量是delph时,有(N-delph)对数据需要比较
{ //调换一对数据
if(a[i]>a[i+delph])
{
temp=a[i];a[i]=a[i+delph];a[i+delph]=temp;
}
}
}
//打印函数//
void print(int a[N])
{
for(int i=0;i<N;i++)
printf("%d ",a[i]);
printf("\n");
}
各种排序算法
最新推荐文章于 2024-09-20 09:03:53 发布