内排序算法时间计算
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
#include
#include
#include
using namespace std;
template
void Swap(T &a, T &b)
{
T temp;
temp = a;
a = b;
b = temp;
}
template
void SelectSort(T A[], int n) //简单选择排序{
int small;
for (int i = 0; i < n - 1; i++)
{
small = i;
for (int j = i + 1; j < n; j++)
if (A[j] < A[small]) small = j;
Swap(A[i],A[small]);
}
}
template
void InsertSort(T A[], int n) //直接插入排序{
for (int i = 1; i < n; i++)
{
int j = i;
T temp = A[i];
while (j > 0 && temp < A[j-1])
{
A[j] = A[j-1];
j--;
}
A[j] = temp;
}
}
template
void BubbleSort(T A[], int n) //冒泡排序{
int i, j, last;
i = n - 1;
while (i > 0)
{
last = 0;
for (j = 0; j < i; j++)
if (A[j+1] < A[j])
{
Swap(A[j],A[j+1]);
last = j;
}
i = last;
}
}
template
void QuickSort(T A[], int n) //快速排序{
if (n < 10)
InsertSort(A,n);
else
QSort(A,0,n-1);
}
template
void QSort(T A[], int left, int right) {
int i, j;
if (left < right)
{
i = left;
j = right + 1;
do
{
do i++; while (A[i] < A[left]);
do j--; while (A[j] > A[left]);
if (i < j) Swap(A[i],A[j]);
}while (i < j);
Swap(A[left],A[j]);
QSort(A,left,j-1);
QSort(A,j+1,right);
}
}
template
void Merge(T A[], int i1, int j1, int i2, int j2) {
T *Temp = new T[j2-i1+1];
int i = i1, j = i2, k = 0;
while (i <= j1 && j <= j2)
if (A[i] <= A[j])
Temp[k++] = A[i++];
else
Temp[k++] = A[j++];
while (i <= j1)
Temp[k++] = A[i++];
while (j <= j2)
Temp[k++] = A[j++];
for (i = 0; i < k; i++)
A[i1++] = Temp[i];
delete []Temp;
}
template
void MergeSort(T A[], int n) //两路合并排序{
int i1, j1, i2, j2;
int size = 1;
while (size < n)
{
i1 = 0;
while (i1 + size < n)
{
i2 = i1 + size;
j1 = i2 - 1;
if (i2 + size - 1 > n - 1)
j2 = n - 1;
else
j2 = i2 + size - 1;
Merge(A,i1,j1,i2,j2);
i1 = j2 + 1;
}
size *= 2;
}
}
void main()
{
/* int a[10] = {61,87,12,3,8,70,97,75,53,26};
SelectSort(a,10); InsertSort(a,10); BubbleSort(a,10);
QuickSort(a,10); MergeSort(a,10);
for (int i = 0; i < 10; i++)
cout << a[i] << " "; */ //函数测试
int max = 50000;
int *a = new int[max], *b = new int[max];
clock_t start, end;
double t;
srand(time(0));
for (int i = 0; i < max; i++) a[i] = rand() % 1000;
for (i = 0; i < max; i++) b[i] = a[i];
start = clock();
SelectSort(b,max);
end = clock();
t = (end - start) * 1.0 / CLOCKS_PER_SEC;
cout << "简单选择排序:" << t << "秒" << endl;