I'm trying to figure out where I went wrong here. Someone had to build the built-in sort function, so I'm trying to figure out how it works. I don't understand the compiler error it gives me (index out of bounds error because i = 5) because the loops should break before that happens. If I print the array every time the loop runs, the list does get sorted properly. The compiler error happens after that...

package com.codegym.task.task06.task0622;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
/*
Ascending numbers
*/
public class Solution {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int a = Integer.parseInt(reader.readLine());
int b = Integer.parseInt(reader.readLine());
int c = Integer.parseInt(reader.readLine());
int d = Integer.parseInt(reader.readLine());
int e = Integer.parseInt(reader.readLine());
//write your code here
ArrayList<Integer> arr = new ArrayList<Integer>();
arr.add(a);
arr.add(b);
arr.add(c);
arr.add(d);
arr.add(e);
int i = 0;
while (!(arr.get(0) <= arr.get(1) && arr.get(1) <= arr.get(2) && arr.get(2) <= arr.get(3) && arr.get(3) <= arr.get(4))) {
while (i < arr.size()) {
if (arr.get(i + 1) < arr.get(i)) {
int temp1 = arr.get(i + 1);
arr.set(i + 1, arr.get(i));
arr.set(i, temp1);
i = 0;
}
else {
i++;
}
}
// System.out.println("Begin:");
// for (int j = 0; j < arr.size(); j++) {
// System.out.println(arr.get(j));
// }
}
for (int j = 0; j < arr.size(); j++) {
System.out.println(arr.get(j));
}
}
}

i + 1) < arr.get(i)) When i = 4 (the max index),i+1will equal 5. Also, fix your indenting, readability helps with coding. **Tip: If you have intelliJ, delete the last '}' (the one at line 59), and then type it back in. IntelliJ's auto format will kick in and fix all the indents and spacing for you.while (!(arr.get(0) <= arr.get(1) && arr.get(1) <= arr.get(2) && arr.get(2) <= arr.get(3) && arr.get(3) <= arr.get(4)))I don't mean un-optimized as in slow, i mean un-optimized as in unnecessary. You don't even need that loop to begin with and can just use what is contained within. This is because you set i back to 0 any time a swap occurs. Get rid of lines 31 and 49while (i < arr.size()) {Modify this line so that adding when line 34 is reached, adding 1 toiwon't result in a possible out of bounds.