Improved algorithm for condensing array