Better Selection Sort in Java

151 views Asked by At

Firstly, can you tell me which piece of code is better of selection sort? Then if you know better ways for selection sort, can you please share?

Note: Please inspect the second code closer because it is more complex than it looks.

class SelectionSort {

    public static void selectionSort(double[] list) {
        for (int i = 0; i < list.length - 1; i++) {

            double currentMin = list[i];
            int currentMinIndex = i;

            for (int j = i + 1; j < list.length; j++) {
                if (currentMin > list[j]) {
                    currentMin = list[j];
                    currentMinIndex = j;
                }
            }

            if (currentMinIndex != i) {
                list[currentMinIndex] = list[i];
                list[i] = currentMin;
            }
        }
    }
}

.

class SelectionSort {

    public static double[] selectionSort(double[] array) {
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < i; j++) {
                if (array[j] > array[i]) {
                    double temp = array[j];
                    array[j] = array[i];
                    array[i] = temp;
                }
            }
        }
    }
}
2

There are 2 answers

0
Francisco Romero On

Both methods will solve your problem but the second one it's clearly and I think it will be faster. Why? Because it has to make less actions to complete the problem: in the first one you have 2 loops (like in the second one), but also it has to make 2 ifs vs 1 if in the second one. I'm not really secure about that but, if the program have to make less actions, it will be faster (just an assumption).

Also, I think it will be faster because in the first one, you through all the j elements, some of them unnecesary (you have to make an extra if), and in the second one you just go through the elements that you need so it is more efficient too.

So, in conclusion, I think the best practice that you have to use it's the second one.

I expect it will helps you a bit!

0
Omar Zaarour On

Performance wise, both are similar, O(n2). The second code is a bit cleaner though.