基本思想:以数组中的某个元素作为枢纽,将小于枢纽的元素放到枢纽的左边,大于枢纽的元素都放到枢纽的右边,这个过程叫做划分,然后在枢纽左边的序列和枢纽右边的序列中不断划分,直到划分序列中只含有不多于一个元素,划分结束后,排序也就完成了,快速排序的关键就是划分。
源代码:
class Solution{
public:
void quickSort(vector<int> &nums, int start, int end){
if(start<end){
int pivotIndex=partition(nums, start, end);
quickSort(nums, start, pivotIndex-1);
quickSort(nums, pivotIndex+1, end);
}
}
int partition(vector<int> &nums, int start, int end){
int pivot=nums[start];
while(start<end){
while(start<end&&pivot<=nums[end])
end--;
swap(nums[start],nums[end]);
while(start<end&&pivot>=nums[start])
start++;
swap(nums[start],nums[end]);
}
return start;
}
void swap(int &a, int &b){
int temp;
temp=a;
a=b;
b=temp;
}
};
应用实例:求中位数 数组按从小到大的顺序排列,中位数即为处在中间的那个数。
class Solution {
public:
/**
* @param nums: A list of integers.
* @return: An integer denotes the middle number of the array.
*/
int median(vector<int> &nums) {
// write your code here
int length=nums.size();
if(length==0)
return 0;
quickSort(nums, 0, length-1);
if(length%2==0)
return nums[length/2-1];
else
return nums[length/2];
}
void quickSort(vector<int> &nums, int start, int end){
if(start<end){
int pivotIndex=partition(nums, start, end);
quickSort(nums, start, pivotIndex-1);
quickSort(nums, pivotIndex+1, end);
}
}
int partition(vector<int> &nums, int start, int end){
int pivot=nums[start];
while(start<end){
while(start<end&&pivot<=nums[end])
end--;
swap(nums[start],nums[end]);
while(start<end&&pivot>=nums[start])
start++;
swap(nums[start],nums[end]);
}
return start;
}
void swap(int &a, int &b){
int temp;
temp=a;
a=b;
b=temp;
}
};
源代码:
class Solution{
public:
void quickSort(vector<int> &nums, int start, int end){
if(start<end){
int pivotIndex=partition(nums, start, end);
quickSort(nums, start, pivotIndex-1);
quickSort(nums, pivotIndex+1, end);
}
}
int partition(vector<int> &nums, int start, int end){
int pivot=nums[start];
while(start<end){
while(start<end&&pivot<=nums[end])
end--;
swap(nums[start],nums[end]);
while(start<end&&pivot>=nums[start])
start++;
swap(nums[start],nums[end]);
}
return start;
}
void swap(int &a, int &b){
int temp;
temp=a;
a=b;
b=temp;
}
};
应用实例:求中位数 数组按从小到大的顺序排列,中位数即为处在中间的那个数。
class Solution {
public:
/**
* @param nums: A list of integers.
* @return: An integer denotes the middle number of the array.
*/
int median(vector<int> &nums) {
// write your code here
int length=nums.size();
if(length==0)
return 0;
quickSort(nums, 0, length-1);
if(length%2==0)
return nums[length/2-1];
else
return nums[length/2];
}
void quickSort(vector<int> &nums, int start, int end){
if(start<end){
int pivotIndex=partition(nums, start, end);
quickSort(nums, start, pivotIndex-1);
quickSort(nums, pivotIndex+1, end);
}
}
int partition(vector<int> &nums, int start, int end){
int pivot=nums[start];
while(start<end){
while(start<end&&pivot<=nums[end])
end--;
swap(nums[start],nums[end]);
while(start<end&&pivot>=nums[start])
start++;
swap(nums[start],nums[end]);
}
return start;
}
void swap(int &a, int &b){
int temp;
temp=a;
a=b;
b=temp;
}
};