堆排序
#include<bits/stdc++.h>
using namespace std;
void HeapAdjusting(int a[], int root, int n)
{
int temp = a[root];
int child = 2 * root + 1;
while (child < n)
{
if (child + 1 < n && a[child + 1] < a[child])
child++;
if (a[root] > a[child])
{
a[root] = a[child];
root = child;
child = 2 * root + 1;
}
else
break;
a[root] = temp;
}
}
void HeapBuilding(int a[], int n)
{
for (int i = (n - 1) / 2; i >= 0; i--)
HeapAdjusting(a, i, n);
}
void HeapSort(int a[], int n)
{
HeapBuilding(a, n);
for (int i = n - 1; i > 0; i--)
{
swap(a[0], a[i]);
HeapAdjusting(a, 0, i);
}
}
归并排序
void MergeArr(int a[], int first, int mid, int last, int temp[])
{
int i = first, j = mid + 1;
int m = mid, n = last;
int k = 0;
while (i <= m && j <= n)
{
if (a[i] < a[j])
temp[k++] = a[i++];
else
temp[k++] = a[j++];
}
while (i <= m)
temp[k++] = a[i++];
while (j <= n)
temp[k++] = a[j++];
for (i = 0; i < k; i++)
a[first + i] = temp[i];
}
void MergeSort(int a[], int first, int last, int temp[])
{
if (first < last)
{
int mid = (first + last) / 2;
MergeSort(a, first, mid, temp);
MergeSort(a, mid + 1, last, temp);
MergeArr(a, first, mid, last, temp);
}
}
快速排序
void QuickSort(int a[], int L, int R)
{
if (L < R)
{
int i = L, j = R, temp = a[i];
while (i < j)
{
while (i < j && a[j] >= temp)
j--;
if (i < j)
a[i++] = a[j];
while (i < j && a[i] < temp)
i++;
if (i < j)
a[j--] = a[i];
}
a[i] = temp;
QuickSort(a, L, i - 1);
QuickSort(a, i + 1, R);
}
}