Search code examples
javaarrayssortingstatic-methods

Modifying a static method to add two counters when comparing arrays using for loops in Java


Using this segment of code I already have, I want to modify the selectionSort method to have two counters, one for the number of comparisons, and one for the number of data swaps. Each time two data elements are compared (regardless of whether the items are in the correct order—we're interested in that a comparison is being done at all), increment the comparison counter. Each time two data items are actually swapped, increment the data swap counter.

So far this is what I have tried to add the counters. However, I receive an error "Unresolved compilation problem: counter cannot be resolved to a variable".

public static void selectionSort(double[] list) {
      for (int i = 0; i < list.length - 1; i++) {
      // Find the minimum in the list[i..list.length-1]
      double currentMin = list[i];
      int currentMinIndex = i;
      int counter = 0;

      for (int j = i + 1; j < list.length; j++) {
        if (currentMin > list[j]) {
          currentMin = list[j];
          currentMinIndex = j;
        }
      }

      // Swap list[i] with list[currentMinIndex] if necessary;
      if (currentMinIndex != i) {
        list[currentMinIndex] = list[i];
        list[i] = currentMin;
      }
      counter += 1;
    }

      System.out.println("The size of the sorted array is " + list.length + " and the count is " + counter);
  }

I have the main method prepared below.

public static void main(String[] args) {
      final int NUM_ELEMENTS = 10;

      double[] lo2Hi = new double[NUM_ELEMENTS];
      for (int i = 0; i < NUM_ELEMENTS; i++) {
          lo2Hi[i] = i + 1;
      }
      selectionSort(lo2Hi);
      double[] hi2Lo = new double[NUM_ELEMENTS];
      for (int i = 0; i < NUM_ELEMENTS; i++) {
          hi2Lo[i] = 10 - i;
      }
      selectionSort(hi2Lo);
      double[] random = new double[NUM_ELEMENTS];
      for (int i = 0; i < random.length; i++) {
          random[i] = Math.random();
      }
      selectionSort(random);
  }

Solution

  • Your println() at the end of selectionSort() is trying to acces the variable counter, but counter is "out of scope" at that point. Variables only exist within the pair of {}'s they were declared inside (that's what "scope" is).

    Move the int counter = 0; statement out of the for loop, and put it at top of the method. Then it will be in-scope for the print statement.