快速排序
步骤
- 确定分界点:q[l], q[(l+r)/2], q[r], 随机
- 调整区间
- 递归处理
void quick_sort(int q[], int l, int r)
{
if (l >= r) return; //递归结束条件
int i = l - 1, j = r + 1, x = q[l + r >> 1]; //定义i, j指针, 确定分界点x(一般取中间值)
while (i < j)
{
do i ++; while (q[i] < x);
do j --; while (q[j] > x);
if (i < j) swap(q[i], q[j]); //交换两值
}
quick_sort(q, l, j), quick_sort(q, j + 1, r);
}
归并排序
步骤
- 确定分界点 mid
- 递归排序left, right
- 归并---合二为一
void merge_sort(int q[], int l, int r)
{
if (l >= r) return;
int mid = l + r >> 1; //确定分界点
merge_sort(q, l, mid);
merge_sort(q, mid + 1, r);
int k = 0, i = l, j = mid + 1;
while (i <= mid && j <= r)
{
if (q[i] < q[j]) temp[k ++] = q[i ++];
else temp[k ++] = q[j ++];
}
while (i <= mid) temp[k ++] = q[i ++];
while (j <= r) temp[k ++] = q[j ++];
for (int i = l, j = 0; i <= r; i ++, j ++) q[i] = temp[j];
}
标签:sort,01,int,mid,while,---,算法,排序
From: https://www.cnblogs.com/hjy94wo/p/16612074.html