#include<stdio.h>
#include<iostream>
using namespace std;
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
#define ElemType int
typedef struct{
ElemType *elem;
int length;
int listsize;
}SqList;
//打印
void PrintL(SqList &L);
//建顺序表
void InitList_Sq(SqList &L)
{
L.elem = (ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType));
if (!L.elem) cout << "存储分配失败!" << endl;
L.length = 0;
L.listsize = LIST_INIT_SIZE;
}
//在第i位置插入元素e
void ListInsert_Sq(SqList &L, int i, ElemType e)
{
int *newbase;
if (i<1 || i>L.length + 1) cout << "位置错误!" << endl;
if (L.length >= L.listsize)
{
newbase = (ElemType *)realloc(L.elem, (L.listsize + LISTINCREMENT)*sizeof(ElemType));
if (!newbase) cout << "重新分配地址错误!" << endl;
L.elem = newbase;
L.listsize += LISTINCREMENT;
}
int *p, *q;
q = &(L.elem[i - 1]);
for (p = &(L.elem[L.length - 1]); p >= q; --p) //将第i位置及其以后的元素后移一个位置
*(p + 1) = *p;
*q = e;
++L.length;
}
//快速排序(冒泡排序)
void QSort(SqList &L, int low, int high)
{
int key; //枢轴关键字
int t; //调换元素临时变量
int first = low, last = high; //first,high定位首位元素变量,用于递归参数
key = L.elem[low];
while (low < high){
while (low < high && L.elem[high] >= key) --high; //满足条件,high逐个前移
t = L.elem[low]; //调换low和high对应元素
L.elem[low] = L.elem[high];
L.elem[high] = t;
//下面一行用于输出当前low和high的位置,以及当前排序结果,可与此次排序前做对比
//cout << "--low=" << low << " high=" << high << ": "; PrintL(L); //向后排较大的
while (low < high && L.elem[low] <= key) ++low; //满足条件,low逐个后移
t = L.elem[low];
L.elem[low] = L.elem[high];
L.elem[high] = t;
//下面一行用于输出当前low和high的位置,以及当前排序结果,可与此次排序前做对比
//cout << "==low=" << low << " high=" << high << ": "; PrintL(L); //向前排较小的
}
if (first<low - 1)QSort(L, first, low - 1); //快速排序前一段
if (low + 1<last)QSort(L, low + 1, last); //快速排序后一段
}
//打印
void PrintL(SqList &L)
{
int i = 0;
while (i < L.length)
{
cout << L.elem[i] << " ";
i++;
}
cout << endl;
}
void main()
{
SqList L;
//创建顺序表La并插入数据
InitList_Sq(L);
ListInsert_Sq(L, 1, 56); ListInsert_Sq(L, 2, 25);
ListInsert_Sq(L, 3, 98); ListInsert_Sq(L, 4, 12);
ListInsert_Sq(L, 5, 78); ListInsert_Sq(L, 6, 88);
ListInsert_Sq(L, 7, 39); ListInsert_Sq(L, 8, 95);
ListInsert_Sq(L, 9, 91); ListInsert_Sq(L, 10, 86);
ListInsert_Sq(L, 11, 80); ListInsert_Sq(L, 12, 99);
cout << "L 的元素为: ";
PrintL(L);
QSort(L, 0, 11);
cout << "快速排序后: ";
PrintL(L);
//防止运行结果一闪而过
system("pause");
}
c++实现快速排序
最新推荐文章于 2021-05-21 00:56:15 发布