Quick Sort
To sort the array subscript p from among a set of data to r, we have to select any one of data between p r as the Pivot (partition points). We traverse the data between p r, smaller than the pivot into the left will be greater than the pivot into the right into the middle of the pivot. After this step, the data between the array p r was divided into three portions, between the front p q-1 is less than the pivot, the middle pivot, the latter is between q + 1 to r greater than the pivot. The partition, recursive processing idea, we can use recursive data sorted from the p and subscript index between the q-1 from q + 1 to the data between the r, the interval until reduced to 1, it means that all of the the data are ordered.
The optimal time complexity of O (nlogn)
average time complexity of O (nlogn)
worst time complexity of O (n ^ 2), assuming that the array has been ordered, but we have not yet been set up at the end of the pivot value .
As compared to a merge sort advantages: his time complexity is O (1). So even if it may be degraded worst time complexity to O (n ^ 2), people still tend to use algorithms, but now people have developed a number of measures to try to avoid its degradation to O (n ^ 2)
Code:
#include <iostream>
#include <vector>
using namespace std;
int getPartition(vector<int>& nums,int head,int rear)
{
int value=nums[rear];
int i=head,j=0,temp=0;
for(j=head;j<rear;j++)
{
if(nums[j]<value)
{
temp=nums[j];
nums[j]=nums[i];
nums[i]=temp;
i++;
}
}
temp=nums[rear];
nums[rear]=nums[i];
nums[i]=temp;
return i;
}
void quickSort(vector<int>& nums,int head,int rear)
{
if(head>=rear)
{
return;
}
else
{
int loc=getPartition(nums,head,rear);
quickSort(nums,head,loc-1); //注意要是-1而不能这里是loc下一行是加1
quickSort(nums,loc+1,rear);
}
}
int main()
{
vector<int> test;
test.push_back(5);
test.push_back(13);
test.push_back(13);
test.push_back(7);
test.push_back(19);
test.push_back(12);
test.push_back(4);
test.push_back(6);
test.push_back(1);
test.push_back(2);
test.push_back(3);
test.push_back(8);
for(int i=0;i<test.size();i++)
{
cout<<test[i]<<" ";
}
cout<<endl;
int qsize=test.size();
quickSort(test,0,qsize-1);
for(int i=0;i<test.size();i++)
{
cout<<test[i]<<" ";
}
return 0;
}