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;
}
}
}
}
}
Performance wise, both are similar, O(n2). The second code is a bit cleaner though.