作为笔记写的,借鉴性不大。
快速排序是基于分治法基础上的,也就是说大概包含了三部分;
1.划分分区
我之前一直以为二分就是所谓的从中间分开,后来才知道,二分只是将属于不同的情况的以某一值或一点分开而已。而且分区的方法多种多样,我们在这里取一种较为简单的来阐述什么是快速排序。
2.递归求解
分开的区间,排序(排序时,我们需要取任意值最为中轴值来将数分到两边);
3.合并
这里其实用不到合并这一项。你想,我们每一次递归的时候就将其变成有序的,在最后一层递归结束时,每一个都有序,那总体不就也有序了。
在这种快速排序的方法中它的T(n) =O(nlg n) 是最理想的一种情况,也就是它的运行次数平均为nlgn次,但如果我们取到的最大值或最小值,那这个时候,T(n) = O(n2) ,也就说我们至少要运行n2 那我们有什么可以解决的方法吗? 问题总是有它的解决方法的,我们取中轴值一般去数组的第一位或最后一位,那我们不不取这两个点,而是在数组中人任取一值不就大大降低我们取到最值的风险了吗?
void quicksort(vector<int> &v, int left, int right) { if (left < right) { int key = v[left]; int low = left; int high = right; while (low < high) { while (low<high && v[high] >= key) high--; v[low] = v[high]; while (low < high && v[low] <= key) low++; v[high] = v[low]; } v[low] = key; quicksort(v, left, low - 1); quicksort(v, low + 1, right); } }