voidmerge(int q[], int l, int r) { if (l >= r) return; int mid = l + r >> 1; merge(q, l, mid);//一开始就要递归 merge(q, mid + 1, r); for (int i = l; i <= r; i++)//把q数组l到r的内容复制到p p[i] = q[i]; int i = l, j = mid + 1, x = l; while (i <= mid && j <= r)//进行合并,循环条件是两部分没有到端点 { if (p[i] < p[j])//把的那个放入q中 q[x++] = p[i++]; else q[x++] = p[j++]; } if (i <= mid)//如果一方没到终点则直接放到q后面 { while (i <= mid) q[x++] = p[i++]; } else while (j <= r) q[x++] = p[j++]; }
inthalf(int q[], int l, int r, int x) { //找x int mid = l + r >> 1; while (l < r) { mid = l + r + 1 >> 1; if (q[mid] <= x) l = mid; else r = mid - 1; } cout << r; }
2.从右往左逼近
1 2 3 4 5 6 7 8 9 10 11 12 13
inthalf(int q[], int l, int r, int x) { //找x int mid ; while (l < r) { mid = l + r >> 1; if (q[mid] >=x) r = mid; else l = mid+1; } cout << l; }