直接插入排序、快速排序和堆排序的C实现

来源:互联网 发布:sql inner join 编辑:程序博客网 时间:2024/06/08 03:01

//1.直接插入排序
/*
#include<stdio.h>
#define MAX 20
typedef int keytype;
typedef char infotype[10];
typedef struct
{
keytype key;
infotype data;
}RecType;
void InsertSort(RecType R[],int n)
{
int i,j,k;
RecType temp;
for(i=1;i<n;i++)
{
temp=R[i];
j=i-1;
while(j>=0&&temp.key<R[j].key)
{
R[j+1]=R[j];
j--;
}
R[j+1]=temp;
printf("   i=%d",i);
for(k=0;k<n;k++)
printf("%3d",R[k].key);
printf("/n");
}
}
void main()
{
int i,k,n=10;
keytype a[]={4,3,7,6,8,0,9,1,2,5};
RecType R[MAX];
for(i=0;i<n;i++)
R[i].key=a[i];
for(k=0;k<n;k++)
    printf("%3d",R[k].key);
    printf("/n");
    InsertSort(R,n);
    printf("The result is:");
    for(k=0;k<n;k++)
    printf("%3d/n",R[k].key);
}
*/
 

//2.快速插入排序

#include<stdio.h>
#define MAX 20
typedef int keytype ;
typedef char infotype[10] ;
typedef struct
{
keytype key;
infotype data;
}RecType;
void QuickSort(RecType R[],int s,int t)
{
int i=s,j=t,k;
RecType temp;
if(s<t)
{
temp=R[s];
while(i!=j)
{
while(j>i&&R[j].key>temp.key)
j--;
if(i<j)
{
R[i]=R[j];
i++;
}
while(i<j&&R[i].key<temp.key)
i++;
if(i<j)
{
R[j]=R[i];
j--;
}
}
R[i]=temp;
printf("     ");
for(k=0;k<10;k++)
if(k==i)
printf("[%d]",R[k].key);
else
printf("%4d",R[k].key);
printf("/n");
QuickSort(R,s,i-1);
QuickSort(R,i+1,t);
}
}
void main()
{
int i,k,n=10;
keytype a[]={4,3,8,7,0,1,5,6,2,9};
RecType R[MAX];
for(i=0;i<n;i++)
R[i].key=a[i];
for(k=0;k<n;k++)
printf("%3d",R[k].key);
printf("/n");
QuickSort(R,0,n-1);
printf("The result is:");
for(k=0;k<n;k++)
printf("%3d/n",R[k].key);
}

 


//3.堆排序
/*
#include<stdio.h>
#define MAX 20
typedef int keytype ;
typedef char infotype[10] ;
typedef struct
{
keytype key;
infotype data;
}RecType;
void DispHeap(RecType R[],int i,int n)
{
if(i<n)
printf("%d",R[i].key);
if(2*i<=n||2*i+1<n)
{
printf(" (" );
if(2*i<=n)
DispHeap(R,2*i,n);
printf(",");
if(2*i+1<=n)
DispHeap(R,2*i+1,n);
printf(")");
}
}
void Sift(RecType R[],int low,int high)
{
int i=low,j=2*i;
RecType temp=R[i];
while(j<=high)
{
if(j<high&&R[j].key<R[j+1].key)
j++;
if(temp.key<R[j].key)
{
R[i]=R[j];
i=j;
j=2*i;
}
else break;
}
R[i]=temp;

}
void HeapSort(RecType R[],int n)
{
int i;
RecType temp;
for(i=n/2;i>=1;i--)
Sift(R,i,n);
DispHeap(R,1,n);
printf("/n");
for(i=n;i>=2;i--)
{
temp=R[1];
R[1]=R[i];
R[i]=temp;
Sift(R,1,i-1);
DispHeap(R,1,i-1);
printf("/n");
}
}
void main()
{
int i,k,n=10;
keytype a[]={4,3,7,6,8,0,9,1,2,5};
RecType R[MAX];
for(i=1;i<=n;i++)
R[i].key=a[i-1];
printf("/n");
for(k=1;k<=n;k++)
printf("%3d",R[k].key);
printf("/n");
for(i=n/2;i>=1;i--)
Sift(R,i,n);
HeapSort(R,n);
printf("The result is:");
for(k=1;k<=n;k++)
printf("%3d/n",R[k].key);
}*/ 

去年写的,可能有的地方写的并不精炼,希望不足的地方能指出...

原创粉丝点击