各类排序源代码

#include<stdio.h>
#include<stdlib.h>
#define leftchild(i) (2*(i)+1)
void insersort(int a[],int n)
{
for(int i=1;i<n;i++)
{
int temp=a[i];
for(int j=i-1;j>0&&temp<a[j];j--)
a[j+1]=a[j];
a[j+1]=temp;
}
}
void bubblesort(int a[],int n)
{ int temp;
for(int i=0;i<n;i++)
{
for(int j=0;j<=n-i-1;j++)
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=a[j];
}

}

}

int partition(int a[],int i,int j)
{
int temp=a[i];

while(i<j)

{
while(a[j]>temp && i<j)
j--;
if(i<j)
a[i++]=a[j];
while(a[i]<temp && i<j)
i++;
if(i<j)
a[j--]=a[i];

}
a[i]=temp;
return i;
}

void quicksort(int a[],int i,int j)
{

if(i<j)
{

int k=partition(a,i,j);
quicksort(a,i,k-1);
quicksort(a,k+1,j);
}

}
void quickselectsort(int a[],int n)
{
int min;
int temp;
for(int i=0;i<n-1;i++)
{
min=i;
for(int j=i+1;j<n;j++)
{
if(a[j]<a[i])
min=j;
temp=a[min];
a[min]=a[i];
a[i]=temp;
}
}
}
void builddown(int a[],int n,int rootindex)
{
int root=a[rootindex];
int childindex=leftchild(rootindex);
while(childindex<n)
{
if(childindex!=n-1 && a[childindex+1]>a[childindex])
childindex++;
if(root<a[childindex])
{
a[rootindex]=a[childindex];
rootindex=childindex;
childindex=leftchild(rootindex);
}
else
break;

}
a[rootindex]=root;

}
void heapsort(int a[],int n)
{
int temp;
for(int rootindex=((n-2)/2);rootindex>=0;rootindex--)
builddown(a,n,rootindex);
for(int i=n-1;i>0;i--)
{
temp=a[0];
a[0]=a[i];
a[i]=temp;
builddown(a,i,0);
}


}
int main()
{
int i, n, a[100];
printf("请输入需要排序元素的个数:");
scanf("%d", &n);
printf("随机生成的数组为:");
for (i = 1; i <= n; i++)
{
a[i] = rand() % 100 + 1;
printf("%d ", a[i]);
}
a[i] = '\0';
printf("\n");
insersort(a,n);
printf("\n插入排序结果为(由小到大):");
for (i = 1; i <= n; i++)
printf("%d ", a[i]);

bubblesort(a,n);
printf("\n冒泡排序结果为(由小到大):");
for (i = 1; i <= n; i++)
printf("%d ", a[i]);

quicksort(a,0,n-1);
printf("\n快速排序结果为(由小到大):");
for (i = 1; i <= n; i++)
printf("%d ", a[i]);

quickselectsort(a,n);
printf("\n快速选择排序结果为(由小到大):");
for (i = 1; i <= n; i++)
printf("%d ", a[i]);

heapsort(a,n);
printf("\n堆排序结果为(由小到大):");
for (i = 1; i <= n; i++)
printf("%d ", a[i]);
}

posted on 2018-01-31 22:21  这个有点难诶  阅读(178)  评论(0编辑  收藏  举报

导航