Page 597 - Computer science 868 Class 12
P. 597

Output of the preceding program is as follows:
                 Enter Size:
                 5

                 17     24     1      8      15
                 23     5      7      14     16
                 4      6      13     20     22
                 10     12     19     21     3
                 11     18     25     2      9


                 PROGRAMS ON RECURSIVE METHODS

                   Program 12    Binary Search using recursion
                                 Design a class BinSearch to search for a particular value in an array. Some of the members of
                                 the class are given below:
                                 Data Members/Instance variables
                                 arr[]                        :  to store integer elements

                                 n                            :  integer to store the size of the array
                                 Member Functions/Methods
                                 BinSearch(int nn)            :  Constructor to initialise n=nn and declare the array
                                 void fillarray()             :  Accept ‘n’  numbers in array arr[]
                                 void sort()                  :  Sort the array in ascending order
                                 int bin_search(int u, int l, int v) :   searches for the value ‘v’ using binary search and recursive
                                                                 technique  and returns  its  location  if found  otherwise
                                                                 returns -1
                   1       import java.util.*;

                   2       class BinSearch
                   3       {

                   4         int arr[];
                   5         int n;

                   6         Scanner sc=new Scanner(System.in);
                   7         BinSearch(int nn)  // constructor

                   8         {
                   9           n=nn;

                   10        }
                   11        void fillarray()

                   12        {
                   13           arr=new int[n];

                   14           System.out.println("Enter "+n + " elements");
                   15           for(int i =0;i<n;i++)  // accepting numbers



                                                                                                                       595
                                                                                                   Internal Assessment  595
   592   593   594   595   596   597   598   599   600   601   602