Reputation: 97
I am trying to implement selection sort algorithm. But i see that it is failing for some cases. I take two different arrays and get two different result. Case 1: Integer [] arr= {100,90,6,43,12,1}; Result:{1,6,12,43,90,100}
Case 2: Integer [] arr= {100,90,6,43,12,7}; Result:{7,6,12,43,90,100}
Below is my code.
public class SelectionSort {
private static boolean less(Comparable v, Comparable w) {
return v.compareTo(w)<0;
}
private static void exch(Comparable[] a,int i,int j) {
Comparable swap=a[i];
a[i]=a[j];
a[j]=swap;
}
public static void sort(Comparable[] a) {
int N= a.length;
for(int i=0;i<N;i++) {
int min=i;
for(int j=i+1;j<N;j++) {
if(less(a[j],a[min]))
min=j;
exch(a,i,min);
}
}
}
}
Upvotes: 1
Views: 102
Reputation: 182
change the algorithm like the following, it works fine
int N= a.length;
for(int i=0;i<N-1;i++) {
int min=i;
for(int j=i+1;j<N;j++)
if(less(a[j],a[min]))
min=j;
exch(a,i,min);
}
Upvotes: 1
Reputation: 1742
Are you sure that you want the exch
to happen inside the j
loop?
Upvotes: 0