You set beg and end to values in the array not the first and last index of the array.