快速排序C++实现

这篇博客详细介绍了两种不同的快速排序算法实现方式:一是通过交换元素,二是通过赋值操作。每种方法都包含完整的C++代码实现,并且经过本地运行验证正确性。博客内容着重于算法的逻辑和递归过程,对于理解和实现快速排序具有指导意义。
摘要由CSDN通过智能技术生成

方式一 交换元素

#include <iostream>   
#include <string>  
#include<vector>
#include <algorithm>
using namespace std;


void quickSort(vector<int>& vec, int first, int end)
{
	if (first >= end)
		return;
	int temp = vec[first];
	int l = first;
	int r = end;
	while (l < r)
	{
		//while (l < r && vec[l] <= temp) l++; 错误
		while (l < r && vec[r] >= temp) r--; //先移动右边
		while (l < r && vec[l] <= temp) l++; //再移动左面
		if(l <  r)
			swap(vec[l], vec[r]);

	}
	swap(vec[first], vec[l]); //最终将基准数归位
	quickSort(vec, first, l - 1); //继续处理左边的,这是一个递归的过程
	quickSort(vec, l + 1, end); //继续处理右边的,这是一个递归的过程

}


int main()
{
	int arr[] = { 2,56,7,88,100,24,54,11 };
	vector<int> vec(arr, arr + sizeof(arr) / sizeof(int));
	for (int x : vec)
	{
		cout << x << " ";
	}
	cout << endl;

	quickSort(vec, 0, vec.size() - 1);
	
	for (int x : vec)
	{
		cout << x << " ";
	}

	system("pause");
	return 0;
}

经过本地运行,确保程序是准确的

 

方式二 赋值

#include <iostream>   
#include <string>  
#include<vector>
#include <algorithm>
using namespace std;


void quickSort(vector<int>& vec, int first, int end)
{
	if (first >= end)
		return;
	int temp = vec[first]; //temp存的就是基准数
	int l = first;
	int r = end;
	while (l < r)
	{
		//顺序很重要,要先从右边开始找
		while (l < r && vec[r] >= temp)
		{
			r--;
		}
		if(l < r)
		//vec[l+++] = vec[r];
			vec[l] = vec[r];
		//再找左边的
		while (l < r && vec[l] <= temp)
		{
			l++;
		}
		if(l < r)
		//vec[r--] = vec[l];
		vec[r] = vec[l];

	}
	//最终将基准数归位
	vec[l] = temp;
	quickSort(vec, first, l - 1); //继续处理左边的,这是一个递归的过程
	quickSort(vec, l + 1, end);//继续处理右边的,这是一个递归的过程


}


int main()
{
	int arr[] = { 2,56,7,88,100,24,54,11 };
	vector<int> vec(arr, arr + sizeof(arr) / sizeof(int));
	for (int x : vec)
	{
		cout << x << " ";
	}
	cout << endl;

	quickSort(vec, 0, vec.size() - 1);
	
	for (int x : vec)
	{
		cout << x << " ";
	}

	system("pause");
	return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值