递归实现:
int Parition(int* br, int left, int right)
{
int tmp = br[left];
while (left < right)
{
while (left<right && br[right]>tmp)
{
--right;
}
if (left < right)br[left] = br[right];
while (left < right && br[left] <= tmp)
{
++left;
}
if (left < right)br[right] = br[left];
}
br[left] = tmp;
return left;
}
void PassQuick(int* br, int left, int right)
{
if (left < right)//不能是<=,确保有两个元素
{
int pos = Parition(br, left, right);
PassQuick(br, left, pos);
PassQuick(br, pos + 1, right);
}
}
void QuickSort(int* br, int n)
{
if (br == NULL || n < 2)return;
PassQuick(br, 0, n - 1);
}
非递归–队或栈实现:
void QuickSort(int* br, int n)
{
if (br == NULL || n < 2)return;
stack<int> qu;
qu.push(0);
qu.push(n - 1);
while (!qu.empty())
{
int left = qu.front; qu.pop();
int right = qu.front; qu.pop();
int pos = Parition(br, left, right);
if (left < pos - 1)
{
qu.push(left);
qu.push(pos - 1);
}
if (pos + 1 < right)
{
qu.push(pos + 1);
qu.push(right);
}
}
}
非递归–对实现
void QuickSort(int* br, int n)
{
if (br == NULL || n < 2)return;
queue<std::pair<int, int>>qu;
qu.push(std::pair<int, int>(0, n - 1));
while (!qu.empty())
{
std::pair<int, int>tmp = qu.front();qu.pop();
int pos = Parition(br, tmp.first,tmp.second);
if (tmp.first < pos - 1)
{
qu.push(std::pair<int, int>(tmp.first, pos - 1));
}
if (pos + 1 < tmp.second)
{
qu.push(std::pair<int, int>(pos + 1, tmp.second));
}
}
}
//改进
void QuickSort(int* br, int n)
{
if (br == NULL || n < 2)return;
typedef std::pair<int, int>Pair;
queue<Pair>qu;
qu.push(Pair(0, n - 1));
while (!qu.empty())
{
std::pair<int, int>tmp = qu.front(); qu.pop();
int pos = Parition(br, tmp.first, tmp.second);
if (tmp.first < pos - 1)
{
qu.push(Pair(tmp.first, pos - 1));
}
if (pos + 1 < tmp.second)
{
qu.push(Pair(pos + 1, tmp.second));
}
}
}
快排特点:越乱越快,越有序越慢
解决方法如下:
快速排序优化一随机化法:在范围内随机找一个数,和left进行交换
int RandParition(int* br, int left, int right)
{
srand(time(NULL));//防止随机数一样
int pos = rand() % (right - left + 1) + left;
std::swap(br[left], br[pos]);
return Parition(br, left, right);
}
void QuickSort(int* br, int n)
{
if (br == NULL || n < 2)return;
queue<std::pair<int, int>>qu;
qu.push(std::pair<int, int>(0, n - 1));
while (!qu.empty())
{
std::pair<int, int>tmp = qu.front();qu.pop();
int pos = RandParition(br, tmp.first,tmp.second);
if (tmp.first < pos - 1)
{
qu.push(std::pair<int, int>(tmp.first, pos - 1));
}
if (pos + 1 < tmp.second)
{
qu.push(std::pair<int, int>(pos + 1, tmp.second));
}
}
}
快速排序优化一三位取中法:left和right还有范围内的中间值,取这三个数中的中间值
int MidParition(int* br, int left, int right)
{
int mid = (right - left) / 2 + left;
struct IndexNode
{
int key;
int index;
operator int()const//强转为int
{
return key;
}
};
struct IndexNode kL = { br[left],left };
struct IndexNode kM = { br[mid],mid };
struct IndexNode kR = { br[right],right };
std::priority_queue<IndexNode>hp;
hp.push(kL); hp.push(kM); hp.push(kR);
hp.pop();
struct IndexNode pos = hp.top();
std::swap(br[kL.index], br[pos.index]);
return Parition(br, left, right);
}