递归实现
#include<stdio.h> #define MAX 100 void print(int p[],int left,int right) { if(left<=right) { int mid=(left+right)/2; printf("%d ",p[mid]); print(p,left,mid-1); print(p,mid+1,right); } }
非递归实现
void Print(int p[],int left,int right) { typedef struct { int l; int r; }stacknode; stacknode stack[MAX]; int i,j,mid,top=0; if(left<=right)//数组不为空 { i=left;j=right; while(i<=j||top!=0)//当当前区域不为空或者栈不为空(存在输出序列) { if(i<=j)//当前区域非空输出该区域 { mid=(i+j)/2; printf("%d ",p[mid]);//优先输出中间 //将右边区域入栈保存 stack[top].l=mid+1; stack[top].r=j; top++; //进入该区域的左边区域 j=mid-1; } else//该区域为空,出栈得到另一边 { top--; i=stack[top].l; j=stack[top].r; } } } }
int main() { int s[7]={1,2,3,4,5,6,7}; Print(s,0,7-1); print(s,0,7-1); }
版权声明:本文为博主原创文章,未经博主允许不得转载。