#include<stdio.h>
#include<stdlib.h>
#define MAX_SIZE 20
// 给int类型起个别名
typedef int KeyType;
typedef int InfoType;
typedef struct RedType
{
KeyType key;
InfoType otherinfo;
}RedType;
typedef struct OrderList
{
RedType R[ MAX_SIZE + 1 ];
int length;
}OrderList;
/*
* 一趟快速排序
*/
int Partition(OrderList *L, int low, int high)
{
// 枢纽
KeyType pivot_key;
// 以子表的首记录作为枢纽,放入R[0]单元
L->R[0] = L->R[low];
// 取枢纽值存入pivot_key变量
pivot_key = L->R[low].key;
while( low < high )
{
while( low < high && L->R[high].key >= pivot_key)
high--;
// 将比枢纽小的记录交换到低端
L->R[low] = L->R[high];
while( low < high && L->R[low].key <= pivot_key)
low++;
//将比枢纽大的记录交换到高端
L->R[high] = L->R[low];
}
// 枢纽到位,现在枢纽元素左边都是比它小的,右边都是比它大的
L->R[low] = L->R[0];
// 返回枢纽元素所在位置
return low;
}
/*
* 快速排序的递归算法
*/
void QuickSort(OrderList *L, int i, int j)
{
int pivot_loc;
// 对顺序表L中的子序列R[i,...,j]作快排
if( i < j)
{
// 一趟快速排序将R[i,...,j]一分为二
pivot_loc = Partition(L, i, j);
// 在左子区间进行递归快排,直到区间长度为1
QuickSort(L, i, pivot_loc-1);
// 在右子区间进行递归快排,直到区间长度为1
QuickSort(L, pivot_loc+1, j);
}
}
int main()
{
OrderList *L;
L = (OrderList *)malloc( sizeof( OrderList ) );
int i, j ;
printf("需要排序的元素个数为:");
scanf("%d", &L->length);
printf("\nPlease input the element: ");
for(i = 0; i < L->length; i++)
{
scanf("%d", &L->R[i+1].key);
}
QuickSort(L, 1, L->length);
printf("\n快排后序列为:");
for(j = 1; j <= L->length; j++)
{
// -2,输出结果左对齐,提供2个字符的空间用于输出a
printf("%-2d", L->R[j].key);
}
printf("\n");
return 0;
}
C语言快速排序
最新推荐文章于 2022-08-20 21:47:45 发布