/************************************************************************/
/* 快速排序 */
/************************************************************************/
#include <iostream>
#define MAXSIZE 10
typedef struct
{
int lenght;
int r[MAXSIZE + 1];
}SqList;
void QSort(SqList* T, int low, int hight);
int Partion(SqList* L, int low, int high);
/* 交换L中数组r的下标为i和j的值 */
void swap(SqList *L, int i, int j);
void QuickSort(SqList* L);
/************************************************************************/
/* 对顺序表L中的子序列做快速排序 */
/************************************************************************/
void QSort(SqList* T, int low, int hight);
int Partion(SqList* L, int low, int high);
void Print(SqList* L);
void main()
{
int arr[] = { 0,50,10,90,30,70,40,80,60,20 , 110 , 250, 320 , 2 , 7};
int length = sizeof(arr) / sizeof(int);
SqList *sl;
sl = (SqList*)malloc(sizeof(SqList));
sl->lenght = length - 1;
for (int i = 1; i < length; i++)
{
sl->r[i] = arr[i];
}
std::cout << "排序前结果:\n";
Print(sl);
QuickSort(sl);
std::cout << "输出快速排序后的结果:\n";
Print(sl);
}
void Print(SqList* L)
{
for (int i = 1; i <= L->lenght; i++)
{
std::cout << L->r[i] << " ";
}
std::cout << std::endl;
}
void swap(SqList *L, int i, int j)
{
int temp = L->r[i];
L->r[i] = L->r[j];
L->r[j] = temp;
}
int Partion(SqList* L, int low, int high)
{
int privotkey;
int m = low + (int)((high - low) * 0.5);
if (L->r[low] > L->r[high])
{
swap(L, low, high);
}
if (L->r[m] > L->r[high])
{
swap(L, high, m);
}
if (L->r[m] > L->r[low])
{
swap(L, m, low);
}
privotkey = L->r[low];
L->r[0] = privotkey;
while (low < high)
{
while (low < high && L->r[high] >= privotkey)
high--;
L->r[low] = L->r[high];
while (low < high && L->r[low] <= privotkey)
low++;
L->r[high] = L->r[low];
}
L->r[low] = L->r[0];
return low;//返回枢轴所在的位置
}
void QSort(SqList* T, int low, int hight)
{
int pivot;
if (low < hight)
{
pivot = Partion(T, low, hight);
QSort(T, low, pivot - 1);
QSort(T, pivot + 1, hight);
}
}
void QuickSort(SqList* L)
{
QSort(L, 1, L->lenght);
}
快速排序
最新推荐文章于 2023-07-12 10:59:32 发布