【快速算法排序的步骤】
快速排序:
1.将序列重排后分成左右两部分,保证两部分有一部分的所有元素都比另一部分的所有元素要小。
有许多不同版本的快速排序以不同的方式选择枢轴。
1.1 总是选择第一个元素作为枢轴。
1.2 总是选择最后一个元素作为枢纽(下面实现)
1.3 选择一个随机元素作为枢轴。
1.4 挑选中位数为枢纽。
当每一趟选择当前所有子序列中的一个关键字(通常是第一个)作为枢轴,将子序列中比枢轴小的移到枢轴前边,比枢轴大的移到枢轴后边。
2.递归求解,将这两部分的元素分别按顺序排列。
3.不用将这两部分合并,因为已经有序。
【快速算法排序简单的两个应用】
1.给出7个整数,10,80,30,90,40,50,70,请用快速排序的方法coding出来。
【coding】
#include<iostream> #include<stdlib.h> using namespace std; #define f 7 void swap(int &c,int &b) { c=c + b; b = c- b; c = c - b; }//这个地方有个坑,传的是形参,所以如果这两个数是同一个数,两个数都会计算成0
void swap(int &a,int &b) { int temp; temp = a; a = b; b = temp; }
int partition(int *a,int m,int n)
{
int x = a[n - 1];
int k = m-1;
for (int i = m; i < n-1; i++)
{
if (a[i] > x)
{
k++;
swap(a[i], a[k]);
}
}
swap(a[k+1],a[n-1]);
return k + 1;
}
void quicksort(int *a,int m,int n)
{
int q=0;
if (m < n-1)
{
q = partition(a, m, n);
quicksort(a,m,q);
quicksort(a,q+1,n);
}
}
int main()
{
int a[f] = { 10,80,30,90,40,50,70 };
quicksort(a,0,f);
for (int i = 0; i < f; i++)
{
cout << a[i] << " ";
}
system("pause");
}
2. Sort Colors:
Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
(https://leetcode.com/problems/sort-colors/description/)
【coding】
class Solution {
public:
void sortColors(vector<int>& nums) {
int i = 0, j = i, k = nums.size() - 1;
while(j <= k){
if(nums[j] == 0) swap(nums[i++], nums[j++]);
else if(nums[j] == 1) j++;
else swap(nums[k--], nums[j]);
}
}
};
另一种方法
class Solution {
public:
void swap(int &num1,int &num2)
{
int temp;
temp =num1;
num1 = num2;
num2 = temp;
}
int partition(vector<int> &nums,int m,int n)
{
int x=nums[n-1];
int q=m-1;
for(int i=m;i<n-1;i++)
{
if(nums[i]<=x)
{
q++;
swap(nums[q],nums[i]);
}
}
swap(nums[q+1],nums[n-1]);
return q+1;
}
void quicksort(vector<int> &nums,int m,int n)
{
int q=0;
if(m<n-1)
{
q=partition(nums,m,n);
quicksort(nums,m,q);
quicksort(nums,q+1,n);
}
}
void sortColors(vector<int>& nums) {
int size=nums.size();
quicksort(nums,0,size);
}
};