一、实验目的及要求
1、掌握算法分析的基本思想;
2、学会求解算法的时间复杂度。
二、实验内容
编写程序实现:
1、设计一个求解最大元素和最小元素的高效算法,并在随机产生的10个1~20整数中实现最大、最小值寻找;
2、统计元素之间的比较次数,并求出执行10次调用算法的平均比较次数,试分析比较次数与算法性能的关系。
# 拓展实验 #
1、尝试以不同排序方法进行最大、最小值寻找;
2、 试比较不同排序算法的时间复杂度。
#include<iostream>
#include<stdlib.h>
#include<time.h>
using namespace std;
double sum;
void sort(int num[10]){
cout<<"选择排序:"<<endl;
int transform;
int flag=0;
for(int i=0;i<9;i++){
for(int j=i+1;j<10;j++){
if(num[i]>num[j]){
transform=num[i];
num[i]=num[j];
num[j]=transform;
flag++;
sum++;
}
}
}
cout<<"排序后为:";
for(int k=0;k<10;k++){
cout<<num[k]<<",";
}
cout<<endl;
cout<<"最小的数是:"<<num[0]<<endl;
cout<<"最大的数是:"<<num[9]<<endl;
cout<<"共比较了"<<flag<<"次"<<endl;
}
void bubblesort(int num[10]){
cout<<"冒泡排序"<<endl;
int fff=0;
for (int i=0;i<10;i++){
for (int j=0; j <9-i;j++){
if (num[j]>num[j + 1]){
int temp;
temp = num[j + 1];
num[j + 1] = num[j];
num[j] = temp;
fff++;
sum++;
}
}
}
cout<<"排序后为:";
for(int k=0;k<10;k++){
cout<<num[k]<<",";
}
cout<<endl;
cout<<"最小的数是:"<<num[0]<<endl;
cout<<"最大的数是:"<<num[9]<<endl;
cout<<"共比较了"<<fff<<"次"<<endl;
}
int main(void){
int num[10];
srand(time(0));
for(int rec=0;rec<10;rec++){
//这里是产生随机数,并且存储到数组里面去
cout<<"数列为:";
for (int i = 0; i < 10; i++){
num[i]=1+rand()%20;
cout<<num[i]<<",";
}
cout<<endl;
//sort(num);
bubblesort(num);
cout<<endl;
}
cout<<"一共比较了"<<sum<<"次,"<<"平均每回比较" <<sum/10<<"次";
return 0;
}