c语言实现希尔排序和快速排序
程序员文章站
2022-03-15 23:45:06
...
希尔排序
#include<stdio.h>
#define SWAP(X,Y) {X=X+Y;Y=X-Y;X=X-Y;}
/*整数数组输出函数*/
int myputs(int *array,int num)
{
int i;
for(i=0;i<num;i++)
{
printf("%3d ",array[i]);
if(!((i+1)%20))printf("\n");
}
printf("\n");
return 0;
}
/*希尔排序*/
int ShellSort(int *array,int num)
{
int i=0,j=0,k=0,len=num;
while(len>1)
{
len=len/3+1;
for(i=0;i<num-len;i++)
{
k=i;
while(k<num-len)k+=len;
for(j=k;j>=len;j-=len)
{
if(array[j-len]>array[j])
SWAP(array[j],array[j-len])
}
}
}
return 0;
}
int test(int (*p)(int *,int),char *pr,int *array,int num)
{
printf("****************************希尔排序函数%s ***************************\n",pr);
printf("排序前:\n");
myputs(array,num);
(*p)(array,num);
printf("排序后:\n");
myputs(array,num);
return 0;
}
int main()
{
int array[]={ 3, 5, 9,88, 7,53,87, 4,38, 1,65,75,46,25,93, 6, 2,79,12, 4,
35,59,98,87,75,58,84,43,31,16,67,74,42,29,96,62,27,71,14,43,
30,50,90,88,70,35,78,40,83,10,56,57,46,52,93,60,20,97,21,40,
53,95,89,78,57,85,48,34,13,61,76,47,24,92,69,26,72,17,41,34};
test(ShellSort,"ShellSort",array,sizeof(array)/sizeof(int));
return 0;
}
快速排序
#include<stdio.h>
/*整数数组输出函数*/
int myputs(int *array,int num)
{
int i;
for(i=0;i<num;i++)
{
printf("%3d ",array[i]);
if(!((i+1)%20))printf("\n");
}
printf("\n");
return 0;
}
/*快速排序*/
int QuickSort(int *array,int beg, int end)
{
if(beg>=end)return 0;
int i=beg,j=end,base=array[beg],flag=0;
while(i<j)
{
if(!flag)
{
if(array[j]<base)
{
array[i++]=array[j];
flag=1;
}
else j--;
}
else
{
if(array[i]>base)
{
array[j--]=array[i];
flag=0;
}
else i++;
}
}
array[i]=base;
QuickSort(array,beg,i-1);
QuickSort(array,i+1,end);
return 0;
}
int test(int (*p)(int *,int,int),char *pr,int *array,int num,int beg,int end)
{
printf("****************************快速排序函数%s ***************************\n",pr);
printf("排序前:\n");
myputs(array,num);
(*p)(array,beg,end);
printf("排序后:\n");
myputs(array,num);
return 0;
}
int main()
{
int array[]={ 3, 5, 9,88, 7,53,87, 4,38, 1,65,75,46,25,93, 6, 2,79,12, 4,
35,59,98,87,75,58,84,43,31,16,67,74,42,29,96,62,27,71,14,43,
30,50,90,88,70,35,78,40,83,10,56,57,46,52,93,60,20,97,21,40,
53,95,89,78,57,85,48,34,13,61,76,47,24,92,69,26,72,17,41,34 };
test(QuickSort,"QuickSort",array,80,0,79);
return 0;
}
上一篇: 解读正则表达式
下一篇: ECharts 高度宽度自适应(转载)