一道例题及其推广——
(思考题答案)
#include <bits/stdc++.h>
using namespace std;
int com(int a[],int low,int high)
{
if(low==high)
if(a[low]%2==0) return 1;
else return 0;
int mid=(low+high)/2;
return com(a,low,mid)+com(a,mid+1,high);
}
int main()
{
int a[50],num;
printf("输入的数共有几个:");
cin>>num;
for(int i=0;i<num;i++)
{
cin>>a[i];
}
int low=0,high=num-1;
int sum=com(a,low,high);
cout<<"偶数个数:"<<sum<<endl;
return 0;
}
快速排序算法
求数组最大元素:
#include <iostream>
using namespace std;
void quick_sort(int *a, int left, int right)
{
int temp;
int t;
int initial=left;
int end=right;
temp=a[left];
if (left>right)
return;
while(left!=right)
{
while(a[right]>=temp && left<right)
right--;
while(a[left]<=temp && left<right)
left++;
if(left<right)
{
t=a[right];
a[right]=a[left];
a[left]=t;
}
}
a[initial]=a[left];
a[left]=temp;
quick_sort(a,initial,left-1);
quick_sort(a,left+1,end);
}
int main()
{
int a[50],n;
cin>>n;
for(int i=0;i<n;i++)
cin>>a[i];
quick_sort(a,0,n-1);
cout<<a[n-1]<<endl;
return 0;
}