Question

I have an assignment to count the assignments and comparisons in a selection sort. For some reason my assignment counter isn't incrementing. I've tried adding it above the swap and I've tried incorporating into the swap method - to no avail. Any ideas why it's not working?

Update: The counter doesn't work for this

            Integer[] test = {1, 0, 4, 2};
            selectionSort(test);

But it does work for this:

    selectionSort(new Integer[] {1, 0, 4, 2});

Anyone know why?

public static void selectionSort(Integer[] array)
{
    int assignmentCounter = 0;
    int comparisonCounter = 0;
    int i, j;

    for(i = 0; i < array.length; i++)
    {
        int minIndex = i;
        for(j = i + 1; j < array.length; j++)
        {
            comparisonCounter++;
            if(array[j].compareTo(array[minIndex]) < 0)
            {
                minIndex = j;
                assignmentCounter++;
                swap(array,minIndex,i);
            }
        }
    }
    System.out.println("Selection Sort Comparisons: " + comparisonCounter + "\nSelection Sort Assignments: " + assignmentCounter);
   for(int k = 0; k < array.length; k++)
        {
            System.out.print(array[k] + ", ");
        }
        System.out.println("\n\n ");
}

Thank you!

Was it helpful?

Solution

When I run this

public static void main(String[] args) {
    selectionSort(new Integer[] { 1, 0, 4, 2 });
}

I get the output

Selection Sort Comparisons: 6
Selection Sort Assignments: 2
0, 1, 2, 4, 

Are you possibly expecting a static or other local variable also called assignmentCounter to be changed?

The variable assignmentCounter declared in selectionSort is local to that method. Nothing outside of it can see it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top