STL 中几个简单的数值算法实现

复习《STL源码剖析》,先把几个简单的算法自己实现一下。参数没有用迭代器,直接用整型数组。
#include #include /* 应用于有序区间,判断 b 中的元素是否全部被 a 包含。默认为升序,如果为降序,改变比较符号即可 */ bool includes(int* a, size_t al, int *b, size_t bl) { size_t i = 0, j = 0; while (i < al && j < bl) { if (a[i] > b[j]) return false; else if (a[i] < b[j]) i++; else i++, j++; } return j == bl; } /* 将序列a中,被pred条件判断为true的放在前段,false的放在后段 */ int* partition(int* a, size_t begin, size_t end, Predicate pred) { size_t i = begin, j = end; while (true) { while (true) { if (i == j) return i; else if (pred(a[i])) i++; else break; } while (true) { if (i == j) return i; else if (!pred(a[j])) j--; else break; } // swap a[i] = a[i] + a[j]; a[j] = a[i] - a[j]; a[i] = a[i] - a[j]; i++; } } /* 整体交换a[begin, middle-1] 和 a[middle, end-1] */ inline void rotate(int* a, size_t begin, size_t middle, size_t end) { for (size_t i = middle; ; ) { // swap int temp = a[i]; a[i] = a[begin]; a[begin] = temp; i++, begin++; if (begin == middle) { if (i == end) return; middle = i; } else if (i == end) i = middle; } } /* 在a[b1, e1-1]中查找b[b2, e2-1]的第一次出现的下标,失败返回e1 */ int search(int* a, size_t b1, size_t e1, int* b, size_t b2, size_t e2) { size_t d1 = e1 - b1; size_t d2 = e2 - b2; if (d1 < d2) return e1; size_t i = b1, j = b2; while (j != e2) { if (a[i] == b[j]) i++, j++; else if (d1 == d2) return e1; else { i = ++b1; j = b2; d1--; } } return b1; } int main() { int a[] = {1, 2, 3, 4, 5}; int b[] = {1, 3, 5}; if (includes(a, sizeof(a) / sizeof(int), b, sizeof(b) / sizeof(int))) printf("yes/n"); int c[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; rotate(c, 0, (sizeof(c) / sizeof(int)) / 2, sizeof(c) / sizeof(int)); for (size_t i = 0; i < sizeof(c) / sizeof(int); i++) printf("%d ", c[i]); printf("/n"); int d[] = {1, 2, 3, 4, 5}; int e[] = {7, 5}; printf("%d/n", search(d, 0, sizeof(d) / sizeof(int), e, 0, sizeof(e) / sizeof(int))); return 0; }

你可能感兴趣的:(数据结构/算法,算法,search,c)