数组算法练习
从最后一项往前走,每次从 0..i 选一项和 a[i] 交换。为什么 rand() % (i + 1) 落在 0..i?因为余数一定比除数小。下面是练习写法…
Fisher–Yates 洗牌
从最后一项往前走,每次从 0..i 选一项和 a[i] 交换。为什么 rand() % (i + 1) 落在 0..i?因为余数一定比除数小。下面是练习写法,直接取模可能有偏差。随机种子通常在程序开始时用 srand 设置一次。
#include <stdlib.h>
void shuffle(int a[], int count) {
for (int i = count - 1; i > 0; i--) {
int j = rand() % (i + 1);
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
Lomuto 快排
快排用分治。这里取末尾元素作为基准,切分结束后基准归位,左右递归都可以跳过它。
int Partition(int a[],int low,int high) {
int partition=low;
int pivot=a[high];
for (int i=low;i<high;i++) {
if (a[i]<=pivot) {
int temp=a[i];
a[i]=a[partition];
a[partition]=temp;
partition++;
}
}
int temp=a[partition];
a[partition]=a[high];
a[high]=temp;
return partition;
}
void QuickSort(int a[],int low,int high) {
if (low>=high) return;
int partition=Partition(a,low,high);
QuickSort(a,low,partition-1);
QuickSort(a,partition+1,high);
}
partition 在这里记的是切分位置。每轮递归的起点可能不同,扫描从 low 开始。扫描只到 i < high,末尾的基准元素留到循环结束后交换。
交换函数与宏
固定类型的交换可以直接传指针。通用的按字节交换可以用 memcpy 和临时缓冲区,下面的 Swap 要求两个区域不重叠,分配失败时不会交换。
#include <stdlib.h>
#include <string.h>
void SwapInt(int *a,int *b) {
int temp=*a;
*a=*b;
*b=temp;
}
void Swap(void *a,void *b,size_t size) {
void *temp=malloc(size);
if (temp) {
memcpy(temp,a,size);
memcpy(a,b,size);
memcpy(b,temp,size);
free(temp);
}
}
多语句宏可以用 do { ... } while (0) 包起来,调用处就能像一条语句一样加分号。typeof 可见于 GNU C,也已进入 C23。
#define SWAP_PLUS(a, b) do { typeof(a) temp = (a); (a) = (b); (b) = temp; } while (0)
Hoare 快排
从两头扫描,遇到站错边的元素就交换。Hoare 切分返回的是区间边界,因此递归使用 [low, boundary] 和 [boundary + 1, high]。两元素逆序的 [2, 1] 很适合检查边界是否收缩。
int PartitionHoare(int a[], int low, int high) {
int pivot = a[low + (high - low) / 2];
int left = low;
int right = high;
for (;;) {
while (a[left] < pivot) left++;
while (a[right] > pivot) right--;
if (left >= right) return right;
int temp = a[left];
a[left++] = a[right];
a[right--] = temp;
}
}
void QuickSortHoare(int a[], int low, int high) {
if (low >= high) return;
int boundary = PartitionHoare(a, low, high);
QuickSortHoare(a, low, boundary);
QuickSortHoare(a, boundary + 1, high);
}
在星图中查看 ↗三川既白 · 33