I need to make a programm in java with the selection sort algorithm. So i tried this to do that but the code doesn't works.
3 Answers
Problem with this code is that it doesn't swap numbers. Instead, it replaces array[i] with the minimum number found.
You can modify your loop like this to do the swapping.
for (int i = 0; i < array.length; i++) {
int minIndex = i;
for (int j = i; j < array.length; j++) {
if (array[j] < array[minIndex]) {
minIndex = j;
}
}
if (array[minIndex] != array[i]) {
int wert = array[minIndex];
array[minIndex] = array[i];
array[i] = wert;
}
}
Comments
For selection sort use this method
public static void selectionSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
int index = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[index]) {
index = j;//searching for lowest index
}
}
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
}
Comments
If you need an ascend order just use:
Arrays.sort(array) from java.util library
But if you need to sort descending I'd suggested to reffer to:
minshould be storing an array index, not a value of the element, so that you can actually swap two array elements after the inner for loop is done