/*
编写递归算法int max(int a[],int left, int right),求数组a[left..right]中的最大数。
*/
#include "ArrayIo.h"
/*请将本函数补充完整,并进行测试*/
int max(int a[],int left,int right)
{
if(left==right){
return a[left];
}
else if(left<right){
if(a[left]>max(a,left+1,right)){
return a[left];
}
else{
return max(a,left+1,right);
}
}
}
int main()
{ int a[10];
input(a,10);
print(a,10);
printf("数组的最大数是:%d\n",max(a,0,9));
return 0;
}
/*
请编写一个递归算法函数void partion(int a[], int left, int right),
将数组a[left..right]中的所有奇数调整到表的左边,所有偶数调整到表的右边。
*/
#include "ArrayIo.h"
#define N 10
/*请将本函数补充完整,并进行测试*/
void partion(int a[], int left,int right)
{
if(left>=right){
return;
}
else{
while(a[left]%2==1){
left++;
if(left>=right){
return;
}
}
while(a[right]%2==0){
right--;
if(left>=right){
return;
}
}
int temp=a[left];
a[left]=a[right];
a[right]=temp;
partion(a,++left,--right);
}
}
int main()
{ int a[N];
init(a,N); /*随机产生N个数*/
print(a,N);
partion(a,0,N-1);
print(a,N);
return 0;
}
/*
请编写递归函数void bubbleSort(int a[],int n),
对长度为n的数组采用冒泡法进行升序排序。
请编写递归函数int binSearch(int a[], int left, int right,int key),
采用二分查找法在数组a[left..right]中查找值为key的元素所在的位置,
若查找失败函数返回-1。
*/
#include "ArrayIo.h"
#define N 10
/*请将本函数补充完整,并进行测试*/
void bubbleSort(int a[],int n)
{
if(n==1){
return;
}
int j;
for(j=0;j<n-1;j++){
if(a[j]>a[j+1]){
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
bubbleSort(a,n-1);
}
int binSearch(int a[], int left,int right,int key)
{
if(left<=right){
int mid=(left+right)/2;
if(a[mid]>key){
return binSearch(a,left,mid-1,key);
}
else if(a[mid]<key){
return binSearch(a,mid+1,right,key);
}
else if(a[mid]==key){
return mid;
}
}
return -1;
}
int main()
{ int x,pos,a[N];
init(a,N);
bubbleSort(a,N);
print(a,N);
printf("请输入要查找的数:\n");
scanf("%d",&x);
pos=binSearch(a,0,N-1,x);
if (pos!=-1) printf("a[%d]=%d\n",pos,x);
else printf("Not found!\n");
return 0;
}
/*
已知带头结点的单链表结构定义同实验3,假设链表中所有结点值均不相同,
请编写一个递归函数linklist max(linklist head),返回表中最大数所在的结点地址,若链表为空,返回NULL。
*/
#include "slnklist.h"
/*请将本函数补充完整,并进行测试*/
linklist max(linklist head)
{
linklist qq;
if (head->next==NULL)
return NULL;
else
if (head->next->next==NULL)
return head->next;
else
{
qq=max(head->next);
return head->next->info > qq->info ? head->next:qq;
}
}
int main()
{ linklist head,p;
head=creatbyqueue();
print(head);
p=max(head);
if (p)
printf("max=%d\n",p->info);
else
printf("链表为空\n");
return 0;
}