【算法】快速排序--C++源代码(VS2015)
2017-09-25 10:31
417 查看
#include <iostream>
#include <vector>
using namespace std;
void QuickSort(vector<int> &vec, int left, int right)
{
if (left > right)
{
return;
}
int first = left;
int last = right;
int key = vec[first];
while (first < last)
{
while(first < last && vec[last] >= key)
{
last--;
}
vec[first] = vec[last];
while (first < last && vec[first] < key)
{
first++;
}
vec[last] = vec[first];
}
vec[first] = key;
QuickSort(vec, left, first - 1);
QuickSort(vec, first+1, right);
}
void Print(vector<int> &vec)
{
cout << "vec[] = ";
for (vector<int>::iterator iter = vec.begin(); iter != vec.end(); iter++)
{
cout << *iter << " ";
}
cout << endl;
}
int main()
{
int arr[] = { 2,4,6,8,10,1,3,5,7,9 };
vector<int> vec(&arr[0], &arr[10]); // 将arr中的所有值赋值到vec中
QuickSort(vec, 0, vec.size() - 1);
Print(vec);
system("pause");
return 0;
}
#include <vector>
using namespace std;
void QuickSort(vector<int> &vec, int left, int right)
{
if (left > right)
{
return;
}
int first = left;
int last = right;
int key = vec[first];
while (first < last)
{
while(first < last && vec[last] >= key)
{
last--;
}
vec[first] = vec[last];
while (first < last && vec[first] < key)
{
first++;
}
vec[last] = vec[first];
}
vec[first] = key;
QuickSort(vec, left, first - 1);
QuickSort(vec, first+1, right);
}
void Print(vector<int> &vec)
{
cout << "vec[] = ";
for (vector<int>::iterator iter = vec.begin(); iter != vec.end(); iter++)
{
cout << *iter << " ";
}
cout << endl;
}
int main()
{
int arr[] = { 2,4,6,8,10,1,3,5,7,9 };
vector<int> vec(&arr[0], &arr[10]); // 将arr中的所有值赋值到vec中
QuickSort(vec, 0, vec.size() - 1);
Print(vec);
system("pause");
return 0;
}
相关文章推荐
- 【算法】斐波那契数列--C++源代码(VS2015)
- 【算法】Shell排序--C++源代码(VS2015)
- 【算法】分而治之(DivideAndConquer) -- C++源代码(VS2015)
- 【LeetNode2-1-9】Three sum closest--C++源代码(VS2015)
- 算法之道(二):快速排序—三路快排 vs 双基准
- 【LeetNode2-1-10】Four sum--C++源代码(VS2015)
- 图像处理之其他杂项(一)之MeanShift的目标跟踪算法opencv c++代码 VS2015+opencv3.2
- 本周算法:快速排序—三路快排 vs 双基准
- 数据结构与算法:C++实现快速排序
- 【LeetNode2-1-1】Remove duplicates from sorted array I--C++源代码(VS2015)
- 【设计】单例模式--C++源代码(VS2015)
- 【LeetNode2-1-2】Remove duplicates from sorted array II--C++源代码(VS2015)
- 采用 CAMSHIFT 算法快速跟踪和检测运动目标的 C/C++ 源代码
- 【设计】工厂模式--C++源代码(VS2015)
- 算法代码实现之快速排序,C/C++实现
- 【LeetNode2-1-4】Search in rotated sorted array II--C++源代码(VS2015)
- 【基础】随机数生成--C++源代码(VS2015)
- 【基础】简析浅拷贝与深拷贝--C++源代码(VS2015)
- 【LeetNode2-1-5】Median of two sorted arrays--C++源代码(VS2015)
- 【基础】大端小端(Big-endian&Little-endian)--C++源代码(VS2015)