*严蔚敏数据结构书上的快速排序
*/
int Partition(LL* a,int low,int high)
{
LL pivot = a[low];
while (low < high){
while (low < high&&a[high] > pivot)--high;
a[low] = a[high];
while (low < high&&a[low] < pivot)++low;
a[high] = a[low];
}
a[low] = pivot;
return low;
}
void QSort(LL* a, int low, int high)
{
if (low < high){
int pivotloc = Partition(a, low, high);
QSort(a, low, pivotloc - 1);
QSort(a, pivotloc + 1, high);
}
}
void QuickSort(LL* a)
{
int len = _msize(a) / sizeof(LL);
QSort(a, 0, len - 1);
}
* 自己写的快速排序,其实是按照严蔚敏书上的思路来的,所以代码结构很相似
*/
void QuickSort(LL* a,int len)
{
if (len <= 1)
return;
LL pivot = a[0];
int le = 0, ri = len - 1;
while (le<ri){
while (le < ri&&a[ri] >= pivot){
ri--;
}
a[le] = a[ri];
while (le < ri&&a[le] <= pivot){
le++;
}
a[ri] = a[le];
}
a[le] = pivot;
QuickSort(a, le);
QuickSort(a + le + 1, len - le - 1);
}
* 自己写的堆排,注意每次更新堆之后需要把根节点与换到数组后面去,然后更新的时候就不把它算进来。直至遍历到根节点
*/
void Up2Down(int e, LL* a)
{
int len = a[0];
int le = 2 * e;
int ri = 2 * e + 1;
int position;
if (le > len)
return;
if (ri > len){
position = le;
}
else{
position = a[le] > a[ri] ? le : ri;
}
if (a[position] > a[e]){
LL tmp = a[e];
a[e] = a[position];
a[position] = tmp;
Up2Down(position, a);
}
}
void HeapSort(LL* a)
{
int len = a[0];
for (int i = len / 2; i >= 1; i--){
Up2Down(i, a);
}
for (int i = len; i > 1; i--){
int tmp = a[1];
a[1] = a[i];
a[i] = tmp;
a[0] = i - 1;
Up2Down(1, a);
}
}