【排序算法实现】快速排序、归并排序和堆排序

快速排序

int partition_(vector<int>& nums, int left, int right) {
    int key = nums[left];
    int st = left, ed = right;
    while(st < ed) {
        while(nums[ed] > key) ed--;
        if (st < ed) swap(nums[st++], nums[ed]);
        while(nums[st] < key) st++;
        if (st < ed) swap(nums[ed--], nums[st]);
    }
    nums[st] = key;
    return st;
}

void quickSort(vector<int>& nums, int left, int right) {
    if (left < right) {
        int pivot = partition_(nums, left, right);
        quickSort(nums, left, pivot-1);
        quickSort(nums, pivot+1, right);
    }
    return;
}

归并排序

void mergeArr(vector<int>& nums, int left, int mid, int right, vector<int>& tmp) {
    int i = left, j = mid + 1;
    int n = mid, m = right;
    int k = 0;
    while (i <= n && j <= m) {
        if (nums[i] < nums[j]) tmp[k++] = nums[i++];
        else tmp[k++] = nums[j++];
    }
    while (i <= n) tmp[k++] = nums[i++];
    while (j <= m) tmp[k++] = nums[j++];
    for (i=0; i<k; ++i) nums[left++] = tmp[i];
    return;
}

void mergeSort(vector<int>& nums, int left, int right, vector<int>& tmp) {
    if (left < right) {
        int mid = left + (right - left) / 2;
        mergeSort(nums, left, mid, tmp);
        mergeSort(nums, mid+1, right, tmp);
        mergeArr(nums, left, mid, right, tmp);
    }
    return;
}

堆排序

void adjust_(vector<int>& nums, int len, int index) {
    int left = index * 2 + 1;
    int right = index * 2 + 2;
    int minIndex = index;
    if (left < len && nums[minIndex] < nums[left]) minIndex = left;
    if (right < len && nums[minIndex] < nums[right]) minIndex = right;
    if (index != minIndex) {
        swap(nums[index], nums[minIndex]);
        adjust_(nums, len, minIndex);
    }
    return;
}

void heapSort_(vector<int>& nums, int len) {
    for (int i=len/2-1; i>=0; --i) {
        adjust_(nums, len, i);
    }
    for (int i=len-1; i>=1; --i) {
        swap(nums[i], nums[0]);
        adjust_(nums, i, 0);
    }
    return;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值