#include <stdio.h>
//函数声明
void Insertion_sort(int a[],int N);//插入排序
void swap(int * a,int * b);//交换数组两位元素的位置
int Median(int a[],int Left,int Right);//将基准放到倒数第二的位置,并返回基准的值
void Qsort(int a[],int Left,int Right);//快速排序主函数
void QuickSort( int a[], int N );//统一入口
int main (void)
{
int i;
int a[6] = {34,8,64,51,32,21};
QuickSort(a,6);
for(i= 0;i<6;i++)
{
printf("%d ",a[i]);
}
return 0;
}
void Insertion_sort(int a[],int N)
{
int i,j,Tmp;
for(i = 1;i < N; i++)
{
Tmp = a[i];
for(j = i;j > 0 && a[j-1] > Tmp; j--)
{
a[j] = a[j-1];
}
a[j] = Tmp;
}
}
void swap(int * a,int * b)
{
int t;
t = *a;
*a = *b;
*b = t;
}
int Median(int a[],int Left,int Right)
{
int Mid = (Left + Right)/2;
if (a[Left] > a[Mid])
{
swap(&a[Left],&a[Mid]);
}
if (a[Left] > a[Right])
{
swap(&a[Left],&a[Right]);
}
if (a[Mid] > a[Right])
{
swap(&a[Mid],&a[Right]);
}
swap(&a[Mid],&a[Right-1]);
return a[Right-1];
}
void Qsort(int a[],int Left,int Right)
{
int cutoff = 50;
int point;//存储基准
int low,high;
if(cutoff < (Right - Left))
{
point = Median(a,Left,Right);
low = Left,high = Right-1;
while( 1 )
{/*将序列中比基准小的移到基准左边,大的移到右边*/
while (a[++low] < point) ;
while (a[--high] > point) ;
if (low < high )swap(&a[low],&a[high]);
else break;
}
swap(&a[low],&a[Right-1]); /* 将基准换到正确的位置 */
Qsort(a,Left,low - 1);/* 递归解决左边 */
Qsort(a,low +1,Right); /* 递归解决右边 */
}
else
{
Insertion_sort(a, Right - Left +1);
}
}
void QuickSort( int a[], int N )
{ /* 统一接口 */
Qsort( a, 0, N-1 );
}
快速排序&& 数据结构
最新推荐文章于 2022-06-13 09:25:28 发布