1

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

1 Answer 1

2

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]

Sign up to request clarification or add additional context in comments.

2 Comments

@minigeek you are welcome. Yes I did remove the casting since it is not needed because you have a generic ArrayList which ensures that whatever you take out is an Integer anyway.
it was showing me error before..donno why..now it isn't

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.