Skip to content
Advertisement

Random search on an array of size N

I need help fixing my code below. I want to do a random search on an array of size N. Random search randomly picks up an integer from arr to compare. And the process repeats until the integer it is looking for is found (again it is remarked that the membership is guaranteed, otherwise random search obviously can enter an infinite loop). How do I search for the searchValue using random search?

public void randomSearch() {
  counter = new int[N]; // Reset the counter
  int stepsTotal = 0; // Total number of steps/comparisons
  for (int i = 0; i < N; i++) { // Comparison for all N from 0 to N-1
    int steps = 0;
    int searchValue = i; // using i as our search value to check membership
    for (int j = 0; j < N; j++) {
      j = (int)(Math.random() * N); // generate a random number from 0 to N-1
      steps++; // increment the steps for each record comparison
      counter[j]++; // increment the number of records stored in the array
      if (arr[j] != searchValue) { // if the records are found in the array
        break; // found
      }
    }

Advertisement

Answer

I don’t exactly get what you intend to do, but based on my idea, you want to search for an element randomly, until it is found. If I am right, then first of all searchValue should be equal arr[i], in this way, your array can take any value, and instead of using a nested-for loop, use nested-do-while loop, like-this.

public void randomSearch() {
  
  counter =new int[N];                   
 
  int stepsTotal = 0;                    
  for (int i = 0; i < N; i++) {          
     int steps = 0;
     int searchValue = arr[i];               
     int j;
     do {
        j = (int)(Math.random()*N);
        steps++;                       
        counter[j]++;                        
     }while(arr[j] != searchValue);
     // More functionality here
   } 
}
Advertisement