最近看完排序,把自己写的代码贴出来,算是对自己的激励,也给有需要的同学一起提示吧,写得稀烂还望谅解。
1.直接出入排序:void InsertSort(int R[],int n)
{
int i,j,temp;
for(i=1;i<n;i++)
{
temp=R[i];
if(R[i]<R[i-1])
{
for(j=i-1;temp<R[j]&&j>=0;j--)
R[j+1]=R[j];
R[j+1]=temp;
}
}
}
2.折半插入排序
void BinsertSort(int R[],int n)
{
int i,j,low,high,temp,m;
for(i=1;i<n;i++)
{
temp=R[i];
low=0;high=i-1;
while(low<=high)
{
m=(low+high)/2;
if(temp>R[m])
low=m+1;
else
high=m-1;
}
for(j=i-1;j>=low;j--)
R[j+1]=R[j];
R[low]=temp;
}
}
3.希尔排序
void Shellsort(int R[],int n)
{
int i,j,temp,d;
d=n/2;
while(d>0)
{
for(i=d;i<n;i++)
if(R[i]<R[i-d])
{
temp=R[i];
for(j=i-d;j>=0&&temp<R[j];j-=d)
R[j+d]=R[j];
R[j+d]=temp;
}
d=d/2;
}
}
4.快速排序
int Partition(int R[],int s,int t)
{
int temp,low,high;
low=s;high=t;
temp=R[s];
while(low<high)
{
while(low<high&&R[high]>=temp)
high--;
R[low]=R[high];
while(low<high&&R[low]<=temp)
low++;
R[high]=R[low];
}
R[low]=temp;
return low;
}
void QSort(int R[],int low,int high)
{
int partition;
if(low<high-1)
{
partition=Partition(R,low,high);
QSort(R,low,partition-1);
QSort(R,partition+1,high);
}
}
5.归并排序
void Merge(int SR[],int TR[],int i,int m,int n)
{
int k,j;
for(j=m+1,k=i;i<=m&&j<=n;k++)
{
if(SR[i]<=SR[j])
TR[k]=SR[i++];
else TR[k]=SR[j++];
}
if(i<=m)
for(;i<=m;k++)
TR[k]=SR[i++];
if (j<=n)
for(;j<=n;k++)
TR[k]=SR[j++];
}
void MSort(int SR[],int TR1[],int s,int t )
{
int m;
int TR2[11];
if(s==t)
TR1[s]=SR[s];
else
{
m=(s+t)/2;
MSort(SR,TR2,s,m);
MSort(SR,TR2,m+1,t);
Merge(TR2,TR1,s,m,t);
}
}
6.堆排序
void HeapAdjuse(int R[],int low,int high)
{
int i,j,temp;
i=low;
j=2*i;
temp=R[low];
for(j=2*i;j<=high;j*=2)
{
if(j<high&&R[j+1]>R[j])
j++;
if(temp>=R[j]) break;
R[low]=R[j];
low=j;
}
R[low]=temp;
}
void HeapSort(int R[],int n)
{
int i,temp;
for(i=n/2;i>0;i--)
HeapAdjuse(R,i,n);
for(i=n;i>1;i--)
{
temp=R[i];
R[i]=R[1];
R[1]=temp;
HeapAdjuse(R,1,i-1);
}
}