I want to build an algorithm that takes into account a list of integers, sort it.
The idea is: iterate over the list of integers, the first value gets into a new list; the following value is compared with the only existing value in the new list and put it in before or after, and so on.
import java.util.*;
import java.util.function.Supplier;
import java.util.ArrayList;
public class SortLists {
public static void main(String args[])
{
// list [5,1,4,2,8]
List<Integer> list = new ArrayList<Integer>();
list.add(5);
list.add(1);
list.add(4);
list.add(2);
list.add(8);
System.out.println("list : " + list.toString());
// new empty list
List<Integer> list2 = new ArrayList<Integer>();
// iterate over the integer list
for (int i = 0; i < list.size(); i++){
//int i=2;
// *** 1st iteration - add the value to the list2
if (i == 0){
list2.add(list.get(i));
} else {
// *** in the next interations, compare with the existing values in list2
for (int j = 0; j < list2.size(); j++){
// *** Note: this if is unecessary but I got an error with list2.get(j)
if (j==0){
// if the value from list is lower than the only value in list2, put in index 0
if (list.get(i) < list2.get(0) ) {
list2.add(j,list.get(i));
}
}else{
if (list.get(i) < list2.get(j) ) {
//list2.add(j,list.get(i)); // GIVES ERROR!
System.out.println("index "+j+" value "+list.get(i));
} else {
//list2.add(list.get(i)); //GIVES ERROR!
System.out.println("else: index "+j+" value "+list.get(i));
}
}
}
}
}
//list2.add(1,4); // no error if add manually here
System.out.println("list2 : " + list2.toString());
}
}
The 5 and 1 are correctly inserted in list2.
The other two list2.add, if I uncomment them, the execution doesn't stop.
size()from within theforstatement and calling `list.get(i)' within the loop is very inefficient.