随机快速排序与堆排序

1.快速排序(随机)

快速排序的时间复杂度为O\left ( nlogn \right ), 最坏情况为O\left ( n^{2} \right ),而随机快速排序的期望时间复杂度为O(n)。或许还要种个时间的种子 srand(unsigned(time(NULL))); 

 void quickSort(vector<int> &nums, int L, int R)
{
    if (L >= R) return;
    int id = rand() % (R - L + 1) + L;
    int pivot = nums[id];
    swap (nums[R], nums[id]);
    int low = L - 1, high = R;
    for(int i = L; i < high; )
    {
        if (nums[i] < pivot)
        {
            swap(nums[i], nums[low + 1]);
            ++low, ++i;
        }
        else if (nums[i] > pivot)
        {
            swap(nums[i], nums[high - 1]);
            --high;    //此时不用++i,因为从后面来的数还没看过
        }
        else 
            ++i;
    }
    swap(nums[R], nums[high]);
    quickSort(nums, L, low);
    quickSort(nums, high + 1, R);
}

2.堆排序

堆排序的核心代码就是heapAdjust部分,就是不断下调节点操作。

class Solution {
    
     void heapAdjust(vector<int> &nums, int parent, int len)
	{
		int id = parent;
		int L = id * 2 + 1, R = id * 2 + 2;
		if (L < len && nums[id] < nums[L])
			id = L;
		if (R < len && nums[id] < nums[R])
			id = R;
		if (id != parent)
		{
			swap(nums[id], nums[parent]);
			heapAdjust(nums, id, len);
		}
		return;
	}

	void heapSort(vector<int> &nums)
	{
		int len = nums.size();
		for (int i = len / 2 - 1; i >= 0; --i)	//build head
		{
			heapAdjust(nums, i, len);
		}
		
		for (int i = len - 1; i >= 0; --i)
		{
			swap(nums[i], nums[0]);
			heapAdjust(nums, 0, i);
		}
	}

};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值