C Program for Binary Search and Towers of Hanoi using Recursion.
Source: Dr. G T Raju, Professor & Head, Dept. of CSE, RNSIT
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | main() { int n,a[50],key,opn,i,pos; do { clrscr(); printf(" \n\n Press 1 -> Binary Search , 2-> Towers of Hanoi 3-> Quit\n"); scanf("%d",&opn); switch(opn) { case 1: printf(" How Many Elements?"); scanf("%d",&n); printf(" Read all the elements is ASC order \n"); for(i=1;i<=n;i++) scanf("%d",&a[i]); printf(" Read the Key Element\n"); scanf("%d",&key); pos=BS(a,key,1,n); if(pos) printf(" Success: %d found at %d \n", key,pos); else printf(" Falure: %d Not found in the list ! \n",key); break; case 2: printf("\n\n How Many Disks ?"); scanf("%d", &n); printf("\n\n Result of Towers of Hanoi for %d Disks \n",n); tower(n,'A','B','C'); printf("\n\n Note: A-> Source, B-> Intermediate, C-> Destination\n"); break; case 3: printf(" Terminating \n"); break; default: printf(" Invalid Option !! Try Again !! \n"); } printf(" Press a Key. . . "); getch(); }while(opn != 3); } int BS(int a[], int key,int low,int high) { int mid; if(low > high) return 0; /* failure */ else { mid=(low+high)/2; if(a[mid]== key) return mid; /* Success */ if(key < a[mid]) return(BS(a,key,low,mid-1)); return(BS(a,key,mid+1,high)); } } tower(int n, char src, char intr, char dst) { if(n > 0) { tower(n-1,src,dst,intr); printf("Move disk %d from %c to %c \n", n,src,dst); tower(n-1,intr,src,dst); } } |