Question

I have this code and need a little help figuring out the count of the swaps. I think I need a for loop where it is mark but I don't quit understand how to extract the swap count. Thanks in advance.

public class Selection
{
    public static void SelectionSort ( int [ ] num, int howmany )
    { 
        int i, j, first, temp;  
        int comparecount = 0;
        int swapcount = 0;

        for ( i = num.length - 1; i > 0; i-- )  
        {   
            first = 0;   
            for(j = 1; j <= i; j ++)   
            {  
                comparecount++;

                if( num[ j ] < num[ first ] )         
                    first = j;
            }
            temp = num[ first ];   //need to count swaps ???
            num[ first ] = num[ i ];
            num[ i ] = temp; 
        }

        System.out.print(comparecount);
        System.out.print(swapcount);
    }
}
Was it helpful?

Solution

You really have answered your own question. You say you want to count the swaps, then have put a comment exactly where you swap items.... so just increment the swapcount there.

As a display error you are using print as opposed to println, which is making your numbers appear side by side and indistinguishable from each other

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