pavlos123 pavlos123 - 2 months ago 8
Java Question

how to sort an intList every 5 elements

im inserting thousand of numbers from a txt file into a list and i want to sort them every 5 numbers. Is this possible and if yes,how this can be done?

public static void readFromFile(){
List<Integer> putInList = new ArrayList<Integer>();
int jNum;
TextIO.readFile("jokerNums.txt");//read from a spesific file.

try{
do{
jNum = TextIO.getInt();
putInList.add(jNum);

} while(!TextIO.eof());// Test whether the next character in
//the current input source is an end-of-file
}

catch(IllegalArgumentException e){

}
TextIO.put(putInList);
}


I have tried the for loop inside the do { }while loop but its infinite.
Just to mention the numbers i insert are 9785.
Thank you in advance.

Answer
for (int i = 0; !TextIO.eof(); i++){
      int value = TextIO.getInt();
      int targetIndex = (i/5)*5;
      for (; targetIndex < putInList.size(); targetIndex++)
      {
          if(putInList.get(targetIndex)>value)
          {
            break;
          }
      }
      putInList.add(targetIndex,value);

    }