Algorithm to sort array