1. 冒泡排序
#include<iostream>
using namespace std;
#define MAXSIZE 20
typedef struct {
int key;
char* otherinfo;
}ElemType;
typedef struct {
ElemType* r;
int length;
}SqList;
void BubbleSort(SqList& L)
{
int m, flag=1;
ElemType t;
m = L.length - 1;
while ((m > 0) && flag == 1)
{
flag = 0;
for (int j = 1; j <= m; j++)
{
if (L.r[j].key > L.r[j + 1].key)
{
flag = 1;
t = L.r[j];
L.r[j] = L.r[j + 1];
L.r[j + 1] = t;
}
}
m--;
}
}
void Create_Sq(SqList& L)
{
int n;
cout << "请输入数据个数,不超过" << MAXSIZE << "个" << endl;
cin >> n;
while (n > MAXSIZE)
{
cout << "个数超过上限,不能超过" << MAXSIZE << ",请重新输入" << endl;
cin >> n;
}
cout << "请输入待排序的数据:" << endl;
for (int i = 1; i <= n; i++)
{
cin >> L.r[i].key;
L.length++;
}
}
void show(SqList L)
{
for (int i = 1; i <= L.length; i++)
{
cout << L.r[i].key << " ";
}
cout << endl;
}
int main()
{
SqList L;
L.r = new ElemType[MAXSIZE + 1];
L.length = 0;
Create_Sq(L);
BubbleSort(L);
cout << "排序后的结果为:";
show(L);
return 0;
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/6486a5fcb63f49ac85baee4669704631.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBARkcu,size_20,color_FFFFFF,t_70,g_se,x_16)
![在这里插入图片描述](https://img-blog.csdnimg.cn/ea4a0c65ac054c648e4772c2192f9306.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBARkcu,size_20,color_FFFFFF,t_70,g_se,x_16)
2.快速排序
#include<iostream>
using namespace std;
#define MAXSIZE 20
typedef struct {
int key;
char* otherinfo;
}ElemType;
typedef struct {
ElemType* r;
int length;
}SqList;
int Partition(SqList& L, int low, int high)
{
int pivotkey;
L.r[0] = L.r[low];
pivotkey = L.r[low].key;
while (low < high)
{
while (low < high && L.r[high].key >= pivotkey)
{
high--;
}
L.r[low] = L.r[high];
while (low < high && L.r[low].key <= pivotkey)
{
low++;
}
L.r[high] = L.r[low];
}
L.r[low] = L.r[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);
}
}
void QuickSort(SqList& L)
{
QSort(L, 1, L.length);
}
void Create_Sq(SqList& L)
{
int n;
cout << "请输入数据个数,不超过" << MAXSIZE << "个" << endl;
cin >> n;
while (n > MAXSIZE)
{
cout << "个数超过上限,不能超过" << MAXSIZE << ",请重新输入" << endl;
cin >> n;
}
cout << "请输入待排序的数据:" << endl;
for (int i = 1; i <= n; i++)
{
cin >> L.r[i].key;
L.length++;
}
}
void show(SqList L)
{
for (int i = 1; i <= L.length; i++)
{
cout << L.r[i].key << " ";
}
cout << endl;
}
int main()
{
SqList L;
L.r = new ElemType[MAXSIZE + 1];
L.length = 0;
Create_Sq(L);
QuickSort(L);
cout << "排序后的结果为:";
show(L);
return 0;
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/0ef253a782ed4a5ab8fadbd8f82f6dee.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBARkcu,size_20,color_FFFFFF,t_70,g_se,x_16)
![在这里插入图片描述](https://img-blog.csdnimg.cn/4df77cc9442f4d2c99658f8f128bc975.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBARkcu,size_20,color_FFFFFF,t_70,g_se,x_16)