your code will give IndexError because when it reaches i == len(ar)-1 it tries to get ar[j] where j == i + 1 == len(ar)