第一章 时间复杂度和基本算法的实现
1、已知求数组最小元素的值及下标的算法如下,编写主函数进行测试,要求输入任意数组,给出运行结果。
源码分析:
2、设计一个时间复杂度为O(n)的算法,实现将数组arr[n]中所有元素循环左移k个位置。
#include “iostream.h”
void Reverse(int arr[],int from,int to){ //将数组arr中元素从from到to逆置
for(int temp ;temp<to;temp++,to–) //填空
{
temp=arr[from]; //填空,交换元素
arr[from]=arr[to];
arr[to]=temp;
}
}
void Converse(int arr[],int n,int k){
Reverse(arr,0,k-1);//调用函数
Reverse(arr,k,n-1);
Reverse(arr,0,n-1);
}
void main(){
int n,m;
cout<<“请输入数组元素个数:”;
cin>>n;
int *arr=new int[n];
cout<<“请输入”<<n<<“个数组元素:”<<endl;
for(int i=0;i<n;i++)
cin>>arr[i];
cout<<“请输入数组左移位置数:”;
cin>>m;
Converse(arr,n,m);
cout<<“数组循环左移”<<m<<“个位置后,数组元素为:”<<endl;
for(int j=0;j<n;j++)
cout<<arr[j]<<" “;
}
3、设计一个时间复杂度为O(n)的算法,实现将数组b[n]中所有元素调整为左右两部分,左边为奇数,右边为偶数。
#include “iostream.h”
void Adjust(int a[],int n){
int i=0,j=n-1,temp;
while(i<j){
while(a[i]%2!=0) i++;
while(a[j]%2==0) j–;
if(i<j) {
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
void main(){
int n,m;
cout<<“请输入数组元素个数:”;
cin>>n;
int *arr=new int[n];
cout<<“请输入”<<n<<“个数组元素:”<<endl;
for(int i=0;i<n;i++)
cin>>arr[i];
Adjust(arr,n);
cout<<“奇偶调整后,数组元素为:”<<endl;
for(int j=0;j<n;j++)
cout<<arr[j]<<” ";
}
4、
答案:A
分析:
5、
答案:C
分析:
6、
答案与分析:
7、
答案:D
分析:
8、
答案:B
分析:
9、
答案:D
分析:算法的时间复杂度和空间复杂度没有直接的关系;所以选择D答案。
10、
答案与分析: