利用快速排序,我写的代码以首元素作为划分基准,可以正常运行,但是使用末元素作为划分基准,为啥变成降序了?
第一种首元素:
#include <stdio.h>
void Swap(int *a,int *b)
{
int c;
c= *a;
*a =*b;
*b =c;
}
int Partition(int a[],int p,int r)
{
int low=p+1,high=r;//low=p,high=r-1;
int x=a[p];//x=a[r]
while (1)
{while (a[low]<x&&low<r)//a[r]>a[high]&&low<r
low++;//high--
while (a[high]>x)//a[low]<x
high--;
if (low >=high) break;
Swap(&a[low],&a[high]);
}
a[p]=a[high];//a[r]=a[low]
a[high]=x;//a[low]=x;
return high;//low
}
void QuickSort(int a[],int p,int r)
{
if(p<r)
{
int q=Partition(a,p,r);
QuickSort(a,p,q-1);
QuickSort(a,q+1,r);
}
}
void main()
{
int i=0;
int p=0,r=19;
int a[]={87,75,45,67,21,54,5,4,7,8,1,2,3,4,5,6,7,8,9,10};
Partition ( a, 0, 19);
QuickSort ( a, 0, 19);
for(i=0;i<r+1;i++)
{
printf("%d,",a[i]);
}
}
第二种为元素:
#include "stdio.h"
void Swap(int *a,int *b)
{
int c;
c= *a;
*a =*b;
*b =c;
}
int Partition(int a[],int p,int r)
{
int low=p,high=r-1;
int x=a[r];//x=a[r-1]
while (1)
{
while (a[low]>x && low<r) //a[r]>a[high]&&low<r
low++;//high--
while (a[high]<x)//a[low]<x
high--;
if (low >=high)
break;
Swap(&a[high],&a[low]);
}
a[r]=a[low];//a[low]=a[r]
a[low]=x;//a[r]=x
return high;
}
void QuickSort(int a[],int p,int r)
{
if(p<r)
{
int q=Partition(a,p,r);
QuickSort(a,p,q-1);
QuickSort(a,q+1,r);
}
}
void main()
{
int i=0;
int p=0,r=19;
int a[]={87,75,45,67,21,54,5,4,7,8,1,2,3,4,5,6,7,8,9,10};
Partition ( a, 0, 19);
QuickSort ( a, 0, 19);
for(i=0;i<r+1;i++)
{
printf("%d,",a[i]);
}