以前写过一篇, 分析的非常详细.
排序算法(1) 快速排序 C++实现
引用了一个动图, 直观地感受快速排序过程.
演示的算法和实现稍有区别, 请仔细感受一下.
实现
class Solution {
public:
/**
* @param A an integer array
* @return void
*/
void sortIntegers2(vector<int>& A) {
// Write your code here
if (A.size() == 0)
{
return;
}
quicksort(A, 0, A.size() - 1);
}
private:
void quicksort(std::vector<int>& nums, int start, int end)
{
if (start >= end) return;
int mid = partition(nums, start, end);
if (mid - 1 > start)
{
quicksort(nums, start, mid - 1);
}
if (mid + 1 < end)
{
quicksort(nums, mid + 1, end);
}
}
int partition(std::vector<int>& nums, int start, int end)
{
int pivot = nums[start];
int left = start;
for (int i = start + 1; i <= end; ++i)
{
if (nums[i] < pivot)
{
left++;
swap(nums, left, i);
}
}
swap(nums, left, start);
return left;
}
int swap(std::vector<int>& nums, int i, int j)
{
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
};
网友评论