#include <iostream>
#include <time.h>
using namespace std;
#define N 1000
void swap(int &a,int &b)
{
int temp=a;
a=b;
b=temp;
}
//冒泡
void Msort(int A[],int size)
{
for(int i=0;i<size;i++)
{
for(int j=0;j<size-i-1;j++)
if(A[j]>A[j+1])
{
swap(A[j],A[j+1]);
}
}
}
//快速排序
int partition(int A[],int p,int r)
{
int x=A[r];
int i=p-1;
for(int j=p;j<r;j++)
{
if(A[j]<=x)
{
i++;
swap(A[j],A[i]);
}
}
swap(A[r],A[i+1]);
return i+1;
}
void quicksort(int A[],int p,int r)
{
if(p<r)
{
int q=partition(A,p,r);
quicksort(A,p,q-1);
quicksort(A,q+1,r);
}
}
//插入排序
void InsertionSort(int input[],int len)
{
int i,j,temp;
for (i = 1; i < len; i++)
{
temp = input[i]; /* 操作当前元素,先保存在其它变量中 */
for (j = i - 1;j>-1&&input[j] > temp ; j--) /* 从当前元素的上一个元素开始查找合适的位置 */
{
input[j + 1] = input[j]; /* 一边找一边移动元素 */
input[j] = temp;
}
}
}
//希尔
void sort(int v[],int n)
{
int gap,i,j,temp;
for(gap=n/2;gap>0;gap /= 2)
{
for(i=gap;i<n;i++)
{
for(j=i-gap;(j >= 0) && (v[j] > v[j+gap]);j -= gap )
{
temp=v[j];
v[j]=v[j+gap];
v[j+gap]=temp;
}
}
}
}
//选择
void Selectsort(int A[],int n)
{
int i,j,min,temp;
for(i=0;i<n;i++)
{
min=i;
for(j=i+1;j<=n;j++) /* 从j往前的数据都是排好的,所以从j开始往下找剩下的元素中最小的 */
{
if(A[min]>A[j]) /* 把剩下元素中最小的那个放到A[i]中 */
{
temp=A[i];
A[i]=A[j];
A[j]=temp;
}
}
}
}
void main()
{
clock_t start,end;
start=clock();
double duration;
int A[N];
for(int i=0;i<N;i++)
A[i]=rand();// 随机取数
// start=clock();
Msort(A,N);
//Selectsort(A,N);
for(int i=0;i<N;i++)
{
cout<<A[i]<<" ";
}
end=clock();
duration=(double)(end-start);
//cout<<"*******************************"<<endl;
cout<<"冒泡排序算法的时间"<<duration<<endl;
cout<<"*******************************"<<endl;
cout<<endl;
start=clock();
// double duration;
//int A[N];
for(int i=0;i<N;i++)
A[i]=rand();
// start=clock();
//Msort(A,N);
Selectsort(A,N);
for(int i=0;i<N;i++)
{
cout<<A[i]<<" ";
}
end=clock();
duration=(double)(end-start);
cout<<"选择排序算法的时间"<<duration<<endl;
cout<<endl;
start=clock();
// double duration;
//int A[N];
for(int i=0;i<N;i++)
A[i]=rand();
// start=clock();
//Msort(A,N);
// Selectsort(A,N);
InsertionSort(A,N);
for(int i=0;i<N;i++)
{
cout<<A[i]<<" ";
}
end=clock();
duration=(double)(end-start);
cout<<"插入排序算法的时间"<<duration<<endl;
cout<<endl;
start=clock();
// double duration;
//int A[N];
for(int i=0;i<N;i++)
A[i]=rand();
// start=clock();
//Msort(A,N);
sort(A,N);
for(int i=0;i<N;i++)
{
cout<<A[i]<<" ";
}
end=clock();
duration=(double)(end-start);
cout<<"希尔排序算法的时间"<<duration<<endl;
start=clock();
// double duration;
//int A[N];
for(int i=0;i<N;i++)
A[i]=rand();
// start=clock();
//Msort(A,N);
quicksort(A,0,N-1);
for(int i=0;i<N;i++)
{
cout<<A[i]<<" ";
}
end=clock();
duration=(double)(end-start);
cout<<"快速排序算法的时间"<<duration<<endl;
//cout<<endl;
// return 0;
}