快速排序手撕简洁版

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/davidsher_zhou/article/details/82314154

一趟划分
挖坑法

int Partition(int a[], int low, int high)
{
	int pivot = a[low];    //以低位为基准
	while (low < high)
	{
		while (low < high && a[high] >= pivot)
			--high;
		a[low] = a[high];
		while (low < high && a[low] <= pivot)
			++low;
		a[high] = a[low];
	}
	a[low] = pivot;
	return low;
}

左右指针法

int Partition1(int a[], int low, int high)
{
	int &pivot = a[low];    //以低位为基准,若想以高位为基准,
	while (low < high)        //只需要交换(1)(2)两个while循环先后顺序
	{
		while (low < high && a[high] >= pivot)    //(1)
			--high;
		while (low < high && a[low] <= pivot)    //(2)
			++low;
		
		swap(a[low], a[high]);
	}
	swap(a[low], pivot);
	return low;
}

前后指针法

int Partition2(int a[], int low, int high)
{
	int pivot = a[high]; // 以高位为基准
	int cur = low;
	int pre = cur - 1;

	while (cur < high)
	{
		while (a[cur] < pivot && ++pre != cur)
			swap(a[cur], a[pre]);
		++cur;
	}
	swap(a[++pre], a[high]);

	return pre;
}
 

递归实现

void quickSort(int a[], int low, int high)
{
	if (low < high)
	{
		int pivotPos = Partition2(a, low, high);
		quickSort(a, low, pivotPos - 1);
		quickSort(a, pivotPos + 1, high);
	}
}

非递归实现

//基本思想:边界入栈,一次划分
void quickSort1(int a[], int low, int high)
{
	assert(a);

	stack<int> s;
	s.push(low);
	s.push(high);

	while (!s.empty())
	{
		int low = s.top();
		s.pop();
		int high = s.top();
		s.pop();

		int pivotPos = Partition(a, low, high);

		if (pivotPos - 1 > low)
		{
			s.push(low);
			s.push(pivotPos - 1);
		}

		if (pivotPos + 1 < high)
		{
			s.push(pivotPos + 1);
			s.push(high);
		}
	}
}

猜你喜欢

转载自blog.csdn.net/davidsher_zhou/article/details/82314154
今日推荐