gpt4 book ai didi

java - 计算交换计数并在选择排序中进行比较

转载 作者:行者123 更新时间:2023-11-29 05:07:16 24 4
gpt4 key购买 nike

我是 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 );

最佳答案

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

关于java - 计算交换计数并在选择排序中进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29934852/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com