以下是常见的几种随机化算法的C语言实例:
- 快速排序
#include<stdio.h>
#include<stdlib.h>
#define max_n 1000000
int pivot(int* arr, int left, int right) {
int p = left;
for(int i = left + 1; i <= right; ++i) {
if(arr[i] < arr[left]) {
++p;
int t = arr[i];
arr[i] = arr[p];
arr[p] = t;
}
}
int t = arr[p];
arr[p] = arr[left];
arr[left] = t;
return p;
}
void quick_sort(int* arr, int left, int right) {
if(left >= right) return;
int p = pivot(arr, left, right);
quick_sort(arr, left, p-1);
quick_sort(arr, p+1, right);
}
int main() {
int n;
scanf("%d", &n);
int arr[max_n];
for(int i = 0; i < n; ++i) {
scanf("%d", &arr[i]);
}
srand(19260817);//设置随机种子
for(int i = 0; i < 3; ++i) {
int p