快速排序

[###算法思想
1.分解:
在 R[low..high]中任选一个记录作为基准(Pivot),以此基准将当前无序区划分为左、右两个较小的子区间 R[low..pivotpos-1)和 R[pivotpos+1..high],并使左边子区间中所有记录的关键字均小于等于基准记录(不妨记为 pivot)的关键字 pivot.key,右边的子区间中所有记录的关键字均大于等于 pivot.key,而基准记录 pivot 则位于正确的位置(pivotpos)上,它无须参加后续的排序。

2.求解:
通过递归调用快速排序对左、右子区间 R[low..pivotpos-1]和R[pivotpos+1..high]快速排序。

3.组合:
因为当”求解”步骤中的两个递归调用结束时,其左、右两个子区间已有序。对快速排序而言,”组合”步骤无须做什么,可看作是空操作。

时间复杂度O(nlgn)

void quickSort(int arr[], int low, int high)
{
    int pivot;
    if (low < high)
    {
        pivot = partition(arr, low, high);
        quickSort(arr, low, pivot - 1);
        quickSort(arr, pivot + 1, high);
    }
}

int partition(int arr[], int low, int high)
{
    int temp;
    int x = arr[high];
    int i = low - 1;
    for (int j = low; i < high; ++j)
    {
        if (arr[j] <= x)
        {
            i += 1;
            temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
    }
    temp = arr[i + 1];
    arr[i + 1] = arr[high];
    arr[high] = temp;
    return i + 1;
}

int partition1(int arr[], int low, int high)
{
    int left = low;
    int right = high;
    int temp = arr[low];
    while(left < right) 
    {
        while(left < right && arr[right] >= temp)
        {
            --right;
        }
        if (left < right)
        {
            arr[left] = arr[right];
        }
        while(left < right && arr[left] <= temp)
        {
            ++left;
        }
        if (left < right)
        {
            arr[right] = arr[left];
        }
    }
    arr[left] = temp;
    return left;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值