if there are duplicate values in the array, this algorithm will fail