本文主要是介绍快速排序算法,并输出每一轮后数据位置的交换,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
快速排序算法
#include <stdio.h>
#include <stdlib.h>
#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;
}
运行结果:
这篇关于快速排序算法,并输出每一轮后数据位置的交换的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!