Java选择排序交换计数



我有这段代码,需要一些帮助来计算交换的计数。我想我需要一个for循环,它是标记,但我不知道如何提取交换计数。提前谢谢。

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);
    }
}

你已经回答了你自己的问题。你说你想要计算交换,然后在你交换物品的地方写一个评论....所以只要增加swapcount

作为显示错误,您使用的是print而不是println,这会使您的数字并排显示并且彼此无法区分

最新更新