真的好久好久没有编写程序,连排序算法都要参考书先可以写出,哎!!
程序要求:随机产生20组数据(比如n=5000i,1≤i≤20)。数据均属于范围(0,105)内的整数。对于同一组数据,运行选择排序算法、快速排序和归并排序算法,并记录各自的运行时间(以毫秒为单位)。
程序中除了设计3种算法,还有用srand(),rand()函数产生随机数,还有用clock() 计算程序运行时间。
刚开始时,挺棘手的,还要上网查资料
平时只看书,没有动手,以后要多点动手才行!!
#include <iostream>
#include <malloc.h>
#include <time.h>
using namespace std;
/*this is a selectionsort */
void SelectionSort(int *str,int n)
{
int i,j,k;
for(i=0; i<n-1; i++)
{
k = i;
for(j=i+1; j<n; j++)
{
if(str[j]<str[k]) k = j;
}
if(k!=i)
{
swap(str[i],str[k]);
}
}
}
/*this is a quicksort */
int Partition(int *str, const int low, const int high)
{
int pivotpos = low; int pivot = str[low];
for(int i = low+1; i<=high;i++)
{
if(str[i]<pivot)
{
pivotpos++;
if(pivotpos!=i) {swap(str[pivotpos],str[i]);}
}
}
str[low] = str[pivotpos];
str[pivotpos] = pivot;
return pivotpos;
}
void QuickSort(int *l, const int left, const int right)
{
if(left<right)
{
int pivotpos = Partition(l,left,right);
QuickSort(l,left,pivotpos-1);
QuickSort(l,pivotpos+1,right);
}
}
/*this is a mergesort */
void Merge(int *p,int left,int mid,int right)
{
int n1,n2,i,j,k;
int *l=NULL,*r=NULL;
n1=mid-left+1;
n2=right-mid;
l = (int *)malloc(sizeof(int)*(n1));
r = (int *)malloc(sizeof(int)*(n2));
for(i=0;i<n1;i++)
l[i] = p[left+i];
for(j=0;j<n2;j++)
r[j] = p[mid+1+j];
i=j=0;
k=left;
while(i<n1&&j<n2)
{
if(l[i]<r[j])
{
p[k++] = l[i++];
}
else
{
p[k++] = r[j++];
}
}
while(i<n1) {p[k++] = l[i++];}
while(j<n2) {p[k++] = r[j++];}
}
void MergeSort(int *p,int left,int right)
{
int mid;
if(left>=right) return;
mid = (left+right)/2;
MergeSort(p,left,mid);
MergeSort(p,mid+1,right);
Merge(p,left,mid,right);
}
int main()
{
int i;
double t1=0,t2=0,t3=0; //存放总时间
for(i=1; i<=20; i++)
{
int n = 5000*i;
int *array1 = NULL;
int *array2 = NULL;
int *array3 = NULL;
array1 = array2 = array3 = (int *)malloc(sizeof(int)*(n)); //给3个数组分配空间
srand(time(0));
for(int j=0; j<n; j++) //产生随机数
{
array1[j] = array2[j] = array3[j] = rand()%100000+1;
}
clock_t t1_start,t1_end ;
t1_start = clock();
QuickSort(array1,0,n-1);
t1_end = clock();
t1 = t1 + (t1_end - t1_start);
clock_t t2_start,t2_end;
t2_start = clock();
MergeSort(array2,0,n-1);
t2_end = clock();
t2 = t2 + (t2_end - t2_start);
clock_t t3_start,t3_end;
t3_start = clock();
SelectionSort(array3,n);
t3_end = clock();
t3 = t3 + t3_end - t3_start;
}
cout<<endl;
cout<<"QuickSort算法的平均运行时间为: "<<(t1+0.0)/20<<" ms"<<endl;
cout<<"MergeSort算法的平均运行时间为: "<<(t2+0.0)/20<<" ms"<<endl;
cout<<"SelectionSort算法的平均运行时间为: "<<(t3+0.0)/20<<" ms"<<endl;
return 0;
}