三路快排板子

还是觉得别人的快排写得太丑了

双路快排

void qsort2(int L, int R) {
    if(L >= R) {
        return ;
    }
/*    //随机取值
    int index = rand() % (R - L + 1) + L;
    swap(nums[L], nums[index]);*/
    int key = nums[L];
    int i = L, j = R;
    while(i < j) {
        while(i < j && nums[j] >= key) {
            j--;
        }
        nums[i] = nums[j];
        while(i < j && nums[i] <= key) {
            i++;
        }
        nums[j] = nums[i];
    }
    nums[i] = key;
    qsort2(L, i - 1);
    qsort2(i + 1, R);
}

三路快排

图示

按i走,小于key的丢到前面去,大于的丢到后面去

void qsort3(int *nums, int L, int R) {
    if(L >= R) {
        return ;
    }
    int index = rand() % (R - L + 1) + L;//随机种子
    swap(nums[index], nums[L]);
    int key = nums[L];
    int lt = L, i = L + 1, j = R;
    while(i <= j) {
        if(nums[i] < key) {
            swap(nums[i++], nums[lt++]);
        } else if(nums[i] > key){
            swap(nums[i], nums[j--]);
        }
        while(i <= j && nums[i] == key) {
            i++;//while一定要在if后,否则当所有数相同时,i越界后还会进入if判断
        }
    }
    qsort3(nums, L, lt - 1);
    qsort3(nums, j + 1, R);
}

int main() {
    int n, l, r;
    while(cin >> n >> l >> r) {
 /*       多组输入
        输入三个数,数组长度 n,取值范围 [l, r]*/
        int nums[n];
        for(int i = 0;i < n;++i) {
            nums[i] = rand() % (r - l + 1) + l;
        }
        cout << " !! " << endl;
        for(int i = 0;i < n;++i) {
            cout << nums[i] << " ";
        }
        cout << endl;
        qsort3(nums, 0, n - 1);
        for(int i = 0;i < n;++i) {
            cout << nums[i] << " ";
        }
        cout << " // " << endl;
    }
    return 0;
}
posted @ 2020-09-23 16:13  谁知道你啊啊啊  阅读(165)  评论(0编辑  收藏  举报