选择排序交换计数



我有一个包含用户输入的数组。这个程序是关于冒泡排序、选择排序和插入排序的。我无法解决选择部分的问题。交换计数器总是给我数组的长度-1。我知道这是因为第一个for循环,但我找不到任何解决方案。

int SComparison = 0;
int SSwaps = 0;
for (int i = 0; i < SorBag.length - 1; i++) {
        min = i;
        for (int j = i + 1; j < SorBag.length; j++) {
            SComparison++;
            if (SorBag[j] < SorBag[min]) {
                min = j;
            }
        }
        SSwaps++;
        temp2 = SorBag[i];
        SorBag[i] = SorBag[min];
        SorBag[min] = temp2;
    }

我试着把SSwaps放进"if",它总是给我0。我试着做一个"if"来计算有多少数组元素比第一个元素小。还是一样。SSwaps++应该放在哪里?非常感谢。

选择排序通过比较更新最小索引(您的if ...),并在需要时执行元素交换

你把swapps++放在正确的位置。但如果min == i。您只想在min !=i的情况下进行交换。相反,你没有检查,只是交换。这就是你修复length -1 的原因

附言:请尽量遵循java命名约定。

检查此代码:

public class Test {

    public static void main(String[] args) {
        int SComparison = 0;
         int SSwaps = 0;
         int totalSwap=0;
        int min = 0;
        int temp = 0;
        int SorBag[] = { 1, 4, 3 };
        for (int i = 0; i < SorBag.length - 1; i++) {
            min = i;
            for (int j = i + 1; j < SorBag.length; j++) {
                SComparison++;
                if (SorBag[j] < SorBag[min]) {
                    min = j;
                    temp = SorBag[i];
                    SorBag[i] = SorBag[min];
                    SorBag[min] = temp;
                    SSwaps++;
                    totalSwap+=SSwaps;
                    System.out.println("swap count at "+j+" pass : "+SSwaps);
                }
            }
            SSwaps=0;

        }
        for (int i = 0; i < SorBag.length; i++) 
            System.out.print(SorBag[i]+" ");
        System.out.println("nTotal swap count :"+totalSwap);
    }

}

输出:

swap count at 2 pass : 1
1 3 4 
Total swap count :1

问题出在哪里?对于您的代码,这提供了4个正确的交换。

    int[] SorBag = new int[]{5 ,4 ,3 ,2 ,1};
    int min = 0;
    int SComparison = 0;
    int SSwaps = 0;
    for (int i = 0; i < SorBag.length - 1; i++) {
            min = i;
            for (int j = i + 1; j < SorBag.length; j++) {
                SComparison++;
                if (SorBag[j] < SorBag[min]) {
                    min = j;
                    SSwaps++;
                }
            }

            int temp2 = SorBag[i];
            SorBag[i] = SorBag[min];
            SorBag[min] = temp2;
        }
    System.out.println("sswaps : "+SSwaps);
    for(int i = 0; i<5;i++){
        System.out.println("SorBag["+i+"] = "+SorBag[i]);
    }
}  

最新更新