subroutine sort_orbitals(nI, par_opt)
!Sort oribtals and gives the parity of the unsorted list with respect to the sorted one.
!Use this instead of the default sort when parity is needed.
!The default sort has issues in calculating parity.
integer, intent(inout) :: nI(:)
integer, intent(out), optional :: par_opt
integer :: temp, par
integer :: i, j, num
logical :: swapped
num = size(nI)
!Bubble sort
par = 1
do j = num - 1, 1, -1
swapped = .FALSE.
do i = 1, j
if (nI(i) > nI(i + 1)) then
temp = nI(i)
nI(i) = nI(i + 1)
nI(i + 1) = temp
swapped = .TRUE.
par = -1 * par
end if
end do
if (.not. swapped) exit
end do
if (present(par_opt)) par_opt = par
end subroutine sort_orbitals