mercredi 1 juillet 2020

How to fix the code so it can run 5 times with for-loop?

I'm trying to run this 5 times with five different numbers (randomly, see int x), it runs without any problem with 1 attempt. I tried to add a for-loop (lines with //) and it became a mess. What can I do to fix it?

Example Result: --> What can I do to fix it?

My code will print the following:
          Trial       Number of Elements      Search Key    ....
            1                65536               123 (random) ....
- - - - - - - - - - - - - - - - - - - - - - --  - -- - - - - - - - - 
I want to become the following: 
  Trial       Number of Elements      Search Key
    1                65536               123 (random)
    2                65536               1234 (random)
    3                65536               1123 (random)
    4                65536               11234 (random)
    5                65536               15234 (random)

import java.util.Random;

class BinarySearch { 
    private int compareCount;


    int binarySearch(int arr[], int l, int r, int x) { 
       
        if (r >= l) { 
            int mid = l + (r - l) / 2; 
              
            compareCount++;   
            if (arr[mid] == x) 
                return mid; 
    
            compareCount++;   
            if (arr[mid] > x) 
                return binarySearch(arr, l, mid - 1, x); 

            return binarySearch(arr, mid + 1, r, x); 
        } 
        return -1; 
    } 

    
    public static void main(String args[]) 
    { 
        
        BinarySearch ob = new BinarySearch(); 
        //for (int i = 0; i<5;i++) {
        
        int[] arr = new Random().ints(65536, 1, 65536 + 1).sorted().toArray();
        int n = arr.length; 
        Random rand = new Random();
        int max_range = 65536;
        

        int x = rand.nextInt(max_range); // generate a random number between 1-65536

        int result = ob.binarySearch(arr, 0, n - 1, x); 
                
        String isFound = "N";
        if (result != -1)
            isFound = "Y";
        

        int N = 65536; 
        int expect = (int)(Math.log(N) / Math.log(2)) + 1; 
        
        
        System.out.println
("   Trial    "  +   "   Number of Elements   " +  "   Search Key   " + "   Left Index  " + "   Right Index  " + "    Found/Not Found   " + " Expected Comparision  " + "   Acutal Comparsion   "   + "\n" 
+"     1              "  +  arr.length +  "              " + x  +   "         " + arr[result-1] + "      " + arr[result+1] +  "              " + isFound  + "            " + expect + "                   "+  ob.compareCount 
//+ i  +  arr.length +  "              " + x  +   "           " + arr[result-1] + "      " + arr[result+1] +  "              " + isFound  + "            " + expect + "                   "+  ob.compareCount   
);
    //  }
        
    }
} 

  



Aucun commentaire:

Enregistrer un commentaire