1、冒泡排序
#include <iostream>
typedef int KeyType;
typedef struct ElemType
{
KeyType key;
};
#define MAXSIZE 100
typedef struct SqList
{
ElemType arr[MAXSIZE + 1];
int len;
};
//冒泡排序
void BubbleSort(SqList & L);
//输出顺序表
void Show(SqList L);
int main()
{
SqList L;
L.arr[1].key = 3;
L.arr[2].key = 5;
L.arr[3].key = 10;
L.arr[4].key = 16;
L.arr[5].key = 7;
L.arr[6].key = 32;
L.arr[7].key = 83;
L.arr[8].key = 23;
L.arr[9].key = 54;
L.arr[10].key = 29;
L.arr[11].key = 96;
L.len = 11;
Show(L);
//测试
std::cout << "****Test****\n";
BubbleSort(L);
Show(L);
std::cout << "****End****\n";
return 0;
}
//冒泡排序
void BubbleSort(SqList & L)
{
int i, j;
for (i = 1; i < L.len; ++i)
for (j = 1; j <= L.len - i; ++j)
if (L.arr[j].key > L.arr[j + 1].key)
L.arr[0].key = L.arr[j].key, L.arr[j].key = L.arr[j + 1].key, L.arr[j + 1].key = L.arr[0].key;
}
//输出顺序表
void Show(SqList L)
{
for (int i = 1; i <= L.len; ++i)
std::cout << L.arr[i].key << '\t';
std::cout << '\n';
}
2、快速排序
#include <iostream>
typedef int KeyType;
typedef struct ElemType
{
KeyType key;
};
#define MAXSIZE 100
typedef struct SqList
{
ElemType arr[MAXSIZE + 1];
int len;
};
//分割表为左右子表
int Partition(SqList & L, int low, int high);
//快速排序
void Qsort(SqList & L, int low, int high);
//输出顺序表
void Show(SqList L);
int main()
{
SqList L;
L.arr[1].key = 3;
L.arr[2].key = 5;
L.arr[3].key = 10;
L.arr[4].key = 16;
L.arr[5].key = 7;
L.arr[6].key = 32;
L.arr[7].key = 83;
L.arr[8].key = 23;
L.arr[9].key = 54;
L.arr[10].key = 29;
L.arr[11].key = 96;
L.len = 11;
Show(L);
//测试
std::cout << "****Test****\n";
Qsort(L, 1, L.len);
Show(L);
std::cout << "****End****\n";
return 0;
}
//分割表为左右子表
int Partition(SqList & L, int low, int high)
{
//1、取第一个元素为中心点, 存入哨兵位置
L.arr[0].key = L.arr[low].key;
//2、遍历剩余所有元素与中心点比较, <中心点, 往前移; >=中心点, 往后移
while (low < high)
{
//从后-前找1个<中心点的元素存入low
while ((low < high) && (L.arr[high].key >= L.arr[0].key))
--high;
L.arr[low].key = L.arr[high].key;
//从前-后找1个>=中心点的元素存入high
while ((low < high) && (L.arr[low].key <= L.arr[0].key))
++low;
L.arr[high].key = L.arr[low].key;
}
//遍历完成low == high, 把中心点元素存入low, 并返回中心点的位置
L.arr[low].key = L.arr[0].key;
return low;
}
//快速排序
void Qsort(SqList & L, int low, int high)
{
//表中有元素
if (low < high)
{
//1、分割表为左子表、右子表
int pivotloc = Partition(L, low, high);
//2、对左子表进行快速排序
Qsort(L, low, pivotloc - 1);
//3、对右子表进行快速排序
Qsort(L, pivotloc + 1, high);
}
}
//输出顺序表
void Show(SqList L)
{
for (int i = 1; i <= L.len; ++i)
std::cout << L.arr[i].key << '\t';
std::cout << '\n';
}