简体   繁体   中英

Number of comparisons in selection sort?

My program deals with the number of comparisons using selection sort. It returns the wrong number of comps. Where is comp going wrong?

My demo:

    ArrayI[] ints = new ArrayI[5];


    ints[0] = new ArrayInts(3);
    ints[1] = new ArrayInts(9);
    ints[2] = new ArrayInts(6);
    ints[3] = new ArrayInts(1);
    ints[4] = new ArrayInts(2);




    SelectionSort.selectionSort(myInts);

    System.out.println(" ");

    System.out.println("Sorted array: ");

    for(ArrayI ints:myInts){
        System.out.println(ints);
    }

    System.out.println(" ");

    System.out.println("Number of comparisons: " + SelectionSort2.selectionSort2(ints));  

That is because, you are incrementing the comparison outside the inner loop. So the value of comparison would be equals to the number of times your outer loop runs. Move the increment to inner loop:

And you really don't need the min variable. You can rather move the swapping logic inside the if block. You should modify your code to:

for(int index = 0; index < data.length-1; index++) {

    for(int scan = index+1; scan < data.length; scan++) {
        comparisons++;  // Each inner loop does one comparison

        if(data[scan].compareTo(data[min]) < 0) {
            temp = data[scan];
            data[scan] = data[index];
            data[index] = temp;
        }
    }   
}

I don't really understand your point of creating an ArrayInts class. That's totally unnecessary. You could have simply used Integer wrapper class. And just for your information, you have an Arrays#sort(Object[]) method, which does the sorting for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM