快速排序算法,并输出每一轮后数据位置的交换

快速排序算法

#include 
#include 
#define MAXSIZE 20//顺序表长度
typedef int KeyType;
typedef struct
{
    KeyType Key;
}RcdType;
typedef struct
{
    RcdType r[MAXSIZE+1];
    int length;
}SqList;
void swap(RcdType &r1,RcdType &r2)
{
    RcdType temp=r1;
    r1=r2;
    r2=temp;
}
void InitList(SqList &L)
{
    int len;
    printf("顺序表长度为:\t");
    scanf("%d",&len);
    L.length=len;
    for(int i=1;i<=L.length;i++)
    {
        printf("第%d个元素为:\t",i);
        scanf(" %d",&L.r[i].Key);
    }
}
void ShowList(SqList L)
{
    for(int i=1;i<=L.length;i++)
    {
        printf("%d\t",L.r[i].Key);
    }
    printf("\n");
}
int Partition(SqList &L,int low,int high)
{
    KeyType pivotKey=L.r[low].Key;
    while(low<high)
    {
        while(low<high&&L.r[high].Key>pivotKey) high--;
        {swap(L.r[low],L.r[high]);printf("%d<--->%d\t",low,high);}
        while(low<high&&L.r[low].Key<pivotKey) low++;
        {swap(L.r[low],L.r[high]);printf("%d<--->%d\t",low,high);}
    }
    printf("此趟排序后的序列为:\n");
    ShowList(L);
    return low;
}
void Qsort(SqList &L,int low,int high)
{
    if(low<high){
    KeyType pivotKey=Partition(L,low,high);
    Qsort(L,low,pivotKey-1);
    Qsort(L,pivotKey+1,high);}
}
void QuickSort(SqList &L)
{
    Qsort(L,1,L.length);
}
int main()
{
    SqList L;
    InitList(L);
    QuickSort(L);
    printf("最终排序为:\n");
    ShowList(L);
    return 0;
}

运行结果:
快速排序算法,并输出每一轮后数据位置的交换_第1张图片

你可能感兴趣的:(c++)