我是Java的新手,我无法理解一个概念。在这段代码中,我需要添加一个交换计数并比较计数,这是我到目前为止所得到的。
public static void SelectionSort ( int [ ] num, int howmany )
{
int i, j, first, temp;
int compCount;
int swapCount;
for ( i = num.length - 1; i > 0; i-- )
{
compCount = 0;
swapCount = 0;
first = 0; //initialize to subscript of first element
for(j = 1; j <= i; j ++) //locate smallest element between positions 1 and i.
{
compCount++;
if( num[ j ] < num[ first ] )
first = j;
}
temp = num[ first ]; //swap smallest found with element in position i.
num[ first ] = num[ i ];
num[ i ] = temp;
swapCount++;
}
System.out.println("selection sort " + compCount + swapCount );
答案 0 :(得分:2)
public static void SelectionSort ( int [ ] num, int howmany )
{
int i, j, first, temp;
int compCount = 0;
int swapCount = 0;
for ( i = num.length - 1; i > 0; i-- )
{
/* you should not be reinitializing swap count and compCount inside the for loop. What this does is make it 0 after each iteration which is not what you want*/
first = 0; //initialize to subscript of first element
for(j = 1; j <= i; j ++) //locate smallest element between positions 1 and i.
{
compCount++;
if( num[ j ] < num[ first ] )
first = j;
}
temp = num[ first ]; //swap smallest found with element in position i.
num[ first ] = num[ i ];
num[ i ] = temp;
swapCount++;
}
System.out.println("selection sort " + compCount + swapCount );
答案 1 :(得分:1)
由于在每次迭代中清除了计数器,因此无法工作
计数器应在开始时初始化,而不是仅增加
这段代码应该更好,但没有经过测试
public static void SelectionSort ( int [ ] num, int howmany )
{
int i, j, first, temp;
int compCount=0;
int swapCount=0;
for ( i = num.length - 1; i > 0; i-- )
{
first = 0; //initialize to subscript of first element
for(j = 1; j <= i; j ++) //locate smallest element between positions 1 and i.
{
compCount++;
if( num[ j ] < num[ first ] )
first = j;
}
temp = num[ first ]; //swap smallest found with element in position i.
num[ first ] = num[ i ];
num[ i ] = temp;
swapCount++;
}
System.out.println("selection sort " + compCount + swapCount );
}
答案 2 :(得分:0)
class ssort {
static void selection_sort(int arr[], int n)
{
int swap=0;
for(int i=0;i<n;i++)
{
//find min
int min_indx=i;
int old_min=min_indx;
for(int j=i+1;j<n;j++)
{
if(arr[j]< arr[min_indx]){
min_indx=j;
}
}
if(old_min != min_indx)
{
int temp= arr[min_indx];//swap`enter code here`
arr[min_indx]=arr[i];
arr[i]=temp;
swap++;
}
}
System.out.println("Total Swaps "+swap);
}
public static void main(String[] args) {
int arr[]=new int[]{7, 1, 3, 2, 4, 5, 6};
int n=arr.length;
selection_sort(arr, n);
for(int i=0;i<n;i++)
System.out.print(arr[i]+" ");
}
}