#include <string>
#include <algorithm>
#include <time.h>
using namespace std;
// 冒泡排序
void BubbleSort(int a[], int len)
{
if (a == NULL || len <= 0)
return;
bool swapped;
int last = len - 1;
do
{
swapped = false;
for (int i = 1; i <= last; i++)
{
// 稳定性体现在这里
if (a[i - 1] > a[i])
{
int tmp = a[i - 1];
a[i - 1] = a[i];
a[i] = tmp;
swapped = true;
}
}
last--; // 每一趟后减少一个带排序个数
} while (swapped);
}
// 快排
int partition(int a[], int start, int end)
{
if (start == end)
return start;
srand((unsigned int)time(NULL));
// 在[start,end]随机选择中枢
int pivotIndex = (rand() % (end - start + 1)) + start;
// a[start]存放中枢
Swap(&a[pivotIndex], &a[start]);
int storeIndex = start + 1;
for (int i = start + 1; i <= end; i++)
{
if (a[i] < a[start])
{
if (i != storeIndex)
Swap(&a[storeIndex], &a[i]);
storeIndex++;
}
}
storeIndex--;
Swap(&a[start], &a[storeIndex]);
return storeIndex;
}
void QuickSort(int a[], int len)
{
if (a == NULL || len <= 0)
return;
int pivotIndex = partition(a, 0, len - 1);
if (pivotIndex > 0)
QuickSort(a, pivotIndex);
if (pivotIndex < len - 1)
QuickSort(a + pivotIndex + 1, len - pivotIndex - 1);
}
// 归并排序
void Merge(int a[], int tmp[], int start, int mid, int end)
{
int p1 = start;
int p2 = mid + 1;
int p = start;
while (p1 <= mid && p2 <= end)
{
// 归并排序的稳定性体现在这里
if (a[p1] <= a[p2])
tmp[p++] = a[p1++];
else
tmp[p++] = a[p2++];
}
while (p1 <= mid)
tmp[p++] = a[p1++];
while (p2 <= end)
tmp[p++] = a[p2++];
for (int i = start; i <= end; i++)
a[i] = tmp[i];
}
void MergeSortCore(int a[], int tmp[], int start, int end)
{
if (start == end)
return;
int mid = (start + end) / 2;
MergeSortCore(a, tmp, start, mid);
MergeSortCore(a, tmp, mid + 1, end);
Merge(a, tmp, start, mid, end);
}
void MergeSort(int a[], int len)
{
if (a == NULL || len <= 0)
return;
int *tmp = new int[len];
MergeSortCore(a, tmp, 0, len - 1);
delete[] tmp;
}
sort.cpp
最新推荐文章于 2024-04-15 10:00:04 发布