Sorting
#define MAXN 1005
int num[MAXN]; //待排序数组
int n; //数组中元素个数
Insertion Sort
直接插入排序
//设置哨兵num[0], 为在查找插入位置的过程中避免数组下标越界
void InsertSort() {
int i, j;
for (i = 2; i <= n; i++)
if (num[i] < num[i - 1]) { //将num[i], 插入有序序列
num[0] = num[i]; //num[i]复制为哨兵
num[i] = num[i - 1];
for (j = i - 2; num[0] < num[j]; j--)
num[j + 1] = num[j]; //记录向后移动
num[j + 1] = num[0]; //插入到正确的位置
}
}
二分插入排序
void BinaryInsertSort() {
int i, j, low, high, mid;
for (i = 2; i <= n; i++) {
num[0] = num[i]; //num[i]复制为哨兵
low = 1; high = i - 1;
while (low <= high) {
mid = (low + high) / 2; //折半
if (num[0] < num[mid])
high = mid - 1; //插入点在低半区
else
low = mid + 1; //插入点在高半区
}
for (j = i - 1; j >= high + 1; j--)
num[j + 1] = num[j]; //记录后移
num[high + 1] = num[0]; //插入到正确的位置
}
Output();
}
Quick Sort
冒泡排序
void BubbleSort() { //一看就明白
int i, j;
for (i = 1; i <= n; i++)
for (j = 1; j <= n - i; j++)
if (num[j + 1] < num[j]) {
num[j + 1] = num[j + 1] + num[j];
num[j] = num[j + 1] - num[j];
num[j + 1] = num[j + 1] - num[j];
}
}
快速排序
int Partition(int low, int high) {
int pivokey = num[low]; //用子序列第一个元素作为枢轴记录
num[0] = num[low];
while (low < high) { //从序列两端交替向中间扫描
while (low < high && num[high] >= pivokey)
high--;
num[low] = num[high]; //将比枢轴记录小的记录移动到低端
while (low < high && num[low] <= pivokey)
low++;
num[high] = num[low]; //将比枢轴记录大的记录移动到高端
}
num[low] = num[0];
return low; //返回枢轴位置
}
void QuickSort(int low, int high) {
int pivotloc; //枢轴的位置
if (low < high) {
pivotloc = Partition(low, high); //将序列一分为二
QuickSort(low, pivotloc - 1); //对低子表递归排序
QuickSort(pivotloc + 1, high); //对高子表递归排序
}
}
Selection Sort
选择排序
void SelectSort() {
int i, j, tmp;
for (i = 1; i <= n; i++) {
tmp = i;
for (j = i + 1; j <= n; j++) //选择第i小的元素
if (num[j] < num[tmp])
tmp = j;
if (tmp != i) { //与第i个元素进行交换
num[tmp] = num[tmp] + num[i];
num[i] = num[tmp] - num[i];
num[tmp] = num[tmp] - num[i];
}
}
}
Counting Sort
计数排序
#define MAXNUM 1005
void CountSort() {
int i;
int cnt[MAXNUM] = { 0 }, ans[MAXN] = { 0 }; //建立计数数组大小是MAXNUM
for (i = 1; i <= n; i++) //记录每一个数字的个数
cnt[num[i]]++;
for (i = 1; i <= MAXNUM - 1; i++) //得到比当前数字小的数字小的个数
cnt[i] += cnt[i - 1];
for (i = 1; i <= n; i++)
ans[cnt[num[i]]] = num[i];
} //时间复杂度O(n + MAXNUM)