I am implementing Selection Sort Algorithm in java using ArrayList. Algorithm I implemented is correct but I am not getting valid output. can anyone help me please if I am going wrong with this Arraylist. code :
import java.util.*;
public class SelectionSort {
public static void main(String[] args) {
ArrayList <Integer> array = new ArrayList<Integer>();
array.add(50);
array.add(30);
array.add(10);
array.add(60);
array.add(40);
System.out.println(array);
selsort(array);
}
private static ArrayList<Integer> selsort(ArrayList<Integer> array){
int i = 0;
int imin = 0;
int len = array.size();
for (i = 0;i <len-1; i++){
imin = i;
for (int j = i+1; j<len; j++) {
if ((Integer) (array.get(j)) < (Integer) (array.get(imin))){
imin = j;
}
Collections.swap(array,i,j);
}
}
System.out.println(array);
return array;
}
}
output :
[50, 30, 10, 60, 40] //before
[40, 60, 10, 30, 50] //after
You are swapping the elements with the wrong indices in the wrong place.
The correct swap is i
with imin
.
The correct place is outside the inner loop:
private static ArrayList<Integer> selsort(ArrayList<Integer> array){
int i = 0;
int len = array.size();
for (i = 0; i < len - 1; i++) {
int imin = i;
for (int j = i + 1; j < len; j++) {
if (array.get(j) < array.get(imin)) {
imin = j;
}
}
Collections.swap(array,i,imin);
}
System.out.println(array);
return array;
}
[50, 30, 10, 60, 40]
[10, 30, 40, 50, 60]