コード例
#include<stdio.h>
#include<stdlib.h>
#define list_size 100
typedef struct {
int* elem;
int length;
int listsize;
}sqlist;
bool initializer_list(sqlist& L)//建表初始化
{
L.elem = (int*)malloc(sizeof(int));
if (!L.elem)
{
return 0;
}
L.length = 0;
L.listsize = list_size;
return 0;
}
bool create_sqlist(sqlist &L,int n)//创建表
{
int i;
L.elem = (int*)malloc(sizeof(int) * list_size);
if (!L.elem)
{
return 0;
}
else
{
printf("请输入各个元素:\n");
for (i =1; i <=n; i++)
{
scanf_s("%d", &L.elem[i]);
L.length++;
}
}
return 0;
}
void print_sqlist(sqlist L)//输出表
{
printf("排序后的线性表为:\n");
for (int i = 1; i <= L.length; i++)
{
printf("%d ", L.elem[i]);
}
}
int Partition(sqlist& L, int low, int high)//进行一次快速排序
{
int pivotkey;
L.elem[0] = L.elem[low];//把表的第一个元素作为基准元素
pivotkey = L.elem[0];
while (low < high)
{
while (low < high && L.elem[high] >= pivotkey)
{
high--;
}
L.elem[low] = L.elem[high];//把比基准元素大的元素移到low的位置
while (low < high && L.elem[low] <= pivotkey)
{
low++;
}
L.elem[high]= L.elem[low];//把比基准元素小的元素移到high的位置
}
L.elem[low] = L.elem[0];//基准元素归位
return low;
}
//排序后基准元素前的元素都比基准元素小,基准元素后的元素都比基准元素大
void qsort(sqlist& L, int low, int high)//运用递归对整个表进行快速排序
{
int pivotloc;
if (low < high)
{
pivotloc = Partition(L, low, high);
qsort(L, low, pivotloc - 1);
qsort(L, pivotloc+1, high);
}
}
int main()
{
int n;
sqlist L;
initializer_list(L);
printf("请输入要输入的有序表元素个数:\n");
scanf_s("%d", &n);
create_sqlist(L,n);
qsort(L, 1, L.length);
print_sqlist(L);
}
サンプル出力