归并算法
#include<stdio.h>
#include <stdlib.h>
#include<math.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<vector>
using namespace std;
const int maxn = 100010;
void merge(int a[], int l1, int r1, int l2, int r2) {
int temp[maxn];
int index = 0;
int i = l1, j = l2;
while (i <= r1 && j <= r2) {
if (a[i] <= a[j]) {
temp[index++] = a[i++];
}
else {
temp[index++] = a[j++];
}
}
if (i == r1 + 1) {
while (j <= r2) {
temp[index++] = a[j++];
}
}
if (j == r2 + 1) {
while (i <= r1) {
temp[index++] = a[i++];
}
}
for (int i = 0; i < index; i++) {
a[l1 + i] = temp[i];
}
}
void printArray(int a[], int n) {
for (int i = 0; i < n; i++) {
printf("%d", a[i]);
if (i != n - 1) {
printf(" ");
}
}
printf("\n");
}
void mergeSort(int a[], int n) {
for (int step = 1; step <= n; step *= 2) {
for (int i = 0; i < n; i += (step * 2)) {//对每一组
int second_array_first = i + step;
if (second_array_first < n) {
merge(a, i, second_array_first - 1, second_array_first, min(i + 2 * step - 1, n-1));
}
}
}
}
int main() {
int a[] = { 1,3,2,4,4,2 };
mergeSort(a, 6);
printArray(a,6);
}
找素数
const int maxn = 10000001;
int prime[maxn], pnum = 0;
bool p[maxn] = { true };
void find_prime() {
memset(p, true, sizeof(p));
for (int i = 2; i < maxn; i++) {
if (p[i] == true) {
prime[pnum++] = i;
for (int j = i * 2; j < maxn; j += i) {
p[j] = false;
}
}
/*if (pnum > n)
break;*/
}
}