Reputation: 133
i'm currently working on a project where I implement different types of sorting methods to sort an array. I got this implementation from my class but for some reason it is not working. I'm not sure where its going wrong and any help would be greatly appreciated.
public static void selectionSort(int[] a) {
int n = a.length;
System.out.println(n);
for (int i = 0; i < n - 1; i++) {
int min = i;
for (int j = i + 1; j < n; j++) {
if (a[j] < a[min]) {
int swap = a[i];
a[i] = a[min];
a[min] = swap;
}
}
}
}
The Algorithm: Finds the minimum value in the list. Swaps it with the value in the first position. Repeat the steps above for the remainder of the list (starting at the second position and advancing each time). It divides the list into two parts. The sublistof items already sorted. The sublistof items remaining to be sorted.
input
int[] a = new int[]{-2, 4, 8, 1, 9, -6};
expected output
-6, -2, 1, 4, 8, 9
Upvotes: 1
Views: 35
Reputation: 8796
You could just use the java.util.Arrays
class for this
int[] a = new int[]{-2, 4, 8, 1, 9, -6};
Arrays.sort(a);
this sorts the array a
into ascending order (your expected output).
Java is pre-built with several tools. Always look for them, writing your own algorithm is fun, but it can be erroneous and painstaking.
Upvotes: 1
Reputation: 8796
The problem lies in the for
loop, min
and i
variables.
int min = i; //min variable is useless, as min is always equals to i
for (int j = i + 1; j < n; j++) {
if (a[j] < a[min]) {
int swap = a[i];
a[i] = a[min]; // remember min equals to i, so here you are assigning the same value
a[min] = swap; // this should be a[j]
}
}
Change the for
loop
for (int j = i + 1; j < n; j++) {
if (a[j] < a[i]) {
int swap = a[i];
a[i] = a[j];
a[j] = swap;
}
}
Upvotes: 1
Reputation: 81
You're missing a crucial step to update the minimum index here. Have a look at if block in below code.
public static void selectionSort(int[] a) {
int n = a.length;
for (int i = 0; i < n - 1; i++) {
int min = i;
for (int j = i + 1; j < n; j++) {
if (a[j] < a[min]) {
min = j;
int swap = a[i];
a[i] = a[min];
a[min] = swap;
}
}
}
}
Upvotes: 1